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