http.c revision 226537
162590Sitojun/*-
2122615Sume * Copyright (c) 2000-2011 Dag-Erling Sm��rgrav
362590Sitojun * All rights reserved.
455505Sshin *
555505Sshin * Redistribution and use in source and binary forms, with or without
655505Sshin * modification, are permitted provided that the following conditions
755505Sshin * are met:
855505Sshin * 1. Redistributions of source code must retain the above copyright
955505Sshin *    notice, this list of conditions and the following disclaimer
1055505Sshin *    in this position and unchanged.
1155505Sshin * 2. Redistributions in binary form must reproduce the above copyright
1255505Sshin *    notice, this list of conditions and the following disclaimer in the
1355505Sshin *    documentation and/or other materials provided with the distribution.
1455505Sshin * 3. The name of the author may not be used to endorse or promote products
1555505Sshin *    derived from this software without specific prior written permission.
1655505Sshin *
1755505Sshin * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1855505Sshin * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1955505Sshin * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2055505Sshin * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2155505Sshin * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2255505Sshin * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2355505Sshin * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2455505Sshin * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2555505Sshin * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2655505Sshin * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2755505Sshin */
2855505Sshin
2955505Sshin#include <sys/cdefs.h>
3055505Sshin__FBSDID("$FreeBSD: head/lib/libfetch/http.c 226537 2011-10-19 11:43:51Z des $");
3155505Sshin
3255505Sshin/*
3355505Sshin * The following copyright applies to the base64 code:
3455505Sshin *
3555505Sshin *-
3655505Sshin * Copyright 1997 Massachusetts Institute of Technology
3755505Sshin *
3855505Sshin * Permission to use, copy, modify, and distribute this software and
3955505Sshin * its documentation for any purpose and without fee is hereby
4055505Sshin * granted, provided that both the above copyright notice and this
4155505Sshin * permission notice appear in all copies, that both the above
4255505Sshin * copyright notice and this permission notice appear in all
4355505Sshin * supporting documentation, and that the name of M.I.T. not be used
4455505Sshin * in advertising or publicity pertaining to distribution of the
4555505Sshin * software without specific, written prior permission.  M.I.T. makes
4655505Sshin * no representations about the suitability of this software for any
4755505Sshin * purpose.  It is provided "as is" without express or implied
4855505Sshin * warranty.
4955505Sshin *
5055505Sshin * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
5155505Sshin * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
5255505Sshin * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5355505Sshin * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
5455505Sshin * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5555505Sshin * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5655505Sshin * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
5755505Sshin * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
5855505Sshin * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
5955505Sshin * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
6055505Sshin * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
6155505Sshin * SUCH DAMAGE.
6255505Sshin */
6355505Sshin
6455505Sshin#include <sys/param.h>
6555505Sshin#include <sys/socket.h>
6655505Sshin#include <sys/time.h>
6755505Sshin
6855505Sshin#include <ctype.h>
6955505Sshin#include <err.h>
7055505Sshin#include <errno.h>
7155505Sshin#include <locale.h>
7255505Sshin#include <netdb.h>
7355505Sshin#include <stdarg.h>
7455505Sshin#include <stdio.h>
7555505Sshin#include <stdlib.h>
7655505Sshin#include <string.h>
7755505Sshin#include <time.h>
7855505Sshin#include <unistd.h>
7955505Sshin#include <md5.h>
8055505Sshin
8155505Sshin#include <netinet/in.h>
82253999Shrs#include <netinet/tcp.h>
8378064Sume
8455505Sshin#include "fetch.h"
8555505Sshin#include "common.h"
8655505Sshin#include "httperr.h"
8755505Sshin
8855505Sshin/* Maximum number of redirects to follow */
8955505Sshin#define MAX_REDIRECT 5
9055505Sshin
9155505Sshin/* Symbolic names for reply codes we care about */
9255505Sshin#define HTTP_OK			200
9355505Sshin#define HTTP_PARTIAL		206
9455505Sshin#define HTTP_MOVED_PERM		301
9555505Sshin#define HTTP_MOVED_TEMP		302
9655505Sshin#define HTTP_SEE_OTHER		303
9755505Sshin#define HTTP_NOT_MODIFIED	304
9855505Sshin#define HTTP_TEMP_REDIRECT	307
99265778Smelifaro#define HTTP_NEED_AUTH		401
10055505Sshin#define HTTP_NEED_PROXY_AUTH	407
10155505Sshin#define HTTP_BAD_RANGE		416
10255505Sshin#define HTTP_PROTOCOL_ERROR	999
10355505Sshin
10455505Sshin#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
10555505Sshin			    || (xyz) == HTTP_MOVED_TEMP \
10655505Sshin			    || (xyz) == HTTP_TEMP_REDIRECT \
10755505Sshin			    || (xyz) == HTTP_SEE_OTHER)
10855505Sshin
10955505Sshin#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
11055505Sshin
11155505Sshin
112186119Sqingli/*****************************************************************************
113186119Sqingli * I/O functions for decoding chunked streams
114196866Sbz */
115186119Sqingli
116186119Sqinglistruct httpio
117100650Sjmallett{
11862590Sitojun	conn_t		*conn;		/* connection */
11962590Sitojun	int		 chunked;	/* chunked mode */
12062590Sitojun	char		*buf;		/* chunk buffer */
12162590Sitojun	size_t		 bufsize;	/* size of chunk buffer */
12262590Sitojun	ssize_t		 buflen;	/* amount of data currently in buffer */
12355505Sshin	int		 bufpos;	/* current read offset in buffer */
124287097Shrs	int		 eof;		/* end-of-file flag */
125287097Shrs	int		 error;		/* error flag */
12655505Sshin	size_t		 chunksize;	/* remaining size of current chunk */
127265778Smelifaro#ifndef NDEBUG
128287097Shrs	size_t		 total;
129287097Shrs#endif
130287097Shrs};
131287097Shrs
132287097Shrs/*
133173412Skevlo * Get next chunk header
134173412Skevlo */
135287097Shrsstatic int
136287097Shrshttp_new_chunk(struct httpio *io)
137287097Shrs{
138287097Shrs	char *p;
139287097Shrs
140287097Shrs	if (fetch_getln(io->conn) == -1)
141287097Shrs		return (-1);
142287097Shrs
143287097Shrs	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
14462590Sitojun		return (-1);
145173412Skevlo
146173412Skevlo	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
14762590Sitojun		if (*p == ';')
148173412Skevlo			break;
149253999Shrs		if (!isxdigit((unsigned char)*p))
15055505Sshin			return (-1);
15178064Sume		if (isdigit((unsigned char)*p)) {
15278064Sume			io->chunksize = io->chunksize * 16 +
15378064Sume			    *p - '0';
15478064Sume		} else {
15578064Sume			io->chunksize = io->chunksize * 16 +
15678064Sume			    10 + tolower((unsigned char)*p) - 'a';
15778064Sume		}
15855505Sshin	}
159259169Sae
16055505Sshin#ifndef NDEBUG
161287097Shrs	if (fetchDebug) {
162287097Shrs		io->total += io->chunksize;
16355505Sshin		if (io->chunksize == 0)
16455505Sshin			fprintf(stderr, "%s(): end of last chunk\n", __func__);
16555505Sshin		else
166122615Sume			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
167121156Sume			    __func__, (unsigned long)io->chunksize,
16855505Sshin			    (unsigned long)io->total);
16955505Sshin	}
170122615Sume#endif
171122615Sume
172122615Sume	return (io->chunksize);
173122615Sume}
174122615Sume
175122615Sume/*
176122615Sume * Grow the input buffer to at least len bytes
177122615Sume */
178122615Sumestatic inline int
179122615Sumehttp_growbuf(struct httpio *io, size_t len)
180122615Sume{
181122615Sume	char *tmp;
182122615Sume
18355505Sshin	if (io->bufsize >= len)
184122615Sume		return (0);
185265778Smelifaro
186268827Speter	if ((tmp = realloc(io->buf, len)) == NULL)
187265778Smelifaro		return (-1);
188122615Sume	io->buf = tmp;
18955505Sshin	io->bufsize = len;
190122615Sume	return (0);
191122615Sume}
192122615Sume
193122615Sume/*
194122615Sume * Fill the input buffer, do chunk decoding on the fly
19555505Sshin */
19655505Sshinstatic int
19755505Sshinhttp_fillbuf(struct httpio *io, size_t len)
19855505Sshin{
19955505Sshin	if (io->error)
20055505Sshin		return (-1);
20155505Sshin	if (io->eof)
202122615Sume		return (0);
203122615Sume
204122615Sume	if (io->chunked == 0) {
205122615Sume		if (http_growbuf(io, len) == -1)
206122615Sume			return (-1);
20755505Sshin		if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) {
208122615Sume			io->error = 1;
20955505Sshin			return (-1);
210122615Sume		}
211122615Sume		io->bufpos = 0;
21255505Sshin		return (io->buflen);
21355505Sshin	}
21455505Sshin
21555505Sshin	if (io->chunksize == 0) {
21655505Sshin		switch (http_new_chunk(io)) {
21755505Sshin		case -1:
21855505Sshin			io->error = 1;
21955505Sshin			return (-1);
220122615Sume		case 0:
221122615Sume			io->eof = 1;
222122615Sume			return (0);
223122615Sume		}
22455505Sshin	}
225122615Sume
226122615Sume	if (len > io->chunksize)
227122615Sume		len = io->chunksize;
228122615Sume	if (http_growbuf(io, len) == -1)
229122615Sume		return (-1);
230122615Sume	if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) {
231122615Sume		io->error = 1;
232122615Sume		return (-1);
233122615Sume	}
234122615Sume	io->chunksize -= io->buflen;
235122615Sume
236122615Sume	if (io->chunksize == 0) {
237122615Sume		char endl[2];
238122615Sume
239122615Sume		if (fetch_read(io->conn, endl, 2) != 2 ||
240122615Sume		    endl[0] != '\r' || endl[1] != '\n')
241122615Sume			return (-1);
242122615Sume	}
243122615Sume
244122615Sume	io->bufpos = 0;
245122615Sume
246122615Sume	return (io->buflen);
247122615Sume}
248122615Sume
249122615Sume/*
250122615Sume * Read function
251122615Sume */
252122615Sumestatic int
253122615Sumehttp_readfn(void *v, char *buf, int len)
254122615Sume{
255122615Sume	struct httpio *io = (struct httpio *)v;
256122615Sume	int l, pos;
257122615Sume
258122615Sume	if (io->error)
25955505Sshin		return (-1);
260122615Sume	if (io->eof)
261122615Sume		return (0);
262122615Sume
263122615Sume	for (pos = 0; len > 0; pos += l, len -= l) {
264122615Sume		/* empty buffer */
265122615Sume		if (!io->buf || io->bufpos == io->buflen)
266122615Sume			if (http_fillbuf(io, len) < 1)
267122615Sume				break;
268122615Sume		l = io->buflen - io->bufpos;
26955505Sshin		if (len < l)
270122615Sume			l = len;
271122615Sume		memcpy(buf + pos, io->buf + io->bufpos, l);
27255505Sshin		io->bufpos += l;
27355505Sshin	}
27455505Sshin
275122615Sume	if (!pos && io->error)
276122615Sume		return (-1);
277122615Sume	return (pos);
278122615Sume}
279122615Sume
28055505Sshin/*
281122615Sume * Write function
282122615Sume */
283122615Sumestatic int
284122615Sumehttp_writefn(void *v, const char *buf, int len)
285122615Sume{
286122615Sume	struct httpio *io = (struct httpio *)v;
28755505Sshin
288122615Sume	return (fetch_write(io->conn, buf, len));
289122615Sume}
290122615Sume
291122615Sume/*
292122615Sume * Close function
293122615Sume */
29455505Sshinstatic int
295122615Sumehttp_closefn(void *v)
296122615Sume{
297122615Sume	struct httpio *io = (struct httpio *)v;
298122615Sume	int r;
299122615Sume
300122615Sume	r = fetch_close(io->conn);
301122615Sume	if (io->buf)
302122615Sume		free(io->buf);
30355505Sshin	free(io);
30455505Sshin	return (r);
30555505Sshin}
30655505Sshin
30755505Sshin/*
30855505Sshin * Wrap a file descriptor up
30955505Sshin */
310265778Smelifarostatic FILE *
311259169Saehttp_funopen(conn_t *conn, int chunked)
31255505Sshin{
31355505Sshin	struct httpio *io;
31455505Sshin	FILE *f;
315265778Smelifaro
31655505Sshin	if ((io = calloc(1, sizeof(*io))) == NULL) {
317265778Smelifaro		fetch_syserr();
318265778Smelifaro		return (NULL);
31955505Sshin	}
32055505Sshin	io->conn = conn;
32155505Sshin	io->chunked = chunked;
32255505Sshin	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
32355505Sshin	if (f == NULL) {
32455505Sshin		fetch_syserr();
325167260Skevlo		free(io);
326265778Smelifaro		return (NULL);
327265778Smelifaro	}
328265778Smelifaro	return (f);
329265778Smelifaro}
330265778Smelifaro
331122615Sume
332122615Sume/*****************************************************************************
33355505Sshin * Helper functions for talking to the server and parsing its replies
334265778Smelifaro */
33555505Sshin
33655505Sshin/* Header types */
33755505Sshintypedef enum {
33855505Sshin	hdr_syserror = -2,
33955505Sshin	hdr_error = -1,
34055505Sshin	hdr_end = 0,
34155505Sshin	hdr_unknown = 1,
34255505Sshin	hdr_content_length,
34355505Sshin	hdr_content_range,
34455505Sshin	hdr_last_modified,
345287097Shrs	hdr_location,
34655505Sshin	hdr_transfer_encoding,
34755505Sshin	hdr_www_authenticate,
34855505Sshin	hdr_proxy_authenticate,
34955505Sshin} hdr_t;
35055505Sshin
351121156Sume/* Names of interesting headers */
352121156Sumestatic struct {
35355505Sshin	hdr_t		 num;
35455505Sshin	const char	*name;
35555505Sshin} hdr_names[] = {
35655505Sshin	{ hdr_content_length,		"Content-Length" },
357287097Shrs	{ hdr_content_range,		"Content-Range" },
358287097Shrs	{ hdr_last_modified,		"Last-Modified" },
359287097Shrs	{ hdr_location,			"Location" },
360287097Shrs	{ hdr_transfer_encoding,	"Transfer-Encoding" },
361287097Shrs	{ hdr_www_authenticate,		"WWW-Authenticate" },
362287097Shrs	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
363287097Shrs	{ hdr_unknown,			NULL },
364287097Shrs};
365287097Shrs
366287097Shrs/*
367287097Shrs * Send a formatted line; optionally echo to terminal
368287097Shrs */
369287097Shrsstatic int
370287097Shrshttp_cmd(conn_t *conn, const char *fmt, ...)
371287097Shrs{
372287097Shrs	va_list ap;
373287097Shrs	size_t len;
37455505Sshin	char *msg;
37555505Sshin	int r;
376287097Shrs
37755505Sshin	va_start(ap, fmt);
37855505Sshin	len = vasprintf(&msg, fmt, ap);
37955505Sshin	va_end(ap);
38055505Sshin
381287097Shrs	if (msg == NULL) {
382259169Sae		errno = ENOMEM;
38355505Sshin		fetch_syserr();
38455505Sshin		return (-1);
38555505Sshin	}
38655505Sshin
38755505Sshin	r = fetch_putln(conn, msg, len);
38855505Sshin	free(msg);
38955505Sshin
39055505Sshin	if (r == -1) {
39155505Sshin		fetch_syserr();
39255505Sshin		return (-1);
39355505Sshin	}
39455505Sshin
39555505Sshin	return (0);
39655505Sshin}
39755505Sshin
39855505Sshin/*
39955505Sshin * Get and parse status line
40055505Sshin */
40155505Sshinstatic int
40255505Sshinhttp_get_reply(conn_t *conn)
40355505Sshin{
40455505Sshin	char *p;
40555505Sshin
40655505Sshin	if (fetch_getln(conn) == -1)
407243903Shrs		return (-1);
408243903Shrs	/*
40955505Sshin	 * A valid status line looks like "HTTP/m.n xyz reason" where m
41055505Sshin	 * and n are the major and minor protocol version numbers and xyz
41155505Sshin	 * is the reply code.
41255505Sshin	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
41355505Sshin	 * just one) that do not send a version number, so we can't rely
41455505Sshin	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
415253999Shrs	 * We don't care about the reason phrase.
416121156Sume	 */
417253999Shrs	if (strncmp(conn->buf, "HTTP", 4) != 0)
418253970Shrs		return (HTTP_PROTOCOL_ERROR);
41962590Sitojun	p = conn->buf + 4;
42062590Sitojun	if (*p == '/') {
42155505Sshin		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
42255505Sshin			return (HTTP_PROTOCOL_ERROR);
42355505Sshin		p += 4;
424121156Sume	}
425121156Sume	if (*p != ' ' ||
42655505Sshin	    !isdigit((unsigned char)p[1]) ||
42755505Sshin	    !isdigit((unsigned char)p[2]) ||
428259171Sae	    !isdigit((unsigned char)p[3]))
42955505Sshin		return (HTTP_PROTOCOL_ERROR);
43055505Sshin
431122615Sume	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
432122615Sume	return (conn->err);
433122615Sume}
434122615Sume
435210936Sjhb/*
436122615Sume * Check a header; if the type matches the given string, return a pointer
437122615Sume * to the beginning of the value.
43855505Sshin */
43962590Sitojunstatic const char *
44062590Sitojunhttp_match(const char *str, const char *hdr)
44155505Sshin{
44262590Sitojun	while (*str && *hdr &&
44355505Sshin	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
44455505Sshin		/* nothing */;
44555505Sshin	if (*str || *hdr != ':')
44655505Sshin		return (NULL);
44755505Sshin	while (*hdr && isspace((unsigned char)*++hdr))
44855505Sshin		/* nothing */;
44955505Sshin	return (hdr);
45055505Sshin}
45155505Sshin
45255505Sshin
45355505Sshin/*
45455505Sshin * Get the next header and return the appropriate symbolic code.  We
45555505Sshin * need to read one line ahead for checking for a continuation line
456287097Shrs * belonging to the current header (continuation lines start with
457259169Sae * white space).
45855505Sshin *
45955505Sshin * We get called with a fresh line already in the conn buffer, either
46055505Sshin * from the previous http_next_header() invocation, or, the first
46155505Sshin * time, from a fetch_getln() performed by our caller.
46255505Sshin *
46355505Sshin * This stops when we encounter an empty line (we dont read beyond the header
46455505Sshin * area).
46555505Sshin *
46655505Sshin * Note that the "headerbuf" is just a place to return the result. Its
46755505Sshin * contents are not used for the next call. This means that no cleanup
46855505Sshin * is needed when ie doing another connection, just call the cleanup when
469121156Sume * fully done to deallocate memory.
47055505Sshin */
47155505Sshin
47255505Sshin/* Limit the max number of continuation lines to some reasonable value */
473259176Sae#define HTTP_MAX_CONT_LINES 10
474259176Sae
475259176Sae/* Place into which to build a header from one or several lines */
47655505Sshintypedef struct {
47755505Sshin	char	*buf;		/* buffer */
478121156Sume	size_t	 bufsize;	/* buffer size */
479121156Sume	size_t	 buflen;	/* length of buffer contents */
48055505Sshin} http_headerbuf_t;
48155505Sshin
48255505Sshinstatic void
48355505Sshininit_http_headerbuf(http_headerbuf_t *buf)
48455505Sshin{
48555505Sshin	buf->buf = NULL;
48655505Sshin	buf->bufsize = 0;
48755505Sshin	buf->buflen = 0;
488287097Shrs}
489259169Sae
49055505Sshinstatic void
49155505Sshinclean_http_headerbuf(http_headerbuf_t *buf)
49255505Sshin{
493186119Sqingli	if (buf->buf)
49455505Sshin		free(buf->buf);
49555505Sshin	init_http_headerbuf(buf);
49655505Sshin}
49755505Sshin
49855505Sshin/* Remove whitespace at the end of the buffer */
49955505Sshinstatic void
50055505Sshinhttp_conn_trimright(conn_t *conn)
50155505Sshin{
50255505Sshin	while (conn->buflen &&
50355505Sshin	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
50455505Sshin		conn->buflen--;
50555505Sshin	conn->buf[conn->buflen] = '\0';
506121156Sume}
50755505Sshin
50855505Sshinstatic hdr_t
50955505Sshinhttp_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
510243903Shrs{
511243903Shrs	unsigned int i, len;
51255505Sshin
513121156Sume	/*
514121156Sume	 * Have to do the stripping here because of the first line. So
51555505Sshin	 * it's done twice for the subsequent lines. No big deal
51655505Sshin	 */
517259171Sae	http_conn_trimright(conn);
51855505Sshin	if (conn->buflen == 0)
51955505Sshin		return (hdr_end);
52062590Sitojun
52178064Sume	/* Copy the line to the headerbuf */
52255505Sshin	if (hbuf->bufsize < conn->buflen + 1) {
52362590Sitojun		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
52462590Sitojun			return (hdr_syserror);
52555505Sshin		hbuf->bufsize = conn->buflen + 1;
52662590Sitojun	}
52755505Sshin	strcpy(hbuf->buf, conn->buf);
52855505Sshin	hbuf->buflen = conn->buflen;
52955505Sshin
53055505Sshin	/*
53155505Sshin	 * Fetch possible continuation lines. Stop at 1st non-continuation
532186119Sqingli	 * and leave it in the conn buffer
533186119Sqingli	 */
534186119Sqingli	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
535186119Sqingli		if (fetch_getln(conn) == -1)
536186119Sqingli			return (hdr_syserror);
537186500Sqingli
53855505Sshin		/*
539243903Shrs		 * Note: we carry on the idea from the previous version
540243903Shrs		 * that a pure whitespace line is equivalent to an empty
541121156Sume		 * one (so it's not continuation and will be handled when
542121156Sume		 * we are called next)
54355505Sshin		 */
54455505Sshin		http_conn_trimright(conn);
54555505Sshin		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
54655505Sshin			break;
54755505Sshin
54855505Sshin		/* Got a continuation line. Concatenate to previous */
549122615Sume		len = hbuf->buflen + conn->buflen;
55078064Sume		if (hbuf->bufsize < len + 1) {
55178064Sume			len *= 2;
55278064Sume			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
55355505Sshin				return (hdr_syserror);
55455505Sshin			hbuf->bufsize = len + 1;
55555505Sshin		}
556287097Shrs		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
557259176Sae		hbuf->buflen += conn->buflen;
55855505Sshin	}
55955505Sshin
56055505Sshin	/*
56162590Sitojun	 * We could check for malformed headers but we don't really care.
56255505Sshin	 * A valid header starts with a token immediately followed by a
56355505Sshin	 * colon; a token is any sequence of non-control, non-whitespace
56455505Sshin	 * characters except "()<>@,;:\\\"{}".
56555505Sshin	 */
566253999Shrs	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
567292333Smelifaro		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
56855505Sshin			return (hdr_names[i].num);
56978064Sume
57078064Sume	return (hdr_unknown);
57162590Sitojun}
57278064Sume
57355505Sshin/**************************
57455505Sshin * [Proxy-]Authenticate header parsing
57566865Ssumikawa */
576122615Sume
57778064Sume/*
578122615Sume * Read doublequote-delimited string into output buffer obuf (allocated
57955505Sshin * by caller, whose responsibility it is to ensure that it's big enough)
58055505Sshin * cp points to the first char after the initial '"'
58155505Sshin * Handles \ quoting
58255505Sshin * Returns pointer to the first char after the terminating double quote, or
58355505Sshin * NULL for error.
58455505Sshin */
58555505Sshinstatic const char *
586186119Sqinglihttp_parse_headerstring(const char *cp, char *obuf)
58755505Sshin{
588186119Sqingli	for (;;) {
589186119Sqingli		switch (*cp) {
590186119Sqingli		case 0: /* Unterminated string */
59155505Sshin			*obuf = 0;
59255505Sshin			return (NULL);
59355505Sshin		case '"': /* Ending quote */
59455505Sshin			*obuf = 0;
595121156Sume			return (++cp);
59655505Sshin		case '\\':
59755505Sshin			if (*++cp == 0) {
59855505Sshin				*obuf = 0;
59955505Sshin				return (NULL);
60055505Sshin			}
60155505Sshin			/* FALLTHROUGH */
60255505Sshin		default:
60355505Sshin			*obuf++ = *cp++;
60455505Sshin		}
60555505Sshin	}
60655505Sshin}
607259171Sae
60878064Sume/* Http auth challenge schemes */
60978064Sumetypedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
61078064Sume
61178064Sume/* Data holder for a Basic or Digest challenge. */
61278064Sumetypedef struct {
61378064Sume	http_auth_schemes_t scheme;
61478064Sume	char	*realm;
61578064Sume	char	*qop;
616121156Sume	char	*nonce;
61778064Sume	char	*opaque;
61878064Sume	char	*algo;
61978064Sume	int	 stale;
62078064Sume	int	 nc; /* Nonce count */
62178064Sume} http_auth_challenge_t;
62278064Sume
62378064Sumestatic void
62478064Sumeinit_http_auth_challenge(http_auth_challenge_t *b)
625122615Sume{
626122615Sume	b->scheme = HTTPAS_UNKNOWN;
627122615Sume	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
62855505Sshin	b->stale = b->nc = 0;
629259176Sae}
630259176Sae
631259176Saestatic void
63255505Sshinclean_http_auth_challenge(http_auth_challenge_t *b)
63355505Sshin{
63455505Sshin	if (b->realm)
63555505Sshin		free(b->realm);
63655505Sshin	if (b->qop)
63755505Sshin		free(b->qop);
63855505Sshin	if (b->nonce)
63955505Sshin		free(b->nonce);
64055505Sshin	if (b->opaque)
64155505Sshin		free(b->opaque);
64255505Sshin	if (b->algo)
643121156Sume		free(b->algo);
644122615Sume	init_http_auth_challenge(b);
64581366Ssumikawa}
64681366Ssumikawa
64781366Ssumikawa/* Data holder for an array of challenges offered in an http response. */
648122615Sume#define MAX_CHALLENGES 10
649122615Sumetypedef struct {
650122615Sume	http_auth_challenge_t *challenges[MAX_CHALLENGES];
65181366Ssumikawa	int	count; /* Number of parsed challenges in the array */
652288297Smelifaro	int	valid; /* We did parse an authenticate header */
653288297Smelifaro} http_auth_challenges_t;
65466865Ssumikawa
65581366Ssumikawastatic void
65666865Ssumikawainit_http_auth_challenges(http_auth_challenges_t *cs)
65766865Ssumikawa{
658253999Shrs	int i;
65955505Sshin	for (i = 0; i < MAX_CHALLENGES; i++)
660253970Shrs		cs->challenges[i] = NULL;
66155505Sshin	cs->count = cs->valid = 0;
66278064Sume}
66378064Sume
66478064Sumestatic void
66578064Sumeclean_http_auth_challenges(http_auth_challenges_t *cs)
66678064Sume{
66778064Sume	int i;
66878064Sume	/* We rely on non-zero pointers being allocated, not on the count */
66978064Sume	for (i = 0; i < MAX_CHALLENGES; i++) {
67078064Sume		if (cs->challenges[i] != NULL) {
67178064Sume			clean_http_auth_challenge(cs->challenges[i]);
67278064Sume			free(cs->challenges[i]);
67378064Sume		}
67455505Sshin	}
67578064Sume	init_http_auth_challenges(cs);
67678064Sume}
67755505Sshin
678289677Seadler/*
679292333Smelifaro * Enumeration for lexical elements. Separators will be returned as their own
680292333Smelifaro * ascii value
681292333Smelifaro */
682292333Smelifarotypedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
683292333Smelifaro	      HTTPHL_ERROR = 259} http_header_lex_t;
684292333Smelifaro
685292333Smelifaro/*
68655505Sshin * Determine what kind of token comes next and return possible value
687292333Smelifaro * in buf, which is supposed to have been allocated big enough by
688292333Smelifaro * caller. Advance input pointer and return element type.
689292333Smelifaro */
690292333Smelifarostatic int
69178064Sumehttp_header_lex(const char **cpp, char *buf)
692292333Smelifaro{
693292333Smelifaro	size_t l;
694292333Smelifaro	/* Eat initial whitespace */
69578064Sume	*cpp += strspn(*cpp, " \t");
696292333Smelifaro	if (**cpp == 0)
697292333Smelifaro		return (HTTPHL_END);
698292333Smelifaro
699292333Smelifaro	/* Separator ? */
700292333Smelifaro	if (**cpp == ',' || **cpp == '=')
701292333Smelifaro		return (*((*cpp)++));
702292333Smelifaro
703292333Smelifaro	/* String ? */
704292333Smelifaro	if (**cpp == '"') {
705292333Smelifaro		*cpp = http_parse_headerstring(++*cpp, buf);
706292333Smelifaro		if (*cpp == NULL)
707292333Smelifaro			return (HTTPHL_ERROR);
708292333Smelifaro		return (HTTPHL_STRING);
709292333Smelifaro	}
710292333Smelifaro
711292333Smelifaro	/* Read other token, until separator or whitespace */
712292333Smelifaro	l = strcspn(*cpp, " \t,=");
713292333Smelifaro	memcpy(buf, *cpp, l);
71455505Sshin	buf[l] = 0;
71555505Sshin	*cpp += l;
716292333Smelifaro	return (HTTPHL_WORD);
717292333Smelifaro}
718292333Smelifaro
71962590Sitojun/*
72062590Sitojun * Read challenges from http xxx-authenticate header and accumulate them
72162590Sitojun * in the challenges list structure.
72262590Sitojun *
72362590Sitojun * Headers with multiple challenges are specified by rfc2617, but
724121156Sume * servers (ie: squid) often send them in separate headers instead,
725121156Sume * which in turn is forbidden by the http spec (multiple headers with
72662590Sitojun * the same name are only allowed for pure comma-separated lists, see
727287995Sdelphij * rfc2616 sec 4.2).
72862590Sitojun *
729121156Sume * We support both approaches anyway
73062590Sitojun */
731121156Sumestatic int
732121156Sumehttp_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
733121156Sume{
734121156Sume	int ret = -1;
735122615Sume	http_header_lex_t lex;
736122615Sume	char *key = malloc(strlen(cp) + 1);
737122615Sume	char *value = malloc(strlen(cp) + 1);
738122615Sume	char *buf = malloc(strlen(cp) + 1);
739122615Sume
74055505Sshin	if (key == NULL || value == NULL || buf == NULL) {
741122615Sume		fetch_syserr();
74255505Sshin		goto out;
74355505Sshin	}
744122615Sume
74555505Sshin	/* In any case we've seen the header and we set the valid bit */
74655505Sshin	cs->valid = 1;
74755505Sshin
74878064Sume	/* Need word first */
74978064Sume	lex = http_header_lex(&cp, key);
75055505Sshin	if (lex != HTTPHL_WORD)
75155505Sshin		goto out;
75255505Sshin
753125675Ssumikawa	/* Loop on challenges */
75455505Sshin	for (; cs->count < MAX_CHALLENGES; cs->count++) {
75555505Sshin		cs->challenges[cs->count] =
75655505Sshin			malloc(sizeof(http_auth_challenge_t));
75755505Sshin		if (cs->challenges[cs->count] == NULL) {
75855505Sshin			fetch_syserr();
75955505Sshin			goto out;
760259169Sae		}
76155505Sshin		init_http_auth_challenge(cs->challenges[cs->count]);
76255505Sshin		if (!strcasecmp(key, "basic")) {
76355505Sshin			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
76455505Sshin		} else if (!strcasecmp(key, "digest")) {
76555505Sshin			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
76655505Sshin		} else {
76755505Sshin			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
76855505Sshin			/*
76955505Sshin			 * Continue parsing as basic or digest may
77055505Sshin			 * follow, and the syntax is the same for
77155505Sshin			 * all. We'll just ignore this one when
77262590Sitojun			 * looking at the list
77362590Sitojun			 */
77455505Sshin		}
77555505Sshin
77655505Sshin		/* Loop on attributes */
77755505Sshin		for (;;) {
77855505Sshin			/* Key */
77955505Sshin			lex = http_header_lex(&cp, key);
78055505Sshin			if (lex != HTTPHL_WORD)
78155505Sshin				goto out;
78255505Sshin
783217140Sdelphij			/* Equal sign */
78455505Sshin			lex = http_header_lex(&cp, buf);
785121156Sume			if (lex != '=')
78655505Sshin				goto out;
787219819Sjeff
788217140Sdelphij			/* Value */
789217140Sdelphij			lex = http_header_lex(&cp, value);
790219819Sjeff			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
791219819Sjeff				goto out;
792219819Sjeff
793219819Sjeff			if (!strcasecmp(key, "realm"))
794121156Sume				cs->challenges[cs->count]->realm =
79555505Sshin					strdup(value);
796121156Sume			else if (!strcasecmp(key, "qop"))
79755505Sshin				cs->challenges[cs->count]->qop =
79855505Sshin					strdup(value);
799287097Shrs			else if (!strcasecmp(key, "nonce"))
800259169Sae				cs->challenges[cs->count]->nonce =
80155505Sshin					strdup(value);
80255505Sshin			else if (!strcasecmp(key, "opaque"))
80355505Sshin				cs->challenges[cs->count]->opaque =
80455505Sshin					strdup(value);
805121156Sume			else if (!strcasecmp(key, "algorithm"))
80655505Sshin				cs->challenges[cs->count]->algo =
80755505Sshin					strdup(value);
80855505Sshin			else if (!strcasecmp(key, "stale"))
80955505Sshin				cs->challenges[cs->count]->stale =
810121156Sume					strcasecmp(value, "no");
81155505Sshin			/* Else ignore unknown attributes */
81255505Sshin
81355505Sshin			/* Comma or Next challenge or End */
81455505Sshin			lex = http_header_lex(&cp, key);
815287097Shrs			/*
81655505Sshin			 * If we get a word here, this is the beginning of the
81755505Sshin			 * next challenge. Break the attributes loop
818122615Sume			 */
819122615Sume			if (lex == HTTPHL_WORD)
82078064Sume				break;
821122615Sume
822122615Sume			if (lex == HTTPHL_END) {
823122615Sume				/* End while looking for ',' is normal exit */
82462590Sitojun				cs->count++;
825122615Sume				ret = 0;
82662590Sitojun				goto out;
827122615Sume			}
82855505Sshin			/* Anything else is an error */
82955505Sshin			if (lex != ',')
83055505Sshin				goto out;
831287097Shrs
832259169Sae		} /* End attributes loop */
83355505Sshin	} /* End challenge loop */
83455505Sshin
83555505Sshin	/*
83655505Sshin	 * Challenges max count exceeded. This really can't happen
83755505Sshin	 * with normal data, something's fishy -> error
83855505Sshin	 */
83955505Sshin
84055505Sshinout:
84155505Sshin	if (key)
84255505Sshin		free(key);
84355505Sshin	if (value)
84455505Sshin		free(value);
84555505Sshin	if (buf)
84655505Sshin		free(buf);
84755505Sshin	return (ret);
84855505Sshin}
84955505Sshin
85055505Sshin
85155505Sshin/*
85255505Sshin * Parse a last-modified header
853122615Sume */
854122615Sumestatic int
855122615Sumehttp_parse_mtime(const char *p, time_t *mtime)
856122615Sume{
857186500Sqingli	char locale[64], *r;
858151473Ssuz	struct tm tm;
85962590Sitojun
86062590Sitojun	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
861124241Ssuz	setlocale(LC_TIME, "C");
86262590Sitojun	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
863151473Ssuz	/* XXX should add support for date-2 and date-3 */
86455505Sshin	setlocale(LC_TIME, locale);
86555505Sshin	if (r == NULL)
86655505Sshin		return (-1);
86755505Sshin	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
86855505Sshin		  "%02d:%02d:%02d]\n",
86955505Sshin		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
87055505Sshin		  tm.tm_hour, tm.tm_min, tm.tm_sec));
871151473Ssuz	*mtime = timegm(&tm);
87262590Sitojun	return (0);
87355505Sshin}
874151473Ssuz
87555505Sshin/*
87655505Sshin * Parse a content-length header
87755505Sshin */
87855505Sshinstatic int
87955505Sshinhttp_parse_length(const char *p, off_t *length)
88055505Sshin{
88155505Sshin	off_t len;
88255505Sshin
883121156Sume	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
884121156Sume		len = len * 10 + (*p - '0');
88555505Sshin	if (*p)
88655505Sshin		return (-1);
88755505Sshin	DEBUG(fprintf(stderr, "content length: [%lld]\n",
88855505Sshin	    (long long)len));
88955505Sshin	*length = len;
89055505Sshin	return (0);
89155505Sshin}
89255505Sshin
89355505Sshin/*
89455505Sshin * Parse a content-range header
89555505Sshin */
896287097Shrsstatic int
897259169Saehttp_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
89855505Sshin{
89955505Sshin	off_t first, last, len;
90062590Sitojun
90162590Sitojun	if (strncasecmp(p, "bytes ", 6) != 0)
90278064Sume		return (-1);
90378064Sume	p += 6;
90478064Sume	if (*p == '*') {
90555505Sshin		first = last = -1;
90655505Sshin		++p;
907121156Sume	} else {
908121156Sume		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
90955505Sshin			first = first * 10 + *p - '0';
91055505Sshin		if (*p != '-')
911121156Sume			return (-1);
91255505Sshin		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
913121156Sume			last = last * 10 + *p - '0';
914121156Sume	}
915122615Sume	if (first > last || *p != '/')
91662590Sitojun		return (-1);
91762590Sitojun	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
918122615Sume		len = len * 10 + *p - '0';
91962590Sitojun	if (*p || len < last - first + 1)
92062590Sitojun		return (-1);
92162590Sitojun	if (first == -1) {
92262590Sitojun		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
92362590Sitojun		    (long long)len));
92462590Sitojun		*length = 0;
92562590Sitojun	} else {
92662590Sitojun		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
92762590Sitojun		    (long long)first, (long long)last, (long long)len));
92862590Sitojun		*length = last - first + 1;
92962590Sitojun	}
93062590Sitojun	*offset = first;
93162590Sitojun	*size = len;
93262590Sitojun	return (0);
93362590Sitojun}
93462590Sitojun
93562590Sitojun
936151468Ssuz/*****************************************************************************
937151468Ssuz * Helper functions for authorization
938151468Ssuz */
939151468Ssuz
940151468Ssuz/*
941151468Ssuz * Base64 encoding
942151468Ssuz */
943151468Ssuzstatic char *
944151468Ssuzhttp_base64(const char *src)
945151468Ssuz{
946151468Ssuz	static const char base64[] =
947151468Ssuz	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
948151468Ssuz	    "abcdefghijklmnopqrstuvwxyz"
949151468Ssuz	    "0123456789+/";
950151468Ssuz	char *str, *dst;
951151468Ssuz	size_t l;
952151468Ssuz	int t, r;
953151468Ssuz
954151468Ssuz	l = strlen(src);
955151468Ssuz	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
956151468Ssuz		return (NULL);
957151474Ssuz	dst = str;
95862590Sitojun	r = 0;
959118498Sume
960118498Sume	while (l >= 3) {
961118498Sume		t = (src[0] << 16) | (src[1] << 8) | src[2];
962197138Shrs		dst[0] = base64[(t >> 18) & 0x3f];
963197138Shrs		dst[1] = base64[(t >> 12) & 0x3f];
964197138Shrs		dst[2] = base64[(t >> 6) & 0x3f];
965245230Sume		dst[3] = base64[(t >> 0) & 0x3f];
966245230Sume		src += 3; l -= 3;
967245230Sume		dst += 4; r += 4;
968151468Ssuz	}
969151468Ssuz
970151468Ssuz	switch (l) {
97162590Sitojun	case 2:
97262590Sitojun		t = (src[0] << 16) | (src[1] << 8);
973151468Ssuz		dst[0] = base64[(t >> 18) & 0x3f];
974151468Ssuz		dst[1] = base64[(t >> 12) & 0x3f];
975121156Sume		dst[2] = base64[(t >> 6) & 0x3f];
97662590Sitojun		dst[3] = '=';
97762590Sitojun		dst += 4;
978151468Ssuz		r += 4;
97962590Sitojun		break;
98062590Sitojun	case 1:
981121162Sume		t = src[0] << 16;
982121162Sume		dst[0] = base64[(t >> 18) & 0x3f];
983121162Sume		dst[1] = base64[(t >> 12) & 0x3f];
984121162Sume		dst[2] = dst[3] = '=';
985121162Sume		dst += 4;
986151468Ssuz		r += 4;
987151468Ssuz		break;
988151468Ssuz	case 0:
989151468Ssuz		break;
99055505Sshin	}
991121471Sume
99255505Sshin	*dst = 0;
99355505Sshin	return (str);
994121156Sume}
99555505Sshin
99662590Sitojun
99778064Sume/*
99878064Sume * Extract authorization parameters from environment value.
99978064Sume * The value is like scheme:realm:user:pass
100078064Sume */
100178064Sumetypedef struct {
100278064Sume	char	*scheme;
100378064Sume	char	*realm;
1004121156Sume	char	*user;
100578064Sume	char	*password;
100678064Sume} http_auth_params_t;
100778064Sume
100878064Sumestatic void
100978064Sumeinit_http_auth_params(http_auth_params_t *s)
101078064Sume{
101178064Sume	s->scheme = s->realm = s->user = s->password = 0;
101278064Sume}
101378064Sume
101478064Sumestatic void
101578064Sumeclean_http_auth_params(http_auth_params_t *s)
101678064Sume{
1017151472Ssuz	if (s->scheme)
1018151472Ssuz		free(s->scheme);
101978064Sume	if (s->realm)
102078064Sume		free(s->realm);
102178064Sume	if (s->user)
102278064Sume		free(s->user);
102378064Sume	if (s->password)
102478064Sume		free(s->password);
102562590Sitojun	init_http_auth_params(s);
102662590Sitojun}
1027151474Ssuz
1028151474Ssuzstatic int
1029151474Ssuzhttp_authfromenv(const char *p, http_auth_params_t *parms)
1030151474Ssuz{
1031118498Sume	int ret = -1;
1032118498Sume	char *v, *ve;
1033118498Sume	char *str = strdup(p);
1034118498Sume
1035118498Sume	if (str == NULL) {
1036118498Sume		fetch_syserr();
1037197138Shrs		return (-1);
1038197138Shrs	}
1039197138Shrs	v = str;
1040197138Shrs
1041245230Sume	if ((ve = strchr(v, ':')) == NULL)
1042245230Sume		goto out;
1043245230Sume
1044245230Sume	*ve = 0;
1045122615Sume	if ((parms->scheme = strdup(v)) == NULL) {
104662590Sitojun		fetch_syserr();
104755505Sshin		goto out;
1048121156Sume	}
104955505Sshin	v = ve + 1;
105055505Sshin
105155505Sshin	if ((ve = strchr(v, ':')) == NULL)
105278064Sume		goto out;
105378064Sume
105478064Sume	*ve = 0;
105578064Sume	if ((parms->realm = strdup(v)) == NULL) {
1056287097Shrs		fetch_syserr();
105755505Sshin		goto out;
105855505Sshin	}
105978064Sume	v = ve + 1;
106078064Sume
106178064Sume	if ((ve = strchr(v, ':')) == NULL)
106278064Sume		goto out;
1063253999Shrs
106478064Sume	*ve = 0;
106578064Sume	if ((parms->user = strdup(v)) == NULL) {
106678064Sume		fetch_syserr();
106778064Sume		goto out;
106878064Sume	}
1069151472Ssuz	v = ve + 1;
1070151472Ssuz
107178064Sume
107278064Sume	if ((parms->password = strdup(v)) == NULL) {
1073121156Sume		fetch_syserr();
107478064Sume		goto out;
107578064Sume	}
107678064Sume	ret = 0;
107778064Sumeout:
107878064Sume	if (ret == -1)
107978064Sume		clean_http_auth_params(parms);
108078064Sume	if (str)
108178064Sume		free(str);
108278064Sume	return (ret);
108378064Sume}
108478064Sume
108578064Sume
108678064Sume/*
1087121156Sume * Digest response: the code to compute the digest is taken from the
108878064Sume * sample implementation in RFC2616
1089121156Sume */
109078064Sume#define IN const
1091121156Sume#define OUT
109278064Sume
1093121156Sume#define HASHLEN 16
1094121156Sumetypedef char HASH[HASHLEN];
109578064Sume#define HASHHEXLEN 32
109678064Sumetypedef char HASHHEX[HASHHEXLEN+1];
1097121156Sume
1098253999Shrsstatic const char *hexchars = "0123456789abcdef";
109978064Sumestatic void
110078064SumeCvtHex(IN HASH Bin, OUT HASHHEX Hex)
110178064Sume{
110278064Sume	unsigned short i;
1103253970Shrs	unsigned char j;
110478064Sume
110578064Sume	for (i = 0; i < HASHLEN; i++) {
110655505Sshin		j = (Bin[i] >> 4) & 0xf;
110755505Sshin		Hex[i*2] = hexchars[j];
1108287097Shrs		j = Bin[i] & 0xf;
110955505Sshin		Hex[i*2+1] = hexchars[j];
111055505Sshin	};
111178064Sume	Hex[HASHHEXLEN] = '\0';
111278064Sume};
111378064Sume
111478064Sume/* calculate H(A1) as per spec */
111578064Sumestatic void
1116253999ShrsDigestCalcHA1(
111778064Sume	IN char * pszAlg,
111878064Sume	IN char * pszUserName,
111978064Sume	IN char * pszRealm,
112078064Sume	IN char * pszPassword,
112178064Sume	IN char * pszNonce,
112278064Sume	IN char * pszCNonce,
112378064Sume	OUT HASHHEX SessionKey
112478064Sume	)
112578064Sume{
112678064Sume	MD5_CTX Md5Ctx;
1127121156Sume	HASH HA1;
112878064Sume
112978064Sume	MD5Init(&Md5Ctx);
113078064Sume	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
113178064Sume	MD5Update(&Md5Ctx, ":", 1);
113278064Sume	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
113378064Sume	MD5Update(&Md5Ctx, ":", 1);
113478064Sume	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
113578064Sume	MD5Final(HA1, &Md5Ctx);
113678064Sume	if (strcasecmp(pszAlg, "md5-sess") == 0) {
113778064Sume
113878064Sume		MD5Init(&Md5Ctx);
113978064Sume		MD5Update(&Md5Ctx, HA1, HASHLEN);
114078064Sume		MD5Update(&Md5Ctx, ":", 1);
114178064Sume		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
114278064Sume		MD5Update(&Md5Ctx, ":", 1);
114378064Sume		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
114478064Sume		MD5Final(HA1, &Md5Ctx);
1145121156Sume	};
114678064Sume	CvtHex(HA1, SessionKey);
1147253999Shrs}
114878064Sume
114978064Sume/* calculate request-digest/response-digest as per HTTP Digest spec */
115078064Sumestatic void
115178064SumeDigestCalcResponse(
115278064Sume	IN HASHHEX HA1,           /* H(A1) */
1153121156Sume	IN char * pszNonce,       /* nonce from server */
1154121156Sume	IN char * pszNonceCount,  /* 8 hex digits */
1155121156Sume	IN char * pszCNonce,      /* client nonce */
1156121156Sume	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
115778064Sume	IN char * pszMethod,      /* method from the request */
1158121156Sume	IN char * pszDigestUri,   /* requested URL */
115978064Sume	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1160121156Sume	OUT HASHHEX Response      /* request-digest or response-digest */
116178064Sume	)
1162121156Sume{
116378064Sume/*	DEBUG(fprintf(stderr,
116478064Sume		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
116578064Sume		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1166122615Sume	MD5_CTX Md5Ctx;
116778064Sume	HASH HA2;
116878064Sume	HASH RespHash;
116978064Sume	HASHHEX HA2Hex;
1170122615Sume
117178064Sume	// calculate H(A2)
117278064Sume	MD5Init(&Md5Ctx);
1173253970Shrs	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
117478064Sume	MD5Update(&Md5Ctx, ":", 1);
1175253970Shrs	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
117678064Sume	if (strcasecmp(pszQop, "auth-int") == 0) {
117778064Sume		MD5Update(&Md5Ctx, ":", 1);
117878064Sume		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
117978064Sume	};
118078064Sume	MD5Final(HA2, &Md5Ctx);
118178064Sume	CvtHex(HA2, HA2Hex);
118278064Sume
118378064Sume	// calculate response
118478064Sume	MD5Init(&Md5Ctx);
118578064Sume	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
118678064Sume	MD5Update(&Md5Ctx, ":", 1);
118778064Sume	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1188122615Sume	MD5Update(&Md5Ctx, ":", 1);
118978064Sume	if (*pszQop) {
119078064Sume		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
119178064Sume		MD5Update(&Md5Ctx, ":", 1);
119278064Sume		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
119378064Sume		MD5Update(&Md5Ctx, ":", 1);
119478064Sume		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
119578064Sume		MD5Update(&Md5Ctx, ":", 1);
119678064Sume	};
119778064Sume	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
119878064Sume	MD5Final(RespHash, &Md5Ctx);
1199121156Sume	CvtHex(RespHash, Response);
1200121156Sume}
120178064Sume
1202121156Sume/*
120378064Sume * Generate/Send a Digest authorization header
120478064Sume * This looks like: [Proxy-]Authorization: credentials
120578064Sume *
120678064Sume *  credentials      = "Digest" digest-response
120778064Sume *  digest-response  = 1#( username | realm | nonce | digest-uri
120878064Sume *                      | response | [ algorithm ] | [cnonce] |
120978064Sume *                      [opaque] | [message-qop] |
121078064Sume *                          [nonce-count]  | [auth-param] )
121178064Sume *  username         = "username" "=" username-value
121278064Sume *  username-value   = quoted-string
121378064Sume *  digest-uri       = "uri" "=" digest-uri-value
121478064Sume *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
121578064Sume *  message-qop      = "qop" "=" qop-value
121678064Sume *  cnonce           = "cnonce" "=" cnonce-value
121778064Sume *  cnonce-value     = nonce-value
121878064Sume *  nonce-count      = "nc" "=" nc-value
121978064Sume *  nc-value         = 8LHEX
122055505Sshin *  response         = "response" "=" request-digest
122155505Sshin *  request-digest = <"> 32LHEX <">
1222287097Shrs */
122355505Sshinstatic int
122455505Sshinhttp_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
122555505Sshin		 http_auth_params_t *parms, struct url *url)
122655505Sshin{
122755505Sshin	int r;
122855505Sshin	char noncecount[10];
122955505Sshin	char cnonce[40];
1230121156Sume	char *options = 0;
123155505Sshin
1232121156Sume	if (!c->realm || !c->nonce) {
123355505Sshin		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
123455505Sshin		return(-1);
1235287097Shrs	}
123655505Sshin	if (!c->algo)
123755505Sshin		c->algo = strdup("");
123855505Sshin
123955505Sshin	if (asprintf(&options, "%s%s%s%s",
124055505Sshin		     *c->algo? ",algorithm=" : "", c->algo,
124155505Sshin		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
124255505Sshin		return (-1);
1243121156Sume
124455505Sshin	if (!c->qop) {
1245121156Sume		c->qop = strdup("");
124662590Sitojun		*noncecount = 0;
124762590Sitojun		*cnonce = 0;
124855505Sshin	} else {
124955505Sshin		c->nc++;
1250287097Shrs		sprintf(noncecount, "%08x", c->nc);
125155505Sshin		/* We don't try very hard with the cnonce ... */
125255505Sshin		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
125355505Sshin	}
125455505Sshin
125555505Sshin	HASHHEX HA1;
125662590Sitojun	DigestCalcHA1(c->algo, parms->user, c->realm,
125762590Sitojun		      parms->password, c->nonce, cnonce, HA1);
1258121156Sume	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
125962590Sitojun	HASHHEX digest;
1260121156Sume	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
126162590Sitojun			   "GET", url->doc, "", digest);
126262590Sitojun
126355505Sshin	if (c->qop[0]) {
126455505Sshin		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
126562590Sitojun			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
126662590Sitojun			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1267259169Sae			     hdr, parms->user, c->realm,
126862590Sitojun			     c->nonce, url->doc, digest,
126962590Sitojun			     cnonce, noncecount, options);
127062590Sitojun	} else {
127162590Sitojun		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
127262590Sitojun			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
127362590Sitojun			     hdr, parms->user, c->realm,
127462590Sitojun			     c->nonce, url->doc, digest, options);
127562590Sitojun	}
127662590Sitojun	if (options)
127762590Sitojun		free(options);
127862590Sitojun	return (r);
127962590Sitojun}
128062590Sitojun
128162590Sitojun/*
1282121156Sume * Encode username and password
128362590Sitojun */
128462590Sitojunstatic int
128562590Sitojunhttp_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1286121156Sume{
128762590Sitojun	char *upw, *auth;
128862590Sitojun	int r;
128962590Sitojun
129062590Sitojun	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
129162590Sitojun	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
129262590Sitojun	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
129362590Sitojun		return (-1);
129462590Sitojun	auth = http_base64(upw);
129562590Sitojun	free(upw);
129662590Sitojun	if (auth == NULL)
129762590Sitojun		return (-1);
129862590Sitojun	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
129962590Sitojun	free(auth);
130062590Sitojun	return (r);
1301121156Sume}
130262590Sitojun
130362590Sitojun/*
1304121156Sume * Chose the challenge to answer and call the appropriate routine to
130562590Sitojun * produce the header.
130662590Sitojun */
130762590Sitojunstatic int
130862590Sitojunhttp_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
130962590Sitojun	       http_auth_params_t *parms, struct url *url)
131062590Sitojun{
131162590Sitojun	http_auth_challenge_t *basic = NULL;
131262590Sitojun	http_auth_challenge_t *digest = NULL;
131362590Sitojun	int i;
131462590Sitojun
131562590Sitojun	/* If user or pass are null we're not happy */
131662590Sitojun	if (!parms->user || !parms->password) {
131762590Sitojun		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
131862590Sitojun		return (-1);
131955505Sshin	}
1320259169Sae
132155505Sshin	/* Look for a Digest and a Basic challenge */
132255505Sshin	for (i = 0; i < cs->count; i++) {
132355505Sshin		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
132455505Sshin			basic = cs->challenges[i];
132555505Sshin		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1326121156Sume			digest = cs->challenges[i];
1327121156Sume	}
132855505Sshin
132955505Sshin	/* Error if "Digest" was specified and there is no Digest challenge */
133055505Sshin	if (!digest && (parms->scheme &&
133155505Sshin			!strcasecmp(parms->scheme, "digest"))) {
133255505Sshin		DEBUG(fprintf(stderr,
133355505Sshin			      "Digest auth in env, not supported by peer\n"));
133455505Sshin		return (-1);
133555505Sshin	}
1336121156Sume	/*
1337121156Sume	 * If "basic" was specified in the environment, or there is no Digest
1338121156Sume	 * challenge, do the basic thing. Don't need a challenge for this,
1339121156Sume	 * so no need to check basic!=NULL
134055505Sshin	 */
134155505Sshin	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
134255505Sshin		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1343121156Sume
1344121156Sume	/* Else, prefer digest. We just checked that it's not NULL */
1345121156Sume	return (http_digest_auth(conn, hdr, digest, parms, url));
1346121156Sume}
134755505Sshin
134855505Sshin/*****************************************************************************
134955505Sshin * Helper functions for connecting to a server or proxy
1350121156Sume */
1351121156Sume
1352121156Sume/*
1353121156Sume * Connect to the correct HTTP server or proxy.
135455505Sshin */
1355121156Sumestatic conn_t *
135655505Sshinhttp_connect(struct url *URL, struct url *purl, const char *flags)
135755505Sshin{
135855505Sshin	conn_t *conn;
135955505Sshin	int verbose;
136055505Sshin	int af, val;
136155505Sshin
136255505Sshin#ifdef INET6
136355505Sshin	af = AF_UNSPEC;
136455505Sshin#else
1365259169Sae	af = AF_INET;
136655505Sshin#endif
136755505Sshin
136855505Sshin	verbose = CHECK_FLAG('v');
136955505Sshin	if (CHECK_FLAG('4'))
1370253999Shrs		af = AF_INET;
137155505Sshin#ifdef INET6
1372253999Shrs	else if (CHECK_FLAG('6'))
137355505Sshin		af = AF_INET6;
1374186119Sqingli#endif
1375186119Sqingli
1376	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
1377		URL = purl;
1378	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
1379		/* can't talk http to an ftp server */
1380		/* XXX should set an error code */
1381		return (NULL);
1382	}
1383
1384	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1385		/* fetch_connect() has already set an error code */
1386		return (NULL);
1387	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1388	    fetch_ssl(conn, verbose) == -1) {
1389		fetch_close(conn);
1390		/* grrr */
1391		errno = EAUTH;
1392		fetch_syserr();
1393		return (NULL);
1394	}
1395
1396	val = 1;
1397	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1398
1399	return (conn);
1400}
1401
1402static struct url *
1403http_get_proxy(struct url * url, const char *flags)
1404{
1405	struct url *purl;
1406	char *p;
1407
1408	if (flags != NULL && strchr(flags, 'd') != NULL)
1409		return (NULL);
1410	if (fetch_no_proxy_match(url->host))
1411		return (NULL);
1412	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1413	    *p && (purl = fetchParseURL(p))) {
1414		if (!*purl->scheme)
1415			strcpy(purl->scheme, SCHEME_HTTP);
1416		if (!purl->port)
1417			purl->port = fetch_default_proxy_port(purl->scheme);
1418		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1419			return (purl);
1420		fetchFreeURL(purl);
1421	}
1422	return (NULL);
1423}
1424
1425static void
1426http_print_html(FILE *out, FILE *in)
1427{
1428	size_t len;
1429	char *line, *p, *q;
1430	int comment, tag;
1431
1432	comment = tag = 0;
1433	while ((line = fgetln(in, &len)) != NULL) {
1434		while (len && isspace((unsigned char)line[len - 1]))
1435			--len;
1436		for (p = q = line; q < line + len; ++q) {
1437			if (comment && *q == '-') {
1438				if (q + 2 < line + len &&
1439				    strcmp(q, "-->") == 0) {
1440					tag = comment = 0;
1441					q += 2;
1442				}
1443			} else if (tag && !comment && *q == '>') {
1444				p = q + 1;
1445				tag = 0;
1446			} else if (!tag && *q == '<') {
1447				if (q > p)
1448					fwrite(p, q - p, 1, out);
1449				tag = 1;
1450				if (q + 3 < line + len &&
1451				    strcmp(q, "<!--") == 0) {
1452					comment = 1;
1453					q += 3;
1454				}
1455			}
1456		}
1457		if (!tag && q > p)
1458			fwrite(p, q - p, 1, out);
1459		fputc('\n', out);
1460	}
1461}
1462
1463
1464/*****************************************************************************
1465 * Core
1466 */
1467
1468/*
1469 * Send a request and process the reply
1470 *
1471 * XXX This function is way too long, the do..while loop should be split
1472 * XXX off into a separate function.
1473 */
1474FILE *
1475http_request(struct url *URL, const char *op, struct url_stat *us,
1476	struct url *purl, const char *flags)
1477{
1478	char timebuf[80];
1479	char hbuf[MAXHOSTNAMELEN + 7], *host;
1480	conn_t *conn;
1481	struct url *url, *new;
1482	int chunked, direct, ims, noredirect, verbose;
1483	int e, i, n, val;
1484	off_t offset, clength, length, size;
1485	time_t mtime;
1486	const char *p;
1487	FILE *f;
1488	hdr_t h;
1489	struct tm *timestruct;
1490	http_headerbuf_t headerbuf;
1491	http_auth_challenges_t server_challenges;
1492	http_auth_challenges_t proxy_challenges;
1493
1494	/* The following calls don't allocate anything */
1495	init_http_headerbuf(&headerbuf);
1496	init_http_auth_challenges(&server_challenges);
1497	init_http_auth_challenges(&proxy_challenges);
1498
1499	direct = CHECK_FLAG('d');
1500	noredirect = CHECK_FLAG('A');
1501	verbose = CHECK_FLAG('v');
1502	ims = CHECK_FLAG('i');
1503
1504	if (direct && purl) {
1505		fetchFreeURL(purl);
1506		purl = NULL;
1507	}
1508
1509	/* try the provided URL first */
1510	url = URL;
1511
1512	/* if the A flag is set, we only get one try */
1513	n = noredirect ? 1 : MAX_REDIRECT;
1514	i = 0;
1515
1516	e = HTTP_PROTOCOL_ERROR;
1517	do {
1518		new = NULL;
1519		chunked = 0;
1520		offset = 0;
1521		clength = -1;
1522		length = -1;
1523		size = -1;
1524		mtime = 0;
1525
1526		/* check port */
1527		if (!url->port)
1528			url->port = fetch_default_port(url->scheme);
1529
1530		/* were we redirected to an FTP URL? */
1531		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1532			if (strcmp(op, "GET") == 0)
1533				return (ftp_request(url, "RETR", us, purl, flags));
1534			else if (strcmp(op, "HEAD") == 0)
1535				return (ftp_request(url, "STAT", us, purl, flags));
1536		}
1537
1538		/* connect to server or proxy */
1539		if ((conn = http_connect(url, purl, flags)) == NULL)
1540			goto ouch;
1541
1542		host = url->host;
1543#ifdef INET6
1544		if (strchr(url->host, ':')) {
1545			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
1546			host = hbuf;
1547		}
1548#endif
1549		if (url->port != fetch_default_port(url->scheme)) {
1550			if (host != hbuf) {
1551				strcpy(hbuf, host);
1552				host = hbuf;
1553			}
1554			snprintf(hbuf + strlen(hbuf),
1555			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1556		}
1557
1558		/* send request */
1559		if (verbose)
1560			fetch_info("requesting %s://%s%s",
1561			    url->scheme, host, url->doc);
1562		if (purl) {
1563			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1564			    op, url->scheme, host, url->doc);
1565		} else {
1566			http_cmd(conn, "%s %s HTTP/1.1",
1567			    op, url->doc);
1568		}
1569
1570		if (ims && url->ims_time) {
1571			timestruct = gmtime((time_t *)&url->ims_time);
1572			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1573			    timestruct);
1574			if (verbose)
1575				fetch_info("If-Modified-Since: %s", timebuf);
1576			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1577		}
1578		/* virtual host */
1579		http_cmd(conn, "Host: %s", host);
1580
1581		/*
1582		 * Proxy authorization: we only send auth after we received
1583		 * a 407 error. We do not first try basic anyway (changed
1584		 * when support was added for digest-auth)
1585		 */
1586		if (purl && proxy_challenges.valid) {
1587			http_auth_params_t aparams;
1588			init_http_auth_params(&aparams);
1589			if (*purl->user || *purl->pwd) {
1590				aparams.user = purl->user ?
1591					strdup(purl->user) : strdup("");
1592				aparams.password = purl->pwd?
1593					strdup(purl->pwd) : strdup("");
1594			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1595				   *p != '\0') {
1596				if (http_authfromenv(p, &aparams) < 0) {
1597					http_seterr(HTTP_NEED_PROXY_AUTH);
1598					goto ouch;
1599				}
1600			}
1601			http_authorize(conn, "Proxy-Authorization",
1602				       &proxy_challenges, &aparams, url);
1603			clean_http_auth_params(&aparams);
1604		}
1605
1606		/*
1607		 * Server authorization: we never send "a priori"
1608		 * Basic auth, which used to be done if user/pass were
1609		 * set in the url. This would be weird because we'd send the
1610		 * password in the clear even if Digest is finally to be
1611		 * used (it would have made more sense for the
1612		 * pre-digest version to do this when Basic was specified
1613		 * in the environment)
1614		 */
1615		if (server_challenges.valid) {
1616			http_auth_params_t aparams;
1617			init_http_auth_params(&aparams);
1618			if (*url->user || *url->pwd) {
1619				aparams.user = url->user ?
1620					strdup(url->user) : strdup("");
1621				aparams.password = url->pwd ?
1622					strdup(url->pwd) : strdup("");
1623			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1624				   *p != '\0') {
1625				if (http_authfromenv(p, &aparams) < 0) {
1626					http_seterr(HTTP_NEED_AUTH);
1627					goto ouch;
1628				}
1629			} else if (fetchAuthMethod &&
1630				   fetchAuthMethod(url) == 0) {
1631				aparams.user = url->user ?
1632					strdup(url->user) : strdup("");
1633				aparams.password = url->pwd ?
1634					strdup(url->pwd) : strdup("");
1635			} else {
1636				http_seterr(HTTP_NEED_AUTH);
1637				goto ouch;
1638			}
1639			http_authorize(conn, "Authorization",
1640				       &server_challenges, &aparams, url);
1641			clean_http_auth_params(&aparams);
1642		}
1643
1644		/* other headers */
1645		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1646			if (strcasecmp(p, "auto") == 0)
1647				http_cmd(conn, "Referer: %s://%s%s",
1648				    url->scheme, host, url->doc);
1649			else
1650				http_cmd(conn, "Referer: %s", p);
1651		}
1652		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1653			http_cmd(conn, "User-Agent: %s", p);
1654		else
1655			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1656		if (url->offset > 0)
1657			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1658		http_cmd(conn, "Connection: close");
1659		http_cmd(conn, "");
1660
1661		/*
1662		 * Force the queued request to be dispatched.  Normally, one
1663		 * would do this with shutdown(2) but squid proxies can be
1664		 * configured to disallow such half-closed connections.  To
1665		 * be compatible with such configurations, fiddle with socket
1666		 * options to force the pending data to be written.
1667		 */
1668		val = 0;
1669		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1670			   sizeof(val));
1671		val = 1;
1672		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1673			   sizeof(val));
1674
1675		/* get reply */
1676		switch (http_get_reply(conn)) {
1677		case HTTP_OK:
1678		case HTTP_PARTIAL:
1679		case HTTP_NOT_MODIFIED:
1680			/* fine */
1681			break;
1682		case HTTP_MOVED_PERM:
1683		case HTTP_MOVED_TEMP:
1684		case HTTP_SEE_OTHER:
1685			/*
1686			 * Not so fine, but we still have to read the
1687			 * headers to get the new location.
1688			 */
1689			break;
1690		case HTTP_NEED_AUTH:
1691			if (server_challenges.valid) {
1692				/*
1693				 * We already sent out authorization code,
1694				 * so there's nothing more we can do.
1695				 */
1696				http_seterr(conn->err);
1697				goto ouch;
1698			}
1699			/* try again, but send the password this time */
1700			if (verbose)
1701				fetch_info("server requires authorization");
1702			break;
1703		case HTTP_NEED_PROXY_AUTH:
1704			if (proxy_challenges.valid) {
1705				/*
1706				 * We already sent our proxy
1707				 * authorization code, so there's
1708				 * nothing more we can do. */
1709				http_seterr(conn->err);
1710				goto ouch;
1711			}
1712			/* try again, but send the password this time */
1713			if (verbose)
1714				fetch_info("proxy requires authorization");
1715			break;
1716		case HTTP_BAD_RANGE:
1717			/*
1718			 * This can happen if we ask for 0 bytes because
1719			 * we already have the whole file.  Consider this
1720			 * a success for now, and check sizes later.
1721			 */
1722			break;
1723		case HTTP_PROTOCOL_ERROR:
1724			/* fall through */
1725		case -1:
1726			fetch_syserr();
1727			goto ouch;
1728		default:
1729			http_seterr(conn->err);
1730			if (!verbose)
1731				goto ouch;
1732			/* fall through so we can get the full error message */
1733		}
1734
1735		/* get headers. http_next_header expects one line readahead */
1736		if (fetch_getln(conn) == -1) {
1737		    fetch_syserr();
1738		    goto ouch;
1739		}
1740		do {
1741		    switch ((h = http_next_header(conn, &headerbuf, &p))) {
1742			case hdr_syserror:
1743				fetch_syserr();
1744				goto ouch;
1745			case hdr_error:
1746				http_seterr(HTTP_PROTOCOL_ERROR);
1747				goto ouch;
1748			case hdr_content_length:
1749				http_parse_length(p, &clength);
1750				break;
1751			case hdr_content_range:
1752				http_parse_range(p, &offset, &length, &size);
1753				break;
1754			case hdr_last_modified:
1755				http_parse_mtime(p, &mtime);
1756				break;
1757			case hdr_location:
1758				if (!HTTP_REDIRECT(conn->err))
1759					break;
1760				if (new)
1761					free(new);
1762				if (verbose)
1763					fetch_info("%d redirect to %s", conn->err, p);
1764				if (*p == '/')
1765					/* absolute path */
1766					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1767					    url->user, url->pwd);
1768				else
1769					new = fetchParseURL(p);
1770				if (new == NULL) {
1771					/* XXX should set an error code */
1772					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1773					goto ouch;
1774				}
1775				if (!*new->user && !*new->pwd) {
1776					strcpy(new->user, url->user);
1777					strcpy(new->pwd, url->pwd);
1778				}
1779				new->offset = url->offset;
1780				new->length = url->length;
1781				break;
1782			case hdr_transfer_encoding:
1783				/* XXX weak test*/
1784				chunked = (strcasecmp(p, "chunked") == 0);
1785				break;
1786			case hdr_www_authenticate:
1787				if (conn->err != HTTP_NEED_AUTH)
1788					break;
1789				if (http_parse_authenticate(p, &server_challenges) == 0)
1790					++n;
1791				break;
1792			case hdr_proxy_authenticate:
1793				if (conn->err != HTTP_NEED_PROXY_AUTH)
1794					break;
1795				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1796					++n;
1797				break;
1798			case hdr_end:
1799				/* fall through */
1800			case hdr_unknown:
1801				/* ignore */
1802				break;
1803			}
1804		} while (h > hdr_end);
1805
1806		/* we need to provide authentication */
1807		if (conn->err == HTTP_NEED_AUTH ||
1808		    conn->err == HTTP_NEED_PROXY_AUTH) {
1809			e = conn->err;
1810			if ((conn->err == HTTP_NEED_AUTH &&
1811			     !server_challenges.valid) ||
1812			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1813			     !proxy_challenges.valid)) {
1814				/* 401/7 but no www/proxy-authenticate ?? */
1815				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1816				goto ouch;
1817			}
1818			fetch_close(conn);
1819			conn = NULL;
1820			continue;
1821		}
1822
1823		/* requested range not satisfiable */
1824		if (conn->err == HTTP_BAD_RANGE) {
1825			if (url->offset == size && url->length == 0) {
1826				/* asked for 0 bytes; fake it */
1827				offset = url->offset;
1828				clength = -1;
1829				conn->err = HTTP_OK;
1830				break;
1831			} else {
1832				http_seterr(conn->err);
1833				goto ouch;
1834			}
1835		}
1836
1837		/* we have a hit or an error */
1838		if (conn->err == HTTP_OK
1839		    || conn->err == HTTP_NOT_MODIFIED
1840		    || conn->err == HTTP_PARTIAL
1841		    || HTTP_ERROR(conn->err))
1842			break;
1843
1844		/* all other cases: we got a redirect */
1845		e = conn->err;
1846		clean_http_auth_challenges(&server_challenges);
1847		fetch_close(conn);
1848		conn = NULL;
1849		if (!new) {
1850			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1851			break;
1852		}
1853		if (url != URL)
1854			fetchFreeURL(url);
1855		url = new;
1856	} while (++i < n);
1857
1858	/* we failed, or ran out of retries */
1859	if (conn == NULL) {
1860		http_seterr(e);
1861		goto ouch;
1862	}
1863
1864	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1865		  " size %lld, clength %lld\n",
1866		  (long long)offset, (long long)length,
1867		  (long long)size, (long long)clength));
1868
1869	if (conn->err == HTTP_NOT_MODIFIED) {
1870		http_seterr(HTTP_NOT_MODIFIED);
1871		return (NULL);
1872	}
1873
1874	/* check for inconsistencies */
1875	if (clength != -1 && length != -1 && clength != length) {
1876		http_seterr(HTTP_PROTOCOL_ERROR);
1877		goto ouch;
1878	}
1879	if (clength == -1)
1880		clength = length;
1881	if (clength != -1)
1882		length = offset + clength;
1883	if (length != -1 && size != -1 && length != size) {
1884		http_seterr(HTTP_PROTOCOL_ERROR);
1885		goto ouch;
1886	}
1887	if (size == -1)
1888		size = length;
1889
1890	/* fill in stats */
1891	if (us) {
1892		us->size = size;
1893		us->atime = us->mtime = mtime;
1894	}
1895
1896	/* too far? */
1897	if (URL->offset > 0 && offset > URL->offset) {
1898		http_seterr(HTTP_PROTOCOL_ERROR);
1899		goto ouch;
1900	}
1901
1902	/* report back real offset and size */
1903	URL->offset = offset;
1904	URL->length = clength;
1905
1906	/* wrap it up in a FILE */
1907	if ((f = http_funopen(conn, chunked)) == NULL) {
1908		fetch_syserr();
1909		goto ouch;
1910	}
1911
1912	if (url != URL)
1913		fetchFreeURL(url);
1914	if (purl)
1915		fetchFreeURL(purl);
1916
1917	if (HTTP_ERROR(conn->err)) {
1918		http_print_html(stderr, f);
1919		fclose(f);
1920		f = NULL;
1921	}
1922	clean_http_headerbuf(&headerbuf);
1923	clean_http_auth_challenges(&server_challenges);
1924	clean_http_auth_challenges(&proxy_challenges);
1925	return (f);
1926
1927ouch:
1928	if (url != URL)
1929		fetchFreeURL(url);
1930	if (purl)
1931		fetchFreeURL(purl);
1932	if (conn != NULL)
1933		fetch_close(conn);
1934	clean_http_headerbuf(&headerbuf);
1935	clean_http_auth_challenges(&server_challenges);
1936	clean_http_auth_challenges(&proxy_challenges);
1937	return (NULL);
1938}
1939
1940
1941/*****************************************************************************
1942 * Entry points
1943 */
1944
1945/*
1946 * Retrieve and stat a file by HTTP
1947 */
1948FILE *
1949fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1950{
1951	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1952}
1953
1954/*
1955 * Retrieve a file by HTTP
1956 */
1957FILE *
1958fetchGetHTTP(struct url *URL, const char *flags)
1959{
1960	return (fetchXGetHTTP(URL, NULL, flags));
1961}
1962
1963/*
1964 * Store a file by HTTP
1965 */
1966FILE *
1967fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1968{
1969	warnx("fetchPutHTTP(): not implemented");
1970	return (NULL);
1971}
1972
1973/*
1974 * Get an HTTP document's metadata
1975 */
1976int
1977fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1978{
1979	FILE *f;
1980
1981	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
1982	if (f == NULL)
1983		return (-1);
1984	fclose(f);
1985	return (0);
1986}
1987
1988/*
1989 * List a directory
1990 */
1991struct url_ent *
1992fetchListHTTP(struct url *url __unused, const char *flags __unused)
1993{
1994	warnx("fetchListHTTP(): not implemented");
1995	return (NULL);
1996}
1997