2 * Copyright (c) 2000-2011 Dag-Erling Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 * The following copyright applies to the base64 code:
36 * Copyright 1997 Massachusetts Institute of Technology
38 * Permission to use, copy, modify, and distribute this software and
39 * its documentation for any purpose and without fee is hereby
40 * granted, provided that both the above copyright notice and this
41 * permission notice appear in all copies, that both the above
42 * copyright notice and this permission notice appear in all
43 * supporting documentation, and that the name of M.I.T. not be used
44 * in advertising or publicity pertaining to distribution of the
45 * software without specific, written prior permission. M.I.T. makes
46 * no representations about the suitability of this software for any
47 * purpose. It is provided "as is" without express or implied
50 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
51 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
52 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
53 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
54 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
56 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
57 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
58 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
59 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
60 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 #include <sys/param.h>
65 #include <sys/socket.h>
81 #include <openssl/md5.h>
82 #define MD5Init(c) MD5_Init(c)
83 #define MD5Update(c, data, len) MD5_Update(c, data, len)
84 #define MD5Final(md, c) MD5_Final(md, c)
89 #include <netinet/in.h>
90 #include <netinet/tcp.h>
96 /* Maximum number of redirects to follow */
97 #define MAX_REDIRECT 20
99 /* Symbolic names for reply codes we care about */
101 #define HTTP_PARTIAL 206
102 #define HTTP_MOVED_PERM 301
103 #define HTTP_MOVED_TEMP 302
104 #define HTTP_SEE_OTHER 303
105 #define HTTP_NOT_MODIFIED 304
106 #define HTTP_USE_PROXY 305
107 #define HTTP_TEMP_REDIRECT 307
108 #define HTTP_PERM_REDIRECT 308
109 #define HTTP_NEED_AUTH 401
110 #define HTTP_NEED_PROXY_AUTH 407
111 #define HTTP_BAD_RANGE 416
112 #define HTTP_PROTOCOL_ERROR 999
114 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
115 || (xyz) == HTTP_MOVED_TEMP \
116 || (xyz) == HTTP_TEMP_REDIRECT \
117 || (xyz) == HTTP_USE_PROXY \
118 || (xyz) == HTTP_SEE_OTHER)
120 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
123 /*****************************************************************************
124 * I/O functions for decoding chunked streams
129 conn_t *conn; /* connection */
130 int chunked; /* chunked mode */
131 char *buf; /* chunk buffer */
132 size_t bufsize; /* size of chunk buffer */
133 ssize_t buflen; /* amount of data currently in buffer */
134 int bufpos; /* current read offset in buffer */
135 int eof; /* end-of-file flag */
136 int error; /* error flag */
137 size_t chunksize; /* remaining size of current chunk */
144 * Get next chunk header
147 http_new_chunk(struct httpio *io)
151 if (fetch_getln(io->conn) == -1)
154 if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
157 for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
160 if (!isxdigit((unsigned char)*p))
162 if (isdigit((unsigned char)*p)) {
163 io->chunksize = io->chunksize * 16 +
166 io->chunksize = io->chunksize * 16 +
167 10 + tolower((unsigned char)*p) - 'a';
173 io->total += io->chunksize;
174 if (io->chunksize == 0)
175 fprintf(stderr, "%s(): end of last chunk\n", __func__);
177 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
178 __func__, (unsigned long)io->chunksize,
179 (unsigned long)io->total);
183 return (io->chunksize);
187 * Grow the input buffer to at least len bytes
190 http_growbuf(struct httpio *io, size_t len)
194 if (io->bufsize >= len)
197 if ((tmp = realloc(io->buf, len)) == NULL)
205 * Fill the input buffer, do chunk decoding on the fly
208 http_fillbuf(struct httpio *io, size_t len)
217 if (io->chunked == 0) {
218 if (http_growbuf(io, len) == -1)
220 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
229 if (io->chunksize == 0) {
230 switch (http_new_chunk(io)) {
240 if (len > io->chunksize)
242 if (http_growbuf(io, len) == -1)
244 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
249 io->chunksize -= io->buflen;
251 if (io->chunksize == 0) {
254 if (fetch_read(io->conn, endl, 2) != 2 ||
255 endl[0] != '\r' || endl[1] != '\n')
268 http_readfn(void *v, char *buf, int len)
270 struct httpio *io = (struct httpio *)v;
278 for (pos = 0; len > 0; pos += l, len -= l) {
280 if (!io->buf || io->bufpos == io->buflen)
281 if (http_fillbuf(io, len) < 1)
283 l = io->buflen - io->bufpos;
286 memcpy(buf + pos, io->buf + io->bufpos, l);
290 if (!pos && io->error) {
291 if (io->error == EINTR)
302 http_writefn(void *v, const char *buf, int len)
304 struct httpio *io = (struct httpio *)v;
306 return (fetch_write(io->conn, buf, len));
313 http_closefn(void *v)
315 struct httpio *io = (struct httpio *)v;
318 r = fetch_close(io->conn);
326 * Wrap a file descriptor up
329 http_funopen(conn_t *conn, int chunked)
334 if ((io = calloc(1, sizeof(*io))) == NULL) {
339 io->chunked = chunked;
340 f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
350 /*****************************************************************************
351 * Helper functions for talking to the server and parsing its replies
364 hdr_transfer_encoding,
365 hdr_www_authenticate,
366 hdr_proxy_authenticate,
369 /* Names of interesting headers */
374 { hdr_content_length, "Content-Length" },
375 { hdr_content_range, "Content-Range" },
376 { hdr_last_modified, "Last-Modified" },
377 { hdr_location, "Location" },
378 { hdr_transfer_encoding, "Transfer-Encoding" },
379 { hdr_www_authenticate, "WWW-Authenticate" },
380 { hdr_proxy_authenticate, "Proxy-Authenticate" },
381 { hdr_unknown, NULL },
385 * Send a formatted line; optionally echo to terminal
388 http_cmd(conn_t *conn, const char *fmt, ...)
396 len = vasprintf(&msg, fmt, ap);
405 r = fetch_putln(conn, msg, len);
417 * Get and parse status line
420 http_get_reply(conn_t *conn)
424 if (fetch_getln(conn) == -1)
427 * A valid status line looks like "HTTP/m.n xyz reason" where m
428 * and n are the major and minor protocol version numbers and xyz
430 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
431 * just one) that do not send a version number, so we can't rely
432 * on finding one, but if we do, insist on it being 1.0 or 1.1.
433 * We don't care about the reason phrase.
435 if (strncmp(conn->buf, "HTTP", 4) != 0)
436 return (HTTP_PROTOCOL_ERROR);
439 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
440 return (HTTP_PROTOCOL_ERROR);
444 !isdigit((unsigned char)p[1]) ||
445 !isdigit((unsigned char)p[2]) ||
446 !isdigit((unsigned char)p[3]))
447 return (HTTP_PROTOCOL_ERROR);
449 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
454 * Check a header; if the type matches the given string, return a pointer
455 * to the beginning of the value.
458 http_match(const char *str, const char *hdr)
460 while (*str && *hdr &&
461 tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
463 if (*str || *hdr != ':')
465 while (*hdr && isspace((unsigned char)*++hdr))
472 * Get the next header and return the appropriate symbolic code. We
473 * need to read one line ahead for checking for a continuation line
474 * belonging to the current header (continuation lines start with
477 * We get called with a fresh line already in the conn buffer, either
478 * from the previous http_next_header() invocation, or, the first
479 * time, from a fetch_getln() performed by our caller.
481 * This stops when we encounter an empty line (we dont read beyond the header
484 * Note that the "headerbuf" is just a place to return the result. Its
485 * contents are not used for the next call. This means that no cleanup
486 * is needed when ie doing another connection, just call the cleanup when
487 * fully done to deallocate memory.
490 /* Limit the max number of continuation lines to some reasonable value */
491 #define HTTP_MAX_CONT_LINES 10
493 /* Place into which to build a header from one or several lines */
495 char *buf; /* buffer */
496 size_t bufsize; /* buffer size */
497 size_t buflen; /* length of buffer contents */
501 init_http_headerbuf(http_headerbuf_t *buf)
509 clean_http_headerbuf(http_headerbuf_t *buf)
513 init_http_headerbuf(buf);
516 /* Remove whitespace at the end of the buffer */
518 http_conn_trimright(conn_t *conn)
520 while (conn->buflen &&
521 isspace((unsigned char)conn->buf[conn->buflen - 1]))
523 conn->buf[conn->buflen] = '\0';
527 http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
532 * Have to do the stripping here because of the first line. So
533 * it's done twice for the subsequent lines. No big deal
535 http_conn_trimright(conn);
536 if (conn->buflen == 0)
539 /* Copy the line to the headerbuf */
540 if (hbuf->bufsize < conn->buflen + 1) {
541 if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
542 return (hdr_syserror);
543 hbuf->bufsize = conn->buflen + 1;
545 strcpy(hbuf->buf, conn->buf);
546 hbuf->buflen = conn->buflen;
549 * Fetch possible continuation lines. Stop at 1st non-continuation
550 * and leave it in the conn buffer
552 for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
553 if (fetch_getln(conn) == -1)
554 return (hdr_syserror);
557 * Note: we carry on the idea from the previous version
558 * that a pure whitespace line is equivalent to an empty
559 * one (so it's not continuation and will be handled when
560 * we are called next)
562 http_conn_trimright(conn);
563 if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
566 /* Got a continuation line. Concatenate to previous */
567 len = hbuf->buflen + conn->buflen;
568 if (hbuf->bufsize < len + 1) {
570 if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
571 return (hdr_syserror);
572 hbuf->bufsize = len + 1;
574 strcpy(hbuf->buf + hbuf->buflen, conn->buf);
575 hbuf->buflen += conn->buflen;
579 * We could check for malformed headers but we don't really care.
580 * A valid header starts with a token immediately followed by a
581 * colon; a token is any sequence of non-control, non-whitespace
582 * characters except "()<>@,;:\\\"{}".
584 for (i = 0; hdr_names[i].num != hdr_unknown; i++)
585 if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
586 return (hdr_names[i].num);
588 return (hdr_unknown);
591 /**************************
592 * [Proxy-]Authenticate header parsing
596 * Read doublequote-delimited string into output buffer obuf (allocated
597 * by caller, whose responsibility it is to ensure that it's big enough)
598 * cp points to the first char after the initial '"'
600 * Returns pointer to the first char after the terminating double quote, or
604 http_parse_headerstring(const char *cp, char *obuf)
608 case 0: /* Unterminated string */
611 case '"': /* Ending quote */
626 /* Http auth challenge schemes */
627 typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
629 /* Data holder for a Basic or Digest challenge. */
631 http_auth_schemes_t scheme;
638 int nc; /* Nonce count */
639 } http_auth_challenge_t;
642 init_http_auth_challenge(http_auth_challenge_t *b)
644 b->scheme = HTTPAS_UNKNOWN;
645 b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
646 b->stale = b->nc = 0;
650 clean_http_auth_challenge(http_auth_challenge_t *b)
662 init_http_auth_challenge(b);
665 /* Data holder for an array of challenges offered in an http response. */
666 #define MAX_CHALLENGES 10
668 http_auth_challenge_t *challenges[MAX_CHALLENGES];
669 int count; /* Number of parsed challenges in the array */
670 int valid; /* We did parse an authenticate header */
671 } http_auth_challenges_t;
674 init_http_auth_challenges(http_auth_challenges_t *cs)
677 for (i = 0; i < MAX_CHALLENGES; i++)
678 cs->challenges[i] = NULL;
679 cs->count = cs->valid = 0;
683 clean_http_auth_challenges(http_auth_challenges_t *cs)
686 /* We rely on non-zero pointers being allocated, not on the count */
687 for (i = 0; i < MAX_CHALLENGES; i++) {
688 if (cs->challenges[i] != NULL) {
689 clean_http_auth_challenge(cs->challenges[i]);
690 free(cs->challenges[i]);
693 init_http_auth_challenges(cs);
697 * Enumeration for lexical elements. Separators will be returned as their own
700 typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
701 HTTPHL_ERROR = 259} http_header_lex_t;
704 * Determine what kind of token comes next and return possible value
705 * in buf, which is supposed to have been allocated big enough by
706 * caller. Advance input pointer and return element type.
709 http_header_lex(const char **cpp, char *buf)
712 /* Eat initial whitespace */
713 *cpp += strspn(*cpp, " \t");
718 if (**cpp == ',' || **cpp == '=')
719 return (*((*cpp)++));
723 *cpp = http_parse_headerstring(++*cpp, buf);
725 return (HTTPHL_ERROR);
726 return (HTTPHL_STRING);
729 /* Read other token, until separator or whitespace */
730 l = strcspn(*cpp, " \t,=");
731 memcpy(buf, *cpp, l);
734 return (HTTPHL_WORD);
738 * Read challenges from http xxx-authenticate header and accumulate them
739 * in the challenges list structure.
741 * Headers with multiple challenges are specified by rfc2617, but
742 * servers (ie: squid) often send them in separate headers instead,
743 * which in turn is forbidden by the http spec (multiple headers with
744 * the same name are only allowed for pure comma-separated lists, see
747 * We support both approaches anyway
750 http_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
753 http_header_lex_t lex;
754 char *key = malloc(strlen(cp) + 1);
755 char *value = malloc(strlen(cp) + 1);
756 char *buf = malloc(strlen(cp) + 1);
758 if (key == NULL || value == NULL || buf == NULL) {
763 /* In any case we've seen the header and we set the valid bit */
766 /* Need word first */
767 lex = http_header_lex(&cp, key);
768 if (lex != HTTPHL_WORD)
771 /* Loop on challenges */
772 for (; cs->count < MAX_CHALLENGES; cs->count++) {
773 cs->challenges[cs->count] =
774 malloc(sizeof(http_auth_challenge_t));
775 if (cs->challenges[cs->count] == NULL) {
779 init_http_auth_challenge(cs->challenges[cs->count]);
780 if (!strcasecmp(key, "basic")) {
781 cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
782 } else if (!strcasecmp(key, "digest")) {
783 cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
785 cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
787 * Continue parsing as basic or digest may
788 * follow, and the syntax is the same for
789 * all. We'll just ignore this one when
790 * looking at the list
794 /* Loop on attributes */
797 lex = http_header_lex(&cp, key);
798 if (lex != HTTPHL_WORD)
802 lex = http_header_lex(&cp, buf);
807 lex = http_header_lex(&cp, value);
808 if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
811 if (!strcasecmp(key, "realm"))
812 cs->challenges[cs->count]->realm =
814 else if (!strcasecmp(key, "qop"))
815 cs->challenges[cs->count]->qop =
817 else if (!strcasecmp(key, "nonce"))
818 cs->challenges[cs->count]->nonce =
820 else if (!strcasecmp(key, "opaque"))
821 cs->challenges[cs->count]->opaque =
823 else if (!strcasecmp(key, "algorithm"))
824 cs->challenges[cs->count]->algo =
826 else if (!strcasecmp(key, "stale"))
827 cs->challenges[cs->count]->stale =
828 strcasecmp(value, "no");
829 /* Else ignore unknown attributes */
831 /* Comma or Next challenge or End */
832 lex = http_header_lex(&cp, key);
834 * If we get a word here, this is the beginning of the
835 * next challenge. Break the attributes loop
837 if (lex == HTTPHL_WORD)
840 if (lex == HTTPHL_END) {
841 /* End while looking for ',' is normal exit */
846 /* Anything else is an error */
850 } /* End attributes loop */
851 } /* End challenge loop */
854 * Challenges max count exceeded. This really can't happen
855 * with normal data, something's fishy -> error
870 * Parse a last-modified header
873 http_parse_mtime(const char *p, time_t *mtime)
878 strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
879 setlocale(LC_TIME, "C");
880 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
881 /* XXX should add support for date-2 and date-3 */
882 setlocale(LC_TIME, locale);
885 DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
887 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
888 tm.tm_hour, tm.tm_min, tm.tm_sec));
889 *mtime = timegm(&tm);
894 * Parse a content-length header
897 http_parse_length(const char *p, off_t *length)
901 for (len = 0; *p && isdigit((unsigned char)*p); ++p)
902 len = len * 10 + (*p - '0');
905 DEBUG(fprintf(stderr, "content length: [%lld]\n",
912 * Parse a content-range header
915 http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
917 off_t first, last, len;
919 if (strncasecmp(p, "bytes ", 6) != 0)
926 for (first = 0; *p && isdigit((unsigned char)*p); ++p)
927 first = first * 10 + *p - '0';
930 for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
931 last = last * 10 + *p - '0';
933 if (first > last || *p != '/')
935 for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
936 len = len * 10 + *p - '0';
937 if (*p || len < last - first + 1)
940 DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
944 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
945 (long long)first, (long long)last, (long long)len));
946 *length = last - first + 1;
954 /*****************************************************************************
955 * Helper functions for authorization
962 http_base64(const char *src)
964 static const char base64[] =
965 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
966 "abcdefghijklmnopqrstuvwxyz"
973 if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
979 t = (src[0] << 16) | (src[1] << 8) | src[2];
980 dst[0] = base64[(t >> 18) & 0x3f];
981 dst[1] = base64[(t >> 12) & 0x3f];
982 dst[2] = base64[(t >> 6) & 0x3f];
983 dst[3] = base64[(t >> 0) & 0x3f];
990 t = (src[0] << 16) | (src[1] << 8);
991 dst[0] = base64[(t >> 18) & 0x3f];
992 dst[1] = base64[(t >> 12) & 0x3f];
993 dst[2] = base64[(t >> 6) & 0x3f];
1000 dst[0] = base64[(t >> 18) & 0x3f];
1001 dst[1] = base64[(t >> 12) & 0x3f];
1002 dst[2] = dst[3] = '=';
1016 * Extract authorization parameters from environment value.
1017 * The value is like scheme:realm:user:pass
1024 } http_auth_params_t;
1027 init_http_auth_params(http_auth_params_t *s)
1029 s->scheme = s->realm = s->user = s->password = 0;
1033 clean_http_auth_params(http_auth_params_t *s)
1043 init_http_auth_params(s);
1047 http_authfromenv(const char *p, http_auth_params_t *parms)
1051 char *str = strdup(p);
1059 if ((ve = strchr(v, ':')) == NULL)
1063 if ((parms->scheme = strdup(v)) == NULL) {
1069 if ((ve = strchr(v, ':')) == NULL)
1073 if ((parms->realm = strdup(v)) == NULL) {
1079 if ((ve = strchr(v, ':')) == NULL)
1083 if ((parms->user = strdup(v)) == NULL) {
1090 if ((parms->password = strdup(v)) == NULL) {
1097 clean_http_auth_params(parms);
1105 * Digest response: the code to compute the digest is taken from the
1106 * sample implementation in RFC2616
1112 typedef char HASH[HASHLEN];
1113 #define HASHHEXLEN 32
1114 typedef char HASHHEX[HASHHEXLEN+1];
1116 static const char *hexchars = "0123456789abcdef";
1118 CvtHex(IN HASH Bin, OUT HASHHEX Hex)
1123 for (i = 0; i < HASHLEN; i++) {
1124 j = (Bin[i] >> 4) & 0xf;
1125 Hex[i*2] = hexchars[j];
1127 Hex[i*2+1] = hexchars[j];
1129 Hex[HASHHEXLEN] = '\0';
1132 /* calculate H(A1) as per spec */
1136 IN char * pszUserName,
1138 IN char * pszPassword,
1140 IN char * pszCNonce,
1141 OUT HASHHEX SessionKey
1148 MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1149 MD5Update(&Md5Ctx, ":", 1);
1150 MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1151 MD5Update(&Md5Ctx, ":", 1);
1152 MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1153 MD5Final(HA1, &Md5Ctx);
1154 if (strcasecmp(pszAlg, "md5-sess") == 0) {
1157 MD5Update(&Md5Ctx, HA1, HASHLEN);
1158 MD5Update(&Md5Ctx, ":", 1);
1159 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1160 MD5Update(&Md5Ctx, ":", 1);
1161 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1162 MD5Final(HA1, &Md5Ctx);
1164 CvtHex(HA1, SessionKey);
1167 /* calculate request-digest/response-digest as per HTTP Digest spec */
1170 IN HASHHEX HA1, /* H(A1) */
1171 IN char * pszNonce, /* nonce from server */
1172 IN char * pszNonceCount, /* 8 hex digits */
1173 IN char * pszCNonce, /* client nonce */
1174 IN char * pszQop, /* qop-value: "", "auth", "auth-int" */
1175 IN char * pszMethod, /* method from the request */
1176 IN char * pszDigestUri, /* requested URL */
1177 IN HASHHEX HEntity, /* H(entity body) if qop="auth-int" */
1178 OUT HASHHEX Response /* request-digest or response-digest */
1181 /* DEBUG(fprintf(stderr,
1182 "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1183 HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1191 MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1192 MD5Update(&Md5Ctx, ":", 1);
1193 MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1194 if (strcasecmp(pszQop, "auth-int") == 0) {
1195 MD5Update(&Md5Ctx, ":", 1);
1196 MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1198 MD5Final(HA2, &Md5Ctx);
1199 CvtHex(HA2, HA2Hex);
1201 // calculate response
1203 MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1204 MD5Update(&Md5Ctx, ":", 1);
1205 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1206 MD5Update(&Md5Ctx, ":", 1);
1208 MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1209 MD5Update(&Md5Ctx, ":", 1);
1210 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1211 MD5Update(&Md5Ctx, ":", 1);
1212 MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1213 MD5Update(&Md5Ctx, ":", 1);
1215 MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1216 MD5Final(RespHash, &Md5Ctx);
1217 CvtHex(RespHash, Response);
1221 * Generate/Send a Digest authorization header
1222 * This looks like: [Proxy-]Authorization: credentials
1224 * credentials = "Digest" digest-response
1225 * digest-response = 1#( username | realm | nonce | digest-uri
1226 * | response | [ algorithm ] | [cnonce] |
1227 * [opaque] | [message-qop] |
1228 * [nonce-count] | [auth-param] )
1229 * username = "username" "=" username-value
1230 * username-value = quoted-string
1231 * digest-uri = "uri" "=" digest-uri-value
1232 * digest-uri-value = request-uri ; As specified by HTTP/1.1
1233 * message-qop = "qop" "=" qop-value
1234 * cnonce = "cnonce" "=" cnonce-value
1235 * cnonce-value = nonce-value
1236 * nonce-count = "nc" "=" nc-value
1238 * response = "response" "=" request-digest
1239 * request-digest = <"> 32LHEX <">
1242 http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1243 http_auth_params_t *parms, struct url *url)
1246 char noncecount[10];
1250 if (!c->realm || !c->nonce) {
1251 DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1255 c->algo = strdup("");
1257 if (asprintf(&options, "%s%s%s%s",
1258 *c->algo? ",algorithm=" : "", c->algo,
1259 c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1263 c->qop = strdup("");
1268 sprintf(noncecount, "%08x", c->nc);
1269 /* We don't try very hard with the cnonce ... */
1270 sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1274 DigestCalcHA1(c->algo, parms->user, c->realm,
1275 parms->password, c->nonce, cnonce, HA1);
1276 DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1278 DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1279 "GET", url->doc, "", digest);
1282 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1283 "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1284 "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1285 hdr, parms->user, c->realm,
1286 c->nonce, url->doc, digest,
1287 cnonce, noncecount, options);
1289 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1290 "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1291 hdr, parms->user, c->realm,
1292 c->nonce, url->doc, digest, options);
1300 * Encode username and password
1303 http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1308 DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1309 DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
1310 if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
1312 auth = http_base64(upw);
1316 r = http_cmd(conn, "%s: Basic %s", hdr, auth);
1322 * Chose the challenge to answer and call the appropriate routine to
1323 * produce the header.
1326 http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1327 http_auth_params_t *parms, struct url *url)
1329 http_auth_challenge_t *basic = NULL;
1330 http_auth_challenge_t *digest = NULL;
1333 /* If user or pass are null we're not happy */
1334 if (!parms->user || !parms->password) {
1335 DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1339 /* Look for a Digest and a Basic challenge */
1340 for (i = 0; i < cs->count; i++) {
1341 if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1342 basic = cs->challenges[i];
1343 if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1344 digest = cs->challenges[i];
1347 /* Error if "Digest" was specified and there is no Digest challenge */
1348 if (!digest && (parms->scheme &&
1349 !strcasecmp(parms->scheme, "digest"))) {
1350 DEBUG(fprintf(stderr,
1351 "Digest auth in env, not supported by peer\n"));
1355 * If "basic" was specified in the environment, or there is no Digest
1356 * challenge, do the basic thing. Don't need a challenge for this,
1357 * so no need to check basic!=NULL
1359 if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1360 return (http_basic_auth(conn,hdr,parms->user,parms->password));
1362 /* Else, prefer digest. We just checked that it's not NULL */
1363 return (http_digest_auth(conn, hdr, digest, parms, url));
1366 /*****************************************************************************
1367 * Helper functions for connecting to a server or proxy
1371 * Connect to the correct HTTP server or proxy.
1374 http_connect(struct url *URL, struct url *purl, const char *flags)
1386 verbose = CHECK_FLAG('v');
1387 if (CHECK_FLAG('4'))
1390 else if (CHECK_FLAG('6'))
1394 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
1396 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
1397 /* can't talk http to an ftp server */
1398 /* XXX should set an error code */
1402 if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1403 /* fetch_connect() has already set an error code */
1405 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1406 fetch_ssl(conn, verbose) == -1) {
1415 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1421 http_get_proxy(struct url * url, const char *flags)
1426 if (flags != NULL && strchr(flags, 'd') != NULL)
1428 if (fetch_no_proxy_match(url->host))
1430 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1431 *p && (purl = fetchParseURL(p))) {
1433 strcpy(purl->scheme, SCHEME_HTTP);
1435 purl->port = fetch_default_proxy_port(purl->scheme);
1436 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1444 http_print_html(FILE *out, FILE *in)
1451 while ((line = fgetln(in, &len)) != NULL) {
1452 while (len && isspace((unsigned char)line[len - 1]))
1454 for (p = q = line; q < line + len; ++q) {
1455 if (comment && *q == '-') {
1456 if (q + 2 < line + len &&
1457 strcmp(q, "-->") == 0) {
1461 } else if (tag && !comment && *q == '>') {
1464 } else if (!tag && *q == '<') {
1466 fwrite(p, q - p, 1, out);
1468 if (q + 3 < line + len &&
1469 strcmp(q, "<!--") == 0) {
1476 fwrite(p, q - p, 1, out);
1482 /*****************************************************************************
1487 * Send a request and process the reply
1489 * XXX This function is way too long, the do..while loop should be split
1490 * XXX off into a separate function.
1493 http_request(struct url *URL, const char *op, struct url_stat *us,
1494 struct url *purl, const char *flags)
1497 char hbuf[MAXHOSTNAMELEN + 7], *host;
1499 struct url *url, *new;
1500 int chunked, direct, ims, noredirect, verbose;
1502 off_t offset, clength, length, size;
1507 struct tm *timestruct;
1508 http_headerbuf_t headerbuf;
1509 http_auth_challenges_t server_challenges;
1510 http_auth_challenges_t proxy_challenges;
1512 /* The following calls don't allocate anything */
1513 init_http_headerbuf(&headerbuf);
1514 init_http_auth_challenges(&server_challenges);
1515 init_http_auth_challenges(&proxy_challenges);
1517 direct = CHECK_FLAG('d');
1518 noredirect = CHECK_FLAG('A');
1519 verbose = CHECK_FLAG('v');
1520 ims = CHECK_FLAG('i');
1522 if (direct && purl) {
1527 /* try the provided URL first */
1533 e = HTTP_PROTOCOL_ERROR;
1545 url->port = fetch_default_port(url->scheme);
1547 /* were we redirected to an FTP URL? */
1548 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1549 if (strcmp(op, "GET") == 0)
1550 return (ftp_request(url, "RETR", us, purl, flags));
1551 else if (strcmp(op, "HEAD") == 0)
1552 return (ftp_request(url, "STAT", us, purl, flags));
1555 /* connect to server or proxy */
1556 if ((conn = http_connect(url, purl, flags)) == NULL)
1561 if (strchr(url->host, ':')) {
1562 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
1566 if (url->port != fetch_default_port(url->scheme)) {
1571 snprintf(hbuf + strlen(hbuf),
1572 sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1577 fetch_info("requesting %s://%s%s",
1578 url->scheme, host, url->doc);
1580 http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1581 op, url->scheme, host, url->doc);
1583 http_cmd(conn, "%s %s HTTP/1.1",
1587 if (ims && url->ims_time) {
1588 timestruct = gmtime((time_t *)&url->ims_time);
1589 (void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1592 fetch_info("If-Modified-Since: %s", timebuf);
1593 http_cmd(conn, "If-Modified-Since: %s", timebuf);
1596 http_cmd(conn, "Host: %s", host);
1599 * Proxy authorization: we only send auth after we received
1600 * a 407 error. We do not first try basic anyway (changed
1601 * when support was added for digest-auth)
1603 if (purl && proxy_challenges.valid) {
1604 http_auth_params_t aparams;
1605 init_http_auth_params(&aparams);
1606 if (*purl->user || *purl->pwd) {
1607 aparams.user = purl->user ?
1608 strdup(purl->user) : strdup("");
1609 aparams.password = purl->pwd?
1610 strdup(purl->pwd) : strdup("");
1611 } else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1613 if (http_authfromenv(p, &aparams) < 0) {
1614 http_seterr(HTTP_NEED_PROXY_AUTH);
1618 http_authorize(conn, "Proxy-Authorization",
1619 &proxy_challenges, &aparams, url);
1620 clean_http_auth_params(&aparams);
1624 * Server authorization: we never send "a priori"
1625 * Basic auth, which used to be done if user/pass were
1626 * set in the url. This would be weird because we'd send the
1627 * password in the clear even if Digest is finally to be
1628 * used (it would have made more sense for the
1629 * pre-digest version to do this when Basic was specified
1630 * in the environment)
1632 if (server_challenges.valid) {
1633 http_auth_params_t aparams;
1634 init_http_auth_params(&aparams);
1635 if (*url->user || *url->pwd) {
1636 aparams.user = url->user ?
1637 strdup(url->user) : strdup("");
1638 aparams.password = url->pwd ?
1639 strdup(url->pwd) : strdup("");
1640 } else if ((p = getenv("HTTP_AUTH")) != NULL &&
1642 if (http_authfromenv(p, &aparams) < 0) {
1643 http_seterr(HTTP_NEED_AUTH);
1646 } else if (fetchAuthMethod &&
1647 fetchAuthMethod(url) == 0) {
1648 aparams.user = url->user ?
1649 strdup(url->user) : strdup("");
1650 aparams.password = url->pwd ?
1651 strdup(url->pwd) : strdup("");
1653 http_seterr(HTTP_NEED_AUTH);
1656 http_authorize(conn, "Authorization",
1657 &server_challenges, &aparams, url);
1658 clean_http_auth_params(&aparams);
1662 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1663 if (strcasecmp(p, "auto") == 0)
1664 http_cmd(conn, "Referer: %s://%s%s",
1665 url->scheme, host, url->doc);
1667 http_cmd(conn, "Referer: %s", p);
1669 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1670 http_cmd(conn, "User-Agent: %s", p);
1672 http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1673 if (url->offset > 0)
1674 http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1675 http_cmd(conn, "Connection: close");
1679 * Force the queued request to be dispatched. Normally, one
1680 * would do this with shutdown(2) but squid proxies can be
1681 * configured to disallow such half-closed connections. To
1682 * be compatible with such configurations, fiddle with socket
1683 * options to force the pending data to be written.
1686 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1689 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1693 switch (http_get_reply(conn)) {
1696 case HTTP_NOT_MODIFIED:
1699 case HTTP_MOVED_PERM:
1700 case HTTP_MOVED_TEMP:
1701 case HTTP_SEE_OTHER:
1702 case HTTP_USE_PROXY:
1704 * Not so fine, but we still have to read the
1705 * headers to get the new location.
1708 case HTTP_NEED_AUTH:
1709 if (server_challenges.valid) {
1711 * We already sent out authorization code,
1712 * so there's nothing more we can do.
1714 http_seterr(conn->err);
1717 /* try again, but send the password this time */
1719 fetch_info("server requires authorization");
1721 case HTTP_NEED_PROXY_AUTH:
1722 if (proxy_challenges.valid) {
1724 * We already sent our proxy
1725 * authorization code, so there's
1726 * nothing more we can do. */
1727 http_seterr(conn->err);
1730 /* try again, but send the password this time */
1732 fetch_info("proxy requires authorization");
1734 case HTTP_BAD_RANGE:
1736 * This can happen if we ask for 0 bytes because
1737 * we already have the whole file. Consider this
1738 * a success for now, and check sizes later.
1741 case HTTP_PROTOCOL_ERROR:
1747 http_seterr(conn->err);
1750 /* fall through so we can get the full error message */
1753 /* get headers. http_next_header expects one line readahead */
1754 if (fetch_getln(conn) == -1) {
1759 switch ((h = http_next_header(conn, &headerbuf, &p))) {
1764 http_seterr(HTTP_PROTOCOL_ERROR);
1766 case hdr_content_length:
1767 http_parse_length(p, &clength);
1769 case hdr_content_range:
1770 http_parse_range(p, &offset, &length, &size);
1772 case hdr_last_modified:
1773 http_parse_mtime(p, &mtime);
1776 if (!HTTP_REDIRECT(conn->err))
1779 * if the A flag is set, we don't follow
1780 * temporary redirects.
1783 conn->err != HTTP_MOVED_PERM &&
1784 conn->err != HTTP_PERM_REDIRECT &&
1785 conn->err != HTTP_USE_PROXY) {
1792 fetch_info("%d redirect to %s", conn->err, p);
1795 new = fetchMakeURL(url->scheme, url->host, url->port, p,
1796 url->user, url->pwd);
1798 new = fetchParseURL(p);
1800 /* XXX should set an error code */
1801 DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1805 /* Only copy credentials if the host matches */
1806 if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) {
1807 strcpy(new->user, url->user);
1808 strcpy(new->pwd, url->pwd);
1810 new->offset = url->offset;
1811 new->length = url->length;
1813 case hdr_transfer_encoding:
1815 chunked = (strcasecmp(p, "chunked") == 0);
1817 case hdr_www_authenticate:
1818 if (conn->err != HTTP_NEED_AUTH)
1820 if (http_parse_authenticate(p, &server_challenges) == 0)
1823 case hdr_proxy_authenticate:
1824 if (conn->err != HTTP_NEED_PROXY_AUTH)
1826 if (http_parse_authenticate(p, &proxy_challenges) == 0)
1835 } while (h > hdr_end);
1837 /* we need to provide authentication */
1838 if (conn->err == HTTP_NEED_AUTH ||
1839 conn->err == HTTP_NEED_PROXY_AUTH) {
1841 if ((conn->err == HTTP_NEED_AUTH &&
1842 !server_challenges.valid) ||
1843 (conn->err == HTTP_NEED_PROXY_AUTH &&
1844 !proxy_challenges.valid)) {
1845 /* 401/7 but no www/proxy-authenticate ?? */
1846 DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1854 /* requested range not satisfiable */
1855 if (conn->err == HTTP_BAD_RANGE) {
1856 if (url->offset == size && url->length == 0) {
1857 /* asked for 0 bytes; fake it */
1858 offset = url->offset;
1860 conn->err = HTTP_OK;
1863 http_seterr(conn->err);
1868 /* we have a hit or an error */
1869 if (conn->err == HTTP_OK
1870 || conn->err == HTTP_NOT_MODIFIED
1871 || conn->err == HTTP_PARTIAL
1872 || HTTP_ERROR(conn->err))
1875 /* all other cases: we got a redirect */
1877 clean_http_auth_challenges(&server_challenges);
1881 DEBUG(fprintf(stderr, "redirect with no new location\n"));
1889 /* we failed, or ran out of retries */
1895 DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1896 " size %lld, clength %lld\n",
1897 (long long)offset, (long long)length,
1898 (long long)size, (long long)clength));
1900 if (conn->err == HTTP_NOT_MODIFIED) {
1901 http_seterr(HTTP_NOT_MODIFIED);
1905 /* check for inconsistencies */
1906 if (clength != -1 && length != -1 && clength != length) {
1907 http_seterr(HTTP_PROTOCOL_ERROR);
1913 length = offset + clength;
1914 if (length != -1 && size != -1 && length != size) {
1915 http_seterr(HTTP_PROTOCOL_ERROR);
1924 us->atime = us->mtime = mtime;
1928 if (URL->offset > 0 && offset > URL->offset) {
1929 http_seterr(HTTP_PROTOCOL_ERROR);
1933 /* report back real offset and size */
1934 URL->offset = offset;
1935 URL->length = clength;
1937 /* wrap it up in a FILE */
1938 if ((f = http_funopen(conn, chunked)) == NULL) {
1948 if (HTTP_ERROR(conn->err)) {
1949 http_print_html(stderr, f);
1953 clean_http_headerbuf(&headerbuf);
1954 clean_http_auth_challenges(&server_challenges);
1955 clean_http_auth_challenges(&proxy_challenges);
1965 clean_http_headerbuf(&headerbuf);
1966 clean_http_auth_challenges(&server_challenges);
1967 clean_http_auth_challenges(&proxy_challenges);
1972 /*****************************************************************************
1977 * Retrieve and stat a file by HTTP
1980 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1982 return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1986 * Retrieve a file by HTTP
1989 fetchGetHTTP(struct url *URL, const char *flags)
1991 return (fetchXGetHTTP(URL, NULL, flags));
1995 * Store a file by HTTP
1998 fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
2000 warnx("fetchPutHTTP(): not implemented");
2005 * Get an HTTP document's metadata
2008 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
2012 f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2023 fetchListHTTP(struct url *url __unused, const char *flags __unused)
2025 warnx("fetchListHTTP(): not implemented");