http.c revision 231247
137535Sdes/*-
2135546Sdes * Copyright (c) 2000-2004 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 */
2837535Sdes
2984203Sdillon#include <sys/cdefs.h>
3084203Sdillon__FBSDID("$FreeBSD: stable/9/lib/libfetch/http.c 231247 2012-02-09 06:48:04Z bapt $");
3184203Sdillon
3263236Sdes/*
3363236Sdes * The following copyright applies to the base64 code:
3463236Sdes *
3563236Sdes *-
3663236Sdes * Copyright 1997 Massachusetts Institute of Technology
3763236Sdes *
3863236Sdes * Permission to use, copy, modify, and distribute this software and
3963236Sdes * its documentation for any purpose and without fee is hereby
4063236Sdes * granted, provided that both the above copyright notice and this
4163236Sdes * permission notice appear in all copies, that both the above
4263236Sdes * copyright notice and this permission notice appear in all
4363236Sdes * supporting documentation, and that the name of M.I.T. not be used
4463236Sdes * in advertising or publicity pertaining to distribution of the
4563236Sdes * software without specific, written prior permission.  M.I.T. makes
4663236Sdes * no representations about the suitability of this software for any
4763236Sdes * purpose.  It is provided "as is" without express or implied
4863236Sdes * warranty.
4990267Sdes *
5063236Sdes * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
5163236Sdes * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
5263236Sdes * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5363236Sdes * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
5463236Sdes * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5563236Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5663236Sdes * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
5763236Sdes * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
5863236Sdes * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
5963236Sdes * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
6063236Sdes * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
6163236Sdes * SUCH DAMAGE.
6263236Sdes */
6363236Sdes
6437535Sdes#include <sys/param.h>
6560737Sume#include <sys/socket.h>
66186124Smurray#include <sys/time.h>
6737535Sdes
6863012Sdes#include <ctype.h>
6937535Sdes#include <err.h>
7063012Sdes#include <errno.h>
7160376Sdes#include <locale.h>
7260189Sdes#include <netdb.h>
7337608Sdes#include <stdarg.h>
7437535Sdes#include <stdio.h>
7537535Sdes#include <stdlib.h>
7637535Sdes#include <string.h>
7760376Sdes#include <time.h>
7837535Sdes#include <unistd.h>
79202613Sdes#include <md5.h>
8037535Sdes
81141958Skbyanc#include <netinet/in.h>
82141958Skbyanc#include <netinet/tcp.h>
83141958Skbyanc
8437535Sdes#include "fetch.h"
8540939Sdes#include "common.h"
8641862Sdes#include "httperr.h"
8737535Sdes
8863012Sdes/* Maximum number of redirects to follow */
8963012Sdes#define MAX_REDIRECT 5
9037535Sdes
9163012Sdes/* Symbolic names for reply codes we care about */
9263012Sdes#define HTTP_OK			200
9363012Sdes#define HTTP_PARTIAL		206
9463012Sdes#define HTTP_MOVED_PERM		301
9563012Sdes#define HTTP_MOVED_TEMP		302
9663012Sdes#define HTTP_SEE_OTHER		303
97186124Smurray#define HTTP_NOT_MODIFIED	304
98169386Sdes#define HTTP_TEMP_REDIRECT	307
9963012Sdes#define HTTP_NEED_AUTH		401
10087317Sdes#define HTTP_NEED_PROXY_AUTH	407
101125696Sdes#define HTTP_BAD_RANGE		416
10263012Sdes#define HTTP_PROTOCOL_ERROR	999
10360196Sdes
10463012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
10590267Sdes			    || (xyz) == HTTP_MOVED_TEMP \
106169386Sdes			    || (xyz) == HTTP_TEMP_REDIRECT \
10790267Sdes			    || (xyz) == HTTP_SEE_OTHER)
10863012Sdes
10988771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
11063012Sdes
11190267Sdes
11263012Sdes/*****************************************************************************
11363012Sdes * I/O functions for decoding chunked streams
11463012Sdes */
11563012Sdes
11697859Sdesstruct httpio
11737535Sdes{
11897858Sdes	conn_t		*conn;		/* connection */
11997866Sdes	int		 chunked;	/* chunked mode */
12097858Sdes	char		*buf;		/* chunk buffer */
12197866Sdes	size_t		 bufsize;	/* size of chunk buffer */
12297866Sdes	ssize_t		 buflen;	/* amount of data currently in buffer */
12397866Sdes	int		 bufpos;	/* current read offset in buffer */
12497858Sdes	int		 eof;		/* end-of-file flag */
12597858Sdes	int		 error;		/* error flag */
12697858Sdes	size_t		 chunksize;	/* remaining size of current chunk */
12763281Sdes#ifndef NDEBUG
12890267Sdes	size_t		 total;
12963012Sdes#endif
13037535Sdes};
13137535Sdes
13237608Sdes/*
13363012Sdes * Get next chunk header
13437608Sdes */
13537608Sdesstatic int
136174588Sdeshttp_new_chunk(struct httpio *io)
13737608Sdes{
13890267Sdes	char *p;
13990267Sdes
140174588Sdes	if (fetch_getln(io->conn) == -1)
14190267Sdes		return (-1);
14290267Sdes
143174761Sdes	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
14490267Sdes		return (-1);
14590267Sdes
146174761Sdes	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
14790267Sdes		if (*p == ';')
14890267Sdes			break;
149174761Sdes		if (!isxdigit((unsigned char)*p))
15090267Sdes			return (-1);
151174761Sdes		if (isdigit((unsigned char)*p)) {
15297859Sdes			io->chunksize = io->chunksize * 16 +
15390267Sdes			    *p - '0';
15490267Sdes		} else {
15597859Sdes			io->chunksize = io->chunksize * 16 +
156176036Sdes			    10 + tolower((unsigned char)*p) - 'a';
15790267Sdes		}
15890267Sdes	}
15990267Sdes
16063281Sdes#ifndef NDEBUG
16190267Sdes	if (fetchDebug) {
16297859Sdes		io->total += io->chunksize;
16397859Sdes		if (io->chunksize == 0)
164106207Sdes			fprintf(stderr, "%s(): end of last chunk\n", __func__);
16590267Sdes		else
166106207Sdes			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
167106207Sdes			    __func__, (unsigned long)io->chunksize,
168106207Sdes			    (unsigned long)io->total);
16990267Sdes	}
17063012Sdes#endif
17190267Sdes
17297859Sdes	return (io->chunksize);
17337608Sdes}
17437608Sdes
17537608Sdes/*
17697866Sdes * Grow the input buffer to at least len bytes
17797866Sdes */
17897866Sdesstatic inline int
179174588Sdeshttp_growbuf(struct httpio *io, size_t len)
18097866Sdes{
18197866Sdes	char *tmp;
18297866Sdes
18397866Sdes	if (io->bufsize >= len)
18497866Sdes		return (0);
18597866Sdes
18697866Sdes	if ((tmp = realloc(io->buf, len)) == NULL)
18797866Sdes		return (-1);
18897866Sdes	io->buf = tmp;
18997866Sdes	io->bufsize = len;
190106044Sdes	return (0);
19197866Sdes}
19297866Sdes
19397866Sdes/*
19437608Sdes * Fill the input buffer, do chunk decoding on the fly
19537608Sdes */
19663012Sdesstatic int
197174588Sdeshttp_fillbuf(struct httpio *io, size_t len)
19837535Sdes{
199231247Sbapt	ssize_t nbytes;
200231247Sbapt
20197859Sdes	if (io->error)
20290267Sdes		return (-1);
20397859Sdes	if (io->eof)
20490267Sdes		return (0);
20590267Sdes
20697866Sdes	if (io->chunked == 0) {
207174588Sdes		if (http_growbuf(io, len) == -1)
20897866Sdes			return (-1);
209231247Sbapt		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
210231247Sbapt			io->error = errno;
21197866Sdes			return (-1);
212106185Sdes		}
213231247Sbapt		io->buflen = nbytes;
21497866Sdes		io->bufpos = 0;
21597866Sdes		return (io->buflen);
21697866Sdes	}
21797866Sdes
21897859Sdes	if (io->chunksize == 0) {
219174588Sdes		switch (http_new_chunk(io)) {
22090267Sdes		case -1:
22197859Sdes			io->error = 1;
22290267Sdes			return (-1);
22390267Sdes		case 0:
22497859Sdes			io->eof = 1;
22590267Sdes			return (0);
22690267Sdes		}
22737535Sdes	}
22863012Sdes
22997866Sdes	if (len > io->chunksize)
23097866Sdes		len = io->chunksize;
231174588Sdes	if (http_growbuf(io, len) == -1)
23290267Sdes		return (-1);
233231247Sbapt	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
234231247Sbapt		io->error = errno;
23597866Sdes		return (-1);
236106185Sdes	}
237231247Sbapt	io->buflen = nbytes;
23897866Sdes	io->chunksize -= io->buflen;
23990267Sdes
24097859Sdes	if (io->chunksize == 0) {
24197856Sdes		char endl[2];
24297856Sdes
243174588Sdes		if (fetch_read(io->conn, endl, 2) != 2 ||
24497856Sdes		    endl[0] != '\r' || endl[1] != '\n')
24590267Sdes			return (-1);
24690267Sdes	}
24790267Sdes
24897866Sdes	io->bufpos = 0;
24990267Sdes
25097866Sdes	return (io->buflen);
25137535Sdes}
25237535Sdes
25337608Sdes/*
25437608Sdes * Read function
25537608Sdes */
25637535Sdesstatic int
257174588Sdeshttp_readfn(void *v, char *buf, int len)
25837535Sdes{
25997859Sdes	struct httpio *io = (struct httpio *)v;
26090267Sdes	int l, pos;
26163012Sdes
26297859Sdes	if (io->error)
26390267Sdes		return (-1);
26497859Sdes	if (io->eof)
26590267Sdes		return (0);
26663012Sdes
26790267Sdes	for (pos = 0; len > 0; pos += l, len -= l) {
26890267Sdes		/* empty buffer */
26997866Sdes		if (!io->buf || io->bufpos == io->buflen)
270174588Sdes			if (http_fillbuf(io, len) < 1)
27190267Sdes				break;
27297866Sdes		l = io->buflen - io->bufpos;
27390267Sdes		if (len < l)
27490267Sdes			l = len;
275176105Sdes		memcpy(buf + pos, io->buf + io->bufpos, l);
27697866Sdes		io->bufpos += l;
27790267Sdes	}
27837535Sdes
279231247Sbapt	if (!pos && io->error) {
280231247Sbapt		if (io->error == EINTR)
281231247Sbapt			io->error = 0;
28290267Sdes		return (-1);
283231247Sbapt	}
28490267Sdes	return (pos);
28537535Sdes}
28637535Sdes
28737608Sdes/*
28837608Sdes * Write function
28937608Sdes */
29037535Sdesstatic int
291174588Sdeshttp_writefn(void *v, const char *buf, int len)
29237535Sdes{
29397859Sdes	struct httpio *io = (struct httpio *)v;
29490267Sdes
295174588Sdes	return (fetch_write(io->conn, buf, len));
29637535Sdes}
29737535Sdes
29837608Sdes/*
29937608Sdes * Close function
30037608Sdes */
30137535Sdesstatic int
302174588Sdeshttp_closefn(void *v)
30337535Sdes{
30497859Sdes	struct httpio *io = (struct httpio *)v;
30590267Sdes	int r;
30663012Sdes
307174588Sdes	r = fetch_close(io->conn);
30897859Sdes	if (io->buf)
30997859Sdes		free(io->buf);
31097859Sdes	free(io);
31190267Sdes	return (r);
31237535Sdes}
31337535Sdes
31437608Sdes/*
31563012Sdes * Wrap a file descriptor up
31637608Sdes */
31763012Sdesstatic FILE *
318174588Sdeshttp_funopen(conn_t *conn, int chunked)
31937535Sdes{
32097859Sdes	struct httpio *io;
32190267Sdes	FILE *f;
32263012Sdes
323109967Sdes	if ((io = calloc(1, sizeof(*io))) == NULL) {
324174588Sdes		fetch_syserr();
32590267Sdes		return (NULL);
32690267Sdes	}
32797859Sdes	io->conn = conn;
32897866Sdes	io->chunked = chunked;
329174588Sdes	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
33090267Sdes	if (f == NULL) {
331174588Sdes		fetch_syserr();
33297859Sdes		free(io);
33390267Sdes		return (NULL);
33490267Sdes	}
33590267Sdes	return (f);
33663012Sdes}
33763012Sdes
33890267Sdes
33963012Sdes/*****************************************************************************
34063012Sdes * Helper functions for talking to the server and parsing its replies
34163012Sdes */
34263012Sdes
34363012Sdes/* Header types */
34463012Sdestypedef enum {
34590267Sdes	hdr_syserror = -2,
34690267Sdes	hdr_error = -1,
34790267Sdes	hdr_end = 0,
34890267Sdes	hdr_unknown = 1,
34990267Sdes	hdr_content_length,
35090267Sdes	hdr_content_range,
35190267Sdes	hdr_last_modified,
35290267Sdes	hdr_location,
35390267Sdes	hdr_transfer_encoding,
354202613Sdes	hdr_www_authenticate,
355202613Sdes	hdr_proxy_authenticate,
35685093Sdes} hdr_t;
35763012Sdes
35863012Sdes/* Names of interesting headers */
35963012Sdesstatic struct {
36090267Sdes	hdr_t		 num;
36190267Sdes	const char	*name;
36263012Sdes} hdr_names[] = {
36390267Sdes	{ hdr_content_length,		"Content-Length" },
36490267Sdes	{ hdr_content_range,		"Content-Range" },
36590267Sdes	{ hdr_last_modified,		"Last-Modified" },
36690267Sdes	{ hdr_location,			"Location" },
36790267Sdes	{ hdr_transfer_encoding,	"Transfer-Encoding" },
36890267Sdes	{ hdr_www_authenticate,		"WWW-Authenticate" },
369202613Sdes	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
37090267Sdes	{ hdr_unknown,			NULL },
37163012Sdes};
37263012Sdes
37363012Sdes/*
37463012Sdes * Send a formatted line; optionally echo to terminal
37563012Sdes */
37663012Sdesstatic int
377174588Sdeshttp_cmd(conn_t *conn, const char *fmt, ...)
37863012Sdes{
37990267Sdes	va_list ap;
38090267Sdes	size_t len;
38190267Sdes	char *msg;
38290267Sdes	int r;
38363012Sdes
38490267Sdes	va_start(ap, fmt);
38590267Sdes	len = vasprintf(&msg, fmt, ap);
38690267Sdes	va_end(ap);
38790267Sdes
38890267Sdes	if (msg == NULL) {
38990267Sdes		errno = ENOMEM;
390174588Sdes		fetch_syserr();
39190267Sdes		return (-1);
39290267Sdes	}
39390267Sdes
394174588Sdes	r = fetch_putln(conn, msg, len);
39590267Sdes	free(msg);
39690267Sdes
39790267Sdes	if (r == -1) {
398174588Sdes		fetch_syserr();
39990267Sdes		return (-1);
40090267Sdes	}
40190267Sdes
40290267Sdes	return (0);
40363012Sdes}
40463012Sdes
40563012Sdes/*
40663012Sdes * Get and parse status line
40763012Sdes */
40863012Sdesstatic int
409174588Sdeshttp_get_reply(conn_t *conn)
41063012Sdes{
41190267Sdes	char *p;
41290267Sdes
413174588Sdes	if (fetch_getln(conn) == -1)
41490267Sdes		return (-1);
41590267Sdes	/*
41690267Sdes	 * A valid status line looks like "HTTP/m.n xyz reason" where m
41790267Sdes	 * and n are the major and minor protocol version numbers and xyz
41890267Sdes	 * is the reply code.
41990267Sdes	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
42090267Sdes	 * just one) that do not send a version number, so we can't rely
42190267Sdes	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
42290267Sdes	 * We don't care about the reason phrase.
42390267Sdes	 */
42497856Sdes	if (strncmp(conn->buf, "HTTP", 4) != 0)
42590267Sdes		return (HTTP_PROTOCOL_ERROR);
42697856Sdes	p = conn->buf + 4;
42790267Sdes	if (*p == '/') {
42890267Sdes		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
42990267Sdes			return (HTTP_PROTOCOL_ERROR);
43090267Sdes		p += 4;
43190267Sdes	}
432174761Sdes	if (*p != ' ' ||
433174761Sdes	    !isdigit((unsigned char)p[1]) ||
434174761Sdes	    !isdigit((unsigned char)p[2]) ||
435174761Sdes	    !isdigit((unsigned char)p[3]))
43690267Sdes		return (HTTP_PROTOCOL_ERROR);
43790267Sdes
43897856Sdes	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
43997856Sdes	return (conn->err);
44037535Sdes}
44137535Sdes
44237608Sdes/*
44390267Sdes * Check a header; if the type matches the given string, return a pointer
44490267Sdes * to the beginning of the value.
44563012Sdes */
44675891Sarchiestatic const char *
447174588Sdeshttp_match(const char *str, const char *hdr)
44863012Sdes{
449176036Sdes	while (*str && *hdr &&
450176036Sdes	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
45190267Sdes		/* nothing */;
45290267Sdes	if (*str || *hdr != ':')
45390267Sdes		return (NULL);
454174761Sdes	while (*hdr && isspace((unsigned char)*++hdr))
45590267Sdes		/* nothing */;
45690267Sdes	return (hdr);
45763012Sdes}
45863012Sdes
459202613Sdes
46063012Sdes/*
461202613Sdes * Get the next header and return the appropriate symbolic code.  We
462202613Sdes * need to read one line ahead for checking for a continuation line
463202613Sdes * belonging to the current header (continuation lines start with
464221821Sdes * white space).
465202613Sdes *
466202613Sdes * We get called with a fresh line already in the conn buffer, either
467202613Sdes * from the previous http_next_header() invocation, or, the first
468202613Sdes * time, from a fetch_getln() performed by our caller.
469202613Sdes *
470202613Sdes * This stops when we encounter an empty line (we dont read beyond the header
471202613Sdes * area).
472221821Sdes *
473202613Sdes * Note that the "headerbuf" is just a place to return the result. Its
474202613Sdes * contents are not used for the next call. This means that no cleanup
475202613Sdes * is needed when ie doing another connection, just call the cleanup when
476202613Sdes * fully done to deallocate memory.
47763012Sdes */
478202613Sdes
479202613Sdes/* Limit the max number of continuation lines to some reasonable value */
480202613Sdes#define HTTP_MAX_CONT_LINES 10
481202613Sdes
482202613Sdes/* Place into which to build a header from one or several lines */
483202613Sdestypedef struct {
484202613Sdes	char	*buf;		/* buffer */
485202613Sdes	size_t	 bufsize;	/* buffer size */
486202613Sdes	size_t	 buflen;	/* length of buffer contents */
487202613Sdes} http_headerbuf_t;
488202613Sdes
489202613Sdesstatic void
490202613Sdesinit_http_headerbuf(http_headerbuf_t *buf)
49163012Sdes{
492202613Sdes	buf->buf = NULL;
493202613Sdes	buf->bufsize = 0;
494202613Sdes	buf->buflen = 0;
495202613Sdes}
49690267Sdes
497221821Sdesstatic void
498202613Sdesclean_http_headerbuf(http_headerbuf_t *buf)
499202613Sdes{
500202613Sdes	if (buf->buf)
501202613Sdes		free(buf->buf);
502202613Sdes	init_http_headerbuf(buf);
503202613Sdes}
504202613Sdes
505202613Sdes/* Remove whitespace at the end of the buffer */
506221821Sdesstatic void
507202613Sdeshttp_conn_trimright(conn_t *conn)
508202613Sdes{
509221821Sdes	while (conn->buflen &&
510202613Sdes	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
51197856Sdes		conn->buflen--;
51297856Sdes	conn->buf[conn->buflen] = '\0';
513202613Sdes}
514202613Sdes
515202613Sdesstatic hdr_t
516202613Sdeshttp_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
517202613Sdes{
518221820Sdes	unsigned int i, len;
519202613Sdes
520221821Sdes	/*
521202613Sdes	 * Have to do the stripping here because of the first line. So
522221821Sdes	 * it's done twice for the subsequent lines. No big deal
523202613Sdes	 */
524202613Sdes	http_conn_trimright(conn);
52597856Sdes	if (conn->buflen == 0)
52697856Sdes		return (hdr_end);
527202613Sdes
528202613Sdes	/* Copy the line to the headerbuf */
529202613Sdes	if (hbuf->bufsize < conn->buflen + 1) {
530202613Sdes		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
531202613Sdes			return (hdr_syserror);
532202613Sdes		hbuf->bufsize = conn->buflen + 1;
533202613Sdes	}
534202613Sdes	strcpy(hbuf->buf, conn->buf);
535202613Sdes	hbuf->buflen = conn->buflen;
536202613Sdes
537221821Sdes	/*
538202613Sdes	 * Fetch possible continuation lines. Stop at 1st non-continuation
539221821Sdes	 * and leave it in the conn buffer
540221821Sdes	 */
541202613Sdes	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
542202613Sdes		if (fetch_getln(conn) == -1)
543202613Sdes			return (hdr_syserror);
544202613Sdes
545221821Sdes		/*
546202613Sdes		 * Note: we carry on the idea from the previous version
547202613Sdes		 * that a pure whitespace line is equivalent to an empty
548202613Sdes		 * one (so it's not continuation and will be handled when
549221821Sdes		 * we are called next)
550202613Sdes		 */
551202613Sdes		http_conn_trimright(conn);
552202613Sdes		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
553202613Sdes			break;
554202613Sdes
555202613Sdes		/* Got a continuation line. Concatenate to previous */
556202613Sdes		len = hbuf->buflen + conn->buflen;
557202613Sdes		if (hbuf->bufsize < len + 1) {
558202613Sdes			len *= 2;
559202613Sdes			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
560202613Sdes				return (hdr_syserror);
561202613Sdes			hbuf->bufsize = len + 1;
562202613Sdes		}
563202613Sdes		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
564202613Sdes		hbuf->buflen += conn->buflen;
565221821Sdes	}
566202613Sdes
56790267Sdes	/*
56890267Sdes	 * We could check for malformed headers but we don't really care.
56990267Sdes	 * A valid header starts with a token immediately followed by a
57090267Sdes	 * colon; a token is any sequence of non-control, non-whitespace
57190267Sdes	 * characters except "()<>@,;:\\\"{}".
57290267Sdes	 */
57390267Sdes	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
574202613Sdes		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
57590267Sdes			return (hdr_names[i].num);
576202613Sdes
57790267Sdes	return (hdr_unknown);
57863012Sdes}
57963012Sdes
580202613Sdes/**************************
581202613Sdes * [Proxy-]Authenticate header parsing
582202613Sdes */
583202613Sdes
584221821Sdes/*
585221821Sdes * Read doublequote-delimited string into output buffer obuf (allocated
586202613Sdes * by caller, whose responsibility it is to ensure that it's big enough)
587202613Sdes * cp points to the first char after the initial '"'
588221821Sdes * Handles \ quoting
589221821Sdes * Returns pointer to the first char after the terminating double quote, or
590202613Sdes * NULL for error.
591202613Sdes */
592202613Sdesstatic const char *
593202613Sdeshttp_parse_headerstring(const char *cp, char *obuf)
594202613Sdes{
595202613Sdes	for (;;) {
596202613Sdes		switch (*cp) {
597202613Sdes		case 0: /* Unterminated string */
598202613Sdes			*obuf = 0;
599202613Sdes			return (NULL);
600202613Sdes		case '"': /* Ending quote */
601202613Sdes			*obuf = 0;
602202613Sdes			return (++cp);
603202613Sdes		case '\\':
604202613Sdes			if (*++cp == 0) {
605202613Sdes				*obuf = 0;
606202613Sdes				return (NULL);
607202613Sdes			}
608202613Sdes			/* FALLTHROUGH */
609202613Sdes		default:
610202613Sdes			*obuf++ = *cp++;
611202613Sdes		}
612202613Sdes	}
613202613Sdes}
614202613Sdes
615202613Sdes/* Http auth challenge schemes */
616202613Sdestypedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
617202613Sdes
618202613Sdes/* Data holder for a Basic or Digest challenge. */
619202613Sdestypedef struct {
620202613Sdes	http_auth_schemes_t scheme;
621202613Sdes	char	*realm;
622202613Sdes	char	*qop;
623202613Sdes	char	*nonce;
624202613Sdes	char	*opaque;
625202613Sdes	char	*algo;
626202613Sdes	int	 stale;
627202613Sdes	int	 nc; /* Nonce count */
628202613Sdes} http_auth_challenge_t;
629202613Sdes
630221821Sdesstatic void
631202613Sdesinit_http_auth_challenge(http_auth_challenge_t *b)
632202613Sdes{
633202613Sdes	b->scheme = HTTPAS_UNKNOWN;
634202613Sdes	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
635202613Sdes	b->stale = b->nc = 0;
636202613Sdes}
637202613Sdes
638221821Sdesstatic void
639202613Sdesclean_http_auth_challenge(http_auth_challenge_t *b)
640202613Sdes{
641221821Sdes	if (b->realm)
642202613Sdes		free(b->realm);
643221821Sdes	if (b->qop)
644202613Sdes		free(b->qop);
645221821Sdes	if (b->nonce)
646202613Sdes		free(b->nonce);
647221821Sdes	if (b->opaque)
648202613Sdes		free(b->opaque);
649221821Sdes	if (b->algo)
650202613Sdes		free(b->algo);
651202613Sdes	init_http_auth_challenge(b);
652202613Sdes}
653202613Sdes
654202613Sdes/* Data holder for an array of challenges offered in an http response. */
655202613Sdes#define MAX_CHALLENGES 10
656202613Sdestypedef struct {
657202613Sdes	http_auth_challenge_t *challenges[MAX_CHALLENGES];
658202613Sdes	int	count; /* Number of parsed challenges in the array */
659202613Sdes	int	valid; /* We did parse an authenticate header */
660202613Sdes} http_auth_challenges_t;
661202613Sdes
662221821Sdesstatic void
663202613Sdesinit_http_auth_challenges(http_auth_challenges_t *cs)
664202613Sdes{
665202613Sdes	int i;
666202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++)
667202613Sdes		cs->challenges[i] = NULL;
668202613Sdes	cs->count = cs->valid = 0;
669202613Sdes}
670202613Sdes
671221821Sdesstatic void
672202613Sdesclean_http_auth_challenges(http_auth_challenges_t *cs)
673202613Sdes{
674202613Sdes	int i;
675202613Sdes	/* We rely on non-zero pointers being allocated, not on the count */
676202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++) {
677202613Sdes		if (cs->challenges[i] != NULL) {
678202613Sdes			clean_http_auth_challenge(cs->challenges[i]);
679202613Sdes			free(cs->challenges[i]);
680202613Sdes		}
681202613Sdes	}
682202613Sdes	init_http_auth_challenges(cs);
683202613Sdes}
684202613Sdes
685221821Sdes/*
686202613Sdes * Enumeration for lexical elements. Separators will be returned as their own
687202613Sdes * ascii value
688202613Sdes */
689202613Sdestypedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
690202613Sdes	      HTTPHL_ERROR = 259} http_header_lex_t;
691202613Sdes
692221821Sdes/*
693202613Sdes * Determine what kind of token comes next and return possible value
694202613Sdes * in buf, which is supposed to have been allocated big enough by
695221821Sdes * caller. Advance input pointer and return element type.
696202613Sdes */
697221821Sdesstatic int
698202613Sdeshttp_header_lex(const char **cpp, char *buf)
699202613Sdes{
700202613Sdes	size_t l;
701202613Sdes	/* Eat initial whitespace */
702202613Sdes	*cpp += strspn(*cpp, " \t");
703202613Sdes	if (**cpp == 0)
704202613Sdes		return (HTTPHL_END);
705202613Sdes
706202613Sdes	/* Separator ? */
707202613Sdes	if (**cpp == ',' || **cpp == '=')
708202613Sdes		return (*((*cpp)++));
709202613Sdes
710202613Sdes	/* String ? */
711202613Sdes	if (**cpp == '"') {
712202613Sdes		*cpp = http_parse_headerstring(++*cpp, buf);
713202613Sdes		if (*cpp == NULL)
714202613Sdes			return (HTTPHL_ERROR);
715202613Sdes		return (HTTPHL_STRING);
716202613Sdes	}
717202613Sdes
718202613Sdes	/* Read other token, until separator or whitespace */
719202613Sdes	l = strcspn(*cpp, " \t,=");
720202613Sdes	memcpy(buf, *cpp, l);
721202613Sdes	buf[l] = 0;
722202613Sdes	*cpp += l;
723202613Sdes	return (HTTPHL_WORD);
724202613Sdes}
725202613Sdes
726221821Sdes/*
727202613Sdes * Read challenges from http xxx-authenticate header and accumulate them
728202613Sdes * in the challenges list structure.
729202613Sdes *
730202613Sdes * Headers with multiple challenges are specified by rfc2617, but
731202613Sdes * servers (ie: squid) often send them in separate headers instead,
732202613Sdes * which in turn is forbidden by the http spec (multiple headers with
733202613Sdes * the same name are only allowed for pure comma-separated lists, see
734202613Sdes * rfc2616 sec 4.2).
735202613Sdes *
736202613Sdes * We support both approaches anyway
737202613Sdes */
738221821Sdesstatic int
739202613Sdeshttp_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
740202613Sdes{
741202613Sdes	int ret = -1;
742202613Sdes	http_header_lex_t lex;
743202613Sdes	char *key = malloc(strlen(cp) + 1);
744202613Sdes	char *value = malloc(strlen(cp) + 1);
745202613Sdes	char *buf = malloc(strlen(cp) + 1);
746202613Sdes
747202613Sdes	if (key == NULL || value == NULL || buf == NULL) {
748202613Sdes		fetch_syserr();
749202613Sdes		goto out;
750202613Sdes	}
751202613Sdes
752202613Sdes	/* In any case we've seen the header and we set the valid bit */
753202613Sdes	cs->valid = 1;
754202613Sdes
755202613Sdes	/* Need word first */
756202613Sdes	lex = http_header_lex(&cp, key);
757202613Sdes	if (lex != HTTPHL_WORD)
758202613Sdes		goto out;
759202613Sdes
760202613Sdes	/* Loop on challenges */
761202613Sdes	for (; cs->count < MAX_CHALLENGES; cs->count++) {
762221821Sdes		cs->challenges[cs->count] =
763202613Sdes			malloc(sizeof(http_auth_challenge_t));
764202613Sdes		if (cs->challenges[cs->count] == NULL) {
765202613Sdes			fetch_syserr();
766202613Sdes			goto out;
767202613Sdes		}
768202613Sdes		init_http_auth_challenge(cs->challenges[cs->count]);
769202613Sdes		if (!strcasecmp(key, "basic")) {
770202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
771202613Sdes		} else if (!strcasecmp(key, "digest")) {
772202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
773202613Sdes		} else {
774202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
775221821Sdes			/*
776221821Sdes			 * Continue parsing as basic or digest may
777202613Sdes			 * follow, and the syntax is the same for
778202613Sdes			 * all. We'll just ignore this one when
779202613Sdes			 * looking at the list
780202613Sdes			 */
781202613Sdes		}
782221821Sdes
783202613Sdes		/* Loop on attributes */
784202613Sdes		for (;;) {
785202613Sdes			/* Key */
786202613Sdes			lex = http_header_lex(&cp, key);
787202613Sdes			if (lex != HTTPHL_WORD)
788202613Sdes				goto out;
789202613Sdes
790202613Sdes			/* Equal sign */
791202613Sdes			lex = http_header_lex(&cp, buf);
792202613Sdes			if (lex != '=')
793202613Sdes				goto out;
794202613Sdes
795202613Sdes			/* Value */
796202613Sdes			lex = http_header_lex(&cp, value);
797202613Sdes			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
798202613Sdes				goto out;
799202613Sdes
800202613Sdes			if (!strcasecmp(key, "realm"))
801221821Sdes				cs->challenges[cs->count]->realm =
802202613Sdes					strdup(value);
803202613Sdes			else if (!strcasecmp(key, "qop"))
804221821Sdes				cs->challenges[cs->count]->qop =
805202613Sdes					strdup(value);
806202613Sdes			else if (!strcasecmp(key, "nonce"))
807221821Sdes				cs->challenges[cs->count]->nonce =
808202613Sdes					strdup(value);
809202613Sdes			else if (!strcasecmp(key, "opaque"))
810221821Sdes				cs->challenges[cs->count]->opaque =
811202613Sdes					strdup(value);
812202613Sdes			else if (!strcasecmp(key, "algorithm"))
813221821Sdes				cs->challenges[cs->count]->algo =
814202613Sdes					strdup(value);
815202613Sdes			else if (!strcasecmp(key, "stale"))
816221821Sdes				cs->challenges[cs->count]->stale =
817202613Sdes					strcasecmp(value, "no");
818202613Sdes			/* Else ignore unknown attributes */
819202613Sdes
820202613Sdes			/* Comma or Next challenge or End */
821202613Sdes			lex = http_header_lex(&cp, key);
822221821Sdes			/*
823221821Sdes			 * If we get a word here, this is the beginning of the
824221821Sdes			 * next challenge. Break the attributes loop
825221821Sdes			 */
826202613Sdes			if (lex == HTTPHL_WORD)
827202613Sdes				break;
828202613Sdes
829202613Sdes			if (lex == HTTPHL_END) {
830202613Sdes				/* End while looking for ',' is normal exit */
831202613Sdes				cs->count++;
832202613Sdes				ret = 0;
833202613Sdes				goto out;
834202613Sdes			}
835202613Sdes			/* Anything else is an error */
836202613Sdes			if (lex != ',')
837202613Sdes				goto out;
838202613Sdes
839202613Sdes		} /* End attributes loop */
840202613Sdes	} /* End challenge loop */
841202613Sdes
842221821Sdes	/*
843221821Sdes	 * Challenges max count exceeded. This really can't happen
844221821Sdes	 * with normal data, something's fishy -> error
845221821Sdes	 */
846202613Sdes
847202613Sdesout:
848202613Sdes	if (key)
849202613Sdes		free(key);
850202613Sdes	if (value)
851202613Sdes		free(value);
852202613Sdes	if (buf)
853202613Sdes		free(buf);
854202613Sdes	return (ret);
855202613Sdes}
856202613Sdes
857202613Sdes
85863012Sdes/*
85963012Sdes * Parse a last-modified header
86063012Sdes */
86163716Sdesstatic int
862174588Sdeshttp_parse_mtime(const char *p, time_t *mtime)
86363012Sdes{
86490267Sdes	char locale[64], *r;
86590267Sdes	struct tm tm;
86663012Sdes
867109967Sdes	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
86890267Sdes	setlocale(LC_TIME, "C");
86990267Sdes	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
87090267Sdes	/* XXX should add support for date-2 and date-3 */
87190267Sdes	setlocale(LC_TIME, locale);
87290267Sdes	if (r == NULL)
87390267Sdes		return (-1);
87490267Sdes	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
87588769Sdes		  "%02d:%02d:%02d]\n",
87663012Sdes		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
87763012Sdes		  tm.tm_hour, tm.tm_min, tm.tm_sec));
87890267Sdes	*mtime = timegm(&tm);
87990267Sdes	return (0);
88063012Sdes}
88163012Sdes
88263012Sdes/*
88363012Sdes * Parse a content-length header
88463012Sdes */
88563716Sdesstatic int
886174588Sdeshttp_parse_length(const char *p, off_t *length)
88763012Sdes{
88890267Sdes	off_t len;
88990267Sdes
890174761Sdes	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
89190267Sdes		len = len * 10 + (*p - '0');
89290267Sdes	if (*p)
89390267Sdes		return (-1);
89490267Sdes	DEBUG(fprintf(stderr, "content length: [%lld]\n",
89590267Sdes	    (long long)len));
89690267Sdes	*length = len;
89790267Sdes	return (0);
89863012Sdes}
89963012Sdes
90063012Sdes/*
90163012Sdes * Parse a content-range header
90263012Sdes */
90363716Sdesstatic int
904174588Sdeshttp_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
90563012Sdes{
90690267Sdes	off_t first, last, len;
90763716Sdes
90890267Sdes	if (strncasecmp(p, "bytes ", 6) != 0)
90990267Sdes		return (-1);
910125696Sdes	p += 6;
911125696Sdes	if (*p == '*') {
912125696Sdes		first = last = -1;
913125696Sdes		++p;
914125696Sdes	} else {
915174761Sdes		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
916125696Sdes			first = first * 10 + *p - '0';
917125696Sdes		if (*p != '-')
918125696Sdes			return (-1);
919174761Sdes		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
920125696Sdes			last = last * 10 + *p - '0';
921125696Sdes	}
92290267Sdes	if (first > last || *p != '/')
92390267Sdes		return (-1);
924174761Sdes	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
92590267Sdes		len = len * 10 + *p - '0';
92690267Sdes	if (*p || len < last - first + 1)
92790267Sdes		return (-1);
928125696Sdes	if (first == -1) {
929125696Sdes		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
930125696Sdes		    (long long)len));
931125696Sdes		*length = 0;
932125696Sdes	} else {
933125696Sdes		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
934125696Sdes		    (long long)first, (long long)last, (long long)len));
935125696Sdes		*length = last - first + 1;
936125696Sdes	}
93790267Sdes	*offset = first;
93890267Sdes	*size = len;
93990267Sdes	return (0);
94063012Sdes}
94163012Sdes
94290267Sdes
94363012Sdes/*****************************************************************************
94463012Sdes * Helper functions for authorization
94563012Sdes */
94663012Sdes
94763012Sdes/*
94837608Sdes * Base64 encoding
94937608Sdes */
95062965Sdesstatic char *
951174588Sdeshttp_base64(const char *src)
95237608Sdes{
95390267Sdes	static const char base64[] =
95490267Sdes	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
95590267Sdes	    "abcdefghijklmnopqrstuvwxyz"
95690267Sdes	    "0123456789+/";
95790267Sdes	char *str, *dst;
95890267Sdes	size_t l;
95990267Sdes	int t, r;
96062965Sdes
96190267Sdes	l = strlen(src);
962133280Sdes	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
96390267Sdes		return (NULL);
96490267Sdes	dst = str;
96590267Sdes	r = 0;
96637608Sdes
96790267Sdes	while (l >= 3) {
96890267Sdes		t = (src[0] << 16) | (src[1] << 8) | src[2];
96990267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
97090267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
97190267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
97290267Sdes		dst[3] = base64[(t >> 0) & 0x3f];
97390267Sdes		src += 3; l -= 3;
97490267Sdes		dst += 4; r += 4;
97590267Sdes	}
97637608Sdes
97790267Sdes	switch (l) {
97890267Sdes	case 2:
97990267Sdes		t = (src[0] << 16) | (src[1] << 8);
98090267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
98190267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
98290267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
98390267Sdes		dst[3] = '=';
98490267Sdes		dst += 4;
98590267Sdes		r += 4;
98690267Sdes		break;
98790267Sdes	case 1:
98890267Sdes		t = src[0] << 16;
98990267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
99090267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
99190267Sdes		dst[2] = dst[3] = '=';
99290267Sdes		dst += 4;
99390267Sdes		r += 4;
99490267Sdes		break;
99590267Sdes	case 0:
99690267Sdes		break;
99790267Sdes	}
99890267Sdes
99990267Sdes	*dst = 0;
100090267Sdes	return (str);
100137608Sdes}
100237608Sdes
1003202613Sdes
100437608Sdes/*
1005202613Sdes * Extract authorization parameters from environment value.
1006202613Sdes * The value is like scheme:realm:user:pass
1007202613Sdes */
1008202613Sdestypedef struct {
1009202613Sdes	char	*scheme;
1010202613Sdes	char	*realm;
1011202613Sdes	char	*user;
1012202613Sdes	char	*password;
1013202613Sdes} http_auth_params_t;
1014202613Sdes
1015202613Sdesstatic void
1016202613Sdesinit_http_auth_params(http_auth_params_t *s)
1017202613Sdes{
1018202613Sdes	s->scheme = s->realm = s->user = s->password = 0;
1019202613Sdes}
1020202613Sdes
1021221821Sdesstatic void
1022202613Sdesclean_http_auth_params(http_auth_params_t *s)
1023202613Sdes{
1024221821Sdes	if (s->scheme)
1025202613Sdes		free(s->scheme);
1026221821Sdes	if (s->realm)
1027202613Sdes		free(s->realm);
1028221821Sdes	if (s->user)
1029202613Sdes		free(s->user);
1030221821Sdes	if (s->password)
1031202613Sdes		free(s->password);
1032202613Sdes	init_http_auth_params(s);
1033202613Sdes}
1034202613Sdes
1035202613Sdesstatic int
1036202613Sdeshttp_authfromenv(const char *p, http_auth_params_t *parms)
1037202613Sdes{
1038202613Sdes	int ret = -1;
1039202613Sdes	char *v, *ve;
1040202613Sdes	char *str = strdup(p);
1041202613Sdes
1042202613Sdes	if (str == NULL) {
1043202613Sdes		fetch_syserr();
1044202613Sdes		return (-1);
1045202613Sdes	}
1046202613Sdes	v = str;
1047202613Sdes
1048202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1049202613Sdes		goto out;
1050202613Sdes
1051202613Sdes	*ve = 0;
1052202613Sdes	if ((parms->scheme = strdup(v)) == NULL) {
1053202613Sdes		fetch_syserr();
1054202613Sdes		goto out;
1055202613Sdes	}
1056202613Sdes	v = ve + 1;
1057202613Sdes
1058202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1059202613Sdes		goto out;
1060202613Sdes
1061202613Sdes	*ve = 0;
1062202613Sdes	if ((parms->realm = strdup(v)) == NULL) {
1063202613Sdes		fetch_syserr();
1064202613Sdes		goto out;
1065202613Sdes	}
1066202613Sdes	v = ve + 1;
1067202613Sdes
1068202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1069202613Sdes		goto out;
1070202613Sdes
1071202613Sdes	*ve = 0;
1072202613Sdes	if ((parms->user = strdup(v)) == NULL) {
1073202613Sdes		fetch_syserr();
1074202613Sdes		goto out;
1075202613Sdes	}
1076202613Sdes	v = ve + 1;
1077202613Sdes
1078202613Sdes
1079202613Sdes	if ((parms->password = strdup(v)) == NULL) {
1080202613Sdes		fetch_syserr();
1081202613Sdes		goto out;
1082202613Sdes	}
1083202613Sdes	ret = 0;
1084202613Sdesout:
1085221821Sdes	if (ret == -1)
1086202613Sdes		clean_http_auth_params(parms);
1087202613Sdes	if (str)
1088202613Sdes		free(str);
1089202613Sdes	return (ret);
1090202613Sdes}
1091202613Sdes
1092202613Sdes
1093221821Sdes/*
1094202613Sdes * Digest response: the code to compute the digest is taken from the
1095221821Sdes * sample implementation in RFC2616
1096202613Sdes */
1097221822Sdes#define IN const
1098202613Sdes#define OUT
1099202613Sdes
1100202613Sdes#define HASHLEN 16
1101202613Sdestypedef char HASH[HASHLEN];
1102202613Sdes#define HASHHEXLEN 32
1103202613Sdestypedef char HASHHEX[HASHHEXLEN+1];
1104202613Sdes
1105202613Sdesstatic const char *hexchars = "0123456789abcdef";
1106221821Sdesstatic void
1107202613SdesCvtHex(IN HASH Bin, OUT HASHHEX Hex)
1108202613Sdes{
1109202613Sdes	unsigned short i;
1110202613Sdes	unsigned char j;
1111202613Sdes
1112202613Sdes	for (i = 0; i < HASHLEN; i++) {
1113202613Sdes		j = (Bin[i] >> 4) & 0xf;
1114202613Sdes		Hex[i*2] = hexchars[j];
1115202613Sdes		j = Bin[i] & 0xf;
1116202613Sdes		Hex[i*2+1] = hexchars[j];
1117202613Sdes	};
1118202613Sdes	Hex[HASHHEXLEN] = '\0';
1119202613Sdes};
1120202613Sdes
1121202613Sdes/* calculate H(A1) as per spec */
1122221821Sdesstatic void
1123202613SdesDigestCalcHA1(
1124202613Sdes	IN char * pszAlg,
1125202613Sdes	IN char * pszUserName,
1126202613Sdes	IN char * pszRealm,
1127202613Sdes	IN char * pszPassword,
1128202613Sdes	IN char * pszNonce,
1129202613Sdes	IN char * pszCNonce,
1130202613Sdes	OUT HASHHEX SessionKey
1131202613Sdes	)
1132202613Sdes{
1133202613Sdes	MD5_CTX Md5Ctx;
1134202613Sdes	HASH HA1;
1135202613Sdes
1136202613Sdes	MD5Init(&Md5Ctx);
1137202613Sdes	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1138202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1139202613Sdes	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1140202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1141202613Sdes	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1142202613Sdes	MD5Final(HA1, &Md5Ctx);
1143202613Sdes	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1144202613Sdes
1145202613Sdes		MD5Init(&Md5Ctx);
1146202613Sdes		MD5Update(&Md5Ctx, HA1, HASHLEN);
1147202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1148202613Sdes		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1149202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1150202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1151202613Sdes		MD5Final(HA1, &Md5Ctx);
1152202613Sdes	};
1153202613Sdes	CvtHex(HA1, SessionKey);
1154202613Sdes}
1155202613Sdes
1156202613Sdes/* calculate request-digest/response-digest as per HTTP Digest spec */
1157221821Sdesstatic void
1158202613SdesDigestCalcResponse(
1159202613Sdes	IN HASHHEX HA1,           /* H(A1) */
1160202613Sdes	IN char * pszNonce,       /* nonce from server */
1161202613Sdes	IN char * pszNonceCount,  /* 8 hex digits */
1162202613Sdes	IN char * pszCNonce,      /* client nonce */
1163202613Sdes	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1164202613Sdes	IN char * pszMethod,      /* method from the request */
1165202613Sdes	IN char * pszDigestUri,   /* requested URL */
1166202613Sdes	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1167202613Sdes	OUT HASHHEX Response      /* request-digest or response-digest */
1168202613Sdes	)
1169202613Sdes{
1170221821Sdes/*	DEBUG(fprintf(stderr,
1171202613Sdes		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1172202613Sdes		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1173202613Sdes	MD5_CTX Md5Ctx;
1174202613Sdes	HASH HA2;
1175202613Sdes	HASH RespHash;
1176202613Sdes	HASHHEX HA2Hex;
1177202613Sdes
1178202613Sdes	// calculate H(A2)
1179202613Sdes	MD5Init(&Md5Ctx);
1180202613Sdes	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1181202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1182202613Sdes	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1183202613Sdes	if (strcasecmp(pszQop, "auth-int") == 0) {
1184202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1185202613Sdes		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1186202613Sdes	};
1187202613Sdes	MD5Final(HA2, &Md5Ctx);
1188202613Sdes	CvtHex(HA2, HA2Hex);
1189202613Sdes
1190202613Sdes	// calculate response
1191202613Sdes	MD5Init(&Md5Ctx);
1192202613Sdes	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1193202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1194202613Sdes	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1195202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1196202613Sdes	if (*pszQop) {
1197202613Sdes		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1198202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1199202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1200202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1201202613Sdes		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1202202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1203202613Sdes	};
1204202613Sdes	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1205202613Sdes	MD5Final(RespHash, &Md5Ctx);
1206202613Sdes	CvtHex(RespHash, Response);
1207202613Sdes}
1208202613Sdes
1209221821Sdes/*
1210221821Sdes * Generate/Send a Digest authorization header
1211202613Sdes * This looks like: [Proxy-]Authorization: credentials
1212202613Sdes *
1213202613Sdes *  credentials      = "Digest" digest-response
1214202613Sdes *  digest-response  = 1#( username | realm | nonce | digest-uri
1215202613Sdes *                      | response | [ algorithm ] | [cnonce] |
1216202613Sdes *                      [opaque] | [message-qop] |
1217202613Sdes *                          [nonce-count]  | [auth-param] )
1218202613Sdes *  username         = "username" "=" username-value
1219202613Sdes *  username-value   = quoted-string
1220202613Sdes *  digest-uri       = "uri" "=" digest-uri-value
1221202613Sdes *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1222202613Sdes *  message-qop      = "qop" "=" qop-value
1223202613Sdes *  cnonce           = "cnonce" "=" cnonce-value
1224202613Sdes *  cnonce-value     = nonce-value
1225202613Sdes *  nonce-count      = "nc" "=" nc-value
1226202613Sdes *  nc-value         = 8LHEX
1227202613Sdes *  response         = "response" "=" request-digest
1228202613Sdes *  request-digest = <"> 32LHEX <">
1229202613Sdes */
1230202613Sdesstatic int
1231202613Sdeshttp_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1232202613Sdes		 http_auth_params_t *parms, struct url *url)
1233202613Sdes{
1234202613Sdes	int r;
1235202613Sdes	char noncecount[10];
1236202613Sdes	char cnonce[40];
1237202613Sdes	char *options = 0;
1238202613Sdes
1239202613Sdes	if (!c->realm || !c->nonce) {
1240202613Sdes		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1241202613Sdes		return(-1);
1242202613Sdes	}
1243221821Sdes	if (!c->algo)
1244202613Sdes		c->algo = strdup("");
1245202613Sdes
1246221821Sdes	if (asprintf(&options, "%s%s%s%s",
1247202613Sdes		     *c->algo? ",algorithm=" : "", c->algo,
1248202613Sdes		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1249202613Sdes		return (-1);
1250202613Sdes
1251202613Sdes	if (!c->qop) {
1252202613Sdes		c->qop = strdup("");
1253202613Sdes		*noncecount = 0;
1254202613Sdes		*cnonce = 0;
1255202613Sdes	} else {
1256202613Sdes		c->nc++;
1257202613Sdes		sprintf(noncecount, "%08x", c->nc);
1258202613Sdes		/* We don't try very hard with the cnonce ... */
1259202613Sdes		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1260202613Sdes	}
1261202613Sdes
1262202613Sdes	HASHHEX HA1;
1263202613Sdes	DigestCalcHA1(c->algo, parms->user, c->realm,
1264202613Sdes		      parms->password, c->nonce, cnonce, HA1);
1265202613Sdes	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1266202613Sdes	HASHHEX digest;
1267202613Sdes	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1268202613Sdes			   "GET", url->doc, "", digest);
1269202613Sdes
1270202613Sdes	if (c->qop[0]) {
1271202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1272202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1273202613Sdes			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1274221821Sdes			     hdr, parms->user, c->realm,
1275202613Sdes			     c->nonce, url->doc, digest,
1276202613Sdes			     cnonce, noncecount, options);
1277202613Sdes	} else {
1278202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1279202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1280221821Sdes			     hdr, parms->user, c->realm,
1281202613Sdes			     c->nonce, url->doc, digest, options);
1282202613Sdes	}
1283202613Sdes	if (options)
1284202613Sdes		free(options);
1285202613Sdes	return (r);
1286202613Sdes}
1287202613Sdes
1288202613Sdes/*
128937608Sdes * Encode username and password
129037608Sdes */
129162965Sdesstatic int
1292174588Sdeshttp_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
129337608Sdes{
129490267Sdes	char *upw, *auth;
129590267Sdes	int r;
129637608Sdes
1297202613Sdes	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1298202613Sdes	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
129990267Sdes	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
130090267Sdes		return (-1);
1301174588Sdes	auth = http_base64(upw);
130290267Sdes	free(upw);
130390267Sdes	if (auth == NULL)
130490267Sdes		return (-1);
1305174588Sdes	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
130690267Sdes	free(auth);
130790267Sdes	return (r);
130862965Sdes}
130962965Sdes
131062965Sdes/*
1311221821Sdes * Chose the challenge to answer and call the appropriate routine to
1312202613Sdes * produce the header.
131362965Sdes */
131462965Sdesstatic int
1315202613Sdeshttp_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1316202613Sdes	       http_auth_params_t *parms, struct url *url)
131762965Sdes{
1318202613Sdes	http_auth_challenge_t *basic = NULL;
1319202613Sdes	http_auth_challenge_t *digest = NULL;
1320202613Sdes	int i;
132162965Sdes
1322202613Sdes	/* If user or pass are null we're not happy */
1323202613Sdes	if (!parms->user || !parms->password) {
1324202613Sdes		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1325202613Sdes		return (-1);
132690267Sdes	}
1327202613Sdes
1328202613Sdes	/* Look for a Digest and a Basic challenge */
1329202613Sdes	for (i = 0; i < cs->count; i++) {
1330202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1331202613Sdes			basic = cs->challenges[i];
1332202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1333202613Sdes			digest = cs->challenges[i];
1334202613Sdes	}
1335202613Sdes
1336202613Sdes	/* Error if "Digest" was specified and there is no Digest challenge */
1337221821Sdes	if (!digest && (parms->scheme &&
1338202613Sdes			!strcasecmp(parms->scheme, "digest"))) {
1339221821Sdes		DEBUG(fprintf(stderr,
1340202613Sdes			      "Digest auth in env, not supported by peer\n"));
1341202613Sdes		return (-1);
1342202613Sdes	}
1343221821Sdes	/*
1344221821Sdes	 * If "basic" was specified in the environment, or there is no Digest
1345202613Sdes	 * challenge, do the basic thing. Don't need a challenge for this,
1346221821Sdes	 * so no need to check basic!=NULL
1347202613Sdes	 */
1348202613Sdes	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1349202613Sdes		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1350202613Sdes
1351202613Sdes	/* Else, prefer digest. We just checked that it's not NULL */
1352202613Sdes	return (http_digest_auth(conn, hdr, digest, parms, url));
135337608Sdes}
135437608Sdes
135563012Sdes/*****************************************************************************
135663012Sdes * Helper functions for connecting to a server or proxy
135763012Sdes */
135863012Sdes
135937608Sdes/*
136090267Sdes * Connect to the correct HTTP server or proxy.
136163012Sdes */
136297856Sdesstatic conn_t *
1363174588Sdeshttp_connect(struct url *URL, struct url *purl, const char *flags)
136463012Sdes{
136597856Sdes	conn_t *conn;
136690267Sdes	int verbose;
1367141958Skbyanc	int af, val;
136890267Sdes
136963012Sdes#ifdef INET6
137090267Sdes	af = AF_UNSPEC;
137160737Sume#else
137290267Sdes	af = AF_INET;
137360737Sume#endif
137490267Sdes
137590267Sdes	verbose = CHECK_FLAG('v');
137690267Sdes	if (CHECK_FLAG('4'))
137790267Sdes		af = AF_INET;
137867043Sdes#ifdef INET6
137990267Sdes	else if (CHECK_FLAG('6'))
138090267Sdes		af = AF_INET6;
138167043Sdes#endif
138267043Sdes
138397868Sdes	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
138490267Sdes		URL = purl;
138590267Sdes	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
138690267Sdes		/* can't talk http to an ftp server */
138790267Sdes		/* XXX should set an error code */
138897856Sdes		return (NULL);
138990267Sdes	}
139090267Sdes
1391174588Sdes	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1392174588Sdes		/* fetch_connect() has already set an error code */
139397856Sdes		return (NULL);
139497868Sdes	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1395174588Sdes	    fetch_ssl(conn, verbose) == -1) {
1396174588Sdes		fetch_close(conn);
139797891Sdes		/* grrr */
139897891Sdes		errno = EAUTH;
1399174588Sdes		fetch_syserr();
140097868Sdes		return (NULL);
140197868Sdes	}
1402141958Skbyanc
1403141958Skbyanc	val = 1;
1404141958Skbyanc	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1405141958Skbyanc
140697856Sdes	return (conn);
140767043Sdes}
140867043Sdes
140967043Sdesstatic struct url *
1410174752Sdeshttp_get_proxy(struct url * url, const char *flags)
141167043Sdes{
141290267Sdes	struct url *purl;
141390267Sdes	char *p;
141490267Sdes
1415112797Sdes	if (flags != NULL && strchr(flags, 'd') != NULL)
1416112081Sdes		return (NULL);
1417174752Sdes	if (fetch_no_proxy_match(url->host))
1418174752Sdes		return (NULL);
141990267Sdes	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1420149414Sdes	    *p && (purl = fetchParseURL(p))) {
142190267Sdes		if (!*purl->scheme)
142290267Sdes			strcpy(purl->scheme, SCHEME_HTTP);
142390267Sdes		if (!purl->port)
1424174588Sdes			purl->port = fetch_default_proxy_port(purl->scheme);
142590267Sdes		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
142690267Sdes			return (purl);
142790267Sdes		fetchFreeURL(purl);
142890267Sdes	}
142990267Sdes	return (NULL);
143060376Sdes}
143160376Sdes
143288771Sdesstatic void
1433174588Sdeshttp_print_html(FILE *out, FILE *in)
143488771Sdes{
143590267Sdes	size_t len;
143690267Sdes	char *line, *p, *q;
143790267Sdes	int comment, tag;
143888771Sdes
143990267Sdes	comment = tag = 0;
144090267Sdes	while ((line = fgetln(in, &len)) != NULL) {
1441174761Sdes		while (len && isspace((unsigned char)line[len - 1]))
144290267Sdes			--len;
144390267Sdes		for (p = q = line; q < line + len; ++q) {
144490267Sdes			if (comment && *q == '-') {
144590267Sdes				if (q + 2 < line + len &&
144690267Sdes				    strcmp(q, "-->") == 0) {
144790267Sdes					tag = comment = 0;
144890267Sdes					q += 2;
144990267Sdes				}
145090267Sdes			} else if (tag && !comment && *q == '>') {
145190267Sdes				p = q + 1;
145290267Sdes				tag = 0;
145390267Sdes			} else if (!tag && *q == '<') {
145490267Sdes				if (q > p)
145590267Sdes					fwrite(p, q - p, 1, out);
145690267Sdes				tag = 1;
145790267Sdes				if (q + 3 < line + len &&
145890267Sdes				    strcmp(q, "<!--") == 0) {
145990267Sdes					comment = 1;
146090267Sdes					q += 3;
146190267Sdes				}
146290267Sdes			}
146388771Sdes		}
146490267Sdes		if (!tag && q > p)
146590267Sdes			fwrite(p, q - p, 1, out);
146690267Sdes		fputc('\n', out);
146788771Sdes	}
146888771Sdes}
146988771Sdes
147090267Sdes
147163012Sdes/*****************************************************************************
147263012Sdes * Core
147360954Sdes */
147460954Sdes
147560954Sdes/*
147663012Sdes * Send a request and process the reply
147797866Sdes *
147897866Sdes * XXX This function is way too long, the do..while loop should be split
147997866Sdes * XXX off into a separate function.
148060376Sdes */
148167043SdesFILE *
1482174588Sdeshttp_request(struct url *URL, const char *op, struct url_stat *us,
1483202613Sdes	struct url *purl, const char *flags)
148460376Sdes{
1485186124Smurray	char timebuf[80];
1486186124Smurray	char hbuf[MAXHOSTNAMELEN + 7], *host;
148797856Sdes	conn_t *conn;
148890267Sdes	struct url *url, *new;
1489202613Sdes	int chunked, direct, ims, noredirect, verbose;
1490143049Skbyanc	int e, i, n, val;
149190267Sdes	off_t offset, clength, length, size;
149290267Sdes	time_t mtime;
149390267Sdes	const char *p;
149490267Sdes	FILE *f;
149590267Sdes	hdr_t h;
1496186124Smurray	struct tm *timestruct;
1497202613Sdes	http_headerbuf_t headerbuf;
1498202613Sdes	http_auth_challenges_t server_challenges;
1499202613Sdes	http_auth_challenges_t proxy_challenges;
150063012Sdes
1501202613Sdes	/* The following calls don't allocate anything */
1502221821Sdes	init_http_headerbuf(&headerbuf);
1503202613Sdes	init_http_auth_challenges(&server_challenges);
1504202613Sdes	init_http_auth_challenges(&proxy_challenges);
1505202613Sdes
150690267Sdes	direct = CHECK_FLAG('d');
150790267Sdes	noredirect = CHECK_FLAG('A');
150890267Sdes	verbose = CHECK_FLAG('v');
1509186124Smurray	ims = CHECK_FLAG('i');
151060737Sume
151190267Sdes	if (direct && purl) {
151290267Sdes		fetchFreeURL(purl);
151390267Sdes		purl = NULL;
151490267Sdes	}
151563716Sdes
151690267Sdes	/* try the provided URL first */
151790267Sdes	url = URL;
151863012Sdes
151990267Sdes	/* if the A flag is set, we only get one try */
152090267Sdes	n = noredirect ? 1 : MAX_REDIRECT;
152190267Sdes	i = 0;
152263012Sdes
152398422Sdes	e = HTTP_PROTOCOL_ERROR;
152490267Sdes	do {
152590267Sdes		new = NULL;
152690267Sdes		chunked = 0;
152790267Sdes		offset = 0;
152890267Sdes		clength = -1;
152990267Sdes		length = -1;
153090267Sdes		size = -1;
153190267Sdes		mtime = 0;
153290267Sdes
153390267Sdes		/* check port */
153490267Sdes		if (!url->port)
1535174588Sdes			url->port = fetch_default_port(url->scheme);
153690267Sdes
153790267Sdes		/* were we redirected to an FTP URL? */
153890267Sdes		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
153990267Sdes			if (strcmp(op, "GET") == 0)
1540174588Sdes				return (ftp_request(url, "RETR", us, purl, flags));
154190267Sdes			else if (strcmp(op, "HEAD") == 0)
1542174588Sdes				return (ftp_request(url, "STAT", us, purl, flags));
154390267Sdes		}
154490267Sdes
154590267Sdes		/* connect to server or proxy */
1546174588Sdes		if ((conn = http_connect(url, purl, flags)) == NULL)
154790267Sdes			goto ouch;
154890267Sdes
154990267Sdes		host = url->host;
155060737Sume#ifdef INET6
155190267Sdes		if (strchr(url->host, ':')) {
155290267Sdes			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
155390267Sdes			host = hbuf;
155490267Sdes		}
155560737Sume#endif
1556174588Sdes		if (url->port != fetch_default_port(url->scheme)) {
1557107372Sdes			if (host != hbuf) {
1558107372Sdes				strcpy(hbuf, host);
1559107372Sdes				host = hbuf;
1560107372Sdes			}
1561107372Sdes			snprintf(hbuf + strlen(hbuf),
1562107372Sdes			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1563107372Sdes		}
156437535Sdes
156590267Sdes		/* send request */
156690267Sdes		if (verbose)
1567174588Sdes			fetch_info("requesting %s://%s%s",
1568107372Sdes			    url->scheme, host, url->doc);
156990267Sdes		if (purl) {
1570174588Sdes			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1571107372Sdes			    op, url->scheme, host, url->doc);
157290267Sdes		} else {
1573174588Sdes			http_cmd(conn, "%s %s HTTP/1.1",
157490267Sdes			    op, url->doc);
157590267Sdes		}
157637535Sdes
1577186124Smurray		if (ims && url->ims_time) {
1578186124Smurray			timestruct = gmtime((time_t *)&url->ims_time);
1579186124Smurray			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1580186124Smurray			    timestruct);
1581186124Smurray			if (verbose)
1582186124Smurray				fetch_info("If-Modified-Since: %s", timebuf);
1583186124Smurray			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1584186124Smurray		}
158590267Sdes		/* virtual host */
1586174588Sdes		http_cmd(conn, "Host: %s", host);
158790267Sdes
1588221821Sdes		/*
1589221821Sdes		 * Proxy authorization: we only send auth after we received
1590221821Sdes		 * a 407 error. We do not first try basic anyway (changed
1591221821Sdes		 * when support was added for digest-auth)
1592221821Sdes		 */
1593202613Sdes		if (purl && proxy_challenges.valid) {
1594202613Sdes			http_auth_params_t aparams;
1595202613Sdes			init_http_auth_params(&aparams);
1596202613Sdes			if (*purl->user || *purl->pwd) {
1597221821Sdes				aparams.user = purl->user ?
1598202613Sdes					strdup(purl->user) : strdup("");
1599202613Sdes				aparams.password = purl->pwd?
1600202613Sdes					strdup(purl->pwd) : strdup("");
1601221821Sdes			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1602202613Sdes				   *p != '\0') {
1603202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1604202613Sdes					http_seterr(HTTP_NEED_PROXY_AUTH);
1605202613Sdes					goto ouch;
1606202613Sdes				}
1607202613Sdes			}
1608221821Sdes			http_authorize(conn, "Proxy-Authorization",
1609202613Sdes				       &proxy_challenges, &aparams, url);
1610202613Sdes			clean_http_auth_params(&aparams);
161190267Sdes		}
161290267Sdes
1613221821Sdes		/*
1614221821Sdes		 * Server authorization: we never send "a priori"
1615202613Sdes		 * Basic auth, which used to be done if user/pass were
1616202613Sdes		 * set in the url. This would be weird because we'd send the
1617221821Sdes		 * password in the clear even if Digest is finally to be
1618202613Sdes		 * used (it would have made more sense for the
1619221821Sdes		 * pre-digest version to do this when Basic was specified
1620221821Sdes		 * in the environment)
1621221821Sdes		 */
1622202613Sdes		if (server_challenges.valid) {
1623202613Sdes			http_auth_params_t aparams;
1624202613Sdes			init_http_auth_params(&aparams);
1625202613Sdes			if (*url->user || *url->pwd) {
1626221821Sdes				aparams.user = url->user ?
1627202613Sdes					strdup(url->user) : strdup("");
1628221821Sdes				aparams.password = url->pwd ?
1629202613Sdes					strdup(url->pwd) : strdup("");
1630221821Sdes			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1631202613Sdes				   *p != '\0') {
1632202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1633202613Sdes					http_seterr(HTTP_NEED_AUTH);
1634202613Sdes					goto ouch;
1635202613Sdes				}
1636221821Sdes			} else if (fetchAuthMethod &&
1637202613Sdes				   fetchAuthMethod(url) == 0) {
1638221821Sdes				aparams.user = url->user ?
1639202613Sdes					strdup(url->user) : strdup("");
1640221821Sdes				aparams.password = url->pwd ?
1641202613Sdes					strdup(url->pwd) : strdup("");
164290267Sdes			} else {
1643174588Sdes				http_seterr(HTTP_NEED_AUTH);
164490267Sdes				goto ouch;
164590267Sdes			}
1646221821Sdes			http_authorize(conn, "Authorization",
1647202613Sdes				       &server_challenges, &aparams, url);
1648202613Sdes			clean_http_auth_params(&aparams);
164990267Sdes		}
165090267Sdes
165190267Sdes		/* other headers */
1652107372Sdes		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1653107372Sdes			if (strcasecmp(p, "auto") == 0)
1654174588Sdes				http_cmd(conn, "Referer: %s://%s%s",
1655107372Sdes				    url->scheme, host, url->doc);
1656107372Sdes			else
1657174588Sdes				http_cmd(conn, "Referer: %s", p);
1658107372Sdes		}
165990267Sdes		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1660174588Sdes			http_cmd(conn, "User-Agent: %s", p);
166190267Sdes		else
1662174588Sdes			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1663109693Sdes		if (url->offset > 0)
1664174588Sdes			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1665174588Sdes		http_cmd(conn, "Connection: close");
1666174588Sdes		http_cmd(conn, "");
166790267Sdes
1668143049Skbyanc		/*
1669143049Skbyanc		 * Force the queued request to be dispatched.  Normally, one
1670143049Skbyanc		 * would do this with shutdown(2) but squid proxies can be
1671143049Skbyanc		 * configured to disallow such half-closed connections.  To
1672143049Skbyanc		 * be compatible with such configurations, fiddle with socket
1673143049Skbyanc		 * options to force the pending data to be written.
1674143049Skbyanc		 */
1675143049Skbyanc		val = 0;
1676143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1677143049Skbyanc			   sizeof(val));
1678143049Skbyanc		val = 1;
1679143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1680143049Skbyanc			   sizeof(val));
1681143049Skbyanc
168290267Sdes		/* get reply */
1683174588Sdes		switch (http_get_reply(conn)) {
168490267Sdes		case HTTP_OK:
168590267Sdes		case HTTP_PARTIAL:
1686186124Smurray		case HTTP_NOT_MODIFIED:
168790267Sdes			/* fine */
168890267Sdes			break;
168990267Sdes		case HTTP_MOVED_PERM:
169090267Sdes		case HTTP_MOVED_TEMP:
169190267Sdes		case HTTP_SEE_OTHER:
169290267Sdes			/*
1693125695Sdes			 * Not so fine, but we still have to read the
1694125695Sdes			 * headers to get the new location.
169590267Sdes			 */
169690267Sdes			break;
169790267Sdes		case HTTP_NEED_AUTH:
1698202613Sdes			if (server_challenges.valid) {
169990267Sdes				/*
1700125695Sdes				 * We already sent out authorization code,
1701125695Sdes				 * so there's nothing more we can do.
170290267Sdes				 */
1703174588Sdes				http_seterr(conn->err);
170490267Sdes				goto ouch;
170590267Sdes			}
170690267Sdes			/* try again, but send the password this time */
170790267Sdes			if (verbose)
1708174588Sdes				fetch_info("server requires authorization");
170990267Sdes			break;
171090267Sdes		case HTTP_NEED_PROXY_AUTH:
1711202613Sdes			if (proxy_challenges.valid) {
1712202613Sdes				/*
1713202613Sdes				 * We already sent our proxy
1714202613Sdes				 * authorization code, so there's
1715202613Sdes				 * nothing more we can do. */
1716202613Sdes				http_seterr(conn->err);
1717202613Sdes				goto ouch;
1718202613Sdes			}
1719202613Sdes			/* try again, but send the password this time */
1720202613Sdes			if (verbose)
1721202613Sdes				fetch_info("proxy requires authorization");
1722202613Sdes			break;
1723125696Sdes		case HTTP_BAD_RANGE:
1724125696Sdes			/*
1725125696Sdes			 * This can happen if we ask for 0 bytes because
1726125696Sdes			 * we already have the whole file.  Consider this
1727125696Sdes			 * a success for now, and check sizes later.
1728125696Sdes			 */
1729125696Sdes			break;
173090267Sdes		case HTTP_PROTOCOL_ERROR:
173190267Sdes			/* fall through */
173290267Sdes		case -1:
1733174588Sdes			fetch_syserr();
173490267Sdes			goto ouch;
173590267Sdes		default:
1736174588Sdes			http_seterr(conn->err);
173790267Sdes			if (!verbose)
173890267Sdes				goto ouch;
173990267Sdes			/* fall through so we can get the full error message */
174090267Sdes		}
174190267Sdes
1742202613Sdes		/* get headers. http_next_header expects one line readahead */
1743202613Sdes		if (fetch_getln(conn) == -1) {
1744202613Sdes		    fetch_syserr();
1745202613Sdes		    goto ouch;
1746202613Sdes		}
174790267Sdes		do {
1748202613Sdes		    switch ((h = http_next_header(conn, &headerbuf, &p))) {
174990267Sdes			case hdr_syserror:
1750174588Sdes				fetch_syserr();
175190267Sdes				goto ouch;
175290267Sdes			case hdr_error:
1753174588Sdes				http_seterr(HTTP_PROTOCOL_ERROR);
175490267Sdes				goto ouch;
175590267Sdes			case hdr_content_length:
1756174588Sdes				http_parse_length(p, &clength);
175790267Sdes				break;
175890267Sdes			case hdr_content_range:
1759174588Sdes				http_parse_range(p, &offset, &length, &size);
176090267Sdes				break;
176190267Sdes			case hdr_last_modified:
1762174588Sdes				http_parse_mtime(p, &mtime);
176390267Sdes				break;
176490267Sdes			case hdr_location:
176597856Sdes				if (!HTTP_REDIRECT(conn->err))
176690267Sdes					break;
176790267Sdes				if (new)
176890267Sdes					free(new);
176990267Sdes				if (verbose)
1770174588Sdes					fetch_info("%d redirect to %s", conn->err, p);
177190267Sdes				if (*p == '/')
177290267Sdes					/* absolute path */
177390267Sdes					new = fetchMakeURL(url->scheme, url->host, url->port, p,
177490267Sdes					    url->user, url->pwd);
177590267Sdes				else
177690267Sdes					new = fetchParseURL(p);
177790267Sdes				if (new == NULL) {
177890267Sdes					/* XXX should set an error code */
177990267Sdes					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
178090267Sdes					goto ouch;
178190267Sdes				}
178290267Sdes				if (!*new->user && !*new->pwd) {
178390267Sdes					strcpy(new->user, url->user);
178490267Sdes					strcpy(new->pwd, url->pwd);
178590267Sdes				}
178690267Sdes				new->offset = url->offset;
178790267Sdes				new->length = url->length;
178890267Sdes				break;
178990267Sdes			case hdr_transfer_encoding:
179090267Sdes				/* XXX weak test*/
179190267Sdes				chunked = (strcasecmp(p, "chunked") == 0);
179290267Sdes				break;
179390267Sdes			case hdr_www_authenticate:
179497856Sdes				if (conn->err != HTTP_NEED_AUTH)
179590267Sdes					break;
1796210563Sdes				if (http_parse_authenticate(p, &server_challenges) == 0)
1797209632Sdes					++n;
179890267Sdes				break;
1799202613Sdes			case hdr_proxy_authenticate:
1800202613Sdes				if (conn->err != HTTP_NEED_PROXY_AUTH)
1801202613Sdes					break;
1802210563Sdes				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1803209632Sdes					++n;
1804202613Sdes				break;
180590267Sdes			case hdr_end:
180690267Sdes				/* fall through */
180790267Sdes			case hdr_unknown:
180890267Sdes				/* ignore */
180990267Sdes				break;
181090267Sdes			}
181190267Sdes		} while (h > hdr_end);
181290267Sdes
181390267Sdes		/* we need to provide authentication */
1814221821Sdes		if (conn->err == HTTP_NEED_AUTH ||
1815202613Sdes		    conn->err == HTTP_NEED_PROXY_AUTH) {
181698422Sdes			e = conn->err;
1817221821Sdes			if ((conn->err == HTTP_NEED_AUTH &&
1818221821Sdes			     !server_challenges.valid) ||
1819221821Sdes			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1820202613Sdes			     !proxy_challenges.valid)) {
1821202613Sdes				/* 401/7 but no www/proxy-authenticate ?? */
1822202613Sdes				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1823202613Sdes				goto ouch;
1824202613Sdes			}
1825174588Sdes			fetch_close(conn);
182697856Sdes			conn = NULL;
182790267Sdes			continue;
182890267Sdes		}
182990267Sdes
1830125696Sdes		/* requested range not satisfiable */
1831125696Sdes		if (conn->err == HTTP_BAD_RANGE) {
1832125696Sdes			if (url->offset == size && url->length == 0) {
1833125696Sdes				/* asked for 0 bytes; fake it */
1834125696Sdes				offset = url->offset;
1835184222Sru				clength = -1;
1836125696Sdes				conn->err = HTTP_OK;
1837125696Sdes				break;
1838125696Sdes			} else {
1839174588Sdes				http_seterr(conn->err);
1840125696Sdes				goto ouch;
1841125696Sdes			}
1842125696Sdes		}
1843125696Sdes
1844104404Sru		/* we have a hit or an error */
1845186124Smurray		if (conn->err == HTTP_OK
1846186124Smurray		    || conn->err == HTTP_NOT_MODIFIED
1847186124Smurray		    || conn->err == HTTP_PARTIAL
1848186124Smurray		    || HTTP_ERROR(conn->err))
1849104404Sru			break;
1850104404Sru
185190267Sdes		/* all other cases: we got a redirect */
185298422Sdes		e = conn->err;
1853202613Sdes		clean_http_auth_challenges(&server_challenges);
1854174588Sdes		fetch_close(conn);
185597856Sdes		conn = NULL;
185690267Sdes		if (!new) {
185790267Sdes			DEBUG(fprintf(stderr, "redirect with no new location\n"));
185890267Sdes			break;
185990267Sdes		}
186090267Sdes		if (url != URL)
186190267Sdes			fetchFreeURL(url);
186290267Sdes		url = new;
186390267Sdes	} while (++i < n);
186490267Sdes
186590267Sdes	/* we failed, or ran out of retries */
186697856Sdes	if (conn == NULL) {
1867174588Sdes		http_seterr(e);
186863012Sdes		goto ouch;
186963012Sdes	}
187060376Sdes
187190267Sdes	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
187290267Sdes		  " size %lld, clength %lld\n",
187390267Sdes		  (long long)offset, (long long)length,
187490267Sdes		  (long long)size, (long long)clength));
187560376Sdes
1876186124Smurray	if (conn->err == HTTP_NOT_MODIFIED) {
1877186124Smurray		http_seterr(HTTP_NOT_MODIFIED);
1878186124Smurray		return (NULL);
1879186124Smurray	}
1880186124Smurray
188190267Sdes	/* check for inconsistencies */
188290267Sdes	if (clength != -1 && length != -1 && clength != length) {
1883174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
188463012Sdes		goto ouch;
188563012Sdes	}
188690267Sdes	if (clength == -1)
188790267Sdes		clength = length;
188890267Sdes	if (clength != -1)
188990267Sdes		length = offset + clength;
189090267Sdes	if (length != -1 && size != -1 && length != size) {
1891174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
189263012Sdes		goto ouch;
189390267Sdes	}
189490267Sdes	if (size == -1)
189590267Sdes		size = length;
189660376Sdes
189790267Sdes	/* fill in stats */
189890267Sdes	if (us) {
189990267Sdes		us->size = size;
190090267Sdes		us->atime = us->mtime = mtime;
190190267Sdes	}
190263069Sdes
190390267Sdes	/* too far? */
1904109693Sdes	if (URL->offset > 0 && offset > URL->offset) {
1905174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
190690267Sdes		goto ouch;
190777238Sdes	}
190860376Sdes
190990267Sdes	/* report back real offset and size */
191090267Sdes	URL->offset = offset;
191190267Sdes	URL->length = clength;
191237535Sdes
191390267Sdes	/* wrap it up in a FILE */
1914174588Sdes	if ((f = http_funopen(conn, chunked)) == NULL) {
1915174588Sdes		fetch_syserr();
191690267Sdes		goto ouch;
191790267Sdes	}
191863716Sdes
191990267Sdes	if (url != URL)
192090267Sdes		fetchFreeURL(url);
192190267Sdes	if (purl)
192290267Sdes		fetchFreeURL(purl);
192363567Sdes
192497856Sdes	if (HTTP_ERROR(conn->err)) {
1925174588Sdes		http_print_html(stderr, f);
192690267Sdes		fclose(f);
192790267Sdes		f = NULL;
192890267Sdes	}
1929202613Sdes	clean_http_headerbuf(&headerbuf);
1930202613Sdes	clean_http_auth_challenges(&server_challenges);
1931202613Sdes	clean_http_auth_challenges(&proxy_challenges);
193290267Sdes	return (f);
193388771Sdes
193490267Sdesouch:
193590267Sdes	if (url != URL)
193690267Sdes		fetchFreeURL(url);
193790267Sdes	if (purl)
193890267Sdes		fetchFreeURL(purl);
193997856Sdes	if (conn != NULL)
1940174588Sdes		fetch_close(conn);
1941202613Sdes	clean_http_headerbuf(&headerbuf);
1942202613Sdes	clean_http_auth_challenges(&server_challenges);
1943202613Sdes	clean_http_auth_challenges(&proxy_challenges);
194490267Sdes	return (NULL);
194563012Sdes}
194660189Sdes
194790267Sdes
194863012Sdes/*****************************************************************************
194963012Sdes * Entry points
195063012Sdes */
195163012Sdes
195263012Sdes/*
195363340Sdes * Retrieve and stat a file by HTTP
195463340Sdes */
195563340SdesFILE *
195675891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
195763340Sdes{
1958174752Sdes	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
195963340Sdes}
196063340Sdes
196163340Sdes/*
196263012Sdes * Retrieve a file by HTTP
196363012Sdes */
196463012SdesFILE *
196575891SarchiefetchGetHTTP(struct url *URL, const char *flags)
196663012Sdes{
196790267Sdes	return (fetchXGetHTTP(URL, NULL, flags));
196837535Sdes}
196937535Sdes
197063340Sdes/*
197163340Sdes * Store a file by HTTP
197263340Sdes */
197337535SdesFILE *
197485093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused)
197537535Sdes{
197690267Sdes	warnx("fetchPutHTTP(): not implemented");
197790267Sdes	return (NULL);
197837535Sdes}
197940975Sdes
198040975Sdes/*
198140975Sdes * Get an HTTP document's metadata
198240975Sdes */
198340975Sdesint
198475891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
198540975Sdes{
198690267Sdes	FILE *f;
198790267Sdes
1988174752Sdes	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
1989112081Sdes	if (f == NULL)
199090267Sdes		return (-1);
199190267Sdes	fclose(f);
199290267Sdes	return (0);
199340975Sdes}
199441989Sdes
199541989Sdes/*
199641989Sdes * List a directory
199741989Sdes */
199841989Sdesstruct url_ent *
199985093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused)
200041989Sdes{
200190267Sdes	warnx("fetchListHTTP(): not implemented");
200290267Sdes	return (NULL);
200341989Sdes}
2004