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);
80 memset(&conn, 0, sizeof(conn));
82 conn.trace = tlstrace;
83 if((fd = tlsClient(fd, &conn)) < 0){
84 if(debug) fprint(2, "tlsClient: %r\n");
99 snprint(addr, sizeof(addr), "tcp!%s!%s", u->host, u->port ? u->port : u->scheme);
102 for(p = nil, h = hpool.head; h; p = h, h = h->next){
103 if(strcmp(h->addr, addr) == 0){
107 hpool.head = h->next;
117 fprint(2, "hdial [%d] %s\n", hpool.active, addr);
120 snprint(addr, sizeof(addr), "tcp!%s!%s",
121 proxy->host, proxy->port ? proxy->port : proxy->scheme);
123 if((fd = dial(addr, 0, 0, &ctl)) >= 0){
125 if(strcmp(proxy->scheme, "https") == 0)
128 if(strcmp(u->scheme, "https") == 0)
137 h = emalloc(sizeof(*h));
148 h->tunnel = strcmp(u->scheme, "https") == 0;
149 snprint(addr, sizeof(addr), "tcp!%s!%s", u->host, u->port ? u->port : u->scheme);
151 nstrcpy(h->addr, addr, sizeof(h->addr));
179 if(!h->tunnel && h->keep && h->fd >= 0){
180 for(n = 0, i = 0, t = nil, x = hpool.head; x; x = x->next){
181 if(strcmp(x->addr, h->addr) == 0)
184 if(++i < hpool.limit)
188 /* return connection to pool */
190 h->next = hpool.head;
206 * if h is first one in pool, spawn proc to close
210 if(rfork(RFMEM|RFPROC|RFNOWAIT) == 0){
223 if((now - h->time) > hpool.idle){
234 i = hpool.head != nil;
249 fprint(2, "hclose [%d] %s\n", hpool.active, h->addr);
262 fprint(2, "hangup pc=%p: %r\n", getcallerpc(&h));
269 hread(Hconn *h, void *data, int len)
274 memmove(data, h->buf, len);
277 memmove(h->buf, h->buf + len, h->len);
280 if((len = read(h->fd, data, len)) == 0)
288 hwrite(Hconn *h, void *data, int len)
290 if(write(h->fd, data, len) != len){
298 hline(Hconn *h, char *data, int len, int cont)
306 while(x = memchr(h->buf, '\n', h->len)){
308 if(n > 0 && x[-1] == '\r')
312 for(y = x+1; y < e; y++)
313 if(*y != ' ' && *y != '\t')
315 if(y >= e || *y == 0)
318 if(x > h->buf && x[-1] == '\r')
320 memmove(x, y, e - y);
327 memmove(data, h->buf, len);
329 h->len -= (++x - h->buf);
331 memmove(h->buf, x, h->len);
335 n = sizeof(h->buf) - h->len;
339 n = 1; /* do not read beyond header */
340 if((n = read(h->fd, h->buf + h->len, n)) <= 0){
349 authenticate(Url *u, Url *ru, char *method, char *s)
351 char *user, *pass, *realm, *nonce, *opaque, *x;
358 realm = nonce = opaque = nil;
359 if(!cistrncmp(s, "Basic ", 6)){
363 if(x = cistrstr(s, "realm="))
364 realm = unquote(x+6, &s);
368 if(user == nil || pass == nil){
370 fmtprint(&fmt, " realm=%q", realm);
372 fmtprint(&fmt, " user=%q", user);
373 if((s = fmtstrflush(&fmt)) == nil)
375 up = auth_getuserpasswd(nil, "proto=pass service=http server=%q%s", u->host, s);
383 fmtprint(&fmt, "%s:%s", user ? user : "", pass ? pass : "");
385 memset(up->user, 0, strlen(up->user));
386 memset(up->passwd, 0, strlen(up->passwd));
389 if((s = fmtstrflush(&fmt)) == nil)
393 fmtprint(&fmt, "Basic %.*[", n, s);
396 u = saneurl(url(".", u)); /* all uris below the requested one */
398 if(!cistrncmp(s, "Digest ", 7)){
399 char chal[1024], ouser[128], resp[2*MD5LEN+1];
403 if(x = cistrstr(s, "realm="))
404 realm = unquote(x+6, &s);
405 if(x = cistrstr(s, "nonce="))
406 nonce = unquote(x+6, &s);
407 if(x = cistrstr(s, "opaque="))
408 opaque = unquote(x+7, &s);
409 if(realm == nil || nonce == nil)
412 fmtprint(&fmt, " realm=%q", realm);
414 fmtprint(&fmt, " user=%q", user);
415 if((s = fmtstrflush(&fmt)) == nil)
417 nchal = snprint(chal, sizeof(chal), "%s %s %U", nonce, method, ru);
418 n = auth_respond(chal, nchal, ouser, sizeof ouser, resp, sizeof resp, nil,
419 "proto=httpdigest role=client server=%q%s", u->host, s);
420 memset(chal, 0, sizeof(chal));
425 fmtprint(&fmt, "Digest ");
426 fmtprint(&fmt, "username=\"%s\", ", ouser);
427 fmtprint(&fmt, "realm=\"%s\", ", realm);
428 fmtprint(&fmt, "host=\"%H\", ", u->host);
429 fmtprint(&fmt, "uri=\"%U\", ", ru);
430 fmtprint(&fmt, "nonce=\"%s\", ", nonce);
431 fmtprint(&fmt, "response=\"%s\"", resp);
433 fmtprint(&fmt, ", opaque=\"%s\"", opaque);
434 u = saneurl(url("/", u)); /* BUG: should be the ones in domain= only */
437 if((s = fmtstrflush(&fmt)) == nil){
445 a = emalloc(sizeof(*a));
457 hauthenticate(Url *u, Url *ru, char *method, char *key, Key *hdr)
459 for(hdr = getkey(hdr, key); hdr != nil; hdr = getkey(hdr->next, key))
460 if(authenticate(u, ru, method, hdr->val) == 0)
466 flushauth(Url *u, char *t)
472 for(p = nil, a = hauth; a; p = a, a = a->next)
473 if(matchurl(u, a->url) && (t == nil || !strcmp(t, a->auth))){
479 fprint(2, "flushauth for %U\n", a->url);
481 memset(a->auth, 0, strlen(a->auth));
490 catch(void *, char *msg)
492 if(strstr("alarm", msg) || strstr("die", msg))
498 #define NOLENGTH 0x7fffffffffffffffLL
501 http(char *m, Url *u, Key *shdr, Buq *qbody, Buq *qpost)
503 int i, l, n, try, pid, fd, cfd, needlength, chunked, retry, nobody;
504 char *s, *x, buf[8192+2], status[256], method[16], *host;
505 vlong length, offset;
512 if(qpost) incref(qpost);
513 nstrcpy(method, m, sizeof(method));
514 switch(rfork(RFPROC|RFMEM|RFNOWAIT)){
518 buclose(qbody, "can't fork");
520 buclose(qpost, "can't fork");
534 /* file for spooling the postbody if we need to restart the request */
535 snprint(buf, sizeof(buf), "/tmp/http.%d.%d.post", getppid(), getpid());
536 fd = create(buf, OEXCL|ORDWR|ORCLOSE, 0600);
545 for(try = 0; try < 12; try++){
546 strcpy(status, "0 No status");
547 if(u == nil || (strcmp(u->scheme, "http") && strcmp(u->scheme, "https"))){
548 werrstr("bad url scheme");
553 fprint(2, "http(%d): %s %U\n", try, method, u);
555 /* preemptive authentication from hauth cache */
557 if(proxy && !lookkey(shdr, "Proxy-Authorization"))
558 for(a = hauth; a; a = a->next)
559 if(matchurl(a->url, proxy)){
560 shdr = addkey(shdr, "Proxy-Authorization", a->auth);
563 if(!lookkey(shdr, "Authorization"))
564 for(a = hauth; a; a = a->next)
565 if(matchurl(a->url, u)){
566 shdr = addkey(shdr, "Authorization", a->auth);
574 /* have to read it to temp file to figure out the length */
575 if(fd >= 0 && needlength && lookkey(shdr, "Content-Length") == nil){
577 while((n = buread(qpost, buf, sizeof(buf))) > 0)
579 shdr = delkey(shdr, "Transfer-Encoding");
583 /* wait until buffer is full, most posts are small */
584 while(!qpost->closed && qpost->size < qpost->limit && qpost->nwq == 0)
587 if(lookkey(shdr, "Content-Length"))
589 else if(x = lookkey(shdr, "Transfer-Encoding"))
590 chunked = cistrstr(x, "chunked") != nil;
591 else if(chunked = !qpost->closed)
592 shdr = addkey(shdr, "Transfer-Encoding", "chunked");
593 else if(qpost->closed){
595 length = seek(fd, 0, 2);
599 length += qpost->size;
600 snprint(buf, sizeof(buf), "%lld", length);
601 shdr = addkey(shdr, "Content-Length", buf);
606 /* http requires ascii encoding of host */
608 host = smprint("%H", u->host);
610 if(proxy && strcmp(u->scheme, "https") != 0){
615 memset(&ru, 0, sizeof(ru));
619 n = snprint(buf, sizeof(buf), "%s %U HTTP/1.1\r\nHost: %s%s%s\r\n",
620 method, &ru, host, u->port ? ":" : "", u->port ? u->port : "");
621 if(n >= sizeof(buf)-64){
622 werrstr("request too large");
627 if((h = hdial(u)) == nil)
631 n = snprint(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n",
632 host, u->port ? u->port : "443",
633 host, u->port ? u->port : "443");
635 else if((cfd = open("/mnt/webcookies/http", ORDWR)) >= 0){
636 /* only scheme, host and path are relevant for cookies */
637 memset(&tu, 0, sizeof(tu));
638 tu.scheme = u->scheme;
641 fprint(cfd, "%U", &tu);
643 if(n >= sizeof(buf)-2){
645 fprint(2, "-> %.*s", n, buf);
646 if(hwrite(h, buf, n) != n)
650 if((l = read(cfd, buf+n, sizeof(buf)-2 - n)) == 0)
661 for(k = shdr; k; k = k->next){
662 /* only send proxy headers when establishing tunnel */
663 if(h->tunnel && cistrncmp(k->key, "Proxy-", 6) != 0)
665 n += snprint(buf+n, sizeof(buf)-2 - n, "%s: %s\r\n", k->key, k->val);
667 n += snprint(buf+n, sizeof(buf)-n, "\r\n");
669 fprint(2, "-> %.*s", n, buf);
670 if(hwrite(h, buf, n) != n){
676 if(qpost && !h->tunnel){
678 if((pid = rfork(RFMEM|RFPROC)) <= 0){
685 if((ifd < 0) || ((n = read(ifd, buf, sizeof(buf)-2)) <= 0)){
687 if((n = buread(qpost, buf, sizeof(buf)-2)) <= 0)
690 if(write(fd, buf, n) != n)
696 if(hwrite(h, tmp, snprint(tmp, sizeof(tmp), "%x\r\n", n)) < 0)
701 if(hwrite(h, buf, n) != n)
706 hwrite(h, "0\r\n\r\n", 5);
712 /* no timeout when posting */
723 for(l = 0; hline(h, s = buf, sizeof(buf)-1, 1) > 0; l++){
725 fprint(2, "<- %s\n", s);
727 if(x = strchr(s, ' '))
730 if(cistrncmp(s, "HTTP", 4)){
732 if(cistrcmp(s, "ICY"))
736 nstrcpy(status, x, sizeof(status));
739 if((k = parsehdr(s)) == nil)
741 if(!cistrcmp(k->key, "Connection")){
742 if(cistrstr(k->val, "close"))
745 else if(!cistrcmp(k->key, "Content-Length"))
746 length = atoll(k->val);
747 else if(!cistrcmp(k->key, "Transfer-Encoding")){
748 if(cistrstr(k->val, "chunked"))
751 else if(!cistrcmp(k->key, "Set-Cookie") ||
752 !cistrcmp(k->key, "Set-Cookie2")){
754 fprint(cfd, "Set-Cookie: %s\n", k->val);
767 nobody = !cistrcmp(method, "HEAD");
768 if((i = atoi(status)) < 0)
777 case 100: /* Continue */
778 case 101: /* Switching Protocols */
784 case 304: /* Not Modified */
786 case 305: /* Use Proxy */
787 case 400: /* Bad Request */
788 case 402: /* Payment Required */
789 case 403: /* Forbidden */
790 case 404: /* Not Found */
791 case 405: /* Method Not Allowed */
792 case 406: /* Not Acceptable */
793 case 408: /* Request Timeout */
794 case 409: /* Conflict */
797 case 411: /* Length Required */
804 case 412: /* Precondition Failed */
805 case 413: /* Request Entity Too Large */
806 case 414: /* Request URI Too Large */
807 case 415: /* Unsupported Media Type */
808 case 416: /* Requested Range Not Satisfiable */
809 case 417: /* Expectation Failed */
810 case 500: /* Internal server error */
811 case 501: /* Not implemented */
812 case 502: /* Bad gateway */
813 case 503: /* Service unavailable */
814 case 504: /* Gateway Timeout */
815 case 505: /* HTTP Version not Supported */
818 buclose(qbody, status);
819 buclose(qpost, status);
821 case 300: /* Multiple choices */
822 case 302: /* Found */
823 case 303: /* See Other */
833 shdr = delkey(shdr, "Content-Length");
834 shdr = delkey(shdr, "Content-Type");
835 shdr = delkey(shdr, "Transfer-Encoding");
836 if(cistrcmp(method, "HEAD"))
837 nstrcpy(method, "GET", sizeof(method));
838 case 301: /* Moved Permanently */
839 case 307: /* Temporary Redirect */
840 case 308: /* Resume Incomplete */
841 if((x = lookkey(rhdr, "Location")) == nil)
843 if((nu = saneurl(url(x, u))) == nil)
848 case 401: /* Unauthorized */
849 if(x = lookkey(shdr, "Authorization"))
851 if(hauthenticate(u, &ru, method, "WWW-Authenticate", rhdr) < 0)
855 case 407: /* Proxy Auth */
858 if(x = lookkey(shdr, "Proxy-Authorization"))
860 if(hauthenticate(u, &ru, method, "Proxy-Authenticate", rhdr) < 0)
863 case 0: /* No status */
872 case 204: /* No Content */
873 case 205: /* Reset Content */
876 case 201: /* Created */
877 case 202: /* Accepted */
878 case 203: /* Non-Authoritative Information */
879 case 206: /* Partial Content */
882 qbody->url = u; u = nil;
883 qbody->hdr = rhdr; rhdr = nil;
895 * remove authorization headers so on the next round, we use
896 * the hauth cache (wich checks the scope url). this makes
897 * sure we wont send credentials to the wrong url after
900 shdr = delkey(shdr, "Proxy-Authorization");
901 shdr = delkey(shdr, "Authorization");
904 * when 2xx response is given for the CONNECT request
905 * then the proxy server has established the connection.
907 if(h->tunnel && !retry && (i/100) == 2){
908 if((h->fd = tlswrap(h->fd)) < 0)
911 /* proceed to the original request */
916 if(!chunked && length == NOLENGTH)
920 * read the response body (if any). retry means we'r just
921 * skipping the error page so we wont touch qbody.
924 if((qbody->closed || retry) && !h->keep)
927 if(hline(h, buf, sizeof(buf)-1, 0) <= 0)
929 length = strtoll(buf, nil, 16);
932 while(offset < length){
934 if(l > (length - offset))
935 l = (length - offset);
936 if((n = hread(h, buf, l)) <= 0)
940 if(buwrite(qbody, buf, n) != n)
943 if(offset != length){
945 if(length != NOLENGTH)
949 while(hline(h, buf, sizeof(buf)-1, 1) > 0){
951 fprint(2, "<= %s\n", buf);
953 if(k = parsehdr(buf)){
954 k->next = qbody->hdr;
979 snprint(buf, sizeof(buf), "%s %r", status);