xref: /freebsd/lib/libfetch/http.c (revision c98323078dede7579020518ec84cdcb478e5c142)
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$");
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_BAD_RANGE		416
95 #define HTTP_PROTOCOL_ERROR	999
96 
97 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
98 			    || (xyz) == HTTP_MOVED_TEMP \
99 			    || (xyz) == HTTP_SEE_OTHER)
100 
101 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
102 
103 
104 /*****************************************************************************
105  * I/O functions for decoding chunked streams
106  */
107 
108 struct httpio
109 {
110 	conn_t		*conn;		/* connection */
111 	int		 chunked;	/* chunked mode */
112 	char		*buf;		/* chunk buffer */
113 	size_t		 bufsize;	/* size of chunk buffer */
114 	ssize_t		 buflen;	/* amount of data currently in buffer */
115 	int		 bufpos;	/* current read offset in buffer */
116 	int		 eof;		/* end-of-file flag */
117 	int		 error;		/* error flag */
118 	size_t		 chunksize;	/* remaining size of current chunk */
119 #ifndef NDEBUG
120 	size_t		 total;
121 #endif
122 };
123 
124 /*
125  * Get next chunk header
126  */
127 static int
128 _http_new_chunk(struct httpio *io)
129 {
130 	char *p;
131 
132 	if (_fetch_getln(io->conn) == -1)
133 		return (-1);
134 
135 	if (io->conn->buflen < 2 || !ishexnumber(*io->conn->buf))
136 		return (-1);
137 
138 	for (p = io->conn->buf; *p && !isspace(*p); ++p) {
139 		if (*p == ';')
140 			break;
141 		if (!ishexnumber(*p))
142 			return (-1);
143 		if (isdigit(*p)) {
144 			io->chunksize = io->chunksize * 16 +
145 			    *p - '0';
146 		} else {
147 			io->chunksize = io->chunksize * 16 +
148 			    10 + tolower(*p) - 'a';
149 		}
150 	}
151 
152 #ifndef NDEBUG
153 	if (fetchDebug) {
154 		io->total += io->chunksize;
155 		if (io->chunksize == 0)
156 			fprintf(stderr, "%s(): end of last chunk\n", __func__);
157 		else
158 			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
159 			    __func__, (unsigned long)io->chunksize,
160 			    (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  */
170 static 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  */
188 static 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  */
244 static 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  */
275 static 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  */
286 static 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  */
302 static 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 */
329 typedef 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 */
343 static 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  */
359 static 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  */
391 static 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  */
426 static 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  */
441 static 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  */
468 static 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  */
492 static 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  */
510 static 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 	p += 6;
518 	if (*p == '*') {
519 		first = last = -1;
520 		++p;
521 	} else {
522 		for (first = 0; *p && isdigit(*p); ++p)
523 			first = first * 10 + *p - '0';
524 		if (*p != '-')
525 			return (-1);
526 		for (last = 0, ++p; *p && isdigit(*p); ++p)
527 			last = last * 10 + *p - '0';
528 	}
529 	if (first > last || *p != '/')
530 		return (-1);
531 	for (len = 0, ++p; *p && isdigit(*p); ++p)
532 		len = len * 10 + *p - '0';
533 	if (*p || len < last - first + 1)
534 		return (-1);
535 	if (first == -1) {
536 		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
537 		    (long long)len));
538 		*length = 0;
539 	} else {
540 		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
541 		    (long long)first, (long long)last, (long long)len));
542 		*length = last - first + 1;
543 	}
544 	*offset = first;
545 	*size = len;
546 	return (0);
547 }
548 
549 
550 /*****************************************************************************
551  * Helper functions for authorization
552  */
553 
554 /*
555  * Base64 encoding
556  */
557 static char *
558 _http_base64(const char *src)
559 {
560 	static const char base64[] =
561 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
562 	    "abcdefghijklmnopqrstuvwxyz"
563 	    "0123456789+/";
564 	char *str, *dst;
565 	size_t l;
566 	int t, r;
567 
568 	l = strlen(src);
569 	if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
570 		return (NULL);
571 	dst = str;
572 	r = 0;
573 
574 	while (l >= 3) {
575 		t = (src[0] << 16) | (src[1] << 8) | src[2];
576 		dst[0] = base64[(t >> 18) & 0x3f];
577 		dst[1] = base64[(t >> 12) & 0x3f];
578 		dst[2] = base64[(t >> 6) & 0x3f];
579 		dst[3] = base64[(t >> 0) & 0x3f];
580 		src += 3; l -= 3;
581 		dst += 4; r += 4;
582 	}
583 
584 	switch (l) {
585 	case 2:
586 		t = (src[0] << 16) | (src[1] << 8);
587 		dst[0] = base64[(t >> 18) & 0x3f];
588 		dst[1] = base64[(t >> 12) & 0x3f];
589 		dst[2] = base64[(t >> 6) & 0x3f];
590 		dst[3] = '=';
591 		dst += 4;
592 		r += 4;
593 		break;
594 	case 1:
595 		t = src[0] << 16;
596 		dst[0] = base64[(t >> 18) & 0x3f];
597 		dst[1] = base64[(t >> 12) & 0x3f];
598 		dst[2] = dst[3] = '=';
599 		dst += 4;
600 		r += 4;
601 		break;
602 	case 0:
603 		break;
604 	}
605 
606 	*dst = 0;
607 	return (str);
608 }
609 
610 /*
611  * Encode username and password
612  */
613 static int
614 _http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
615 {
616 	char *upw, *auth;
617 	int r;
618 
619 	DEBUG(fprintf(stderr, "usr: [%s]\n", usr));
620 	DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
621 	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
622 		return (-1);
623 	auth = _http_base64(upw);
624 	free(upw);
625 	if (auth == NULL)
626 		return (-1);
627 	r = _http_cmd(conn, "%s: Basic %s", hdr, auth);
628 	free(auth);
629 	return (r);
630 }
631 
632 /*
633  * Send an authorization header
634  */
635 static int
636 _http_authorize(conn_t *conn, const char *hdr, const char *p)
637 {
638 	/* basic authorization */
639 	if (strncasecmp(p, "basic:", 6) == 0) {
640 		char *user, *pwd, *str;
641 		int r;
642 
643 		/* skip realm */
644 		for (p += 6; *p && *p != ':'; ++p)
645 			/* nothing */ ;
646 		if (!*p || strchr(++p, ':') == NULL)
647 			return (-1);
648 		if ((str = strdup(p)) == NULL)
649 			return (-1); /* XXX */
650 		user = str;
651 		pwd = strchr(str, ':');
652 		*pwd++ = '\0';
653 		r = _http_basic_auth(conn, hdr, user, pwd);
654 		free(str);
655 		return (r);
656 	}
657 	return (-1);
658 }
659 
660 
661 /*****************************************************************************
662  * Helper functions for connecting to a server or proxy
663  */
664 
665 /*
666  * Connect to the correct HTTP server or proxy.
667  */
668 static conn_t *
669 _http_connect(struct url *URL, struct url *purl, const char *flags)
670 {
671 	conn_t *conn;
672 	int verbose;
673 	int af;
674 
675 #ifdef INET6
676 	af = AF_UNSPEC;
677 #else
678 	af = AF_INET;
679 #endif
680 
681 	verbose = CHECK_FLAG('v');
682 	if (CHECK_FLAG('4'))
683 		af = AF_INET;
684 #ifdef INET6
685 	else if (CHECK_FLAG('6'))
686 		af = AF_INET6;
687 #endif
688 
689 	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
690 		URL = purl;
691 	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
692 		/* can't talk http to an ftp server */
693 		/* XXX should set an error code */
694 		return (NULL);
695 	}
696 
697 	if ((conn = _fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
698 		/* _fetch_connect() has already set an error code */
699 		return (NULL);
700 	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
701 	    _fetch_ssl(conn, verbose) == -1) {
702 		_fetch_close(conn);
703 		/* grrr */
704 		errno = EAUTH;
705 		_fetch_syserr();
706 		return (NULL);
707 	}
708 	return (conn);
709 }
710 
711 static struct url *
712 _http_get_proxy(const char *flags)
713 {
714 	struct url *purl;
715 	char *p;
716 
717 	if (flags != NULL && strchr(flags, 'd') != NULL)
718 		return (NULL);
719 	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
720 	    (purl = fetchParseURL(p))) {
721 		if (!*purl->scheme)
722 			strcpy(purl->scheme, SCHEME_HTTP);
723 		if (!purl->port)
724 			purl->port = _fetch_default_proxy_port(purl->scheme);
725 		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
726 			return (purl);
727 		fetchFreeURL(purl);
728 	}
729 	return (NULL);
730 }
731 
732 static void
733 _http_print_html(FILE *out, FILE *in)
734 {
735 	size_t len;
736 	char *line, *p, *q;
737 	int comment, tag;
738 
739 	comment = tag = 0;
740 	while ((line = fgetln(in, &len)) != NULL) {
741 		while (len && isspace(line[len - 1]))
742 			--len;
743 		for (p = q = line; q < line + len; ++q) {
744 			if (comment && *q == '-') {
745 				if (q + 2 < line + len &&
746 				    strcmp(q, "-->") == 0) {
747 					tag = comment = 0;
748 					q += 2;
749 				}
750 			} else if (tag && !comment && *q == '>') {
751 				p = q + 1;
752 				tag = 0;
753 			} else if (!tag && *q == '<') {
754 				if (q > p)
755 					fwrite(p, q - p, 1, out);
756 				tag = 1;
757 				if (q + 3 < line + len &&
758 				    strcmp(q, "<!--") == 0) {
759 					comment = 1;
760 					q += 3;
761 				}
762 			}
763 		}
764 		if (!tag && q > p)
765 			fwrite(p, q - p, 1, out);
766 		fputc('\n', out);
767 	}
768 }
769 
770 
771 /*****************************************************************************
772  * Core
773  */
774 
775 /*
776  * Send a request and process the reply
777  *
778  * XXX This function is way too long, the do..while loop should be split
779  * XXX off into a separate function.
780  */
781 FILE *
782 _http_request(struct url *URL, const char *op, struct url_stat *us,
783     struct url *purl, const char *flags)
784 {
785 	conn_t *conn;
786 	struct url *url, *new;
787 	int chunked, direct, need_auth, noredirect, verbose;
788 	int e, i, n;
789 	off_t offset, clength, length, size;
790 	time_t mtime;
791 	const char *p;
792 	FILE *f;
793 	hdr_t h;
794 	char hbuf[MAXHOSTNAMELEN + 7], *host;
795 
796 	direct = CHECK_FLAG('d');
797 	noredirect = CHECK_FLAG('A');
798 	verbose = CHECK_FLAG('v');
799 
800 	if (direct && purl) {
801 		fetchFreeURL(purl);
802 		purl = NULL;
803 	}
804 
805 	/* try the provided URL first */
806 	url = URL;
807 
808 	/* if the A flag is set, we only get one try */
809 	n = noredirect ? 1 : MAX_REDIRECT;
810 	i = 0;
811 
812 	e = HTTP_PROTOCOL_ERROR;
813 	need_auth = 0;
814 	do {
815 		new = NULL;
816 		chunked = 0;
817 		offset = 0;
818 		clength = -1;
819 		length = -1;
820 		size = -1;
821 		mtime = 0;
822 
823 		/* check port */
824 		if (!url->port)
825 			url->port = _fetch_default_port(url->scheme);
826 
827 		/* were we redirected to an FTP URL? */
828 		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
829 			if (strcmp(op, "GET") == 0)
830 				return (_ftp_request(url, "RETR", us, purl, flags));
831 			else if (strcmp(op, "HEAD") == 0)
832 				return (_ftp_request(url, "STAT", us, purl, flags));
833 		}
834 
835 		/* connect to server or proxy */
836 		if ((conn = _http_connect(url, purl, flags)) == NULL)
837 			goto ouch;
838 
839 		host = url->host;
840 #ifdef INET6
841 		if (strchr(url->host, ':')) {
842 			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
843 			host = hbuf;
844 		}
845 #endif
846 		if (url->port != _fetch_default_port(url->scheme)) {
847 			if (host != hbuf) {
848 				strcpy(hbuf, host);
849 				host = hbuf;
850 			}
851 			snprintf(hbuf + strlen(hbuf),
852 			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
853 		}
854 
855 		/* send request */
856 		if (verbose)
857 			_fetch_info("requesting %s://%s%s",
858 			    url->scheme, host, url->doc);
859 		if (purl) {
860 			_http_cmd(conn, "%s %s://%s%s HTTP/1.1",
861 			    op, url->scheme, host, url->doc);
862 		} else {
863 			_http_cmd(conn, "%s %s HTTP/1.1",
864 			    op, url->doc);
865 		}
866 
867 		/* virtual host */
868 		_http_cmd(conn, "Host: %s", host);
869 
870 		/* proxy authorization */
871 		if (purl) {
872 			if (*purl->user || *purl->pwd)
873 				_http_basic_auth(conn, "Proxy-Authorization",
874 				    purl->user, purl->pwd);
875 			else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
876 				_http_authorize(conn, "Proxy-Authorization", p);
877 		}
878 
879 		/* server authorization */
880 		if (need_auth || *url->user || *url->pwd) {
881 			if (*url->user || *url->pwd)
882 				_http_basic_auth(conn, "Authorization", url->user, url->pwd);
883 			else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
884 				_http_authorize(conn, "Authorization", p);
885 			else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
886 				_http_basic_auth(conn, "Authorization", url->user, url->pwd);
887 			} else {
888 				_http_seterr(HTTP_NEED_AUTH);
889 				goto ouch;
890 			}
891 		}
892 
893 		/* other headers */
894 		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
895 			if (strcasecmp(p, "auto") == 0)
896 				_http_cmd(conn, "Referer: %s://%s%s",
897 				    url->scheme, host, url->doc);
898 			else
899 				_http_cmd(conn, "Referer: %s", p);
900 		}
901 		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
902 			_http_cmd(conn, "User-Agent: %s", p);
903 		else
904 			_http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
905 		if (url->offset > 0)
906 			_http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
907 		_http_cmd(conn, "Connection: close");
908 		_http_cmd(conn, "");
909 
910 		/* get reply */
911 		switch (_http_get_reply(conn)) {
912 		case HTTP_OK:
913 		case HTTP_PARTIAL:
914 			/* fine */
915 			break;
916 		case HTTP_MOVED_PERM:
917 		case HTTP_MOVED_TEMP:
918 		case HTTP_SEE_OTHER:
919 			/*
920 			 * Not so fine, but we still have to read the
921 			 * headers to get the new location.
922 			 */
923 			break;
924 		case HTTP_NEED_AUTH:
925 			if (need_auth) {
926 				/*
927 				 * We already sent out authorization code,
928 				 * so there's nothing more we can do.
929 				 */
930 				_http_seterr(conn->err);
931 				goto ouch;
932 			}
933 			/* try again, but send the password this time */
934 			if (verbose)
935 				_fetch_info("server requires authorization");
936 			break;
937 		case HTTP_NEED_PROXY_AUTH:
938 			/*
939 			 * If we're talking to a proxy, we already sent
940 			 * our proxy authorization code, so there's
941 			 * nothing more we can do.
942 			 */
943 			_http_seterr(conn->err);
944 			goto ouch;
945 		case HTTP_BAD_RANGE:
946 			/*
947 			 * This can happen if we ask for 0 bytes because
948 			 * we already have the whole file.  Consider this
949 			 * a success for now, and check sizes later.
950 			 */
951 			break;
952 		case HTTP_PROTOCOL_ERROR:
953 			/* fall through */
954 		case -1:
955 			_fetch_syserr();
956 			goto ouch;
957 		default:
958 			_http_seterr(conn->err);
959 			if (!verbose)
960 				goto ouch;
961 			/* fall through so we can get the full error message */
962 		}
963 
964 		/* get headers */
965 		do {
966 			switch ((h = _http_next_header(conn, &p))) {
967 			case hdr_syserror:
968 				_fetch_syserr();
969 				goto ouch;
970 			case hdr_error:
971 				_http_seterr(HTTP_PROTOCOL_ERROR);
972 				goto ouch;
973 			case hdr_content_length:
974 				_http_parse_length(p, &clength);
975 				break;
976 			case hdr_content_range:
977 				_http_parse_range(p, &offset, &length, &size);
978 				break;
979 			case hdr_last_modified:
980 				_http_parse_mtime(p, &mtime);
981 				break;
982 			case hdr_location:
983 				if (!HTTP_REDIRECT(conn->err))
984 					break;
985 				if (new)
986 					free(new);
987 				if (verbose)
988 					_fetch_info("%d redirect to %s", conn->err, p);
989 				if (*p == '/')
990 					/* absolute path */
991 					new = fetchMakeURL(url->scheme, url->host, url->port, p,
992 					    url->user, url->pwd);
993 				else
994 					new = fetchParseURL(p);
995 				if (new == NULL) {
996 					/* XXX should set an error code */
997 					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
998 					goto ouch;
999 				}
1000 				if (!*new->user && !*new->pwd) {
1001 					strcpy(new->user, url->user);
1002 					strcpy(new->pwd, url->pwd);
1003 				}
1004 				new->offset = url->offset;
1005 				new->length = url->length;
1006 				break;
1007 			case hdr_transfer_encoding:
1008 				/* XXX weak test*/
1009 				chunked = (strcasecmp(p, "chunked") == 0);
1010 				break;
1011 			case hdr_www_authenticate:
1012 				if (conn->err != HTTP_NEED_AUTH)
1013 					break;
1014 				/* if we were smarter, we'd check the method and realm */
1015 				break;
1016 			case hdr_end:
1017 				/* fall through */
1018 			case hdr_unknown:
1019 				/* ignore */
1020 				break;
1021 			}
1022 		} while (h > hdr_end);
1023 
1024 		/* we need to provide authentication */
1025 		if (conn->err == HTTP_NEED_AUTH) {
1026 			e = conn->err;
1027 			need_auth = 1;
1028 			_fetch_close(conn);
1029 			conn = NULL;
1030 			continue;
1031 		}
1032 
1033 		/* requested range not satisfiable */
1034 		if (conn->err == HTTP_BAD_RANGE) {
1035 			if (url->offset == size && url->length == 0) {
1036 				/* asked for 0 bytes; fake it */
1037 				offset = url->offset;
1038 				conn->err = HTTP_OK;
1039 				break;
1040 			} else {
1041 				_http_seterr(conn->err);
1042 				goto ouch;
1043 			}
1044 		}
1045 
1046 		/* we have a hit or an error */
1047 		if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
1048 			break;
1049 
1050 		/* all other cases: we got a redirect */
1051 		e = conn->err;
1052 		need_auth = 0;
1053 		_fetch_close(conn);
1054 		conn = NULL;
1055 		if (!new) {
1056 			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1057 			break;
1058 		}
1059 		if (url != URL)
1060 			fetchFreeURL(url);
1061 		url = new;
1062 	} while (++i < n);
1063 
1064 	/* we failed, or ran out of retries */
1065 	if (conn == NULL) {
1066 		_http_seterr(e);
1067 		goto ouch;
1068 	}
1069 
1070 	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1071 		  " size %lld, clength %lld\n",
1072 		  (long long)offset, (long long)length,
1073 		  (long long)size, (long long)clength));
1074 
1075 	/* check for inconsistencies */
1076 	if (clength != -1 && length != -1 && clength != length) {
1077 		_http_seterr(HTTP_PROTOCOL_ERROR);
1078 		goto ouch;
1079 	}
1080 	if (clength == -1)
1081 		clength = length;
1082 	if (clength != -1)
1083 		length = offset + clength;
1084 	if (length != -1 && size != -1 && length != size) {
1085 		_http_seterr(HTTP_PROTOCOL_ERROR);
1086 		goto ouch;
1087 	}
1088 	if (size == -1)
1089 		size = length;
1090 
1091 	/* fill in stats */
1092 	if (us) {
1093 		us->size = size;
1094 		us->atime = us->mtime = mtime;
1095 	}
1096 
1097 	/* too far? */
1098 	if (URL->offset > 0 && offset > URL->offset) {
1099 		_http_seterr(HTTP_PROTOCOL_ERROR);
1100 		goto ouch;
1101 	}
1102 
1103 	/* report back real offset and size */
1104 	URL->offset = offset;
1105 	URL->length = clength;
1106 
1107 	/* wrap it up in a FILE */
1108 	if ((f = _http_funopen(conn, chunked)) == NULL) {
1109 		_fetch_syserr();
1110 		goto ouch;
1111 	}
1112 
1113 	if (url != URL)
1114 		fetchFreeURL(url);
1115 	if (purl)
1116 		fetchFreeURL(purl);
1117 
1118 	if (HTTP_ERROR(conn->err)) {
1119 		_http_print_html(stderr, f);
1120 		fclose(f);
1121 		f = NULL;
1122 	}
1123 
1124 	return (f);
1125 
1126 ouch:
1127 	if (url != URL)
1128 		fetchFreeURL(url);
1129 	if (purl)
1130 		fetchFreeURL(purl);
1131 	if (conn != NULL)
1132 		_fetch_close(conn);
1133 	return (NULL);
1134 }
1135 
1136 
1137 /*****************************************************************************
1138  * Entry points
1139  */
1140 
1141 /*
1142  * Retrieve and stat a file by HTTP
1143  */
1144 FILE *
1145 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1146 {
1147 	return (_http_request(URL, "GET", us, _http_get_proxy(flags), flags));
1148 }
1149 
1150 /*
1151  * Retrieve a file by HTTP
1152  */
1153 FILE *
1154 fetchGetHTTP(struct url *URL, const char *flags)
1155 {
1156 	return (fetchXGetHTTP(URL, NULL, flags));
1157 }
1158 
1159 /*
1160  * Store a file by HTTP
1161  */
1162 FILE *
1163 fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1164 {
1165 	warnx("fetchPutHTTP(): not implemented");
1166 	return (NULL);
1167 }
1168 
1169 /*
1170  * Get an HTTP document's metadata
1171  */
1172 int
1173 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1174 {
1175 	FILE *f;
1176 
1177 	f = _http_request(URL, "HEAD", us, _http_get_proxy(flags), flags);
1178 	if (f == NULL)
1179 		return (-1);
1180 	fclose(f);
1181 	return (0);
1182 }
1183 
1184 /*
1185  * List a directory
1186  */
1187 struct url_ent *
1188 fetchListHTTP(struct url *url __unused, const char *flags __unused)
1189 {
1190 	warnx("fetchListHTTP(): not implemented");
1191 	return (NULL);
1192 }
1193