http.c revision 242293
137535Sdes/*-
2236103Sdes * Copyright (c) 2000-2011 Dag-Erling 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 242293 2012-10-29 04:18:34Z eadler $");
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 */
89242032Seadler#define MAX_REDIRECT 20
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
98242293Seadler#define HTTP_USE_PROXY		305
99169386Sdes#define HTTP_TEMP_REDIRECT	307
100242289Seadler#define HTTP_PERM_REDIRECT	308
10163012Sdes#define HTTP_NEED_AUTH		401
10287317Sdes#define HTTP_NEED_PROXY_AUTH	407
103125696Sdes#define HTTP_BAD_RANGE		416
10463012Sdes#define HTTP_PROTOCOL_ERROR	999
10560196Sdes
10663012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
10790267Sdes			    || (xyz) == HTTP_MOVED_TEMP \
108169386Sdes			    || (xyz) == HTTP_TEMP_REDIRECT \
109242293Seadler			    || (xyz) == HTTP_USE_PROXY \
11090267Sdes			    || (xyz) == HTTP_SEE_OTHER)
11163012Sdes
11288771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
11363012Sdes
11490267Sdes
11563012Sdes/*****************************************************************************
11663012Sdes * I/O functions for decoding chunked streams
11763012Sdes */
11863012Sdes
11997859Sdesstruct httpio
12037535Sdes{
12197858Sdes	conn_t		*conn;		/* connection */
12297866Sdes	int		 chunked;	/* chunked mode */
12397858Sdes	char		*buf;		/* chunk buffer */
12497866Sdes	size_t		 bufsize;	/* size of chunk buffer */
12597866Sdes	ssize_t		 buflen;	/* amount of data currently in buffer */
12697866Sdes	int		 bufpos;	/* current read offset in buffer */
12797858Sdes	int		 eof;		/* end-of-file flag */
12897858Sdes	int		 error;		/* error flag */
12997858Sdes	size_t		 chunksize;	/* remaining size of current chunk */
13063281Sdes#ifndef NDEBUG
13190267Sdes	size_t		 total;
13263012Sdes#endif
13337535Sdes};
13437535Sdes
13537608Sdes/*
13663012Sdes * Get next chunk header
13737608Sdes */
13837608Sdesstatic int
139174588Sdeshttp_new_chunk(struct httpio *io)
14037608Sdes{
14190267Sdes	char *p;
14290267Sdes
143174588Sdes	if (fetch_getln(io->conn) == -1)
14490267Sdes		return (-1);
14590267Sdes
146174761Sdes	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
14790267Sdes		return (-1);
14890267Sdes
149174761Sdes	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
15090267Sdes		if (*p == ';')
15190267Sdes			break;
152174761Sdes		if (!isxdigit((unsigned char)*p))
15390267Sdes			return (-1);
154174761Sdes		if (isdigit((unsigned char)*p)) {
15597859Sdes			io->chunksize = io->chunksize * 16 +
15690267Sdes			    *p - '0';
15790267Sdes		} else {
15897859Sdes			io->chunksize = io->chunksize * 16 +
159176036Sdes			    10 + tolower((unsigned char)*p) - 'a';
16090267Sdes		}
16190267Sdes	}
16290267Sdes
16363281Sdes#ifndef NDEBUG
16490267Sdes	if (fetchDebug) {
16597859Sdes		io->total += io->chunksize;
16697859Sdes		if (io->chunksize == 0)
167106207Sdes			fprintf(stderr, "%s(): end of last chunk\n", __func__);
16890267Sdes		else
169106207Sdes			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
170106207Sdes			    __func__, (unsigned long)io->chunksize,
171106207Sdes			    (unsigned long)io->total);
17290267Sdes	}
17363012Sdes#endif
17490267Sdes
17597859Sdes	return (io->chunksize);
17637608Sdes}
17737608Sdes
17837608Sdes/*
17997866Sdes * Grow the input buffer to at least len bytes
18097866Sdes */
18197866Sdesstatic inline int
182174588Sdeshttp_growbuf(struct httpio *io, size_t len)
18397866Sdes{
18497866Sdes	char *tmp;
18597866Sdes
18697866Sdes	if (io->bufsize >= len)
18797866Sdes		return (0);
18897866Sdes
18997866Sdes	if ((tmp = realloc(io->buf, len)) == NULL)
19097866Sdes		return (-1);
19197866Sdes	io->buf = tmp;
19297866Sdes	io->bufsize = len;
193106044Sdes	return (0);
19497866Sdes}
19597866Sdes
19697866Sdes/*
19737608Sdes * Fill the input buffer, do chunk decoding on the fly
19837608Sdes */
19963012Sdesstatic int
200174588Sdeshttp_fillbuf(struct httpio *io, size_t len)
20137535Sdes{
202231247Sbapt	ssize_t nbytes;
203231247Sbapt
20497859Sdes	if (io->error)
20590267Sdes		return (-1);
20697859Sdes	if (io->eof)
20790267Sdes		return (0);
20890267Sdes
20997866Sdes	if (io->chunked == 0) {
210174588Sdes		if (http_growbuf(io, len) == -1)
21197866Sdes			return (-1);
212231247Sbapt		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
213231247Sbapt			io->error = errno;
21497866Sdes			return (-1);
215106185Sdes		}
216231247Sbapt		io->buflen = nbytes;
21797866Sdes		io->bufpos = 0;
21897866Sdes		return (io->buflen);
21997866Sdes	}
22097866Sdes
22197859Sdes	if (io->chunksize == 0) {
222174588Sdes		switch (http_new_chunk(io)) {
22390267Sdes		case -1:
22497859Sdes			io->error = 1;
22590267Sdes			return (-1);
22690267Sdes		case 0:
22797859Sdes			io->eof = 1;
22890267Sdes			return (0);
22990267Sdes		}
23037535Sdes	}
23163012Sdes
23297866Sdes	if (len > io->chunksize)
23397866Sdes		len = io->chunksize;
234174588Sdes	if (http_growbuf(io, len) == -1)
23590267Sdes		return (-1);
236231247Sbapt	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
237231247Sbapt		io->error = errno;
23897866Sdes		return (-1);
239106185Sdes	}
240231247Sbapt	io->buflen = nbytes;
24197866Sdes	io->chunksize -= io->buflen;
24290267Sdes
24397859Sdes	if (io->chunksize == 0) {
24497856Sdes		char endl[2];
24597856Sdes
246174588Sdes		if (fetch_read(io->conn, endl, 2) != 2 ||
24797856Sdes		    endl[0] != '\r' || endl[1] != '\n')
24890267Sdes			return (-1);
24990267Sdes	}
25090267Sdes
25197866Sdes	io->bufpos = 0;
25290267Sdes
25397866Sdes	return (io->buflen);
25437535Sdes}
25537535Sdes
25637608Sdes/*
25737608Sdes * Read function
25837608Sdes */
25937535Sdesstatic int
260174588Sdeshttp_readfn(void *v, char *buf, int len)
26137535Sdes{
26297859Sdes	struct httpio *io = (struct httpio *)v;
26390267Sdes	int l, pos;
26463012Sdes
26597859Sdes	if (io->error)
26690267Sdes		return (-1);
26797859Sdes	if (io->eof)
26890267Sdes		return (0);
26963012Sdes
27090267Sdes	for (pos = 0; len > 0; pos += l, len -= l) {
27190267Sdes		/* empty buffer */
27297866Sdes		if (!io->buf || io->bufpos == io->buflen)
273174588Sdes			if (http_fillbuf(io, len) < 1)
27490267Sdes				break;
27597866Sdes		l = io->buflen - io->bufpos;
27690267Sdes		if (len < l)
27790267Sdes			l = len;
278176105Sdes		memcpy(buf + pos, io->buf + io->bufpos, l);
27997866Sdes		io->bufpos += l;
28090267Sdes	}
28137535Sdes
282231247Sbapt	if (!pos && io->error) {
283231247Sbapt		if (io->error == EINTR)
284231247Sbapt			io->error = 0;
28590267Sdes		return (-1);
286231247Sbapt	}
28790267Sdes	return (pos);
28837535Sdes}
28937535Sdes
29037608Sdes/*
29137608Sdes * Write function
29237608Sdes */
29337535Sdesstatic int
294174588Sdeshttp_writefn(void *v, const char *buf, int len)
29537535Sdes{
29697859Sdes	struct httpio *io = (struct httpio *)v;
29790267Sdes
298174588Sdes	return (fetch_write(io->conn, buf, len));
29937535Sdes}
30037535Sdes
30137608Sdes/*
30237608Sdes * Close function
30337608Sdes */
30437535Sdesstatic int
305174588Sdeshttp_closefn(void *v)
30637535Sdes{
30797859Sdes	struct httpio *io = (struct httpio *)v;
30890267Sdes	int r;
30963012Sdes
310174588Sdes	r = fetch_close(io->conn);
31197859Sdes	if (io->buf)
31297859Sdes		free(io->buf);
31397859Sdes	free(io);
31490267Sdes	return (r);
31537535Sdes}
31637535Sdes
31737608Sdes/*
31863012Sdes * Wrap a file descriptor up
31937608Sdes */
32063012Sdesstatic FILE *
321174588Sdeshttp_funopen(conn_t *conn, int chunked)
32237535Sdes{
32397859Sdes	struct httpio *io;
32490267Sdes	FILE *f;
32563012Sdes
326109967Sdes	if ((io = calloc(1, sizeof(*io))) == NULL) {
327174588Sdes		fetch_syserr();
32890267Sdes		return (NULL);
32990267Sdes	}
33097859Sdes	io->conn = conn;
33197866Sdes	io->chunked = chunked;
332174588Sdes	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
33390267Sdes	if (f == NULL) {
334174588Sdes		fetch_syserr();
33597859Sdes		free(io);
33690267Sdes		return (NULL);
33790267Sdes	}
33890267Sdes	return (f);
33963012Sdes}
34063012Sdes
34190267Sdes
34263012Sdes/*****************************************************************************
34363012Sdes * Helper functions for talking to the server and parsing its replies
34463012Sdes */
34563012Sdes
34663012Sdes/* Header types */
34763012Sdestypedef enum {
34890267Sdes	hdr_syserror = -2,
34990267Sdes	hdr_error = -1,
35090267Sdes	hdr_end = 0,
35190267Sdes	hdr_unknown = 1,
35290267Sdes	hdr_content_length,
35390267Sdes	hdr_content_range,
35490267Sdes	hdr_last_modified,
35590267Sdes	hdr_location,
35690267Sdes	hdr_transfer_encoding,
357202613Sdes	hdr_www_authenticate,
358202613Sdes	hdr_proxy_authenticate,
35985093Sdes} hdr_t;
36063012Sdes
36163012Sdes/* Names of interesting headers */
36263012Sdesstatic struct {
36390267Sdes	hdr_t		 num;
36490267Sdes	const char	*name;
36563012Sdes} hdr_names[] = {
36690267Sdes	{ hdr_content_length,		"Content-Length" },
36790267Sdes	{ hdr_content_range,		"Content-Range" },
36890267Sdes	{ hdr_last_modified,		"Last-Modified" },
36990267Sdes	{ hdr_location,			"Location" },
37090267Sdes	{ hdr_transfer_encoding,	"Transfer-Encoding" },
37190267Sdes	{ hdr_www_authenticate,		"WWW-Authenticate" },
372202613Sdes	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
37390267Sdes	{ hdr_unknown,			NULL },
37463012Sdes};
37563012Sdes
37663012Sdes/*
37763012Sdes * Send a formatted line; optionally echo to terminal
37863012Sdes */
37963012Sdesstatic int
380174588Sdeshttp_cmd(conn_t *conn, const char *fmt, ...)
38163012Sdes{
38290267Sdes	va_list ap;
38390267Sdes	size_t len;
38490267Sdes	char *msg;
38590267Sdes	int r;
38663012Sdes
38790267Sdes	va_start(ap, fmt);
38890267Sdes	len = vasprintf(&msg, fmt, ap);
38990267Sdes	va_end(ap);
39090267Sdes
39190267Sdes	if (msg == NULL) {
39290267Sdes		errno = ENOMEM;
393174588Sdes		fetch_syserr();
39490267Sdes		return (-1);
39590267Sdes	}
39690267Sdes
397174588Sdes	r = fetch_putln(conn, msg, len);
39890267Sdes	free(msg);
39990267Sdes
40090267Sdes	if (r == -1) {
401174588Sdes		fetch_syserr();
40290267Sdes		return (-1);
40390267Sdes	}
40490267Sdes
40590267Sdes	return (0);
40663012Sdes}
40763012Sdes
40863012Sdes/*
40963012Sdes * Get and parse status line
41063012Sdes */
41163012Sdesstatic int
412174588Sdeshttp_get_reply(conn_t *conn)
41363012Sdes{
41490267Sdes	char *p;
41590267Sdes
416174588Sdes	if (fetch_getln(conn) == -1)
41790267Sdes		return (-1);
41890267Sdes	/*
41990267Sdes	 * A valid status line looks like "HTTP/m.n xyz reason" where m
42090267Sdes	 * and n are the major and minor protocol version numbers and xyz
42190267Sdes	 * is the reply code.
42290267Sdes	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
42390267Sdes	 * just one) that do not send a version number, so we can't rely
42490267Sdes	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
42590267Sdes	 * We don't care about the reason phrase.
42690267Sdes	 */
42797856Sdes	if (strncmp(conn->buf, "HTTP", 4) != 0)
42890267Sdes		return (HTTP_PROTOCOL_ERROR);
42997856Sdes	p = conn->buf + 4;
43090267Sdes	if (*p == '/') {
43190267Sdes		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
43290267Sdes			return (HTTP_PROTOCOL_ERROR);
43390267Sdes		p += 4;
43490267Sdes	}
435174761Sdes	if (*p != ' ' ||
436174761Sdes	    !isdigit((unsigned char)p[1]) ||
437174761Sdes	    !isdigit((unsigned char)p[2]) ||
438174761Sdes	    !isdigit((unsigned char)p[3]))
43990267Sdes		return (HTTP_PROTOCOL_ERROR);
44090267Sdes
44197856Sdes	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
44297856Sdes	return (conn->err);
44337535Sdes}
44437535Sdes
44537608Sdes/*
44690267Sdes * Check a header; if the type matches the given string, return a pointer
44790267Sdes * to the beginning of the value.
44863012Sdes */
44975891Sarchiestatic const char *
450174588Sdeshttp_match(const char *str, const char *hdr)
45163012Sdes{
452176036Sdes	while (*str && *hdr &&
453176036Sdes	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
45490267Sdes		/* nothing */;
45590267Sdes	if (*str || *hdr != ':')
45690267Sdes		return (NULL);
457174761Sdes	while (*hdr && isspace((unsigned char)*++hdr))
45890267Sdes		/* nothing */;
45990267Sdes	return (hdr);
46063012Sdes}
46163012Sdes
462202613Sdes
46363012Sdes/*
464202613Sdes * Get the next header and return the appropriate symbolic code.  We
465202613Sdes * need to read one line ahead for checking for a continuation line
466202613Sdes * belonging to the current header (continuation lines start with
467221821Sdes * white space).
468202613Sdes *
469202613Sdes * We get called with a fresh line already in the conn buffer, either
470202613Sdes * from the previous http_next_header() invocation, or, the first
471202613Sdes * time, from a fetch_getln() performed by our caller.
472202613Sdes *
473202613Sdes * This stops when we encounter an empty line (we dont read beyond the header
474202613Sdes * area).
475221821Sdes *
476202613Sdes * Note that the "headerbuf" is just a place to return the result. Its
477202613Sdes * contents are not used for the next call. This means that no cleanup
478202613Sdes * is needed when ie doing another connection, just call the cleanup when
479202613Sdes * fully done to deallocate memory.
48063012Sdes */
481202613Sdes
482202613Sdes/* Limit the max number of continuation lines to some reasonable value */
483202613Sdes#define HTTP_MAX_CONT_LINES 10
484202613Sdes
485202613Sdes/* Place into which to build a header from one or several lines */
486202613Sdestypedef struct {
487202613Sdes	char	*buf;		/* buffer */
488202613Sdes	size_t	 bufsize;	/* buffer size */
489202613Sdes	size_t	 buflen;	/* length of buffer contents */
490202613Sdes} http_headerbuf_t;
491202613Sdes
492202613Sdesstatic void
493202613Sdesinit_http_headerbuf(http_headerbuf_t *buf)
49463012Sdes{
495202613Sdes	buf->buf = NULL;
496202613Sdes	buf->bufsize = 0;
497202613Sdes	buf->buflen = 0;
498202613Sdes}
49990267Sdes
500221821Sdesstatic void
501202613Sdesclean_http_headerbuf(http_headerbuf_t *buf)
502202613Sdes{
503202613Sdes	if (buf->buf)
504202613Sdes		free(buf->buf);
505202613Sdes	init_http_headerbuf(buf);
506202613Sdes}
507202613Sdes
508202613Sdes/* Remove whitespace at the end of the buffer */
509221821Sdesstatic void
510202613Sdeshttp_conn_trimright(conn_t *conn)
511202613Sdes{
512221821Sdes	while (conn->buflen &&
513202613Sdes	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
51497856Sdes		conn->buflen--;
51597856Sdes	conn->buf[conn->buflen] = '\0';
516202613Sdes}
517202613Sdes
518202613Sdesstatic hdr_t
519202613Sdeshttp_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
520202613Sdes{
521221820Sdes	unsigned int i, len;
522202613Sdes
523221821Sdes	/*
524202613Sdes	 * Have to do the stripping here because of the first line. So
525221821Sdes	 * it's done twice for the subsequent lines. No big deal
526202613Sdes	 */
527202613Sdes	http_conn_trimright(conn);
52897856Sdes	if (conn->buflen == 0)
52997856Sdes		return (hdr_end);
530202613Sdes
531202613Sdes	/* Copy the line to the headerbuf */
532202613Sdes	if (hbuf->bufsize < conn->buflen + 1) {
533202613Sdes		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
534202613Sdes			return (hdr_syserror);
535202613Sdes		hbuf->bufsize = conn->buflen + 1;
536202613Sdes	}
537202613Sdes	strcpy(hbuf->buf, conn->buf);
538202613Sdes	hbuf->buflen = conn->buflen;
539202613Sdes
540221821Sdes	/*
541202613Sdes	 * Fetch possible continuation lines. Stop at 1st non-continuation
542221821Sdes	 * and leave it in the conn buffer
543221821Sdes	 */
544202613Sdes	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
545202613Sdes		if (fetch_getln(conn) == -1)
546202613Sdes			return (hdr_syserror);
547202613Sdes
548221821Sdes		/*
549202613Sdes		 * Note: we carry on the idea from the previous version
550202613Sdes		 * that a pure whitespace line is equivalent to an empty
551202613Sdes		 * one (so it's not continuation and will be handled when
552221821Sdes		 * we are called next)
553202613Sdes		 */
554202613Sdes		http_conn_trimright(conn);
555202613Sdes		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
556202613Sdes			break;
557202613Sdes
558202613Sdes		/* Got a continuation line. Concatenate to previous */
559202613Sdes		len = hbuf->buflen + conn->buflen;
560202613Sdes		if (hbuf->bufsize < len + 1) {
561202613Sdes			len *= 2;
562202613Sdes			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
563202613Sdes				return (hdr_syserror);
564202613Sdes			hbuf->bufsize = len + 1;
565202613Sdes		}
566202613Sdes		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
567202613Sdes		hbuf->buflen += conn->buflen;
568221821Sdes	}
569202613Sdes
57090267Sdes	/*
57190267Sdes	 * We could check for malformed headers but we don't really care.
57290267Sdes	 * A valid header starts with a token immediately followed by a
57390267Sdes	 * colon; a token is any sequence of non-control, non-whitespace
57490267Sdes	 * characters except "()<>@,;:\\\"{}".
57590267Sdes	 */
57690267Sdes	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
577202613Sdes		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
57890267Sdes			return (hdr_names[i].num);
579202613Sdes
58090267Sdes	return (hdr_unknown);
58163012Sdes}
58263012Sdes
583202613Sdes/**************************
584202613Sdes * [Proxy-]Authenticate header parsing
585202613Sdes */
586202613Sdes
587221821Sdes/*
588221821Sdes * Read doublequote-delimited string into output buffer obuf (allocated
589202613Sdes * by caller, whose responsibility it is to ensure that it's big enough)
590202613Sdes * cp points to the first char after the initial '"'
591221821Sdes * Handles \ quoting
592221821Sdes * Returns pointer to the first char after the terminating double quote, or
593202613Sdes * NULL for error.
594202613Sdes */
595202613Sdesstatic const char *
596202613Sdeshttp_parse_headerstring(const char *cp, char *obuf)
597202613Sdes{
598202613Sdes	for (;;) {
599202613Sdes		switch (*cp) {
600202613Sdes		case 0: /* Unterminated string */
601202613Sdes			*obuf = 0;
602202613Sdes			return (NULL);
603202613Sdes		case '"': /* Ending quote */
604202613Sdes			*obuf = 0;
605202613Sdes			return (++cp);
606202613Sdes		case '\\':
607202613Sdes			if (*++cp == 0) {
608202613Sdes				*obuf = 0;
609202613Sdes				return (NULL);
610202613Sdes			}
611202613Sdes			/* FALLTHROUGH */
612202613Sdes		default:
613202613Sdes			*obuf++ = *cp++;
614202613Sdes		}
615202613Sdes	}
616202613Sdes}
617202613Sdes
618202613Sdes/* Http auth challenge schemes */
619202613Sdestypedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
620202613Sdes
621202613Sdes/* Data holder for a Basic or Digest challenge. */
622202613Sdestypedef struct {
623202613Sdes	http_auth_schemes_t scheme;
624202613Sdes	char	*realm;
625202613Sdes	char	*qop;
626202613Sdes	char	*nonce;
627202613Sdes	char	*opaque;
628202613Sdes	char	*algo;
629202613Sdes	int	 stale;
630202613Sdes	int	 nc; /* Nonce count */
631202613Sdes} http_auth_challenge_t;
632202613Sdes
633221821Sdesstatic void
634202613Sdesinit_http_auth_challenge(http_auth_challenge_t *b)
635202613Sdes{
636202613Sdes	b->scheme = HTTPAS_UNKNOWN;
637202613Sdes	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
638202613Sdes	b->stale = b->nc = 0;
639202613Sdes}
640202613Sdes
641221821Sdesstatic void
642202613Sdesclean_http_auth_challenge(http_auth_challenge_t *b)
643202613Sdes{
644221821Sdes	if (b->realm)
645202613Sdes		free(b->realm);
646221821Sdes	if (b->qop)
647202613Sdes		free(b->qop);
648221821Sdes	if (b->nonce)
649202613Sdes		free(b->nonce);
650221821Sdes	if (b->opaque)
651202613Sdes		free(b->opaque);
652221821Sdes	if (b->algo)
653202613Sdes		free(b->algo);
654202613Sdes	init_http_auth_challenge(b);
655202613Sdes}
656202613Sdes
657202613Sdes/* Data holder for an array of challenges offered in an http response. */
658202613Sdes#define MAX_CHALLENGES 10
659202613Sdestypedef struct {
660202613Sdes	http_auth_challenge_t *challenges[MAX_CHALLENGES];
661202613Sdes	int	count; /* Number of parsed challenges in the array */
662202613Sdes	int	valid; /* We did parse an authenticate header */
663202613Sdes} http_auth_challenges_t;
664202613Sdes
665221821Sdesstatic void
666202613Sdesinit_http_auth_challenges(http_auth_challenges_t *cs)
667202613Sdes{
668202613Sdes	int i;
669202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++)
670202613Sdes		cs->challenges[i] = NULL;
671202613Sdes	cs->count = cs->valid = 0;
672202613Sdes}
673202613Sdes
674221821Sdesstatic void
675202613Sdesclean_http_auth_challenges(http_auth_challenges_t *cs)
676202613Sdes{
677202613Sdes	int i;
678202613Sdes	/* We rely on non-zero pointers being allocated, not on the count */
679202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++) {
680202613Sdes		if (cs->challenges[i] != NULL) {
681202613Sdes			clean_http_auth_challenge(cs->challenges[i]);
682202613Sdes			free(cs->challenges[i]);
683202613Sdes		}
684202613Sdes	}
685202613Sdes	init_http_auth_challenges(cs);
686202613Sdes}
687202613Sdes
688221821Sdes/*
689202613Sdes * Enumeration for lexical elements. Separators will be returned as their own
690202613Sdes * ascii value
691202613Sdes */
692202613Sdestypedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
693202613Sdes	      HTTPHL_ERROR = 259} http_header_lex_t;
694202613Sdes
695221821Sdes/*
696202613Sdes * Determine what kind of token comes next and return possible value
697202613Sdes * in buf, which is supposed to have been allocated big enough by
698221821Sdes * caller. Advance input pointer and return element type.
699202613Sdes */
700221821Sdesstatic int
701202613Sdeshttp_header_lex(const char **cpp, char *buf)
702202613Sdes{
703202613Sdes	size_t l;
704202613Sdes	/* Eat initial whitespace */
705202613Sdes	*cpp += strspn(*cpp, " \t");
706202613Sdes	if (**cpp == 0)
707202613Sdes		return (HTTPHL_END);
708202613Sdes
709202613Sdes	/* Separator ? */
710202613Sdes	if (**cpp == ',' || **cpp == '=')
711202613Sdes		return (*((*cpp)++));
712202613Sdes
713202613Sdes	/* String ? */
714202613Sdes	if (**cpp == '"') {
715202613Sdes		*cpp = http_parse_headerstring(++*cpp, buf);
716202613Sdes		if (*cpp == NULL)
717202613Sdes			return (HTTPHL_ERROR);
718202613Sdes		return (HTTPHL_STRING);
719202613Sdes	}
720202613Sdes
721202613Sdes	/* Read other token, until separator or whitespace */
722202613Sdes	l = strcspn(*cpp, " \t,=");
723202613Sdes	memcpy(buf, *cpp, l);
724202613Sdes	buf[l] = 0;
725202613Sdes	*cpp += l;
726202613Sdes	return (HTTPHL_WORD);
727202613Sdes}
728202613Sdes
729221821Sdes/*
730202613Sdes * Read challenges from http xxx-authenticate header and accumulate them
731202613Sdes * in the challenges list structure.
732202613Sdes *
733202613Sdes * Headers with multiple challenges are specified by rfc2617, but
734202613Sdes * servers (ie: squid) often send them in separate headers instead,
735202613Sdes * which in turn is forbidden by the http spec (multiple headers with
736202613Sdes * the same name are only allowed for pure comma-separated lists, see
737202613Sdes * rfc2616 sec 4.2).
738202613Sdes *
739202613Sdes * We support both approaches anyway
740202613Sdes */
741221821Sdesstatic int
742202613Sdeshttp_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
743202613Sdes{
744202613Sdes	int ret = -1;
745202613Sdes	http_header_lex_t lex;
746202613Sdes	char *key = malloc(strlen(cp) + 1);
747202613Sdes	char *value = malloc(strlen(cp) + 1);
748202613Sdes	char *buf = malloc(strlen(cp) + 1);
749202613Sdes
750202613Sdes	if (key == NULL || value == NULL || buf == NULL) {
751202613Sdes		fetch_syserr();
752202613Sdes		goto out;
753202613Sdes	}
754202613Sdes
755202613Sdes	/* In any case we've seen the header and we set the valid bit */
756202613Sdes	cs->valid = 1;
757202613Sdes
758202613Sdes	/* Need word first */
759202613Sdes	lex = http_header_lex(&cp, key);
760202613Sdes	if (lex != HTTPHL_WORD)
761202613Sdes		goto out;
762202613Sdes
763202613Sdes	/* Loop on challenges */
764202613Sdes	for (; cs->count < MAX_CHALLENGES; cs->count++) {
765221821Sdes		cs->challenges[cs->count] =
766202613Sdes			malloc(sizeof(http_auth_challenge_t));
767202613Sdes		if (cs->challenges[cs->count] == NULL) {
768202613Sdes			fetch_syserr();
769202613Sdes			goto out;
770202613Sdes		}
771202613Sdes		init_http_auth_challenge(cs->challenges[cs->count]);
772202613Sdes		if (!strcasecmp(key, "basic")) {
773202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
774202613Sdes		} else if (!strcasecmp(key, "digest")) {
775202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
776202613Sdes		} else {
777202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
778221821Sdes			/*
779221821Sdes			 * Continue parsing as basic or digest may
780202613Sdes			 * follow, and the syntax is the same for
781202613Sdes			 * all. We'll just ignore this one when
782202613Sdes			 * looking at the list
783202613Sdes			 */
784202613Sdes		}
785221821Sdes
786202613Sdes		/* Loop on attributes */
787202613Sdes		for (;;) {
788202613Sdes			/* Key */
789202613Sdes			lex = http_header_lex(&cp, key);
790202613Sdes			if (lex != HTTPHL_WORD)
791202613Sdes				goto out;
792202613Sdes
793202613Sdes			/* Equal sign */
794202613Sdes			lex = http_header_lex(&cp, buf);
795202613Sdes			if (lex != '=')
796202613Sdes				goto out;
797202613Sdes
798202613Sdes			/* Value */
799202613Sdes			lex = http_header_lex(&cp, value);
800202613Sdes			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
801202613Sdes				goto out;
802202613Sdes
803202613Sdes			if (!strcasecmp(key, "realm"))
804221821Sdes				cs->challenges[cs->count]->realm =
805202613Sdes					strdup(value);
806202613Sdes			else if (!strcasecmp(key, "qop"))
807221821Sdes				cs->challenges[cs->count]->qop =
808202613Sdes					strdup(value);
809202613Sdes			else if (!strcasecmp(key, "nonce"))
810221821Sdes				cs->challenges[cs->count]->nonce =
811202613Sdes					strdup(value);
812202613Sdes			else if (!strcasecmp(key, "opaque"))
813221821Sdes				cs->challenges[cs->count]->opaque =
814202613Sdes					strdup(value);
815202613Sdes			else if (!strcasecmp(key, "algorithm"))
816221821Sdes				cs->challenges[cs->count]->algo =
817202613Sdes					strdup(value);
818202613Sdes			else if (!strcasecmp(key, "stale"))
819221821Sdes				cs->challenges[cs->count]->stale =
820202613Sdes					strcasecmp(value, "no");
821202613Sdes			/* Else ignore unknown attributes */
822202613Sdes
823202613Sdes			/* Comma or Next challenge or End */
824202613Sdes			lex = http_header_lex(&cp, key);
825221821Sdes			/*
826221821Sdes			 * If we get a word here, this is the beginning of the
827221821Sdes			 * next challenge. Break the attributes loop
828221821Sdes			 */
829202613Sdes			if (lex == HTTPHL_WORD)
830202613Sdes				break;
831202613Sdes
832202613Sdes			if (lex == HTTPHL_END) {
833202613Sdes				/* End while looking for ',' is normal exit */
834202613Sdes				cs->count++;
835202613Sdes				ret = 0;
836202613Sdes				goto out;
837202613Sdes			}
838202613Sdes			/* Anything else is an error */
839202613Sdes			if (lex != ',')
840202613Sdes				goto out;
841202613Sdes
842202613Sdes		} /* End attributes loop */
843202613Sdes	} /* End challenge loop */
844202613Sdes
845221821Sdes	/*
846221821Sdes	 * Challenges max count exceeded. This really can't happen
847221821Sdes	 * with normal data, something's fishy -> error
848221821Sdes	 */
849202613Sdes
850202613Sdesout:
851202613Sdes	if (key)
852202613Sdes		free(key);
853202613Sdes	if (value)
854202613Sdes		free(value);
855202613Sdes	if (buf)
856202613Sdes		free(buf);
857202613Sdes	return (ret);
858202613Sdes}
859202613Sdes
860202613Sdes
86163012Sdes/*
86263012Sdes * Parse a last-modified header
86363012Sdes */
86463716Sdesstatic int
865174588Sdeshttp_parse_mtime(const char *p, time_t *mtime)
86663012Sdes{
86790267Sdes	char locale[64], *r;
86890267Sdes	struct tm tm;
86963012Sdes
870109967Sdes	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
87190267Sdes	setlocale(LC_TIME, "C");
87290267Sdes	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
87390267Sdes	/* XXX should add support for date-2 and date-3 */
87490267Sdes	setlocale(LC_TIME, locale);
87590267Sdes	if (r == NULL)
87690267Sdes		return (-1);
87790267Sdes	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
87888769Sdes		  "%02d:%02d:%02d]\n",
87963012Sdes		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
88063012Sdes		  tm.tm_hour, tm.tm_min, tm.tm_sec));
88190267Sdes	*mtime = timegm(&tm);
88290267Sdes	return (0);
88363012Sdes}
88463012Sdes
88563012Sdes/*
88663012Sdes * Parse a content-length header
88763012Sdes */
88863716Sdesstatic int
889174588Sdeshttp_parse_length(const char *p, off_t *length)
89063012Sdes{
89190267Sdes	off_t len;
89290267Sdes
893174761Sdes	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
89490267Sdes		len = len * 10 + (*p - '0');
89590267Sdes	if (*p)
89690267Sdes		return (-1);
89790267Sdes	DEBUG(fprintf(stderr, "content length: [%lld]\n",
89890267Sdes	    (long long)len));
89990267Sdes	*length = len;
90090267Sdes	return (0);
90163012Sdes}
90263012Sdes
90363012Sdes/*
90463012Sdes * Parse a content-range header
90563012Sdes */
90663716Sdesstatic int
907174588Sdeshttp_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
90863012Sdes{
90990267Sdes	off_t first, last, len;
91063716Sdes
91190267Sdes	if (strncasecmp(p, "bytes ", 6) != 0)
91290267Sdes		return (-1);
913125696Sdes	p += 6;
914125696Sdes	if (*p == '*') {
915125696Sdes		first = last = -1;
916125696Sdes		++p;
917125696Sdes	} else {
918174761Sdes		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
919125696Sdes			first = first * 10 + *p - '0';
920125696Sdes		if (*p != '-')
921125696Sdes			return (-1);
922174761Sdes		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
923125696Sdes			last = last * 10 + *p - '0';
924125696Sdes	}
92590267Sdes	if (first > last || *p != '/')
92690267Sdes		return (-1);
927174761Sdes	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
92890267Sdes		len = len * 10 + *p - '0';
92990267Sdes	if (*p || len < last - first + 1)
93090267Sdes		return (-1);
931125696Sdes	if (first == -1) {
932125696Sdes		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
933125696Sdes		    (long long)len));
934125696Sdes		*length = 0;
935125696Sdes	} else {
936125696Sdes		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
937125696Sdes		    (long long)first, (long long)last, (long long)len));
938125696Sdes		*length = last - first + 1;
939125696Sdes	}
94090267Sdes	*offset = first;
94190267Sdes	*size = len;
94290267Sdes	return (0);
94363012Sdes}
94463012Sdes
94590267Sdes
94663012Sdes/*****************************************************************************
94763012Sdes * Helper functions for authorization
94863012Sdes */
94963012Sdes
95063012Sdes/*
95137608Sdes * Base64 encoding
95237608Sdes */
95362965Sdesstatic char *
954174588Sdeshttp_base64(const char *src)
95537608Sdes{
95690267Sdes	static const char base64[] =
95790267Sdes	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
95890267Sdes	    "abcdefghijklmnopqrstuvwxyz"
95990267Sdes	    "0123456789+/";
96090267Sdes	char *str, *dst;
96190267Sdes	size_t l;
96290267Sdes	int t, r;
96362965Sdes
96490267Sdes	l = strlen(src);
965133280Sdes	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
96690267Sdes		return (NULL);
96790267Sdes	dst = str;
96890267Sdes	r = 0;
96937608Sdes
97090267Sdes	while (l >= 3) {
97190267Sdes		t = (src[0] << 16) | (src[1] << 8) | src[2];
97290267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
97390267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
97490267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
97590267Sdes		dst[3] = base64[(t >> 0) & 0x3f];
97690267Sdes		src += 3; l -= 3;
97790267Sdes		dst += 4; r += 4;
97890267Sdes	}
97937608Sdes
98090267Sdes	switch (l) {
98190267Sdes	case 2:
98290267Sdes		t = (src[0] << 16) | (src[1] << 8);
98390267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
98490267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
98590267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
98690267Sdes		dst[3] = '=';
98790267Sdes		dst += 4;
98890267Sdes		r += 4;
98990267Sdes		break;
99090267Sdes	case 1:
99190267Sdes		t = src[0] << 16;
99290267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
99390267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
99490267Sdes		dst[2] = dst[3] = '=';
99590267Sdes		dst += 4;
99690267Sdes		r += 4;
99790267Sdes		break;
99890267Sdes	case 0:
99990267Sdes		break;
100090267Sdes	}
100190267Sdes
100290267Sdes	*dst = 0;
100390267Sdes	return (str);
100437608Sdes}
100537608Sdes
1006202613Sdes
100737608Sdes/*
1008202613Sdes * Extract authorization parameters from environment value.
1009202613Sdes * The value is like scheme:realm:user:pass
1010202613Sdes */
1011202613Sdestypedef struct {
1012202613Sdes	char	*scheme;
1013202613Sdes	char	*realm;
1014202613Sdes	char	*user;
1015202613Sdes	char	*password;
1016202613Sdes} http_auth_params_t;
1017202613Sdes
1018202613Sdesstatic void
1019202613Sdesinit_http_auth_params(http_auth_params_t *s)
1020202613Sdes{
1021202613Sdes	s->scheme = s->realm = s->user = s->password = 0;
1022202613Sdes}
1023202613Sdes
1024221821Sdesstatic void
1025202613Sdesclean_http_auth_params(http_auth_params_t *s)
1026202613Sdes{
1027221821Sdes	if (s->scheme)
1028202613Sdes		free(s->scheme);
1029221821Sdes	if (s->realm)
1030202613Sdes		free(s->realm);
1031221821Sdes	if (s->user)
1032202613Sdes		free(s->user);
1033221821Sdes	if (s->password)
1034202613Sdes		free(s->password);
1035202613Sdes	init_http_auth_params(s);
1036202613Sdes}
1037202613Sdes
1038202613Sdesstatic int
1039202613Sdeshttp_authfromenv(const char *p, http_auth_params_t *parms)
1040202613Sdes{
1041202613Sdes	int ret = -1;
1042202613Sdes	char *v, *ve;
1043202613Sdes	char *str = strdup(p);
1044202613Sdes
1045202613Sdes	if (str == NULL) {
1046202613Sdes		fetch_syserr();
1047202613Sdes		return (-1);
1048202613Sdes	}
1049202613Sdes	v = str;
1050202613Sdes
1051202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1052202613Sdes		goto out;
1053202613Sdes
1054202613Sdes	*ve = 0;
1055202613Sdes	if ((parms->scheme = strdup(v)) == NULL) {
1056202613Sdes		fetch_syserr();
1057202613Sdes		goto out;
1058202613Sdes	}
1059202613Sdes	v = ve + 1;
1060202613Sdes
1061202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1062202613Sdes		goto out;
1063202613Sdes
1064202613Sdes	*ve = 0;
1065202613Sdes	if ((parms->realm = strdup(v)) == NULL) {
1066202613Sdes		fetch_syserr();
1067202613Sdes		goto out;
1068202613Sdes	}
1069202613Sdes	v = ve + 1;
1070202613Sdes
1071202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1072202613Sdes		goto out;
1073202613Sdes
1074202613Sdes	*ve = 0;
1075202613Sdes	if ((parms->user = strdup(v)) == NULL) {
1076202613Sdes		fetch_syserr();
1077202613Sdes		goto out;
1078202613Sdes	}
1079202613Sdes	v = ve + 1;
1080202613Sdes
1081202613Sdes
1082202613Sdes	if ((parms->password = strdup(v)) == NULL) {
1083202613Sdes		fetch_syserr();
1084202613Sdes		goto out;
1085202613Sdes	}
1086202613Sdes	ret = 0;
1087202613Sdesout:
1088221821Sdes	if (ret == -1)
1089202613Sdes		clean_http_auth_params(parms);
1090202613Sdes	if (str)
1091202613Sdes		free(str);
1092202613Sdes	return (ret);
1093202613Sdes}
1094202613Sdes
1095202613Sdes
1096221821Sdes/*
1097202613Sdes * Digest response: the code to compute the digest is taken from the
1098221821Sdes * sample implementation in RFC2616
1099202613Sdes */
1100221822Sdes#define IN const
1101202613Sdes#define OUT
1102202613Sdes
1103202613Sdes#define HASHLEN 16
1104202613Sdestypedef char HASH[HASHLEN];
1105202613Sdes#define HASHHEXLEN 32
1106202613Sdestypedef char HASHHEX[HASHHEXLEN+1];
1107202613Sdes
1108202613Sdesstatic const char *hexchars = "0123456789abcdef";
1109221821Sdesstatic void
1110202613SdesCvtHex(IN HASH Bin, OUT HASHHEX Hex)
1111202613Sdes{
1112202613Sdes	unsigned short i;
1113202613Sdes	unsigned char j;
1114202613Sdes
1115202613Sdes	for (i = 0; i < HASHLEN; i++) {
1116202613Sdes		j = (Bin[i] >> 4) & 0xf;
1117202613Sdes		Hex[i*2] = hexchars[j];
1118202613Sdes		j = Bin[i] & 0xf;
1119202613Sdes		Hex[i*2+1] = hexchars[j];
1120202613Sdes	};
1121202613Sdes	Hex[HASHHEXLEN] = '\0';
1122202613Sdes};
1123202613Sdes
1124202613Sdes/* calculate H(A1) as per spec */
1125221821Sdesstatic void
1126202613SdesDigestCalcHA1(
1127202613Sdes	IN char * pszAlg,
1128202613Sdes	IN char * pszUserName,
1129202613Sdes	IN char * pszRealm,
1130202613Sdes	IN char * pszPassword,
1131202613Sdes	IN char * pszNonce,
1132202613Sdes	IN char * pszCNonce,
1133202613Sdes	OUT HASHHEX SessionKey
1134202613Sdes	)
1135202613Sdes{
1136202613Sdes	MD5_CTX Md5Ctx;
1137202613Sdes	HASH HA1;
1138202613Sdes
1139202613Sdes	MD5Init(&Md5Ctx);
1140202613Sdes	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1141202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1142202613Sdes	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1143202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1144202613Sdes	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1145202613Sdes	MD5Final(HA1, &Md5Ctx);
1146202613Sdes	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1147202613Sdes
1148202613Sdes		MD5Init(&Md5Ctx);
1149202613Sdes		MD5Update(&Md5Ctx, HA1, HASHLEN);
1150202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1151202613Sdes		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1152202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1153202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1154202613Sdes		MD5Final(HA1, &Md5Ctx);
1155202613Sdes	};
1156202613Sdes	CvtHex(HA1, SessionKey);
1157202613Sdes}
1158202613Sdes
1159202613Sdes/* calculate request-digest/response-digest as per HTTP Digest spec */
1160221821Sdesstatic void
1161202613SdesDigestCalcResponse(
1162202613Sdes	IN HASHHEX HA1,           /* H(A1) */
1163202613Sdes	IN char * pszNonce,       /* nonce from server */
1164202613Sdes	IN char * pszNonceCount,  /* 8 hex digits */
1165202613Sdes	IN char * pszCNonce,      /* client nonce */
1166202613Sdes	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1167202613Sdes	IN char * pszMethod,      /* method from the request */
1168202613Sdes	IN char * pszDigestUri,   /* requested URL */
1169202613Sdes	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1170202613Sdes	OUT HASHHEX Response      /* request-digest or response-digest */
1171202613Sdes	)
1172202613Sdes{
1173221821Sdes/*	DEBUG(fprintf(stderr,
1174202613Sdes		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1175202613Sdes		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1176202613Sdes	MD5_CTX Md5Ctx;
1177202613Sdes	HASH HA2;
1178202613Sdes	HASH RespHash;
1179202613Sdes	HASHHEX HA2Hex;
1180202613Sdes
1181202613Sdes	// calculate H(A2)
1182202613Sdes	MD5Init(&Md5Ctx);
1183202613Sdes	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1184202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1185202613Sdes	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1186202613Sdes	if (strcasecmp(pszQop, "auth-int") == 0) {
1187202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1188202613Sdes		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1189202613Sdes	};
1190202613Sdes	MD5Final(HA2, &Md5Ctx);
1191202613Sdes	CvtHex(HA2, HA2Hex);
1192202613Sdes
1193202613Sdes	// calculate response
1194202613Sdes	MD5Init(&Md5Ctx);
1195202613Sdes	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1196202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1197202613Sdes	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1198202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1199202613Sdes	if (*pszQop) {
1200202613Sdes		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1201202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1202202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1203202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1204202613Sdes		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1205202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1206202613Sdes	};
1207202613Sdes	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1208202613Sdes	MD5Final(RespHash, &Md5Ctx);
1209202613Sdes	CvtHex(RespHash, Response);
1210202613Sdes}
1211202613Sdes
1212221821Sdes/*
1213221821Sdes * Generate/Send a Digest authorization header
1214202613Sdes * This looks like: [Proxy-]Authorization: credentials
1215202613Sdes *
1216202613Sdes *  credentials      = "Digest" digest-response
1217202613Sdes *  digest-response  = 1#( username | realm | nonce | digest-uri
1218202613Sdes *                      | response | [ algorithm ] | [cnonce] |
1219202613Sdes *                      [opaque] | [message-qop] |
1220202613Sdes *                          [nonce-count]  | [auth-param] )
1221202613Sdes *  username         = "username" "=" username-value
1222202613Sdes *  username-value   = quoted-string
1223202613Sdes *  digest-uri       = "uri" "=" digest-uri-value
1224202613Sdes *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1225202613Sdes *  message-qop      = "qop" "=" qop-value
1226202613Sdes *  cnonce           = "cnonce" "=" cnonce-value
1227202613Sdes *  cnonce-value     = nonce-value
1228202613Sdes *  nonce-count      = "nc" "=" nc-value
1229202613Sdes *  nc-value         = 8LHEX
1230202613Sdes *  response         = "response" "=" request-digest
1231202613Sdes *  request-digest = <"> 32LHEX <">
1232202613Sdes */
1233202613Sdesstatic int
1234202613Sdeshttp_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1235202613Sdes		 http_auth_params_t *parms, struct url *url)
1236202613Sdes{
1237202613Sdes	int r;
1238202613Sdes	char noncecount[10];
1239202613Sdes	char cnonce[40];
1240202613Sdes	char *options = 0;
1241202613Sdes
1242202613Sdes	if (!c->realm || !c->nonce) {
1243202613Sdes		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1244202613Sdes		return(-1);
1245202613Sdes	}
1246221821Sdes	if (!c->algo)
1247202613Sdes		c->algo = strdup("");
1248202613Sdes
1249221821Sdes	if (asprintf(&options, "%s%s%s%s",
1250202613Sdes		     *c->algo? ",algorithm=" : "", c->algo,
1251202613Sdes		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1252202613Sdes		return (-1);
1253202613Sdes
1254202613Sdes	if (!c->qop) {
1255202613Sdes		c->qop = strdup("");
1256202613Sdes		*noncecount = 0;
1257202613Sdes		*cnonce = 0;
1258202613Sdes	} else {
1259202613Sdes		c->nc++;
1260202613Sdes		sprintf(noncecount, "%08x", c->nc);
1261202613Sdes		/* We don't try very hard with the cnonce ... */
1262202613Sdes		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1263202613Sdes	}
1264202613Sdes
1265202613Sdes	HASHHEX HA1;
1266202613Sdes	DigestCalcHA1(c->algo, parms->user, c->realm,
1267202613Sdes		      parms->password, c->nonce, cnonce, HA1);
1268202613Sdes	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1269202613Sdes	HASHHEX digest;
1270202613Sdes	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1271202613Sdes			   "GET", url->doc, "", digest);
1272202613Sdes
1273202613Sdes	if (c->qop[0]) {
1274202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1275202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1276202613Sdes			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1277221821Sdes			     hdr, parms->user, c->realm,
1278202613Sdes			     c->nonce, url->doc, digest,
1279202613Sdes			     cnonce, noncecount, options);
1280202613Sdes	} else {
1281202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1282202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1283221821Sdes			     hdr, parms->user, c->realm,
1284202613Sdes			     c->nonce, url->doc, digest, options);
1285202613Sdes	}
1286202613Sdes	if (options)
1287202613Sdes		free(options);
1288202613Sdes	return (r);
1289202613Sdes}
1290202613Sdes
1291202613Sdes/*
129237608Sdes * Encode username and password
129337608Sdes */
129462965Sdesstatic int
1295174588Sdeshttp_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
129637608Sdes{
129790267Sdes	char *upw, *auth;
129890267Sdes	int r;
129937608Sdes
1300202613Sdes	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1301202613Sdes	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
130290267Sdes	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
130390267Sdes		return (-1);
1304174588Sdes	auth = http_base64(upw);
130590267Sdes	free(upw);
130690267Sdes	if (auth == NULL)
130790267Sdes		return (-1);
1308174588Sdes	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
130990267Sdes	free(auth);
131090267Sdes	return (r);
131162965Sdes}
131262965Sdes
131362965Sdes/*
1314221821Sdes * Chose the challenge to answer and call the appropriate routine to
1315202613Sdes * produce the header.
131662965Sdes */
131762965Sdesstatic int
1318202613Sdeshttp_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1319202613Sdes	       http_auth_params_t *parms, struct url *url)
132062965Sdes{
1321202613Sdes	http_auth_challenge_t *basic = NULL;
1322202613Sdes	http_auth_challenge_t *digest = NULL;
1323202613Sdes	int i;
132462965Sdes
1325202613Sdes	/* If user or pass are null we're not happy */
1326202613Sdes	if (!parms->user || !parms->password) {
1327202613Sdes		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1328202613Sdes		return (-1);
132990267Sdes	}
1330202613Sdes
1331202613Sdes	/* Look for a Digest and a Basic challenge */
1332202613Sdes	for (i = 0; i < cs->count; i++) {
1333202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1334202613Sdes			basic = cs->challenges[i];
1335202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1336202613Sdes			digest = cs->challenges[i];
1337202613Sdes	}
1338202613Sdes
1339202613Sdes	/* Error if "Digest" was specified and there is no Digest challenge */
1340221821Sdes	if (!digest && (parms->scheme &&
1341202613Sdes			!strcasecmp(parms->scheme, "digest"))) {
1342221821Sdes		DEBUG(fprintf(stderr,
1343202613Sdes			      "Digest auth in env, not supported by peer\n"));
1344202613Sdes		return (-1);
1345202613Sdes	}
1346221821Sdes	/*
1347221821Sdes	 * If "basic" was specified in the environment, or there is no Digest
1348202613Sdes	 * challenge, do the basic thing. Don't need a challenge for this,
1349221821Sdes	 * so no need to check basic!=NULL
1350202613Sdes	 */
1351202613Sdes	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1352202613Sdes		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1353202613Sdes
1354202613Sdes	/* Else, prefer digest. We just checked that it's not NULL */
1355202613Sdes	return (http_digest_auth(conn, hdr, digest, parms, url));
135637608Sdes}
135737608Sdes
135863012Sdes/*****************************************************************************
135963012Sdes * Helper functions for connecting to a server or proxy
136063012Sdes */
136163012Sdes
136237608Sdes/*
136390267Sdes * Connect to the correct HTTP server or proxy.
136463012Sdes */
136597856Sdesstatic conn_t *
1366174588Sdeshttp_connect(struct url *URL, struct url *purl, const char *flags)
136763012Sdes{
136897856Sdes	conn_t *conn;
136990267Sdes	int verbose;
1370141958Skbyanc	int af, val;
137190267Sdes
137263012Sdes#ifdef INET6
137390267Sdes	af = AF_UNSPEC;
137460737Sume#else
137590267Sdes	af = AF_INET;
137660737Sume#endif
137790267Sdes
137890267Sdes	verbose = CHECK_FLAG('v');
137990267Sdes	if (CHECK_FLAG('4'))
138090267Sdes		af = AF_INET;
138167043Sdes#ifdef INET6
138290267Sdes	else if (CHECK_FLAG('6'))
138390267Sdes		af = AF_INET6;
138467043Sdes#endif
138567043Sdes
138697868Sdes	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
138790267Sdes		URL = purl;
138890267Sdes	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
138990267Sdes		/* can't talk http to an ftp server */
139090267Sdes		/* XXX should set an error code */
139197856Sdes		return (NULL);
139290267Sdes	}
139390267Sdes
1394174588Sdes	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1395174588Sdes		/* fetch_connect() has already set an error code */
139697856Sdes		return (NULL);
139797868Sdes	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1398174588Sdes	    fetch_ssl(conn, verbose) == -1) {
1399174588Sdes		fetch_close(conn);
140097891Sdes		/* grrr */
140197891Sdes		errno = EAUTH;
1402174588Sdes		fetch_syserr();
140397868Sdes		return (NULL);
140497868Sdes	}
1405141958Skbyanc
1406141958Skbyanc	val = 1;
1407141958Skbyanc	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1408141958Skbyanc
140997856Sdes	return (conn);
141067043Sdes}
141167043Sdes
141267043Sdesstatic struct url *
1413174752Sdeshttp_get_proxy(struct url * url, const char *flags)
141467043Sdes{
141590267Sdes	struct url *purl;
141690267Sdes	char *p;
141790267Sdes
1418112797Sdes	if (flags != NULL && strchr(flags, 'd') != NULL)
1419112081Sdes		return (NULL);
1420174752Sdes	if (fetch_no_proxy_match(url->host))
1421174752Sdes		return (NULL);
142290267Sdes	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1423149414Sdes	    *p && (purl = fetchParseURL(p))) {
142490267Sdes		if (!*purl->scheme)
142590267Sdes			strcpy(purl->scheme, SCHEME_HTTP);
142690267Sdes		if (!purl->port)
1427174588Sdes			purl->port = fetch_default_proxy_port(purl->scheme);
142890267Sdes		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
142990267Sdes			return (purl);
143090267Sdes		fetchFreeURL(purl);
143190267Sdes	}
143290267Sdes	return (NULL);
143360376Sdes}
143460376Sdes
143588771Sdesstatic void
1436174588Sdeshttp_print_html(FILE *out, FILE *in)
143788771Sdes{
143890267Sdes	size_t len;
143990267Sdes	char *line, *p, *q;
144090267Sdes	int comment, tag;
144188771Sdes
144290267Sdes	comment = tag = 0;
144390267Sdes	while ((line = fgetln(in, &len)) != NULL) {
1444174761Sdes		while (len && isspace((unsigned char)line[len - 1]))
144590267Sdes			--len;
144690267Sdes		for (p = q = line; q < line + len; ++q) {
144790267Sdes			if (comment && *q == '-') {
144890267Sdes				if (q + 2 < line + len &&
144990267Sdes				    strcmp(q, "-->") == 0) {
145090267Sdes					tag = comment = 0;
145190267Sdes					q += 2;
145290267Sdes				}
145390267Sdes			} else if (tag && !comment && *q == '>') {
145490267Sdes				p = q + 1;
145590267Sdes				tag = 0;
145690267Sdes			} else if (!tag && *q == '<') {
145790267Sdes				if (q > p)
145890267Sdes					fwrite(p, q - p, 1, out);
145990267Sdes				tag = 1;
146090267Sdes				if (q + 3 < line + len &&
146190267Sdes				    strcmp(q, "<!--") == 0) {
146290267Sdes					comment = 1;
146390267Sdes					q += 3;
146490267Sdes				}
146590267Sdes			}
146688771Sdes		}
146790267Sdes		if (!tag && q > p)
146890267Sdes			fwrite(p, q - p, 1, out);
146990267Sdes		fputc('\n', out);
147088771Sdes	}
147188771Sdes}
147288771Sdes
147390267Sdes
147463012Sdes/*****************************************************************************
147563012Sdes * Core
147660954Sdes */
147760954Sdes
147860954Sdes/*
147963012Sdes * Send a request and process the reply
148097866Sdes *
148197866Sdes * XXX This function is way too long, the do..while loop should be split
148297866Sdes * XXX off into a separate function.
148360376Sdes */
148467043SdesFILE *
1485174588Sdeshttp_request(struct url *URL, const char *op, struct url_stat *us,
1486202613Sdes	struct url *purl, const char *flags)
148760376Sdes{
1488186124Smurray	char timebuf[80];
1489186124Smurray	char hbuf[MAXHOSTNAMELEN + 7], *host;
149097856Sdes	conn_t *conn;
149190267Sdes	struct url *url, *new;
1492202613Sdes	int chunked, direct, ims, noredirect, verbose;
1493143049Skbyanc	int e, i, n, val;
149490267Sdes	off_t offset, clength, length, size;
149590267Sdes	time_t mtime;
149690267Sdes	const char *p;
149790267Sdes	FILE *f;
149890267Sdes	hdr_t h;
1499186124Smurray	struct tm *timestruct;
1500202613Sdes	http_headerbuf_t headerbuf;
1501202613Sdes	http_auth_challenges_t server_challenges;
1502202613Sdes	http_auth_challenges_t proxy_challenges;
150363012Sdes
1504202613Sdes	/* The following calls don't allocate anything */
1505221821Sdes	init_http_headerbuf(&headerbuf);
1506202613Sdes	init_http_auth_challenges(&server_challenges);
1507202613Sdes	init_http_auth_challenges(&proxy_challenges);
1508202613Sdes
150990267Sdes	direct = CHECK_FLAG('d');
151090267Sdes	noredirect = CHECK_FLAG('A');
151190267Sdes	verbose = CHECK_FLAG('v');
1512186124Smurray	ims = CHECK_FLAG('i');
151360737Sume
151490267Sdes	if (direct && purl) {
151590267Sdes		fetchFreeURL(purl);
151690267Sdes		purl = NULL;
151790267Sdes	}
151863716Sdes
151990267Sdes	/* try the provided URL first */
152090267Sdes	url = URL;
152163012Sdes
1522242289Seadler	n = MAX_REDIRECT;
152390267Sdes	i = 0;
152463012Sdes
152598422Sdes	e = HTTP_PROTOCOL_ERROR;
152690267Sdes	do {
152790267Sdes		new = NULL;
152890267Sdes		chunked = 0;
152990267Sdes		offset = 0;
153090267Sdes		clength = -1;
153190267Sdes		length = -1;
153290267Sdes		size = -1;
153390267Sdes		mtime = 0;
153490267Sdes
153590267Sdes		/* check port */
153690267Sdes		if (!url->port)
1537174588Sdes			url->port = fetch_default_port(url->scheme);
153890267Sdes
153990267Sdes		/* were we redirected to an FTP URL? */
154090267Sdes		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
154190267Sdes			if (strcmp(op, "GET") == 0)
1542174588Sdes				return (ftp_request(url, "RETR", us, purl, flags));
154390267Sdes			else if (strcmp(op, "HEAD") == 0)
1544174588Sdes				return (ftp_request(url, "STAT", us, purl, flags));
154590267Sdes		}
154690267Sdes
154790267Sdes		/* connect to server or proxy */
1548174588Sdes		if ((conn = http_connect(url, purl, flags)) == NULL)
154990267Sdes			goto ouch;
155090267Sdes
155190267Sdes		host = url->host;
155260737Sume#ifdef INET6
155390267Sdes		if (strchr(url->host, ':')) {
155490267Sdes			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
155590267Sdes			host = hbuf;
155690267Sdes		}
155760737Sume#endif
1558174588Sdes		if (url->port != fetch_default_port(url->scheme)) {
1559107372Sdes			if (host != hbuf) {
1560107372Sdes				strcpy(hbuf, host);
1561107372Sdes				host = hbuf;
1562107372Sdes			}
1563107372Sdes			snprintf(hbuf + strlen(hbuf),
1564107372Sdes			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1565107372Sdes		}
156637535Sdes
156790267Sdes		/* send request */
156890267Sdes		if (verbose)
1569174588Sdes			fetch_info("requesting %s://%s%s",
1570107372Sdes			    url->scheme, host, url->doc);
157190267Sdes		if (purl) {
1572174588Sdes			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1573107372Sdes			    op, url->scheme, host, url->doc);
157490267Sdes		} else {
1575174588Sdes			http_cmd(conn, "%s %s HTTP/1.1",
157690267Sdes			    op, url->doc);
157790267Sdes		}
157837535Sdes
1579186124Smurray		if (ims && url->ims_time) {
1580186124Smurray			timestruct = gmtime((time_t *)&url->ims_time);
1581186124Smurray			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1582186124Smurray			    timestruct);
1583186124Smurray			if (verbose)
1584186124Smurray				fetch_info("If-Modified-Since: %s", timebuf);
1585186124Smurray			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1586186124Smurray		}
158790267Sdes		/* virtual host */
1588174588Sdes		http_cmd(conn, "Host: %s", host);
158990267Sdes
1590221821Sdes		/*
1591221821Sdes		 * Proxy authorization: we only send auth after we received
1592221821Sdes		 * a 407 error. We do not first try basic anyway (changed
1593221821Sdes		 * when support was added for digest-auth)
1594221821Sdes		 */
1595202613Sdes		if (purl && proxy_challenges.valid) {
1596202613Sdes			http_auth_params_t aparams;
1597202613Sdes			init_http_auth_params(&aparams);
1598202613Sdes			if (*purl->user || *purl->pwd) {
1599221821Sdes				aparams.user = purl->user ?
1600202613Sdes					strdup(purl->user) : strdup("");
1601202613Sdes				aparams.password = purl->pwd?
1602202613Sdes					strdup(purl->pwd) : strdup("");
1603221821Sdes			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1604202613Sdes				   *p != '\0') {
1605202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1606202613Sdes					http_seterr(HTTP_NEED_PROXY_AUTH);
1607202613Sdes					goto ouch;
1608202613Sdes				}
1609202613Sdes			}
1610221821Sdes			http_authorize(conn, "Proxy-Authorization",
1611202613Sdes				       &proxy_challenges, &aparams, url);
1612202613Sdes			clean_http_auth_params(&aparams);
161390267Sdes		}
161490267Sdes
1615221821Sdes		/*
1616221821Sdes		 * Server authorization: we never send "a priori"
1617202613Sdes		 * Basic auth, which used to be done if user/pass were
1618202613Sdes		 * set in the url. This would be weird because we'd send the
1619221821Sdes		 * password in the clear even if Digest is finally to be
1620202613Sdes		 * used (it would have made more sense for the
1621221821Sdes		 * pre-digest version to do this when Basic was specified
1622221821Sdes		 * in the environment)
1623221821Sdes		 */
1624202613Sdes		if (server_challenges.valid) {
1625202613Sdes			http_auth_params_t aparams;
1626202613Sdes			init_http_auth_params(&aparams);
1627202613Sdes			if (*url->user || *url->pwd) {
1628221821Sdes				aparams.user = url->user ?
1629202613Sdes					strdup(url->user) : strdup("");
1630221821Sdes				aparams.password = url->pwd ?
1631202613Sdes					strdup(url->pwd) : strdup("");
1632221821Sdes			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1633202613Sdes				   *p != '\0') {
1634202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1635202613Sdes					http_seterr(HTTP_NEED_AUTH);
1636202613Sdes					goto ouch;
1637202613Sdes				}
1638221821Sdes			} else if (fetchAuthMethod &&
1639202613Sdes				   fetchAuthMethod(url) == 0) {
1640221821Sdes				aparams.user = url->user ?
1641202613Sdes					strdup(url->user) : strdup("");
1642221821Sdes				aparams.password = url->pwd ?
1643202613Sdes					strdup(url->pwd) : strdup("");
164490267Sdes			} else {
1645174588Sdes				http_seterr(HTTP_NEED_AUTH);
164690267Sdes				goto ouch;
164790267Sdes			}
1648221821Sdes			http_authorize(conn, "Authorization",
1649202613Sdes				       &server_challenges, &aparams, url);
1650202613Sdes			clean_http_auth_params(&aparams);
165190267Sdes		}
165290267Sdes
165390267Sdes		/* other headers */
1654107372Sdes		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1655107372Sdes			if (strcasecmp(p, "auto") == 0)
1656174588Sdes				http_cmd(conn, "Referer: %s://%s%s",
1657107372Sdes				    url->scheme, host, url->doc);
1658107372Sdes			else
1659174588Sdes				http_cmd(conn, "Referer: %s", p);
1660107372Sdes		}
166190267Sdes		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1662174588Sdes			http_cmd(conn, "User-Agent: %s", p);
166390267Sdes		else
1664174588Sdes			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1665109693Sdes		if (url->offset > 0)
1666174588Sdes			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1667174588Sdes		http_cmd(conn, "Connection: close");
1668174588Sdes		http_cmd(conn, "");
166990267Sdes
1670143049Skbyanc		/*
1671143049Skbyanc		 * Force the queued request to be dispatched.  Normally, one
1672143049Skbyanc		 * would do this with shutdown(2) but squid proxies can be
1673143049Skbyanc		 * configured to disallow such half-closed connections.  To
1674143049Skbyanc		 * be compatible with such configurations, fiddle with socket
1675143049Skbyanc		 * options to force the pending data to be written.
1676143049Skbyanc		 */
1677143049Skbyanc		val = 0;
1678143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1679143049Skbyanc			   sizeof(val));
1680143049Skbyanc		val = 1;
1681143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1682143049Skbyanc			   sizeof(val));
1683143049Skbyanc
168490267Sdes		/* get reply */
1685174588Sdes		switch (http_get_reply(conn)) {
168690267Sdes		case HTTP_OK:
168790267Sdes		case HTTP_PARTIAL:
1688186124Smurray		case HTTP_NOT_MODIFIED:
168990267Sdes			/* fine */
169090267Sdes			break;
169190267Sdes		case HTTP_MOVED_PERM:
169290267Sdes		case HTTP_MOVED_TEMP:
169390267Sdes		case HTTP_SEE_OTHER:
1694242293Seadler		case HTTP_USE_PROXY:
169590267Sdes			/*
1696125695Sdes			 * Not so fine, but we still have to read the
1697125695Sdes			 * headers to get the new location.
169890267Sdes			 */
169990267Sdes			break;
170090267Sdes		case HTTP_NEED_AUTH:
1701202613Sdes			if (server_challenges.valid) {
170290267Sdes				/*
1703125695Sdes				 * We already sent out authorization code,
1704125695Sdes				 * so there's nothing more we can do.
170590267Sdes				 */
1706174588Sdes				http_seterr(conn->err);
170790267Sdes				goto ouch;
170890267Sdes			}
170990267Sdes			/* try again, but send the password this time */
171090267Sdes			if (verbose)
1711174588Sdes				fetch_info("server requires authorization");
171290267Sdes			break;
171390267Sdes		case HTTP_NEED_PROXY_AUTH:
1714202613Sdes			if (proxy_challenges.valid) {
1715202613Sdes				/*
1716202613Sdes				 * We already sent our proxy
1717202613Sdes				 * authorization code, so there's
1718202613Sdes				 * nothing more we can do. */
1719202613Sdes				http_seterr(conn->err);
1720202613Sdes				goto ouch;
1721202613Sdes			}
1722202613Sdes			/* try again, but send the password this time */
1723202613Sdes			if (verbose)
1724202613Sdes				fetch_info("proxy requires authorization");
1725202613Sdes			break;
1726125696Sdes		case HTTP_BAD_RANGE:
1727125696Sdes			/*
1728125696Sdes			 * This can happen if we ask for 0 bytes because
1729125696Sdes			 * we already have the whole file.  Consider this
1730125696Sdes			 * a success for now, and check sizes later.
1731125696Sdes			 */
1732125696Sdes			break;
173390267Sdes		case HTTP_PROTOCOL_ERROR:
173490267Sdes			/* fall through */
173590267Sdes		case -1:
1736174588Sdes			fetch_syserr();
173790267Sdes			goto ouch;
173890267Sdes		default:
1739174588Sdes			http_seterr(conn->err);
174090267Sdes			if (!verbose)
174190267Sdes				goto ouch;
174290267Sdes			/* fall through so we can get the full error message */
174390267Sdes		}
174490267Sdes
1745202613Sdes		/* get headers. http_next_header expects one line readahead */
1746202613Sdes		if (fetch_getln(conn) == -1) {
1747202613Sdes		    fetch_syserr();
1748202613Sdes		    goto ouch;
1749202613Sdes		}
175090267Sdes		do {
1751202613Sdes		    switch ((h = http_next_header(conn, &headerbuf, &p))) {
175290267Sdes			case hdr_syserror:
1753174588Sdes				fetch_syserr();
175490267Sdes				goto ouch;
175590267Sdes			case hdr_error:
1756174588Sdes				http_seterr(HTTP_PROTOCOL_ERROR);
175790267Sdes				goto ouch;
175890267Sdes			case hdr_content_length:
1759174588Sdes				http_parse_length(p, &clength);
176090267Sdes				break;
176190267Sdes			case hdr_content_range:
1762174588Sdes				http_parse_range(p, &offset, &length, &size);
176390267Sdes				break;
176490267Sdes			case hdr_last_modified:
1765174588Sdes				http_parse_mtime(p, &mtime);
176690267Sdes				break;
176790267Sdes			case hdr_location:
176897856Sdes				if (!HTTP_REDIRECT(conn->err))
176990267Sdes					break;
1770242289Seadler				/*
1771242289Seadler				 * if the A flag is set, we don't follow
1772242289Seadler				 * temporary redirects.
1773242289Seadler				 */
1774242289Seadler				if (noredirect &&
1775242289Seadler				    conn->err != HTTP_MOVED_PERM &&
1776242293Seadler				    conn->err != HTTP_PERM_REDIRECT &&
1777242293Seadler				    conn->err != HTTP_USE_PROXY) {
1778242289Seadler					n = 1;
1779242289Seadler					break;
1780242289Seadler                                }
178190267Sdes				if (new)
178290267Sdes					free(new);
178390267Sdes				if (verbose)
1784174588Sdes					fetch_info("%d redirect to %s", conn->err, p);
178590267Sdes				if (*p == '/')
178690267Sdes					/* absolute path */
178790267Sdes					new = fetchMakeURL(url->scheme, url->host, url->port, p,
178890267Sdes					    url->user, url->pwd);
178990267Sdes				else
179090267Sdes					new = fetchParseURL(p);
179190267Sdes				if (new == NULL) {
179290267Sdes					/* XXX should set an error code */
179390267Sdes					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
179490267Sdes					goto ouch;
179590267Sdes				}
1796236108Sdes
1797236108Sdes				/* Only copy credentials if the host matches */
1798236108Sdes				if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) {
179990267Sdes					strcpy(new->user, url->user);
180090267Sdes					strcpy(new->pwd, url->pwd);
180190267Sdes				}
180290267Sdes				new->offset = url->offset;
180390267Sdes				new->length = url->length;
180490267Sdes				break;
180590267Sdes			case hdr_transfer_encoding:
180690267Sdes				/* XXX weak test*/
180790267Sdes				chunked = (strcasecmp(p, "chunked") == 0);
180890267Sdes				break;
180990267Sdes			case hdr_www_authenticate:
181097856Sdes				if (conn->err != HTTP_NEED_AUTH)
181190267Sdes					break;
1812210563Sdes				if (http_parse_authenticate(p, &server_challenges) == 0)
1813209632Sdes					++n;
181490267Sdes				break;
1815202613Sdes			case hdr_proxy_authenticate:
1816202613Sdes				if (conn->err != HTTP_NEED_PROXY_AUTH)
1817202613Sdes					break;
1818210563Sdes				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1819209632Sdes					++n;
1820202613Sdes				break;
182190267Sdes			case hdr_end:
182290267Sdes				/* fall through */
182390267Sdes			case hdr_unknown:
182490267Sdes				/* ignore */
182590267Sdes				break;
182690267Sdes			}
182790267Sdes		} while (h > hdr_end);
182890267Sdes
182990267Sdes		/* we need to provide authentication */
1830221821Sdes		if (conn->err == HTTP_NEED_AUTH ||
1831202613Sdes		    conn->err == HTTP_NEED_PROXY_AUTH) {
183298422Sdes			e = conn->err;
1833221821Sdes			if ((conn->err == HTTP_NEED_AUTH &&
1834221821Sdes			     !server_challenges.valid) ||
1835221821Sdes			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1836202613Sdes			     !proxy_challenges.valid)) {
1837202613Sdes				/* 401/7 but no www/proxy-authenticate ?? */
1838202613Sdes				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1839202613Sdes				goto ouch;
1840202613Sdes			}
1841174588Sdes			fetch_close(conn);
184297856Sdes			conn = NULL;
184390267Sdes			continue;
184490267Sdes		}
184590267Sdes
1846125696Sdes		/* requested range not satisfiable */
1847125696Sdes		if (conn->err == HTTP_BAD_RANGE) {
1848125696Sdes			if (url->offset == size && url->length == 0) {
1849125696Sdes				/* asked for 0 bytes; fake it */
1850125696Sdes				offset = url->offset;
1851184222Sru				clength = -1;
1852125696Sdes				conn->err = HTTP_OK;
1853125696Sdes				break;
1854125696Sdes			} else {
1855174588Sdes				http_seterr(conn->err);
1856125696Sdes				goto ouch;
1857125696Sdes			}
1858125696Sdes		}
1859125696Sdes
1860104404Sru		/* we have a hit or an error */
1861186124Smurray		if (conn->err == HTTP_OK
1862186124Smurray		    || conn->err == HTTP_NOT_MODIFIED
1863186124Smurray		    || conn->err == HTTP_PARTIAL
1864186124Smurray		    || HTTP_ERROR(conn->err))
1865104404Sru			break;
1866104404Sru
186790267Sdes		/* all other cases: we got a redirect */
186898422Sdes		e = conn->err;
1869202613Sdes		clean_http_auth_challenges(&server_challenges);
1870174588Sdes		fetch_close(conn);
187197856Sdes		conn = NULL;
187290267Sdes		if (!new) {
187390267Sdes			DEBUG(fprintf(stderr, "redirect with no new location\n"));
187490267Sdes			break;
187590267Sdes		}
187690267Sdes		if (url != URL)
187790267Sdes			fetchFreeURL(url);
187890267Sdes		url = new;
187990267Sdes	} while (++i < n);
188090267Sdes
188190267Sdes	/* we failed, or ran out of retries */
188297856Sdes	if (conn == NULL) {
1883174588Sdes		http_seterr(e);
188463012Sdes		goto ouch;
188563012Sdes	}
188660376Sdes
188790267Sdes	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
188890267Sdes		  " size %lld, clength %lld\n",
188990267Sdes		  (long long)offset, (long long)length,
189090267Sdes		  (long long)size, (long long)clength));
189160376Sdes
1892186124Smurray	if (conn->err == HTTP_NOT_MODIFIED) {
1893186124Smurray		http_seterr(HTTP_NOT_MODIFIED);
1894186124Smurray		return (NULL);
1895186124Smurray	}
1896186124Smurray
189790267Sdes	/* check for inconsistencies */
189890267Sdes	if (clength != -1 && length != -1 && clength != length) {
1899174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
190063012Sdes		goto ouch;
190163012Sdes	}
190290267Sdes	if (clength == -1)
190390267Sdes		clength = length;
190490267Sdes	if (clength != -1)
190590267Sdes		length = offset + clength;
190690267Sdes	if (length != -1 && size != -1 && length != size) {
1907174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
190863012Sdes		goto ouch;
190990267Sdes	}
191090267Sdes	if (size == -1)
191190267Sdes		size = length;
191260376Sdes
191390267Sdes	/* fill in stats */
191490267Sdes	if (us) {
191590267Sdes		us->size = size;
191690267Sdes		us->atime = us->mtime = mtime;
191790267Sdes	}
191863069Sdes
191990267Sdes	/* too far? */
1920109693Sdes	if (URL->offset > 0 && offset > URL->offset) {
1921174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
192290267Sdes		goto ouch;
192377238Sdes	}
192460376Sdes
192590267Sdes	/* report back real offset and size */
192690267Sdes	URL->offset = offset;
192790267Sdes	URL->length = clength;
192837535Sdes
192990267Sdes	/* wrap it up in a FILE */
1930174588Sdes	if ((f = http_funopen(conn, chunked)) == NULL) {
1931174588Sdes		fetch_syserr();
193290267Sdes		goto ouch;
193390267Sdes	}
193463716Sdes
193590267Sdes	if (url != URL)
193690267Sdes		fetchFreeURL(url);
193790267Sdes	if (purl)
193890267Sdes		fetchFreeURL(purl);
193963567Sdes
194097856Sdes	if (HTTP_ERROR(conn->err)) {
1941174588Sdes		http_print_html(stderr, f);
194290267Sdes		fclose(f);
194390267Sdes		f = NULL;
194490267Sdes	}
1945202613Sdes	clean_http_headerbuf(&headerbuf);
1946202613Sdes	clean_http_auth_challenges(&server_challenges);
1947202613Sdes	clean_http_auth_challenges(&proxy_challenges);
194890267Sdes	return (f);
194988771Sdes
195090267Sdesouch:
195190267Sdes	if (url != URL)
195290267Sdes		fetchFreeURL(url);
195390267Sdes	if (purl)
195490267Sdes		fetchFreeURL(purl);
195597856Sdes	if (conn != NULL)
1956174588Sdes		fetch_close(conn);
1957202613Sdes	clean_http_headerbuf(&headerbuf);
1958202613Sdes	clean_http_auth_challenges(&server_challenges);
1959202613Sdes	clean_http_auth_challenges(&proxy_challenges);
196090267Sdes	return (NULL);
196163012Sdes}
196260189Sdes
196390267Sdes
196463012Sdes/*****************************************************************************
196563012Sdes * Entry points
196663012Sdes */
196763012Sdes
196863012Sdes/*
196963340Sdes * Retrieve and stat a file by HTTP
197063340Sdes */
197163340SdesFILE *
197275891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
197363340Sdes{
1974174752Sdes	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
197563340Sdes}
197663340Sdes
197763340Sdes/*
197863012Sdes * Retrieve a file by HTTP
197963012Sdes */
198063012SdesFILE *
198175891SarchiefetchGetHTTP(struct url *URL, const char *flags)
198263012Sdes{
198390267Sdes	return (fetchXGetHTTP(URL, NULL, flags));
198437535Sdes}
198537535Sdes
198663340Sdes/*
198763340Sdes * Store a file by HTTP
198863340Sdes */
198937535SdesFILE *
199085093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused)
199137535Sdes{
199290267Sdes	warnx("fetchPutHTTP(): not implemented");
199390267Sdes	return (NULL);
199437535Sdes}
199540975Sdes
199640975Sdes/*
199740975Sdes * Get an HTTP document's metadata
199840975Sdes */
199940975Sdesint
200075891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
200140975Sdes{
200290267Sdes	FILE *f;
200390267Sdes
2004174752Sdes	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2005112081Sdes	if (f == NULL)
200690267Sdes		return (-1);
200790267Sdes	fclose(f);
200890267Sdes	return (0);
200940975Sdes}
201041989Sdes
201141989Sdes/*
201241989Sdes * List a directory
201341989Sdes */
201441989Sdesstruct url_ent *
201585093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused)
201641989Sdes{
201790267Sdes	warnx("fetchListHTTP(): not implemented");
201890267Sdes	return (NULL);
201941989Sdes}
2020