http.c revision 67043
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 67043 2000-10-12 22:10:26Z 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{
35566325Sdes    char *p;
35666325Sdes
35763012Sdes    if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
35863012Sdes	return -1;
35937535Sdes    /*
36063012Sdes     * A valid status line looks like "HTTP/m.n xyz reason" where m
36163012Sdes     * and n are the major and minor protocol version numbers and xyz
36263012Sdes     * is the reply code.
36366325Sdes     * Unfortunately, there are servers out there (NCSA 1.5.1, to name
36466325Sdes     * just one) that do not send a version number, so we can't rely
36566325Sdes     * on finding one, but if we do, insist on it being 1.0 or 1.1.
36663012Sdes     * We don't care about the reason phrase.
36737535Sdes     */
36866325Sdes    if (strncmp(reply_buf, "HTTP", 4) != 0)
36963012Sdes	return HTTP_PROTOCOL_ERROR;
37066325Sdes    p = reply_buf + 4;
37166325Sdes    if (*p == '/') {
37266325Sdes	if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
37366325Sdes	    return HTTP_PROTOCOL_ERROR;
37466325Sdes	p += 4;
37566325Sdes    }
37666325Sdes    if (*p != ' '
37766325Sdes	|| !isdigit(p[1])
37866325Sdes	|| !isdigit(p[2])
37966325Sdes	|| !isdigit(p[3]))
38066325Sdes	return HTTP_PROTOCOL_ERROR;
38163012Sdes
38266325Sdes    return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'));
38337535Sdes}
38437535Sdes
38537608Sdes/*
38663012Sdes * Check a header; if the type matches the given string, return a
38763012Sdes * pointer to the beginning of the value.
38863012Sdes */
38963012Sdesstatic char *
39063012Sdes_http_match(char *str, char *hdr)
39163012Sdes{
39263012Sdes    while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
39363012Sdes	/* nothing */;
39463012Sdes    if (*str || *hdr != ':')
39563012Sdes	return NULL;
39663012Sdes    while (*hdr && isspace(*++hdr))
39763012Sdes	/* nothing */;
39863012Sdes    return hdr;
39963012Sdes}
40063012Sdes
40163012Sdes/*
40263012Sdes * Get the next header and return the appropriate symbolic code.
40363012Sdes */
40463012Sdesstatic hdr
40563012Sdes_http_next_header(int fd, char **p)
40663012Sdes{
40763012Sdes    int i;
40863012Sdes
40963012Sdes    if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
41063012Sdes	return hdr_syserror;
41163012Sdes    while (reply_length && isspace(reply_buf[reply_length-1]))
41263012Sdes	reply_length--;
41363012Sdes    reply_buf[reply_length] = 0;
41463012Sdes    if (reply_length == 0)
41563012Sdes	return hdr_end;
41663012Sdes    /*
41763012Sdes     * We could check for malformed headers but we don't really care.
41863012Sdes     * A valid header starts with a token immediately followed by a
41963012Sdes     * colon; a token is any sequence of non-control, non-whitespace
42063012Sdes     * characters except "()<>@,;:\\\"{}".
42163012Sdes     */
42263012Sdes    for (i = 0; hdr_names[i].num != hdr_unknown; i++)
42363012Sdes	if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL)
42463012Sdes	    return hdr_names[i].num;
42563012Sdes    return hdr_unknown;
42663012Sdes}
42763012Sdes
42863012Sdes/*
42963012Sdes * Parse a last-modified header
43063012Sdes */
43163716Sdesstatic int
43263716Sdes_http_parse_mtime(char *p, time_t *mtime)
43363012Sdes{
43463716Sdes    char locale[64], *r;
43563012Sdes    struct tm tm;
43663012Sdes
43763012Sdes    strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale);
43863012Sdes    setlocale(LC_TIME, "C");
43963716Sdes    r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
44063012Sdes    /* XXX should add support for date-2 and date-3 */
44163012Sdes    setlocale(LC_TIME, locale);
44263716Sdes    if (r == NULL)
44363716Sdes	return -1;
44463012Sdes    DEBUG(fprintf(stderr, "last modified: [\033[1m%04d-%02d-%02d "
44563012Sdes		  "%02d:%02d:%02d\033[m]\n",
44663012Sdes		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
44763012Sdes		  tm.tm_hour, tm.tm_min, tm.tm_sec));
44863716Sdes    *mtime = timegm(&tm);
44963716Sdes    return 0;
45063012Sdes}
45163012Sdes
45263012Sdes/*
45363012Sdes * Parse a content-length header
45463012Sdes */
45563716Sdesstatic int
45664129Sdes_http_parse_length(char *p, off_t *length)
45763012Sdes{
45864129Sdes    off_t len;
45963012Sdes
46063012Sdes    for (len = 0; *p && isdigit(*p); ++p)
46163012Sdes	len = len * 10 + (*p - '0');
46264129Sdes    DEBUG(fprintf(stderr, "content length: [\033[1m%lld\033[m]\n", len));
46363716Sdes    *length = len;
46463716Sdes    return 0;
46563012Sdes}
46663012Sdes
46763012Sdes/*
46863012Sdes * Parse a content-range header
46963012Sdes */
47063716Sdesstatic int
47164129Sdes_http_parse_range(char *p, off_t *offset, off_t *length, off_t *size)
47263012Sdes{
47363716Sdes    int first, last, len;
47463716Sdes
47563012Sdes    if (strncasecmp(p, "bytes ", 6) != 0)
47663012Sdes	return -1;
47763716Sdes    for (first = 0, p += 6; *p && isdigit(*p); ++p)
47863716Sdes	first = first * 10 + *p - '0';
47963012Sdes    if (*p != '-')
48063012Sdes	return -1;
48163716Sdes    for (last = 0, ++p; *p && isdigit(*p); ++p)
48263716Sdes	last = last * 10 + *p - '0';
48363716Sdes    if (first > last || *p != '/')
48463716Sdes	return -1;
48563716Sdes    for (len = 0, ++p; *p && isdigit(*p); ++p)
48663716Sdes	len = len * 10 + *p - '0';
48763716Sdes    if (len < last - first + 1)
48863716Sdes	return -1;
48963716Sdes    DEBUG(fprintf(stderr, "content range: [\033[1m%d-%d/%d\033[m]\n",
49063716Sdes		  first, last, len));
49163716Sdes    *offset = first;
49263716Sdes    *length = last - first + 1;
49363716Sdes    *size = len;
49463716Sdes    return 0;
49563012Sdes}
49663012Sdes
49763012Sdes
49863012Sdes/*****************************************************************************
49963012Sdes * Helper functions for authorization
50063012Sdes */
50163012Sdes
50263012Sdes/*
50337608Sdes * Base64 encoding
50437608Sdes */
50562965Sdesstatic char *
50662965Sdes_http_base64(char *src)
50737608Sdes{
50837608Sdes    static const char base64[] =
50937608Sdes	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
51037608Sdes	"abcdefghijklmnopqrstuvwxyz"
51137608Sdes	"0123456789+/";
51262965Sdes    char *str, *dst;
51362965Sdes    size_t l;
51462965Sdes    int t, r;
51562965Sdes
51662965Sdes    l = strlen(src);
51762965Sdes    if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
51862965Sdes	return NULL;
51962965Sdes    dst = str;
52062965Sdes    r = 0;
52137608Sdes
52237608Sdes    while (l >= 3) {
52337608Sdes	t = (src[0] << 16) | (src[1] << 8) | src[2];
52437608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
52537608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
52637608Sdes	dst[2] = base64[(t >> 6) & 0x3f];
52737608Sdes	dst[3] = base64[(t >> 0) & 0x3f];
52837608Sdes	src += 3; l -= 3;
52937608Sdes	dst += 4; r += 4;
53037608Sdes    }
53137608Sdes
53237608Sdes    switch (l) {
53337608Sdes    case 2:
53437608Sdes	t = (src[0] << 16) | (src[1] << 8);
53537608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
53637608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
53737608Sdes	dst[2] = base64[(t >> 6) & 0x3f];
53837608Sdes	dst[3] = '=';
53937608Sdes	dst += 4;
54037608Sdes	r += 4;
54137608Sdes	break;
54237608Sdes    case 1:
54337608Sdes	t = src[0] << 16;
54437608Sdes	dst[0] = base64[(t >> 18) & 0x3f];
54537608Sdes	dst[1] = base64[(t >> 12) & 0x3f];
54637608Sdes	dst[2] = dst[3] = '=';
54737608Sdes	dst += 4;
54837608Sdes	r += 4;
54937608Sdes	break;
55037608Sdes    case 0:
55137608Sdes	break;
55237608Sdes    }
55337608Sdes
55437608Sdes    *dst = 0;
55562965Sdes    return str;
55637608Sdes}
55737608Sdes
55837608Sdes/*
55937608Sdes * Encode username and password
56037608Sdes */
56162965Sdesstatic int
56263012Sdes_http_basic_auth(int fd, char *hdr, char *usr, char *pwd)
56337608Sdes{
56462965Sdes    char *upw, *auth;
56562965Sdes    int r;
56637608Sdes
56762965Sdes    if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
56862965Sdes	return -1;
56962965Sdes    auth = _http_base64(upw);
57062965Sdes    free(upw);
57162965Sdes    if (auth == NULL)
57262965Sdes	return -1;
57363012Sdes    r = _http_cmd(fd, "%s: Basic %s", hdr, auth);
57462965Sdes    free(auth);
57562965Sdes    return r;
57662965Sdes}
57762965Sdes
57862965Sdes/*
57962965Sdes * Send an authorization header
58062965Sdes */
58162965Sdesstatic int
58263012Sdes_http_authorize(int fd, char *hdr, char *p)
58362965Sdes{
58462965Sdes    /* basic authorization */
58562965Sdes    if (strncasecmp(p, "basic:", 6) == 0) {
58662965Sdes	char *user, *pwd, *str;
58762965Sdes	int r;
58862965Sdes
58962965Sdes	/* skip realm */
59062965Sdes	for (p += 6; *p && *p != ':'; ++p)
59162965Sdes	    /* nothing */ ;
59262965Sdes	if (!*p || strchr(++p, ':') == NULL)
59362965Sdes	    return -1;
59462965Sdes	if ((str = strdup(p)) == NULL)
59562965Sdes	    return -1; /* XXX */
59662965Sdes	user = str;
59762965Sdes	pwd = strchr(str, ':');
59862965Sdes	*pwd++ = '\0';
59963012Sdes	r = _http_basic_auth(fd, hdr, user, pwd);
60062965Sdes	free(str);
60162965Sdes	return r;
60262811Sdes    }
60362965Sdes    return -1;
60437608Sdes}
60537608Sdes
60663012Sdes
60763012Sdes/*****************************************************************************
60863012Sdes * Helper functions for connecting to a server or proxy
60963012Sdes */
61063012Sdes
61137608Sdes/*
61263842Sdes * Return the default port for this scheme
61363842Sdes */
61463842Sdesstatic int
61563842Sdes_http_default_port(char *scheme)
61663842Sdes{
61763842Sdes    struct servent *se;
61863842Sdes
61963842Sdes    if ((se = getservbyname(scheme, "tcp")) != NULL)
62063842Sdes	return ntohs(se->s_port);
62167043Sdes    if (strcasecmp(scheme, SCHEME_FTP) == 0)
62263842Sdes	return FTP_DEFAULT_PORT;
62367043Sdes    if (strcasecmp(scheme, SCHEME_HTTP) == 0)
62463842Sdes	return HTTP_DEFAULT_PORT;
62563842Sdes    return 0;
62663842Sdes}
62763842Sdes
62863842Sdes/*
62963012Sdes * Connect to the correct HTTP server or proxy.
63063012Sdes */
63163012Sdesstatic int
63267043Sdes_http_connect(struct url *URL, struct url *purl, char *flags)
63363012Sdes{
63467043Sdes    int verbose;
63563012Sdes    int af, fd;
63663012Sdes
63763012Sdes#ifdef INET6
63863012Sdes    af = AF_UNSPEC;
63960737Sume#else
64063012Sdes    af = AF_INET;
64160737Sume#endif
64267043Sdes
64355544Sdes    verbose = (flags && strchr(flags, 'v'));
64463012Sdes    if (flags && strchr(flags, '4'))
64560737Sume	af = AF_INET;
64667043Sdes#ifdef INET6
64763012Sdes    else if (flags && strchr(flags, '6'))
64860737Sume	af = AF_INET6;
64967043Sdes#endif
65067043Sdes
65167043Sdes    if (purl) {
65267043Sdes	URL = purl;
65367043Sdes    } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
65467043Sdes	/* can't talk http to an ftp server */
65567043Sdes	/* XXX should set an error code */
65667043Sdes	return -1;
65767043Sdes    }
65841862Sdes
65967043Sdes    if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1)
66067043Sdes	/* _fetch_connect() has already set an error code */
66167043Sdes	return -1;
66267043Sdes    return fd;
66367043Sdes}
66467043Sdes
66567043Sdesstatic struct url *
66667043Sdes_http_get_proxy()
66767043Sdes{
66867043Sdes    struct url *purl;
66967043Sdes    char *p;
67037535Sdes
67167043Sdes    if ((p = getenv("HTTP_PROXY")) && (purl = fetchParseURL(p))) {
67267043Sdes	if (!*purl->scheme)
67367043Sdes	    strcpy(purl->scheme, SCHEME_HTTP);
67467043Sdes	if (!purl->port)
67567043Sdes	    purl->port = _http_default_port(SCHEME_HTTP);
67667043Sdes	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
67767043Sdes	    return purl;
67867043Sdes	fetchFreeURL(purl);
67937535Sdes    }
68067043Sdes    return NULL;
68160376Sdes}
68260376Sdes
68363012Sdes
68463012Sdes/*****************************************************************************
68563012Sdes * Core
68660954Sdes */
68760954Sdes
68860954Sdes/*
68963012Sdes * Send a request and process the reply
69060376Sdes */
69167043SdesFILE *
69267043Sdes_http_request(struct url *URL, char *op, struct url_stat *us,
69367043Sdes	      struct url *purl, char *flags)
69460376Sdes{
69563012Sdes    struct url *url, *new;
69667043Sdes    int chunked, direct, need_auth, noredirect, verbose;
69763012Sdes    int code, fd, i, n;
69864129Sdes    off_t offset, clength, length, size;
69963716Sdes    time_t mtime;
70063012Sdes    char *p;
70163012Sdes    FILE *f;
70263012Sdes    hdr h;
70360737Sume    char *host;
70460737Sume#ifdef INET6
70560737Sume    char hbuf[MAXHOSTNAMELEN + 1];
70660737Sume#endif
70763012Sdes
70867043Sdes    direct = (flags && strchr(flags, 'd'));
70963012Sdes    noredirect = (flags && strchr(flags, 'A'));
71060376Sdes    verbose = (flags && strchr(flags, 'v'));
71160737Sume
71267043Sdes    if (direct && purl) {
71367043Sdes	fetchFreeURL(purl);
71467043Sdes	purl = NULL;
71567043Sdes    }
71667043Sdes
71763716Sdes    /* try the provided URL first */
71863716Sdes    url = URL;
71963716Sdes
72063716Sdes    /* if the A flag is set, we only get one try */
72163012Sdes    n = noredirect ? 1 : MAX_REDIRECT;
72263716Sdes    i = 0;
72363012Sdes
72463716Sdes    do {
72563069Sdes	new = NULL;
72663069Sdes	chunked = 0;
72763012Sdes	need_auth = 0;
72863069Sdes	offset = 0;
72963716Sdes	clength = -1;
73063716Sdes	length = -1;
73163716Sdes	size = -1;
73263716Sdes	mtime = 0;
73363012Sdes    retry:
73467043Sdes	/* check port */
73567043Sdes	if (!url->port)
73667043Sdes	    url->port = _http_default_port(url->scheme);
73767043Sdes
73863012Sdes	/* connect to server or proxy */
73967043Sdes	if ((fd = _http_connect(url, purl, flags)) == -1)
74063012Sdes	    goto ouch;
74163012Sdes
74263012Sdes	host = url->host;
74360737Sume#ifdef INET6
74463012Sdes	if (strchr(url->host, ':')) {
74563012Sdes	    snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
74663012Sdes	    host = hbuf;
74763012Sdes	}
74860737Sume#endif
74937535Sdes
75063012Sdes	/* send request */
75163012Sdes	if (verbose)
75263012Sdes	    _fetch_info("requesting %s://%s:%d%s",
75363012Sdes			url->scheme, host, url->port, url->doc);
75467043Sdes	if (purl) {
75563012Sdes	    _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1",
75663012Sdes		      op, url->scheme, host, url->port, url->doc);
75763012Sdes	} else {
75863012Sdes	    _http_cmd(fd, "%s %s HTTP/1.1",
75963012Sdes		      op, url->doc);
76063012Sdes	}
76137535Sdes
76263012Sdes	/* proxy authorization */
76367043Sdes	if (purl) {
76467043Sdes	    if (*purl->user || *purl->pwd)
76567043Sdes		_http_basic_auth(fd, "Proxy-Authorization",
76667043Sdes				 purl->user, purl->pwd);
76767043Sdes	    else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
76867043Sdes		_http_authorize(fd, "Proxy-Authorization", p);
76967043Sdes	}
77063012Sdes
77163012Sdes	/* server authorization */
77263012Sdes	if (need_auth) {
77363012Sdes	    if (*url->user || *url->pwd)
77467043Sdes		_http_basic_auth(fd, "Authorization", url->user, url->pwd);
77563716Sdes	    else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
77663012Sdes		_http_authorize(fd, "Authorization", p);
77763012Sdes	    else {
77863012Sdes		_http_seterr(HTTP_NEED_AUTH);
77963012Sdes		goto ouch;
78063012Sdes	    }
78163012Sdes	}
78260376Sdes
78363012Sdes	/* other headers */
78463842Sdes	if (url->port == _http_default_port(url->scheme))
78563842Sdes	    _http_cmd(fd, "Host: %s", host);
78663842Sdes	else
78763842Sdes	    _http_cmd(fd, "Host: %s:%d", host, url->port);
78863012Sdes	_http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname);
78963567Sdes	if (url->offset)
79063012Sdes	    _http_cmd(fd, "Range: bytes=%lld-", url->offset);
79163012Sdes	_http_cmd(fd, "Connection: close");
79263012Sdes	_http_cmd(fd, "");
79360376Sdes
79463012Sdes	/* get reply */
79563012Sdes	switch ((code = _http_get_reply(fd))) {
79663012Sdes	case HTTP_OK:
79763012Sdes	case HTTP_PARTIAL:
79863012Sdes	    /* fine */
79963012Sdes	    break;
80063012Sdes	case HTTP_MOVED_PERM:
80163012Sdes	case HTTP_MOVED_TEMP:
80263012Sdes	    /*
80363012Sdes	     * Not so fine, but we still have to read the headers to
80463012Sdes	     * get the new location.
80563012Sdes	     */
80663012Sdes	    break;
80763012Sdes	case HTTP_NEED_AUTH:
80863012Sdes	    if (need_auth) {
80963012Sdes		/*
81063012Sdes		 * We already sent out authorization code, so there's
81163012Sdes		 * nothing more we can do.
81263012Sdes		 */
81363012Sdes		_http_seterr(code);
81463012Sdes		goto ouch;
81563012Sdes	    }
81663012Sdes	    /* try again, but send the password this time */
81763012Sdes	    if (verbose)
81863012Sdes		_fetch_info("server requires authorization");
81963012Sdes	    need_auth = 1;
82063012Sdes	    close(fd);
82163012Sdes	    goto retry;
82263012Sdes	case HTTP_NEED_PROXY_AUTH:
82363012Sdes	    /*
82463012Sdes	     * If we're talking to a proxy, we already sent our proxy
82563012Sdes	     * authorization code, so there's nothing more we can do.
82663012Sdes	     */
82763012Sdes	    _http_seterr(code);
82863012Sdes	    goto ouch;
82963012Sdes	case HTTP_PROTOCOL_ERROR:
83063012Sdes	    /* fall through */
83163012Sdes	case -1:
83263012Sdes	    _fetch_syserr();
83363012Sdes	    goto ouch;
83463012Sdes	default:
83563012Sdes	    _http_seterr(code);
83663012Sdes	    goto ouch;
83763012Sdes	}
83863012Sdes
83963012Sdes	/* get headers */
84063012Sdes	do {
84163012Sdes	    switch ((h = _http_next_header(fd, &p))) {
84263012Sdes	    case hdr_syserror:
84363012Sdes		_fetch_syserr();
84463012Sdes		goto ouch;
84563012Sdes	    case hdr_error:
84663012Sdes		_http_seterr(HTTP_PROTOCOL_ERROR);
84763012Sdes		goto ouch;
84863012Sdes	    case hdr_content_length:
84963716Sdes		_http_parse_length(p, &clength);
85063012Sdes		break;
85163012Sdes	    case hdr_content_range:
85263716Sdes		_http_parse_range(p, &offset, &length, &size);
85363012Sdes		break;
85463012Sdes	    case hdr_last_modified:
85563716Sdes		_http_parse_mtime(p, &mtime);
85663012Sdes		break;
85763012Sdes	    case hdr_location:
85863012Sdes		if (!HTTP_REDIRECT(code))
85963012Sdes		    break;
86063069Sdes		if (new)
86163069Sdes		    free(new);
86263012Sdes		if (verbose)
86363012Sdes		    _fetch_info("%d redirect to %s", code, p);
86463069Sdes		if (*p == '/')
86563069Sdes		    /* absolute path */
86663069Sdes		    new = fetchMakeURL(url->scheme, url->host, url->port, p,
86763069Sdes				       url->user, url->pwd);
86863069Sdes		else
86963069Sdes		    new = fetchParseURL(p);
87063069Sdes		if (new == NULL) {
87163069Sdes		    /* XXX should set an error code */
87263069Sdes		    DEBUG(fprintf(stderr, "failed to parse new URL\n"));
87363012Sdes		    goto ouch;
87463069Sdes		}
87563012Sdes		if (!*new->user && !*new->pwd) {
87663012Sdes		    strcpy(new->user, url->user);
87763012Sdes		    strcpy(new->pwd, url->pwd);
87863012Sdes		}
87963012Sdes		new->offset = url->offset;
88063012Sdes		new->length = url->length;
88163069Sdes		break;
88263012Sdes	    case hdr_transfer_encoding:
88363012Sdes		/* XXX weak test*/
88463012Sdes		chunked = (strcasecmp(p, "chunked") == 0);
88563012Sdes		break;
88663012Sdes	    case hdr_end:
88763012Sdes		/* fall through */
88863012Sdes	    case hdr_unknown:
88963012Sdes		/* ignore */
89063012Sdes		break;
89163012Sdes	    }
89263012Sdes	} while (h > hdr_end);
89360376Sdes
89463069Sdes	/* we either have a hit, or a redirect with no Location: header */
89563069Sdes	if (code == HTTP_OK || code == HTTP_PARTIAL || !new)
89663012Sdes	    break;
89763069Sdes
89863069Sdes	/* we have a redirect */
89963069Sdes	close(fd);
90063337Sdes	fd = -1;
90163069Sdes	if (url != URL)
90263069Sdes	    fetchFreeURL(url);
90363069Sdes	url = new;
90463716Sdes    } while (++i < n);
90560376Sdes
90663012Sdes    /* no success */
90763012Sdes    if (fd == -1) {
90863012Sdes	_http_seterr(code);
90963012Sdes	goto ouch;
91037571Sdes    }
91137535Sdes
91264129Sdes    DEBUG(fprintf(stderr, "offset %lld, length %lld, size %lld, clength %lld\n",
91363716Sdes		  offset, length, size, clength));
91463716Sdes
91563716Sdes    /* check for inconsistencies */
91663716Sdes    if (clength != -1 && length != -1 && clength != length) {
91763716Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
91863716Sdes	goto ouch;
91963716Sdes    }
92063716Sdes    if (clength == -1)
92163716Sdes	clength = length;
92263716Sdes    if (clength != -1)
92363716Sdes	length = offset + clength;
92463716Sdes    if (length != -1 && size != -1 && length != size) {
92563716Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
92663716Sdes	goto ouch;
92763716Sdes    }
92863716Sdes    if (size == -1)
92963716Sdes	size = length;
93063716Sdes
93163716Sdes    /* fill in stats */
93263716Sdes    if (us) {
93363716Sdes	us->size = size;
93463716Sdes	us->atime = us->mtime = mtime;
93563716Sdes    }
93663716Sdes
93763567Sdes    /* too far? */
93863716Sdes    if (offset > URL->offset) {
93963567Sdes	_http_seterr(HTTP_PROTOCOL_ERROR);
94063567Sdes	goto ouch;
94163567Sdes    }
94263567Sdes
94363716Sdes    /* report back real offset and size */
94463567Sdes    URL->offset = offset;
94563716Sdes    URL->length = clength;
94663567Sdes
94763012Sdes    /* wrap it up in a FILE */
94863012Sdes    if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) {
94963012Sdes	_fetch_syserr();
95063012Sdes	goto ouch;
95163012Sdes    }
95263012Sdes
95363012Sdes    if (url != URL)
95463012Sdes	fetchFreeURL(url);
95567043Sdes    if (purl)
95667043Sdes	fetchFreeURL(purl);
95763012Sdes
95863012Sdes    return f;
95937535Sdes
96063012Sdes ouch:
96163012Sdes    if (url != URL)
96263012Sdes	fetchFreeURL(url);
96367043Sdes    if (purl)
96467043Sdes	fetchFreeURL(purl);
96563012Sdes    if (fd != -1)
96663012Sdes	close(fd);
96763012Sdes    return NULL;
96863012Sdes}
96960189Sdes
97063012Sdes
97163012Sdes/*****************************************************************************
97263012Sdes * Entry points
97363012Sdes */
97463012Sdes
97563012Sdes/*
97663340Sdes * Retrieve and stat a file by HTTP
97763340Sdes */
97863340SdesFILE *
97963340SdesfetchXGetHTTP(struct url *URL, struct url_stat *us, char *flags)
98063340Sdes{
98167043Sdes    return _http_request(URL, "GET", us, _http_get_proxy(), flags);
98263340Sdes}
98363340Sdes
98463340Sdes/*
98563012Sdes * Retrieve a file by HTTP
98663012Sdes */
98763012SdesFILE *
98863012SdesfetchGetHTTP(struct url *URL, char *flags)
98963012Sdes{
99063340Sdes    return fetchXGetHTTP(URL, NULL, flags);
99137535Sdes}
99237535Sdes
99363340Sdes/*
99463340Sdes * Store a file by HTTP
99563340Sdes */
99637535SdesFILE *
99740975SdesfetchPutHTTP(struct url *URL, char *flags)
99837535Sdes{
99937535Sdes    warnx("fetchPutHTTP(): not implemented");
100037535Sdes    return NULL;
100137535Sdes}
100240975Sdes
100340975Sdes/*
100440975Sdes * Get an HTTP document's metadata
100540975Sdes */
100640975Sdesint
100760376SdesfetchStatHTTP(struct url *URL, struct url_stat *us, char *flags)
100840975Sdes{
100960376Sdes    FILE *f;
101060376Sdes
101167043Sdes    if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL)
101260376Sdes	return -1;
101360581Sdes    fclose(f);
101460376Sdes    return 0;
101540975Sdes}
101641989Sdes
101741989Sdes/*
101841989Sdes * List a directory
101941989Sdes */
102041989Sdesstruct url_ent *
102141989SdesfetchListHTTP(struct url *url, char *flags)
102241989Sdes{
102341989Sdes    warnx("fetchListHTTP(): not implemented");
102441989Sdes    return NULL;
102541989Sdes}
1026