http.c revision 242293
1/*-
2 * Copyright (c) 2000-2011 Dag-Erling Sm��rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: stable/9/lib/libfetch/http.c 242293 2012-10-29 04:18:34Z eadler $");
31
32/*
33 * The following copyright applies to the base64 code:
34 *
35 *-
36 * Copyright 1997 Massachusetts Institute of Technology
37 *
38 * Permission to use, copy, modify, and distribute this software and
39 * its documentation for any purpose and without fee is hereby
40 * granted, provided that both the above copyright notice and this
41 * permission notice appear in all copies, that both the above
42 * copyright notice and this permission notice appear in all
43 * supporting documentation, and that the name of M.I.T. not be used
44 * in advertising or publicity pertaining to distribution of the
45 * software without specific, written prior permission.  M.I.T. makes
46 * no representations about the suitability of this software for any
47 * purpose.  It is provided "as is" without express or implied
48 * warranty.
49 *
50 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
51 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
52 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
53 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
54 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
56 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
57 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
58 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
59 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
60 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * SUCH DAMAGE.
62 */
63
64#include <sys/param.h>
65#include <sys/socket.h>
66#include <sys/time.h>
67
68#include <ctype.h>
69#include <err.h>
70#include <errno.h>
71#include <locale.h>
72#include <netdb.h>
73#include <stdarg.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <time.h>
78#include <unistd.h>
79#include <md5.h>
80
81#include <netinet/in.h>
82#include <netinet/tcp.h>
83
84#include "fetch.h"
85#include "common.h"
86#include "httperr.h"
87
88/* Maximum number of redirects to follow */
89#define MAX_REDIRECT 20
90
91/* Symbolic names for reply codes we care about */
92#define HTTP_OK			200
93#define HTTP_PARTIAL		206
94#define HTTP_MOVED_PERM		301
95#define HTTP_MOVED_TEMP		302
96#define HTTP_SEE_OTHER		303
97#define HTTP_NOT_MODIFIED	304
98#define HTTP_USE_PROXY		305
99#define HTTP_TEMP_REDIRECT	307
100#define HTTP_PERM_REDIRECT	308
101#define HTTP_NEED_AUTH		401
102#define HTTP_NEED_PROXY_AUTH	407
103#define HTTP_BAD_RANGE		416
104#define HTTP_PROTOCOL_ERROR	999
105
106#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
107			    || (xyz) == HTTP_MOVED_TEMP \
108			    || (xyz) == HTTP_TEMP_REDIRECT \
109			    || (xyz) == HTTP_USE_PROXY \
110			    || (xyz) == HTTP_SEE_OTHER)
111
112#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
113
114
115/*****************************************************************************
116 * I/O functions for decoding chunked streams
117 */
118
119struct httpio
120{
121	conn_t		*conn;		/* connection */
122	int		 chunked;	/* chunked mode */
123	char		*buf;		/* chunk buffer */
124	size_t		 bufsize;	/* size of chunk buffer */
125	ssize_t		 buflen;	/* amount of data currently in buffer */
126	int		 bufpos;	/* current read offset in buffer */
127	int		 eof;		/* end-of-file flag */
128	int		 error;		/* error flag */
129	size_t		 chunksize;	/* remaining size of current chunk */
130#ifndef NDEBUG
131	size_t		 total;
132#endif
133};
134
135/*
136 * Get next chunk header
137 */
138static int
139http_new_chunk(struct httpio *io)
140{
141	char *p;
142
143	if (fetch_getln(io->conn) == -1)
144		return (-1);
145
146	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
147		return (-1);
148
149	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
150		if (*p == ';')
151			break;
152		if (!isxdigit((unsigned char)*p))
153			return (-1);
154		if (isdigit((unsigned char)*p)) {
155			io->chunksize = io->chunksize * 16 +
156			    *p - '0';
157		} else {
158			io->chunksize = io->chunksize * 16 +
159			    10 + tolower((unsigned char)*p) - 'a';
160		}
161	}
162
163#ifndef NDEBUG
164	if (fetchDebug) {
165		io->total += io->chunksize;
166		if (io->chunksize == 0)
167			fprintf(stderr, "%s(): end of last chunk\n", __func__);
168		else
169			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
170			    __func__, (unsigned long)io->chunksize,
171			    (unsigned long)io->total);
172	}
173#endif
174
175	return (io->chunksize);
176}
177
178/*
179 * Grow the input buffer to at least len bytes
180 */
181static inline int
182http_growbuf(struct httpio *io, size_t len)
183{
184	char *tmp;
185
186	if (io->bufsize >= len)
187		return (0);
188
189	if ((tmp = realloc(io->buf, len)) == NULL)
190		return (-1);
191	io->buf = tmp;
192	io->bufsize = len;
193	return (0);
194}
195
196/*
197 * Fill the input buffer, do chunk decoding on the fly
198 */
199static int
200http_fillbuf(struct httpio *io, size_t len)
201{
202	ssize_t nbytes;
203
204	if (io->error)
205		return (-1);
206	if (io->eof)
207		return (0);
208
209	if (io->chunked == 0) {
210		if (http_growbuf(io, len) == -1)
211			return (-1);
212		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
213			io->error = errno;
214			return (-1);
215		}
216		io->buflen = nbytes;
217		io->bufpos = 0;
218		return (io->buflen);
219	}
220
221	if (io->chunksize == 0) {
222		switch (http_new_chunk(io)) {
223		case -1:
224			io->error = 1;
225			return (-1);
226		case 0:
227			io->eof = 1;
228			return (0);
229		}
230	}
231
232	if (len > io->chunksize)
233		len = io->chunksize;
234	if (http_growbuf(io, len) == -1)
235		return (-1);
236	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
237		io->error = errno;
238		return (-1);
239	}
240	io->buflen = nbytes;
241	io->chunksize -= io->buflen;
242
243	if (io->chunksize == 0) {
244		char endl[2];
245
246		if (fetch_read(io->conn, endl, 2) != 2 ||
247		    endl[0] != '\r' || endl[1] != '\n')
248			return (-1);
249	}
250
251	io->bufpos = 0;
252
253	return (io->buflen);
254}
255
256/*
257 * Read function
258 */
259static int
260http_readfn(void *v, char *buf, int len)
261{
262	struct httpio *io = (struct httpio *)v;
263	int l, pos;
264
265	if (io->error)
266		return (-1);
267	if (io->eof)
268		return (0);
269
270	for (pos = 0; len > 0; pos += l, len -= l) {
271		/* empty buffer */
272		if (!io->buf || io->bufpos == io->buflen)
273			if (http_fillbuf(io, len) < 1)
274				break;
275		l = io->buflen - io->bufpos;
276		if (len < l)
277			l = len;
278		memcpy(buf + pos, io->buf + io->bufpos, l);
279		io->bufpos += l;
280	}
281
282	if (!pos && io->error) {
283		if (io->error == EINTR)
284			io->error = 0;
285		return (-1);
286	}
287	return (pos);
288}
289
290/*
291 * Write function
292 */
293static int
294http_writefn(void *v, const char *buf, int len)
295{
296	struct httpio *io = (struct httpio *)v;
297
298	return (fetch_write(io->conn, buf, len));
299}
300
301/*
302 * Close function
303 */
304static int
305http_closefn(void *v)
306{
307	struct httpio *io = (struct httpio *)v;
308	int r;
309
310	r = fetch_close(io->conn);
311	if (io->buf)
312		free(io->buf);
313	free(io);
314	return (r);
315}
316
317/*
318 * Wrap a file descriptor up
319 */
320static FILE *
321http_funopen(conn_t *conn, int chunked)
322{
323	struct httpio *io;
324	FILE *f;
325
326	if ((io = calloc(1, sizeof(*io))) == NULL) {
327		fetch_syserr();
328		return (NULL);
329	}
330	io->conn = conn;
331	io->chunked = chunked;
332	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
333	if (f == NULL) {
334		fetch_syserr();
335		free(io);
336		return (NULL);
337	}
338	return (f);
339}
340
341
342/*****************************************************************************
343 * Helper functions for talking to the server and parsing its replies
344 */
345
346/* Header types */
347typedef enum {
348	hdr_syserror = -2,
349	hdr_error = -1,
350	hdr_end = 0,
351	hdr_unknown = 1,
352	hdr_content_length,
353	hdr_content_range,
354	hdr_last_modified,
355	hdr_location,
356	hdr_transfer_encoding,
357	hdr_www_authenticate,
358	hdr_proxy_authenticate,
359} hdr_t;
360
361/* Names of interesting headers */
362static struct {
363	hdr_t		 num;
364	const char	*name;
365} hdr_names[] = {
366	{ hdr_content_length,		"Content-Length" },
367	{ hdr_content_range,		"Content-Range" },
368	{ hdr_last_modified,		"Last-Modified" },
369	{ hdr_location,			"Location" },
370	{ hdr_transfer_encoding,	"Transfer-Encoding" },
371	{ hdr_www_authenticate,		"WWW-Authenticate" },
372	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
373	{ hdr_unknown,			NULL },
374};
375
376/*
377 * Send a formatted line; optionally echo to terminal
378 */
379static int
380http_cmd(conn_t *conn, const char *fmt, ...)
381{
382	va_list ap;
383	size_t len;
384	char *msg;
385	int r;
386
387	va_start(ap, fmt);
388	len = vasprintf(&msg, fmt, ap);
389	va_end(ap);
390
391	if (msg == NULL) {
392		errno = ENOMEM;
393		fetch_syserr();
394		return (-1);
395	}
396
397	r = fetch_putln(conn, msg, len);
398	free(msg);
399
400	if (r == -1) {
401		fetch_syserr();
402		return (-1);
403	}
404
405	return (0);
406}
407
408/*
409 * Get and parse status line
410 */
411static int
412http_get_reply(conn_t *conn)
413{
414	char *p;
415
416	if (fetch_getln(conn) == -1)
417		return (-1);
418	/*
419	 * A valid status line looks like "HTTP/m.n xyz reason" where m
420	 * and n are the major and minor protocol version numbers and xyz
421	 * is the reply code.
422	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
423	 * just one) that do not send a version number, so we can't rely
424	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
425	 * We don't care about the reason phrase.
426	 */
427	if (strncmp(conn->buf, "HTTP", 4) != 0)
428		return (HTTP_PROTOCOL_ERROR);
429	p = conn->buf + 4;
430	if (*p == '/') {
431		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
432			return (HTTP_PROTOCOL_ERROR);
433		p += 4;
434	}
435	if (*p != ' ' ||
436	    !isdigit((unsigned char)p[1]) ||
437	    !isdigit((unsigned char)p[2]) ||
438	    !isdigit((unsigned char)p[3]))
439		return (HTTP_PROTOCOL_ERROR);
440
441	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
442	return (conn->err);
443}
444
445/*
446 * Check a header; if the type matches the given string, return a pointer
447 * to the beginning of the value.
448 */
449static const char *
450http_match(const char *str, const char *hdr)
451{
452	while (*str && *hdr &&
453	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
454		/* nothing */;
455	if (*str || *hdr != ':')
456		return (NULL);
457	while (*hdr && isspace((unsigned char)*++hdr))
458		/* nothing */;
459	return (hdr);
460}
461
462
463/*
464 * Get the next header and return the appropriate symbolic code.  We
465 * need to read one line ahead for checking for a continuation line
466 * belonging to the current header (continuation lines start with
467 * white space).
468 *
469 * We get called with a fresh line already in the conn buffer, either
470 * from the previous http_next_header() invocation, or, the first
471 * time, from a fetch_getln() performed by our caller.
472 *
473 * This stops when we encounter an empty line (we dont read beyond the header
474 * area).
475 *
476 * Note that the "headerbuf" is just a place to return the result. Its
477 * contents are not used for the next call. This means that no cleanup
478 * is needed when ie doing another connection, just call the cleanup when
479 * fully done to deallocate memory.
480 */
481
482/* Limit the max number of continuation lines to some reasonable value */
483#define HTTP_MAX_CONT_LINES 10
484
485/* Place into which to build a header from one or several lines */
486typedef struct {
487	char	*buf;		/* buffer */
488	size_t	 bufsize;	/* buffer size */
489	size_t	 buflen;	/* length of buffer contents */
490} http_headerbuf_t;
491
492static void
493init_http_headerbuf(http_headerbuf_t *buf)
494{
495	buf->buf = NULL;
496	buf->bufsize = 0;
497	buf->buflen = 0;
498}
499
500static void
501clean_http_headerbuf(http_headerbuf_t *buf)
502{
503	if (buf->buf)
504		free(buf->buf);
505	init_http_headerbuf(buf);
506}
507
508/* Remove whitespace at the end of the buffer */
509static void
510http_conn_trimright(conn_t *conn)
511{
512	while (conn->buflen &&
513	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
514		conn->buflen--;
515	conn->buf[conn->buflen] = '\0';
516}
517
518static hdr_t
519http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
520{
521	unsigned int i, len;
522
523	/*
524	 * Have to do the stripping here because of the first line. So
525	 * it's done twice for the subsequent lines. No big deal
526	 */
527	http_conn_trimright(conn);
528	if (conn->buflen == 0)
529		return (hdr_end);
530
531	/* Copy the line to the headerbuf */
532	if (hbuf->bufsize < conn->buflen + 1) {
533		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
534			return (hdr_syserror);
535		hbuf->bufsize = conn->buflen + 1;
536	}
537	strcpy(hbuf->buf, conn->buf);
538	hbuf->buflen = conn->buflen;
539
540	/*
541	 * Fetch possible continuation lines. Stop at 1st non-continuation
542	 * and leave it in the conn buffer
543	 */
544	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
545		if (fetch_getln(conn) == -1)
546			return (hdr_syserror);
547
548		/*
549		 * Note: we carry on the idea from the previous version
550		 * that a pure whitespace line is equivalent to an empty
551		 * one (so it's not continuation and will be handled when
552		 * we are called next)
553		 */
554		http_conn_trimright(conn);
555		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
556			break;
557
558		/* Got a continuation line. Concatenate to previous */
559		len = hbuf->buflen + conn->buflen;
560		if (hbuf->bufsize < len + 1) {
561			len *= 2;
562			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
563				return (hdr_syserror);
564			hbuf->bufsize = len + 1;
565		}
566		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
567		hbuf->buflen += conn->buflen;
568	}
569
570	/*
571	 * We could check for malformed headers but we don't really care.
572	 * A valid header starts with a token immediately followed by a
573	 * colon; a token is any sequence of non-control, non-whitespace
574	 * characters except "()<>@,;:\\\"{}".
575	 */
576	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
577		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
578			return (hdr_names[i].num);
579
580	return (hdr_unknown);
581}
582
583/**************************
584 * [Proxy-]Authenticate header parsing
585 */
586
587/*
588 * Read doublequote-delimited string into output buffer obuf (allocated
589 * by caller, whose responsibility it is to ensure that it's big enough)
590 * cp points to the first char after the initial '"'
591 * Handles \ quoting
592 * Returns pointer to the first char after the terminating double quote, or
593 * NULL for error.
594 */
595static const char *
596http_parse_headerstring(const char *cp, char *obuf)
597{
598	for (;;) {
599		switch (*cp) {
600		case 0: /* Unterminated string */
601			*obuf = 0;
602			return (NULL);
603		case '"': /* Ending quote */
604			*obuf = 0;
605			return (++cp);
606		case '\\':
607			if (*++cp == 0) {
608				*obuf = 0;
609				return (NULL);
610			}
611			/* FALLTHROUGH */
612		default:
613			*obuf++ = *cp++;
614		}
615	}
616}
617
618/* Http auth challenge schemes */
619typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
620
621/* Data holder for a Basic or Digest challenge. */
622typedef struct {
623	http_auth_schemes_t scheme;
624	char	*realm;
625	char	*qop;
626	char	*nonce;
627	char	*opaque;
628	char	*algo;
629	int	 stale;
630	int	 nc; /* Nonce count */
631} http_auth_challenge_t;
632
633static void
634init_http_auth_challenge(http_auth_challenge_t *b)
635{
636	b->scheme = HTTPAS_UNKNOWN;
637	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
638	b->stale = b->nc = 0;
639}
640
641static void
642clean_http_auth_challenge(http_auth_challenge_t *b)
643{
644	if (b->realm)
645		free(b->realm);
646	if (b->qop)
647		free(b->qop);
648	if (b->nonce)
649		free(b->nonce);
650	if (b->opaque)
651		free(b->opaque);
652	if (b->algo)
653		free(b->algo);
654	init_http_auth_challenge(b);
655}
656
657/* Data holder for an array of challenges offered in an http response. */
658#define MAX_CHALLENGES 10
659typedef struct {
660	http_auth_challenge_t *challenges[MAX_CHALLENGES];
661	int	count; /* Number of parsed challenges in the array */
662	int	valid; /* We did parse an authenticate header */
663} http_auth_challenges_t;
664
665static void
666init_http_auth_challenges(http_auth_challenges_t *cs)
667{
668	int i;
669	for (i = 0; i < MAX_CHALLENGES; i++)
670		cs->challenges[i] = NULL;
671	cs->count = cs->valid = 0;
672}
673
674static void
675clean_http_auth_challenges(http_auth_challenges_t *cs)
676{
677	int i;
678	/* We rely on non-zero pointers being allocated, not on the count */
679	for (i = 0; i < MAX_CHALLENGES; i++) {
680		if (cs->challenges[i] != NULL) {
681			clean_http_auth_challenge(cs->challenges[i]);
682			free(cs->challenges[i]);
683		}
684	}
685	init_http_auth_challenges(cs);
686}
687
688/*
689 * Enumeration for lexical elements. Separators will be returned as their own
690 * ascii value
691 */
692typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
693	      HTTPHL_ERROR = 259} http_header_lex_t;
694
695/*
696 * Determine what kind of token comes next and return possible value
697 * in buf, which is supposed to have been allocated big enough by
698 * caller. Advance input pointer and return element type.
699 */
700static int
701http_header_lex(const char **cpp, char *buf)
702{
703	size_t l;
704	/* Eat initial whitespace */
705	*cpp += strspn(*cpp, " \t");
706	if (**cpp == 0)
707		return (HTTPHL_END);
708
709	/* Separator ? */
710	if (**cpp == ',' || **cpp == '=')
711		return (*((*cpp)++));
712
713	/* String ? */
714	if (**cpp == '"') {
715		*cpp = http_parse_headerstring(++*cpp, buf);
716		if (*cpp == NULL)
717			return (HTTPHL_ERROR);
718		return (HTTPHL_STRING);
719	}
720
721	/* Read other token, until separator or whitespace */
722	l = strcspn(*cpp, " \t,=");
723	memcpy(buf, *cpp, l);
724	buf[l] = 0;
725	*cpp += l;
726	return (HTTPHL_WORD);
727}
728
729/*
730 * Read challenges from http xxx-authenticate header and accumulate them
731 * in the challenges list structure.
732 *
733 * Headers with multiple challenges are specified by rfc2617, but
734 * servers (ie: squid) often send them in separate headers instead,
735 * which in turn is forbidden by the http spec (multiple headers with
736 * the same name are only allowed for pure comma-separated lists, see
737 * rfc2616 sec 4.2).
738 *
739 * We support both approaches anyway
740 */
741static int
742http_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
743{
744	int ret = -1;
745	http_header_lex_t lex;
746	char *key = malloc(strlen(cp) + 1);
747	char *value = malloc(strlen(cp) + 1);
748	char *buf = malloc(strlen(cp) + 1);
749
750	if (key == NULL || value == NULL || buf == NULL) {
751		fetch_syserr();
752		goto out;
753	}
754
755	/* In any case we've seen the header and we set the valid bit */
756	cs->valid = 1;
757
758	/* Need word first */
759	lex = http_header_lex(&cp, key);
760	if (lex != HTTPHL_WORD)
761		goto out;
762
763	/* Loop on challenges */
764	for (; cs->count < MAX_CHALLENGES; cs->count++) {
765		cs->challenges[cs->count] =
766			malloc(sizeof(http_auth_challenge_t));
767		if (cs->challenges[cs->count] == NULL) {
768			fetch_syserr();
769			goto out;
770		}
771		init_http_auth_challenge(cs->challenges[cs->count]);
772		if (!strcasecmp(key, "basic")) {
773			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
774		} else if (!strcasecmp(key, "digest")) {
775			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
776		} else {
777			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
778			/*
779			 * Continue parsing as basic or digest may
780			 * follow, and the syntax is the same for
781			 * all. We'll just ignore this one when
782			 * looking at the list
783			 */
784		}
785
786		/* Loop on attributes */
787		for (;;) {
788			/* Key */
789			lex = http_header_lex(&cp, key);
790			if (lex != HTTPHL_WORD)
791				goto out;
792
793			/* Equal sign */
794			lex = http_header_lex(&cp, buf);
795			if (lex != '=')
796				goto out;
797
798			/* Value */
799			lex = http_header_lex(&cp, value);
800			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
801				goto out;
802
803			if (!strcasecmp(key, "realm"))
804				cs->challenges[cs->count]->realm =
805					strdup(value);
806			else if (!strcasecmp(key, "qop"))
807				cs->challenges[cs->count]->qop =
808					strdup(value);
809			else if (!strcasecmp(key, "nonce"))
810				cs->challenges[cs->count]->nonce =
811					strdup(value);
812			else if (!strcasecmp(key, "opaque"))
813				cs->challenges[cs->count]->opaque =
814					strdup(value);
815			else if (!strcasecmp(key, "algorithm"))
816				cs->challenges[cs->count]->algo =
817					strdup(value);
818			else if (!strcasecmp(key, "stale"))
819				cs->challenges[cs->count]->stale =
820					strcasecmp(value, "no");
821			/* Else ignore unknown attributes */
822
823			/* Comma or Next challenge or End */
824			lex = http_header_lex(&cp, key);
825			/*
826			 * If we get a word here, this is the beginning of the
827			 * next challenge. Break the attributes loop
828			 */
829			if (lex == HTTPHL_WORD)
830				break;
831
832			if (lex == HTTPHL_END) {
833				/* End while looking for ',' is normal exit */
834				cs->count++;
835				ret = 0;
836				goto out;
837			}
838			/* Anything else is an error */
839			if (lex != ',')
840				goto out;
841
842		} /* End attributes loop */
843	} /* End challenge loop */
844
845	/*
846	 * Challenges max count exceeded. This really can't happen
847	 * with normal data, something's fishy -> error
848	 */
849
850out:
851	if (key)
852		free(key);
853	if (value)
854		free(value);
855	if (buf)
856		free(buf);
857	return (ret);
858}
859
860
861/*
862 * Parse a last-modified header
863 */
864static int
865http_parse_mtime(const char *p, time_t *mtime)
866{
867	char locale[64], *r;
868	struct tm tm;
869
870	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
871	setlocale(LC_TIME, "C");
872	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
873	/* XXX should add support for date-2 and date-3 */
874	setlocale(LC_TIME, locale);
875	if (r == NULL)
876		return (-1);
877	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
878		  "%02d:%02d:%02d]\n",
879		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
880		  tm.tm_hour, tm.tm_min, tm.tm_sec));
881	*mtime = timegm(&tm);
882	return (0);
883}
884
885/*
886 * Parse a content-length header
887 */
888static int
889http_parse_length(const char *p, off_t *length)
890{
891	off_t len;
892
893	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
894		len = len * 10 + (*p - '0');
895	if (*p)
896		return (-1);
897	DEBUG(fprintf(stderr, "content length: [%lld]\n",
898	    (long long)len));
899	*length = len;
900	return (0);
901}
902
903/*
904 * Parse a content-range header
905 */
906static int
907http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
908{
909	off_t first, last, len;
910
911	if (strncasecmp(p, "bytes ", 6) != 0)
912		return (-1);
913	p += 6;
914	if (*p == '*') {
915		first = last = -1;
916		++p;
917	} else {
918		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
919			first = first * 10 + *p - '0';
920		if (*p != '-')
921			return (-1);
922		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
923			last = last * 10 + *p - '0';
924	}
925	if (first > last || *p != '/')
926		return (-1);
927	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
928		len = len * 10 + *p - '0';
929	if (*p || len < last - first + 1)
930		return (-1);
931	if (first == -1) {
932		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
933		    (long long)len));
934		*length = 0;
935	} else {
936		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
937		    (long long)first, (long long)last, (long long)len));
938		*length = last - first + 1;
939	}
940	*offset = first;
941	*size = len;
942	return (0);
943}
944
945
946/*****************************************************************************
947 * Helper functions for authorization
948 */
949
950/*
951 * Base64 encoding
952 */
953static char *
954http_base64(const char *src)
955{
956	static const char base64[] =
957	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
958	    "abcdefghijklmnopqrstuvwxyz"
959	    "0123456789+/";
960	char *str, *dst;
961	size_t l;
962	int t, r;
963
964	l = strlen(src);
965	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
966		return (NULL);
967	dst = str;
968	r = 0;
969
970	while (l >= 3) {
971		t = (src[0] << 16) | (src[1] << 8) | src[2];
972		dst[0] = base64[(t >> 18) & 0x3f];
973		dst[1] = base64[(t >> 12) & 0x3f];
974		dst[2] = base64[(t >> 6) & 0x3f];
975		dst[3] = base64[(t >> 0) & 0x3f];
976		src += 3; l -= 3;
977		dst += 4; r += 4;
978	}
979
980	switch (l) {
981	case 2:
982		t = (src[0] << 16) | (src[1] << 8);
983		dst[0] = base64[(t >> 18) & 0x3f];
984		dst[1] = base64[(t >> 12) & 0x3f];
985		dst[2] = base64[(t >> 6) & 0x3f];
986		dst[3] = '=';
987		dst += 4;
988		r += 4;
989		break;
990	case 1:
991		t = src[0] << 16;
992		dst[0] = base64[(t >> 18) & 0x3f];
993		dst[1] = base64[(t >> 12) & 0x3f];
994		dst[2] = dst[3] = '=';
995		dst += 4;
996		r += 4;
997		break;
998	case 0:
999		break;
1000	}
1001
1002	*dst = 0;
1003	return (str);
1004}
1005
1006
1007/*
1008 * Extract authorization parameters from environment value.
1009 * The value is like scheme:realm:user:pass
1010 */
1011typedef struct {
1012	char	*scheme;
1013	char	*realm;
1014	char	*user;
1015	char	*password;
1016} http_auth_params_t;
1017
1018static void
1019init_http_auth_params(http_auth_params_t *s)
1020{
1021	s->scheme = s->realm = s->user = s->password = 0;
1022}
1023
1024static void
1025clean_http_auth_params(http_auth_params_t *s)
1026{
1027	if (s->scheme)
1028		free(s->scheme);
1029	if (s->realm)
1030		free(s->realm);
1031	if (s->user)
1032		free(s->user);
1033	if (s->password)
1034		free(s->password);
1035	init_http_auth_params(s);
1036}
1037
1038static int
1039http_authfromenv(const char *p, http_auth_params_t *parms)
1040{
1041	int ret = -1;
1042	char *v, *ve;
1043	char *str = strdup(p);
1044
1045	if (str == NULL) {
1046		fetch_syserr();
1047		return (-1);
1048	}
1049	v = str;
1050
1051	if ((ve = strchr(v, ':')) == NULL)
1052		goto out;
1053
1054	*ve = 0;
1055	if ((parms->scheme = strdup(v)) == NULL) {
1056		fetch_syserr();
1057		goto out;
1058	}
1059	v = ve + 1;
1060
1061	if ((ve = strchr(v, ':')) == NULL)
1062		goto out;
1063
1064	*ve = 0;
1065	if ((parms->realm = strdup(v)) == NULL) {
1066		fetch_syserr();
1067		goto out;
1068	}
1069	v = ve + 1;
1070
1071	if ((ve = strchr(v, ':')) == NULL)
1072		goto out;
1073
1074	*ve = 0;
1075	if ((parms->user = strdup(v)) == NULL) {
1076		fetch_syserr();
1077		goto out;
1078	}
1079	v = ve + 1;
1080
1081
1082	if ((parms->password = strdup(v)) == NULL) {
1083		fetch_syserr();
1084		goto out;
1085	}
1086	ret = 0;
1087out:
1088	if (ret == -1)
1089		clean_http_auth_params(parms);
1090	if (str)
1091		free(str);
1092	return (ret);
1093}
1094
1095
1096/*
1097 * Digest response: the code to compute the digest is taken from the
1098 * sample implementation in RFC2616
1099 */
1100#define IN const
1101#define OUT
1102
1103#define HASHLEN 16
1104typedef char HASH[HASHLEN];
1105#define HASHHEXLEN 32
1106typedef char HASHHEX[HASHHEXLEN+1];
1107
1108static const char *hexchars = "0123456789abcdef";
1109static void
1110CvtHex(IN HASH Bin, OUT HASHHEX Hex)
1111{
1112	unsigned short i;
1113	unsigned char j;
1114
1115	for (i = 0; i < HASHLEN; i++) {
1116		j = (Bin[i] >> 4) & 0xf;
1117		Hex[i*2] = hexchars[j];
1118		j = Bin[i] & 0xf;
1119		Hex[i*2+1] = hexchars[j];
1120	};
1121	Hex[HASHHEXLEN] = '\0';
1122};
1123
1124/* calculate H(A1) as per spec */
1125static void
1126DigestCalcHA1(
1127	IN char * pszAlg,
1128	IN char * pszUserName,
1129	IN char * pszRealm,
1130	IN char * pszPassword,
1131	IN char * pszNonce,
1132	IN char * pszCNonce,
1133	OUT HASHHEX SessionKey
1134	)
1135{
1136	MD5_CTX Md5Ctx;
1137	HASH HA1;
1138
1139	MD5Init(&Md5Ctx);
1140	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1141	MD5Update(&Md5Ctx, ":", 1);
1142	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1143	MD5Update(&Md5Ctx, ":", 1);
1144	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1145	MD5Final(HA1, &Md5Ctx);
1146	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1147
1148		MD5Init(&Md5Ctx);
1149		MD5Update(&Md5Ctx, HA1, HASHLEN);
1150		MD5Update(&Md5Ctx, ":", 1);
1151		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1152		MD5Update(&Md5Ctx, ":", 1);
1153		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1154		MD5Final(HA1, &Md5Ctx);
1155	};
1156	CvtHex(HA1, SessionKey);
1157}
1158
1159/* calculate request-digest/response-digest as per HTTP Digest spec */
1160static void
1161DigestCalcResponse(
1162	IN HASHHEX HA1,           /* H(A1) */
1163	IN char * pszNonce,       /* nonce from server */
1164	IN char * pszNonceCount,  /* 8 hex digits */
1165	IN char * pszCNonce,      /* client nonce */
1166	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1167	IN char * pszMethod,      /* method from the request */
1168	IN char * pszDigestUri,   /* requested URL */
1169	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1170	OUT HASHHEX Response      /* request-digest or response-digest */
1171	)
1172{
1173/*	DEBUG(fprintf(stderr,
1174		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1175		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1176	MD5_CTX Md5Ctx;
1177	HASH HA2;
1178	HASH RespHash;
1179	HASHHEX HA2Hex;
1180
1181	// calculate H(A2)
1182	MD5Init(&Md5Ctx);
1183	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1184	MD5Update(&Md5Ctx, ":", 1);
1185	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1186	if (strcasecmp(pszQop, "auth-int") == 0) {
1187		MD5Update(&Md5Ctx, ":", 1);
1188		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1189	};
1190	MD5Final(HA2, &Md5Ctx);
1191	CvtHex(HA2, HA2Hex);
1192
1193	// calculate response
1194	MD5Init(&Md5Ctx);
1195	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1196	MD5Update(&Md5Ctx, ":", 1);
1197	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1198	MD5Update(&Md5Ctx, ":", 1);
1199	if (*pszQop) {
1200		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1201		MD5Update(&Md5Ctx, ":", 1);
1202		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1203		MD5Update(&Md5Ctx, ":", 1);
1204		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1205		MD5Update(&Md5Ctx, ":", 1);
1206	};
1207	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1208	MD5Final(RespHash, &Md5Ctx);
1209	CvtHex(RespHash, Response);
1210}
1211
1212/*
1213 * Generate/Send a Digest authorization header
1214 * This looks like: [Proxy-]Authorization: credentials
1215 *
1216 *  credentials      = "Digest" digest-response
1217 *  digest-response  = 1#( username | realm | nonce | digest-uri
1218 *                      | response | [ algorithm ] | [cnonce] |
1219 *                      [opaque] | [message-qop] |
1220 *                          [nonce-count]  | [auth-param] )
1221 *  username         = "username" "=" username-value
1222 *  username-value   = quoted-string
1223 *  digest-uri       = "uri" "=" digest-uri-value
1224 *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1225 *  message-qop      = "qop" "=" qop-value
1226 *  cnonce           = "cnonce" "=" cnonce-value
1227 *  cnonce-value     = nonce-value
1228 *  nonce-count      = "nc" "=" nc-value
1229 *  nc-value         = 8LHEX
1230 *  response         = "response" "=" request-digest
1231 *  request-digest = <"> 32LHEX <">
1232 */
1233static int
1234http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1235		 http_auth_params_t *parms, struct url *url)
1236{
1237	int r;
1238	char noncecount[10];
1239	char cnonce[40];
1240	char *options = 0;
1241
1242	if (!c->realm || !c->nonce) {
1243		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1244		return(-1);
1245	}
1246	if (!c->algo)
1247		c->algo = strdup("");
1248
1249	if (asprintf(&options, "%s%s%s%s",
1250		     *c->algo? ",algorithm=" : "", c->algo,
1251		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1252		return (-1);
1253
1254	if (!c->qop) {
1255		c->qop = strdup("");
1256		*noncecount = 0;
1257		*cnonce = 0;
1258	} else {
1259		c->nc++;
1260		sprintf(noncecount, "%08x", c->nc);
1261		/* We don't try very hard with the cnonce ... */
1262		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1263	}
1264
1265	HASHHEX HA1;
1266	DigestCalcHA1(c->algo, parms->user, c->realm,
1267		      parms->password, c->nonce, cnonce, HA1);
1268	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1269	HASHHEX digest;
1270	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1271			   "GET", url->doc, "", digest);
1272
1273	if (c->qop[0]) {
1274		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1275			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1276			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1277			     hdr, parms->user, c->realm,
1278			     c->nonce, url->doc, digest,
1279			     cnonce, noncecount, options);
1280	} else {
1281		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1282			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1283			     hdr, parms->user, c->realm,
1284			     c->nonce, url->doc, digest, options);
1285	}
1286	if (options)
1287		free(options);
1288	return (r);
1289}
1290
1291/*
1292 * Encode username and password
1293 */
1294static int
1295http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1296{
1297	char *upw, *auth;
1298	int r;
1299
1300	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1301	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
1302	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
1303		return (-1);
1304	auth = http_base64(upw);
1305	free(upw);
1306	if (auth == NULL)
1307		return (-1);
1308	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
1309	free(auth);
1310	return (r);
1311}
1312
1313/*
1314 * Chose the challenge to answer and call the appropriate routine to
1315 * produce the header.
1316 */
1317static int
1318http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1319	       http_auth_params_t *parms, struct url *url)
1320{
1321	http_auth_challenge_t *basic = NULL;
1322	http_auth_challenge_t *digest = NULL;
1323	int i;
1324
1325	/* If user or pass are null we're not happy */
1326	if (!parms->user || !parms->password) {
1327		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1328		return (-1);
1329	}
1330
1331	/* Look for a Digest and a Basic challenge */
1332	for (i = 0; i < cs->count; i++) {
1333		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1334			basic = cs->challenges[i];
1335		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1336			digest = cs->challenges[i];
1337	}
1338
1339	/* Error if "Digest" was specified and there is no Digest challenge */
1340	if (!digest && (parms->scheme &&
1341			!strcasecmp(parms->scheme, "digest"))) {
1342		DEBUG(fprintf(stderr,
1343			      "Digest auth in env, not supported by peer\n"));
1344		return (-1);
1345	}
1346	/*
1347	 * If "basic" was specified in the environment, or there is no Digest
1348	 * challenge, do the basic thing. Don't need a challenge for this,
1349	 * so no need to check basic!=NULL
1350	 */
1351	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1352		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1353
1354	/* Else, prefer digest. We just checked that it's not NULL */
1355	return (http_digest_auth(conn, hdr, digest, parms, url));
1356}
1357
1358/*****************************************************************************
1359 * Helper functions for connecting to a server or proxy
1360 */
1361
1362/*
1363 * Connect to the correct HTTP server or proxy.
1364 */
1365static conn_t *
1366http_connect(struct url *URL, struct url *purl, const char *flags)
1367{
1368	conn_t *conn;
1369	int verbose;
1370	int af, val;
1371
1372#ifdef INET6
1373	af = AF_UNSPEC;
1374#else
1375	af = AF_INET;
1376#endif
1377
1378	verbose = CHECK_FLAG('v');
1379	if (CHECK_FLAG('4'))
1380		af = AF_INET;
1381#ifdef INET6
1382	else if (CHECK_FLAG('6'))
1383		af = AF_INET6;
1384#endif
1385
1386	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
1387		URL = purl;
1388	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
1389		/* can't talk http to an ftp server */
1390		/* XXX should set an error code */
1391		return (NULL);
1392	}
1393
1394	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1395		/* fetch_connect() has already set an error code */
1396		return (NULL);
1397	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1398	    fetch_ssl(conn, verbose) == -1) {
1399		fetch_close(conn);
1400		/* grrr */
1401		errno = EAUTH;
1402		fetch_syserr();
1403		return (NULL);
1404	}
1405
1406	val = 1;
1407	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1408
1409	return (conn);
1410}
1411
1412static struct url *
1413http_get_proxy(struct url * url, const char *flags)
1414{
1415	struct url *purl;
1416	char *p;
1417
1418	if (flags != NULL && strchr(flags, 'd') != NULL)
1419		return (NULL);
1420	if (fetch_no_proxy_match(url->host))
1421		return (NULL);
1422	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1423	    *p && (purl = fetchParseURL(p))) {
1424		if (!*purl->scheme)
1425			strcpy(purl->scheme, SCHEME_HTTP);
1426		if (!purl->port)
1427			purl->port = fetch_default_proxy_port(purl->scheme);
1428		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1429			return (purl);
1430		fetchFreeURL(purl);
1431	}
1432	return (NULL);
1433}
1434
1435static void
1436http_print_html(FILE *out, FILE *in)
1437{
1438	size_t len;
1439	char *line, *p, *q;
1440	int comment, tag;
1441
1442	comment = tag = 0;
1443	while ((line = fgetln(in, &len)) != NULL) {
1444		while (len && isspace((unsigned char)line[len - 1]))
1445			--len;
1446		for (p = q = line; q < line + len; ++q) {
1447			if (comment && *q == '-') {
1448				if (q + 2 < line + len &&
1449				    strcmp(q, "-->") == 0) {
1450					tag = comment = 0;
1451					q += 2;
1452				}
1453			} else if (tag && !comment && *q == '>') {
1454				p = q + 1;
1455				tag = 0;
1456			} else if (!tag && *q == '<') {
1457				if (q > p)
1458					fwrite(p, q - p, 1, out);
1459				tag = 1;
1460				if (q + 3 < line + len &&
1461				    strcmp(q, "<!--") == 0) {
1462					comment = 1;
1463					q += 3;
1464				}
1465			}
1466		}
1467		if (!tag && q > p)
1468			fwrite(p, q - p, 1, out);
1469		fputc('\n', out);
1470	}
1471}
1472
1473
1474/*****************************************************************************
1475 * Core
1476 */
1477
1478/*
1479 * Send a request and process the reply
1480 *
1481 * XXX This function is way too long, the do..while loop should be split
1482 * XXX off into a separate function.
1483 */
1484FILE *
1485http_request(struct url *URL, const char *op, struct url_stat *us,
1486	struct url *purl, const char *flags)
1487{
1488	char timebuf[80];
1489	char hbuf[MAXHOSTNAMELEN + 7], *host;
1490	conn_t *conn;
1491	struct url *url, *new;
1492	int chunked, direct, ims, noredirect, verbose;
1493	int e, i, n, val;
1494	off_t offset, clength, length, size;
1495	time_t mtime;
1496	const char *p;
1497	FILE *f;
1498	hdr_t h;
1499	struct tm *timestruct;
1500	http_headerbuf_t headerbuf;
1501	http_auth_challenges_t server_challenges;
1502	http_auth_challenges_t proxy_challenges;
1503
1504	/* The following calls don't allocate anything */
1505	init_http_headerbuf(&headerbuf);
1506	init_http_auth_challenges(&server_challenges);
1507	init_http_auth_challenges(&proxy_challenges);
1508
1509	direct = CHECK_FLAG('d');
1510	noredirect = CHECK_FLAG('A');
1511	verbose = CHECK_FLAG('v');
1512	ims = CHECK_FLAG('i');
1513
1514	if (direct && purl) {
1515		fetchFreeURL(purl);
1516		purl = NULL;
1517	}
1518
1519	/* try the provided URL first */
1520	url = URL;
1521
1522	n = MAX_REDIRECT;
1523	i = 0;
1524
1525	e = HTTP_PROTOCOL_ERROR;
1526	do {
1527		new = NULL;
1528		chunked = 0;
1529		offset = 0;
1530		clength = -1;
1531		length = -1;
1532		size = -1;
1533		mtime = 0;
1534
1535		/* check port */
1536		if (!url->port)
1537			url->port = fetch_default_port(url->scheme);
1538
1539		/* were we redirected to an FTP URL? */
1540		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1541			if (strcmp(op, "GET") == 0)
1542				return (ftp_request(url, "RETR", us, purl, flags));
1543			else if (strcmp(op, "HEAD") == 0)
1544				return (ftp_request(url, "STAT", us, purl, flags));
1545		}
1546
1547		/* connect to server or proxy */
1548		if ((conn = http_connect(url, purl, flags)) == NULL)
1549			goto ouch;
1550
1551		host = url->host;
1552#ifdef INET6
1553		if (strchr(url->host, ':')) {
1554			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
1555			host = hbuf;
1556		}
1557#endif
1558		if (url->port != fetch_default_port(url->scheme)) {
1559			if (host != hbuf) {
1560				strcpy(hbuf, host);
1561				host = hbuf;
1562			}
1563			snprintf(hbuf + strlen(hbuf),
1564			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1565		}
1566
1567		/* send request */
1568		if (verbose)
1569			fetch_info("requesting %s://%s%s",
1570			    url->scheme, host, url->doc);
1571		if (purl) {
1572			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1573			    op, url->scheme, host, url->doc);
1574		} else {
1575			http_cmd(conn, "%s %s HTTP/1.1",
1576			    op, url->doc);
1577		}
1578
1579		if (ims && url->ims_time) {
1580			timestruct = gmtime((time_t *)&url->ims_time);
1581			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1582			    timestruct);
1583			if (verbose)
1584				fetch_info("If-Modified-Since: %s", timebuf);
1585			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1586		}
1587		/* virtual host */
1588		http_cmd(conn, "Host: %s", host);
1589
1590		/*
1591		 * Proxy authorization: we only send auth after we received
1592		 * a 407 error. We do not first try basic anyway (changed
1593		 * when support was added for digest-auth)
1594		 */
1595		if (purl && proxy_challenges.valid) {
1596			http_auth_params_t aparams;
1597			init_http_auth_params(&aparams);
1598			if (*purl->user || *purl->pwd) {
1599				aparams.user = purl->user ?
1600					strdup(purl->user) : strdup("");
1601				aparams.password = purl->pwd?
1602					strdup(purl->pwd) : strdup("");
1603			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1604				   *p != '\0') {
1605				if (http_authfromenv(p, &aparams) < 0) {
1606					http_seterr(HTTP_NEED_PROXY_AUTH);
1607					goto ouch;
1608				}
1609			}
1610			http_authorize(conn, "Proxy-Authorization",
1611				       &proxy_challenges, &aparams, url);
1612			clean_http_auth_params(&aparams);
1613		}
1614
1615		/*
1616		 * Server authorization: we never send "a priori"
1617		 * Basic auth, which used to be done if user/pass were
1618		 * set in the url. This would be weird because we'd send the
1619		 * password in the clear even if Digest is finally to be
1620		 * used (it would have made more sense for the
1621		 * pre-digest version to do this when Basic was specified
1622		 * in the environment)
1623		 */
1624		if (server_challenges.valid) {
1625			http_auth_params_t aparams;
1626			init_http_auth_params(&aparams);
1627			if (*url->user || *url->pwd) {
1628				aparams.user = url->user ?
1629					strdup(url->user) : strdup("");
1630				aparams.password = url->pwd ?
1631					strdup(url->pwd) : strdup("");
1632			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1633				   *p != '\0') {
1634				if (http_authfromenv(p, &aparams) < 0) {
1635					http_seterr(HTTP_NEED_AUTH);
1636					goto ouch;
1637				}
1638			} else if (fetchAuthMethod &&
1639				   fetchAuthMethod(url) == 0) {
1640				aparams.user = url->user ?
1641					strdup(url->user) : strdup("");
1642				aparams.password = url->pwd ?
1643					strdup(url->pwd) : strdup("");
1644			} else {
1645				http_seterr(HTTP_NEED_AUTH);
1646				goto ouch;
1647			}
1648			http_authorize(conn, "Authorization",
1649				       &server_challenges, &aparams, url);
1650			clean_http_auth_params(&aparams);
1651		}
1652
1653		/* other headers */
1654		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1655			if (strcasecmp(p, "auto") == 0)
1656				http_cmd(conn, "Referer: %s://%s%s",
1657				    url->scheme, host, url->doc);
1658			else
1659				http_cmd(conn, "Referer: %s", p);
1660		}
1661		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1662			http_cmd(conn, "User-Agent: %s", p);
1663		else
1664			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1665		if (url->offset > 0)
1666			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1667		http_cmd(conn, "Connection: close");
1668		http_cmd(conn, "");
1669
1670		/*
1671		 * Force the queued request to be dispatched.  Normally, one
1672		 * would do this with shutdown(2) but squid proxies can be
1673		 * configured to disallow such half-closed connections.  To
1674		 * be compatible with such configurations, fiddle with socket
1675		 * options to force the pending data to be written.
1676		 */
1677		val = 0;
1678		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1679			   sizeof(val));
1680		val = 1;
1681		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1682			   sizeof(val));
1683
1684		/* get reply */
1685		switch (http_get_reply(conn)) {
1686		case HTTP_OK:
1687		case HTTP_PARTIAL:
1688		case HTTP_NOT_MODIFIED:
1689			/* fine */
1690			break;
1691		case HTTP_MOVED_PERM:
1692		case HTTP_MOVED_TEMP:
1693		case HTTP_SEE_OTHER:
1694		case HTTP_USE_PROXY:
1695			/*
1696			 * Not so fine, but we still have to read the
1697			 * headers to get the new location.
1698			 */
1699			break;
1700		case HTTP_NEED_AUTH:
1701			if (server_challenges.valid) {
1702				/*
1703				 * We already sent out authorization code,
1704				 * so there's nothing more we can do.
1705				 */
1706				http_seterr(conn->err);
1707				goto ouch;
1708			}
1709			/* try again, but send the password this time */
1710			if (verbose)
1711				fetch_info("server requires authorization");
1712			break;
1713		case HTTP_NEED_PROXY_AUTH:
1714			if (proxy_challenges.valid) {
1715				/*
1716				 * We already sent our proxy
1717				 * authorization code, so there's
1718				 * nothing more we can do. */
1719				http_seterr(conn->err);
1720				goto ouch;
1721			}
1722			/* try again, but send the password this time */
1723			if (verbose)
1724				fetch_info("proxy requires authorization");
1725			break;
1726		case HTTP_BAD_RANGE:
1727			/*
1728			 * This can happen if we ask for 0 bytes because
1729			 * we already have the whole file.  Consider this
1730			 * a success for now, and check sizes later.
1731			 */
1732			break;
1733		case HTTP_PROTOCOL_ERROR:
1734			/* fall through */
1735		case -1:
1736			fetch_syserr();
1737			goto ouch;
1738		default:
1739			http_seterr(conn->err);
1740			if (!verbose)
1741				goto ouch;
1742			/* fall through so we can get the full error message */
1743		}
1744
1745		/* get headers. http_next_header expects one line readahead */
1746		if (fetch_getln(conn) == -1) {
1747		    fetch_syserr();
1748		    goto ouch;
1749		}
1750		do {
1751		    switch ((h = http_next_header(conn, &headerbuf, &p))) {
1752			case hdr_syserror:
1753				fetch_syserr();
1754				goto ouch;
1755			case hdr_error:
1756				http_seterr(HTTP_PROTOCOL_ERROR);
1757				goto ouch;
1758			case hdr_content_length:
1759				http_parse_length(p, &clength);
1760				break;
1761			case hdr_content_range:
1762				http_parse_range(p, &offset, &length, &size);
1763				break;
1764			case hdr_last_modified:
1765				http_parse_mtime(p, &mtime);
1766				break;
1767			case hdr_location:
1768				if (!HTTP_REDIRECT(conn->err))
1769					break;
1770				/*
1771				 * if the A flag is set, we don't follow
1772				 * temporary redirects.
1773				 */
1774				if (noredirect &&
1775				    conn->err != HTTP_MOVED_PERM &&
1776				    conn->err != HTTP_PERM_REDIRECT &&
1777				    conn->err != HTTP_USE_PROXY) {
1778					n = 1;
1779					break;
1780                                }
1781				if (new)
1782					free(new);
1783				if (verbose)
1784					fetch_info("%d redirect to %s", conn->err, p);
1785				if (*p == '/')
1786					/* absolute path */
1787					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1788					    url->user, url->pwd);
1789				else
1790					new = fetchParseURL(p);
1791				if (new == NULL) {
1792					/* XXX should set an error code */
1793					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1794					goto ouch;
1795				}
1796
1797				/* Only copy credentials if the host matches */
1798				if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) {
1799					strcpy(new->user, url->user);
1800					strcpy(new->pwd, url->pwd);
1801				}
1802				new->offset = url->offset;
1803				new->length = url->length;
1804				break;
1805			case hdr_transfer_encoding:
1806				/* XXX weak test*/
1807				chunked = (strcasecmp(p, "chunked") == 0);
1808				break;
1809			case hdr_www_authenticate:
1810				if (conn->err != HTTP_NEED_AUTH)
1811					break;
1812				if (http_parse_authenticate(p, &server_challenges) == 0)
1813					++n;
1814				break;
1815			case hdr_proxy_authenticate:
1816				if (conn->err != HTTP_NEED_PROXY_AUTH)
1817					break;
1818				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1819					++n;
1820				break;
1821			case hdr_end:
1822				/* fall through */
1823			case hdr_unknown:
1824				/* ignore */
1825				break;
1826			}
1827		} while (h > hdr_end);
1828
1829		/* we need to provide authentication */
1830		if (conn->err == HTTP_NEED_AUTH ||
1831		    conn->err == HTTP_NEED_PROXY_AUTH) {
1832			e = conn->err;
1833			if ((conn->err == HTTP_NEED_AUTH &&
1834			     !server_challenges.valid) ||
1835			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1836			     !proxy_challenges.valid)) {
1837				/* 401/7 but no www/proxy-authenticate ?? */
1838				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1839				goto ouch;
1840			}
1841			fetch_close(conn);
1842			conn = NULL;
1843			continue;
1844		}
1845
1846		/* requested range not satisfiable */
1847		if (conn->err == HTTP_BAD_RANGE) {
1848			if (url->offset == size && url->length == 0) {
1849				/* asked for 0 bytes; fake it */
1850				offset = url->offset;
1851				clength = -1;
1852				conn->err = HTTP_OK;
1853				break;
1854			} else {
1855				http_seterr(conn->err);
1856				goto ouch;
1857			}
1858		}
1859
1860		/* we have a hit or an error */
1861		if (conn->err == HTTP_OK
1862		    || conn->err == HTTP_NOT_MODIFIED
1863		    || conn->err == HTTP_PARTIAL
1864		    || HTTP_ERROR(conn->err))
1865			break;
1866
1867		/* all other cases: we got a redirect */
1868		e = conn->err;
1869		clean_http_auth_challenges(&server_challenges);
1870		fetch_close(conn);
1871		conn = NULL;
1872		if (!new) {
1873			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1874			break;
1875		}
1876		if (url != URL)
1877			fetchFreeURL(url);
1878		url = new;
1879	} while (++i < n);
1880
1881	/* we failed, or ran out of retries */
1882	if (conn == NULL) {
1883		http_seterr(e);
1884		goto ouch;
1885	}
1886
1887	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1888		  " size %lld, clength %lld\n",
1889		  (long long)offset, (long long)length,
1890		  (long long)size, (long long)clength));
1891
1892	if (conn->err == HTTP_NOT_MODIFIED) {
1893		http_seterr(HTTP_NOT_MODIFIED);
1894		return (NULL);
1895	}
1896
1897	/* check for inconsistencies */
1898	if (clength != -1 && length != -1 && clength != length) {
1899		http_seterr(HTTP_PROTOCOL_ERROR);
1900		goto ouch;
1901	}
1902	if (clength == -1)
1903		clength = length;
1904	if (clength != -1)
1905		length = offset + clength;
1906	if (length != -1 && size != -1 && length != size) {
1907		http_seterr(HTTP_PROTOCOL_ERROR);
1908		goto ouch;
1909	}
1910	if (size == -1)
1911		size = length;
1912
1913	/* fill in stats */
1914	if (us) {
1915		us->size = size;
1916		us->atime = us->mtime = mtime;
1917	}
1918
1919	/* too far? */
1920	if (URL->offset > 0 && offset > URL->offset) {
1921		http_seterr(HTTP_PROTOCOL_ERROR);
1922		goto ouch;
1923	}
1924
1925	/* report back real offset and size */
1926	URL->offset = offset;
1927	URL->length = clength;
1928
1929	/* wrap it up in a FILE */
1930	if ((f = http_funopen(conn, chunked)) == NULL) {
1931		fetch_syserr();
1932		goto ouch;
1933	}
1934
1935	if (url != URL)
1936		fetchFreeURL(url);
1937	if (purl)
1938		fetchFreeURL(purl);
1939
1940	if (HTTP_ERROR(conn->err)) {
1941		http_print_html(stderr, f);
1942		fclose(f);
1943		f = NULL;
1944	}
1945	clean_http_headerbuf(&headerbuf);
1946	clean_http_auth_challenges(&server_challenges);
1947	clean_http_auth_challenges(&proxy_challenges);
1948	return (f);
1949
1950ouch:
1951	if (url != URL)
1952		fetchFreeURL(url);
1953	if (purl)
1954		fetchFreeURL(purl);
1955	if (conn != NULL)
1956		fetch_close(conn);
1957	clean_http_headerbuf(&headerbuf);
1958	clean_http_auth_challenges(&server_challenges);
1959	clean_http_auth_challenges(&proxy_challenges);
1960	return (NULL);
1961}
1962
1963
1964/*****************************************************************************
1965 * Entry points
1966 */
1967
1968/*
1969 * Retrieve and stat a file by HTTP
1970 */
1971FILE *
1972fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1973{
1974	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1975}
1976
1977/*
1978 * Retrieve a file by HTTP
1979 */
1980FILE *
1981fetchGetHTTP(struct url *URL, const char *flags)
1982{
1983	return (fetchXGetHTTP(URL, NULL, flags));
1984}
1985
1986/*
1987 * Store a file by HTTP
1988 */
1989FILE *
1990fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1991{
1992	warnx("fetchPutHTTP(): not implemented");
1993	return (NULL);
1994}
1995
1996/*
1997 * Get an HTTP document's metadata
1998 */
1999int
2000fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
2001{
2002	FILE *f;
2003
2004	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2005	if (f == NULL)
2006		return (-1);
2007	fclose(f);
2008	return (0);
2009}
2010
2011/*
2012 * List a directory
2013 */
2014struct url_ent *
2015fetchListHTTP(struct url *url __unused, const char *flags __unused)
2016{
2017	warnx("fetchListHTTP(): not implemented");
2018	return (NULL);
2019}
2020