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