http.c revision 243149
137535Sdes/*-
2226537Sdes * 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: head/lib/libfetch/http.c 243149 2012-11-16 12:31:43Z des $");
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>
79240496Sdes
80240496Sdes#ifdef WITH_SSL
81240496Sdes#include <openssl/md5.h>
82240496Sdes#define MD5Init(c) MD5_Init(c)
83240496Sdes#define MD5Update(c, data, len) MD5_Update(c, data, len)
84240496Sdes#define MD5Final(md, c) MD5_Final(md, c)
85240496Sdes#else
86202613Sdes#include <md5.h>
87240496Sdes#endif
8837535Sdes
89141958Skbyanc#include <netinet/in.h>
90141958Skbyanc#include <netinet/tcp.h>
91141958Skbyanc
9237535Sdes#include "fetch.h"
9340939Sdes#include "common.h"
9441862Sdes#include "httperr.h"
9537535Sdes
9663012Sdes/* Maximum number of redirects to follow */
97241839Seadler#define MAX_REDIRECT 20
9837535Sdes
9963012Sdes/* Symbolic names for reply codes we care about */
10063012Sdes#define HTTP_OK			200
10163012Sdes#define HTTP_PARTIAL		206
10263012Sdes#define HTTP_MOVED_PERM		301
10363012Sdes#define HTTP_MOVED_TEMP		302
10463012Sdes#define HTTP_SEE_OTHER		303
105186124Smurray#define HTTP_NOT_MODIFIED	304
106241841Seadler#define HTTP_USE_PROXY		305
107169386Sdes#define HTTP_TEMP_REDIRECT	307
108241840Seadler#define HTTP_PERM_REDIRECT	308
10963012Sdes#define HTTP_NEED_AUTH		401
11087317Sdes#define HTTP_NEED_PROXY_AUTH	407
111125696Sdes#define HTTP_BAD_RANGE		416
11263012Sdes#define HTTP_PROTOCOL_ERROR	999
11360196Sdes
11463012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
11590267Sdes			    || (xyz) == HTTP_MOVED_TEMP \
116169386Sdes			    || (xyz) == HTTP_TEMP_REDIRECT \
117241841Seadler			    || (xyz) == HTTP_USE_PROXY \
11890267Sdes			    || (xyz) == HTTP_SEE_OTHER)
11963012Sdes
12088771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
12163012Sdes
12290267Sdes
12363012Sdes/*****************************************************************************
12463012Sdes * I/O functions for decoding chunked streams
12563012Sdes */
12663012Sdes
12797859Sdesstruct httpio
12837535Sdes{
12997858Sdes	conn_t		*conn;		/* connection */
13097866Sdes	int		 chunked;	/* chunked mode */
13197858Sdes	char		*buf;		/* chunk buffer */
13297866Sdes	size_t		 bufsize;	/* size of chunk buffer */
13397866Sdes	ssize_t		 buflen;	/* amount of data currently in buffer */
13497866Sdes	int		 bufpos;	/* current read offset in buffer */
13597858Sdes	int		 eof;		/* end-of-file flag */
13697858Sdes	int		 error;		/* error flag */
13797858Sdes	size_t		 chunksize;	/* remaining size of current chunk */
13863281Sdes#ifndef NDEBUG
13990267Sdes	size_t		 total;
14063012Sdes#endif
14137535Sdes};
14237535Sdes
14337608Sdes/*
14463012Sdes * Get next chunk header
14537608Sdes */
14637608Sdesstatic int
147174588Sdeshttp_new_chunk(struct httpio *io)
14837608Sdes{
14990267Sdes	char *p;
15090267Sdes
151174588Sdes	if (fetch_getln(io->conn) == -1)
15290267Sdes		return (-1);
15390267Sdes
154174761Sdes	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
15590267Sdes		return (-1);
15690267Sdes
157174761Sdes	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
15890267Sdes		if (*p == ';')
15990267Sdes			break;
160174761Sdes		if (!isxdigit((unsigned char)*p))
16190267Sdes			return (-1);
162174761Sdes		if (isdigit((unsigned char)*p)) {
16397859Sdes			io->chunksize = io->chunksize * 16 +
16490267Sdes			    *p - '0';
16590267Sdes		} else {
16697859Sdes			io->chunksize = io->chunksize * 16 +
167176036Sdes			    10 + tolower((unsigned char)*p) - 'a';
16890267Sdes		}
16990267Sdes	}
17090267Sdes
17163281Sdes#ifndef NDEBUG
17290267Sdes	if (fetchDebug) {
17397859Sdes		io->total += io->chunksize;
17497859Sdes		if (io->chunksize == 0)
175106207Sdes			fprintf(stderr, "%s(): end of last chunk\n", __func__);
17690267Sdes		else
177106207Sdes			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
178106207Sdes			    __func__, (unsigned long)io->chunksize,
179106207Sdes			    (unsigned long)io->total);
18090267Sdes	}
18163012Sdes#endif
18290267Sdes
18397859Sdes	return (io->chunksize);
18437608Sdes}
18537608Sdes
18637608Sdes/*
18797866Sdes * Grow the input buffer to at least len bytes
18897866Sdes */
18997866Sdesstatic inline int
190174588Sdeshttp_growbuf(struct httpio *io, size_t len)
19197866Sdes{
19297866Sdes	char *tmp;
19397866Sdes
19497866Sdes	if (io->bufsize >= len)
19597866Sdes		return (0);
19697866Sdes
19797866Sdes	if ((tmp = realloc(io->buf, len)) == NULL)
19897866Sdes		return (-1);
19997866Sdes	io->buf = tmp;
20097866Sdes	io->bufsize = len;
201106044Sdes	return (0);
20297866Sdes}
20397866Sdes
20497866Sdes/*
20537608Sdes * Fill the input buffer, do chunk decoding on the fly
20637608Sdes */
20763012Sdesstatic int
208174588Sdeshttp_fillbuf(struct httpio *io, size_t len)
20937535Sdes{
210230307Sdes	ssize_t nbytes;
211230307Sdes
21297859Sdes	if (io->error)
21390267Sdes		return (-1);
21497859Sdes	if (io->eof)
21590267Sdes		return (0);
21690267Sdes
21797866Sdes	if (io->chunked == 0) {
218174588Sdes		if (http_growbuf(io, len) == -1)
21997866Sdes			return (-1);
220230307Sdes		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
221230307Sdes			io->error = errno;
22297866Sdes			return (-1);
223106185Sdes		}
224230307Sdes		io->buflen = nbytes;
22597866Sdes		io->bufpos = 0;
22697866Sdes		return (io->buflen);
22797866Sdes	}
22897866Sdes
22997859Sdes	if (io->chunksize == 0) {
230174588Sdes		switch (http_new_chunk(io)) {
23190267Sdes		case -1:
23297859Sdes			io->error = 1;
23390267Sdes			return (-1);
23490267Sdes		case 0:
23597859Sdes			io->eof = 1;
23690267Sdes			return (0);
23790267Sdes		}
23837535Sdes	}
23963012Sdes
24097866Sdes	if (len > io->chunksize)
24197866Sdes		len = io->chunksize;
242174588Sdes	if (http_growbuf(io, len) == -1)
24390267Sdes		return (-1);
244230307Sdes	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
245230307Sdes		io->error = errno;
24697866Sdes		return (-1);
247106185Sdes	}
248230307Sdes	io->buflen = nbytes;
24997866Sdes	io->chunksize -= io->buflen;
25090267Sdes
25197859Sdes	if (io->chunksize == 0) {
25297856Sdes		char endl[2];
25397856Sdes
254174588Sdes		if (fetch_read(io->conn, endl, 2) != 2 ||
25597856Sdes		    endl[0] != '\r' || endl[1] != '\n')
25690267Sdes			return (-1);
25790267Sdes	}
25890267Sdes
25997866Sdes	io->bufpos = 0;
26090267Sdes
26197866Sdes	return (io->buflen);
26237535Sdes}
26337535Sdes
26437608Sdes/*
26537608Sdes * Read function
26637608Sdes */
26737535Sdesstatic int
268174588Sdeshttp_readfn(void *v, char *buf, int len)
26937535Sdes{
27097859Sdes	struct httpio *io = (struct httpio *)v;
27190267Sdes	int l, pos;
27263012Sdes
27397859Sdes	if (io->error)
27490267Sdes		return (-1);
27597859Sdes	if (io->eof)
27690267Sdes		return (0);
27763012Sdes
27890267Sdes	for (pos = 0; len > 0; pos += l, len -= l) {
27990267Sdes		/* empty buffer */
28097866Sdes		if (!io->buf || io->bufpos == io->buflen)
281174588Sdes			if (http_fillbuf(io, len) < 1)
28290267Sdes				break;
28397866Sdes		l = io->buflen - io->bufpos;
28490267Sdes		if (len < l)
28590267Sdes			l = len;
286176105Sdes		memcpy(buf + pos, io->buf + io->bufpos, l);
28797866Sdes		io->bufpos += l;
28890267Sdes	}
28937535Sdes
290230307Sdes	if (!pos && io->error) {
291230307Sdes		if (io->error == EINTR)
292230307Sdes			io->error = 0;
29390267Sdes		return (-1);
294230307Sdes	}
29590267Sdes	return (pos);
29637535Sdes}
29737535Sdes
29837608Sdes/*
29937608Sdes * Write function
30037608Sdes */
30137535Sdesstatic int
302174588Sdeshttp_writefn(void *v, const char *buf, int len)
30337535Sdes{
30497859Sdes	struct httpio *io = (struct httpio *)v;
30590267Sdes
306174588Sdes	return (fetch_write(io->conn, buf, len));
30737535Sdes}
30837535Sdes
30937608Sdes/*
31037608Sdes * Close function
31137608Sdes */
31237535Sdesstatic int
313174588Sdeshttp_closefn(void *v)
31437535Sdes{
31597859Sdes	struct httpio *io = (struct httpio *)v;
31690267Sdes	int r;
31763012Sdes
318174588Sdes	r = fetch_close(io->conn);
31997859Sdes	if (io->buf)
32097859Sdes		free(io->buf);
32197859Sdes	free(io);
32290267Sdes	return (r);
32337535Sdes}
32437535Sdes
32537608Sdes/*
32663012Sdes * Wrap a file descriptor up
32737608Sdes */
32863012Sdesstatic FILE *
329174588Sdeshttp_funopen(conn_t *conn, int chunked)
33037535Sdes{
33197859Sdes	struct httpio *io;
33290267Sdes	FILE *f;
33363012Sdes
334109967Sdes	if ((io = calloc(1, sizeof(*io))) == NULL) {
335174588Sdes		fetch_syserr();
33690267Sdes		return (NULL);
33790267Sdes	}
33897859Sdes	io->conn = conn;
33997866Sdes	io->chunked = chunked;
340174588Sdes	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
34190267Sdes	if (f == NULL) {
342174588Sdes		fetch_syserr();
34397859Sdes		free(io);
34490267Sdes		return (NULL);
34590267Sdes	}
34690267Sdes	return (f);
34763012Sdes}
34863012Sdes
34990267Sdes
35063012Sdes/*****************************************************************************
35163012Sdes * Helper functions for talking to the server and parsing its replies
35263012Sdes */
35363012Sdes
35463012Sdes/* Header types */
35563012Sdestypedef enum {
35690267Sdes	hdr_syserror = -2,
35790267Sdes	hdr_error = -1,
35890267Sdes	hdr_end = 0,
35990267Sdes	hdr_unknown = 1,
36090267Sdes	hdr_content_length,
36190267Sdes	hdr_content_range,
36290267Sdes	hdr_last_modified,
36390267Sdes	hdr_location,
36490267Sdes	hdr_transfer_encoding,
365202613Sdes	hdr_www_authenticate,
366202613Sdes	hdr_proxy_authenticate,
36785093Sdes} hdr_t;
36863012Sdes
36963012Sdes/* Names of interesting headers */
37063012Sdesstatic struct {
37190267Sdes	hdr_t		 num;
37290267Sdes	const char	*name;
37363012Sdes} hdr_names[] = {
37490267Sdes	{ hdr_content_length,		"Content-Length" },
37590267Sdes	{ hdr_content_range,		"Content-Range" },
37690267Sdes	{ hdr_last_modified,		"Last-Modified" },
37790267Sdes	{ hdr_location,			"Location" },
37890267Sdes	{ hdr_transfer_encoding,	"Transfer-Encoding" },
37990267Sdes	{ hdr_www_authenticate,		"WWW-Authenticate" },
380202613Sdes	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
38190267Sdes	{ hdr_unknown,			NULL },
38263012Sdes};
38363012Sdes
38463012Sdes/*
38563012Sdes * Send a formatted line; optionally echo to terminal
38663012Sdes */
38763012Sdesstatic int
388174588Sdeshttp_cmd(conn_t *conn, const char *fmt, ...)
38963012Sdes{
39090267Sdes	va_list ap;
39190267Sdes	size_t len;
39290267Sdes	char *msg;
39390267Sdes	int r;
39463012Sdes
39590267Sdes	va_start(ap, fmt);
39690267Sdes	len = vasprintf(&msg, fmt, ap);
39790267Sdes	va_end(ap);
39890267Sdes
39990267Sdes	if (msg == NULL) {
40090267Sdes		errno = ENOMEM;
401174588Sdes		fetch_syserr();
40290267Sdes		return (-1);
40390267Sdes	}
40490267Sdes
405174588Sdes	r = fetch_putln(conn, msg, len);
40690267Sdes	free(msg);
40790267Sdes
40890267Sdes	if (r == -1) {
409174588Sdes		fetch_syserr();
41090267Sdes		return (-1);
41190267Sdes	}
41290267Sdes
41390267Sdes	return (0);
41463012Sdes}
41563012Sdes
41663012Sdes/*
41763012Sdes * Get and parse status line
41863012Sdes */
41963012Sdesstatic int
420174588Sdeshttp_get_reply(conn_t *conn)
42163012Sdes{
42290267Sdes	char *p;
42390267Sdes
424174588Sdes	if (fetch_getln(conn) == -1)
42590267Sdes		return (-1);
42690267Sdes	/*
42790267Sdes	 * A valid status line looks like "HTTP/m.n xyz reason" where m
42890267Sdes	 * and n are the major and minor protocol version numbers and xyz
42990267Sdes	 * is the reply code.
43090267Sdes	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
43190267Sdes	 * just one) that do not send a version number, so we can't rely
43290267Sdes	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
43390267Sdes	 * We don't care about the reason phrase.
43490267Sdes	 */
43597856Sdes	if (strncmp(conn->buf, "HTTP", 4) != 0)
43690267Sdes		return (HTTP_PROTOCOL_ERROR);
43797856Sdes	p = conn->buf + 4;
43890267Sdes	if (*p == '/') {
43990267Sdes		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
44090267Sdes			return (HTTP_PROTOCOL_ERROR);
44190267Sdes		p += 4;
44290267Sdes	}
443174761Sdes	if (*p != ' ' ||
444174761Sdes	    !isdigit((unsigned char)p[1]) ||
445174761Sdes	    !isdigit((unsigned char)p[2]) ||
446174761Sdes	    !isdigit((unsigned char)p[3]))
44790267Sdes		return (HTTP_PROTOCOL_ERROR);
44890267Sdes
44997856Sdes	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
45097856Sdes	return (conn->err);
45137535Sdes}
45237535Sdes
45337608Sdes/*
45490267Sdes * Check a header; if the type matches the given string, return a pointer
45590267Sdes * to the beginning of the value.
45663012Sdes */
45775891Sarchiestatic const char *
458174588Sdeshttp_match(const char *str, const char *hdr)
45963012Sdes{
460176036Sdes	while (*str && *hdr &&
461176036Sdes	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
46290267Sdes		/* nothing */;
46390267Sdes	if (*str || *hdr != ':')
46490267Sdes		return (NULL);
465174761Sdes	while (*hdr && isspace((unsigned char)*++hdr))
46690267Sdes		/* nothing */;
46790267Sdes	return (hdr);
46863012Sdes}
46963012Sdes
470202613Sdes
47163012Sdes/*
472202613Sdes * Get the next header and return the appropriate symbolic code.  We
473202613Sdes * need to read one line ahead for checking for a continuation line
474202613Sdes * belonging to the current header (continuation lines start with
475221821Sdes * white space).
476202613Sdes *
477202613Sdes * We get called with a fresh line already in the conn buffer, either
478202613Sdes * from the previous http_next_header() invocation, or, the first
479202613Sdes * time, from a fetch_getln() performed by our caller.
480202613Sdes *
481202613Sdes * This stops when we encounter an empty line (we dont read beyond the header
482202613Sdes * area).
483221821Sdes *
484202613Sdes * Note that the "headerbuf" is just a place to return the result. Its
485202613Sdes * contents are not used for the next call. This means that no cleanup
486202613Sdes * is needed when ie doing another connection, just call the cleanup when
487202613Sdes * fully done to deallocate memory.
48863012Sdes */
489202613Sdes
490202613Sdes/* Limit the max number of continuation lines to some reasonable value */
491202613Sdes#define HTTP_MAX_CONT_LINES 10
492202613Sdes
493202613Sdes/* Place into which to build a header from one or several lines */
494202613Sdestypedef struct {
495202613Sdes	char	*buf;		/* buffer */
496202613Sdes	size_t	 bufsize;	/* buffer size */
497202613Sdes	size_t	 buflen;	/* length of buffer contents */
498202613Sdes} http_headerbuf_t;
499202613Sdes
500202613Sdesstatic void
501202613Sdesinit_http_headerbuf(http_headerbuf_t *buf)
50263012Sdes{
503202613Sdes	buf->buf = NULL;
504202613Sdes	buf->bufsize = 0;
505202613Sdes	buf->buflen = 0;
506202613Sdes}
50790267Sdes
508221821Sdesstatic void
509202613Sdesclean_http_headerbuf(http_headerbuf_t *buf)
510202613Sdes{
511202613Sdes	if (buf->buf)
512202613Sdes		free(buf->buf);
513202613Sdes	init_http_headerbuf(buf);
514202613Sdes}
515202613Sdes
516202613Sdes/* Remove whitespace at the end of the buffer */
517221821Sdesstatic void
518202613Sdeshttp_conn_trimright(conn_t *conn)
519202613Sdes{
520221821Sdes	while (conn->buflen &&
521202613Sdes	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
52297856Sdes		conn->buflen--;
52397856Sdes	conn->buf[conn->buflen] = '\0';
524202613Sdes}
525202613Sdes
526202613Sdesstatic hdr_t
527202613Sdeshttp_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
528202613Sdes{
529221820Sdes	unsigned int i, len;
530202613Sdes
531221821Sdes	/*
532202613Sdes	 * Have to do the stripping here because of the first line. So
533221821Sdes	 * it's done twice for the subsequent lines. No big deal
534202613Sdes	 */
535202613Sdes	http_conn_trimright(conn);
53697856Sdes	if (conn->buflen == 0)
53797856Sdes		return (hdr_end);
538202613Sdes
539202613Sdes	/* Copy the line to the headerbuf */
540202613Sdes	if (hbuf->bufsize < conn->buflen + 1) {
541202613Sdes		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
542202613Sdes			return (hdr_syserror);
543202613Sdes		hbuf->bufsize = conn->buflen + 1;
544202613Sdes	}
545202613Sdes	strcpy(hbuf->buf, conn->buf);
546202613Sdes	hbuf->buflen = conn->buflen;
547202613Sdes
548221821Sdes	/*
549202613Sdes	 * Fetch possible continuation lines. Stop at 1st non-continuation
550221821Sdes	 * and leave it in the conn buffer
551221821Sdes	 */
552202613Sdes	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
553202613Sdes		if (fetch_getln(conn) == -1)
554202613Sdes			return (hdr_syserror);
555202613Sdes
556221821Sdes		/*
557202613Sdes		 * Note: we carry on the idea from the previous version
558202613Sdes		 * that a pure whitespace line is equivalent to an empty
559202613Sdes		 * one (so it's not continuation and will be handled when
560221821Sdes		 * we are called next)
561202613Sdes		 */
562202613Sdes		http_conn_trimright(conn);
563202613Sdes		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
564202613Sdes			break;
565202613Sdes
566202613Sdes		/* Got a continuation line. Concatenate to previous */
567202613Sdes		len = hbuf->buflen + conn->buflen;
568202613Sdes		if (hbuf->bufsize < len + 1) {
569202613Sdes			len *= 2;
570202613Sdes			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
571202613Sdes				return (hdr_syserror);
572202613Sdes			hbuf->bufsize = len + 1;
573202613Sdes		}
574202613Sdes		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
575202613Sdes		hbuf->buflen += conn->buflen;
576221821Sdes	}
577202613Sdes
57890267Sdes	/*
57990267Sdes	 * We could check for malformed headers but we don't really care.
58090267Sdes	 * A valid header starts with a token immediately followed by a
58190267Sdes	 * colon; a token is any sequence of non-control, non-whitespace
58290267Sdes	 * characters except "()<>@,;:\\\"{}".
58390267Sdes	 */
58490267Sdes	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
585202613Sdes		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
58690267Sdes			return (hdr_names[i].num);
587202613Sdes
58890267Sdes	return (hdr_unknown);
58963012Sdes}
59063012Sdes
591202613Sdes/**************************
592202613Sdes * [Proxy-]Authenticate header parsing
593202613Sdes */
594202613Sdes
595221821Sdes/*
596221821Sdes * Read doublequote-delimited string into output buffer obuf (allocated
597202613Sdes * by caller, whose responsibility it is to ensure that it's big enough)
598202613Sdes * cp points to the first char after the initial '"'
599221821Sdes * Handles \ quoting
600221821Sdes * Returns pointer to the first char after the terminating double quote, or
601202613Sdes * NULL for error.
602202613Sdes */
603202613Sdesstatic const char *
604202613Sdeshttp_parse_headerstring(const char *cp, char *obuf)
605202613Sdes{
606202613Sdes	for (;;) {
607202613Sdes		switch (*cp) {
608202613Sdes		case 0: /* Unterminated string */
609202613Sdes			*obuf = 0;
610202613Sdes			return (NULL);
611202613Sdes		case '"': /* Ending quote */
612202613Sdes			*obuf = 0;
613202613Sdes			return (++cp);
614202613Sdes		case '\\':
615202613Sdes			if (*++cp == 0) {
616202613Sdes				*obuf = 0;
617202613Sdes				return (NULL);
618202613Sdes			}
619202613Sdes			/* FALLTHROUGH */
620202613Sdes		default:
621202613Sdes			*obuf++ = *cp++;
622202613Sdes		}
623202613Sdes	}
624202613Sdes}
625202613Sdes
626202613Sdes/* Http auth challenge schemes */
627202613Sdestypedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
628202613Sdes
629202613Sdes/* Data holder for a Basic or Digest challenge. */
630202613Sdestypedef struct {
631202613Sdes	http_auth_schemes_t scheme;
632202613Sdes	char	*realm;
633202613Sdes	char	*qop;
634202613Sdes	char	*nonce;
635202613Sdes	char	*opaque;
636202613Sdes	char	*algo;
637202613Sdes	int	 stale;
638202613Sdes	int	 nc; /* Nonce count */
639202613Sdes} http_auth_challenge_t;
640202613Sdes
641221821Sdesstatic void
642202613Sdesinit_http_auth_challenge(http_auth_challenge_t *b)
643202613Sdes{
644202613Sdes	b->scheme = HTTPAS_UNKNOWN;
645202613Sdes	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
646202613Sdes	b->stale = b->nc = 0;
647202613Sdes}
648202613Sdes
649221821Sdesstatic void
650202613Sdesclean_http_auth_challenge(http_auth_challenge_t *b)
651202613Sdes{
652221821Sdes	if (b->realm)
653202613Sdes		free(b->realm);
654221821Sdes	if (b->qop)
655202613Sdes		free(b->qop);
656221821Sdes	if (b->nonce)
657202613Sdes		free(b->nonce);
658221821Sdes	if (b->opaque)
659202613Sdes		free(b->opaque);
660221821Sdes	if (b->algo)
661202613Sdes		free(b->algo);
662202613Sdes	init_http_auth_challenge(b);
663202613Sdes}
664202613Sdes
665202613Sdes/* Data holder for an array of challenges offered in an http response. */
666202613Sdes#define MAX_CHALLENGES 10
667202613Sdestypedef struct {
668202613Sdes	http_auth_challenge_t *challenges[MAX_CHALLENGES];
669202613Sdes	int	count; /* Number of parsed challenges in the array */
670202613Sdes	int	valid; /* We did parse an authenticate header */
671202613Sdes} http_auth_challenges_t;
672202613Sdes
673221821Sdesstatic void
674202613Sdesinit_http_auth_challenges(http_auth_challenges_t *cs)
675202613Sdes{
676202613Sdes	int i;
677202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++)
678202613Sdes		cs->challenges[i] = NULL;
679202613Sdes	cs->count = cs->valid = 0;
680202613Sdes}
681202613Sdes
682221821Sdesstatic void
683202613Sdesclean_http_auth_challenges(http_auth_challenges_t *cs)
684202613Sdes{
685202613Sdes	int i;
686202613Sdes	/* We rely on non-zero pointers being allocated, not on the count */
687202613Sdes	for (i = 0; i < MAX_CHALLENGES; i++) {
688202613Sdes		if (cs->challenges[i] != NULL) {
689202613Sdes			clean_http_auth_challenge(cs->challenges[i]);
690202613Sdes			free(cs->challenges[i]);
691202613Sdes		}
692202613Sdes	}
693202613Sdes	init_http_auth_challenges(cs);
694202613Sdes}
695202613Sdes
696221821Sdes/*
697202613Sdes * Enumeration for lexical elements. Separators will be returned as their own
698202613Sdes * ascii value
699202613Sdes */
700202613Sdestypedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
701202613Sdes	      HTTPHL_ERROR = 259} http_header_lex_t;
702202613Sdes
703221821Sdes/*
704202613Sdes * Determine what kind of token comes next and return possible value
705202613Sdes * in buf, which is supposed to have been allocated big enough by
706221821Sdes * caller. Advance input pointer and return element type.
707202613Sdes */
708221821Sdesstatic int
709202613Sdeshttp_header_lex(const char **cpp, char *buf)
710202613Sdes{
711202613Sdes	size_t l;
712202613Sdes	/* Eat initial whitespace */
713202613Sdes	*cpp += strspn(*cpp, " \t");
714202613Sdes	if (**cpp == 0)
715202613Sdes		return (HTTPHL_END);
716202613Sdes
717202613Sdes	/* Separator ? */
718202613Sdes	if (**cpp == ',' || **cpp == '=')
719202613Sdes		return (*((*cpp)++));
720202613Sdes
721202613Sdes	/* String ? */
722202613Sdes	if (**cpp == '"') {
723202613Sdes		*cpp = http_parse_headerstring(++*cpp, buf);
724202613Sdes		if (*cpp == NULL)
725202613Sdes			return (HTTPHL_ERROR);
726202613Sdes		return (HTTPHL_STRING);
727202613Sdes	}
728202613Sdes
729202613Sdes	/* Read other token, until separator or whitespace */
730202613Sdes	l = strcspn(*cpp, " \t,=");
731202613Sdes	memcpy(buf, *cpp, l);
732202613Sdes	buf[l] = 0;
733202613Sdes	*cpp += l;
734202613Sdes	return (HTTPHL_WORD);
735202613Sdes}
736202613Sdes
737221821Sdes/*
738202613Sdes * Read challenges from http xxx-authenticate header and accumulate them
739202613Sdes * in the challenges list structure.
740202613Sdes *
741202613Sdes * Headers with multiple challenges are specified by rfc2617, but
742202613Sdes * servers (ie: squid) often send them in separate headers instead,
743202613Sdes * which in turn is forbidden by the http spec (multiple headers with
744202613Sdes * the same name are only allowed for pure comma-separated lists, see
745202613Sdes * rfc2616 sec 4.2).
746202613Sdes *
747202613Sdes * We support both approaches anyway
748202613Sdes */
749221821Sdesstatic int
750202613Sdeshttp_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
751202613Sdes{
752202613Sdes	int ret = -1;
753202613Sdes	http_header_lex_t lex;
754202613Sdes	char *key = malloc(strlen(cp) + 1);
755202613Sdes	char *value = malloc(strlen(cp) + 1);
756202613Sdes	char *buf = malloc(strlen(cp) + 1);
757202613Sdes
758202613Sdes	if (key == NULL || value == NULL || buf == NULL) {
759202613Sdes		fetch_syserr();
760202613Sdes		goto out;
761202613Sdes	}
762202613Sdes
763202613Sdes	/* In any case we've seen the header and we set the valid bit */
764202613Sdes	cs->valid = 1;
765202613Sdes
766202613Sdes	/* Need word first */
767202613Sdes	lex = http_header_lex(&cp, key);
768202613Sdes	if (lex != HTTPHL_WORD)
769202613Sdes		goto out;
770202613Sdes
771202613Sdes	/* Loop on challenges */
772202613Sdes	for (; cs->count < MAX_CHALLENGES; cs->count++) {
773221821Sdes		cs->challenges[cs->count] =
774202613Sdes			malloc(sizeof(http_auth_challenge_t));
775202613Sdes		if (cs->challenges[cs->count] == NULL) {
776202613Sdes			fetch_syserr();
777202613Sdes			goto out;
778202613Sdes		}
779202613Sdes		init_http_auth_challenge(cs->challenges[cs->count]);
780202613Sdes		if (!strcasecmp(key, "basic")) {
781202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
782202613Sdes		} else if (!strcasecmp(key, "digest")) {
783202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
784202613Sdes		} else {
785202613Sdes			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
786221821Sdes			/*
787221821Sdes			 * Continue parsing as basic or digest may
788202613Sdes			 * follow, and the syntax is the same for
789202613Sdes			 * all. We'll just ignore this one when
790202613Sdes			 * looking at the list
791202613Sdes			 */
792202613Sdes		}
793221821Sdes
794202613Sdes		/* Loop on attributes */
795202613Sdes		for (;;) {
796202613Sdes			/* Key */
797202613Sdes			lex = http_header_lex(&cp, key);
798202613Sdes			if (lex != HTTPHL_WORD)
799202613Sdes				goto out;
800202613Sdes
801202613Sdes			/* Equal sign */
802202613Sdes			lex = http_header_lex(&cp, buf);
803202613Sdes			if (lex != '=')
804202613Sdes				goto out;
805202613Sdes
806202613Sdes			/* Value */
807202613Sdes			lex = http_header_lex(&cp, value);
808202613Sdes			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
809202613Sdes				goto out;
810202613Sdes
811202613Sdes			if (!strcasecmp(key, "realm"))
812221821Sdes				cs->challenges[cs->count]->realm =
813202613Sdes					strdup(value);
814202613Sdes			else if (!strcasecmp(key, "qop"))
815221821Sdes				cs->challenges[cs->count]->qop =
816202613Sdes					strdup(value);
817202613Sdes			else if (!strcasecmp(key, "nonce"))
818221821Sdes				cs->challenges[cs->count]->nonce =
819202613Sdes					strdup(value);
820202613Sdes			else if (!strcasecmp(key, "opaque"))
821221821Sdes				cs->challenges[cs->count]->opaque =
822202613Sdes					strdup(value);
823202613Sdes			else if (!strcasecmp(key, "algorithm"))
824221821Sdes				cs->challenges[cs->count]->algo =
825202613Sdes					strdup(value);
826202613Sdes			else if (!strcasecmp(key, "stale"))
827221821Sdes				cs->challenges[cs->count]->stale =
828202613Sdes					strcasecmp(value, "no");
829202613Sdes			/* Else ignore unknown attributes */
830202613Sdes
831202613Sdes			/* Comma or Next challenge or End */
832202613Sdes			lex = http_header_lex(&cp, key);
833221821Sdes			/*
834221821Sdes			 * If we get a word here, this is the beginning of the
835221821Sdes			 * next challenge. Break the attributes loop
836221821Sdes			 */
837202613Sdes			if (lex == HTTPHL_WORD)
838202613Sdes				break;
839202613Sdes
840202613Sdes			if (lex == HTTPHL_END) {
841202613Sdes				/* End while looking for ',' is normal exit */
842202613Sdes				cs->count++;
843202613Sdes				ret = 0;
844202613Sdes				goto out;
845202613Sdes			}
846202613Sdes			/* Anything else is an error */
847202613Sdes			if (lex != ',')
848202613Sdes				goto out;
849202613Sdes
850202613Sdes		} /* End attributes loop */
851202613Sdes	} /* End challenge loop */
852202613Sdes
853221821Sdes	/*
854221821Sdes	 * Challenges max count exceeded. This really can't happen
855221821Sdes	 * with normal data, something's fishy -> error
856221821Sdes	 */
857202613Sdes
858202613Sdesout:
859202613Sdes	if (key)
860202613Sdes		free(key);
861202613Sdes	if (value)
862202613Sdes		free(value);
863202613Sdes	if (buf)
864202613Sdes		free(buf);
865202613Sdes	return (ret);
866202613Sdes}
867202613Sdes
868202613Sdes
86963012Sdes/*
87063012Sdes * Parse a last-modified header
87163012Sdes */
87263716Sdesstatic int
873174588Sdeshttp_parse_mtime(const char *p, time_t *mtime)
87463012Sdes{
87590267Sdes	char locale[64], *r;
87690267Sdes	struct tm tm;
87763012Sdes
878109967Sdes	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
87990267Sdes	setlocale(LC_TIME, "C");
88090267Sdes	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
88190267Sdes	/* XXX should add support for date-2 and date-3 */
88290267Sdes	setlocale(LC_TIME, locale);
88390267Sdes	if (r == NULL)
88490267Sdes		return (-1);
88590267Sdes	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
88688769Sdes		  "%02d:%02d:%02d]\n",
88763012Sdes		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
88863012Sdes		  tm.tm_hour, tm.tm_min, tm.tm_sec));
88990267Sdes	*mtime = timegm(&tm);
89090267Sdes	return (0);
89163012Sdes}
89263012Sdes
89363012Sdes/*
89463012Sdes * Parse a content-length header
89563012Sdes */
89663716Sdesstatic int
897174588Sdeshttp_parse_length(const char *p, off_t *length)
89863012Sdes{
89990267Sdes	off_t len;
90090267Sdes
901174761Sdes	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
90290267Sdes		len = len * 10 + (*p - '0');
90390267Sdes	if (*p)
90490267Sdes		return (-1);
90590267Sdes	DEBUG(fprintf(stderr, "content length: [%lld]\n",
90690267Sdes	    (long long)len));
90790267Sdes	*length = len;
90890267Sdes	return (0);
90963012Sdes}
91063012Sdes
91163012Sdes/*
91263012Sdes * Parse a content-range header
91363012Sdes */
91463716Sdesstatic int
915174588Sdeshttp_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
91663012Sdes{
91790267Sdes	off_t first, last, len;
91863716Sdes
91990267Sdes	if (strncasecmp(p, "bytes ", 6) != 0)
92090267Sdes		return (-1);
921125696Sdes	p += 6;
922125696Sdes	if (*p == '*') {
923125696Sdes		first = last = -1;
924125696Sdes		++p;
925125696Sdes	} else {
926174761Sdes		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
927125696Sdes			first = first * 10 + *p - '0';
928125696Sdes		if (*p != '-')
929125696Sdes			return (-1);
930174761Sdes		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
931125696Sdes			last = last * 10 + *p - '0';
932125696Sdes	}
93390267Sdes	if (first > last || *p != '/')
93490267Sdes		return (-1);
935174761Sdes	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
93690267Sdes		len = len * 10 + *p - '0';
93790267Sdes	if (*p || len < last - first + 1)
93890267Sdes		return (-1);
939125696Sdes	if (first == -1) {
940125696Sdes		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
941125696Sdes		    (long long)len));
942125696Sdes		*length = 0;
943125696Sdes	} else {
944125696Sdes		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
945125696Sdes		    (long long)first, (long long)last, (long long)len));
946125696Sdes		*length = last - first + 1;
947125696Sdes	}
94890267Sdes	*offset = first;
94990267Sdes	*size = len;
95090267Sdes	return (0);
95163012Sdes}
95263012Sdes
95390267Sdes
95463012Sdes/*****************************************************************************
95563012Sdes * Helper functions for authorization
95663012Sdes */
95763012Sdes
95863012Sdes/*
95937608Sdes * Base64 encoding
96037608Sdes */
96162965Sdesstatic char *
962174588Sdeshttp_base64(const char *src)
96337608Sdes{
96490267Sdes	static const char base64[] =
96590267Sdes	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
96690267Sdes	    "abcdefghijklmnopqrstuvwxyz"
96790267Sdes	    "0123456789+/";
96890267Sdes	char *str, *dst;
96990267Sdes	size_t l;
97090267Sdes	int t, r;
97162965Sdes
97290267Sdes	l = strlen(src);
973133280Sdes	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
97490267Sdes		return (NULL);
97590267Sdes	dst = str;
97690267Sdes	r = 0;
97737608Sdes
97890267Sdes	while (l >= 3) {
97990267Sdes		t = (src[0] << 16) | (src[1] << 8) | src[2];
98090267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
98190267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
98290267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
98390267Sdes		dst[3] = base64[(t >> 0) & 0x3f];
98490267Sdes		src += 3; l -= 3;
98590267Sdes		dst += 4; r += 4;
98690267Sdes	}
98737608Sdes
98890267Sdes	switch (l) {
98990267Sdes	case 2:
99090267Sdes		t = (src[0] << 16) | (src[1] << 8);
99190267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
99290267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
99390267Sdes		dst[2] = base64[(t >> 6) & 0x3f];
99490267Sdes		dst[3] = '=';
99590267Sdes		dst += 4;
99690267Sdes		r += 4;
99790267Sdes		break;
99890267Sdes	case 1:
99990267Sdes		t = src[0] << 16;
100090267Sdes		dst[0] = base64[(t >> 18) & 0x3f];
100190267Sdes		dst[1] = base64[(t >> 12) & 0x3f];
100290267Sdes		dst[2] = dst[3] = '=';
100390267Sdes		dst += 4;
100490267Sdes		r += 4;
100590267Sdes		break;
100690267Sdes	case 0:
100790267Sdes		break;
100890267Sdes	}
100990267Sdes
101090267Sdes	*dst = 0;
101190267Sdes	return (str);
101237608Sdes}
101337608Sdes
1014202613Sdes
101537608Sdes/*
1016202613Sdes * Extract authorization parameters from environment value.
1017202613Sdes * The value is like scheme:realm:user:pass
1018202613Sdes */
1019202613Sdestypedef struct {
1020202613Sdes	char	*scheme;
1021202613Sdes	char	*realm;
1022202613Sdes	char	*user;
1023202613Sdes	char	*password;
1024202613Sdes} http_auth_params_t;
1025202613Sdes
1026202613Sdesstatic void
1027202613Sdesinit_http_auth_params(http_auth_params_t *s)
1028202613Sdes{
1029202613Sdes	s->scheme = s->realm = s->user = s->password = 0;
1030202613Sdes}
1031202613Sdes
1032221821Sdesstatic void
1033202613Sdesclean_http_auth_params(http_auth_params_t *s)
1034202613Sdes{
1035221821Sdes	if (s->scheme)
1036202613Sdes		free(s->scheme);
1037221821Sdes	if (s->realm)
1038202613Sdes		free(s->realm);
1039221821Sdes	if (s->user)
1040202613Sdes		free(s->user);
1041221821Sdes	if (s->password)
1042202613Sdes		free(s->password);
1043202613Sdes	init_http_auth_params(s);
1044202613Sdes}
1045202613Sdes
1046202613Sdesstatic int
1047202613Sdeshttp_authfromenv(const char *p, http_auth_params_t *parms)
1048202613Sdes{
1049202613Sdes	int ret = -1;
1050202613Sdes	char *v, *ve;
1051202613Sdes	char *str = strdup(p);
1052202613Sdes
1053202613Sdes	if (str == NULL) {
1054202613Sdes		fetch_syserr();
1055202613Sdes		return (-1);
1056202613Sdes	}
1057202613Sdes	v = str;
1058202613Sdes
1059202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1060202613Sdes		goto out;
1061202613Sdes
1062202613Sdes	*ve = 0;
1063202613Sdes	if ((parms->scheme = strdup(v)) == NULL) {
1064202613Sdes		fetch_syserr();
1065202613Sdes		goto out;
1066202613Sdes	}
1067202613Sdes	v = ve + 1;
1068202613Sdes
1069202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1070202613Sdes		goto out;
1071202613Sdes
1072202613Sdes	*ve = 0;
1073202613Sdes	if ((parms->realm = strdup(v)) == NULL) {
1074202613Sdes		fetch_syserr();
1075202613Sdes		goto out;
1076202613Sdes	}
1077202613Sdes	v = ve + 1;
1078202613Sdes
1079202613Sdes	if ((ve = strchr(v, ':')) == NULL)
1080202613Sdes		goto out;
1081202613Sdes
1082202613Sdes	*ve = 0;
1083202613Sdes	if ((parms->user = strdup(v)) == NULL) {
1084202613Sdes		fetch_syserr();
1085202613Sdes		goto out;
1086202613Sdes	}
1087202613Sdes	v = ve + 1;
1088202613Sdes
1089202613Sdes
1090202613Sdes	if ((parms->password = strdup(v)) == NULL) {
1091202613Sdes		fetch_syserr();
1092202613Sdes		goto out;
1093202613Sdes	}
1094202613Sdes	ret = 0;
1095202613Sdesout:
1096221821Sdes	if (ret == -1)
1097202613Sdes		clean_http_auth_params(parms);
1098202613Sdes	if (str)
1099202613Sdes		free(str);
1100202613Sdes	return (ret);
1101202613Sdes}
1102202613Sdes
1103202613Sdes
1104221821Sdes/*
1105202613Sdes * Digest response: the code to compute the digest is taken from the
1106221821Sdes * sample implementation in RFC2616
1107202613Sdes */
1108221822Sdes#define IN const
1109202613Sdes#define OUT
1110202613Sdes
1111202613Sdes#define HASHLEN 16
1112202613Sdestypedef char HASH[HASHLEN];
1113202613Sdes#define HASHHEXLEN 32
1114202613Sdestypedef char HASHHEX[HASHHEXLEN+1];
1115202613Sdes
1116202613Sdesstatic const char *hexchars = "0123456789abcdef";
1117221821Sdesstatic void
1118202613SdesCvtHex(IN HASH Bin, OUT HASHHEX Hex)
1119202613Sdes{
1120202613Sdes	unsigned short i;
1121202613Sdes	unsigned char j;
1122202613Sdes
1123202613Sdes	for (i = 0; i < HASHLEN; i++) {
1124202613Sdes		j = (Bin[i] >> 4) & 0xf;
1125202613Sdes		Hex[i*2] = hexchars[j];
1126202613Sdes		j = Bin[i] & 0xf;
1127202613Sdes		Hex[i*2+1] = hexchars[j];
1128202613Sdes	};
1129202613Sdes	Hex[HASHHEXLEN] = '\0';
1130202613Sdes};
1131202613Sdes
1132202613Sdes/* calculate H(A1) as per spec */
1133221821Sdesstatic void
1134202613SdesDigestCalcHA1(
1135202613Sdes	IN char * pszAlg,
1136202613Sdes	IN char * pszUserName,
1137202613Sdes	IN char * pszRealm,
1138202613Sdes	IN char * pszPassword,
1139202613Sdes	IN char * pszNonce,
1140202613Sdes	IN char * pszCNonce,
1141202613Sdes	OUT HASHHEX SessionKey
1142202613Sdes	)
1143202613Sdes{
1144202613Sdes	MD5_CTX Md5Ctx;
1145202613Sdes	HASH HA1;
1146202613Sdes
1147202613Sdes	MD5Init(&Md5Ctx);
1148202613Sdes	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1149202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1150202613Sdes	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1151202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1152202613Sdes	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1153202613Sdes	MD5Final(HA1, &Md5Ctx);
1154202613Sdes	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1155202613Sdes
1156202613Sdes		MD5Init(&Md5Ctx);
1157202613Sdes		MD5Update(&Md5Ctx, HA1, HASHLEN);
1158202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1159202613Sdes		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1160202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1161202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1162202613Sdes		MD5Final(HA1, &Md5Ctx);
1163202613Sdes	};
1164202613Sdes	CvtHex(HA1, SessionKey);
1165202613Sdes}
1166202613Sdes
1167202613Sdes/* calculate request-digest/response-digest as per HTTP Digest spec */
1168221821Sdesstatic void
1169202613SdesDigestCalcResponse(
1170202613Sdes	IN HASHHEX HA1,           /* H(A1) */
1171202613Sdes	IN char * pszNonce,       /* nonce from server */
1172202613Sdes	IN char * pszNonceCount,  /* 8 hex digits */
1173202613Sdes	IN char * pszCNonce,      /* client nonce */
1174202613Sdes	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1175202613Sdes	IN char * pszMethod,      /* method from the request */
1176202613Sdes	IN char * pszDigestUri,   /* requested URL */
1177202613Sdes	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1178202613Sdes	OUT HASHHEX Response      /* request-digest or response-digest */
1179202613Sdes	)
1180202613Sdes{
1181221821Sdes/*	DEBUG(fprintf(stderr,
1182202613Sdes		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1183202613Sdes		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1184202613Sdes	MD5_CTX Md5Ctx;
1185202613Sdes	HASH HA2;
1186202613Sdes	HASH RespHash;
1187202613Sdes	HASHHEX HA2Hex;
1188202613Sdes
1189202613Sdes	// calculate H(A2)
1190202613Sdes	MD5Init(&Md5Ctx);
1191202613Sdes	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1192202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1193202613Sdes	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1194202613Sdes	if (strcasecmp(pszQop, "auth-int") == 0) {
1195202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1196202613Sdes		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1197202613Sdes	};
1198202613Sdes	MD5Final(HA2, &Md5Ctx);
1199202613Sdes	CvtHex(HA2, HA2Hex);
1200202613Sdes
1201202613Sdes	// calculate response
1202202613Sdes	MD5Init(&Md5Ctx);
1203202613Sdes	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1204202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1205202613Sdes	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1206202613Sdes	MD5Update(&Md5Ctx, ":", 1);
1207202613Sdes	if (*pszQop) {
1208202613Sdes		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1209202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1210202613Sdes		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1211202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1212202613Sdes		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1213202613Sdes		MD5Update(&Md5Ctx, ":", 1);
1214202613Sdes	};
1215202613Sdes	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1216202613Sdes	MD5Final(RespHash, &Md5Ctx);
1217202613Sdes	CvtHex(RespHash, Response);
1218202613Sdes}
1219202613Sdes
1220221821Sdes/*
1221221821Sdes * Generate/Send a Digest authorization header
1222202613Sdes * This looks like: [Proxy-]Authorization: credentials
1223202613Sdes *
1224202613Sdes *  credentials      = "Digest" digest-response
1225202613Sdes *  digest-response  = 1#( username | realm | nonce | digest-uri
1226202613Sdes *                      | response | [ algorithm ] | [cnonce] |
1227202613Sdes *                      [opaque] | [message-qop] |
1228202613Sdes *                          [nonce-count]  | [auth-param] )
1229202613Sdes *  username         = "username" "=" username-value
1230202613Sdes *  username-value   = quoted-string
1231202613Sdes *  digest-uri       = "uri" "=" digest-uri-value
1232202613Sdes *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1233202613Sdes *  message-qop      = "qop" "=" qop-value
1234202613Sdes *  cnonce           = "cnonce" "=" cnonce-value
1235202613Sdes *  cnonce-value     = nonce-value
1236202613Sdes *  nonce-count      = "nc" "=" nc-value
1237202613Sdes *  nc-value         = 8LHEX
1238202613Sdes *  response         = "response" "=" request-digest
1239202613Sdes *  request-digest = <"> 32LHEX <">
1240202613Sdes */
1241202613Sdesstatic int
1242202613Sdeshttp_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1243202613Sdes		 http_auth_params_t *parms, struct url *url)
1244202613Sdes{
1245202613Sdes	int r;
1246202613Sdes	char noncecount[10];
1247202613Sdes	char cnonce[40];
1248202613Sdes	char *options = 0;
1249202613Sdes
1250202613Sdes	if (!c->realm || !c->nonce) {
1251202613Sdes		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1252202613Sdes		return(-1);
1253202613Sdes	}
1254221821Sdes	if (!c->algo)
1255202613Sdes		c->algo = strdup("");
1256202613Sdes
1257221821Sdes	if (asprintf(&options, "%s%s%s%s",
1258202613Sdes		     *c->algo? ",algorithm=" : "", c->algo,
1259202613Sdes		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1260202613Sdes		return (-1);
1261202613Sdes
1262202613Sdes	if (!c->qop) {
1263202613Sdes		c->qop = strdup("");
1264202613Sdes		*noncecount = 0;
1265202613Sdes		*cnonce = 0;
1266202613Sdes	} else {
1267202613Sdes		c->nc++;
1268202613Sdes		sprintf(noncecount, "%08x", c->nc);
1269202613Sdes		/* We don't try very hard with the cnonce ... */
1270202613Sdes		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1271202613Sdes	}
1272202613Sdes
1273202613Sdes	HASHHEX HA1;
1274202613Sdes	DigestCalcHA1(c->algo, parms->user, c->realm,
1275202613Sdes		      parms->password, c->nonce, cnonce, HA1);
1276202613Sdes	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1277202613Sdes	HASHHEX digest;
1278202613Sdes	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1279202613Sdes			   "GET", url->doc, "", digest);
1280202613Sdes
1281202613Sdes	if (c->qop[0]) {
1282202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1283202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1284202613Sdes			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1285221821Sdes			     hdr, parms->user, c->realm,
1286202613Sdes			     c->nonce, url->doc, digest,
1287202613Sdes			     cnonce, noncecount, options);
1288202613Sdes	} else {
1289202613Sdes		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1290202613Sdes			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1291221821Sdes			     hdr, parms->user, c->realm,
1292202613Sdes			     c->nonce, url->doc, digest, options);
1293202613Sdes	}
1294202613Sdes	if (options)
1295202613Sdes		free(options);
1296202613Sdes	return (r);
1297202613Sdes}
1298202613Sdes
1299202613Sdes/*
130037608Sdes * Encode username and password
130137608Sdes */
130262965Sdesstatic int
1303174588Sdeshttp_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
130437608Sdes{
130590267Sdes	char *upw, *auth;
130690267Sdes	int r;
130737608Sdes
1308202613Sdes	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1309202613Sdes	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
131090267Sdes	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
131190267Sdes		return (-1);
1312174588Sdes	auth = http_base64(upw);
131390267Sdes	free(upw);
131490267Sdes	if (auth == NULL)
131590267Sdes		return (-1);
1316174588Sdes	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
131790267Sdes	free(auth);
131890267Sdes	return (r);
131962965Sdes}
132062965Sdes
132162965Sdes/*
1322221821Sdes * Chose the challenge to answer and call the appropriate routine to
1323202613Sdes * produce the header.
132462965Sdes */
132562965Sdesstatic int
1326202613Sdeshttp_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1327202613Sdes	       http_auth_params_t *parms, struct url *url)
132862965Sdes{
1329202613Sdes	http_auth_challenge_t *basic = NULL;
1330202613Sdes	http_auth_challenge_t *digest = NULL;
1331202613Sdes	int i;
133262965Sdes
1333202613Sdes	/* If user or pass are null we're not happy */
1334202613Sdes	if (!parms->user || !parms->password) {
1335202613Sdes		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1336202613Sdes		return (-1);
133790267Sdes	}
1338202613Sdes
1339202613Sdes	/* Look for a Digest and a Basic challenge */
1340202613Sdes	for (i = 0; i < cs->count; i++) {
1341202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1342202613Sdes			basic = cs->challenges[i];
1343202613Sdes		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1344202613Sdes			digest = cs->challenges[i];
1345202613Sdes	}
1346202613Sdes
1347202613Sdes	/* Error if "Digest" was specified and there is no Digest challenge */
1348221821Sdes	if (!digest && (parms->scheme &&
1349202613Sdes			!strcasecmp(parms->scheme, "digest"))) {
1350221821Sdes		DEBUG(fprintf(stderr,
1351202613Sdes			      "Digest auth in env, not supported by peer\n"));
1352202613Sdes		return (-1);
1353202613Sdes	}
1354221821Sdes	/*
1355221821Sdes	 * If "basic" was specified in the environment, or there is no Digest
1356202613Sdes	 * challenge, do the basic thing. Don't need a challenge for this,
1357221821Sdes	 * so no need to check basic!=NULL
1358202613Sdes	 */
1359202613Sdes	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1360202613Sdes		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1361202613Sdes
1362202613Sdes	/* Else, prefer digest. We just checked that it's not NULL */
1363202613Sdes	return (http_digest_auth(conn, hdr, digest, parms, url));
136437608Sdes}
136537608Sdes
136663012Sdes/*****************************************************************************
136763012Sdes * Helper functions for connecting to a server or proxy
136863012Sdes */
136963012Sdes
137037608Sdes/*
137190267Sdes * Connect to the correct HTTP server or proxy.
137263012Sdes */
137397856Sdesstatic conn_t *
1374174588Sdeshttp_connect(struct url *URL, struct url *purl, const char *flags)
137563012Sdes{
137697856Sdes	conn_t *conn;
137790267Sdes	int verbose;
1378141958Skbyanc	int af, val;
137990267Sdes
138063012Sdes#ifdef INET6
138190267Sdes	af = AF_UNSPEC;
138260737Sume#else
138390267Sdes	af = AF_INET;
138460737Sume#endif
138590267Sdes
138690267Sdes	verbose = CHECK_FLAG('v');
138790267Sdes	if (CHECK_FLAG('4'))
138890267Sdes		af = AF_INET;
138967043Sdes#ifdef INET6
139090267Sdes	else if (CHECK_FLAG('6'))
139190267Sdes		af = AF_INET6;
139267043Sdes#endif
139367043Sdes
139497868Sdes	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
139590267Sdes		URL = purl;
139690267Sdes	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
139790267Sdes		/* can't talk http to an ftp server */
139890267Sdes		/* XXX should set an error code */
139997856Sdes		return (NULL);
140090267Sdes	}
140190267Sdes
1402174588Sdes	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1403174588Sdes		/* fetch_connect() has already set an error code */
140497856Sdes		return (NULL);
140597868Sdes	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1406174588Sdes	    fetch_ssl(conn, verbose) == -1) {
1407174588Sdes		fetch_close(conn);
140897891Sdes		/* grrr */
140997891Sdes		errno = EAUTH;
1410174588Sdes		fetch_syserr();
141197868Sdes		return (NULL);
141297868Sdes	}
1413141958Skbyanc
1414141958Skbyanc	val = 1;
1415141958Skbyanc	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1416141958Skbyanc
141797856Sdes	return (conn);
141867043Sdes}
141967043Sdes
142067043Sdesstatic struct url *
1421174752Sdeshttp_get_proxy(struct url * url, const char *flags)
142267043Sdes{
142390267Sdes	struct url *purl;
142490267Sdes	char *p;
142590267Sdes
1426112797Sdes	if (flags != NULL && strchr(flags, 'd') != NULL)
1427112081Sdes		return (NULL);
1428174752Sdes	if (fetch_no_proxy_match(url->host))
1429174752Sdes		return (NULL);
143090267Sdes	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1431149414Sdes	    *p && (purl = fetchParseURL(p))) {
143290267Sdes		if (!*purl->scheme)
143390267Sdes			strcpy(purl->scheme, SCHEME_HTTP);
143490267Sdes		if (!purl->port)
1435174588Sdes			purl->port = fetch_default_proxy_port(purl->scheme);
143690267Sdes		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
143790267Sdes			return (purl);
143890267Sdes		fetchFreeURL(purl);
143990267Sdes	}
144090267Sdes	return (NULL);
144160376Sdes}
144260376Sdes
144388771Sdesstatic void
1444174588Sdeshttp_print_html(FILE *out, FILE *in)
144588771Sdes{
144690267Sdes	size_t len;
144790267Sdes	char *line, *p, *q;
144890267Sdes	int comment, tag;
144988771Sdes
145090267Sdes	comment = tag = 0;
145190267Sdes	while ((line = fgetln(in, &len)) != NULL) {
1452174761Sdes		while (len && isspace((unsigned char)line[len - 1]))
145390267Sdes			--len;
145490267Sdes		for (p = q = line; q < line + len; ++q) {
145590267Sdes			if (comment && *q == '-') {
145690267Sdes				if (q + 2 < line + len &&
145790267Sdes				    strcmp(q, "-->") == 0) {
145890267Sdes					tag = comment = 0;
145990267Sdes					q += 2;
146090267Sdes				}
146190267Sdes			} else if (tag && !comment && *q == '>') {
146290267Sdes				p = q + 1;
146390267Sdes				tag = 0;
146490267Sdes			} else if (!tag && *q == '<') {
146590267Sdes				if (q > p)
146690267Sdes					fwrite(p, q - p, 1, out);
146790267Sdes				tag = 1;
146890267Sdes				if (q + 3 < line + len &&
146990267Sdes				    strcmp(q, "<!--") == 0) {
147090267Sdes					comment = 1;
147190267Sdes					q += 3;
147290267Sdes				}
147390267Sdes			}
147488771Sdes		}
147590267Sdes		if (!tag && q > p)
147690267Sdes			fwrite(p, q - p, 1, out);
147790267Sdes		fputc('\n', out);
147888771Sdes	}
147988771Sdes}
148088771Sdes
148190267Sdes
148263012Sdes/*****************************************************************************
148363012Sdes * Core
148460954Sdes */
148560954Sdes
148660954Sdes/*
148763012Sdes * Send a request and process the reply
148897866Sdes *
148997866Sdes * XXX This function is way too long, the do..while loop should be split
149097866Sdes * XXX off into a separate function.
149160376Sdes */
149267043SdesFILE *
1493174588Sdeshttp_request(struct url *URL, const char *op, struct url_stat *us,
1494202613Sdes	struct url *purl, const char *flags)
149560376Sdes{
1496186124Smurray	char timebuf[80];
1497186124Smurray	char hbuf[MAXHOSTNAMELEN + 7], *host;
149897856Sdes	conn_t *conn;
149990267Sdes	struct url *url, *new;
1500202613Sdes	int chunked, direct, ims, noredirect, verbose;
1501143049Skbyanc	int e, i, n, val;
150290267Sdes	off_t offset, clength, length, size;
150390267Sdes	time_t mtime;
150490267Sdes	const char *p;
150590267Sdes	FILE *f;
150690267Sdes	hdr_t h;
1507186124Smurray	struct tm *timestruct;
1508202613Sdes	http_headerbuf_t headerbuf;
1509202613Sdes	http_auth_challenges_t server_challenges;
1510202613Sdes	http_auth_challenges_t proxy_challenges;
151163012Sdes
1512202613Sdes	/* The following calls don't allocate anything */
1513221821Sdes	init_http_headerbuf(&headerbuf);
1514202613Sdes	init_http_auth_challenges(&server_challenges);
1515202613Sdes	init_http_auth_challenges(&proxy_challenges);
1516202613Sdes
151790267Sdes	direct = CHECK_FLAG('d');
151890267Sdes	noredirect = CHECK_FLAG('A');
151990267Sdes	verbose = CHECK_FLAG('v');
1520186124Smurray	ims = CHECK_FLAG('i');
152160737Sume
152290267Sdes	if (direct && purl) {
152390267Sdes		fetchFreeURL(purl);
152490267Sdes		purl = NULL;
152590267Sdes	}
152663716Sdes
152790267Sdes	/* try the provided URL first */
152890267Sdes	url = URL;
152963012Sdes
1530241840Seadler	n = MAX_REDIRECT;
153190267Sdes	i = 0;
153263012Sdes
153398422Sdes	e = HTTP_PROTOCOL_ERROR;
153490267Sdes	do {
153590267Sdes		new = NULL;
153690267Sdes		chunked = 0;
153790267Sdes		offset = 0;
153890267Sdes		clength = -1;
153990267Sdes		length = -1;
154090267Sdes		size = -1;
154190267Sdes		mtime = 0;
154290267Sdes
154390267Sdes		/* check port */
154490267Sdes		if (!url->port)
1545174588Sdes			url->port = fetch_default_port(url->scheme);
154690267Sdes
154790267Sdes		/* were we redirected to an FTP URL? */
154890267Sdes		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
154990267Sdes			if (strcmp(op, "GET") == 0)
1550174588Sdes				return (ftp_request(url, "RETR", us, purl, flags));
155190267Sdes			else if (strcmp(op, "HEAD") == 0)
1552174588Sdes				return (ftp_request(url, "STAT", us, purl, flags));
155390267Sdes		}
155490267Sdes
155590267Sdes		/* connect to server or proxy */
1556174588Sdes		if ((conn = http_connect(url, purl, flags)) == NULL)
155790267Sdes			goto ouch;
155890267Sdes
155990267Sdes		host = url->host;
156060737Sume#ifdef INET6
156190267Sdes		if (strchr(url->host, ':')) {
156290267Sdes			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
156390267Sdes			host = hbuf;
156490267Sdes		}
156560737Sume#endif
1566174588Sdes		if (url->port != fetch_default_port(url->scheme)) {
1567107372Sdes			if (host != hbuf) {
1568107372Sdes				strcpy(hbuf, host);
1569107372Sdes				host = hbuf;
1570107372Sdes			}
1571107372Sdes			snprintf(hbuf + strlen(hbuf),
1572107372Sdes			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1573107372Sdes		}
157437535Sdes
157590267Sdes		/* send request */
157690267Sdes		if (verbose)
1577174588Sdes			fetch_info("requesting %s://%s%s",
1578107372Sdes			    url->scheme, host, url->doc);
157990267Sdes		if (purl) {
1580174588Sdes			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1581107372Sdes			    op, url->scheme, host, url->doc);
158290267Sdes		} else {
1583174588Sdes			http_cmd(conn, "%s %s HTTP/1.1",
158490267Sdes			    op, url->doc);
158590267Sdes		}
158637535Sdes
1587186124Smurray		if (ims && url->ims_time) {
1588186124Smurray			timestruct = gmtime((time_t *)&url->ims_time);
1589186124Smurray			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1590186124Smurray			    timestruct);
1591186124Smurray			if (verbose)
1592186124Smurray				fetch_info("If-Modified-Since: %s", timebuf);
1593186124Smurray			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1594186124Smurray		}
159590267Sdes		/* virtual host */
1596174588Sdes		http_cmd(conn, "Host: %s", host);
159790267Sdes
1598221821Sdes		/*
1599221821Sdes		 * Proxy authorization: we only send auth after we received
1600221821Sdes		 * a 407 error. We do not first try basic anyway (changed
1601221821Sdes		 * when support was added for digest-auth)
1602221821Sdes		 */
1603202613Sdes		if (purl && proxy_challenges.valid) {
1604202613Sdes			http_auth_params_t aparams;
1605202613Sdes			init_http_auth_params(&aparams);
1606202613Sdes			if (*purl->user || *purl->pwd) {
1607221821Sdes				aparams.user = purl->user ?
1608202613Sdes					strdup(purl->user) : strdup("");
1609202613Sdes				aparams.password = purl->pwd?
1610202613Sdes					strdup(purl->pwd) : strdup("");
1611221821Sdes			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1612202613Sdes				   *p != '\0') {
1613202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1614202613Sdes					http_seterr(HTTP_NEED_PROXY_AUTH);
1615202613Sdes					goto ouch;
1616202613Sdes				}
1617202613Sdes			}
1618221821Sdes			http_authorize(conn, "Proxy-Authorization",
1619202613Sdes				       &proxy_challenges, &aparams, url);
1620202613Sdes			clean_http_auth_params(&aparams);
162190267Sdes		}
162290267Sdes
1623221821Sdes		/*
1624221821Sdes		 * Server authorization: we never send "a priori"
1625202613Sdes		 * Basic auth, which used to be done if user/pass were
1626202613Sdes		 * set in the url. This would be weird because we'd send the
1627221821Sdes		 * password in the clear even if Digest is finally to be
1628202613Sdes		 * used (it would have made more sense for the
1629221821Sdes		 * pre-digest version to do this when Basic was specified
1630221821Sdes		 * in the environment)
1631221821Sdes		 */
1632202613Sdes		if (server_challenges.valid) {
1633202613Sdes			http_auth_params_t aparams;
1634202613Sdes			init_http_auth_params(&aparams);
1635202613Sdes			if (*url->user || *url->pwd) {
1636221821Sdes				aparams.user = url->user ?
1637202613Sdes					strdup(url->user) : strdup("");
1638221821Sdes				aparams.password = url->pwd ?
1639202613Sdes					strdup(url->pwd) : strdup("");
1640221821Sdes			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1641202613Sdes				   *p != '\0') {
1642202613Sdes				if (http_authfromenv(p, &aparams) < 0) {
1643202613Sdes					http_seterr(HTTP_NEED_AUTH);
1644202613Sdes					goto ouch;
1645202613Sdes				}
1646221821Sdes			} else if (fetchAuthMethod &&
1647202613Sdes				   fetchAuthMethod(url) == 0) {
1648221821Sdes				aparams.user = url->user ?
1649202613Sdes					strdup(url->user) : strdup("");
1650221821Sdes				aparams.password = url->pwd ?
1651202613Sdes					strdup(url->pwd) : strdup("");
165290267Sdes			} else {
1653174588Sdes				http_seterr(HTTP_NEED_AUTH);
165490267Sdes				goto ouch;
165590267Sdes			}
1656221821Sdes			http_authorize(conn, "Authorization",
1657202613Sdes				       &server_challenges, &aparams, url);
1658202613Sdes			clean_http_auth_params(&aparams);
165990267Sdes		}
166090267Sdes
166190267Sdes		/* other headers */
1662107372Sdes		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1663107372Sdes			if (strcasecmp(p, "auto") == 0)
1664174588Sdes				http_cmd(conn, "Referer: %s://%s%s",
1665107372Sdes				    url->scheme, host, url->doc);
1666107372Sdes			else
1667174588Sdes				http_cmd(conn, "Referer: %s", p);
1668107372Sdes		}
166990267Sdes		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1670174588Sdes			http_cmd(conn, "User-Agent: %s", p);
167190267Sdes		else
1672174588Sdes			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1673109693Sdes		if (url->offset > 0)
1674174588Sdes			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1675174588Sdes		http_cmd(conn, "Connection: close");
1676174588Sdes		http_cmd(conn, "");
167790267Sdes
1678143049Skbyanc		/*
1679143049Skbyanc		 * Force the queued request to be dispatched.  Normally, one
1680143049Skbyanc		 * would do this with shutdown(2) but squid proxies can be
1681143049Skbyanc		 * configured to disallow such half-closed connections.  To
1682143049Skbyanc		 * be compatible with such configurations, fiddle with socket
1683143049Skbyanc		 * options to force the pending data to be written.
1684143049Skbyanc		 */
1685143049Skbyanc		val = 0;
1686143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1687143049Skbyanc			   sizeof(val));
1688143049Skbyanc		val = 1;
1689143049Skbyanc		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1690143049Skbyanc			   sizeof(val));
1691143049Skbyanc
169290267Sdes		/* get reply */
1693174588Sdes		switch (http_get_reply(conn)) {
169490267Sdes		case HTTP_OK:
169590267Sdes		case HTTP_PARTIAL:
1696186124Smurray		case HTTP_NOT_MODIFIED:
169790267Sdes			/* fine */
169890267Sdes			break;
169990267Sdes		case HTTP_MOVED_PERM:
170090267Sdes		case HTTP_MOVED_TEMP:
170190267Sdes		case HTTP_SEE_OTHER:
1702241841Seadler		case HTTP_USE_PROXY:
170390267Sdes			/*
1704125695Sdes			 * Not so fine, but we still have to read the
1705125695Sdes			 * headers to get the new location.
170690267Sdes			 */
170790267Sdes			break;
170890267Sdes		case HTTP_NEED_AUTH:
1709202613Sdes			if (server_challenges.valid) {
171090267Sdes				/*
1711125695Sdes				 * We already sent out authorization code,
1712125695Sdes				 * so there's nothing more we can do.
171390267Sdes				 */
1714174588Sdes				http_seterr(conn->err);
171590267Sdes				goto ouch;
171690267Sdes			}
171790267Sdes			/* try again, but send the password this time */
171890267Sdes			if (verbose)
1719174588Sdes				fetch_info("server requires authorization");
172090267Sdes			break;
172190267Sdes		case HTTP_NEED_PROXY_AUTH:
1722202613Sdes			if (proxy_challenges.valid) {
1723202613Sdes				/*
1724202613Sdes				 * We already sent our proxy
1725202613Sdes				 * authorization code, so there's
1726202613Sdes				 * nothing more we can do. */
1727202613Sdes				http_seterr(conn->err);
1728202613Sdes				goto ouch;
1729202613Sdes			}
1730202613Sdes			/* try again, but send the password this time */
1731202613Sdes			if (verbose)
1732202613Sdes				fetch_info("proxy requires authorization");
1733202613Sdes			break;
1734125696Sdes		case HTTP_BAD_RANGE:
1735125696Sdes			/*
1736125696Sdes			 * This can happen if we ask for 0 bytes because
1737125696Sdes			 * we already have the whole file.  Consider this
1738125696Sdes			 * a success for now, and check sizes later.
1739125696Sdes			 */
1740125696Sdes			break;
174190267Sdes		case HTTP_PROTOCOL_ERROR:
174290267Sdes			/* fall through */
174390267Sdes		case -1:
1744174588Sdes			fetch_syserr();
174590267Sdes			goto ouch;
174690267Sdes		default:
1747174588Sdes			http_seterr(conn->err);
174890267Sdes			if (!verbose)
174990267Sdes				goto ouch;
175090267Sdes			/* fall through so we can get the full error message */
175190267Sdes		}
175290267Sdes
1753202613Sdes		/* get headers. http_next_header expects one line readahead */
1754202613Sdes		if (fetch_getln(conn) == -1) {
1755243149Sdes			fetch_syserr();
1756243149Sdes			goto ouch;
1757202613Sdes		}
175890267Sdes		do {
1759243149Sdes			switch ((h = http_next_header(conn, &headerbuf, &p))) {
176090267Sdes			case hdr_syserror:
1761174588Sdes				fetch_syserr();
176290267Sdes				goto ouch;
176390267Sdes			case hdr_error:
1764174588Sdes				http_seterr(HTTP_PROTOCOL_ERROR);
176590267Sdes				goto ouch;
176690267Sdes			case hdr_content_length:
1767174588Sdes				http_parse_length(p, &clength);
176890267Sdes				break;
176990267Sdes			case hdr_content_range:
1770174588Sdes				http_parse_range(p, &offset, &length, &size);
177190267Sdes				break;
177290267Sdes			case hdr_last_modified:
1773174588Sdes				http_parse_mtime(p, &mtime);
177490267Sdes				break;
177590267Sdes			case hdr_location:
177697856Sdes				if (!HTTP_REDIRECT(conn->err))
177790267Sdes					break;
1778241840Seadler				/*
1779241840Seadler				 * if the A flag is set, we don't follow
1780241840Seadler				 * temporary redirects.
1781241840Seadler				 */
1782241840Seadler				if (noredirect &&
1783241840Seadler				    conn->err != HTTP_MOVED_PERM &&
1784241841Seadler				    conn->err != HTTP_PERM_REDIRECT &&
1785241841Seadler				    conn->err != HTTP_USE_PROXY) {
1786241840Seadler					n = 1;
1787241840Seadler					break;
1788243149Sdes				}
178990267Sdes				if (new)
179090267Sdes					free(new);
179190267Sdes				if (verbose)
1792174588Sdes					fetch_info("%d redirect to %s", conn->err, p);
179390267Sdes				if (*p == '/')
179490267Sdes					/* absolute path */
179590267Sdes					new = fetchMakeURL(url->scheme, url->host, url->port, p,
179690267Sdes					    url->user, url->pwd);
179790267Sdes				else
179890267Sdes					new = fetchParseURL(p);
179990267Sdes				if (new == NULL) {
180090267Sdes					/* XXX should set an error code */
180190267Sdes					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
180290267Sdes					goto ouch;
180390267Sdes				}
1804234838Sdes
1805234838Sdes				/* Only copy credentials if the host matches */
1806234838Sdes				if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) {
180790267Sdes					strcpy(new->user, url->user);
180890267Sdes					strcpy(new->pwd, url->pwd);
180990267Sdes				}
181090267Sdes				new->offset = url->offset;
181190267Sdes				new->length = url->length;
181290267Sdes				break;
181390267Sdes			case hdr_transfer_encoding:
181490267Sdes				/* XXX weak test*/
181590267Sdes				chunked = (strcasecmp(p, "chunked") == 0);
181690267Sdes				break;
181790267Sdes			case hdr_www_authenticate:
181897856Sdes				if (conn->err != HTTP_NEED_AUTH)
181990267Sdes					break;
1820210563Sdes				if (http_parse_authenticate(p, &server_challenges) == 0)
1821209632Sdes					++n;
182290267Sdes				break;
1823202613Sdes			case hdr_proxy_authenticate:
1824202613Sdes				if (conn->err != HTTP_NEED_PROXY_AUTH)
1825202613Sdes					break;
1826210563Sdes				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1827209632Sdes					++n;
1828202613Sdes				break;
182990267Sdes			case hdr_end:
183090267Sdes				/* fall through */
183190267Sdes			case hdr_unknown:
183290267Sdes				/* ignore */
183390267Sdes				break;
183490267Sdes			}
183590267Sdes		} while (h > hdr_end);
183690267Sdes
183790267Sdes		/* we need to provide authentication */
1838221821Sdes		if (conn->err == HTTP_NEED_AUTH ||
1839202613Sdes		    conn->err == HTTP_NEED_PROXY_AUTH) {
184098422Sdes			e = conn->err;
1841221821Sdes			if ((conn->err == HTTP_NEED_AUTH &&
1842221821Sdes			     !server_challenges.valid) ||
1843221821Sdes			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1844202613Sdes			     !proxy_challenges.valid)) {
1845202613Sdes				/* 401/7 but no www/proxy-authenticate ?? */
1846202613Sdes				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1847202613Sdes				goto ouch;
1848202613Sdes			}
1849174588Sdes			fetch_close(conn);
185097856Sdes			conn = NULL;
185190267Sdes			continue;
185290267Sdes		}
185390267Sdes
1854125696Sdes		/* requested range not satisfiable */
1855125696Sdes		if (conn->err == HTTP_BAD_RANGE) {
1856125696Sdes			if (url->offset == size && url->length == 0) {
1857125696Sdes				/* asked for 0 bytes; fake it */
1858125696Sdes				offset = url->offset;
1859184222Sru				clength = -1;
1860125696Sdes				conn->err = HTTP_OK;
1861125696Sdes				break;
1862125696Sdes			} else {
1863174588Sdes				http_seterr(conn->err);
1864125696Sdes				goto ouch;
1865125696Sdes			}
1866125696Sdes		}
1867125696Sdes
1868104404Sru		/* we have a hit or an error */
1869186124Smurray		if (conn->err == HTTP_OK
1870186124Smurray		    || conn->err == HTTP_NOT_MODIFIED
1871186124Smurray		    || conn->err == HTTP_PARTIAL
1872186124Smurray		    || HTTP_ERROR(conn->err))
1873104404Sru			break;
1874104404Sru
187590267Sdes		/* all other cases: we got a redirect */
187698422Sdes		e = conn->err;
1877202613Sdes		clean_http_auth_challenges(&server_challenges);
1878174588Sdes		fetch_close(conn);
187997856Sdes		conn = NULL;
188090267Sdes		if (!new) {
188190267Sdes			DEBUG(fprintf(stderr, "redirect with no new location\n"));
188290267Sdes			break;
188390267Sdes		}
188490267Sdes		if (url != URL)
188590267Sdes			fetchFreeURL(url);
188690267Sdes		url = new;
188790267Sdes	} while (++i < n);
188890267Sdes
188990267Sdes	/* we failed, or ran out of retries */
189097856Sdes	if (conn == NULL) {
1891174588Sdes		http_seterr(e);
189263012Sdes		goto ouch;
189363012Sdes	}
189460376Sdes
189590267Sdes	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
189690267Sdes		  " size %lld, clength %lld\n",
189790267Sdes		  (long long)offset, (long long)length,
189890267Sdes		  (long long)size, (long long)clength));
189960376Sdes
1900186124Smurray	if (conn->err == HTTP_NOT_MODIFIED) {
1901186124Smurray		http_seterr(HTTP_NOT_MODIFIED);
1902186124Smurray		return (NULL);
1903186124Smurray	}
1904186124Smurray
190590267Sdes	/* check for inconsistencies */
190690267Sdes	if (clength != -1 && length != -1 && clength != length) {
1907174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
190863012Sdes		goto ouch;
190963012Sdes	}
191090267Sdes	if (clength == -1)
191190267Sdes		clength = length;
191290267Sdes	if (clength != -1)
191390267Sdes		length = offset + clength;
191490267Sdes	if (length != -1 && size != -1 && length != size) {
1915174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
191663012Sdes		goto ouch;
191790267Sdes	}
191890267Sdes	if (size == -1)
191990267Sdes		size = length;
192060376Sdes
192190267Sdes	/* fill in stats */
192290267Sdes	if (us) {
192390267Sdes		us->size = size;
192490267Sdes		us->atime = us->mtime = mtime;
192590267Sdes	}
192663069Sdes
192790267Sdes	/* too far? */
1928109693Sdes	if (URL->offset > 0 && offset > URL->offset) {
1929174588Sdes		http_seterr(HTTP_PROTOCOL_ERROR);
193090267Sdes		goto ouch;
193177238Sdes	}
193260376Sdes
193390267Sdes	/* report back real offset and size */
193490267Sdes	URL->offset = offset;
193590267Sdes	URL->length = clength;
193637535Sdes
193790267Sdes	/* wrap it up in a FILE */
1938174588Sdes	if ((f = http_funopen(conn, chunked)) == NULL) {
1939174588Sdes		fetch_syserr();
194090267Sdes		goto ouch;
194190267Sdes	}
194263716Sdes
194390267Sdes	if (url != URL)
194490267Sdes		fetchFreeURL(url);
194590267Sdes	if (purl)
194690267Sdes		fetchFreeURL(purl);
194763567Sdes
194897856Sdes	if (HTTP_ERROR(conn->err)) {
1949174588Sdes		http_print_html(stderr, f);
195090267Sdes		fclose(f);
195190267Sdes		f = NULL;
195290267Sdes	}
1953202613Sdes	clean_http_headerbuf(&headerbuf);
1954202613Sdes	clean_http_auth_challenges(&server_challenges);
1955202613Sdes	clean_http_auth_challenges(&proxy_challenges);
195690267Sdes	return (f);
195788771Sdes
195890267Sdesouch:
195990267Sdes	if (url != URL)
196090267Sdes		fetchFreeURL(url);
196190267Sdes	if (purl)
196290267Sdes		fetchFreeURL(purl);
196397856Sdes	if (conn != NULL)
1964174588Sdes		fetch_close(conn);
1965202613Sdes	clean_http_headerbuf(&headerbuf);
1966202613Sdes	clean_http_auth_challenges(&server_challenges);
1967202613Sdes	clean_http_auth_challenges(&proxy_challenges);
196890267Sdes	return (NULL);
196963012Sdes}
197060189Sdes
197190267Sdes
197263012Sdes/*****************************************************************************
197363012Sdes * Entry points
197463012Sdes */
197563012Sdes
197663012Sdes/*
197763340Sdes * Retrieve and stat a file by HTTP
197863340Sdes */
197963340SdesFILE *
198075891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
198163340Sdes{
1982174752Sdes	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
198363340Sdes}
198463340Sdes
198563340Sdes/*
198663012Sdes * Retrieve a file by HTTP
198763012Sdes */
198863012SdesFILE *
198975891SarchiefetchGetHTTP(struct url *URL, const char *flags)
199063012Sdes{
199190267Sdes	return (fetchXGetHTTP(URL, NULL, flags));
199237535Sdes}
199337535Sdes
199463340Sdes/*
199563340Sdes * Store a file by HTTP
199663340Sdes */
199737535SdesFILE *
199885093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused)
199937535Sdes{
200090267Sdes	warnx("fetchPutHTTP(): not implemented");
200190267Sdes	return (NULL);
200237535Sdes}
200340975Sdes
200440975Sdes/*
200540975Sdes * Get an HTTP document's metadata
200640975Sdes */
200740975Sdesint
200875891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
200940975Sdes{
201090267Sdes	FILE *f;
201190267Sdes
2012174752Sdes	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2013112081Sdes	if (f == NULL)
201490267Sdes		return (-1);
201590267Sdes	fclose(f);
201690267Sdes	return (0);
201740975Sdes}
201841989Sdes
201941989Sdes/*
202041989Sdes * List a directory
202141989Sdes */
202241989Sdesstruct url_ent *
202385093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused)
202441989Sdes{
202590267Sdes	warnx("fetchListHTTP(): not implemented");
202690267Sdes	return (NULL);
202741989Sdes}
2028