15 typedef struct Hconn Hconn;
16 typedef struct Hpool Hpool;
17 typedef struct Hauth Hauth;
53 static Hpool hpool = {
56 .idle = 5, /* seconds */
62 static void hclose(Hconn *h);
65 tlstrace(char *fmt, ...)
70 r = vfprint(2, fmt, a);
76 tlswrap(int fd, char *servername)
80 memset(&conn, 0, sizeof(conn));
82 conn.trace = tlstrace;
84 conn.serverName = smprint("%N", servername);
85 if((fd = tlsClient(fd, &conn)) < 0){
86 if(debug) fprint(2, "tlsClient: %r\n");
91 free(conn.serverName);
102 snprint(addr, sizeof(addr), "tcp!%s!%s", u->host, u->port ? u->port : u->scheme);
105 for(p = nil, h = hpool.head; h; p = h, h = h->next){
106 if(strcmp(h->addr, addr) == 0){
110 hpool.head = h->next;
120 fprint(2, "hdial [%d] %s\n", hpool.active, addr);
123 snprint(addr, sizeof(addr), "tcp!%s!%s",
124 proxy->host, proxy->port ? proxy->port : proxy->scheme);
126 if((fd = dial(addr, 0, 0, &ctl)) >= 0){
128 if(strcmp(proxy->scheme, "https") == 0)
129 fd = tlswrap(fd, proxy->host);
131 if(strcmp(u->scheme, "https") == 0)
132 fd = tlswrap(fd, u->host);
140 h = emalloc(sizeof(*h));
151 h->tunnel = strcmp(u->scheme, "https") == 0;
152 snprint(addr, sizeof(addr), "tcp!%s!%s", u->host, u->port ? u->port : u->scheme);
154 nstrcpy(h->addr, addr, sizeof(h->addr));
182 if(!h->tunnel && h->keep && h->fd >= 0){
183 for(n = 0, i = 0, t = nil, x = hpool.head; x; x = x->next){
184 if(strcmp(x->addr, h->addr) == 0)
187 if(++i < hpool.limit)
191 /* return connection to pool */
193 h->next = hpool.head;
209 * if h is first one in pool, spawn proc to close
213 if(rfork(RFMEM|RFPROC|RFNOWAIT) == 0){
226 if((now - h->time) > hpool.idle){
237 i = hpool.head != nil;
252 fprint(2, "hclose [%d] %s\n", hpool.active, h->addr);
265 fprint(2, "hangup pc=%p: %r\n", getcallerpc(&h));
272 hread(Hconn *h, void *data, int len)
277 memmove(data, h->buf, len);
280 memmove(h->buf, h->buf + len, h->len);
283 if((len = read(h->fd, data, len)) == 0)
291 hwrite(Hconn *h, void *data, int len)
293 if(write(h->fd, data, len) != len){
301 hline(Hconn *h, char *data, int len, int cont)
309 while(x = memchr(h->buf, '\n', h->len)){
311 if(n > 0 && x[-1] == '\r')
315 for(y = x+1; y < e; y++)
316 if(*y != ' ' && *y != '\t')
318 if(y >= e || *y == 0)
321 if(x > h->buf && x[-1] == '\r')
323 memmove(x, y, e - y);
330 memmove(data, h->buf, len);
332 h->len -= (++x - h->buf);
334 memmove(h->buf, x, h->len);
338 n = sizeof(h->buf) - h->len;
342 n = 1; /* do not read beyond header */
343 if((n = read(h->fd, h->buf + h->len, n)) <= 0){
352 authenticate(Url *u, Url *ru, char *method, char *s)
354 char *user, *pass, *realm, *nonce, *opaque, *x;
361 realm = nonce = opaque = nil;
362 if(!cistrncmp(s, "Basic ", 6)){
366 if(x = cistrstr(s, "realm="))
367 realm = unquote(x+6, &s);
371 if(user == nil || pass == nil){
373 fmtprint(&fmt, " realm=%q", realm);
375 fmtprint(&fmt, " user=%q", user);
376 if((s = fmtstrflush(&fmt)) == nil)
378 up = auth_getuserpasswd(nil, "proto=pass service=http server=%q%s", u->host, s);
386 fmtprint(&fmt, "%s:%s", user ? user : "", pass ? pass : "");
388 memset(up->user, 0, strlen(up->user));
389 memset(up->passwd, 0, strlen(up->passwd));
392 if((s = fmtstrflush(&fmt)) == nil)
396 fmtprint(&fmt, "Basic %.*[", n, s);
399 u = saneurl(url(".", u)); /* all uris below the requested one */
401 if(!cistrncmp(s, "Digest ", 7)){
402 char chal[1024], ouser[128], resp[2*MD5LEN+1];
406 if(x = cistrstr(s, "realm="))
407 realm = unquote(x+6, &s);
408 if(x = cistrstr(s, "nonce="))
409 nonce = unquote(x+6, &s);
410 if(x = cistrstr(s, "opaque="))
411 opaque = unquote(x+7, &s);
412 if(realm == nil || nonce == nil)
415 fmtprint(&fmt, " realm=%q", realm);
417 fmtprint(&fmt, " user=%q", user);
418 if((s = fmtstrflush(&fmt)) == nil)
420 nchal = snprint(chal, sizeof(chal), "%s %s %U", nonce, method, ru);
421 n = auth_respond(chal, nchal, ouser, sizeof ouser, resp, sizeof resp, nil,
422 "proto=httpdigest role=client server=%q%s", u->host, s);
423 memset(chal, 0, sizeof(chal));
428 fmtprint(&fmt, "Digest ");
429 fmtprint(&fmt, "username=\"%s\", ", ouser);
430 fmtprint(&fmt, "realm=\"%s\", ", realm);
431 fmtprint(&fmt, "host=\"%N\", ", u->host);
432 fmtprint(&fmt, "uri=\"%U\", ", ru);
433 fmtprint(&fmt, "nonce=\"%s\", ", nonce);
434 fmtprint(&fmt, "response=\"%s\"", resp);
436 fmtprint(&fmt, ", opaque=\"%s\"", opaque);
437 u = saneurl(url("/", u)); /* BUG: should be the ones in domain= only */
440 if((s = fmtstrflush(&fmt)) == nil){
448 a = emalloc(sizeof(*a));
460 hauthenticate(Url *u, Url *ru, char *method, char *key, Key *hdr)
462 for(hdr = getkey(hdr, key); hdr != nil; hdr = getkey(hdr->next, key))
463 if(authenticate(u, ru, method, hdr->val) == 0)
469 flushauth(Url *u, char *t)
475 for(p = nil, a = hauth; a; p = a, a = a->next)
476 if(matchurl(u, a->url) && (t == nil || !strcmp(t, a->auth))){
482 fprint(2, "flushauth for %U\n", a->url);
484 memset(a->auth, 0, strlen(a->auth));
493 catch(void *, char *msg)
495 if(strstr("alarm", msg) != nil)
501 #define NOLENGTH 0x7fffffffffffffffLL
504 http(char *m, Url *u, Key *shdr, Buq *qbody, Buq *qpost)
506 int i, l, n, try, pid, fd, cfd, needlength, chunked, retry, nobody;
507 char *s, *x, buf[8192+2], status[256], method[16], *host;
508 vlong length, offset;
515 if(qpost) incref(qpost);
516 nstrcpy(method, m, sizeof(method));
517 switch(rfork(RFPROC|RFMEM|RFNOWAIT)){
521 buclose(qbody, "can't fork");
523 buclose(qpost, "can't fork");
537 /* file for spooling the postbody if we need to restart the request */
538 snprint(buf, sizeof(buf), "/tmp/http.%d.%d.post", getppid(), getpid());
539 fd = create(buf, OEXCL|ORDWR|ORCLOSE, 0600);
548 for(try = 0; try < 12; try++){
549 strcpy(status, "0 No status");
550 if(u == nil || (strcmp(u->scheme, "http") && strcmp(u->scheme, "https"))){
551 werrstr("bad url scheme");
556 fprint(2, "http(%d): %s %U\n", try, method, u);
558 /* preemptive authentication from hauth cache */
560 if(proxy && !lookkey(shdr, "Proxy-Authorization"))
561 for(a = hauth; a; a = a->next)
562 if(matchurl(a->url, proxy)){
563 shdr = addkey(shdr, "Proxy-Authorization", a->auth);
566 if(!lookkey(shdr, "Authorization"))
567 for(a = hauth; a; a = a->next)
568 if(matchurl(a->url, u)){
569 shdr = addkey(shdr, "Authorization", a->auth);
577 /* have to read it to temp file to figure out the length */
578 if(fd >= 0 && needlength && lookkey(shdr, "Content-Length") == nil){
580 while((n = buread(qpost, buf, sizeof(buf))) > 0)
582 shdr = delkey(shdr, "Transfer-Encoding");
586 /* wait until buffer is full, most posts are small */
587 while(!qpost->closed && qpost->size < qpost->limit && qpost->nwq == 0)
590 if(lookkey(shdr, "Content-Length"))
592 else if(x = lookkey(shdr, "Transfer-Encoding"))
593 chunked = cistrstr(x, "chunked") != nil;
594 else if(chunked = !qpost->closed)
595 shdr = addkey(shdr, "Transfer-Encoding", "chunked");
596 else if(qpost->closed){
598 length = seek(fd, 0, 2);
602 length += qpost->size;
603 snprint(buf, sizeof(buf), "%lld", length);
604 shdr = addkey(shdr, "Content-Length", buf);
609 /* http requires ascii encoding of host */
611 host = smprint("%N", u->host);
613 if(proxy && strcmp(u->scheme, "https") != 0){
618 memset(&ru, 0, sizeof(ru));
622 n = snprint(buf, sizeof(buf), "%s %U HTTP/1.1\r\nHost: %s%s%s\r\n",
623 method, &ru, host, u->port ? ":" : "", u->port ? u->port : "");
624 if(n >= sizeof(buf)-64){
625 werrstr("request too large");
630 if((h = hdial(u)) == nil)
634 n = snprint(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n",
635 host, u->port ? u->port : "443",
636 host, u->port ? u->port : "443");
638 else if((cfd = open("/mnt/webcookies/http", ORDWR)) >= 0){
639 /* only scheme, host and path are relevant for cookies */
640 memset(&tu, 0, sizeof(tu));
641 tu.scheme = u->scheme;
644 fprint(cfd, "%U", &tu);
646 if(n >= sizeof(buf)-2){
648 fprint(2, "-> %.*s", n, buf);
649 if(hwrite(h, buf, n) != n)
653 if((l = read(cfd, buf+n, sizeof(buf)-2 - n)) == 0)
664 for(k = shdr; k; k = k->next){
665 /* only send proxy headers when establishing tunnel */
666 if(h->tunnel && cistrncmp(k->key, "Proxy-", 6) != 0)
668 n += snprint(buf+n, sizeof(buf)-2 - n, "%s: %s\r\n", k->key, k->val);
670 n += snprint(buf+n, sizeof(buf)-n, "\r\n");
672 fprint(2, "-> %.*s", n, buf);
673 if(hwrite(h, buf, n) != n){
679 if(qpost && !h->tunnel){
681 if((pid = rfork(RFMEM|RFPROC)) <= 0){
688 if((ifd < 0) || ((n = read(ifd, buf, sizeof(buf)-2)) <= 0)){
690 if((n = buread(qpost, buf, sizeof(buf)-2)) <= 0)
693 if(write(fd, buf, n) != n)
699 if(hwrite(h, tmp, snprint(tmp, sizeof(tmp), "%x\r\n", n)) < 0)
704 if(hwrite(h, buf, n) != n)
709 hwrite(h, "0\r\n\r\n", 5);
715 /* no timeout when posting */
726 for(l = 0; hline(h, s = buf, sizeof(buf)-1, 1) > 0; l++){
728 fprint(2, "<- %s\n", s);
730 if(x = strchr(s, ' '))
733 if(cistrncmp(s, "HTTP", 4)){
735 if(cistrcmp(s, "ICY"))
739 nstrcpy(status, x, sizeof(status));
742 if((k = parsehdr(s)) == nil)
744 if(!cistrcmp(k->key, "Connection")){
745 if(cistrstr(k->val, "close"))
748 else if(!cistrcmp(k->key, "Content-Length"))
749 length = atoll(k->val);
750 else if(!cistrcmp(k->key, "Transfer-Encoding")){
751 if(cistrstr(k->val, "chunked"))
754 else if(!cistrcmp(k->key, "Set-Cookie") ||
755 !cistrcmp(k->key, "Set-Cookie2")){
757 fprint(cfd, "Set-Cookie: %s\n", k->val);
770 nobody = !cistrcmp(method, "HEAD");
771 if((i = atoi(status)) < 0)
780 case 100: /* Continue */
781 case 101: /* Switching Protocols */
787 case 304: /* Not Modified */
789 case 305: /* Use Proxy */
790 case 400: /* Bad Request */
791 case 402: /* Payment Required */
792 case 403: /* Forbidden */
793 case 404: /* Not Found */
794 case 405: /* Method Not Allowed */
795 case 406: /* Not Acceptable */
796 case 408: /* Request Timeout */
797 case 409: /* Conflict */
800 case 411: /* Length Required */
807 case 412: /* Precondition Failed */
808 case 413: /* Request Entity Too Large */
809 case 414: /* Request URI Too Large */
810 case 415: /* Unsupported Media Type */
811 case 416: /* Requested Range Not Satisfiable */
812 case 417: /* Expectation Failed */
813 case 500: /* Internal server error */
814 case 501: /* Not implemented */
815 case 502: /* Bad gateway */
816 case 503: /* Service unavailable */
817 case 504: /* Gateway Timeout */
818 case 505: /* HTTP Version not Supported */
821 buclose(qbody, status);
822 buclose(qpost, status);
824 case 300: /* Multiple choices */
825 case 302: /* Found */
826 case 303: /* See Other */
836 shdr = delkey(shdr, "Content-Length");
837 shdr = delkey(shdr, "Content-Type");
838 shdr = delkey(shdr, "Transfer-Encoding");
839 if(cistrcmp(method, "HEAD"))
840 nstrcpy(method, "GET", sizeof(method));
841 case 301: /* Moved Permanently */
842 case 307: /* Temporary Redirect */
843 case 308: /* Resume Incomplete */
844 if((x = lookkey(rhdr, "Location")) == nil)
846 if((nu = saneurl(url(x, u))) == nil)
851 case 401: /* Unauthorized */
852 if(x = lookkey(shdr, "Authorization"))
854 if(hauthenticate(u, &ru, method, "WWW-Authenticate", rhdr) < 0)
858 case 407: /* Proxy Auth */
861 if(x = lookkey(shdr, "Proxy-Authorization"))
863 if(hauthenticate(proxy, proxy, method, "Proxy-Authenticate", rhdr) < 0)
866 case 0: /* No status */
875 case 204: /* No Content */
876 case 205: /* Reset Content */
879 case 201: /* Created */
880 case 202: /* Accepted */
881 case 203: /* Non-Authoritative Information */
882 case 206: /* Partial Content */
885 qbody->url = u; u = nil;
886 qbody->hdr = rhdr; rhdr = nil;
898 * remove authorization headers so on the next round, we use
899 * the hauth cache (wich checks the scope url). this makes
900 * sure we wont send credentials to the wrong url after
903 shdr = delkey(shdr, "Proxy-Authorization");
904 shdr = delkey(shdr, "Authorization");
907 * when 2xx response is given for the CONNECT request
908 * then the proxy server has established the connection.
910 if(h->tunnel && !retry && (i/100) == 2){
911 if((h->fd = tlswrap(h->fd, host)) < 0)
914 /* proceed to the original request */
919 if(!chunked && length == NOLENGTH)
923 * read the response body (if any). retry means we'r just
924 * skipping the error page so we wont touch qbody.
927 if((qbody->closed || retry) && !h->keep)
930 if(hline(h, buf, sizeof(buf)-1, 0) <= 0)
932 length = strtoll(buf, nil, 16);
935 while(offset < length){
937 if(l > (length - offset))
938 l = (length - offset);
939 if((n = hread(h, buf, l)) <= 0)
943 if(buwrite(qbody, buf, n) != n)
946 if(offset != length){
948 if(length != NOLENGTH)
952 while(hline(h, buf, sizeof(buf)-1, 1) > 0){
954 fprint(2, "<= %s\n", buf);
956 if(k = parsehdr(buf)){
957 k->next = qbody->hdr;
982 snprint(buf, sizeof(buf), "%s %r", status);