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