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