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