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