2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2000-2014 Dag-Erling Smørgrav
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
35 * The following copyright applies to the base64 code:
38 * Copyright 1997 Massachusetts Institute of Technology
40 * Permission to use, copy, modify, and distribute this software and
41 * its documentation for any purpose and without fee is hereby
42 * granted, provided that both the above copyright notice and this
43 * permission notice appear in all copies, that both the above
44 * copyright notice and this permission notice appear in all
45 * supporting documentation, and that the name of M.I.T. not be used
46 * in advertising or publicity pertaining to distribution of the
47 * software without specific, written prior permission. M.I.T. makes
48 * no representations about the suitability of this software for any
49 * purpose. It is provided "as is" without express or implied
52 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
53 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
54 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
55 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
56 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
58 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
59 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
60 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
61 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
62 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 #include <sys/param.h>
67 #include <sys/socket.h>
84 #include <openssl/md5.h>
85 #define MD5Init(c) MD5_Init(c)
86 #define MD5Update(c, data, len) MD5_Update(c, data, len)
87 #define MD5Final(md, c) MD5_Final(md, c)
92 #include <netinet/in.h>
93 #include <netinet/tcp.h>
99 /* Maximum number of redirects to follow */
100 #define MAX_REDIRECT 20
102 /* Symbolic names for reply codes we care about */
104 #define HTTP_PARTIAL 206
105 #define HTTP_MOVED_PERM 301
106 #define HTTP_MOVED_TEMP 302
107 #define HTTP_SEE_OTHER 303
108 #define HTTP_NOT_MODIFIED 304
109 #define HTTP_USE_PROXY 305
110 #define HTTP_TEMP_REDIRECT 307
111 #define HTTP_PERM_REDIRECT 308
112 #define HTTP_NEED_AUTH 401
113 #define HTTP_NEED_PROXY_AUTH 407
114 #define HTTP_BAD_RANGE 416
115 #define HTTP_PROTOCOL_ERROR 999
117 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
118 || (xyz) == HTTP_MOVED_TEMP \
119 || (xyz) == HTTP_TEMP_REDIRECT \
120 || (xyz) == HTTP_PERM_REDIRECT \
121 || (xyz) == HTTP_USE_PROXY \
122 || (xyz) == HTTP_SEE_OTHER)
124 #define HTTP_ERROR(xyz) ((xyz) >= 400 && (xyz) <= 599)
127 /*****************************************************************************
128 * I/O functions for decoding chunked streams
133 conn_t *conn; /* connection */
134 int chunked; /* chunked mode */
135 char *buf; /* chunk buffer */
136 size_t bufsize; /* size of chunk buffer */
137 size_t buflen; /* amount of data currently in buffer */
138 size_t bufpos; /* current read offset in buffer */
139 int eof; /* end-of-file flag */
140 int error; /* error flag */
141 size_t chunksize; /* remaining size of current chunk */
148 * Get next chunk header
151 http_new_chunk(struct httpio *io)
155 if (fetch_getln(io->conn) == -1)
158 if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
161 for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
164 if (!isxdigit((unsigned char)*p))
166 if (isdigit((unsigned char)*p)) {
167 io->chunksize = io->chunksize * 16 +
170 io->chunksize = io->chunksize * 16 +
171 10 + tolower((unsigned char)*p) - 'a';
177 io->total += io->chunksize;
178 if (io->chunksize == 0)
179 fprintf(stderr, "%s(): end of last chunk\n", __func__);
181 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
182 __func__, (unsigned long)io->chunksize,
183 (unsigned long)io->total);
187 return (io->chunksize);
191 * Grow the input buffer to at least len bytes
194 http_growbuf(struct httpio *io, size_t len)
198 if (io->bufsize >= len)
201 if ((tmp = realloc(io->buf, len)) == NULL)
209 * Fill the input buffer, do chunk decoding on the fly
212 http_fillbuf(struct httpio *io, size_t len)
222 /* not chunked: just fetch the requested amount */
223 if (io->chunked == 0) {
224 if (http_growbuf(io, len) == -1)
226 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
235 /* chunked, but we ran out: get the next chunk header */
236 if (io->chunksize == 0) {
237 switch (http_new_chunk(io)) {
247 /* fetch the requested amount, but no more than the current chunk */
248 if (len > io->chunksize)
250 if (http_growbuf(io, len) == -1)
252 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
258 io->chunksize -= nbytes;
260 if (io->chunksize == 0) {
261 if (fetch_read(io->conn, &ch, 1) != 1 || ch != '\r' ||
262 fetch_read(io->conn, &ch, 1) != 1 || ch != '\n')
273 http_readfn(void *v, char *buf, int len)
275 struct httpio *io = (struct httpio *)v;
284 if (!io->buf || io->bufpos == io->buflen) {
285 if ((rlen = http_fillbuf(io, len)) < 0) {
286 if ((errno = io->error) == EINTR)
289 } else if (rlen == 0) {
294 rlen = io->buflen - io->bufpos;
297 memcpy(buf, io->buf + io->bufpos, rlen);
306 http_writefn(void *v, const char *buf, int len)
308 struct httpio *io = (struct httpio *)v;
310 return (fetch_write(io->conn, buf, len));
317 http_closefn(void *v)
319 struct httpio *io = (struct httpio *)v;
322 r = fetch_close(io->conn);
330 * Wrap a file descriptor up
333 http_funopen(conn_t *conn, int chunked)
338 if ((io = calloc(1, sizeof(*io))) == NULL) {
343 io->chunked = chunked;
344 f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
354 /*****************************************************************************
355 * Helper functions for talking to the server and parsing its replies
368 hdr_transfer_encoding,
369 hdr_www_authenticate,
370 hdr_proxy_authenticate,
373 /* Names of interesting headers */
378 { hdr_content_length, "Content-Length" },
379 { hdr_content_range, "Content-Range" },
380 { hdr_last_modified, "Last-Modified" },
381 { hdr_location, "Location" },
382 { hdr_transfer_encoding, "Transfer-Encoding" },
383 { hdr_www_authenticate, "WWW-Authenticate" },
384 { hdr_proxy_authenticate, "Proxy-Authenticate" },
385 { hdr_unknown, NULL },
389 * Send a formatted line; optionally echo to terminal
392 http_cmd(conn_t *conn, const char *fmt, ...)
400 len = vasprintf(&msg, fmt, ap);
409 r = fetch_putln(conn, msg, len);
421 * Get and parse status line
424 http_get_reply(conn_t *conn)
428 if (fetch_getln(conn) == -1)
431 * A valid status line looks like "HTTP/m.n xyz reason" where m
432 * and n are the major and minor protocol version numbers and xyz
434 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
435 * just one) that do not send a version number, so we can't rely
436 * on finding one, but if we do, insist on it being 1.0 or 1.1.
437 * We don't care about the reason phrase.
439 if (strncmp(conn->buf, "HTTP", 4) != 0)
440 return (HTTP_PROTOCOL_ERROR);
443 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
444 return (HTTP_PROTOCOL_ERROR);
448 !isdigit((unsigned char)p[1]) ||
449 !isdigit((unsigned char)p[2]) ||
450 !isdigit((unsigned char)p[3]))
451 return (HTTP_PROTOCOL_ERROR);
453 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
458 * Check a header; if the type matches the given string, return a pointer
459 * to the beginning of the value.
462 http_match(const char *str, const char *hdr)
464 while (*str && *hdr &&
465 tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
467 if (*str || *hdr != ':')
469 while (*hdr && isspace((unsigned char)*++hdr))
476 * Get the next header and return the appropriate symbolic code. We
477 * need to read one line ahead for checking for a continuation line
478 * belonging to the current header (continuation lines start with
481 * We get called with a fresh line already in the conn buffer, either
482 * from the previous http_next_header() invocation, or, the first
483 * time, from a fetch_getln() performed by our caller.
485 * This stops when we encounter an empty line (we dont read beyond the header
488 * Note that the "headerbuf" is just a place to return the result. Its
489 * contents are not used for the next call. This means that no cleanup
490 * is needed when ie doing another connection, just call the cleanup when
491 * fully done to deallocate memory.
494 /* Limit the max number of continuation lines to some reasonable value */
495 #define HTTP_MAX_CONT_LINES 10
497 /* Place into which to build a header from one or several lines */
499 char *buf; /* buffer */
500 size_t bufsize; /* buffer size */
501 size_t buflen; /* length of buffer contents */
505 init_http_headerbuf(http_headerbuf_t *buf)
513 clean_http_headerbuf(http_headerbuf_t *buf)
517 init_http_headerbuf(buf);
520 /* Remove whitespace at the end of the buffer */
522 http_conn_trimright(conn_t *conn)
524 while (conn->buflen &&
525 isspace((unsigned char)conn->buf[conn->buflen - 1]))
527 conn->buf[conn->buflen] = '\0';
531 http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
536 * Have to do the stripping here because of the first line. So
537 * it's done twice for the subsequent lines. No big deal
539 http_conn_trimright(conn);
540 if (conn->buflen == 0)
543 /* Copy the line to the headerbuf */
544 if (hbuf->bufsize < conn->buflen + 1) {
545 if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
546 return (hdr_syserror);
547 hbuf->bufsize = conn->buflen + 1;
549 strcpy(hbuf->buf, conn->buf);
550 hbuf->buflen = conn->buflen;
553 * Fetch possible continuation lines. Stop at 1st non-continuation
554 * and leave it in the conn buffer
556 for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
557 if (fetch_getln(conn) == -1)
558 return (hdr_syserror);
561 * Note: we carry on the idea from the previous version
562 * that a pure whitespace line is equivalent to an empty
563 * one (so it's not continuation and will be handled when
564 * we are called next)
566 http_conn_trimright(conn);
567 if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
570 /* Got a continuation line. Concatenate to previous */
571 len = hbuf->buflen + conn->buflen;
572 if (hbuf->bufsize < len + 1) {
574 if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
575 return (hdr_syserror);
576 hbuf->bufsize = len + 1;
578 strcpy(hbuf->buf + hbuf->buflen, conn->buf);
579 hbuf->buflen += conn->buflen;
583 * We could check for malformed headers but we don't really care.
584 * A valid header starts with a token immediately followed by a
585 * colon; a token is any sequence of non-control, non-whitespace
586 * characters except "()<>@,;:\\\"{}".
588 for (i = 0; hdr_names[i].num != hdr_unknown; i++)
589 if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
590 return (hdr_names[i].num);
592 return (hdr_unknown);
595 /**************************
596 * [Proxy-]Authenticate header parsing
600 * Read doublequote-delimited string into output buffer obuf (allocated
601 * by caller, whose responsibility it is to ensure that it's big enough)
602 * cp points to the first char after the initial '"'
604 * Returns pointer to the first char after the terminating double quote, or
608 http_parse_headerstring(const char *cp, char *obuf)
612 case 0: /* Unterminated string */
615 case '"': /* Ending quote */
630 /* Http auth challenge schemes */
631 typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
633 /* Data holder for a Basic or Digest challenge. */
635 http_auth_schemes_t scheme;
642 int nc; /* Nonce count */
643 } http_auth_challenge_t;
646 init_http_auth_challenge(http_auth_challenge_t *b)
648 b->scheme = HTTPAS_UNKNOWN;
649 b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
650 b->stale = b->nc = 0;
654 clean_http_auth_challenge(http_auth_challenge_t *b)
666 init_http_auth_challenge(b);
669 /* Data holder for an array of challenges offered in an http response. */
670 #define MAX_CHALLENGES 10
672 http_auth_challenge_t *challenges[MAX_CHALLENGES];
673 int count; /* Number of parsed challenges in the array */
674 int valid; /* We did parse an authenticate header */
675 } http_auth_challenges_t;
678 init_http_auth_challenges(http_auth_challenges_t *cs)
681 for (i = 0; i < MAX_CHALLENGES; i++)
682 cs->challenges[i] = NULL;
683 cs->count = cs->valid = 0;
687 clean_http_auth_challenges(http_auth_challenges_t *cs)
690 /* We rely on non-zero pointers being allocated, not on the count */
691 for (i = 0; i < MAX_CHALLENGES; i++) {
692 if (cs->challenges[i] != NULL) {
693 clean_http_auth_challenge(cs->challenges[i]);
694 free(cs->challenges[i]);
697 init_http_auth_challenges(cs);
701 * Enumeration for lexical elements. Separators will be returned as their own
704 typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
705 HTTPHL_ERROR = 259} http_header_lex_t;
708 * Determine what kind of token comes next and return possible value
709 * in buf, which is supposed to have been allocated big enough by
710 * caller. Advance input pointer and return element type.
713 http_header_lex(const char **cpp, char *buf)
716 /* Eat initial whitespace */
717 *cpp += strspn(*cpp, " \t");
722 if (**cpp == ',' || **cpp == '=')
723 return (*((*cpp)++));
727 *cpp = http_parse_headerstring(++*cpp, buf);
729 return (HTTPHL_ERROR);
730 return (HTTPHL_STRING);
733 /* Read other token, until separator or whitespace */
734 l = strcspn(*cpp, " \t,=");
735 memcpy(buf, *cpp, l);
738 return (HTTPHL_WORD);
742 * Read challenges from http xxx-authenticate header and accumulate them
743 * in the challenges list structure.
745 * Headers with multiple challenges are specified by rfc2617, but
746 * servers (ie: squid) often send them in separate headers instead,
747 * which in turn is forbidden by the http spec (multiple headers with
748 * the same name are only allowed for pure comma-separated lists, see
751 * We support both approaches anyway
754 http_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
757 http_header_lex_t lex;
758 char *key = malloc(strlen(cp) + 1);
759 char *value = malloc(strlen(cp) + 1);
760 char *buf = malloc(strlen(cp) + 1);
762 if (key == NULL || value == NULL || buf == NULL) {
767 /* In any case we've seen the header and we set the valid bit */
770 /* Need word first */
771 lex = http_header_lex(&cp, key);
772 if (lex != HTTPHL_WORD)
775 /* Loop on challenges */
776 for (; cs->count < MAX_CHALLENGES; cs->count++) {
777 cs->challenges[cs->count] =
778 malloc(sizeof(http_auth_challenge_t));
779 if (cs->challenges[cs->count] == NULL) {
783 init_http_auth_challenge(cs->challenges[cs->count]);
784 if (strcasecmp(key, "basic") == 0) {
785 cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
786 } else if (strcasecmp(key, "digest") == 0) {
787 cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
789 cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
791 * Continue parsing as basic or digest may
792 * follow, and the syntax is the same for
793 * all. We'll just ignore this one when
794 * looking at the list
798 /* Loop on attributes */
801 lex = http_header_lex(&cp, key);
802 if (lex != HTTPHL_WORD)
806 lex = http_header_lex(&cp, buf);
811 lex = http_header_lex(&cp, value);
812 if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
815 if (strcasecmp(key, "realm") == 0) {
816 cs->challenges[cs->count]->realm =
818 } else if (strcasecmp(key, "qop") == 0) {
819 cs->challenges[cs->count]->qop =
821 } else if (strcasecmp(key, "nonce") == 0) {
822 cs->challenges[cs->count]->nonce =
824 } else if (strcasecmp(key, "opaque") == 0) {
825 cs->challenges[cs->count]->opaque =
827 } else if (strcasecmp(key, "algorithm") == 0) {
828 cs->challenges[cs->count]->algo =
830 } else if (strcasecmp(key, "stale") == 0) {
831 cs->challenges[cs->count]->stale =
832 strcasecmp(value, "no");
834 /* ignore unknown attributes */
837 /* Comma or Next challenge or End */
838 lex = http_header_lex(&cp, key);
840 * If we get a word here, this is the beginning of the
841 * next challenge. Break the attributes loop
843 if (lex == HTTPHL_WORD)
846 if (lex == HTTPHL_END) {
847 /* End while looking for ',' is normal exit */
852 /* Anything else is an error */
856 } /* End attributes loop */
857 } /* End challenge loop */
860 * Challenges max count exceeded. This really can't happen
861 * with normal data, something's fishy -> error
876 * Parse a last-modified header
879 http_parse_mtime(const char *p, time_t *mtime)
884 strlcpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
885 setlocale(LC_TIME, "C");
886 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
888 * Some proxies use UTC in response, but it should still be
889 * parsed. RFC2616 states GMT and UTC are exactly equal for HTTP.
892 r = strptime(p, "%a, %d %b %Y %H:%M:%S UTC", &tm);
893 /* XXX should add support for date-2 and date-3 */
894 setlocale(LC_TIME, locale);
897 DEBUGF("last modified: [%04d-%02d-%02d %02d:%02d:%02d]\n",
898 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
899 tm.tm_hour, tm.tm_min, tm.tm_sec);
900 *mtime = timegm(&tm);
905 * Parse a content-length header
908 http_parse_length(const char *p, off_t *length)
912 for (len = 0; *p && isdigit((unsigned char)*p); ++p)
913 len = len * 10 + (*p - '0');
916 DEBUGF("content length: [%lld]\n", (long long)len);
922 * Parse a content-range header
925 http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
927 off_t first, last, len;
929 if (strncasecmp(p, "bytes ", 6) != 0)
936 for (first = 0; *p && isdigit((unsigned char)*p); ++p)
937 first = first * 10 + *p - '0';
940 for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
941 last = last * 10 + *p - '0';
943 if (first > last || *p != '/')
945 for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
946 len = len * 10 + *p - '0';
947 if (*p || len < last - first + 1)
950 DEBUGF("content range: [*/%lld]\n", (long long)len);
953 DEBUGF("content range: [%lld-%lld/%lld]\n",
954 (long long)first, (long long)last, (long long)len);
955 *length = last - first + 1;
963 /*****************************************************************************
964 * Helper functions for authorization
971 http_base64(const char *src)
973 static const char base64[] =
974 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
975 "abcdefghijklmnopqrstuvwxyz"
982 if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
987 t = (src[0] << 16) | (src[1] << 8) | src[2];
988 dst[0] = base64[(t >> 18) & 0x3f];
989 dst[1] = base64[(t >> 12) & 0x3f];
990 dst[2] = base64[(t >> 6) & 0x3f];
991 dst[3] = base64[(t >> 0) & 0x3f];
998 t = (src[0] << 16) | (src[1] << 8);
999 dst[0] = base64[(t >> 18) & 0x3f];
1000 dst[1] = base64[(t >> 12) & 0x3f];
1001 dst[2] = base64[(t >> 6) & 0x3f];
1007 dst[0] = base64[(t >> 18) & 0x3f];
1008 dst[1] = base64[(t >> 12) & 0x3f];
1009 dst[2] = dst[3] = '=';
1022 * Extract authorization parameters from environment value.
1023 * The value is like scheme:realm:user:pass
1030 } http_auth_params_t;
1033 init_http_auth_params(http_auth_params_t *s)
1035 s->scheme = s->realm = s->user = s->password = NULL;
1039 clean_http_auth_params(http_auth_params_t *s)
1049 init_http_auth_params(s);
1053 http_authfromenv(const char *p, http_auth_params_t *parms)
1057 char *str = strdup(p);
1065 if ((ve = strchr(v, ':')) == NULL)
1069 if ((parms->scheme = strdup(v)) == NULL) {
1075 if ((ve = strchr(v, ':')) == NULL)
1079 if ((parms->realm = strdup(v)) == NULL) {
1085 if ((ve = strchr(v, ':')) == NULL)
1089 if ((parms->user = strdup(v)) == NULL) {
1096 if ((parms->password = strdup(v)) == NULL) {
1103 clean_http_auth_params(parms);
1111 * Digest response: the code to compute the digest is taken from the
1112 * sample implementation in RFC2616
1118 typedef char HASH[HASHLEN];
1119 #define HASHHEXLEN 32
1120 typedef char HASHHEX[HASHHEXLEN+1];
1122 static const char *hexchars = "0123456789abcdef";
1124 CvtHex(IN HASH Bin, OUT HASHHEX Hex)
1129 for (i = 0; i < HASHLEN; i++) {
1130 j = (Bin[i] >> 4) & 0xf;
1131 Hex[i*2] = hexchars[j];
1133 Hex[i*2+1] = hexchars[j];
1135 Hex[HASHHEXLEN] = '\0';
1138 /* calculate H(A1) as per spec */
1142 IN char * pszUserName,
1144 IN char * pszPassword,
1146 IN char * pszCNonce,
1147 OUT HASHHEX SessionKey
1154 MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1155 MD5Update(&Md5Ctx, ":", 1);
1156 MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1157 MD5Update(&Md5Ctx, ":", 1);
1158 MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1159 MD5Final(HA1, &Md5Ctx);
1160 if (strcasecmp(pszAlg, "md5-sess") == 0) {
1163 MD5Update(&Md5Ctx, HA1, HASHLEN);
1164 MD5Update(&Md5Ctx, ":", 1);
1165 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1166 MD5Update(&Md5Ctx, ":", 1);
1167 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1168 MD5Final(HA1, &Md5Ctx);
1170 CvtHex(HA1, SessionKey);
1173 /* calculate request-digest/response-digest as per HTTP Digest spec */
1176 IN HASHHEX HA1, /* H(A1) */
1177 IN char * pszNonce, /* nonce from server */
1178 IN char * pszNonceCount, /* 8 hex digits */
1179 IN char * pszCNonce, /* client nonce */
1180 IN char * pszQop, /* qop-value: "", "auth", "auth-int" */
1181 IN char * pszMethod, /* method from the request */
1182 IN char * pszDigestUri, /* requested URL */
1183 IN HASHHEX HEntity, /* H(entity body) if qop="auth-int" */
1184 OUT HASHHEX Response /* request-digest or response-digest */
1188 DEBUGF("Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1189 HA1, pszNonce, pszQop, pszMethod, pszDigestUri);
1198 MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1199 MD5Update(&Md5Ctx, ":", 1);
1200 MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1201 if (strcasecmp(pszQop, "auth-int") == 0) {
1202 MD5Update(&Md5Ctx, ":", 1);
1203 MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1205 MD5Final(HA2, &Md5Ctx);
1206 CvtHex(HA2, HA2Hex);
1208 // calculate response
1210 MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1211 MD5Update(&Md5Ctx, ":", 1);
1212 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1213 MD5Update(&Md5Ctx, ":", 1);
1215 MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1216 MD5Update(&Md5Ctx, ":", 1);
1217 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1218 MD5Update(&Md5Ctx, ":", 1);
1219 MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1220 MD5Update(&Md5Ctx, ":", 1);
1222 MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1223 MD5Final(RespHash, &Md5Ctx);
1224 CvtHex(RespHash, Response);
1228 * Generate/Send a Digest authorization header
1229 * This looks like: [Proxy-]Authorization: credentials
1231 * credentials = "Digest" digest-response
1232 * digest-response = 1#( username | realm | nonce | digest-uri
1233 * | response | [ algorithm ] | [cnonce] |
1234 * [opaque] | [message-qop] |
1235 * [nonce-count] | [auth-param] )
1236 * username = "username" "=" username-value
1237 * username-value = quoted-string
1238 * digest-uri = "uri" "=" digest-uri-value
1239 * digest-uri-value = request-uri ; As specified by HTTP/1.1
1240 * message-qop = "qop" "=" qop-value
1241 * cnonce = "cnonce" "=" cnonce-value
1242 * cnonce-value = nonce-value
1243 * nonce-count = "nc" "=" nc-value
1245 * response = "response" "=" request-digest
1246 * request-digest = <"> 32LHEX <">
1249 http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1250 http_auth_params_t *parms, struct url *url)
1253 char noncecount[10];
1255 char *options = NULL;
1257 if (!c->realm || !c->nonce) {
1258 DEBUGF("realm/nonce not set in challenge\n");
1262 c->algo = strdup("");
1264 if (asprintf(&options, "%s%s%s%s",
1265 *c->algo? ",algorithm=" : "", c->algo,
1266 c->opaque? ",opaque=" : "", c->opaque?c->opaque:"") < 0)
1270 c->qop = strdup("");
1275 sprintf(noncecount, "%08x", c->nc);
1276 /* We don't try very hard with the cnonce ... */
1277 sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1281 DigestCalcHA1(c->algo, parms->user, c->realm,
1282 parms->password, c->nonce, cnonce, HA1);
1283 DEBUGF("HA1: [%s]\n", HA1);
1284 HASHHEX digest, null;
1285 memset(null, 0, sizeof(null));
1286 DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1287 "GET", url->doc, null, digest);
1290 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1291 "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1292 "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1293 hdr, parms->user, c->realm,
1294 c->nonce, url->doc, digest,
1295 cnonce, noncecount, options);
1297 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1298 "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1299 hdr, parms->user, c->realm,
1300 c->nonce, url->doc, digest, options);
1308 * Encode username and password
1311 http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1316 DEBUGF("basic: usr: [%s]\n", usr);
1317 DEBUGF("basic: pwd: [%s]\n", pwd);
1318 if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
1320 auth = http_base64(upw);
1324 r = http_cmd(conn, "%s: Basic %s", hdr, auth);
1330 * Chose the challenge to answer and call the appropriate routine to
1331 * produce the header.
1334 http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1335 http_auth_params_t *parms, struct url *url)
1337 http_auth_challenge_t *digest = NULL;
1340 /* If user or pass are null we're not happy */
1341 if (!parms->user || !parms->password) {
1342 DEBUGF("NULL usr or pass\n");
1346 /* Look for a Digest */
1347 for (i = 0; i < cs->count; i++) {
1348 if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1349 digest = cs->challenges[i];
1352 /* Error if "Digest" was specified and there is no Digest challenge */
1354 (parms->scheme && strcasecmp(parms->scheme, "digest") == 0)) {
1355 DEBUGF("Digest auth in env, not supported by peer\n");
1359 * If "basic" was specified in the environment, or there is no Digest
1360 * challenge, do the basic thing. Don't need a challenge for this,
1361 * so no need to check basic!=NULL
1364 (parms->scheme && strcasecmp(parms->scheme, "basic") == 0))
1365 return (http_basic_auth(conn,hdr,parms->user,parms->password));
1367 /* Else, prefer digest. We just checked that it's not NULL */
1368 return (http_digest_auth(conn, hdr, digest, parms, url));
1371 /*****************************************************************************
1372 * Helper functions for connecting to a server or proxy
1376 * Connect to the correct HTTP server or proxy.
1379 http_connect(struct url *URL, struct url *purl, const char *flags)
1384 http_headerbuf_t headerbuf;
1389 bool isproxyauth = false;
1390 http_auth_challenges_t proxy_challenges;
1398 verbose = CHECK_FLAG('v');
1399 if (CHECK_FLAG('4'))
1402 else if (CHECK_FLAG('6'))
1406 curl = (purl != NULL) ? purl : URL;
1409 if ((conn = fetch_connect(curl->host, curl->port, af, verbose)) == NULL)
1410 /* fetch_connect() has already set an error code */
1412 init_http_headerbuf(&headerbuf);
1413 if (strcmp(URL->scheme, SCHEME_HTTPS) == 0 && purl) {
1414 init_http_auth_challenges(&proxy_challenges);
1415 http_cmd(conn, "CONNECT %s:%d HTTP/1.1", URL->host, URL->port);
1416 http_cmd(conn, "Host: %s:%d", URL->host, URL->port);
1418 http_auth_params_t aparams;
1419 init_http_auth_params(&aparams);
1420 if (*purl->user || *purl->pwd) {
1421 aparams.user = strdup(purl->user);
1422 aparams.password = strdup(purl->pwd);
1423 } else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1425 if (http_authfromenv(p, &aparams) < 0) {
1426 http_seterr(HTTP_NEED_PROXY_AUTH);
1430 } else if (fetch_netrc_auth(purl) == 0) {
1431 aparams.user = strdup(purl->user);
1432 aparams.password = strdup(purl->pwd);
1435 * No auth information found in system - exiting
1438 warnx("Missing username and/or password set");
1442 http_authorize(conn, "Proxy-Authorization",
1443 &proxy_challenges, &aparams, purl);
1444 clean_http_auth_params(&aparams);
1447 /* Get reply from CONNECT Tunnel attempt */
1448 int httpreply = http_get_reply(conn);
1449 if (httpreply != HTTP_OK) {
1450 http_seterr(httpreply);
1451 /* If the error is a 407/HTTP_NEED_PROXY_AUTH */
1452 if (httpreply == HTTP_NEED_PROXY_AUTH &&
1454 /* Try again with authentication. */
1455 clean_http_headerbuf(&headerbuf);
1462 /* Read and discard the rest of the proxy response */
1463 if (fetch_getln(conn) < 0) {
1468 switch ((h = http_next_header(conn, &headerbuf, &p))) {
1473 http_seterr(HTTP_PROTOCOL_ERROR);
1478 } while (h > hdr_end);
1480 if (strcmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1481 fetch_ssl(conn, URL, verbose) == -1) {
1489 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1491 clean_http_headerbuf(&headerbuf);
1495 clean_http_headerbuf(&headerbuf);
1502 http_get_proxy(struct url * url, const char *flags)
1507 if (flags != NULL && strchr(flags, 'd') != NULL)
1509 if (fetch_no_proxy_match(url->host))
1511 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1512 *p && (purl = fetchParseURL(p))) {
1514 strcpy(purl->scheme, SCHEME_HTTP);
1516 purl->port = fetch_default_proxy_port(purl->scheme);
1517 if (strcmp(purl->scheme, SCHEME_HTTP) == 0)
1525 http_print_html(FILE *out, FILE *in)
1529 char *line = NULL, *p, *q;
1533 while ((len = getline(&line, &cap, in)) >= 0) {
1534 while (len && isspace((unsigned char)line[len - 1]))
1536 for (p = q = line; q < line + len; ++q) {
1537 if (comment && *q == '-') {
1538 if (q + 2 < line + len &&
1539 strcmp(q, "-->") == 0) {
1543 } else if (tag && !comment && *q == '>') {
1546 } else if (!tag && *q == '<') {
1548 fwrite(p, q - p, 1, out);
1550 if (q + 3 < line + len &&
1551 strcmp(q, "<!--") == 0) {
1558 fwrite(p, q - p, 1, out);
1566 /*****************************************************************************
1571 http_request(struct url *URL, const char *op, struct url_stat *us,
1572 struct url *purl, const char *flags)
1575 return (http_request_body(URL, op, us, purl, flags, NULL, NULL));
1579 * Send a request and process the reply
1581 * XXX This function is way too long, the do..while loop should be split
1582 * XXX off into a separate function.
1585 http_request_body(struct url *URL, const char *op, struct url_stat *us,
1586 struct url *purl, const char *flags, const char *content_type,
1590 char hbuf[MAXHOSTNAMELEN + 7], *host;
1592 struct url *url, *new;
1593 int chunked, direct, ims, noredirect, verbose;
1595 off_t offset, clength, length, size;
1600 struct tm *timestruct;
1601 http_headerbuf_t headerbuf;
1602 http_auth_challenges_t server_challenges;
1603 http_auth_challenges_t proxy_challenges;
1606 /* The following calls don't allocate anything */
1607 init_http_headerbuf(&headerbuf);
1608 init_http_auth_challenges(&server_challenges);
1609 init_http_auth_challenges(&proxy_challenges);
1611 direct = CHECK_FLAG('d');
1612 noredirect = CHECK_FLAG('A');
1613 verbose = CHECK_FLAG('v');
1614 ims = CHECK_FLAG('i');
1616 if (direct && purl) {
1621 /* try the provided URL first */
1627 e = HTTP_PROTOCOL_ERROR;
1639 url->port = fetch_default_port(url->scheme);
1641 /* were we redirected to an FTP URL? */
1642 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1643 if (strcmp(op, "GET") == 0)
1644 return (ftp_request(url, "RETR", us, purl, flags));
1645 else if (strcmp(op, "HEAD") == 0)
1646 return (ftp_request(url, "STAT", us, purl, flags));
1649 /* connect to server or proxy */
1650 if ((conn = http_connect(url, purl, flags)) == NULL)
1653 /* append port number only if necessary */
1655 if (url->port != fetch_default_port(url->scheme)) {
1656 snprintf(hbuf, sizeof(hbuf), "%s:%d", host, url->port);
1662 fetch_info("requesting %s://%s%s",
1663 url->scheme, host, url->doc);
1664 if (purl && strcmp(url->scheme, SCHEME_HTTPS) != 0) {
1665 http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1666 op, url->scheme, host, url->doc);
1668 http_cmd(conn, "%s %s HTTP/1.1",
1672 if (ims && url->ims_time) {
1673 timestruct = gmtime((time_t *)&url->ims_time);
1674 (void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1677 fetch_info("If-Modified-Since: %s", timebuf);
1678 http_cmd(conn, "If-Modified-Since: %s", timebuf);
1681 http_cmd(conn, "Host: %s", host);
1684 * Proxy authorization: we only send auth after we received
1685 * a 407 error. We do not first try basic anyway (changed
1686 * when support was added for digest-auth)
1688 if (purl && proxy_challenges.valid) {
1689 http_auth_params_t aparams;
1690 init_http_auth_params(&aparams);
1691 if (*purl->user || *purl->pwd) {
1692 aparams.user = strdup(purl->user);
1693 aparams.password = strdup(purl->pwd);
1694 } else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1696 if (http_authfromenv(p, &aparams) < 0) {
1697 http_seterr(HTTP_NEED_PROXY_AUTH);
1700 } else if (fetch_netrc_auth(purl) == 0) {
1701 aparams.user = strdup(purl->user);
1702 aparams.password = strdup(purl->pwd);
1704 http_authorize(conn, "Proxy-Authorization",
1705 &proxy_challenges, &aparams, url);
1706 clean_http_auth_params(&aparams);
1710 * Server authorization: we never send "a priori"
1711 * Basic auth, which used to be done if user/pass were
1712 * set in the url. This would be weird because we'd send the
1713 * password in the clear even if Digest is finally to be
1714 * used (it would have made more sense for the
1715 * pre-digest version to do this when Basic was specified
1716 * in the environment)
1718 if (server_challenges.valid) {
1719 http_auth_params_t aparams;
1720 init_http_auth_params(&aparams);
1721 if (*url->user || *url->pwd) {
1722 aparams.user = strdup(url->user);
1723 aparams.password = strdup(url->pwd);
1724 } else if ((p = getenv("HTTP_AUTH")) != NULL &&
1726 if (http_authfromenv(p, &aparams) < 0) {
1727 http_seterr(HTTP_NEED_AUTH);
1730 } else if (fetch_netrc_auth(url) == 0) {
1731 aparams.user = strdup(url->user);
1732 aparams.password = strdup(url->pwd);
1733 } else if (fetchAuthMethod &&
1734 fetchAuthMethod(url) == 0) {
1735 aparams.user = strdup(url->user);
1736 aparams.password = strdup(url->pwd);
1738 http_seterr(HTTP_NEED_AUTH);
1741 http_authorize(conn, "Authorization",
1742 &server_challenges, &aparams, url);
1743 clean_http_auth_params(&aparams);
1747 if ((p = getenv("HTTP_ACCEPT")) != NULL) {
1749 http_cmd(conn, "Accept: %s", p);
1751 http_cmd(conn, "Accept: */*");
1753 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1754 if (strcasecmp(p, "auto") == 0)
1755 http_cmd(conn, "Referer: %s://%s%s",
1756 url->scheme, host, url->doc);
1758 http_cmd(conn, "Referer: %s", p);
1760 if ((p = getenv("HTTP_USER_AGENT")) != NULL) {
1761 /* no User-Agent if defined but empty */
1763 http_cmd(conn, "User-Agent: %s", p);
1765 /* default User-Agent */
1766 http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER,
1769 if (url->offset > 0)
1770 http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1771 http_cmd(conn, "Connection: close");
1774 body_len = strlen(body);
1775 http_cmd(conn, "Content-Length: %zu", body_len);
1776 if (content_type != NULL)
1777 http_cmd(conn, "Content-Type: %s", content_type);
1783 fetch_write(conn, body, body_len);
1786 * Force the queued request to be dispatched. Normally, one
1787 * would do this with shutdown(2) but squid proxies can be
1788 * configured to disallow such half-closed connections. To
1789 * be compatible with such configurations, fiddle with socket
1790 * options to force the pending data to be written.
1793 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1796 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1800 switch (http_get_reply(conn)) {
1803 case HTTP_NOT_MODIFIED:
1806 case HTTP_MOVED_PERM:
1807 case HTTP_MOVED_TEMP:
1808 case HTTP_TEMP_REDIRECT:
1809 case HTTP_PERM_REDIRECT:
1810 case HTTP_SEE_OTHER:
1811 case HTTP_USE_PROXY:
1813 * Not so fine, but we still have to read the
1814 * headers to get the new location.
1817 case HTTP_NEED_AUTH:
1818 if (server_challenges.valid) {
1820 * We already sent out authorization code,
1821 * so there's nothing more we can do.
1823 http_seterr(conn->err);
1826 /* try again, but send the password this time */
1828 fetch_info("server requires authorization");
1830 case HTTP_NEED_PROXY_AUTH:
1831 if (proxy_challenges.valid) {
1833 * We already sent our proxy
1834 * authorization code, so there's
1835 * nothing more we can do. */
1836 http_seterr(conn->err);
1839 /* try again, but send the password this time */
1841 fetch_info("proxy requires authorization");
1843 case HTTP_BAD_RANGE:
1845 * This can happen if we ask for 0 bytes because
1846 * we already have the whole file. Consider this
1847 * a success for now, and check sizes later.
1850 case HTTP_PROTOCOL_ERROR:
1856 http_seterr(conn->err);
1859 /* fall through so we can get the full error message */
1862 /* get headers. http_next_header expects one line readahead */
1863 if (fetch_getln(conn) == -1) {
1868 switch ((h = http_next_header(conn, &headerbuf, &p))) {
1873 http_seterr(HTTP_PROTOCOL_ERROR);
1875 case hdr_content_length:
1876 http_parse_length(p, &clength);
1878 case hdr_content_range:
1879 http_parse_range(p, &offset, &length, &size);
1881 case hdr_last_modified:
1882 http_parse_mtime(p, &mtime);
1885 if (!HTTP_REDIRECT(conn->err))
1888 * if the A flag is set, we don't follow
1889 * temporary redirects.
1892 conn->err != HTTP_MOVED_PERM &&
1893 conn->err != HTTP_PERM_REDIRECT &&
1894 conn->err != HTTP_USE_PROXY) {
1901 fetch_info("%d redirect to %s",
1905 new = fetchMakeURL(url->scheme, url->host,
1906 url->port, p, url->user, url->pwd);
1908 new = fetchParseURL(p);
1910 /* XXX should set an error code */
1911 DEBUGF("failed to parse new URL\n");
1915 /* Only copy credentials if the host matches */
1916 if (strcmp(new->host, url->host) == 0 &&
1917 !*new->user && !*new->pwd) {
1918 strcpy(new->user, url->user);
1919 strcpy(new->pwd, url->pwd);
1921 new->offset = url->offset;
1922 new->length = url->length;
1923 new->ims_time = url->ims_time;
1925 case hdr_transfer_encoding:
1927 chunked = (strcasecmp(p, "chunked") == 0);
1929 case hdr_www_authenticate:
1930 if (conn->err != HTTP_NEED_AUTH)
1932 if (http_parse_authenticate(p, &server_challenges) == 0)
1935 case hdr_proxy_authenticate:
1936 if (conn->err != HTTP_NEED_PROXY_AUTH)
1938 if (http_parse_authenticate(p, &proxy_challenges) == 0)
1947 } while (h > hdr_end);
1949 /* we need to provide authentication */
1950 if (conn->err == HTTP_NEED_AUTH ||
1951 conn->err == HTTP_NEED_PROXY_AUTH) {
1953 if ((conn->err == HTTP_NEED_AUTH &&
1954 !server_challenges.valid) ||
1955 (conn->err == HTTP_NEED_PROXY_AUTH &&
1956 !proxy_challenges.valid)) {
1957 /* 401/7 but no www/proxy-authenticate ?? */
1958 DEBUGF("%03d without auth header\n", conn->err);
1966 /* requested range not satisfiable */
1967 if (conn->err == HTTP_BAD_RANGE) {
1968 if (url->offset > 0 && url->length == 0) {
1969 /* asked for 0 bytes; fake it */
1970 offset = url->offset;
1972 conn->err = HTTP_OK;
1975 http_seterr(conn->err);
1980 /* we have a hit or an error */
1981 if (conn->err == HTTP_OK
1982 || conn->err == HTTP_NOT_MODIFIED
1983 || conn->err == HTTP_PARTIAL
1984 || HTTP_ERROR(conn->err))
1987 /* all other cases: we got a redirect */
1989 clean_http_auth_challenges(&server_challenges);
1993 DEBUGF("redirect with no new location\n");
2001 /* we failed, or ran out of retries */
2007 DEBUGF("offset %lld, length %lld, size %lld, clength %lld\n",
2008 (long long)offset, (long long)length,
2009 (long long)size, (long long)clength);
2011 if (conn->err == HTTP_NOT_MODIFIED) {
2012 http_seterr(HTTP_NOT_MODIFIED);
2016 /* check for inconsistencies */
2017 if (clength != -1 && length != -1 && clength != length) {
2018 http_seterr(HTTP_PROTOCOL_ERROR);
2024 length = offset + clength;
2025 if (length != -1 && size != -1 && length != size) {
2026 http_seterr(HTTP_PROTOCOL_ERROR);
2035 us->atime = us->mtime = mtime;
2039 if (URL->offset > 0 && offset > URL->offset) {
2040 http_seterr(HTTP_PROTOCOL_ERROR);
2044 /* report back real offset and size */
2045 URL->offset = offset;
2046 URL->length = clength;
2048 /* wrap it up in a FILE */
2049 if ((f = http_funopen(conn, chunked)) == NULL) {
2059 if (HTTP_ERROR(conn->err)) {
2060 http_print_html(stderr, f);
2064 clean_http_headerbuf(&headerbuf);
2065 clean_http_auth_challenges(&server_challenges);
2066 clean_http_auth_challenges(&proxy_challenges);
2076 clean_http_headerbuf(&headerbuf);
2077 clean_http_auth_challenges(&server_challenges);
2078 clean_http_auth_challenges(&proxy_challenges);
2083 /*****************************************************************************
2088 * Retrieve and stat a file by HTTP
2091 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
2093 return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
2097 * Retrieve a file by HTTP
2100 fetchGetHTTP(struct url *URL, const char *flags)
2102 return (fetchXGetHTTP(URL, NULL, flags));
2106 * Store a file by HTTP
2109 fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
2111 warnx("fetchPutHTTP(): not implemented");
2116 * Get an HTTP document's metadata
2119 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
2123 f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2134 fetchListHTTP(struct url *url __unused, const char *flags __unused)
2136 warnx("fetchListHTTP(): not implemented");
2141 * Arbitrary HTTP verb and content requests
2144 fetchReqHTTP(struct url *URL, const char *method, const char *flags,
2145 const char *content_type, const char *body)
2148 return (http_request_body(URL, method, NULL, http_get_proxy(URL, flags),
2149 flags, content_type, body));