http.c revision 97868
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 97868 2002-06-05 12:46:36Z 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		return (NULL);
687	}
688	return (conn);
689}
690
691static struct url *
692_http_get_proxy(void)
693{
694	struct url *purl;
695	char *p;
696
697	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
698	    (purl = fetchParseURL(p))) {
699		if (!*purl->scheme)
700			strcpy(purl->scheme, SCHEME_HTTP);
701		if (!purl->port)
702			purl->port = _fetch_default_proxy_port(purl->scheme);
703		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
704			return (purl);
705		fetchFreeURL(purl);
706	}
707	return (NULL);
708}
709
710static void
711_http_print_html(FILE *out, FILE *in)
712{
713	size_t len;
714	char *line, *p, *q;
715	int comment, tag;
716
717	comment = tag = 0;
718	while ((line = fgetln(in, &len)) != NULL) {
719		while (len && isspace(line[len - 1]))
720			--len;
721		for (p = q = line; q < line + len; ++q) {
722			if (comment && *q == '-') {
723				if (q + 2 < line + len &&
724				    strcmp(q, "-->") == 0) {
725					tag = comment = 0;
726					q += 2;
727				}
728			} else if (tag && !comment && *q == '>') {
729				p = q + 1;
730				tag = 0;
731			} else if (!tag && *q == '<') {
732				if (q > p)
733					fwrite(p, q - p, 1, out);
734				tag = 1;
735				if (q + 3 < line + len &&
736				    strcmp(q, "<!--") == 0) {
737					comment = 1;
738					q += 3;
739				}
740			}
741		}
742		if (!tag && q > p)
743			fwrite(p, q - p, 1, out);
744		fputc('\n', out);
745	}
746}
747
748
749/*****************************************************************************
750 * Core
751 */
752
753/*
754 * Send a request and process the reply
755 *
756 * XXX This function is way too long, the do..while loop should be split
757 * XXX off into a separate function.
758 */
759FILE *
760_http_request(struct url *URL, const char *op, struct url_stat *us,
761    struct url *purl, const char *flags)
762{
763	conn_t *conn;
764	struct url *url, *new;
765	int chunked, direct, need_auth, noredirect, verbose;
766	int i, n;
767	off_t offset, clength, length, size;
768	time_t mtime;
769	const char *p;
770	FILE *f;
771	hdr_t h;
772	char *host;
773#ifdef INET6
774	char hbuf[MAXHOSTNAMELEN + 1];
775#endif
776
777	direct = CHECK_FLAG('d');
778	noredirect = CHECK_FLAG('A');
779	verbose = CHECK_FLAG('v');
780
781	if (direct && purl) {
782		fetchFreeURL(purl);
783		purl = NULL;
784	}
785
786	/* try the provided URL first */
787	url = URL;
788
789	/* if the A flag is set, we only get one try */
790	n = noredirect ? 1 : MAX_REDIRECT;
791	i = 0;
792
793	need_auth = 0;
794	do {
795		new = NULL;
796		chunked = 0;
797		offset = 0;
798		clength = -1;
799		length = -1;
800		size = -1;
801		mtime = 0;
802
803		/* check port */
804		if (!url->port)
805			url->port = _fetch_default_port(url->scheme);
806
807		/* were we redirected to an FTP URL? */
808		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
809			if (strcmp(op, "GET") == 0)
810				return (_ftp_request(url, "RETR", us, purl, flags));
811			else if (strcmp(op, "HEAD") == 0)
812				return (_ftp_request(url, "STAT", us, purl, flags));
813		}
814
815		/* connect to server or proxy */
816		if ((conn = _http_connect(url, purl, flags)) == NULL)
817			goto ouch;
818
819		host = url->host;
820#ifdef INET6
821		if (strchr(url->host, ':')) {
822			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
823			host = hbuf;
824		}
825#endif
826
827		/* send request */
828		if (verbose)
829			_fetch_info("requesting %s://%s:%d%s",
830			    url->scheme, host, url->port, url->doc);
831		if (purl) {
832			_http_cmd(conn, "%s %s://%s:%d%s HTTP/1.1",
833			    op, url->scheme, host, url->port, url->doc);
834		} else {
835			_http_cmd(conn, "%s %s HTTP/1.1",
836			    op, url->doc);
837		}
838
839		/* virtual host */
840		if (url->port == _fetch_default_port(url->scheme))
841			_http_cmd(conn, "Host: %s", host);
842		else
843			_http_cmd(conn, "Host: %s:%d", host, url->port);
844
845		/* proxy authorization */
846		if (purl) {
847			if (*purl->user || *purl->pwd)
848				_http_basic_auth(conn, "Proxy-Authorization",
849				    purl->user, purl->pwd);
850			else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
851				_http_authorize(conn, "Proxy-Authorization", p);
852		}
853
854		/* server authorization */
855		if (need_auth || *url->user || *url->pwd) {
856			if (*url->user || *url->pwd)
857				_http_basic_auth(conn, "Authorization", url->user, url->pwd);
858			else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
859				_http_authorize(conn, "Authorization", p);
860			else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
861				_http_basic_auth(conn, "Authorization", url->user, url->pwd);
862			} else {
863				_http_seterr(HTTP_NEED_AUTH);
864				goto ouch;
865			}
866		}
867
868		/* other headers */
869		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
870			_http_cmd(conn, "User-Agent: %s", p);
871		else
872			_http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
873		if (url->offset)
874			_http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
875		_http_cmd(conn, "Connection: close");
876		_http_cmd(conn, "");
877
878		/* get reply */
879		switch (_http_get_reply(conn)) {
880		case HTTP_OK:
881		case HTTP_PARTIAL:
882			/* fine */
883			break;
884		case HTTP_MOVED_PERM:
885		case HTTP_MOVED_TEMP:
886		case HTTP_SEE_OTHER:
887			/*
888			 * Not so fine, but we still have to read the headers to
889			 * get the new location.
890			 */
891			break;
892		case HTTP_NEED_AUTH:
893			if (need_auth) {
894				/*
895				 * We already sent out authorization code, so there's
896				 * nothing more we can do.
897				 */
898				_http_seterr(conn->err);
899				goto ouch;
900			}
901			/* try again, but send the password this time */
902			if (verbose)
903				_fetch_info("server requires authorization");
904			break;
905		case HTTP_NEED_PROXY_AUTH:
906			/*
907			 * If we're talking to a proxy, we already sent our proxy
908			 * authorization code, so there's nothing more we can do.
909			 */
910			_http_seterr(conn->err);
911			goto ouch;
912		case HTTP_PROTOCOL_ERROR:
913			/* fall through */
914		case -1:
915			_fetch_syserr();
916			goto ouch;
917		default:
918			_http_seterr(conn->err);
919			if (!verbose)
920				goto ouch;
921			/* fall through so we can get the full error message */
922		}
923
924		/* get headers */
925		do {
926			switch ((h = _http_next_header(conn, &p))) {
927			case hdr_syserror:
928				_fetch_syserr();
929				goto ouch;
930			case hdr_error:
931				_http_seterr(HTTP_PROTOCOL_ERROR);
932				goto ouch;
933			case hdr_content_length:
934				_http_parse_length(p, &clength);
935				break;
936			case hdr_content_range:
937				_http_parse_range(p, &offset, &length, &size);
938				break;
939			case hdr_last_modified:
940				_http_parse_mtime(p, &mtime);
941				break;
942			case hdr_location:
943				if (!HTTP_REDIRECT(conn->err))
944					break;
945				if (new)
946					free(new);
947				if (verbose)
948					_fetch_info("%d redirect to %s", conn->err, p);
949				if (*p == '/')
950					/* absolute path */
951					new = fetchMakeURL(url->scheme, url->host, url->port, p,
952					    url->user, url->pwd);
953				else
954					new = fetchParseURL(p);
955				if (new == NULL) {
956					/* XXX should set an error code */
957					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
958					goto ouch;
959				}
960				if (!*new->user && !*new->pwd) {
961					strcpy(new->user, url->user);
962					strcpy(new->pwd, url->pwd);
963				}
964				new->offset = url->offset;
965				new->length = url->length;
966				break;
967			case hdr_transfer_encoding:
968				/* XXX weak test*/
969				chunked = (strcasecmp(p, "chunked") == 0);
970				break;
971			case hdr_www_authenticate:
972				if (conn->err != HTTP_NEED_AUTH)
973					break;
974				/* if we were smarter, we'd check the method and realm */
975				break;
976			case hdr_end:
977				/* fall through */
978			case hdr_unknown:
979				/* ignore */
980				break;
981			}
982		} while (h > hdr_end);
983
984		/* we have a hit or an error */
985		if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
986			break;
987
988		/* we need to provide authentication */
989		if (conn->err == HTTP_NEED_AUTH) {
990			need_auth = 1;
991			_fetch_close(conn);
992			conn = NULL;
993			continue;
994		}
995
996		/* all other cases: we got a redirect */
997		need_auth = 0;
998		_fetch_close(conn);
999		conn = NULL;
1000		if (!new) {
1001			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1002			break;
1003		}
1004		if (url != URL)
1005			fetchFreeURL(url);
1006		url = new;
1007	} while (++i < n);
1008
1009	/* we failed, or ran out of retries */
1010	if (conn == NULL) {
1011		_http_seterr(conn->err);
1012		goto ouch;
1013	}
1014
1015	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1016		  " size %lld, clength %lld\n",
1017		  (long long)offset, (long long)length,
1018		  (long long)size, (long long)clength));
1019
1020	/* check for inconsistencies */
1021	if (clength != -1 && length != -1 && clength != length) {
1022		_http_seterr(HTTP_PROTOCOL_ERROR);
1023		goto ouch;
1024	}
1025	if (clength == -1)
1026		clength = length;
1027	if (clength != -1)
1028		length = offset + clength;
1029	if (length != -1 && size != -1 && length != size) {
1030		_http_seterr(HTTP_PROTOCOL_ERROR);
1031		goto ouch;
1032	}
1033	if (size == -1)
1034		size = length;
1035
1036	/* fill in stats */
1037	if (us) {
1038		us->size = size;
1039		us->atime = us->mtime = mtime;
1040	}
1041
1042	/* too far? */
1043	if (offset > URL->offset) {
1044		_http_seterr(HTTP_PROTOCOL_ERROR);
1045		goto ouch;
1046	}
1047
1048	/* report back real offset and size */
1049	URL->offset = offset;
1050	URL->length = clength;
1051
1052	/* wrap it up in a FILE */
1053	if ((f = _http_funopen(conn, chunked)) == NULL) {
1054		_fetch_syserr();
1055		goto ouch;
1056	}
1057
1058	if (url != URL)
1059		fetchFreeURL(url);
1060	if (purl)
1061		fetchFreeURL(purl);
1062
1063	if (HTTP_ERROR(conn->err)) {
1064		_http_print_html(stderr, f);
1065		fclose(f);
1066		f = NULL;
1067	}
1068
1069	return (f);
1070
1071ouch:
1072	if (url != URL)
1073		fetchFreeURL(url);
1074	if (purl)
1075		fetchFreeURL(purl);
1076	if (conn != NULL)
1077		_fetch_close(conn);
1078	return (NULL);
1079}
1080
1081
1082/*****************************************************************************
1083 * Entry points
1084 */
1085
1086/*
1087 * Retrieve and stat a file by HTTP
1088 */
1089FILE *
1090fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1091{
1092	return (_http_request(URL, "GET", us, _http_get_proxy(), flags));
1093}
1094
1095/*
1096 * Retrieve a file by HTTP
1097 */
1098FILE *
1099fetchGetHTTP(struct url *URL, const char *flags)
1100{
1101	return (fetchXGetHTTP(URL, NULL, flags));
1102}
1103
1104/*
1105 * Store a file by HTTP
1106 */
1107FILE *
1108fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1109{
1110	warnx("fetchPutHTTP(): not implemented");
1111	return (NULL);
1112}
1113
1114/*
1115 * Get an HTTP document's metadata
1116 */
1117int
1118fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1119{
1120	FILE *f;
1121
1122	if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL)
1123		return (-1);
1124	fclose(f);
1125	return (0);
1126}
1127
1128/*
1129 * List a directory
1130 */
1131struct url_ent *
1132fetchListHTTP(struct url *url __unused, const char *flags __unused)
1133{
1134	warnx("fetchListHTTP(): not implemented");
1135	return (NULL);
1136}
1137