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