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