10 typedef struct URL URL;
24 typedef struct Range Range;
27 long start; /* only 2 gig supported, tdb */
31 typedef struct Out Out;
35 int offset; /* notional current offset in output */
36 int written; /* number of bytes successfully transferred to output */
37 DigestState *curr; /* digest state up to offset (if known) */
38 DigestState *hiwat; /* digest state of all bytes written */
61 int doftp(URL*, URL*, Range*, Out*, long);
62 int dohttp(URL*, URL*, Range*, Out*, long);
63 int crackurl(URL*, char*);
64 Range* crackrange(char*);
65 int getheader(int, char*, int);
66 int httpheaders(int, int, URL*, Range*);
68 int cistrncmp(char*, char*, int);
69 int cistrcmp(char*, char*);
71 int readline(int, char*, int);
72 int readibuf(int, char*, int);
73 int dfprint(int, char*, ...);
74 void unreadline(char*);
75 int output(Out*, char*, int);
76 void setoffset(Out*, int);
80 char tcpdir[NETPATHLEN];
85 int (*f)(URL*, URL*, Range*, Out*, long);
96 fprint(2, "usage: %s [-hv] [-o outfile] [-p body] [-x netmtpt] url\n", argv0);
97 threadexitsall("usage");
101 threadmain(int argc, char **argv)
108 char postbody[4096], *p, *e, *t, *hpx;
114 e = p + sizeof(postbody);
118 memset(&u, 0, sizeof(u));
119 memset(&px, 0, sizeof(px));
120 hpx = getenv("httpproxy");
145 p = seprint(p, e, "&%s", t);
147 p = seprint(p, e, "%s", t);
148 u.postbody = postbody;
156 if(strlen(net) > sizeof(tcpdir)-5)
157 sysfatal("network mount point too long");
158 snprint(tcpdir, sizeof(tcpdir), "%s/tcp", net);
160 snprint(tcpdir, sizeof(tcpdir), "tcp");
174 out.fd = create(ofile, OWRITE, 0664);
176 sysfatal("creating %s: %r", ofile);
178 out.fd = open(ofile, OWRITE);
180 sysfatal("can't open %s: %r", ofile);
189 if(crackurl(&u, argv[0]) < 0)
191 if(hpx && crackurl(&px, hpx) < 0)
198 n = (*method[u.method].f)(&u, &px, &r, &out, mtime);
207 sysfatal("too many errors with no progress %r");
210 sysfatal("server returned: %r");
214 /* forward progress */
225 crackurl(URL *u, char *s)
247 if(*p == ':' && *(p+1)=='/' && *(p+2)=='/'){
250 for(i = 0; i < nelem(method); i++){
251 if(cistrcmp(s, method[i].name) == 0){
260 if(u->method == Other){
261 werrstr("unsupported URL type %s", s);
270 u->page = strdup("/");
278 if(p = strchr(u->host, ':')) {
282 u->port = method[u->method].name;
285 werrstr("bad url, null host");
293 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
297 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
307 catch(void *v, char *s)
315 d.mtime = note.mtime;
316 if(dirfwstat(note.fd, &d) < 0)
317 sysfatal("catch: can't dirfwstat: %r");
322 dohttp(URL *u, URL *px, Range *r, Out *out, long mtime)
325 int redirect, auth, loop;
333 /* always move back to a previous 512 byte bound because some
334 * servers can't seem to deal with requests that start at the
338 r->start = ((r->start-1)/512)*512;
340 /* loop for redirects, requires reading both response code and headers */
342 for(loop = 0; loop < 32; loop++){
344 fd = dial(netmkaddr(u->host, tcpdir, u->port), 0, 0, 0);
346 fd = dial(netmkaddr(px->host, tcpdir, px->port), 0, 0, 0);
351 if(u->method == Https){
355 memset(&conn, 0, sizeof conn);
356 tfd = tlsClient(fd, &conn);
358 fprint(2, "tlsClient: %r\n");
362 /* BUG: check cert here? */
369 /* write request, use range if not start of file */
370 if(u->postbody == nil){
372 dfprint(fd, "GET %s HTTP/1.0\r\n"
374 "User-agent: Plan9/hget\r\n"
375 "Cache-Control: no-cache\r\n"
376 "Pragma: no-cache\r\n",
379 dfprint(fd, "GET http://%s%s HTTP/1.0\r\n"
381 "User-agent: Plan9/hget\r\n"
382 "Cache-Control: no-cache\r\n"
383 "Pragma: no-cache\r\n",
384 u->host, u->page, u->host);
387 dfprint(fd, "Authorization: Basic %s\r\n",
391 dfprint(fd, "POST %s HTTP/1.0\r\n"
393 "Content-type: application/x-www-form-urlencoded\r\n"
394 "Content-length: %d\r\n"
395 "User-agent: Plan9/hget\r\n"
397 u->page, u->host, strlen(u->postbody));
399 dfprint(fd, "POST http://%s%s HTTP/1.0\r\n"
401 "Content-type: application/x-www-form-urlencoded\r\n"
402 "Content-length: %d\r\n"
403 "User-agent: Plan9/hget\r\n"
405 u->host, u->page, u->host, strlen(u->postbody));
407 dfprint(fd, "%s", u->postbody);
410 dfprint(fd, "Range: bytes=%d-\n", r->start);
412 dfprint(fd, "If-range: %s\n", u->etag);
415 dfprint(fd, "If-range: %s, %d %s %d %2d:%2.2d:%2.2d GMT\n",
416 day[tm->wday], tm->mday, month[tm->mon],
417 tm->year+1900, tm->hour, tm->min, tm->sec);
420 if((cfd = open("/mnt/webcookies/http", ORDWR)) >= 0){
421 if(fprint(cfd, "http://%s%s", u->host, u->page) > 0){
422 while((n = read(cfd, buf, sizeof buf)) > 0){
433 dfprint(fd, "\r\n", u->host);
438 code = httprcode(fd);
440 case Error: /* connection timed out */
447 case 201: /* Created */
448 case 202: /* Accepted */
449 if(ofile == nil && r->start != 0)
450 sysfatal("page changed underfoot");
453 case 204: /* No Content */
454 sysfatal("No Content");
456 case 206: /* Partial Content */
457 setoffset(out, r->start);
460 case 301: /* Moved Permanently */
461 case 302: /* Moved Temporarily */
466 case 304: /* Not Modified */
469 case 400: /* Bad Request */
470 sysfatal("Bad Request");
472 case 401: /* Unauthorized */
474 sysfatal("Authentication failed");
479 sysfatal("Unauthorized");
481 case 403: /* Forbidden */
482 sysfatal("Forbidden by server");
484 case 404: /* Not Found */
485 sysfatal("Not found on server");
487 case 407: /* Proxy Authentication */
488 sysfatal("Proxy authentication required");
490 case 500: /* Internal server error */
491 sysfatal("Server choked");
493 case 501: /* Not implemented */
494 sysfatal("Server can't do it!");
496 case 502: /* Bad gateway */
497 sysfatal("Bad gateway");
499 case 503: /* Service unavailable */
500 sysfatal("Service unavailable");
503 sysfatal("Unknown response code %d", code);
506 if(u->redirect != nil){
511 rv = httpheaders(fd, cfd, u, r);
518 if(!redirect && !auth)
522 if(u->redirect == nil)
523 sysfatal("redirect: no URL");
524 if(crackurl(u, u->redirect) < 0)
525 sysfatal("redirect: %r");
529 /* transfer whatever you get */
530 if(ofile != nil && u->mtime != 0){
532 note.mtime = u->mtime;
539 n = readibuf(fd, buf, sizeof(buf));
542 if(output(out, buf, n) != n)
545 if(verbose && (vtime != time(0) || r->start == r->end)) {
547 fprint(2, "%ld %ld\n", r->start+tot, r->end);
553 if(ofile != nil && u->mtime != 0){
556 rerrstr(err, sizeof err);
559 if(dirfwstat(out->fd, &d) < 0)
560 fprint(2, "couldn't set mtime: %r\n");
561 errstr(err, sizeof err);
567 /* get the http response code */
575 n = readline(fd, buf, sizeof(buf)-1);
579 fprint(2, "%d <- %s\n", fd, buf);
580 p = strchr(buf, ' ');
581 if(strncmp(buf, "HTTP/", 5) != 0 || p == nil){
582 werrstr("bad response from server");
589 /* read in and crack the http headers, update u and r */
590 void hhetag(char*, URL*, Range*);
591 void hhmtime(char*, URL*, Range*);
592 void hhclen(char*, URL*, Range*);
593 void hhcrange(char*, URL*, Range*);
594 void hhuri(char*, URL*, Range*);
595 void hhlocation(char*, URL*, Range*);
596 void hhauth(char*, URL*, Range*);
600 void (*f)(char*, URL*, Range*);
603 { "last-modified:", hhmtime },
604 { "content-length:", hhclen },
605 { "content-range:", hhcrange },
607 { "location:", hhlocation },
608 { "WWW-Authenticate:", hhauth },
611 httpheaders(int fd, int cfd, URL *u, Range *r)
618 n = getheader(fd, buf, sizeof(buf));
622 fprint(cfd, "%s\n", buf);
623 for(i = 0; i < nelem(headers); i++){
624 n = strlen(headers[i].name);
625 if(cistrncmp(buf, headers[i].name, n) == 0){
626 /* skip field name and leading white */
628 while(*p == ' ' || *p == '\t')
631 (*headers[i].f)(p, u, r);
640 * read a single mime header, collect continuations.
642 * this routine assumes that there is a blank line twixt
643 * the header and the message body, otherwise bytes will
647 getheader(int fd, char *buf, int n)
654 for(e = p + n; ; p += i){
655 i = readline(fd, p, e-p);
661 if(strchr(buf, ':') == nil)
662 break; /* end of headers */
664 /* continuation line */
665 if(*p != ' ' && *p != '\t'){
668 break; /* end of this header */
676 fprint(2, "%d <- %s\n", fd, buf);
681 hhetag(char *p, URL *u, Range *r)
686 if(strcmp(u->etag, p) != 0)
687 sysfatal("file changed underfoot");
692 char* monthchars = "janfebmaraprmayjunjulaugsepoctnovdec";
695 hhmtime(char *p, URL *u, Range *r)
697 char *month, *day, *yr, *hms;
704 i = getfields(p, fields, 6, 1, " \t");
714 now = *gmtime(time(0));
718 /* convert ascii month to a number twixt 1 and 12 */
719 if(*month >= '0' && *month <= '9'){
720 tm.mon = atoi(month) - 1;
721 if(tm.mon < 0 || tm.mon > 11)
724 for(p = month; *p; p++)
725 *p = tolower((uchar)*p);
726 for(i = 0; i < 12; i++)
727 if(strncmp(&monthchars[i*3], month, 3) == 0){
736 tm.hour = strtoul(hms, &p, 10);
739 tm.min = strtoul(p, &p, 10);
742 tm.sec = strtoul(p, &p, 10);
745 if(tolower((uchar)*p) == 'p')
754 if(tm.mon > now.mon || (tm.mon == now.mon && tm.mday > now.mday+1))
758 strcpy(tm.zone, "GMT");
759 /* convert to epoch seconds */
760 u->mtime = tm2sec(&tm);
764 hhclen(char *p, URL *u, Range *r)
772 hhcrange(char *p, URL *u, Range *r)
791 hhuri(char *p, URL *u, Range *r)
797 u->redirect = strdup(p+1);
798 p = strchr(u->redirect, '>');
804 hhlocation(char *p, URL *u, Range *r)
808 u->redirect = strdup(p);
812 hhauth(char *p, URL *u, Range *r)
820 if (cistrncmp(p, "basic ", 6) != 0)
821 sysfatal("only Basic authentication supported");
823 if (gettokens(p, f, nelem(f), "\"") < 2)
824 sysfatal("garbled auth data");
826 if ((up = auth_getuserpasswd(auth_getkey, "proto=pass service=http dom=%q relm=%q",
827 u->host, f[1])) == nil)
828 sysfatal("cannot authenticate");
830 s = smprint("%s:%s", up->user, up->passwd);
831 if(enc64(cred, sizeof(cred), (uchar *)s, strlen(s)) == -1)
835 assert(u->cred = strdup(cred));
840 /* ftp return codes */
847 Nnetdir= 64, /* max length of network directory paths */
848 Ndialstr= 64 /* max length of dial strings */
851 int ftpcmd(int, char*, ...);
852 int ftprcode(int, char*, int);
855 int xfertype(int, char*);
856 int passive(int, URL*);
857 int active(int, URL*);
858 int ftpxfer(int, Out*, Range*);
859 int terminateftp(int, int);
860 int getaddrport(char*, uchar*, uchar*);
861 int ftprestart(int, Out*, URL*, Range*, long);
864 doftp(URL *u, URL *px, Range *r, Out *out, long mtime)
866 int pid, ctl, data, rv;
870 /* untested, proxy dosn't work with ftp (I think) */
872 ctl = dial(netmkaddr(u->host, tcpdir, u->port), 0, 0, 0);
874 ctl = dial(netmkaddr(px->host, tcpdir, px->port), 0, 0, 0);
880 strcpy(tcpdir, "tcp");
886 return terminateftp(ctl, rv);
890 return terminateftp(ctl, rv);
892 rv = xfertype(ctl, "I");
894 return terminateftp(ctl, rv);
896 /* if file is up to date and the right size, stop */
897 if(ftprestart(ctl, out, u, r, mtime) > 0){
902 /* first try passive mode, then active */
903 data = passive(ctl, u);
905 data = active(ctl, u);
911 switch(pid = fork()){
914 return terminateftp(ctl, Error);
916 ftpxfer(data, out, r);
925 /* wait for reply message */
926 rv = ftprcode(ctl, msg, sizeof(msg));
929 /* wait for process to terminate */
941 werrstr("xfer: %s", w->msg);
958 ftpcmd(int ctl, char *fmt, ...)
961 char buf[2*1024], *s;
964 s = vseprint(buf, buf + (sizeof(buf)-4) / sizeof(*buf), fmt, arg);
967 fprint(2, "%d -> %s\n", ctl, buf);
970 if(write(ctl, buf, s - buf) != s - buf)
976 ftprcode(int ctl, char *msg, int len)
982 len--; /* room for terminating null */
985 i = readline(ctl, msg, len);
989 fprint(2, "%d <- %s\n", ctl, msg);
991 /* stop if not a continuation */
992 rv = strtol(msg, &p, 10);
993 if(rv >= 100 && rv < 600 && p==msg+3 && *p == ' ')
1006 /* wait for hello from other side */
1007 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1008 werrstr("HELLO: %s", msg);
1015 getdec(char *p, int n)
1020 for(i = 0; i < n; i++)
1021 x = x*10 + (*p++ - '0');
1026 ftprestart(int ctl, Out *out, URL *u, Range *r, long mtime)
1032 ftpcmd(ctl, "MDTM %s", u->page);
1033 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1035 return 0; /* need to do something */
1038 /* decode modification time */
1039 if(strlen(msg) < 4 + 4 + 2 + 2 + 2 + 2 + 2){
1041 return 0; /* need to do something */
1043 memset(&tm, 0, sizeof(tm));
1044 tm.year = getdec(msg+4, 4) - 1900;
1045 tm.mon = getdec(msg+4+4, 2) - 1;
1046 tm.mday = getdec(msg+4+4+2, 2);
1047 tm.hour = getdec(msg+4+4+2+2, 2);
1048 tm.min = getdec(msg+4+4+2+2+2, 2);
1049 tm.sec = getdec(msg+4+4+2+2+2+2, 2);
1050 strcpy(tm.zone, "GMT");
1051 rmtime = tm2sec(&tm);
1056 ftpcmd(ctl, "SIZE %s", u->page);
1057 if(ftprcode(ctl, msg, sizeof(msg)) == Success){
1060 return 1; /* we're up to date */
1064 /* seek to restart point */
1066 ftpcmd(ctl, "REST %lud", r->start);
1067 if(ftprcode(ctl, msg, sizeof(msg)) == Incomplete){
1068 setoffset(out, r->start);
1073 return 0; /* need to do something */
1081 /* login anonymous */
1082 ftpcmd(ctl, "USER anonymous");
1083 switch(ftprcode(ctl, msg, sizeof(msg))){
1087 break; /* need password */
1089 werrstr("USER: %s", msg);
1093 /* send user id as password */
1094 sprint(msg, "%s@closedmind.org", getuser());
1095 ftpcmd(ctl, "PASS %s", msg);
1096 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1097 werrstr("PASS: %s", msg);
1105 xfertype(int ctl, char *t)
1109 ftpcmd(ctl, "TYPE %s", t);
1110 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1111 werrstr("TYPE %s: %s", t, msg);
1119 passive(int ctl, URL *u)
1129 ftpcmd(ctl, "PASV");
1130 if(ftprcode(ctl, msg, sizeof(msg)) != Success)
1133 /* get address and port number from reply, this is AI */
1134 p = strchr(msg, '(');
1136 for(p = msg+3; *p; p++)
1137 if(isdigit((uchar)*p))
1141 if(getfields(p, f, 6, 0, ",)") < 6){
1142 werrstr("ftp protocol botch");
1145 snprint(ipaddr, sizeof(ipaddr), "%s.%s.%s.%s",
1146 f[0], f[1], f[2], f[3]);
1147 port = ((atoi(f[4])&0xff)<<8) + (atoi(f[5])&0xff);
1148 sprint(aport, "%d", port);
1150 /* open data connection */
1151 fd = dial(netmkaddr(ipaddr, tcpdir, aport), 0, 0, 0);
1153 werrstr("passive mode failed: %r");
1157 /* tell remote to send a file */
1158 ftpcmd(ctl, "RETR %s", u->page);
1159 if(ftprcode(ctl, msg, sizeof(msg)) != Extra){
1160 werrstr("RETR %s: %s", u->page, msg);
1167 active(int ctl, URL *u)
1170 char dir[40], ldir[40];
1175 /* announce a port for the call back */
1176 snprint(msg, sizeof(msg), "%s!*!0", tcpdir);
1177 afd = announce(msg, dir);
1181 /* get a local address/port of the annoucement */
1182 if(getaddrport(dir, ipaddr, port) < 0){
1187 /* tell remote side address and port*/
1188 ftpcmd(ctl, "PORT %d,%d,%d,%d,%d,%d", ipaddr[0], ipaddr[1], ipaddr[2],
1189 ipaddr[3], port[0], port[1]);
1190 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1192 werrstr("active: %s", msg);
1196 /* tell remote to send a file */
1197 ftpcmd(ctl, "RETR %s", u->page);
1198 if(ftprcode(ctl, msg, sizeof(msg)) != Extra){
1200 werrstr("RETR: %s", msg);
1204 /* wait for a connection */
1205 lcfd = listen(dir, ldir);
1210 dfd = accept(lcfd, ldir);
1223 ftpxfer(int in, Out *out, Range *r)
1231 i = read(in, buf, sizeof(buf));
1236 if(output(out, buf, i) != i)
1239 if(verbose && (vtime != time(0) || r->start == r->end)) {
1241 fprint(2, "%ld %ld\n", r->start, r->end);
1248 terminateftp(int ctl, int rv)
1255 * case insensitive strcmp (why aren't these in libc?)
1258 cistrncmp(char *a, char *b, int n)
1261 if(tolower((uchar)*a++) != tolower((uchar)*b++))
1268 cistrcmp(char *a, char *b)
1271 if(tolower((uchar)*a++) != tolower((uchar)*b++))
1290 b.rp = b.wp = b.buf;
1294 * read a possibly buffered line, strip off trailing while
1297 readline(int fd, char *buf, int len)
1307 n = read(fd, b.wp, sizeof(b.buf)/2);
1325 /* drop trailing white */
1330 if(n != ' ' && n != '\t' && n != '\r' && n != '\n')
1343 unreadline(char *line)
1349 memmove(&b.buf[i+1], b.rp, n);
1350 memmove(b.buf, line, i);
1353 b.wp = b.rp + i + 1 + n;
1357 readibuf(int fd, char *buf, int len)
1365 memmove(buf, b.rp, n);
1369 return read(fd, buf, len);
1373 dfprint(int fd, char *fmt, ...)
1379 vseprint(buf, buf+sizeof(buf), fmt, arg);
1382 fprint(2, "%d -> %s", fd, buf);
1383 return fprint(fd, "%s", buf);
1387 getaddrport(char *dir, uchar *ipaddr, uchar *port)
1393 snprint(buf, sizeof(buf), "%s/local", dir);
1394 fd = open(buf, OREAD);
1397 i = read(fd, buf, sizeof(buf)-1);
1402 p = strchr(buf, '!');
1405 v4parseip(ipaddr, buf);
1413 md5free(DigestState *state)
1416 md5(nil, 0, x, state);
1420 md5dup(DigestState *state)
1424 s2 = malloc(sizeof(DigestState));
1426 sysfatal("malloc: %r");
1433 setoffset(Out *out, int offset)
1437 out->curr = md5(nil, 0, nil, nil);
1440 out->offset = offset;
1444 * write some output, discarding it (but keeping track)
1445 * if we've already written it. if we've gone backwards,
1446 * verify that everything previously written matches
1447 * that which would have been written from the current
1451 output(Out *out, char *buf, int nb)
1454 uchar m0[MD5dlen], m1[MD5dlen];
1457 d = out->written - out->offset;
1461 if(out->curr != nil)
1462 md5((uchar*)buf, n, nil, out->curr);
1466 if(out->curr != nil){
1467 md5((uchar*)buf, d, m0, out->curr);
1469 md5(nil, 0, m1, md5dup(out->hiwat));
1470 if(memcmp(m0, m1, MD5dlen) != 0){
1471 fprint(2, "integrity check failure at offset %d\n", out->written);
1480 out->hiwat = md5((uchar*)buf, n, nil, out->hiwat);
1481 n = write(out->fd, buf, n);