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