http.c revision 63716
137535Sdes/*-
263012Sdes * Copyright (c) 2000 Dag-Erling Co�dan Sm�rgrav
337535Sdes * All rights reserved.
437535Sdes *
537535Sdes * Redistribution and use in source and binary forms, with or without
637535Sdes * modification, are permitted provided that the following conditions
737535Sdes * are met:
837535Sdes * 1. Redistributions of source code must retain the above copyright
937535Sdes *    notice, this list of conditions and the following disclaimer
1037535Sdes *    in this position and unchanged.
1137535Sdes * 2. Redistributions in binary form must reproduce the above copyright
1237535Sdes *    notice, this list of conditions and the following disclaimer in the
1337535Sdes *    documentation and/or other materials provided with the distribution.
1437535Sdes * 3. The name of the author may not be used to endorse or promote products
1563012Sdes *    derived from this software without specific prior written permission.
1637535Sdes *
1737535Sdes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1837535Sdes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1937535Sdes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2037535Sdes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2137535Sdes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2237535Sdes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2337535Sdes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2437535Sdes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2537535Sdes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2637535Sdes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2737535Sdes *
2863012Sdes *      $FreeBSD: head/lib/libfetch/http.c 63716 2000-07-21 11:02:43Z des $
2937535Sdes */
3037535Sdes
3163236Sdes/*
3263236Sdes * The following copyright applies to the base64 code:
3363236Sdes *
3463236Sdes *-
3563236Sdes * Copyright 1997 Massachusetts Institute of Technology
3663236Sdes *
3763236Sdes * Permission to use, copy, modify, and distribute this software and
3863236Sdes * its documentation for any purpose and without fee is hereby
3963236Sdes * granted, provided that both the above copyright notice and this
4063236Sdes * permission notice appear in all copies, that both the above
4163236Sdes * copyright notice and this permission notice appear in all
4263236Sdes * supporting documentation, and that the name of M.I.T. not be used
4363236Sdes * in advertising or publicity pertaining to distribution of the
4463236Sdes * software without specific, written prior permission.  M.I.T. makes
4563236Sdes * no representations about the suitability of this software for any
4663236Sdes * purpose.  It is provided "as is" without express or implied
4763236Sdes * warranty.
4863236Sdes *
4963236Sdes * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
5063236Sdes * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
5163236Sdes * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5263236Sdes * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
5363236Sdes * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5463236Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5563236Sdes * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
5663236Sdes * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
5763236Sdes * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
5863236Sdes * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
5963236Sdes * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
6063236Sdes * SUCH DAMAGE.
6163236Sdes */
6263236Sdes
6337535Sdes#include <sys/param.h>
6460737Sume#include <sys/socket.h>
6537535Sdes
6663012Sdes#include <ctype.h>
6737535Sdes#include <err.h>
6863012Sdes#include <errno.h>
6960376Sdes#include <locale.h>
7060189Sdes#include <netdb.h>
7137608Sdes#include <stdarg.h>
7237535Sdes#include <stdio.h>
7337535Sdes#include <stdlib.h>
7437535Sdes#include <string.h>
7560376Sdes#include <time.h>
7637535Sdes#include <unistd.h>
7737535Sdes
7837535Sdes#include "fetch.h"
7940939Sdes#include "common.h"
8041862Sdes#include "httperr.h"
8137535Sdes
8263012Sdesextern char *__progname; /* XXX not portable */
8337535Sdes
8463012Sdes/* Maximum number of redirects to follow */
8563012Sdes#define MAX_REDIRECT 5
8637535Sdes
8763012Sdes/* Symbolic names for reply codes we care about */
8863012Sdes#define HTTP_OK			200
8963012Sdes#define HTTP_PARTIAL		206
9063012Sdes#define HTTP_MOVED_PERM		301
9163012Sdes#define HTTP_MOVED_TEMP		302
9263012Sdes#define HTTP_SEE_OTHER		303
9363012Sdes#define HTTP_NEED_AUTH		401
9463012Sdes#define HTTP_NEED_PROXY_AUTH	403
9563012Sdes#define HTTP_PROTOCOL_ERROR	999
9660196Sdes
9763012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
9863012Sdes                            || (xyz) == HTTP_MOVED_TEMP \
9963012Sdes                            || (xyz) == HTTP_SEE_OTHER)
10063012Sdes
10163012Sdes
10263012Sdes
10363012Sdes/*****************************************************************************
10463012Sdes * I/O functions for decoding chunked streams
10563012Sdes */
10663012Sdes
10737535Sdesstruct cookie
10837535Sdes{
10963012Sdes    int		 fd;
11063012Sdes    char	*buf;
11163012Sdes    size_t	 b_size;
11263012Sdes    size_t	 b_len;
11363012Sdes    int		 b_pos;
11463012Sdes    int		 eof;
11563012Sdes    int		 error;
11663012Sdes    long	 chunksize;
11763281Sdes#ifndef NDEBUG
11863012Sdes    long	 total;
11963012Sdes#endif
12037535Sdes};
12137535Sdes
12237608Sdes/*
12363012Sdes * Get next chunk header
12437608Sdes */
12537608Sdesstatic int
12663012Sdes_http_new_chunk(struct cookie *c)
12737608Sdes{
12863012Sdes    char *p;
12937608Sdes
13063012Sdes    if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1)
13163012Sdes	return -1;
13263012Sdes
13363012Sdes    if (c->b_len < 2 || !ishexnumber(*c->buf))
13463012Sdes	return -1;
13563012Sdes
13663012Sdes    for (p = c->buf; !isspace(*p) && *p != ';' && p < c->buf + c->b_len; ++p)
13763012Sdes	if (!ishexnumber(*p))
13863012Sdes	    return -1;
13963012Sdes	else if (isdigit(*p))
14063012Sdes	    c->chunksize = c->chunksize * 16 + *p - '0';
14163012Sdes	else
14263012Sdes	    c->chunksize = c->chunksize * 16 + 10 + tolower(*p) - 'a';
14363012Sdes
14463281Sdes#ifndef NDEBUG
14563012Sdes    c->total += c->chunksize;
14663012Sdes    if (c->chunksize == 0)
14763012Sdes	fprintf(stderr, "\033[1m_http_fillbuf(): "
14863012Sdes		"end of last chunk\033[m\n");
14963012Sdes    else
15063012Sdes	fprintf(stderr, "\033[1m_http_fillbuf(): "
15163012Sdes		"new chunk: %ld (%ld)\033[m\n", c->chunksize, c->total);
15263012Sdes#endif
15363012Sdes
15463012Sdes    return c->chunksize;
15537608Sdes}
15637608Sdes
15737608Sdes/*
15837608Sdes * Fill the input buffer, do chunk decoding on the fly
15937608Sdes */
16063012Sdesstatic int
16137535Sdes_http_fillbuf(struct cookie *c)
16237535Sdes{
16363012Sdes    if (c->error)
16463012Sdes	return -1;
16537535Sdes    if (c->eof)
16663012Sdes	return 0;
16763012Sdes
16863012Sdes    if (c->chunksize == 0) {
16963012Sdes	switch (_http_new_chunk(c)) {
17063012Sdes	case -1:
17163012Sdes	    c->error = 1;
17263012Sdes	    return -1;
17363012Sdes	case 0:
17463012Sdes	    c->eof = 1;
17563012Sdes	    return 0;
17637535Sdes	}
17737535Sdes    }
17863012Sdes
17963012Sdes    if (c->b_size < c->chunksize) {
18063012Sdes	char *tmp;
18163012Sdes
18263012Sdes	if ((tmp = realloc(c->buf, c->chunksize)) == NULL)
18363012Sdes	    return -1;
18463012Sdes	c->buf = tmp;
18563012Sdes	c->b_size = c->chunksize;
18663012Sdes    }
18763012Sdes
18863012Sdes    if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1)
18963012Sdes	return -1;
19063012Sdes    c->chunksize -= c->b_len;
19163012Sdes
19263012Sdes    if (c->chunksize == 0) {
19363012Sdes	char endl[2];
19463012Sdes	read(c->fd, endl, 2);
19563012Sdes    }
19663012Sdes
19763012Sdes    c->b_pos = 0;
19863012Sdes
19963012Sdes    return c->b_len;
20037535Sdes}
20137535Sdes
20237608Sdes/*
20337608Sdes * Read function
20437608Sdes */
20537535Sdesstatic int
20663012Sdes_http_readfn(void *v, char *buf, int len)
20737535Sdes{
20863012Sdes    struct cookie *c = (struct cookie *)v;
20963012Sdes    int l, pos;
21063012Sdes
21163012Sdes    if (c->error)
21263012Sdes	return -1;
21363012Sdes    if (c->eof)
21463012Sdes	return 0;
21563012Sdes
21663012Sdes    for (pos = 0; len > 0; pos += l, len -= l) {
21737535Sdes	/* empty buffer */
21863012Sdes	if (!c->buf || c->b_pos == c->b_len)
21963012Sdes	    if (_http_fillbuf(c) < 1)
22037535Sdes		break;
22163012Sdes	l = c->b_len - c->b_pos;
22263012Sdes	if (len < l)
22363012Sdes	    l = len;
22463012Sdes	bcopy(c->buf + c->b_pos, buf + pos, l);
22563012Sdes	c->b_pos += l;
22663012Sdes    }
22737535Sdes
22863012Sdes    if (!pos && c->error)
22937535Sdes	return -1;
23063012Sdes    return pos;
23137535Sdes}
23237535Sdes
23337608Sdes/*
23437608Sdes * Write function
23537608Sdes */
23637535Sdesstatic int
23763012Sdes_http_writefn(void *v, const char *buf, int len)
23837535Sdes{
23963012Sdes    struct cookie *c = (struct cookie *)v;
24063012Sdes
24163012Sdes    return write(c->fd, buf, len);
24237535Sdes}
24337535Sdes
24437608Sdes/*
24537608Sdes * Close function
24637608Sdes */
24737535Sdesstatic int
24863012Sdes_http_closefn(void *v)
24937535Sdes{
25063012Sdes    struct cookie *c = (struct cookie *)v;
25163012Sdes    int r;
25263012Sdes
25363012Sdes    r = close(c->fd);
25463012Sdes    if (c->buf)
25563012Sdes	free(c->buf);
25637535Sdes    free(c);
25763012Sdes    return r;
25837535Sdes}
25937535Sdes
26037608Sdes/*
26163012Sdes * Wrap a file descriptor up
26237608Sdes */
26363012Sdesstatic FILE *
26463012Sdes_http_funopen(int fd)
26537535Sdes{
26663012Sdes    struct cookie *c;
26763012Sdes    FILE *f;
26863012Sdes
26963012Sdes    if ((c = calloc(1, sizeof *c)) == NULL) {
27063012Sdes	_fetch_syserr();
27163012Sdes	return NULL;
27263012Sdes    }
27363012Sdes    c->fd = fd;
27463012Sdes    if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) {
27563012Sdes	_fetch_syserr();
27663012Sdes	free(c);
27763012Sdes	return NULL;
27863012Sdes    }
27963012Sdes    return f;
28063012Sdes}
28163012Sdes
28263012Sdes
28363012Sdes/*****************************************************************************
28463012Sdes * Helper functions for talking to the server and parsing its replies
28563012Sdes */
28663012Sdes
28763012Sdes/* Header types */
28863012Sdestypedef enum {
28963012Sdes    hdr_syserror = -2,
29063012Sdes    hdr_error = -1,
29163012Sdes    hdr_end = 0,
29263012Sdes    hdr_unknown = 1,
29363012Sdes    hdr_content_length,
29463012Sdes    hdr_content_range,
29563012Sdes    hdr_last_modified,
29663012Sdes    hdr_location,
29763012Sdes    hdr_transfer_encoding
29863012Sdes} hdr;
29963012Sdes
30063012Sdes/* Names of interesting headers */
30163012Sdesstatic struct {
30263012Sdes    hdr		 num;
30363012Sdes    char	*name;
30463012Sdes} hdr_names[] = {
30563012Sdes    { hdr_content_length,	"Content-Length" },
30663012Sdes    { hdr_content_range,	"Content-Range" },
30763012Sdes    { hdr_last_modified,	"Last-Modified" },
30863012Sdes    { hdr_location,		"Location" },
30963012Sdes    { hdr_transfer_encoding,	"Transfer-Encoding" },
31063012Sdes    { hdr_unknown,		NULL },
31163012Sdes};
31263012Sdes
31363012Sdesstatic char	*reply_buf;
31463012Sdesstatic size_t	 reply_size;
31563012Sdesstatic size_t	 reply_length;
31663012Sdes
31763012Sdes/*
31863012Sdes * Send a formatted line; optionally echo to terminal
31963012Sdes */
32063012Sdesstatic int
32163012Sdes_http_cmd(int fd, char *fmt, ...)
32263012Sdes{
32363012Sdes    va_list ap;
32463012Sdes    size_t len;
32563012Sdes    char *msg;
32663012Sdes    int r;
32763012Sdes
32863012Sdes    va_start(ap, fmt);
32963012Sdes    len = vasprintf(&msg, fmt, ap);
33063012Sdes    va_end(ap);
33163012Sdes
33263012Sdes    if (msg == NULL) {
33363012Sdes	errno = ENOMEM;
33463012Sdes	_fetch_syserr();
33563012Sdes	return -1;
33663012Sdes    }
33763012Sdes
33863012Sdes    r = _fetch_putln(fd, msg, len);
33963012Sdes    free(msg);
34063012Sdes
34163012Sdes    if (r == -1) {
34263012Sdes	_fetch_syserr();
34363012Sdes	return -1;
34463012Sdes    }
34563012Sdes
34663012Sdes    return 0;
34763012Sdes}
34863012Sdes
34963012Sdes/*
35063012Sdes * Get and parse status line
35163012Sdes */
35263012Sdesstatic int
35363012Sdes_http_get_reply(int fd)
35463012Sdes{
35563012Sdes    if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
35663012Sdes	return -1;
35737535Sdes    /*
35863012Sdes     * A valid status line looks like "HTTP/m.n xyz reason" where m
35963012Sdes     * and n are the major and minor protocol version numbers and xyz
36063012Sdes     * is the reply code.
36163012Sdes     * We grok HTTP 1.0 and 1.1, so m must be 1 and n must be 0 or 1.
36263012Sdes     * We don't care about the reason phrase.
36337535Sdes     */
36463012Sdes    if (strncmp(reply_buf, "HTTP/1.", 7) != 0
36563012Sdes	|| (reply_buf[7] != '0' && reply_buf[7] != '1') || reply_buf[8] != ' '
36663012Sdes	|| !isdigit(reply_buf[9])
36763012Sdes	|| !isdigit(reply_buf[10])
36863012Sdes	|| !isdigit(reply_buf[11]))
36963012Sdes	return HTTP_PROTOCOL_ERROR;
37063012Sdes
37163012Sdes    return ((reply_buf[9] - '0') * 100
37263012Sdes	    + (reply_buf[10] - '0') * 10
37363012Sdes	    + (reply_buf[11] - '0'));
37437535Sdes}
37537535Sdes
37637608Sdes/*
37763012Sdes * Check a header; if the type matches the given string, return a
37863012Sdes * pointer to the beginning of the value.
37963012Sdes */
38063012Sdesstatic char *
38163012Sdes_http_match(char *str, char *hdr)
38263012Sdes{
38363012Sdes    while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
38463012Sdes	/* nothing */;
38563012Sdes    if (*str || *hdr != ':')
38663012Sdes	return NULL;
38763012Sdes    while (*hdr && isspace(*++hdr))
38863012Sdes	/* nothing */;
38963012Sdes    return hdr;
39063012Sdes}
39163012Sdes
39263012Sdes/*
39363012Sdes * Get the next header and return the appropriate symbolic code.
39463012Sdes */
39563012Sdesstatic hdr
39663012Sdes_http_next_header(int fd, char **p)
39763012Sdes{
39863012Sdes    int i;
39963012Sdes
40063012Sdes    if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
40163012Sdes	return hdr_syserror;
40263012Sdes    while (reply_length && isspace(reply_buf[reply_length-1]))
40363012Sdes	reply_length--;
40463012Sdes    reply_buf[reply_length] = 0;
40563012Sdes    if (reply_length == 0)
40663012Sdes	return hdr_end;
40763012Sdes    /*
40863012Sdes     * We could check for malformed headers but we don't really care.
40963012Sdes     * A valid header starts with a token immediately followed by a
41063012Sdes     * colon; a token is any sequence of non-control, non-whitespace
41163012Sdes     * characters except "()<>@,;:\\\"{}".
41263012Sdes     */
41363012Sdes    for (i = 0; hdr_names[i].num != hdr_unknown; i++)
41463012Sdes	if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL)
41563012Sdes	    return hdr_names[i].num;
41663012Sdes    return hdr_unknown;
41763012Sdes}
41863012Sdes
41963012Sdes/*
42063012Sdes * Parse a last-modified header
42163012Sdes */
42263716Sdesstatic int
42363716Sdes_http_parse_mtime(char *p, time_t *mtime)
42463012Sdes{
42563716Sdes    char locale[64], *r;
42663012Sdes    struct tm tm;
42763012Sdes
42863012Sdes    strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale);
42963012Sdes    setlocale(LC_TIME, "C");
43063716Sdes    r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
43163012Sdes    /* XXX should add support for date-2 and date-3 */
43263012Sdes    setlocale(LC_TIME, locale);
43363716Sdes    if (r == NULL)
43463716Sdes	return -1;
43563012Sdes    DEBUG(fprintf(stderr, "last modified: [\033[1m%04d-%02d-%02d "
43663012Sdes		  "%02d:%02d:%02d\033[m]\n",
43763012Sdes		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
43863012Sdes		  tm.tm_hour, tm.tm_min, tm.tm_sec));
43963716Sdes    *mtime = timegm(&tm);
44063716Sdes    return 0;
44163012Sdes}
44263012Sdes
44363012Sdes/*
44463012Sdes * Parse a content-length header
44563012Sdes */
44663716Sdesstatic int
44763716Sdes_http_parse_length(char *p, size_t *length)
44863012Sdes{
44963716Sdes    size_t len;
45063012Sdes
45163012Sdes    for (len = 0; *p && isdigit(*p); ++p)
45263012Sdes	len = len * 10 + (*p - '0');
45363716Sdes    DEBUG(fprintf(stderr, "content length: [\033[1m%d\033[m]\n", len));
45463716Sdes    *length = len;
45563716Sdes    return 0;
45663012Sdes}
45763012Sdes
45863012Sdes/*
45963012Sdes * Parse a content-range header
46063012Sdes */
46163716Sdesstatic int
46263716Sdes_http_parse_range(char *p, off_t *offset, size_t *length, size_t *size)
46363012Sdes{
46463716Sdes    int first, last, len;
46563716Sdes
46663012Sdes    if (strncasecmp(p, "bytes ", 6) != 0)
46763012Sdes	return -1;
46863716Sdes    for (first = 0, p += 6; *p && isdigit(*p); ++p)
46963716Sdes	first = first * 10 + *p - '0';
47063012Sdes    if (*p != '-')
47163012Sdes	return -1;
47263716Sdes    for (last = 0, ++p; *p && isdigit(*p); ++p)
47363716Sdes	last = last * 10 + *p - '0';
47463716Sdes    if (first > last || *p != '/')
47563716Sdes	return -1;
47663716Sdes    for (len = 0, ++p; *p && isdigit(*p); ++p)
47763716Sdes	len = len * 10 + *p - '0';
47863716Sdes    if (len < last - first + 1)
47963716Sdes	return -1;
48063716Sdes    DEBUG(fprintf(stderr, "content range: [\033[1m%d-%d/%d\033[m]\n",
48163716Sdes		  first, last, len));
48263716Sdes    *offset = first;
48363716Sdes    *length = last - first + 1;
48463716Sdes    *size = len;
48563716Sdes    return 0;
48663012Sdes}
48763012Sdes
48863012Sdes
48963012Sdes/*****************************************************************************
49063012Sdes * Helper functions for authorization
49163012Sdes */
49263012Sdes
49363012Sdes/*
49437608Sdes * Base64 encoding
49537608Sdes */
49662965Sdesstatic char *
49762965Sdes_http_base64(char *src)
49837608Sdes{
49937608Sdes    static const char base64[] =
50037608Sdes	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
50137608Sdes	"abcdefghijklmnopqrstuvwxyz"
50237608Sdes	"0123456789+/";
50362965Sdes    char *str, *dst;
50462965Sdes    size_t l;
50562965Sdes    int t, r;
50662965Sdes
50762965Sdes    l = strlen(src);
50862965Sdes    if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
50962965Sdes	return NULL;
51062965Sdes    dst = str;
51162965Sdes    r = 0;
51237608Sdes
51337608Sdes    while (l >= 3) {
51437608Sdes	t = (src[0] << 16) | (src[1] << 8) | src[2];
51537608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
51637608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
51737608Sdes	dst[2] = base64[(t >> 6) & 0x3f];
51837608Sdes	dst[3] = base64[(t >> 0) & 0x3f];
51937608Sdes	src += 3; l -= 3;
52037608Sdes	dst += 4; r += 4;
52137608Sdes    }
52237608Sdes
52337608Sdes    switch (l) {
52437608Sdes    case 2:
52537608Sdes	t = (src[0] << 16) | (src[1] << 8);
52637608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
52737608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
52837608Sdes	dst[2] = base64[(t >> 6) & 0x3f];
52937608Sdes	dst[3] = '=';
53037608Sdes	dst += 4;
53137608Sdes	r += 4;
53237608Sdes	break;
53337608Sdes    case 1:
53437608Sdes	t = src[0] << 16;
53537608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
53637608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
53737608Sdes	dst[2] = dst[3] = '=';
53837608Sdes	dst += 4;
53937608Sdes	r += 4;
54037608Sdes	break;
54137608Sdes    case 0:
54237608Sdes	break;
54337608Sdes    }
54437608Sdes
54537608Sdes    *dst = 0;
54662965Sdes    return str;
54737608Sdes}
54837608Sdes
54937608Sdes/*
55037608Sdes * Encode username and password
55137608Sdes */
55262965Sdesstatic int
55363012Sdes_http_basic_auth(int fd, char *hdr, char *usr, char *pwd)
55437608Sdes{
55562965Sdes    char *upw, *auth;
55662965Sdes    int r;
55737608Sdes
55862965Sdes    if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
55962965Sdes	return -1;
56062965Sdes    auth = _http_base64(upw);
56162965Sdes    free(upw);
56262965Sdes    if (auth == NULL)
56362965Sdes	return -1;
56463012Sdes    r = _http_cmd(fd, "%s: Basic %s", hdr, auth);
56562965Sdes    free(auth);
56662965Sdes    return r;
56762965Sdes}
56862965Sdes
56962965Sdes/*
57062965Sdes * Send an authorization header
57162965Sdes */
57262965Sdesstatic int
57363012Sdes_http_authorize(int fd, char *hdr, char *p)
57462965Sdes{
57562965Sdes    /* basic authorization */
57662965Sdes    if (strncasecmp(p, "basic:", 6) == 0) {
57762965Sdes	char *user, *pwd, *str;
57862965Sdes	int r;
57962965Sdes
58062965Sdes	/* skip realm */
58162965Sdes	for (p += 6; *p && *p != ':'; ++p)
58262965Sdes	    /* nothing */ ;
58362965Sdes	if (!*p || strchr(++p, ':') == NULL)
58462965Sdes	    return -1;
58562965Sdes	if ((str = strdup(p)) == NULL)
58662965Sdes	    return -1; /* XXX */
58762965Sdes	user = str;
58862965Sdes	pwd = strchr(str, ':');
58962965Sdes	*pwd++ = '\0';
59063012Sdes	r = _http_basic_auth(fd, hdr, user, pwd);
59162965Sdes	free(str);
59262965Sdes	return r;
59362811Sdes    }
59462965Sdes    return -1;
59537608Sdes}
59637608Sdes
59763012Sdes
59863012Sdes/*****************************************************************************
59963012Sdes * Helper functions for connecting to a server or proxy
60063012Sdes */
60163012Sdes
60237608Sdes/*
60363012Sdes * Connect to the specified HTTP proxy server.
60437608Sdes */
60563012Sdesstatic int
60663012Sdes_http_proxy_connect(char *proxy, int af, int verbose)
60737535Sdes{
60863012Sdes    char *hostname, *p;
60963012Sdes    int fd, port;
61063012Sdes
61163012Sdes    /* get hostname */
61263012Sdes    hostname = NULL;
61360737Sume#ifdef INET6
61463012Sdes    /* host part can be an IPv6 address enclosed in square brackets */
61563012Sdes    if (*proxy == '[') {
61663012Sdes	if ((p = strchr(proxy, ']')) == NULL) {
61763012Sdes	    /* no terminating bracket */
61863012Sdes	    /* XXX should set an error code */
61963012Sdes	    goto ouch;
62063012Sdes	}
62163012Sdes	if (p[1] != '\0' && p[1] != ':') {
62263012Sdes	    /* garbage after address */
62363012Sdes	    /* XXX should set an error code */
62463012Sdes	    goto ouch;
62563012Sdes	}
62663012Sdes	if ((hostname = malloc(p - proxy)) == NULL) {
62763012Sdes	    errno = ENOMEM;
62863012Sdes	    _fetch_syserr();
62963012Sdes	    goto ouch;
63063012Sdes	}
63163012Sdes	strncpy(hostname, proxy + 1, p - proxy - 1);
63263012Sdes	hostname[p - proxy - 1] = '\0';
63363012Sdes	++p;
63463012Sdes    } else {
63563012Sdes#endif /* INET6 */
63663012Sdes	if ((p = strchr(proxy, ':')) == NULL)
63763012Sdes	    p = strchr(proxy, '\0');
63863012Sdes	if ((hostname = malloc(p - proxy + 1)) == NULL) {
63963012Sdes	    errno = ENOMEM;
64063012Sdes	    _fetch_syserr();
64163012Sdes	    goto ouch;
64263012Sdes	}
64363012Sdes	strncpy(hostname, proxy, p - proxy);
64463012Sdes	hostname[p - proxy] = '\0';
64563012Sdes#ifdef INET6
64663012Sdes    }
64763012Sdes#endif /* INET6 */
64863012Sdes    DEBUG(fprintf(stderr, "proxy name: [%s]\n", hostname));
64963012Sdes
65063012Sdes    /* get port number */
65163012Sdes    port = 0;
65263012Sdes    if (*p == ':') {
65363012Sdes	++p;
65463012Sdes	if (strspn(p, "0123456789") != strlen(p) || strlen(p) > 5) {
65563012Sdes	    /* port number is non-numeric or too long */
65663012Sdes	    /* XXX should set an error code */
65763012Sdes	    goto ouch;
65863012Sdes	}
65963012Sdes	port = atoi(p);
66063012Sdes	if (port < 1 || port > 65535) {
66163012Sdes	    /* port number is out of range */
66263012Sdes	    /* XXX should set an error code */
66363012Sdes	    goto ouch;
66463012Sdes	}
66563012Sdes    }
66663012Sdes
66763012Sdes    if (!port) {
66863012Sdes#if 0
66963012Sdes	/*
67063012Sdes	 * commented out, since there is currently no service name
67163012Sdes	 * for HTTP proxies
67263012Sdes	 */
67363012Sdes	struct servent *se;
67463012Sdes
67563012Sdes	if ((se = getservbyname("xxxx", "tcp")) != NULL)
67663012Sdes	    port = ntohs(se->s_port);
67763012Sdes	else
67863012Sdes#endif
67963012Sdes	    port = 3128;
68063012Sdes    }
68163012Sdes    DEBUG(fprintf(stderr, "proxy port: %d\n", port));
68263012Sdes
68363012Sdes    /* connect */
68463012Sdes    if ((fd = _fetch_connect(hostname, port, af, verbose)) == -1)
68563012Sdes	_fetch_syserr();
68663012Sdes    return fd;
68763012Sdes
68863012Sdes ouch:
68963012Sdes    if (hostname)
69063012Sdes	free(hostname);
69163012Sdes    return -1;
69263012Sdes}
69363012Sdes
69463012Sdes/*
69563012Sdes * Connect to the correct HTTP server or proxy.
69663012Sdes */
69763012Sdesstatic int
69863012Sdes_http_connect(struct url *URL, int *proxy, char *flags)
69963012Sdes{
70063012Sdes    int direct, verbose;
70163012Sdes    int af, fd;
70263012Sdes    char *p;
70363012Sdes
70463012Sdes#ifdef INET6
70563012Sdes    af = AF_UNSPEC;
70660737Sume#else
70763012Sdes    af = AF_INET;
70860737Sume#endif
70963012Sdes
71055544Sdes    direct = (flags && strchr(flags, 'd'));
71155544Sdes    verbose = (flags && strchr(flags, 'v'));
71263012Sdes    if (flags && strchr(flags, '4'))
71360737Sume	af = AF_INET;
71463012Sdes    else if (flags && strchr(flags, '6'))
71560737Sume	af = AF_INET6;
71641862Sdes
71737535Sdes    /* check port */
71860189Sdes    if (!URL->port) {
71960189Sdes	struct servent *se;
72060189Sdes
72163012Sdes	/* Scheme can be ftp if we're using a proxy */
72260587Sume	if (strcasecmp(URL->scheme, "ftp") == 0)
72360587Sume	    if ((se = getservbyname("ftp", "tcp")) != NULL)
72460587Sume		URL->port = ntohs(se->s_port);
72560587Sume	    else
72660587Sume		URL->port = 21;
72760189Sdes	else
72860587Sume	    if ((se = getservbyname("http", "tcp")) != NULL)
72960587Sume		URL->port = ntohs(se->s_port);
73060587Sume	    else
73160587Sume		URL->port = 80;
73260189Sdes    }
73337535Sdes
73463716Sdes    if (!direct && (p = getenv("HTTP_PROXY")) != NULL && *p != '\0') {
73563012Sdes	/* attempt to connect to proxy server */
73663012Sdes	if ((fd = _http_proxy_connect(p, af, verbose)) == -1)
73763012Sdes	    return -1;
73863012Sdes	*proxy = 1;
73963012Sdes    } else {
74063012Sdes	/* if no proxy is configured, try direct */
74163012Sdes	if (strcasecmp(URL->scheme, "ftp") == 0) {
74263012Sdes	    /* can't talk http to an ftp server */
74363012Sdes	    /* XXX should set an error code */
74463012Sdes	    return -1;
74560189Sdes	}
74663012Sdes	if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1)
74763012Sdes	    /* _fetch_connect() has already set an error code */
74863012Sdes	    return -1;
74963012Sdes	*proxy = 0;
75037535Sdes    }
75137535Sdes
75263012Sdes    return fd;
75360376Sdes}
75460376Sdes
75563012Sdes
75663012Sdes/*****************************************************************************
75763012Sdes * Core
75860954Sdes */
75960954Sdes
76060954Sdes/*
76163012Sdes * Send a request and process the reply
76260376Sdes */
76363012Sdesstatic FILE *
76463012Sdes_http_request(struct url *URL, char *op, struct url_stat *us, char *flags)
76560376Sdes{
76663012Sdes    struct url *url, *new;
76763012Sdes    int chunked, need_auth, noredirect, proxy, verbose;
76863012Sdes    int code, fd, i, n;
76963012Sdes    off_t offset;
77063716Sdes    size_t clength, length, size;
77163716Sdes    time_t mtime;
77263012Sdes    char *p;
77363012Sdes    FILE *f;
77463012Sdes    hdr h;
77560737Sume    char *host;
77660737Sume#ifdef INET6
77760737Sume    char hbuf[MAXHOSTNAMELEN + 1];
77860737Sume#endif
77963012Sdes
78063012Sdes    noredirect = (flags && strchr(flags, 'A'));
78160376Sdes    verbose = (flags && strchr(flags, 'v'));
78260737Sume
78363716Sdes    /* try the provided URL first */
78463716Sdes    url = URL;
78563716Sdes
78663716Sdes    /* if the A flag is set, we only get one try */
78763012Sdes    n = noredirect ? 1 : MAX_REDIRECT;
78863716Sdes    i = 0;
78963012Sdes
79063716Sdes    do {
79163069Sdes	new = NULL;
79263069Sdes	chunked = 0;
79363012Sdes	need_auth = 0;
79463069Sdes	offset = 0;
79563716Sdes	clength = -1;
79663716Sdes	length = -1;
79763716Sdes	size = -1;
79863716Sdes	mtime = 0;
79963012Sdes    retry:
80063012Sdes	/* connect to server or proxy */
80163012Sdes	if ((fd = _http_connect(url, &proxy, flags)) == -1)
80263012Sdes	    goto ouch;
80363012Sdes
80463012Sdes	host = url->host;
80560737Sume#ifdef INET6
80663012Sdes	if (strchr(url->host, ':')) {
80763012Sdes	    snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
80863012Sdes	    host = hbuf;
80963012Sdes	}
81060737Sume#endif
81137535Sdes
81263012Sdes	/* send request */
81363012Sdes	if (verbose)
81463012Sdes	    _fetch_info("requesting %s://%s:%d%s",
81563012Sdes			url->scheme, host, url->port, url->doc);
81663012Sdes	if (proxy) {
81763012Sdes	    _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1",
81863012Sdes		      op, url->scheme, host, url->port, url->doc);
81963012Sdes	} else {
82063012Sdes	    _http_cmd(fd, "%s %s HTTP/1.1",
82163012Sdes		      op, url->doc);
82263012Sdes	}
82337535Sdes
82463012Sdes	/* proxy authorization */
82563716Sdes	if (proxy && (p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
82663012Sdes	    _http_authorize(fd, "Proxy-Authorization", p);
82763012Sdes
82863012Sdes	/* server authorization */
82963012Sdes	if (need_auth) {
83063012Sdes	    if (*url->user || *url->pwd)
83163012Sdes		_http_basic_auth(fd, "Authorization",
83263012Sdes				 url->user ? url->user : "",
83363012Sdes				 url->pwd ? url->pwd : "");
83463716Sdes	    else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
83563012Sdes		_http_authorize(fd, "Authorization", p);
83663012Sdes	    else {
83763012Sdes		_http_seterr(HTTP_NEED_AUTH);
83863012Sdes		goto ouch;
83963012Sdes	    }
84063012Sdes	}
84160376Sdes
84263012Sdes	/* other headers */
84363012Sdes	_http_cmd(fd, "Host: %s:%d", host, url->port);
84463012Sdes	_http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname);
84563567Sdes	if (url->offset)
84663012Sdes	    _http_cmd(fd, "Range: bytes=%lld-", url->offset);
84763012Sdes	_http_cmd(fd, "Connection: close");
84863012Sdes	_http_cmd(fd, "");
84960376Sdes
85063012Sdes	/* get reply */
85163012Sdes	switch ((code = _http_get_reply(fd))) {
85263012Sdes	case HTTP_OK:
85363012Sdes	case HTTP_PARTIAL:
85463012Sdes	    /* fine */
85563012Sdes	    break;
85663012Sdes	case HTTP_MOVED_PERM:
85763012Sdes	case HTTP_MOVED_TEMP:
85863012Sdes	    /*
85963012Sdes	     * Not so fine, but we still have to read the headers to
86063012Sdes	     * get the new location.
86163012Sdes	     */
86263012Sdes	    break;
86363012Sdes	case HTTP_NEED_AUTH:
86463012Sdes	    if (need_auth) {
86563012Sdes		/*
86663012Sdes		 * We already sent out authorization code, so there's
86763012Sdes		 * nothing more we can do.
86863012Sdes		 */
86963012Sdes		_http_seterr(code);
87063012Sdes		goto ouch;
87163012Sdes	    }
87263012Sdes	    /* try again, but send the password this time */
87363012Sdes	    if (verbose)
87463012Sdes		_fetch_info("server requires authorization");
87563012Sdes	    need_auth = 1;
87663012Sdes	    close(fd);
87763012Sdes	    goto retry;
87863012Sdes	case HTTP_NEED_PROXY_AUTH:
87963012Sdes	    /*
88063012Sdes	     * If we're talking to a proxy, we already sent our proxy
88163012Sdes	     * authorization code, so there's nothing more we can do.
88263012Sdes	     */
88363012Sdes	    _http_seterr(code);
88463012Sdes	    goto ouch;
88563012Sdes	case HTTP_PROTOCOL_ERROR:
88663012Sdes	    /* fall through */
88763012Sdes	case -1:
88863012Sdes	    _fetch_syserr();
88963012Sdes	    goto ouch;
89063012Sdes	default:
89163012Sdes	    _http_seterr(code);
89263012Sdes	    goto ouch;
89363012Sdes	}
89463012Sdes
89563012Sdes	/* get headers */
89663012Sdes	do {
89763012Sdes	    switch ((h = _http_next_header(fd, &p))) {
89863012Sdes	    case hdr_syserror:
89963012Sdes		_fetch_syserr();
90063012Sdes		goto ouch;
90163012Sdes	    case hdr_error:
90263012Sdes		_http_seterr(HTTP_PROTOCOL_ERROR);
90363012Sdes		goto ouch;
90463012Sdes	    case hdr_content_length:
90563716Sdes		_http_parse_length(p, &clength);
90663012Sdes		break;
90763012Sdes	    case hdr_content_range:
90863716Sdes		_http_parse_range(p, &offset, &length, &size);
90963012Sdes		break;
91063012Sdes	    case hdr_last_modified:
91163716Sdes		_http_parse_mtime(p, &mtime);
91263012Sdes		break;
91363012Sdes	    case hdr_location:
91463012Sdes		if (!HTTP_REDIRECT(code))
91563012Sdes		    break;
91663069Sdes		if (new)
91763069Sdes		    free(new);
91863012Sdes		if (verbose)
91963012Sdes		    _fetch_info("%d redirect to %s", code, p);
92063069Sdes		if (*p == '/')
92163069Sdes		    /* absolute path */
92263069Sdes		    new = fetchMakeURL(url->scheme, url->host, url->port, p,
92363069Sdes				       url->user, url->pwd);
92463069Sdes		else
92563069Sdes		    new = fetchParseURL(p);
92663069Sdes		if (new == NULL) {
92763069Sdes		    /* XXX should set an error code */
92863069Sdes		    DEBUG(fprintf(stderr, "failed to parse new URL\n"));
92963012Sdes		    goto ouch;
93063069Sdes		}
93163012Sdes		if (!*new->user && !*new->pwd) {
93263012Sdes		    strcpy(new->user, url->user);
93363012Sdes		    strcpy(new->pwd, url->pwd);
93463012Sdes		}
93563012Sdes		new->offset = url->offset;
93663012Sdes		new->length = url->length;
93763069Sdes		break;
93863012Sdes	    case hdr_transfer_encoding:
93963012Sdes		/* XXX weak test*/
94063012Sdes		chunked = (strcasecmp(p, "chunked") == 0);
94163012Sdes		break;
94263012Sdes	    case hdr_end:
94363012Sdes		/* fall through */
94463012Sdes	    case hdr_unknown:
94563012Sdes		/* ignore */
94663012Sdes		break;
94763012Sdes	    }
94863012Sdes	} while (h > hdr_end);
94960376Sdes
95063069Sdes	/* we either have a hit, or a redirect with no Location: header */
95163069Sdes	if (code == HTTP_OK || code == HTTP_PARTIAL || !new)
95263012Sdes	    break;
95363069Sdes
95463069Sdes	/* we have a redirect */
95563069Sdes	close(fd);
95663337Sdes	fd = -1;
95763069Sdes	if (url != URL)
95863069Sdes	    fetchFreeURL(url);
95963069Sdes	url = new;
96063716Sdes    } while (++i < n);
96160376Sdes
96263012Sdes    /* no success */
96363012Sdes    if (fd == -1) {
96463012Sdes	_http_seterr(code);
96563012Sdes	goto ouch;
96637571Sdes    }
96737535Sdes
96863716Sdes    DEBUG(fprintf(stderr, "offset: %lld, length: %d, size: %d, clength: %d\n",
96963716Sdes		  offset, length, size, clength));
97063716Sdes
97163716Sdes    /* check for inconsistencies */
97263716Sdes    if (clength != -1 && length != -1 && clength != length) {
97363716Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
97463716Sdes	goto ouch;
97563716Sdes    }
97663716Sdes    if (clength == -1)
97763716Sdes	clength = length;
97863716Sdes    if (clength != -1)
97963716Sdes	length = offset + clength;
98063716Sdes    if (length != -1 && size != -1 && length != size) {
98163716Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
98263716Sdes	goto ouch;
98363716Sdes    }
98463716Sdes    if (size == -1)
98563716Sdes	size = length;
98663716Sdes
98763716Sdes    /* fill in stats */
98863716Sdes    if (us) {
98963716Sdes	us->size = size;
99063716Sdes	us->atime = us->mtime = mtime;
99163716Sdes    }
99263716Sdes
99363567Sdes    /* too far? */
99463716Sdes    if (offset > URL->offset) {
99563567Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
99663567Sdes	goto ouch;
99763567Sdes    }
99863567Sdes
99963716Sdes    /* report back real offset and size */
100063567Sdes    URL->offset = offset;
100163716Sdes    URL->length = clength;
100263567Sdes
100363012Sdes    /* wrap it up in a FILE */
100463012Sdes    if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) {
100563012Sdes	_fetch_syserr();
100663012Sdes	goto ouch;
100763012Sdes    }
100863012Sdes
100963012Sdes    if (url != URL)
101063012Sdes	fetchFreeURL(url);
101163012Sdes
101263012Sdes    return f;
101337535Sdes
101463012Sdes ouch:
101563012Sdes    if (url != URL)
101663012Sdes	fetchFreeURL(url);
101763012Sdes    if (fd != -1)
101863012Sdes	close(fd);
101963012Sdes    return NULL;
102063012Sdes}
102160189Sdes
102263012Sdes
102363012Sdes/*****************************************************************************
102463012Sdes * Entry points
102563012Sdes */
102663012Sdes
102763012Sdes/*
102863340Sdes * Retrieve and stat a file by HTTP
102963340Sdes */
103063340SdesFILE *
103163340SdesfetchXGetHTTP(struct url *URL, struct url_stat *us, char *flags)
103263340Sdes{
103363340Sdes    return _http_request(URL, "GET", us, flags);
103463340Sdes}
103563340Sdes
103663340Sdes/*
103763012Sdes * Retrieve a file by HTTP
103863012Sdes */
103963012SdesFILE *
104063012SdesfetchGetHTTP(struct url *URL, char *flags)
104163012Sdes{
104263340Sdes    return fetchXGetHTTP(URL, NULL, flags);
104337535Sdes}
104437535Sdes
104563340Sdes/*
104663340Sdes * Store a file by HTTP
104763340Sdes */
104837535SdesFILE *
104940975SdesfetchPutHTTP(struct url *URL, char *flags)
105037535Sdes{
105137535Sdes    warnx("fetchPutHTTP(): not implemented");
105237535Sdes    return NULL;
105337535Sdes}
105440975Sdes
105540975Sdes/*
105640975Sdes * Get an HTTP document's metadata
105740975Sdes */
105840975Sdesint
105960376SdesfetchStatHTTP(struct url *URL, struct url_stat *us, char *flags)
106040975Sdes{
106160376Sdes    FILE *f;
106260376Sdes
106363012Sdes    if ((f = _http_request(URL, "HEAD", us, flags)) == NULL)
106460376Sdes	return -1;
106560581Sdes    fclose(f);
106660376Sdes    return 0;
106740975Sdes}
106841989Sdes
106941989Sdes/*
107041989Sdes * List a directory
107141989Sdes */
107241989Sdesstruct url_ent *
107341989SdesfetchListHTTP(struct url *url, char *flags)
107441989Sdes{
107541989Sdes    warnx("fetchListHTTP(): not implemented");
107641989Sdes    return NULL;
107741989Sdes}
1078