http.c revision 176105
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 176105 2008-02-08 09:48:48Z 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((unsigned char)*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		memcpy(buf + pos, io->buf + io->bufpos, 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 &&
438	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
439		/* nothing */;
440	if (*str || *hdr != ':')
441		return (NULL);
442	while (*hdr && isspace((unsigned char)*++hdr))
443		/* nothing */;
444	return (hdr);
445}
446
447/*
448 * Get the next header and return the appropriate symbolic code.
449 */
450static hdr_t
451http_next_header(conn_t *conn, const char **p)
452{
453	int i;
454
455	if (fetch_getln(conn) == -1)
456		return (hdr_syserror);
457	while (conn->buflen && isspace((unsigned char)conn->buf[conn->buflen - 1]))
458		conn->buflen--;
459	conn->buf[conn->buflen] = '\0';
460	if (conn->buflen == 0)
461		return (hdr_end);
462	/*
463	 * We could check for malformed headers but we don't really care.
464	 * A valid header starts with a token immediately followed by a
465	 * colon; a token is any sequence of non-control, non-whitespace
466	 * characters except "()<>@,;:\\\"{}".
467	 */
468	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
469		if ((*p = http_match(hdr_names[i].name, conn->buf)) != NULL)
470			return (hdr_names[i].num);
471	return (hdr_unknown);
472}
473
474/*
475 * Parse a last-modified header
476 */
477static int
478http_parse_mtime(const char *p, time_t *mtime)
479{
480	char locale[64], *r;
481	struct tm tm;
482
483	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
484	setlocale(LC_TIME, "C");
485	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
486	/* XXX should add support for date-2 and date-3 */
487	setlocale(LC_TIME, locale);
488	if (r == NULL)
489		return (-1);
490	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
491		  "%02d:%02d:%02d]\n",
492		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
493		  tm.tm_hour, tm.tm_min, tm.tm_sec));
494	*mtime = timegm(&tm);
495	return (0);
496}
497
498/*
499 * Parse a content-length header
500 */
501static int
502http_parse_length(const char *p, off_t *length)
503{
504	off_t len;
505
506	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
507		len = len * 10 + (*p - '0');
508	if (*p)
509		return (-1);
510	DEBUG(fprintf(stderr, "content length: [%lld]\n",
511	    (long long)len));
512	*length = len;
513	return (0);
514}
515
516/*
517 * Parse a content-range header
518 */
519static int
520http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
521{
522	off_t first, last, len;
523
524	if (strncasecmp(p, "bytes ", 6) != 0)
525		return (-1);
526	p += 6;
527	if (*p == '*') {
528		first = last = -1;
529		++p;
530	} else {
531		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
532			first = first * 10 + *p - '0';
533		if (*p != '-')
534			return (-1);
535		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
536			last = last * 10 + *p - '0';
537	}
538	if (first > last || *p != '/')
539		return (-1);
540	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
541		len = len * 10 + *p - '0';
542	if (*p || len < last - first + 1)
543		return (-1);
544	if (first == -1) {
545		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
546		    (long long)len));
547		*length = 0;
548	} else {
549		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
550		    (long long)first, (long long)last, (long long)len));
551		*length = last - first + 1;
552	}
553	*offset = first;
554	*size = len;
555	return (0);
556}
557
558
559/*****************************************************************************
560 * Helper functions for authorization
561 */
562
563/*
564 * Base64 encoding
565 */
566static char *
567http_base64(const char *src)
568{
569	static const char base64[] =
570	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
571	    "abcdefghijklmnopqrstuvwxyz"
572	    "0123456789+/";
573	char *str, *dst;
574	size_t l;
575	int t, r;
576
577	l = strlen(src);
578	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
579		return (NULL);
580	dst = str;
581	r = 0;
582
583	while (l >= 3) {
584		t = (src[0] << 16) | (src[1] << 8) | src[2];
585		dst[0] = base64[(t >> 18) & 0x3f];
586		dst[1] = base64[(t >> 12) & 0x3f];
587		dst[2] = base64[(t >> 6) & 0x3f];
588		dst[3] = base64[(t >> 0) & 0x3f];
589		src += 3; l -= 3;
590		dst += 4; r += 4;
591	}
592
593	switch (l) {
594	case 2:
595		t = (src[0] << 16) | (src[1] << 8);
596		dst[0] = base64[(t >> 18) & 0x3f];
597		dst[1] = base64[(t >> 12) & 0x3f];
598		dst[2] = base64[(t >> 6) & 0x3f];
599		dst[3] = '=';
600		dst += 4;
601		r += 4;
602		break;
603	case 1:
604		t = src[0] << 16;
605		dst[0] = base64[(t >> 18) & 0x3f];
606		dst[1] = base64[(t >> 12) & 0x3f];
607		dst[2] = dst[3] = '=';
608		dst += 4;
609		r += 4;
610		break;
611	case 0:
612		break;
613	}
614
615	*dst = 0;
616	return (str);
617}
618
619/*
620 * Encode username and password
621 */
622static int
623http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
624{
625	char *upw, *auth;
626	int r;
627
628	DEBUG(fprintf(stderr, "usr: [%s]\n", usr));
629	DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
630	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
631		return (-1);
632	auth = http_base64(upw);
633	free(upw);
634	if (auth == NULL)
635		return (-1);
636	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
637	free(auth);
638	return (r);
639}
640
641/*
642 * Send an authorization header
643 */
644static int
645http_authorize(conn_t *conn, const char *hdr, const char *p)
646{
647	/* basic authorization */
648	if (strncasecmp(p, "basic:", 6) == 0) {
649		char *user, *pwd, *str;
650		int r;
651
652		/* skip realm */
653		for (p += 6; *p && *p != ':'; ++p)
654			/* nothing */ ;
655		if (!*p || strchr(++p, ':') == NULL)
656			return (-1);
657		if ((str = strdup(p)) == NULL)
658			return (-1); /* XXX */
659		user = str;
660		pwd = strchr(str, ':');
661		*pwd++ = '\0';
662		r = http_basic_auth(conn, hdr, user, pwd);
663		free(str);
664		return (r);
665	}
666	return (-1);
667}
668
669
670/*****************************************************************************
671 * Helper functions for connecting to a server or proxy
672 */
673
674/*
675 * Connect to the correct HTTP server or proxy.
676 */
677static conn_t *
678http_connect(struct url *URL, struct url *purl, const char *flags)
679{
680	conn_t *conn;
681	int verbose;
682	int af, val;
683
684#ifdef INET6
685	af = AF_UNSPEC;
686#else
687	af = AF_INET;
688#endif
689
690	verbose = CHECK_FLAG('v');
691	if (CHECK_FLAG('4'))
692		af = AF_INET;
693#ifdef INET6
694	else if (CHECK_FLAG('6'))
695		af = AF_INET6;
696#endif
697
698	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
699		URL = purl;
700	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
701		/* can't talk http to an ftp server */
702		/* XXX should set an error code */
703		return (NULL);
704	}
705
706	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
707		/* fetch_connect() has already set an error code */
708		return (NULL);
709	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
710	    fetch_ssl(conn, verbose) == -1) {
711		fetch_close(conn);
712		/* grrr */
713		errno = EAUTH;
714		fetch_syserr();
715		return (NULL);
716	}
717
718	val = 1;
719	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
720
721	return (conn);
722}
723
724static struct url *
725http_get_proxy(struct url * url, const char *flags)
726{
727	struct url *purl;
728	char *p;
729
730	if (flags != NULL && strchr(flags, 'd') != NULL)
731		return (NULL);
732	if (fetch_no_proxy_match(url->host))
733		return (NULL);
734	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
735	    *p && (purl = fetchParseURL(p))) {
736		if (!*purl->scheme)
737			strcpy(purl->scheme, SCHEME_HTTP);
738		if (!purl->port)
739			purl->port = fetch_default_proxy_port(purl->scheme);
740		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
741			return (purl);
742		fetchFreeURL(purl);
743	}
744	return (NULL);
745}
746
747static void
748http_print_html(FILE *out, FILE *in)
749{
750	size_t len;
751	char *line, *p, *q;
752	int comment, tag;
753
754	comment = tag = 0;
755	while ((line = fgetln(in, &len)) != NULL) {
756		while (len && isspace((unsigned char)line[len - 1]))
757			--len;
758		for (p = q = line; q < line + len; ++q) {
759			if (comment && *q == '-') {
760				if (q + 2 < line + len &&
761				    strcmp(q, "-->") == 0) {
762					tag = comment = 0;
763					q += 2;
764				}
765			} else if (tag && !comment && *q == '>') {
766				p = q + 1;
767				tag = 0;
768			} else if (!tag && *q == '<') {
769				if (q > p)
770					fwrite(p, q - p, 1, out);
771				tag = 1;
772				if (q + 3 < line + len &&
773				    strcmp(q, "<!--") == 0) {
774					comment = 1;
775					q += 3;
776				}
777			}
778		}
779		if (!tag && q > p)
780			fwrite(p, q - p, 1, out);
781		fputc('\n', out);
782	}
783}
784
785
786/*****************************************************************************
787 * Core
788 */
789
790/*
791 * Send a request and process the reply
792 *
793 * XXX This function is way too long, the do..while loop should be split
794 * XXX off into a separate function.
795 */
796FILE *
797http_request(struct url *URL, const char *op, struct url_stat *us,
798    struct url *purl, const char *flags)
799{
800	conn_t *conn;
801	struct url *url, *new;
802	int chunked, direct, need_auth, noredirect, verbose;
803	int e, i, n, val;
804	off_t offset, clength, length, size;
805	time_t mtime;
806	const char *p;
807	FILE *f;
808	hdr_t h;
809	char hbuf[MAXHOSTNAMELEN + 7], *host;
810
811	direct = CHECK_FLAG('d');
812	noredirect = CHECK_FLAG('A');
813	verbose = CHECK_FLAG('v');
814
815	if (direct && purl) {
816		fetchFreeURL(purl);
817		purl = NULL;
818	}
819
820	/* try the provided URL first */
821	url = URL;
822
823	/* if the A flag is set, we only get one try */
824	n = noredirect ? 1 : MAX_REDIRECT;
825	i = 0;
826
827	e = HTTP_PROTOCOL_ERROR;
828	need_auth = 0;
829	do {
830		new = NULL;
831		chunked = 0;
832		offset = 0;
833		clength = -1;
834		length = -1;
835		size = -1;
836		mtime = 0;
837
838		/* check port */
839		if (!url->port)
840			url->port = fetch_default_port(url->scheme);
841
842		/* were we redirected to an FTP URL? */
843		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
844			if (strcmp(op, "GET") == 0)
845				return (ftp_request(url, "RETR", us, purl, flags));
846			else if (strcmp(op, "HEAD") == 0)
847				return (ftp_request(url, "STAT", us, purl, flags));
848		}
849
850		/* connect to server or proxy */
851		if ((conn = http_connect(url, purl, flags)) == NULL)
852			goto ouch;
853
854		host = url->host;
855#ifdef INET6
856		if (strchr(url->host, ':')) {
857			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
858			host = hbuf;
859		}
860#endif
861		if (url->port != fetch_default_port(url->scheme)) {
862			if (host != hbuf) {
863				strcpy(hbuf, host);
864				host = hbuf;
865			}
866			snprintf(hbuf + strlen(hbuf),
867			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
868		}
869
870		/* send request */
871		if (verbose)
872			fetch_info("requesting %s://%s%s",
873			    url->scheme, host, url->doc);
874		if (purl) {
875			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
876			    op, url->scheme, host, url->doc);
877		} else {
878			http_cmd(conn, "%s %s HTTP/1.1",
879			    op, url->doc);
880		}
881
882		/* virtual host */
883		http_cmd(conn, "Host: %s", host);
884
885		/* proxy authorization */
886		if (purl) {
887			if (*purl->user || *purl->pwd)
888				http_basic_auth(conn, "Proxy-Authorization",
889				    purl->user, purl->pwd);
890			else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
891				http_authorize(conn, "Proxy-Authorization", p);
892		}
893
894		/* server authorization */
895		if (need_auth || *url->user || *url->pwd) {
896			if (*url->user || *url->pwd)
897				http_basic_auth(conn, "Authorization", url->user, url->pwd);
898			else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
899				http_authorize(conn, "Authorization", p);
900			else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
901				http_basic_auth(conn, "Authorization", url->user, url->pwd);
902			} else {
903				http_seterr(HTTP_NEED_AUTH);
904				goto ouch;
905			}
906		}
907
908		/* other headers */
909		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
910			if (strcasecmp(p, "auto") == 0)
911				http_cmd(conn, "Referer: %s://%s%s",
912				    url->scheme, host, url->doc);
913			else
914				http_cmd(conn, "Referer: %s", p);
915		}
916		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
917			http_cmd(conn, "User-Agent: %s", p);
918		else
919			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
920		if (url->offset > 0)
921			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
922		http_cmd(conn, "Connection: close");
923		http_cmd(conn, "");
924
925		/*
926		 * Force the queued request to be dispatched.  Normally, one
927		 * would do this with shutdown(2) but squid proxies can be
928		 * configured to disallow such half-closed connections.  To
929		 * be compatible with such configurations, fiddle with socket
930		 * options to force the pending data to be written.
931		 */
932		val = 0;
933		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
934			   sizeof(val));
935		val = 1;
936		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
937			   sizeof(val));
938
939		/* get reply */
940		switch (http_get_reply(conn)) {
941		case HTTP_OK:
942		case HTTP_PARTIAL:
943			/* fine */
944			break;
945		case HTTP_MOVED_PERM:
946		case HTTP_MOVED_TEMP:
947		case HTTP_SEE_OTHER:
948			/*
949			 * Not so fine, but we still have to read the
950			 * headers to get the new location.
951			 */
952			break;
953		case HTTP_NEED_AUTH:
954			if (need_auth) {
955				/*
956				 * We already sent out authorization code,
957				 * so there's nothing more we can do.
958				 */
959				http_seterr(conn->err);
960				goto ouch;
961			}
962			/* try again, but send the password this time */
963			if (verbose)
964				fetch_info("server requires authorization");
965			break;
966		case HTTP_NEED_PROXY_AUTH:
967			/*
968			 * If we're talking to a proxy, we already sent
969			 * our proxy authorization code, so there's
970			 * nothing more we can do.
971			 */
972			http_seterr(conn->err);
973			goto ouch;
974		case HTTP_BAD_RANGE:
975			/*
976			 * This can happen if we ask for 0 bytes because
977			 * we already have the whole file.  Consider this
978			 * a success for now, and check sizes later.
979			 */
980			break;
981		case HTTP_PROTOCOL_ERROR:
982			/* fall through */
983		case -1:
984			fetch_syserr();
985			goto ouch;
986		default:
987			http_seterr(conn->err);
988			if (!verbose)
989				goto ouch;
990			/* fall through so we can get the full error message */
991		}
992
993		/* get headers */
994		do {
995			switch ((h = http_next_header(conn, &p))) {
996			case hdr_syserror:
997				fetch_syserr();
998				goto ouch;
999			case hdr_error:
1000				http_seterr(HTTP_PROTOCOL_ERROR);
1001				goto ouch;
1002			case hdr_content_length:
1003				http_parse_length(p, &clength);
1004				break;
1005			case hdr_content_range:
1006				http_parse_range(p, &offset, &length, &size);
1007				break;
1008			case hdr_last_modified:
1009				http_parse_mtime(p, &mtime);
1010				break;
1011			case hdr_location:
1012				if (!HTTP_REDIRECT(conn->err))
1013					break;
1014				if (new)
1015					free(new);
1016				if (verbose)
1017					fetch_info("%d redirect to %s", conn->err, p);
1018				if (*p == '/')
1019					/* absolute path */
1020					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1021					    url->user, url->pwd);
1022				else
1023					new = fetchParseURL(p);
1024				if (new == NULL) {
1025					/* XXX should set an error code */
1026					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1027					goto ouch;
1028				}
1029				if (!*new->user && !*new->pwd) {
1030					strcpy(new->user, url->user);
1031					strcpy(new->pwd, url->pwd);
1032				}
1033				new->offset = url->offset;
1034				new->length = url->length;
1035				break;
1036			case hdr_transfer_encoding:
1037				/* XXX weak test*/
1038				chunked = (strcasecmp(p, "chunked") == 0);
1039				break;
1040			case hdr_www_authenticate:
1041				if (conn->err != HTTP_NEED_AUTH)
1042					break;
1043				/* if we were smarter, we'd check the method and realm */
1044				break;
1045			case hdr_end:
1046				/* fall through */
1047			case hdr_unknown:
1048				/* ignore */
1049				break;
1050			}
1051		} while (h > hdr_end);
1052
1053		/* we need to provide authentication */
1054		if (conn->err == HTTP_NEED_AUTH) {
1055			e = conn->err;
1056			need_auth = 1;
1057			fetch_close(conn);
1058			conn = NULL;
1059			continue;
1060		}
1061
1062		/* requested range not satisfiable */
1063		if (conn->err == HTTP_BAD_RANGE) {
1064			if (url->offset == size && url->length == 0) {
1065				/* asked for 0 bytes; fake it */
1066				offset = url->offset;
1067				conn->err = HTTP_OK;
1068				break;
1069			} else {
1070				http_seterr(conn->err);
1071				goto ouch;
1072			}
1073		}
1074
1075		/* we have a hit or an error */
1076		if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
1077			break;
1078
1079		/* all other cases: we got a redirect */
1080		e = conn->err;
1081		need_auth = 0;
1082		fetch_close(conn);
1083		conn = NULL;
1084		if (!new) {
1085			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1086			break;
1087		}
1088		if (url != URL)
1089			fetchFreeURL(url);
1090		url = new;
1091	} while (++i < n);
1092
1093	/* we failed, or ran out of retries */
1094	if (conn == NULL) {
1095		http_seterr(e);
1096		goto ouch;
1097	}
1098
1099	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1100		  " size %lld, clength %lld\n",
1101		  (long long)offset, (long long)length,
1102		  (long long)size, (long long)clength));
1103
1104	/* check for inconsistencies */
1105	if (clength != -1 && length != -1 && clength != length) {
1106		http_seterr(HTTP_PROTOCOL_ERROR);
1107		goto ouch;
1108	}
1109	if (clength == -1)
1110		clength = length;
1111	if (clength != -1)
1112		length = offset + clength;
1113	if (length != -1 && size != -1 && length != size) {
1114		http_seterr(HTTP_PROTOCOL_ERROR);
1115		goto ouch;
1116	}
1117	if (size == -1)
1118		size = length;
1119
1120	/* fill in stats */
1121	if (us) {
1122		us->size = size;
1123		us->atime = us->mtime = mtime;
1124	}
1125
1126	/* too far? */
1127	if (URL->offset > 0 && offset > URL->offset) {
1128		http_seterr(HTTP_PROTOCOL_ERROR);
1129		goto ouch;
1130	}
1131
1132	/* report back real offset and size */
1133	URL->offset = offset;
1134	URL->length = clength;
1135
1136	/* wrap it up in a FILE */
1137	if ((f = http_funopen(conn, chunked)) == NULL) {
1138		fetch_syserr();
1139		goto ouch;
1140	}
1141
1142	if (url != URL)
1143		fetchFreeURL(url);
1144	if (purl)
1145		fetchFreeURL(purl);
1146
1147	if (HTTP_ERROR(conn->err)) {
1148		http_print_html(stderr, f);
1149		fclose(f);
1150		f = NULL;
1151	}
1152
1153	return (f);
1154
1155ouch:
1156	if (url != URL)
1157		fetchFreeURL(url);
1158	if (purl)
1159		fetchFreeURL(purl);
1160	if (conn != NULL)
1161		fetch_close(conn);
1162	return (NULL);
1163}
1164
1165
1166/*****************************************************************************
1167 * Entry points
1168 */
1169
1170/*
1171 * Retrieve and stat a file by HTTP
1172 */
1173FILE *
1174fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1175{
1176	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1177}
1178
1179/*
1180 * Retrieve a file by HTTP
1181 */
1182FILE *
1183fetchGetHTTP(struct url *URL, const char *flags)
1184{
1185	return (fetchXGetHTTP(URL, NULL, flags));
1186}
1187
1188/*
1189 * Store a file by HTTP
1190 */
1191FILE *
1192fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1193{
1194	warnx("fetchPutHTTP(): not implemented");
1195	return (NULL);
1196}
1197
1198/*
1199 * Get an HTTP document's metadata
1200 */
1201int
1202fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1203{
1204	FILE *f;
1205
1206	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
1207	if (f == NULL)
1208		return (-1);
1209	fclose(f);
1210	return (0);
1211}
1212
1213/*
1214 * List a directory
1215 */
1216struct url_ent *
1217fetchListHTTP(struct url *url __unused, const char *flags __unused)
1218{
1219	warnx("fetchListHTTP(): not implemented");
1220	return (NULL);
1221}
1222