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.
32 * The following copyright applies to the base64 code:
35 * Copyright 1997 Massachusetts Institute of Technology
37 * Permission to use, copy, modify, and distribute this software and
38 * its documentation for any purpose and without fee is hereby
39 * granted, provided that both the above copyright notice and this
40 * permission notice appear in all copies, that both the above
41 * copyright notice and this permission notice appear in all
42 * supporting documentation, and that the name of M.I.T. not be used
43 * in advertising or publicity pertaining to distribution of the
44 * software without specific, written prior permission. M.I.T. makes
45 * no representations about the suitability of this software for any
46 * purpose. It is provided "as is" without express or implied
49 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
50 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
51 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
52 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
53 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
54 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
55 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
56 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
57 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
58 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
59 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 #include <sys/param.h>
64 #include <sys/socket.h>
82 extern char *__progname; /* XXX not portable */
84 /* Maximum number of redirects to follow */
85 #define MAX_REDIRECT 5
87 /* Symbolic names for reply codes we care about */
89 #define HTTP_PARTIAL 206
90 #define HTTP_MOVED_PERM 301
91 #define HTTP_MOVED_TEMP 302
92 #define HTTP_SEE_OTHER 303
93 #define HTTP_NEED_AUTH 401
94 #define HTTP_NEED_PROXY_AUTH 403
95 #define HTTP_PROTOCOL_ERROR 999
97 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
98 || (xyz) == HTTP_MOVED_TEMP \
99 || (xyz) == HTTP_SEE_OTHER)
103 /*****************************************************************************
104 * I/O functions for decoding chunked streams
123 * Get next chunk header
126 _http_new_chunk(struct cookie *c)
130 if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1)
133 if (c->b_len < 2 || !ishexnumber(*c->buf))
136 for (p = c->buf; !isspace(*p) && *p != ';' && p < c->buf + c->b_len; ++p)
137 if (!ishexnumber(*p))
139 else if (isdigit(*p))
140 c->chunksize = c->chunksize * 16 + *p - '0';
142 c->chunksize = c->chunksize * 16 + 10 + tolower(*p) - 'a';
145 c->total += c->chunksize;
146 if (c->chunksize == 0)
147 fprintf(stderr, "\033[1m_http_fillbuf(): "
148 "end of last chunk\033[m\n");
150 fprintf(stderr, "\033[1m_http_fillbuf(): "
151 "new chunk: %ld (%ld)\033[m\n", c->chunksize, c->total);
158 * Fill the input buffer, do chunk decoding on the fly
161 _http_fillbuf(struct cookie *c)
168 if (c->chunksize == 0) {
169 switch (_http_new_chunk(c)) {
179 if (c->b_size < c->chunksize) {
182 if ((tmp = realloc(c->buf, c->chunksize)) == NULL)
185 c->b_size = c->chunksize;
188 if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1)
190 c->chunksize -= c->b_len;
192 if (c->chunksize == 0) {
194 read(c->fd, endl, 2);
206 _http_readfn(void *v, char *buf, int len)
208 struct cookie *c = (struct cookie *)v;
216 for (pos = 0; len > 0; pos += l, len -= l) {
218 if (!c->buf || c->b_pos == c->b_len)
219 if (_http_fillbuf(c) < 1)
221 l = c->b_len - c->b_pos;
224 bcopy(c->buf + c->b_pos, buf + pos, l);
228 if (!pos && c->error)
237 _http_writefn(void *v, const char *buf, int len)
239 struct cookie *c = (struct cookie *)v;
241 return write(c->fd, buf, len);
248 _http_closefn(void *v)
250 struct cookie *c = (struct cookie *)v;
261 * Wrap a file descriptor up
264 _http_funopen(int fd)
269 if ((c = calloc(1, sizeof *c)) == NULL) {
274 if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) {
283 /*****************************************************************************
284 * Helper functions for talking to the server and parsing its replies
297 hdr_transfer_encoding,
301 /* Names of interesting headers */
306 { hdr_content_length, "Content-Length" },
307 { hdr_content_range, "Content-Range" },
308 { hdr_last_modified, "Last-Modified" },
309 { hdr_location, "Location" },
310 { hdr_transfer_encoding, "Transfer-Encoding" },
311 { hdr_www_authenticate, "WWW-Authenticate" },
312 { hdr_unknown, NULL },
315 static char *reply_buf;
316 static size_t reply_size;
317 static size_t reply_length;
320 * Send a formatted line; optionally echo to terminal
323 _http_cmd(int fd, const char *fmt, ...)
331 len = vasprintf(&msg, fmt, ap);
340 r = _fetch_putln(fd, msg, len);
352 * Get and parse status line
355 _http_get_reply(int fd)
359 if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
362 * A valid status line looks like "HTTP/m.n xyz reason" where m
363 * and n are the major and minor protocol version numbers and xyz
365 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
366 * just one) that do not send a version number, so we can't rely
367 * on finding one, but if we do, insist on it being 1.0 or 1.1.
368 * We don't care about the reason phrase.
370 if (strncmp(reply_buf, "HTTP", 4) != 0)
371 return HTTP_PROTOCOL_ERROR;
374 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
375 return HTTP_PROTOCOL_ERROR;
382 return HTTP_PROTOCOL_ERROR;
384 return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'));
388 * Check a header; if the type matches the given string, return a
389 * pointer to the beginning of the value.
392 _http_match(const char *str, const char *hdr)
394 while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
396 if (*str || *hdr != ':')
398 while (*hdr && isspace(*++hdr))
404 * Get the next header and return the appropriate symbolic code.
407 _http_next_header(int fd, const char **p)
411 if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
413 while (reply_length && isspace(reply_buf[reply_length-1]))
415 reply_buf[reply_length] = 0;
416 if (reply_length == 0)
419 * We could check for malformed headers but we don't really care.
420 * A valid header starts with a token immediately followed by a
421 * colon; a token is any sequence of non-control, non-whitespace
422 * characters except "()<>@,;:\\\"{}".
424 for (i = 0; hdr_names[i].num != hdr_unknown; i++)
425 if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL)
426 return hdr_names[i].num;
431 * Parse a last-modified header
434 _http_parse_mtime(const char *p, time_t *mtime)
439 strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale);
440 setlocale(LC_TIME, "C");
441 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
442 /* XXX should add support for date-2 and date-3 */
443 setlocale(LC_TIME, locale);
446 DEBUG(fprintf(stderr, "last modified: [\033[1m%04d-%02d-%02d "
447 "%02d:%02d:%02d\033[m]\n",
448 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
449 tm.tm_hour, tm.tm_min, tm.tm_sec));
450 *mtime = timegm(&tm);
455 * Parse a content-length header
458 _http_parse_length(const char *p, off_t *length)
462 for (len = 0; *p && isdigit(*p); ++p)
463 len = len * 10 + (*p - '0');
464 DEBUG(fprintf(stderr, "content length: [\033[1m%lld\033[m]\n", len));
470 * Parse a content-range header
473 _http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
475 int first, last, len;
477 if (strncasecmp(p, "bytes ", 6) != 0)
479 for (first = 0, p += 6; *p && isdigit(*p); ++p)
480 first = first * 10 + *p - '0';
483 for (last = 0, ++p; *p && isdigit(*p); ++p)
484 last = last * 10 + *p - '0';
485 if (first > last || *p != '/')
487 for (len = 0, ++p; *p && isdigit(*p); ++p)
488 len = len * 10 + *p - '0';
489 if (len < last - first + 1)
491 DEBUG(fprintf(stderr, "content range: [\033[1m%d-%d/%d\033[m]\n",
494 *length = last - first + 1;
500 /*****************************************************************************
501 * Helper functions for authorization
508 _http_base64(char *src)
510 static const char base64[] =
511 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
512 "abcdefghijklmnopqrstuvwxyz"
519 if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
525 t = (src[0] << 16) | (src[1] << 8) | src[2];
526 dst[0] = base64[(t >> 18) & 0x3f];
527 dst[1] = base64[(t >> 12) & 0x3f];
528 dst[2] = base64[(t >> 6) & 0x3f];
529 dst[3] = base64[(t >> 0) & 0x3f];
536 t = (src[0] << 16) | (src[1] << 8);
537 dst[0] = base64[(t >> 18) & 0x3f];
538 dst[1] = base64[(t >> 12) & 0x3f];
539 dst[2] = base64[(t >> 6) & 0x3f];
546 dst[0] = base64[(t >> 18) & 0x3f];
547 dst[1] = base64[(t >> 12) & 0x3f];
548 dst[2] = dst[3] = '=';
561 * Encode username and password
564 _http_basic_auth(int fd, const char *hdr, const char *usr, const char *pwd)
569 DEBUG(fprintf(stderr, "usr: [\033[1m%s\033[m]\n", usr));
570 DEBUG(fprintf(stderr, "pwd: [\033[1m%s\033[m]\n", pwd));
571 if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
573 auth = _http_base64(upw);
577 r = _http_cmd(fd, "%s: Basic %s", hdr, auth);
583 * Send an authorization header
586 _http_authorize(int fd, const char *hdr, const char *p)
588 /* basic authorization */
589 if (strncasecmp(p, "basic:", 6) == 0) {
590 char *user, *pwd, *str;
594 for (p += 6; *p && *p != ':'; ++p)
596 if (!*p || strchr(++p, ':') == NULL)
598 if ((str = strdup(p)) == NULL)
601 pwd = strchr(str, ':');
603 r = _http_basic_auth(fd, hdr, user, pwd);
611 /*****************************************************************************
612 * Helper functions for connecting to a server or proxy
616 * Connect to the correct HTTP server or proxy.
619 _http_connect(struct url *URL, struct url *purl, const char *flags)
630 verbose = CHECK_FLAG('v');
634 else if (CHECK_FLAG('6'))
640 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
641 /* can't talk http to an ftp server */
642 /* XXX should set an error code */
646 if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1)
647 /* _fetch_connect() has already set an error code */
653 _http_get_proxy(void)
658 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
659 (purl = fetchParseURL(p))) {
661 strcpy(purl->scheme, SCHEME_HTTP);
663 purl->port = _fetch_default_proxy_port(purl->scheme);
664 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
672 /*****************************************************************************
677 * Send a request and process the reply
680 _http_request(struct url *URL, const char *op, struct url_stat *us,
681 struct url *purl, const char *flags)
683 struct url *url, *new;
684 int chunked, direct, need_auth, noredirect, verbose;
686 off_t offset, clength, length, size;
693 char hbuf[MAXHOSTNAMELEN + 1];
696 direct = CHECK_FLAG('d');
697 noredirect = CHECK_FLAG('A');
698 verbose = CHECK_FLAG('v');
700 if (direct && purl) {
705 /* try the provided URL first */
708 /* if the A flag is set, we only get one try */
709 n = noredirect ? 1 : MAX_REDIRECT;
724 url->port = _fetch_default_port(url->scheme);
726 /* connect to server or proxy */
727 if ((fd = _http_connect(url, purl, flags)) == -1)
732 if (strchr(url->host, ':')) {
733 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
740 _fetch_info("requesting %s://%s:%d%s",
741 url->scheme, host, url->port, url->doc);
743 _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1",
744 op, url->scheme, host, url->port, url->doc);
746 _http_cmd(fd, "%s %s HTTP/1.1",
751 if (url->port == _fetch_default_port(url->scheme))
752 _http_cmd(fd, "Host: %s", host);
754 _http_cmd(fd, "Host: %s:%d", host, url->port);
756 /* proxy authorization */
758 if (*purl->user || *purl->pwd)
759 _http_basic_auth(fd, "Proxy-Authorization",
760 purl->user, purl->pwd);
761 else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
762 _http_authorize(fd, "Proxy-Authorization", p);
765 /* server authorization */
766 if (need_auth || *url->user || *url->pwd) {
767 if (*url->user || *url->pwd)
768 _http_basic_auth(fd, "Authorization", url->user, url->pwd);
769 else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
770 _http_authorize(fd, "Authorization", p);
771 else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
772 _http_basic_auth(fd, "Authorization", url->user, url->pwd);
774 _http_seterr(HTTP_NEED_AUTH);
780 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
781 _http_cmd(fd, "User-Agent: %s", p);
783 _http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname);
785 _http_cmd(fd, "Range: bytes=%lld-", url->offset);
786 _http_cmd(fd, "Connection: close");
790 switch ((code = _http_get_reply(fd))) {
795 case HTTP_MOVED_PERM:
796 case HTTP_MOVED_TEMP:
798 * Not so fine, but we still have to read the headers to
799 * get the new location.
805 * We already sent out authorization code, so there's
806 * nothing more we can do.
811 /* try again, but send the password this time */
813 _fetch_info("server requires authorization");
815 case HTTP_NEED_PROXY_AUTH:
817 * If we're talking to a proxy, we already sent our proxy
818 * authorization code, so there's nothing more we can do.
822 case HTTP_PROTOCOL_ERROR:
834 switch ((h = _http_next_header(fd, &p))) {
839 _http_seterr(HTTP_PROTOCOL_ERROR);
841 case hdr_content_length:
842 _http_parse_length(p, &clength);
844 case hdr_content_range:
845 _http_parse_range(p, &offset, &length, &size);
847 case hdr_last_modified:
848 _http_parse_mtime(p, &mtime);
851 if (!HTTP_REDIRECT(code))
856 _fetch_info("%d redirect to %s", code, p);
859 new = fetchMakeURL(url->scheme, url->host, url->port, p,
860 url->user, url->pwd);
862 new = fetchParseURL(p);
864 /* XXX should set an error code */
865 DEBUG(fprintf(stderr, "failed to parse new URL\n"));
868 if (!*new->user && !*new->pwd) {
869 strcpy(new->user, url->user);
870 strcpy(new->pwd, url->pwd);
872 new->offset = url->offset;
873 new->length = url->length;
875 case hdr_transfer_encoding:
877 chunked = (strcasecmp(p, "chunked") == 0);
879 case hdr_www_authenticate:
880 if (code != HTTP_NEED_AUTH)
882 /* if we were smarter, we'd check the method and realm */
890 } while (h > hdr_end);
893 if (code == HTTP_OK || code == HTTP_PARTIAL)
896 /* we need to provide authentication */
897 if (code == HTTP_NEED_AUTH) {
904 /* all other cases: we got a redirect */
909 DEBUG(fprintf(stderr, "redirect with no new location\n"));
917 /* we failed, or ran out of retries */
923 DEBUG(fprintf(stderr, "offset %lld, length %lld, size %lld, clength %lld\n",
924 offset, length, size, clength));
926 /* check for inconsistencies */
927 if (clength != -1 && length != -1 && clength != length) {
928 _http_seterr(HTTP_PROTOCOL_ERROR);
934 length = offset + clength;
935 if (length != -1 && size != -1 && length != size) {
936 _http_seterr(HTTP_PROTOCOL_ERROR);
945 us->atime = us->mtime = mtime;
949 if (offset > URL->offset) {
950 _http_seterr(HTTP_PROTOCOL_ERROR);
954 /* report back real offset and size */
955 URL->offset = offset;
956 URL->length = clength;
958 /* wrap it up in a FILE */
959 if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) {
982 /*****************************************************************************
987 * Retrieve and stat a file by HTTP
990 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
992 return _http_request(URL, "GET", us, _http_get_proxy(), flags);
996 * Retrieve a file by HTTP
999 fetchGetHTTP(struct url *URL, const char *flags)
1001 return fetchXGetHTTP(URL, NULL, flags);
1005 * Store a file by HTTP
1008 fetchPutHTTP(struct url *URL, const char *flags)
1010 warnx("fetchPutHTTP(): not implemented");
1015 * Get an HTTP document's metadata
1018 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1022 if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL)
1032 fetchListHTTP(struct url *url, const char *flags)
1034 warnx("fetchListHTTP(): not implemented");