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