http.c revision 174761
1/*-
2 * Copyright (c) 2000-2004 Dag-Erling Co�dan 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 174761 2007-12-19 00:26:36Z des $");
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
67#include <ctype.h>
68#include <err.h>
69#include <errno.h>
70#include <locale.h>
71#include <netdb.h>
72#include <stdarg.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <time.h>
77#include <unistd.h>
78
79#include <netinet/in.h>
80#include <netinet/tcp.h>
81
82#include "fetch.h"
83#include "common.h"
84#include "httperr.h"
85
86/* Maximum number of redirects to follow */
87#define MAX_REDIRECT 5
88
89/* Symbolic names for reply codes we care about */
90#define HTTP_OK			200
91#define HTTP_PARTIAL		206
92#define HTTP_MOVED_PERM		301
93#define HTTP_MOVED_TEMP		302
94#define HTTP_SEE_OTHER		303
95#define HTTP_TEMP_REDIRECT	307
96#define HTTP_NEED_AUTH		401
97#define HTTP_NEED_PROXY_AUTH	407
98#define HTTP_BAD_RANGE		416
99#define HTTP_PROTOCOL_ERROR	999
100
101#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
102			    || (xyz) == HTTP_MOVED_TEMP \
103			    || (xyz) == HTTP_TEMP_REDIRECT \
104			    || (xyz) == HTTP_SEE_OTHER)
105
106#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
107
108
109/*****************************************************************************
110 * I/O functions for decoding chunked streams
111 */
112
113struct httpio
114{
115	conn_t		*conn;		/* connection */
116	int		 chunked;	/* chunked mode */
117	char		*buf;		/* chunk buffer */
118	size_t		 bufsize;	/* size of chunk buffer */
119	ssize_t		 buflen;	/* amount of data currently in buffer */
120	int		 bufpos;	/* current read offset in buffer */
121	int		 eof;		/* end-of-file flag */
122	int		 error;		/* error flag */
123	size_t		 chunksize;	/* remaining size of current chunk */
124#ifndef NDEBUG
125	size_t		 total;
126#endif
127};
128
129/*
130 * Get next chunk header
131 */
132static int
133http_new_chunk(struct httpio *io)
134{
135	char *p;
136
137	if (fetch_getln(io->conn) == -1)
138		return (-1);
139
140	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
141		return (-1);
142
143	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
144		if (*p == ';')
145			break;
146		if (!isxdigit((unsigned char)*p))
147			return (-1);
148		if (isdigit((unsigned char)*p)) {
149			io->chunksize = io->chunksize * 16 +
150			    *p - '0';
151		} else {
152			io->chunksize = io->chunksize * 16 +
153			    10 + tolower(*p) - 'a';
154		}
155	}
156
157#ifndef NDEBUG
158	if (fetchDebug) {
159		io->total += io->chunksize;
160		if (io->chunksize == 0)
161			fprintf(stderr, "%s(): end of last chunk\n", __func__);
162		else
163			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
164			    __func__, (unsigned long)io->chunksize,
165			    (unsigned long)io->total);
166	}
167#endif
168
169	return (io->chunksize);
170}
171
172/*
173 * Grow the input buffer to at least len bytes
174 */
175static inline int
176http_growbuf(struct httpio *io, size_t len)
177{
178	char *tmp;
179
180	if (io->bufsize >= len)
181		return (0);
182
183	if ((tmp = realloc(io->buf, len)) == NULL)
184		return (-1);
185	io->buf = tmp;
186	io->bufsize = len;
187	return (0);
188}
189
190/*
191 * Fill the input buffer, do chunk decoding on the fly
192 */
193static int
194http_fillbuf(struct httpio *io, size_t len)
195{
196	if (io->error)
197		return (-1);
198	if (io->eof)
199		return (0);
200
201	if (io->chunked == 0) {
202		if (http_growbuf(io, len) == -1)
203			return (-1);
204		if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) {
205			io->error = 1;
206			return (-1);
207		}
208		io->bufpos = 0;
209		return (io->buflen);
210	}
211
212	if (io->chunksize == 0) {
213		switch (http_new_chunk(io)) {
214		case -1:
215			io->error = 1;
216			return (-1);
217		case 0:
218			io->eof = 1;
219			return (0);
220		}
221	}
222
223	if (len > io->chunksize)
224		len = io->chunksize;
225	if (http_growbuf(io, len) == -1)
226		return (-1);
227	if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) {
228		io->error = 1;
229		return (-1);
230	}
231	io->chunksize -= io->buflen;
232
233	if (io->chunksize == 0) {
234		char endl[2];
235
236		if (fetch_read(io->conn, endl, 2) != 2 ||
237		    endl[0] != '\r' || endl[1] != '\n')
238			return (-1);
239	}
240
241	io->bufpos = 0;
242
243	return (io->buflen);
244}
245
246/*
247 * Read function
248 */
249static int
250http_readfn(void *v, char *buf, int len)
251{
252	struct httpio *io = (struct httpio *)v;
253	int l, pos;
254
255	if (io->error)
256		return (-1);
257	if (io->eof)
258		return (0);
259
260	for (pos = 0; len > 0; pos += l, len -= l) {
261		/* empty buffer */
262		if (!io->buf || io->bufpos == io->buflen)
263			if (http_fillbuf(io, len) < 1)
264				break;
265		l = io->buflen - io->bufpos;
266		if (len < l)
267			l = len;
268		bcopy(io->buf + io->bufpos, buf + pos, l);
269		io->bufpos += l;
270	}
271
272	if (!pos && io->error)
273		return (-1);
274	return (pos);
275}
276
277/*
278 * Write function
279 */
280static int
281http_writefn(void *v, const char *buf, int len)
282{
283	struct httpio *io = (struct httpio *)v;
284
285	return (fetch_write(io->conn, buf, len));
286}
287
288/*
289 * Close function
290 */
291static int
292http_closefn(void *v)
293{
294	struct httpio *io = (struct httpio *)v;
295	int r;
296
297	r = fetch_close(io->conn);
298	if (io->buf)
299		free(io->buf);
300	free(io);
301	return (r);
302}
303
304/*
305 * Wrap a file descriptor up
306 */
307static FILE *
308http_funopen(conn_t *conn, int chunked)
309{
310	struct httpio *io;
311	FILE *f;
312
313	if ((io = calloc(1, sizeof(*io))) == NULL) {
314		fetch_syserr();
315		return (NULL);
316	}
317	io->conn = conn;
318	io->chunked = chunked;
319	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
320	if (f == NULL) {
321		fetch_syserr();
322		free(io);
323		return (NULL);
324	}
325	return (f);
326}
327
328
329/*****************************************************************************
330 * Helper functions for talking to the server and parsing its replies
331 */
332
333/* Header types */
334typedef enum {
335	hdr_syserror = -2,
336	hdr_error = -1,
337	hdr_end = 0,
338	hdr_unknown = 1,
339	hdr_content_length,
340	hdr_content_range,
341	hdr_last_modified,
342	hdr_location,
343	hdr_transfer_encoding,
344	hdr_www_authenticate
345} hdr_t;
346
347/* Names of interesting headers */
348static struct {
349	hdr_t		 num;
350	const char	*name;
351} hdr_names[] = {
352	{ hdr_content_length,		"Content-Length" },
353	{ hdr_content_range,		"Content-Range" },
354	{ hdr_last_modified,		"Last-Modified" },
355	{ hdr_location,			"Location" },
356	{ hdr_transfer_encoding,	"Transfer-Encoding" },
357	{ hdr_www_authenticate,		"WWW-Authenticate" },
358	{ hdr_unknown,			NULL },
359};
360
361/*
362 * Send a formatted line; optionally echo to terminal
363 */
364static int
365http_cmd(conn_t *conn, const char *fmt, ...)
366{
367	va_list ap;
368	size_t len;
369	char *msg;
370	int r;
371
372	va_start(ap, fmt);
373	len = vasprintf(&msg, fmt, ap);
374	va_end(ap);
375
376	if (msg == NULL) {
377		errno = ENOMEM;
378		fetch_syserr();
379		return (-1);
380	}
381
382	r = fetch_putln(conn, msg, len);
383	free(msg);
384
385	if (r == -1) {
386		fetch_syserr();
387		return (-1);
388	}
389
390	return (0);
391}
392
393/*
394 * Get and parse status line
395 */
396static int
397http_get_reply(conn_t *conn)
398{
399	char *p;
400
401	if (fetch_getln(conn) == -1)
402		return (-1);
403	/*
404	 * A valid status line looks like "HTTP/m.n xyz reason" where m
405	 * and n are the major and minor protocol version numbers and xyz
406	 * is the reply code.
407	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
408	 * just one) that do not send a version number, so we can't rely
409	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
410	 * We don't care about the reason phrase.
411	 */
412	if (strncmp(conn->buf, "HTTP", 4) != 0)
413		return (HTTP_PROTOCOL_ERROR);
414	p = conn->buf + 4;
415	if (*p == '/') {
416		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
417			return (HTTP_PROTOCOL_ERROR);
418		p += 4;
419	}
420	if (*p != ' ' ||
421	    !isdigit((unsigned char)p[1]) ||
422	    !isdigit((unsigned char)p[2]) ||
423	    !isdigit((unsigned char)p[3]))
424		return (HTTP_PROTOCOL_ERROR);
425
426	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
427	return (conn->err);
428}
429
430/*
431 * Check a header; if the type matches the given string, return a pointer
432 * to the beginning of the value.
433 */
434static const char *
435http_match(const char *str, const char *hdr)
436{
437	while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
438		/* nothing */;
439	if (*str || *hdr != ':')
440		return (NULL);
441	while (*hdr && isspace((unsigned char)*++hdr))
442		/* nothing */;
443	return (hdr);
444}
445
446/*
447 * Get the next header and return the appropriate symbolic code.
448 */
449static hdr_t
450http_next_header(conn_t *conn, const char **p)
451{
452	int i;
453
454	if (fetch_getln(conn) == -1)
455		return (hdr_syserror);
456	while (conn->buflen && isspace((unsigned char)conn->buf[conn->buflen - 1]))
457		conn->buflen--;
458	conn->buf[conn->buflen] = '\0';
459	if (conn->buflen == 0)
460		return (hdr_end);
461	/*
462	 * We could check for malformed headers but we don't really care.
463	 * A valid header starts with a token immediately followed by a
464	 * colon; a token is any sequence of non-control, non-whitespace
465	 * characters except "()<>@,;:\\\"{}".
466	 */
467	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
468		if ((*p = http_match(hdr_names[i].name, conn->buf)) != NULL)
469			return (hdr_names[i].num);
470	return (hdr_unknown);
471}
472
473/*
474 * Parse a last-modified header
475 */
476static int
477http_parse_mtime(const char *p, time_t *mtime)
478{
479	char locale[64], *r;
480	struct tm tm;
481
482	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
483	setlocale(LC_TIME, "C");
484	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
485	/* XXX should add support for date-2 and date-3 */
486	setlocale(LC_TIME, locale);
487	if (r == NULL)
488		return (-1);
489	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
490		  "%02d:%02d:%02d]\n",
491		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
492		  tm.tm_hour, tm.tm_min, tm.tm_sec));
493	*mtime = timegm(&tm);
494	return (0);
495}
496
497/*
498 * Parse a content-length header
499 */
500static int
501http_parse_length(const char *p, off_t *length)
502{
503	off_t len;
504
505	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
506		len = len * 10 + (*p - '0');
507	if (*p)
508		return (-1);
509	DEBUG(fprintf(stderr, "content length: [%lld]\n",
510	    (long long)len));
511	*length = len;
512	return (0);
513}
514
515/*
516 * Parse a content-range header
517 */
518static int
519http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
520{
521	off_t first, last, len;
522
523	if (strncasecmp(p, "bytes ", 6) != 0)
524		return (-1);
525	p += 6;
526	if (*p == '*') {
527		first = last = -1;
528		++p;
529	} else {
530		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
531			first = first * 10 + *p - '0';
532		if (*p != '-')
533			return (-1);
534		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
535			last = last * 10 + *p - '0';
536	}
537	if (first > last || *p != '/')
538		return (-1);
539	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
540		len = len * 10 + *p - '0';
541	if (*p || len < last - first + 1)
542		return (-1);
543	if (first == -1) {
544		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
545		    (long long)len));
546		*length = 0;
547	} else {
548		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
549		    (long long)first, (long long)last, (long long)len));
550		*length = last - first + 1;
551	}
552	*offset = first;
553	*size = len;
554	return (0);
555}
556
557
558/*****************************************************************************
559 * Helper functions for authorization
560 */
561
562/*
563 * Base64 encoding
564 */
565static char *
566http_base64(const char *src)
567{
568	static const char base64[] =
569	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
570	    "abcdefghijklmnopqrstuvwxyz"
571	    "0123456789+/";
572	char *str, *dst;
573	size_t l;
574	int t, r;
575
576	l = strlen(src);
577	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
578		return (NULL);
579	dst = str;
580	r = 0;
581
582	while (l >= 3) {
583		t = (src[0] << 16) | (src[1] << 8) | src[2];
584		dst[0] = base64[(t >> 18) & 0x3f];
585		dst[1] = base64[(t >> 12) & 0x3f];
586		dst[2] = base64[(t >> 6) & 0x3f];
587		dst[3] = base64[(t >> 0) & 0x3f];
588		src += 3; l -= 3;
589		dst += 4; r += 4;
590	}
591
592	switch (l) {
593	case 2:
594		t = (src[0] << 16) | (src[1] << 8);
595		dst[0] = base64[(t >> 18) & 0x3f];
596		dst[1] = base64[(t >> 12) & 0x3f];
597		dst[2] = base64[(t >> 6) & 0x3f];
598		dst[3] = '=';
599		dst += 4;
600		r += 4;
601		break;
602	case 1:
603		t = src[0] << 16;
604		dst[0] = base64[(t >> 18) & 0x3f];
605		dst[1] = base64[(t >> 12) & 0x3f];
606		dst[2] = dst[3] = '=';
607		dst += 4;
608		r += 4;
609		break;
610	case 0:
611		break;
612	}
613
614	*dst = 0;
615	return (str);
616}
617
618/*
619 * Encode username and password
620 */
621static int
622http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
623{
624	char *upw, *auth;
625	int r;
626
627	DEBUG(fprintf(stderr, "usr: [%s]\n", usr));
628	DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
629	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
630		return (-1);
631	auth = http_base64(upw);
632	free(upw);
633	if (auth == NULL)
634		return (-1);
635	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
636	free(auth);
637	return (r);
638}
639
640/*
641 * Send an authorization header
642 */
643static int
644http_authorize(conn_t *conn, const char *hdr, const char *p)
645{
646	/* basic authorization */
647	if (strncasecmp(p, "basic:", 6) == 0) {
648		char *user, *pwd, *str;
649		int r;
650
651		/* skip realm */
652		for (p += 6; *p && *p != ':'; ++p)
653			/* nothing */ ;
654		if (!*p || strchr(++p, ':') == NULL)
655			return (-1);
656		if ((str = strdup(p)) == NULL)
657			return (-1); /* XXX */
658		user = str;
659		pwd = strchr(str, ':');
660		*pwd++ = '\0';
661		r = http_basic_auth(conn, hdr, user, pwd);
662		free(str);
663		return (r);
664	}
665	return (-1);
666}
667
668
669/*****************************************************************************
670 * Helper functions for connecting to a server or proxy
671 */
672
673/*
674 * Connect to the correct HTTP server or proxy.
675 */
676static conn_t *
677http_connect(struct url *URL, struct url *purl, const char *flags)
678{
679	conn_t *conn;
680	int verbose;
681	int af, val;
682
683#ifdef INET6
684	af = AF_UNSPEC;
685#else
686	af = AF_INET;
687#endif
688
689	verbose = CHECK_FLAG('v');
690	if (CHECK_FLAG('4'))
691		af = AF_INET;
692#ifdef INET6
693	else if (CHECK_FLAG('6'))
694		af = AF_INET6;
695#endif
696
697	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
698		URL = purl;
699	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
700		/* can't talk http to an ftp server */
701		/* XXX should set an error code */
702		return (NULL);
703	}
704
705	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
706		/* fetch_connect() has already set an error code */
707		return (NULL);
708	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
709	    fetch_ssl(conn, verbose) == -1) {
710		fetch_close(conn);
711		/* grrr */
712		errno = EAUTH;
713		fetch_syserr();
714		return (NULL);
715	}
716
717	val = 1;
718	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
719
720	return (conn);
721}
722
723static struct url *
724http_get_proxy(struct url * url, const char *flags)
725{
726	struct url *purl;
727	char *p;
728
729	if (flags != NULL && strchr(flags, 'd') != NULL)
730		return (NULL);
731	if (fetch_no_proxy_match(url->host))
732		return (NULL);
733	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
734	    *p && (purl = fetchParseURL(p))) {
735		if (!*purl->scheme)
736			strcpy(purl->scheme, SCHEME_HTTP);
737		if (!purl->port)
738			purl->port = fetch_default_proxy_port(purl->scheme);
739		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
740			return (purl);
741		fetchFreeURL(purl);
742	}
743	return (NULL);
744}
745
746static void
747http_print_html(FILE *out, FILE *in)
748{
749	size_t len;
750	char *line, *p, *q;
751	int comment, tag;
752
753	comment = tag = 0;
754	while ((line = fgetln(in, &len)) != NULL) {
755		while (len && isspace((unsigned char)line[len - 1]))
756			--len;
757		for (p = q = line; q < line + len; ++q) {
758			if (comment && *q == '-') {
759				if (q + 2 < line + len &&
760				    strcmp(q, "-->") == 0) {
761					tag = comment = 0;
762					q += 2;
763				}
764			} else if (tag && !comment && *q == '>') {
765				p = q + 1;
766				tag = 0;
767			} else if (!tag && *q == '<') {
768				if (q > p)
769					fwrite(p, q - p, 1, out);
770				tag = 1;
771				if (q + 3 < line + len &&
772				    strcmp(q, "<!--") == 0) {
773					comment = 1;
774					q += 3;
775				}
776			}
777		}
778		if (!tag && q > p)
779			fwrite(p, q - p, 1, out);
780		fputc('\n', out);
781	}
782}
783
784
785/*****************************************************************************
786 * Core
787 */
788
789/*
790 * Send a request and process the reply
791 *
792 * XXX This function is way too long, the do..while loop should be split
793 * XXX off into a separate function.
794 */
795FILE *
796http_request(struct url *URL, const char *op, struct url_stat *us,
797    struct url *purl, const char *flags)
798{
799	conn_t *conn;
800	struct url *url, *new;
801	int chunked, direct, need_auth, noredirect, verbose;
802	int e, i, n, val;
803	off_t offset, clength, length, size;
804	time_t mtime;
805	const char *p;
806	FILE *f;
807	hdr_t h;
808	char hbuf[MAXHOSTNAMELEN + 7], *host;
809
810	direct = CHECK_FLAG('d');
811	noredirect = CHECK_FLAG('A');
812	verbose = CHECK_FLAG('v');
813
814	if (direct && purl) {
815		fetchFreeURL(purl);
816		purl = NULL;
817	}
818
819	/* try the provided URL first */
820	url = URL;
821
822	/* if the A flag is set, we only get one try */
823	n = noredirect ? 1 : MAX_REDIRECT;
824	i = 0;
825
826	e = HTTP_PROTOCOL_ERROR;
827	need_auth = 0;
828	do {
829		new = NULL;
830		chunked = 0;
831		offset = 0;
832		clength = -1;
833		length = -1;
834		size = -1;
835		mtime = 0;
836
837		/* check port */
838		if (!url->port)
839			url->port = fetch_default_port(url->scheme);
840
841		/* were we redirected to an FTP URL? */
842		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
843			if (strcmp(op, "GET") == 0)
844				return (ftp_request(url, "RETR", us, purl, flags));
845			else if (strcmp(op, "HEAD") == 0)
846				return (ftp_request(url, "STAT", us, purl, flags));
847		}
848
849		/* connect to server or proxy */
850		if ((conn = http_connect(url, purl, flags)) == NULL)
851			goto ouch;
852
853		host = url->host;
854#ifdef INET6
855		if (strchr(url->host, ':')) {
856			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
857			host = hbuf;
858		}
859#endif
860		if (url->port != fetch_default_port(url->scheme)) {
861			if (host != hbuf) {
862				strcpy(hbuf, host);
863				host = hbuf;
864			}
865			snprintf(hbuf + strlen(hbuf),
866			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
867		}
868
869		/* send request */
870		if (verbose)
871			fetch_info("requesting %s://%s%s",
872			    url->scheme, host, url->doc);
873		if (purl) {
874			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
875			    op, url->scheme, host, url->doc);
876		} else {
877			http_cmd(conn, "%s %s HTTP/1.1",
878			    op, url->doc);
879		}
880
881		/* virtual host */
882		http_cmd(conn, "Host: %s", host);
883
884		/* proxy authorization */
885		if (purl) {
886			if (*purl->user || *purl->pwd)
887				http_basic_auth(conn, "Proxy-Authorization",
888				    purl->user, purl->pwd);
889			else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
890				http_authorize(conn, "Proxy-Authorization", p);
891		}
892
893		/* server authorization */
894		if (need_auth || *url->user || *url->pwd) {
895			if (*url->user || *url->pwd)
896				http_basic_auth(conn, "Authorization", url->user, url->pwd);
897			else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
898				http_authorize(conn, "Authorization", p);
899			else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
900				http_basic_auth(conn, "Authorization", url->user, url->pwd);
901			} else {
902				http_seterr(HTTP_NEED_AUTH);
903				goto ouch;
904			}
905		}
906
907		/* other headers */
908		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
909			if (strcasecmp(p, "auto") == 0)
910				http_cmd(conn, "Referer: %s://%s%s",
911				    url->scheme, host, url->doc);
912			else
913				http_cmd(conn, "Referer: %s", p);
914		}
915		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
916			http_cmd(conn, "User-Agent: %s", p);
917		else
918			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
919		if (url->offset > 0)
920			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
921		http_cmd(conn, "Connection: close");
922		http_cmd(conn, "");
923
924		/*
925		 * Force the queued request to be dispatched.  Normally, one
926		 * would do this with shutdown(2) but squid proxies can be
927		 * configured to disallow such half-closed connections.  To
928		 * be compatible with such configurations, fiddle with socket
929		 * options to force the pending data to be written.
930		 */
931		val = 0;
932		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
933			   sizeof(val));
934		val = 1;
935		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
936			   sizeof(val));
937
938		/* get reply */
939		switch (http_get_reply(conn)) {
940		case HTTP_OK:
941		case HTTP_PARTIAL:
942			/* fine */
943			break;
944		case HTTP_MOVED_PERM:
945		case HTTP_MOVED_TEMP:
946		case HTTP_SEE_OTHER:
947			/*
948			 * Not so fine, but we still have to read the
949			 * headers to get the new location.
950			 */
951			break;
952		case HTTP_NEED_AUTH:
953			if (need_auth) {
954				/*
955				 * We already sent out authorization code,
956				 * so there's nothing more we can do.
957				 */
958				http_seterr(conn->err);
959				goto ouch;
960			}
961			/* try again, but send the password this time */
962			if (verbose)
963				fetch_info("server requires authorization");
964			break;
965		case HTTP_NEED_PROXY_AUTH:
966			/*
967			 * If we're talking to a proxy, we already sent
968			 * our proxy authorization code, so there's
969			 * nothing more we can do.
970			 */
971			http_seterr(conn->err);
972			goto ouch;
973		case HTTP_BAD_RANGE:
974			/*
975			 * This can happen if we ask for 0 bytes because
976			 * we already have the whole file.  Consider this
977			 * a success for now, and check sizes later.
978			 */
979			break;
980		case HTTP_PROTOCOL_ERROR:
981			/* fall through */
982		case -1:
983			fetch_syserr();
984			goto ouch;
985		default:
986			http_seterr(conn->err);
987			if (!verbose)
988				goto ouch;
989			/* fall through so we can get the full error message */
990		}
991
992		/* get headers */
993		do {
994			switch ((h = http_next_header(conn, &p))) {
995			case hdr_syserror:
996				fetch_syserr();
997				goto ouch;
998			case hdr_error:
999				http_seterr(HTTP_PROTOCOL_ERROR);
1000				goto ouch;
1001			case hdr_content_length:
1002				http_parse_length(p, &clength);
1003				break;
1004			case hdr_content_range:
1005				http_parse_range(p, &offset, &length, &size);
1006				break;
1007			case hdr_last_modified:
1008				http_parse_mtime(p, &mtime);
1009				break;
1010			case hdr_location:
1011				if (!HTTP_REDIRECT(conn->err))
1012					break;
1013				if (new)
1014					free(new);
1015				if (verbose)
1016					fetch_info("%d redirect to %s", conn->err, p);
1017				if (*p == '/')
1018					/* absolute path */
1019					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1020					    url->user, url->pwd);
1021				else
1022					new = fetchParseURL(p);
1023				if (new == NULL) {
1024					/* XXX should set an error code */
1025					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1026					goto ouch;
1027				}
1028				if (!*new->user && !*new->pwd) {
1029					strcpy(new->user, url->user);
1030					strcpy(new->pwd, url->pwd);
1031				}
1032				new->offset = url->offset;
1033				new->length = url->length;
1034				break;
1035			case hdr_transfer_encoding:
1036				/* XXX weak test*/
1037				chunked = (strcasecmp(p, "chunked") == 0);
1038				break;
1039			case hdr_www_authenticate:
1040				if (conn->err != HTTP_NEED_AUTH)
1041					break;
1042				/* if we were smarter, we'd check the method and realm */
1043				break;
1044			case hdr_end:
1045				/* fall through */
1046			case hdr_unknown:
1047				/* ignore */
1048				break;
1049			}
1050		} while (h > hdr_end);
1051
1052		/* we need to provide authentication */
1053		if (conn->err == HTTP_NEED_AUTH) {
1054			e = conn->err;
1055			need_auth = 1;
1056			fetch_close(conn);
1057			conn = NULL;
1058			continue;
1059		}
1060
1061		/* requested range not satisfiable */
1062		if (conn->err == HTTP_BAD_RANGE) {
1063			if (url->offset == size && url->length == 0) {
1064				/* asked for 0 bytes; fake it */
1065				offset = url->offset;
1066				conn->err = HTTP_OK;
1067				break;
1068			} else {
1069				http_seterr(conn->err);
1070				goto ouch;
1071			}
1072		}
1073
1074		/* we have a hit or an error */
1075		if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
1076			break;
1077
1078		/* all other cases: we got a redirect */
1079		e = conn->err;
1080		need_auth = 0;
1081		fetch_close(conn);
1082		conn = NULL;
1083		if (!new) {
1084			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1085			break;
1086		}
1087		if (url != URL)
1088			fetchFreeURL(url);
1089		url = new;
1090	} while (++i < n);
1091
1092	/* we failed, or ran out of retries */
1093	if (conn == NULL) {
1094		http_seterr(e);
1095		goto ouch;
1096	}
1097
1098	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1099		  " size %lld, clength %lld\n",
1100		  (long long)offset, (long long)length,
1101		  (long long)size, (long long)clength));
1102
1103	/* check for inconsistencies */
1104	if (clength != -1 && length != -1 && clength != length) {
1105		http_seterr(HTTP_PROTOCOL_ERROR);
1106		goto ouch;
1107	}
1108	if (clength == -1)
1109		clength = length;
1110	if (clength != -1)
1111		length = offset + clength;
1112	if (length != -1 && size != -1 && length != size) {
1113		http_seterr(HTTP_PROTOCOL_ERROR);
1114		goto ouch;
1115	}
1116	if (size == -1)
1117		size = length;
1118
1119	/* fill in stats */
1120	if (us) {
1121		us->size = size;
1122		us->atime = us->mtime = mtime;
1123	}
1124
1125	/* too far? */
1126	if (URL->offset > 0 && offset > URL->offset) {
1127		http_seterr(HTTP_PROTOCOL_ERROR);
1128		goto ouch;
1129	}
1130
1131	/* report back real offset and size */
1132	URL->offset = offset;
1133	URL->length = clength;
1134
1135	/* wrap it up in a FILE */
1136	if ((f = http_funopen(conn, chunked)) == NULL) {
1137		fetch_syserr();
1138		goto ouch;
1139	}
1140
1141	if (url != URL)
1142		fetchFreeURL(url);
1143	if (purl)
1144		fetchFreeURL(purl);
1145
1146	if (HTTP_ERROR(conn->err)) {
1147		http_print_html(stderr, f);
1148		fclose(f);
1149		f = NULL;
1150	}
1151
1152	return (f);
1153
1154ouch:
1155	if (url != URL)
1156		fetchFreeURL(url);
1157	if (purl)
1158		fetchFreeURL(purl);
1159	if (conn != NULL)
1160		fetch_close(conn);
1161	return (NULL);
1162}
1163
1164
1165/*****************************************************************************
1166 * Entry points
1167 */
1168
1169/*
1170 * Retrieve and stat a file by HTTP
1171 */
1172FILE *
1173fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1174{
1175	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1176}
1177
1178/*
1179 * Retrieve a file by HTTP
1180 */
1181FILE *
1182fetchGetHTTP(struct url *URL, const char *flags)
1183{
1184	return (fetchXGetHTTP(URL, NULL, flags));
1185}
1186
1187/*
1188 * Store a file by HTTP
1189 */
1190FILE *
1191fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1192{
1193	warnx("fetchPutHTTP(): not implemented");
1194	return (NULL);
1195}
1196
1197/*
1198 * Get an HTTP document's metadata
1199 */
1200int
1201fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1202{
1203	FILE *f;
1204
1205	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
1206	if (f == NULL)
1207		return (-1);
1208	fclose(f);
1209	return (0);
1210}
1211
1212/*
1213 * List a directory
1214 */
1215struct url_ent *
1216fetchListHTTP(struct url *url __unused, const char *flags __unused)
1217{
1218	warnx("fetchListHTTP(): not implemented");
1219	return (NULL);
1220}
1221