2 * Copyright (c) 2000 Dag-Erling Coïdan 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.
28 * $FreeBSD: src/lib/libfetch/http.c,v 1.13.2.23 2003/06/06 06:45:25 des Exp $
29 * $DragonFly: src/lib/libfetch/http.c,v 1.2 2003/06/17 04:26:49 dillon Exp $
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>
83 /* Maximum number of redirects to follow */
84 #define MAX_REDIRECT 5
86 /* Symbolic names for reply codes we care about */
88 #define HTTP_PARTIAL 206
89 #define HTTP_MOVED_PERM 301
90 #define HTTP_MOVED_TEMP 302
91 #define HTTP_SEE_OTHER 303
92 #define HTTP_NEED_AUTH 401
93 #define HTTP_NEED_PROXY_AUTH 407
94 #define HTTP_PROTOCOL_ERROR 999
96 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
97 || (xyz) == HTTP_MOVED_TEMP \
98 || (xyz) == HTTP_SEE_OTHER)
100 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
103 /*****************************************************************************
104 * I/O functions for decoding chunked streams
109 conn_t *conn; /* connection */
110 int chunked; /* chunked mode */
111 char *buf; /* chunk buffer */
112 size_t bufsize; /* size of chunk buffer */
113 ssize_t buflen; /* amount of data currently in buffer */
114 int bufpos; /* current read offset in buffer */
115 int eof; /* end-of-file flag */
116 int error; /* error flag */
117 size_t chunksize; /* remaining size of current chunk */
124 * Get next chunk header
127 _http_new_chunk(struct httpio *io)
131 if (_fetch_getln(io->conn) == -1)
134 if (io->conn->buflen < 2 || !ishexnumber(*io->conn->buf))
137 for (p = io->conn->buf; *p && !isspace(*p); ++p) {
140 if (!ishexnumber(*p))
143 io->chunksize = io->chunksize * 16 +
146 io->chunksize = io->chunksize * 16 +
147 10 + tolower(*p) - 'a';
153 io->total += io->chunksize;
154 if (io->chunksize == 0)
155 fprintf(stderr, "%s(): end of last chunk\n", __func__);
157 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
158 __func__, (unsigned long)io->chunksize,
159 (unsigned long)io->total);
163 return (io->chunksize);
167 * Grow the input buffer to at least len bytes
170 _http_growbuf(struct httpio *io, size_t len)
174 if (io->bufsize >= len)
177 if ((tmp = realloc(io->buf, len)) == NULL)
185 * Fill the input buffer, do chunk decoding on the fly
188 _http_fillbuf(struct httpio *io, size_t len)
195 if (io->chunked == 0) {
196 if (_http_growbuf(io, len) == -1)
198 if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) {
206 if (io->chunksize == 0) {
207 switch (_http_new_chunk(io)) {
217 if (len > io->chunksize)
219 if (_http_growbuf(io, len) == -1)
221 if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) {
225 io->chunksize -= io->buflen;
227 if (io->chunksize == 0) {
230 if (_fetch_read(io->conn, endl, 2) != 2 ||
231 endl[0] != '\r' || endl[1] != '\n')
244 _http_readfn(void *v, char *buf, int len)
246 struct httpio *io = (struct httpio *)v;
254 for (pos = 0; len > 0; pos += l, len -= l) {
256 if (!io->buf || io->bufpos == io->buflen)
257 if (_http_fillbuf(io, len) < 1)
259 l = io->buflen - io->bufpos;
262 bcopy(io->buf + io->bufpos, buf + pos, l);
266 if (!pos && io->error)
275 _http_writefn(void *v, const char *buf, int len)
277 struct httpio *io = (struct httpio *)v;
279 return (_fetch_write(io->conn, buf, len));
286 _http_closefn(void *v)
288 struct httpio *io = (struct httpio *)v;
291 r = _fetch_close(io->conn);
299 * Wrap a file descriptor up
302 _http_funopen(conn_t *conn, int chunked)
307 if ((io = calloc(1, sizeof(*io))) == NULL) {
312 io->chunked = chunked;
313 f = funopen(io, _http_readfn, _http_writefn, NULL, _http_closefn);
323 /*****************************************************************************
324 * Helper functions for talking to the server and parsing its replies
337 hdr_transfer_encoding,
341 /* Names of interesting headers */
346 { hdr_content_length, "Content-Length" },
347 { hdr_content_range, "Content-Range" },
348 { hdr_last_modified, "Last-Modified" },
349 { hdr_location, "Location" },
350 { hdr_transfer_encoding, "Transfer-Encoding" },
351 { hdr_www_authenticate, "WWW-Authenticate" },
352 { hdr_unknown, NULL },
356 * Send a formatted line; optionally echo to terminal
359 _http_cmd(conn_t *conn, const char *fmt, ...)
367 len = vasprintf(&msg, fmt, ap);
376 r = _fetch_putln(conn, msg, len);
388 * Get and parse status line
391 _http_get_reply(conn_t *conn)
395 if (_fetch_getln(conn) == -1)
398 * A valid status line looks like "HTTP/m.n xyz reason" where m
399 * and n are the major and minor protocol version numbers and xyz
401 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
402 * just one) that do not send a version number, so we can't rely
403 * on finding one, but if we do, insist on it being 1.0 or 1.1.
404 * We don't care about the reason phrase.
406 if (strncmp(conn->buf, "HTTP", 4) != 0)
407 return (HTTP_PROTOCOL_ERROR);
410 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
411 return (HTTP_PROTOCOL_ERROR);
414 if (*p != ' ' || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3]))
415 return (HTTP_PROTOCOL_ERROR);
417 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
422 * Check a header; if the type matches the given string, return a pointer
423 * to the beginning of the value.
426 _http_match(const char *str, const char *hdr)
428 while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
430 if (*str || *hdr != ':')
432 while (*hdr && isspace(*++hdr))
438 * Get the next header and return the appropriate symbolic code.
441 _http_next_header(conn_t *conn, const char **p)
445 if (_fetch_getln(conn) == -1)
446 return (hdr_syserror);
447 while (conn->buflen && isspace(conn->buf[conn->buflen - 1]))
449 conn->buf[conn->buflen] = '\0';
450 if (conn->buflen == 0)
453 * We could check for malformed headers but we don't really care.
454 * A valid header starts with a token immediately followed by a
455 * colon; a token is any sequence of non-control, non-whitespace
456 * characters except "()<>@,;:\\\"{}".
458 for (i = 0; hdr_names[i].num != hdr_unknown; i++)
459 if ((*p = _http_match(hdr_names[i].name, conn->buf)) != NULL)
460 return (hdr_names[i].num);
461 return (hdr_unknown);
465 * Parse a last-modified header
468 _http_parse_mtime(const char *p, time_t *mtime)
473 strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
474 setlocale(LC_TIME, "C");
475 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
476 /* XXX should add support for date-2 and date-3 */
477 setlocale(LC_TIME, locale);
480 DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
482 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
483 tm.tm_hour, tm.tm_min, tm.tm_sec));
484 *mtime = timegm(&tm);
489 * Parse a content-length header
492 _http_parse_length(const char *p, off_t *length)
496 for (len = 0; *p && isdigit(*p); ++p)
497 len = len * 10 + (*p - '0');
500 DEBUG(fprintf(stderr, "content length: [%lld]\n",
507 * Parse a content-range header
510 _http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
512 off_t first, last, len;
514 if (strncasecmp(p, "bytes ", 6) != 0)
516 for (first = 0, p += 6; *p && isdigit(*p); ++p)
517 first = first * 10 + *p - '0';
520 for (last = 0, ++p; *p && isdigit(*p); ++p)
521 last = last * 10 + *p - '0';
522 if (first > last || *p != '/')
524 for (len = 0, ++p; *p && isdigit(*p); ++p)
525 len = len * 10 + *p - '0';
526 if (*p || len < last - first + 1)
528 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
529 (long long)first, (long long)last, (long long)len));
531 *length = last - first + 1;
537 /*****************************************************************************
538 * Helper functions for authorization
545 _http_base64(const char *src)
547 static const char base64[] =
548 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
549 "abcdefghijklmnopqrstuvwxyz"
556 if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
562 t = (src[0] << 16) | (src[1] << 8) | src[2];
563 dst[0] = base64[(t >> 18) & 0x3f];
564 dst[1] = base64[(t >> 12) & 0x3f];
565 dst[2] = base64[(t >> 6) & 0x3f];
566 dst[3] = base64[(t >> 0) & 0x3f];
573 t = (src[0] << 16) | (src[1] << 8);
574 dst[0] = base64[(t >> 18) & 0x3f];
575 dst[1] = base64[(t >> 12) & 0x3f];
576 dst[2] = base64[(t >> 6) & 0x3f];
583 dst[0] = base64[(t >> 18) & 0x3f];
584 dst[1] = base64[(t >> 12) & 0x3f];
585 dst[2] = dst[3] = '=';
598 * Encode username and password
601 _http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
606 DEBUG(fprintf(stderr, "usr: [%s]\n", usr));
607 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
608 if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
610 auth = _http_base64(upw);
614 r = _http_cmd(conn, "%s: Basic %s", hdr, auth);
620 * Send an authorization header
623 _http_authorize(conn_t *conn, const char *hdr, const char *p)
625 /* basic authorization */
626 if (strncasecmp(p, "basic:", 6) == 0) {
627 char *user, *pwd, *str;
631 for (p += 6; *p && *p != ':'; ++p)
633 if (!*p || strchr(++p, ':') == NULL)
635 if ((str = strdup(p)) == NULL)
636 return (-1); /* XXX */
638 pwd = strchr(str, ':');
640 r = _http_basic_auth(conn, hdr, user, pwd);
648 /*****************************************************************************
649 * Helper functions for connecting to a server or proxy
653 * Connect to the correct HTTP server or proxy.
656 _http_connect(struct url *URL, struct url *purl, const char *flags)
668 verbose = CHECK_FLAG('v');
672 else if (CHECK_FLAG('6'))
676 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
678 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
679 /* can't talk http to an ftp server */
680 /* XXX should set an error code */
684 if ((conn = _fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
685 /* _fetch_connect() has already set an error code */
687 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
688 _fetch_ssl(conn, verbose) == -1) {
699 _http_get_proxy(const char *flags)
704 if (flags != NULL && strchr(flags, 'd') != NULL)
706 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
707 (purl = fetchParseURL(p))) {
709 strcpy(purl->scheme, SCHEME_HTTP);
711 purl->port = _fetch_default_proxy_port(purl->scheme);
712 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
720 _http_print_html(FILE *out, FILE *in)
727 while ((line = fgetln(in, &len)) != NULL) {
728 while (len && isspace(line[len - 1]))
730 for (p = q = line; q < line + len; ++q) {
731 if (comment && *q == '-') {
732 if (q + 2 < line + len &&
733 strcmp(q, "-->") == 0) {
737 } else if (tag && !comment && *q == '>') {
740 } else if (!tag && *q == '<') {
742 fwrite(p, q - p, 1, out);
744 if (q + 3 < line + len &&
745 strcmp(q, "<!--") == 0) {
752 fwrite(p, q - p, 1, out);
758 /*****************************************************************************
763 * Send a request and process the reply
765 * XXX This function is way too long, the do..while loop should be split
766 * XXX off into a separate function.
769 _http_request(struct url *URL, const char *op, struct url_stat *us,
770 struct url *purl, const char *flags)
773 struct url *url, *new;
774 int chunked, direct, need_auth, noredirect, verbose;
776 off_t offset, clength, length, size;
781 char hbuf[MAXHOSTNAMELEN + 7], *host;
783 direct = CHECK_FLAG('d');
784 noredirect = CHECK_FLAG('A');
785 verbose = CHECK_FLAG('v');
787 if (direct && purl) {
792 /* try the provided URL first */
795 /* if the A flag is set, we only get one try */
796 n = noredirect ? 1 : MAX_REDIRECT;
799 e = HTTP_PROTOCOL_ERROR;
812 url->port = _fetch_default_port(url->scheme);
814 /* were we redirected to an FTP URL? */
815 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
816 if (strcmp(op, "GET") == 0)
817 return (_ftp_request(url, "RETR", us, purl, flags));
818 else if (strcmp(op, "HEAD") == 0)
819 return (_ftp_request(url, "STAT", us, purl, flags));
822 /* connect to server or proxy */
823 if ((conn = _http_connect(url, purl, flags)) == NULL)
828 if (strchr(url->host, ':')) {
829 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
833 if (url->port != _fetch_default_port(url->scheme)) {
838 snprintf(hbuf + strlen(hbuf),
839 sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
844 _fetch_info("requesting %s://%s%s",
845 url->scheme, host, url->doc);
847 _http_cmd(conn, "%s %s://%s%s HTTP/1.1",
848 op, url->scheme, host, url->doc);
850 _http_cmd(conn, "%s %s HTTP/1.1",
855 _http_cmd(conn, "Host: %s", host);
857 /* proxy authorization */
859 if (*purl->user || *purl->pwd)
860 _http_basic_auth(conn, "Proxy-Authorization",
861 purl->user, purl->pwd);
862 else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
863 _http_authorize(conn, "Proxy-Authorization", p);
866 /* server authorization */
867 if (need_auth || *url->user || *url->pwd) {
868 if (*url->user || *url->pwd)
869 _http_basic_auth(conn, "Authorization", url->user, url->pwd);
870 else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
871 _http_authorize(conn, "Authorization", p);
872 else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
873 _http_basic_auth(conn, "Authorization", url->user, url->pwd);
875 _http_seterr(HTTP_NEED_AUTH);
881 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
882 if (strcasecmp(p, "auto") == 0)
883 _http_cmd(conn, "Referer: %s://%s%s",
884 url->scheme, host, url->doc);
886 _http_cmd(conn, "Referer: %s", p);
888 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
889 _http_cmd(conn, "User-Agent: %s", p);
891 _http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
893 _http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
894 _http_cmd(conn, "Connection: close");
898 switch (_http_get_reply(conn)) {
903 case HTTP_MOVED_PERM:
904 case HTTP_MOVED_TEMP:
907 * Not so fine, but we still have to read the headers to
908 * get the new location.
914 * We already sent out authorization code, so there's
915 * nothing more we can do.
917 _http_seterr(conn->err);
920 /* try again, but send the password this time */
922 _fetch_info("server requires authorization");
924 case HTTP_NEED_PROXY_AUTH:
926 * If we're talking to a proxy, we already sent our proxy
927 * authorization code, so there's nothing more we can do.
929 _http_seterr(conn->err);
931 case HTTP_PROTOCOL_ERROR:
937 _http_seterr(conn->err);
940 /* fall through so we can get the full error message */
945 switch ((h = _http_next_header(conn, &p))) {
950 _http_seterr(HTTP_PROTOCOL_ERROR);
952 case hdr_content_length:
953 _http_parse_length(p, &clength);
955 case hdr_content_range:
956 _http_parse_range(p, &offset, &length, &size);
958 case hdr_last_modified:
959 _http_parse_mtime(p, &mtime);
962 if (!HTTP_REDIRECT(conn->err))
967 _fetch_info("%d redirect to %s", conn->err, p);
970 new = fetchMakeURL(url->scheme, url->host, url->port, p,
971 url->user, url->pwd);
973 new = fetchParseURL(p);
975 /* XXX should set an error code */
976 DEBUG(fprintf(stderr, "failed to parse new URL\n"));
979 if (!*new->user && !*new->pwd) {
980 strcpy(new->user, url->user);
981 strcpy(new->pwd, url->pwd);
983 new->offset = url->offset;
984 new->length = url->length;
986 case hdr_transfer_encoding:
988 chunked = (strcasecmp(p, "chunked") == 0);
990 case hdr_www_authenticate:
991 if (conn->err != HTTP_NEED_AUTH)
993 /* if we were smarter, we'd check the method and realm */
1001 } while (h > hdr_end);
1003 /* we need to provide authentication */
1004 if (conn->err == HTTP_NEED_AUTH) {
1012 /* we have a hit or an error */
1013 if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
1016 /* all other cases: we got a redirect */
1022 DEBUG(fprintf(stderr, "redirect with no new location\n"));
1030 /* we failed, or ran out of retries */
1036 DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1037 " size %lld, clength %lld\n",
1038 (long long)offset, (long long)length,
1039 (long long)size, (long long)clength));
1041 /* check for inconsistencies */
1042 if (clength != -1 && length != -1 && clength != length) {
1043 _http_seterr(HTTP_PROTOCOL_ERROR);
1049 length = offset + clength;
1050 if (length != -1 && size != -1 && length != size) {
1051 _http_seterr(HTTP_PROTOCOL_ERROR);
1060 us->atime = us->mtime = mtime;
1064 if (URL->offset > 0 && offset > URL->offset) {
1065 _http_seterr(HTTP_PROTOCOL_ERROR);
1069 /* report back real offset and size */
1070 URL->offset = offset;
1071 URL->length = clength;
1073 /* wrap it up in a FILE */
1074 if ((f = _http_funopen(conn, chunked)) == NULL) {
1084 if (HTTP_ERROR(conn->err)) {
1085 _http_print_html(stderr, f);
1103 /*****************************************************************************
1108 * Retrieve and stat a file by HTTP
1111 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1113 return (_http_request(URL, "GET", us, _http_get_proxy(flags), flags));
1117 * Retrieve a file by HTTP
1120 fetchGetHTTP(struct url *URL, const char *flags)
1122 return (fetchXGetHTTP(URL, NULL, flags));
1126 * Store a file by HTTP
1129 fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1131 warnx("fetchPutHTTP(): not implemented");
1136 * Get an HTTP document's metadata
1139 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1143 f = _http_request(URL, "HEAD", us, _http_get_proxy(flags), flags);
1154 fetchListHTTP(struct url *url __unused, const char *flags __unused)
1156 warnx("fetchListHTTP(): not implemented");