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",
390 dfprint(fd, "POST %s HTTP/1.0\r\n"
392 "Content-type: application/x-www-form-urlencoded\r\n"
393 "Content-length: %d\r\n"
394 "User-agent: Plan9/hget\r\n"
396 u->page, u->host, strlen(u->postbody));
397 dfprint(fd, "%s", u->postbody);
400 dfprint(fd, "Range: bytes=%d-\n", r->start);
402 dfprint(fd, "If-range: %s\n", u->etag);
405 dfprint(fd, "If-range: %s, %d %s %d %2d:%2.2d:%2.2d GMT\n",
406 day[tm->wday], tm->mday, month[tm->mon],
407 tm->year+1900, tm->hour, tm->min, tm->sec);
410 if((cfd = open("/mnt/webcookies/http", ORDWR)) >= 0){
411 if(fprint(cfd, "http://%s%s", u->host, u->page) > 0){
412 while((n = read(cfd, buf, sizeof buf)) > 0){
423 dfprint(fd, "\r\n", u->host);
428 code = httprcode(fd);
430 case Error: /* connection timed out */
437 case 201: /* Created */
438 case 202: /* Accepted */
439 if(ofile == nil && r->start != 0)
440 sysfatal("page changed underfoot");
443 case 204: /* No Content */
444 sysfatal("No Content");
446 case 206: /* Partial Content */
447 setoffset(out, r->start);
450 case 301: /* Moved Permanently */
451 case 302: /* Moved Temporarily */
456 case 304: /* Not Modified */
459 case 400: /* Bad Request */
460 sysfatal("Bad Request");
462 case 401: /* Unauthorized */
464 sysfatal("Authentication failed");
469 sysfatal("Unauthorized");
471 case 403: /* Forbidden */
472 sysfatal("Forbidden by server");
474 case 404: /* Not Found */
475 sysfatal("Not found on server");
477 case 407: /* Proxy Authentication */
478 sysfatal("Proxy authentication required");
480 case 500: /* Internal server error */
481 sysfatal("Server choked");
483 case 501: /* Not implemented */
484 sysfatal("Server can't do it!");
486 case 502: /* Bad gateway */
487 sysfatal("Bad gateway");
489 case 503: /* Service unavailable */
490 sysfatal("Service unavailable");
493 sysfatal("Unknown response code %d", code);
496 if(u->redirect != nil){
501 rv = httpheaders(fd, cfd, u, r);
508 if(!redirect && !auth)
512 if(u->redirect == nil)
513 sysfatal("redirect: no URL");
514 if(crackurl(u, u->redirect) < 0)
515 sysfatal("redirect: %r");
519 /* transfer whatever you get */
520 if(ofile != nil && u->mtime != 0){
522 note.mtime = u->mtime;
529 n = readibuf(fd, buf, sizeof(buf));
532 if(output(out, buf, n) != n)
535 if(verbose && (vtime != time(0) || r->start == r->end)) {
537 fprint(2, "%ld %ld\n", r->start+tot, r->end);
543 if(ofile != nil && u->mtime != 0){
546 rerrstr(err, sizeof err);
549 if(dirfwstat(out->fd, &d) < 0)
550 fprint(2, "couldn't set mtime: %r\n");
551 errstr(err, sizeof err);
557 /* get the http response code */
565 n = readline(fd, buf, sizeof(buf)-1);
569 fprint(2, "%d <- %s\n", fd, buf);
570 p = strchr(buf, ' ');
571 if(strncmp(buf, "HTTP/", 5) != 0 || p == nil){
572 werrstr("bad response from server");
579 /* read in and crack the http headers, update u and r */
580 void hhetag(char*, URL*, Range*);
581 void hhmtime(char*, URL*, Range*);
582 void hhclen(char*, URL*, Range*);
583 void hhcrange(char*, URL*, Range*);
584 void hhuri(char*, URL*, Range*);
585 void hhlocation(char*, URL*, Range*);
586 void hhauth(char*, URL*, Range*);
590 void (*f)(char*, URL*, Range*);
593 { "last-modified:", hhmtime },
594 { "content-length:", hhclen },
595 { "content-range:", hhcrange },
597 { "location:", hhlocation },
598 { "WWW-Authenticate:", hhauth },
601 httpheaders(int fd, int cfd, URL *u, Range *r)
608 n = getheader(fd, buf, sizeof(buf));
612 fprint(cfd, "%s\n", buf);
613 for(i = 0; i < nelem(headers); i++){
614 n = strlen(headers[i].name);
615 if(cistrncmp(buf, headers[i].name, n) == 0){
616 /* skip field name and leading white */
618 while(*p == ' ' || *p == '\t')
621 (*headers[i].f)(p, u, r);
630 * read a single mime header, collect continuations.
632 * this routine assumes that there is a blank line twixt
633 * the header and the message body, otherwise bytes will
637 getheader(int fd, char *buf, int n)
644 for(e = p + n; ; p += i){
645 i = readline(fd, p, e-p);
651 if(strchr(buf, ':') == nil)
652 break; /* end of headers */
654 /* continuation line */
655 if(*p != ' ' && *p != '\t'){
658 break; /* end of this header */
666 fprint(2, "%d <- %s\n", fd, buf);
671 hhetag(char *p, URL *u, Range *r)
676 if(strcmp(u->etag, p) != 0)
677 sysfatal("file changed underfoot");
682 char* monthchars = "janfebmaraprmayjunjulaugsepoctnovdec";
685 hhmtime(char *p, URL *u, Range *r)
687 char *month, *day, *yr, *hms;
694 i = getfields(p, fields, 6, 1, " \t");
704 now = *gmtime(time(0));
708 /* convert ascii month to a number twixt 1 and 12 */
709 if(*month >= '0' && *month <= '9'){
710 tm.mon = atoi(month) - 1;
711 if(tm.mon < 0 || tm.mon > 11)
714 for(p = month; *p; p++)
715 *p = tolower((uchar)*p);
716 for(i = 0; i < 12; i++)
717 if(strncmp(&monthchars[i*3], month, 3) == 0){
726 tm.hour = strtoul(hms, &p, 10);
729 tm.min = strtoul(p, &p, 10);
732 tm.sec = strtoul(p, &p, 10);
735 if(tolower((uchar)*p) == 'p')
744 if(tm.mon > now.mon || (tm.mon == now.mon && tm.mday > now.mday+1))
748 strcpy(tm.zone, "GMT");
749 /* convert to epoch seconds */
750 u->mtime = tm2sec(&tm);
754 hhclen(char *p, URL *u, Range *r)
762 hhcrange(char *p, URL *u, Range *r)
781 hhuri(char *p, URL *u, Range *r)
787 u->redirect = strdup(p+1);
788 p = strchr(u->redirect, '>');
794 hhlocation(char *p, URL *u, Range *r)
798 u->redirect = strdup(p);
802 hhauth(char *p, URL *u, Range *r)
810 if (cistrncmp(p, "basic ", 6) != 0)
811 sysfatal("only Basic authentication supported");
813 if (gettokens(p, f, nelem(f), "\"") < 2)
814 sysfatal("garbled auth data");
816 if ((up = auth_getuserpasswd(auth_getkey, "proto=pass service=http dom=%q relm=%q",
817 u->host, f[1])) == nil)
818 sysfatal("cannot authenticate");
820 s = smprint("%s:%s", up->user, up->passwd);
821 if(enc64(cred, sizeof(cred), (uchar *)s, strlen(s)) == -1)
825 assert(u->cred = strdup(cred));
830 /* ftp return codes */
837 Nnetdir= 64, /* max length of network directory paths */
838 Ndialstr= 64 /* max length of dial strings */
841 int ftpcmd(int, char*, ...);
842 int ftprcode(int, char*, int);
845 int xfertype(int, char*);
846 int passive(int, URL*);
847 int active(int, URL*);
848 int ftpxfer(int, Out*, Range*);
849 int terminateftp(int, int);
850 int getaddrport(char*, uchar*, uchar*);
851 int ftprestart(int, Out*, URL*, Range*, long);
854 doftp(URL *u, URL *px, Range *r, Out *out, long mtime)
856 int pid, ctl, data, rv;
860 /* untested, proxy dosn't work with ftp (I think) */
862 ctl = dial(netmkaddr(u->host, tcpdir, u->port), 0, 0, 0);
864 ctl = dial(netmkaddr(px->host, tcpdir, px->port), 0, 0, 0);
870 strcpy(tcpdir, "tcp");
876 return terminateftp(ctl, rv);
880 return terminateftp(ctl, rv);
882 rv = xfertype(ctl, "I");
884 return terminateftp(ctl, rv);
886 /* if file is up to date and the right size, stop */
887 if(ftprestart(ctl, out, u, r, mtime) > 0){
892 /* first try passive mode, then active */
893 data = passive(ctl, u);
895 data = active(ctl, u);
901 switch(pid = fork()){
904 return terminateftp(ctl, Error);
906 ftpxfer(data, out, r);
915 /* wait for reply message */
916 rv = ftprcode(ctl, msg, sizeof(msg));
919 /* wait for process to terminate */
931 werrstr("xfer: %s", w->msg);
948 ftpcmd(int ctl, char *fmt, ...)
951 char buf[2*1024], *s;
954 s = vseprint(buf, buf + (sizeof(buf)-4) / sizeof(*buf), fmt, arg);
957 fprint(2, "%d -> %s\n", ctl, buf);
960 if(write(ctl, buf, s - buf) != s - buf)
966 ftprcode(int ctl, char *msg, int len)
972 len--; /* room for terminating null */
975 i = readline(ctl, msg, len);
979 fprint(2, "%d <- %s\n", ctl, msg);
981 /* stop if not a continuation */
982 rv = strtol(msg, &p, 10);
983 if(rv >= 100 && rv < 600 && p==msg+3 && *p == ' ')
996 /* wait for hello from other side */
997 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
998 werrstr("HELLO: %s", msg);
1005 getdec(char *p, int n)
1010 for(i = 0; i < n; i++)
1011 x = x*10 + (*p++ - '0');
1016 ftprestart(int ctl, Out *out, URL *u, Range *r, long mtime)
1022 ftpcmd(ctl, "MDTM %s", u->page);
1023 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1025 return 0; /* need to do something */
1028 /* decode modification time */
1029 if(strlen(msg) < 4 + 4 + 2 + 2 + 2 + 2 + 2){
1031 return 0; /* need to do something */
1033 memset(&tm, 0, sizeof(tm));
1034 tm.year = getdec(msg+4, 4) - 1900;
1035 tm.mon = getdec(msg+4+4, 2) - 1;
1036 tm.mday = getdec(msg+4+4+2, 2);
1037 tm.hour = getdec(msg+4+4+2+2, 2);
1038 tm.min = getdec(msg+4+4+2+2+2, 2);
1039 tm.sec = getdec(msg+4+4+2+2+2+2, 2);
1040 strcpy(tm.zone, "GMT");
1041 rmtime = tm2sec(&tm);
1046 ftpcmd(ctl, "SIZE %s", u->page);
1047 if(ftprcode(ctl, msg, sizeof(msg)) == Success){
1050 return 1; /* we're up to date */
1054 /* seek to restart point */
1056 ftpcmd(ctl, "REST %lud", r->start);
1057 if(ftprcode(ctl, msg, sizeof(msg)) == Incomplete){
1058 setoffset(out, r->start);
1063 return 0; /* need to do something */
1071 /* login anonymous */
1072 ftpcmd(ctl, "USER anonymous");
1073 switch(ftprcode(ctl, msg, sizeof(msg))){
1077 break; /* need password */
1079 werrstr("USER: %s", msg);
1083 /* send user id as password */
1084 sprint(msg, "%s@closedmind.org", getuser());
1085 ftpcmd(ctl, "PASS %s", msg);
1086 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1087 werrstr("PASS: %s", msg);
1095 xfertype(int ctl, char *t)
1099 ftpcmd(ctl, "TYPE %s", t);
1100 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1101 werrstr("TYPE %s: %s", t, msg);
1109 passive(int ctl, URL *u)
1119 ftpcmd(ctl, "PASV");
1120 if(ftprcode(ctl, msg, sizeof(msg)) != Success)
1123 /* get address and port number from reply, this is AI */
1124 p = strchr(msg, '(');
1126 for(p = msg+3; *p; p++)
1127 if(isdigit((uchar)*p))
1131 if(getfields(p, f, 6, 0, ",)") < 6){
1132 werrstr("ftp protocol botch");
1135 snprint(ipaddr, sizeof(ipaddr), "%s.%s.%s.%s",
1136 f[0], f[1], f[2], f[3]);
1137 port = ((atoi(f[4])&0xff)<<8) + (atoi(f[5])&0xff);
1138 sprint(aport, "%d", port);
1140 /* open data connection */
1141 fd = dial(netmkaddr(ipaddr, tcpdir, aport), 0, 0, 0);
1143 werrstr("passive mode failed: %r");
1147 /* tell remote to send a file */
1148 ftpcmd(ctl, "RETR %s", u->page);
1149 if(ftprcode(ctl, msg, sizeof(msg)) != Extra){
1150 werrstr("RETR %s: %s", u->page, msg);
1157 active(int ctl, URL *u)
1160 char dir[40], ldir[40];
1165 /* announce a port for the call back */
1166 snprint(msg, sizeof(msg), "%s!*!0", tcpdir);
1167 afd = announce(msg, dir);
1171 /* get a local address/port of the annoucement */
1172 if(getaddrport(dir, ipaddr, port) < 0){
1177 /* tell remote side address and port*/
1178 ftpcmd(ctl, "PORT %d,%d,%d,%d,%d,%d", ipaddr[0], ipaddr[1], ipaddr[2],
1179 ipaddr[3], port[0], port[1]);
1180 if(ftprcode(ctl, msg, sizeof(msg)) != Success){
1182 werrstr("active: %s", msg);
1186 /* tell remote to send a file */
1187 ftpcmd(ctl, "RETR %s", u->page);
1188 if(ftprcode(ctl, msg, sizeof(msg)) != Extra){
1190 werrstr("RETR: %s", msg);
1194 /* wait for a connection */
1195 lcfd = listen(dir, ldir);
1200 dfd = accept(lcfd, ldir);
1213 ftpxfer(int in, Out *out, Range *r)
1221 i = read(in, buf, sizeof(buf));
1226 if(output(out, buf, i) != i)
1229 if(verbose && (vtime != time(0) || r->start == r->end)) {
1231 fprint(2, "%ld %ld\n", r->start, r->end);
1238 terminateftp(int ctl, int rv)
1245 * case insensitive strcmp (why aren't these in libc?)
1248 cistrncmp(char *a, char *b, int n)
1251 if(tolower((uchar)*a++) != tolower((uchar)*b++))
1258 cistrcmp(char *a, char *b)
1261 if(tolower((uchar)*a++) != tolower((uchar)*b++))
1280 b.rp = b.wp = b.buf;
1284 * read a possibly buffered line, strip off trailing while
1287 readline(int fd, char *buf, int len)
1297 n = read(fd, b.wp, sizeof(b.buf)/2);
1315 /* drop trailing white */
1320 if(n != ' ' && n != '\t' && n != '\r' && n != '\n')
1333 unreadline(char *line)
1339 memmove(&b.buf[i+1], b.rp, n);
1340 memmove(b.buf, line, i);
1343 b.wp = b.rp + i + 1 + n;
1347 readibuf(int fd, char *buf, int len)
1355 memmove(buf, b.rp, n);
1359 return read(fd, buf, len);
1363 dfprint(int fd, char *fmt, ...)
1369 vseprint(buf, buf+sizeof(buf), fmt, arg);
1372 fprint(2, "%d -> %s", fd, buf);
1373 return fprint(fd, "%s", buf);
1377 getaddrport(char *dir, uchar *ipaddr, uchar *port)
1383 snprint(buf, sizeof(buf), "%s/local", dir);
1384 fd = open(buf, OREAD);
1387 i = read(fd, buf, sizeof(buf)-1);
1392 p = strchr(buf, '!');
1395 v4parseip(ipaddr, buf);
1403 md5free(DigestState *state)
1406 md5(nil, 0, x, state);
1410 md5dup(DigestState *state)
1414 s2 = malloc(sizeof(DigestState));
1416 sysfatal("malloc: %r");
1423 setoffset(Out *out, int offset)
1427 out->curr = md5(nil, 0, nil, nil);
1430 out->offset = offset;
1434 * write some output, discarding it (but keeping track)
1435 * if we've already written it. if we've gone backwards,
1436 * verify that everything previously written matches
1437 * that which would have been written from the current
1441 output(Out *out, char *buf, int nb)
1444 uchar m0[MD5dlen], m1[MD5dlen];
1447 d = out->written - out->offset;
1451 if(out->curr != nil)
1452 md5((uchar*)buf, n, nil, out->curr);
1456 if(out->curr != nil){
1457 md5((uchar*)buf, d, m0, out->curr);
1459 md5(nil, 0, m1, md5dup(out->hiwat));
1460 if(memcmp(m0, m1, MD5dlen) != 0){
1461 fprint(2, "integrity check failure at offset %d\n", out->written);
1470 out->hiwat = md5((uchar*)buf, n, nil, out->hiwat);
1471 n = write(out->fd, buf, n);