xref: /freebsd/lib/libfetch/http.c (revision 4cee73c80f52cef57f3e95357ada6ea352be14e2)
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  *      $FreeBSD$
29  */
30 
31 /*
32  * The following copyright applies to the base64 code:
33  *
34  *-
35  * Copyright 1997 Massachusetts Institute of Technology
36  *
37  * Permission to use, copy, modify, and distribute this software and
38  * its documentation for any purpose and without fee is hereby
39  * granted, provided that both the above copyright notice and this
40  * permission notice appear in all copies, that both the above
41  * copyright notice and this permission notice appear in all
42  * supporting documentation, and that the name of M.I.T. not be used
43  * in advertising or publicity pertaining to distribution of the
44  * software without specific, written prior permission.  M.I.T. makes
45  * no representations about the suitability of this software for any
46  * purpose.  It is provided "as is" without express or implied
47  * warranty.
48  *
49  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
50  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
51  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
52  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
53  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
54  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
55  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
56  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
57  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
58  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
59  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 
63 #include <sys/param.h>
64 #include <sys/socket.h>
65 
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <locale.h>
70 #include <netdb.h>
71 #include <stdarg.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <time.h>
76 #include <unistd.h>
77 
78 #include "fetch.h"
79 #include "common.h"
80 #include "httperr.h"
81 
82 extern char *__progname; /* XXX not portable */
83 
84 /* Maximum number of redirects to follow */
85 #define MAX_REDIRECT 5
86 
87 /* Symbolic names for reply codes we care about */
88 #define HTTP_OK			200
89 #define HTTP_PARTIAL		206
90 #define HTTP_MOVED_PERM		301
91 #define HTTP_MOVED_TEMP		302
92 #define HTTP_SEE_OTHER		303
93 #define HTTP_NEED_AUTH		401
94 #define HTTP_NEED_PROXY_AUTH	403
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 
102 
103 /*****************************************************************************
104  * I/O functions for decoding chunked streams
105  */
106 
107 struct cookie
108 {
109     int		 fd;
110     char	*buf;
111     size_t	 b_size;
112     size_t	 b_len;
113     int		 b_pos;
114     int		 eof;
115     int		 error;
116     long	 chunksize;
117 #ifndef NDEBUG
118     long	 total;
119 #endif
120 };
121 
122 /*
123  * Get next chunk header
124  */
125 static int
126 _http_new_chunk(struct cookie *c)
127 {
128     char *p;
129 
130     if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1)
131 	return -1;
132 
133     if (c->b_len < 2 || !ishexnumber(*c->buf))
134 	return -1;
135 
136     for (p = c->buf; !isspace(*p) && *p != ';' && p < c->buf + c->b_len; ++p)
137 	if (!ishexnumber(*p))
138 	    return -1;
139 	else if (isdigit(*p))
140 	    c->chunksize = c->chunksize * 16 + *p - '0';
141 	else
142 	    c->chunksize = c->chunksize * 16 + 10 + tolower(*p) - 'a';
143 
144 #ifndef NDEBUG
145     c->total += c->chunksize;
146     if (c->chunksize == 0)
147 	fprintf(stderr, "\033[1m_http_fillbuf(): "
148 		"end of last chunk\033[m\n");
149     else
150 	fprintf(stderr, "\033[1m_http_fillbuf(): "
151 		"new chunk: %ld (%ld)\033[m\n", c->chunksize, c->total);
152 #endif
153 
154     return c->chunksize;
155 }
156 
157 /*
158  * Fill the input buffer, do chunk decoding on the fly
159  */
160 static int
161 _http_fillbuf(struct cookie *c)
162 {
163     if (c->error)
164 	return -1;
165     if (c->eof)
166 	return 0;
167 
168     if (c->chunksize == 0) {
169 	switch (_http_new_chunk(c)) {
170 	case -1:
171 	    c->error = 1;
172 	    return -1;
173 	case 0:
174 	    c->eof = 1;
175 	    return 0;
176 	}
177     }
178 
179     if (c->b_size < c->chunksize) {
180 	char *tmp;
181 
182 	if ((tmp = realloc(c->buf, c->chunksize)) == NULL)
183 	    return -1;
184 	c->buf = tmp;
185 	c->b_size = c->chunksize;
186     }
187 
188     if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1)
189 	return -1;
190     c->chunksize -= c->b_len;
191 
192     if (c->chunksize == 0) {
193 	char endl[2];
194 	read(c->fd, endl, 2);
195     }
196 
197     c->b_pos = 0;
198 
199     return c->b_len;
200 }
201 
202 /*
203  * Read function
204  */
205 static int
206 _http_readfn(void *v, char *buf, int len)
207 {
208     struct cookie *c = (struct cookie *)v;
209     int l, pos;
210 
211     if (c->error)
212 	return -1;
213     if (c->eof)
214 	return 0;
215 
216     for (pos = 0; len > 0; pos += l, len -= l) {
217 	/* empty buffer */
218 	if (!c->buf || c->b_pos == c->b_len)
219 	    if (_http_fillbuf(c) < 1)
220 		break;
221 	l = c->b_len - c->b_pos;
222 	if (len < l)
223 	    l = len;
224 	bcopy(c->buf + c->b_pos, buf + pos, l);
225 	c->b_pos += l;
226     }
227 
228     if (!pos && c->error)
229 	return -1;
230     return pos;
231 }
232 
233 /*
234  * Write function
235  */
236 static int
237 _http_writefn(void *v, const char *buf, int len)
238 {
239     struct cookie *c = (struct cookie *)v;
240 
241     return write(c->fd, buf, len);
242 }
243 
244 /*
245  * Close function
246  */
247 static int
248 _http_closefn(void *v)
249 {
250     struct cookie *c = (struct cookie *)v;
251     int r;
252 
253     r = close(c->fd);
254     if (c->buf)
255 	free(c->buf);
256     free(c);
257     return r;
258 }
259 
260 /*
261  * Wrap a file descriptor up
262  */
263 static FILE *
264 _http_funopen(int fd)
265 {
266     struct cookie *c;
267     FILE *f;
268 
269     if ((c = calloc(1, sizeof *c)) == NULL) {
270 	_fetch_syserr();
271 	return NULL;
272     }
273     c->fd = fd;
274     if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) {
275 	_fetch_syserr();
276 	free(c);
277 	return NULL;
278     }
279     return f;
280 }
281 
282 
283 /*****************************************************************************
284  * Helper functions for talking to the server and parsing its replies
285  */
286 
287 /* Header types */
288 typedef enum {
289     hdr_syserror = -2,
290     hdr_error = -1,
291     hdr_end = 0,
292     hdr_unknown = 1,
293     hdr_content_length,
294     hdr_content_range,
295     hdr_last_modified,
296     hdr_location,
297     hdr_transfer_encoding
298 } hdr;
299 
300 /* Names of interesting headers */
301 static struct {
302     hdr		 num;
303     char	*name;
304 } hdr_names[] = {
305     { hdr_content_length,	"Content-Length" },
306     { hdr_content_range,	"Content-Range" },
307     { hdr_last_modified,	"Last-Modified" },
308     { hdr_location,		"Location" },
309     { hdr_transfer_encoding,	"Transfer-Encoding" },
310     { hdr_unknown,		NULL },
311 };
312 
313 static char	*reply_buf;
314 static size_t	 reply_size;
315 static size_t	 reply_length;
316 
317 /*
318  * Send a formatted line; optionally echo to terminal
319  */
320 static int
321 _http_cmd(int fd, char *fmt, ...)
322 {
323     va_list ap;
324     size_t len;
325     char *msg;
326     int r;
327 
328     va_start(ap, fmt);
329     len = vasprintf(&msg, fmt, ap);
330     va_end(ap);
331 
332     if (msg == NULL) {
333 	errno = ENOMEM;
334 	_fetch_syserr();
335 	return -1;
336     }
337 
338     r = _fetch_putln(fd, msg, len);
339     free(msg);
340 
341     if (r == -1) {
342 	_fetch_syserr();
343 	return -1;
344     }
345 
346     return 0;
347 }
348 
349 /*
350  * Get and parse status line
351  */
352 static int
353 _http_get_reply(int fd)
354 {
355     char *p;
356 
357     if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
358 	return -1;
359     /*
360      * A valid status line looks like "HTTP/m.n xyz reason" where m
361      * and n are the major and minor protocol version numbers and xyz
362      * is the reply code.
363      * Unfortunately, there are servers out there (NCSA 1.5.1, to name
364      * just one) that do not send a version number, so we can't rely
365      * on finding one, but if we do, insist on it being 1.0 or 1.1.
366      * We don't care about the reason phrase.
367      */
368     if (strncmp(reply_buf, "HTTP", 4) != 0)
369 	return HTTP_PROTOCOL_ERROR;
370     p = reply_buf + 4;
371     if (*p == '/') {
372 	if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
373 	    return HTTP_PROTOCOL_ERROR;
374 	p += 4;
375     }
376     if (*p != ' '
377 	|| !isdigit(p[1])
378 	|| !isdigit(p[2])
379 	|| !isdigit(p[3]))
380 	return HTTP_PROTOCOL_ERROR;
381 
382     return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'));
383 }
384 
385 /*
386  * Check a header; if the type matches the given string, return a
387  * pointer to the beginning of the value.
388  */
389 static char *
390 _http_match(char *str, char *hdr)
391 {
392     while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
393 	/* nothing */;
394     if (*str || *hdr != ':')
395 	return NULL;
396     while (*hdr && isspace(*++hdr))
397 	/* nothing */;
398     return hdr;
399 }
400 
401 /*
402  * Get the next header and return the appropriate symbolic code.
403  */
404 static hdr
405 _http_next_header(int fd, char **p)
406 {
407     int i;
408 
409     if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1)
410 	return hdr_syserror;
411     while (reply_length && isspace(reply_buf[reply_length-1]))
412 	reply_length--;
413     reply_buf[reply_length] = 0;
414     if (reply_length == 0)
415 	return hdr_end;
416     /*
417      * We could check for malformed headers but we don't really care.
418      * A valid header starts with a token immediately followed by a
419      * colon; a token is any sequence of non-control, non-whitespace
420      * characters except "()<>@,;:\\\"{}".
421      */
422     for (i = 0; hdr_names[i].num != hdr_unknown; i++)
423 	if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL)
424 	    return hdr_names[i].num;
425     return hdr_unknown;
426 }
427 
428 /*
429  * Parse a last-modified header
430  */
431 static int
432 _http_parse_mtime(char *p, time_t *mtime)
433 {
434     char locale[64], *r;
435     struct tm tm;
436 
437     strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale);
438     setlocale(LC_TIME, "C");
439     r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
440     /* XXX should add support for date-2 and date-3 */
441     setlocale(LC_TIME, locale);
442     if (r == NULL)
443 	return -1;
444     DEBUG(fprintf(stderr, "last modified: [\033[1m%04d-%02d-%02d "
445 		  "%02d:%02d:%02d\033[m]\n",
446 		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
447 		  tm.tm_hour, tm.tm_min, tm.tm_sec));
448     *mtime = timegm(&tm);
449     return 0;
450 }
451 
452 /*
453  * Parse a content-length header
454  */
455 static int
456 _http_parse_length(char *p, off_t *length)
457 {
458     off_t len;
459 
460     for (len = 0; *p && isdigit(*p); ++p)
461 	len = len * 10 + (*p - '0');
462     DEBUG(fprintf(stderr, "content length: [\033[1m%lld\033[m]\n", len));
463     *length = len;
464     return 0;
465 }
466 
467 /*
468  * Parse a content-range header
469  */
470 static int
471 _http_parse_range(char *p, off_t *offset, off_t *length, off_t *size)
472 {
473     int first, last, len;
474 
475     if (strncasecmp(p, "bytes ", 6) != 0)
476 	return -1;
477     for (first = 0, p += 6; *p && isdigit(*p); ++p)
478 	first = first * 10 + *p - '0';
479     if (*p != '-')
480 	return -1;
481     for (last = 0, ++p; *p && isdigit(*p); ++p)
482 	last = last * 10 + *p - '0';
483     if (first > last || *p != '/')
484 	return -1;
485     for (len = 0, ++p; *p && isdigit(*p); ++p)
486 	len = len * 10 + *p - '0';
487     if (len < last - first + 1)
488 	return -1;
489     DEBUG(fprintf(stderr, "content range: [\033[1m%d-%d/%d\033[m]\n",
490 		  first, last, len));
491     *offset = first;
492     *length = last - first + 1;
493     *size = len;
494     return 0;
495 }
496 
497 
498 /*****************************************************************************
499  * Helper functions for authorization
500  */
501 
502 /*
503  * Base64 encoding
504  */
505 static char *
506 _http_base64(char *src)
507 {
508     static const char base64[] =
509 	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
510 	"abcdefghijklmnopqrstuvwxyz"
511 	"0123456789+/";
512     char *str, *dst;
513     size_t l;
514     int t, r;
515 
516     l = strlen(src);
517     if ((str = malloc(((l + 2) / 3) * 4)) == NULL)
518 	return NULL;
519     dst = str;
520     r = 0;
521 
522     while (l >= 3) {
523 	t = (src[0] << 16) | (src[1] << 8) | src[2];
524 	dst[0] = base64[(t >> 18) & 0x3f];
525 	dst[1] = base64[(t >> 12) & 0x3f];
526 	dst[2] = base64[(t >> 6) & 0x3f];
527 	dst[3] = base64[(t >> 0) & 0x3f];
528 	src += 3; l -= 3;
529 	dst += 4; r += 4;
530     }
531 
532     switch (l) {
533     case 2:
534 	t = (src[0] << 16) | (src[1] << 8);
535 	dst[0] = base64[(t >> 18) & 0x3f];
536 	dst[1] = base64[(t >> 12) & 0x3f];
537 	dst[2] = base64[(t >> 6) & 0x3f];
538 	dst[3] = '=';
539 	dst += 4;
540 	r += 4;
541 	break;
542     case 1:
543 	t = src[0] << 16;
544 	dst[0] = base64[(t >> 18) & 0x3f];
545 	dst[1] = base64[(t >> 12) & 0x3f];
546 	dst[2] = dst[3] = '=';
547 	dst += 4;
548 	r += 4;
549 	break;
550     case 0:
551 	break;
552     }
553 
554     *dst = 0;
555     return str;
556 }
557 
558 /*
559  * Encode username and password
560  */
561 static int
562 _http_basic_auth(int fd, char *hdr, char *usr, char *pwd)
563 {
564     char *upw, *auth;
565     int r;
566 
567     if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
568 	return -1;
569     auth = _http_base64(upw);
570     free(upw);
571     if (auth == NULL)
572 	return -1;
573     r = _http_cmd(fd, "%s: Basic %s", hdr, auth);
574     free(auth);
575     return r;
576 }
577 
578 /*
579  * Send an authorization header
580  */
581 static int
582 _http_authorize(int fd, char *hdr, char *p)
583 {
584     /* basic authorization */
585     if (strncasecmp(p, "basic:", 6) == 0) {
586 	char *user, *pwd, *str;
587 	int r;
588 
589 	/* skip realm */
590 	for (p += 6; *p && *p != ':'; ++p)
591 	    /* nothing */ ;
592 	if (!*p || strchr(++p, ':') == NULL)
593 	    return -1;
594 	if ((str = strdup(p)) == NULL)
595 	    return -1; /* XXX */
596 	user = str;
597 	pwd = strchr(str, ':');
598 	*pwd++ = '\0';
599 	r = _http_basic_auth(fd, hdr, user, pwd);
600 	free(str);
601 	return r;
602     }
603     return -1;
604 }
605 
606 
607 /*****************************************************************************
608  * Helper functions for connecting to a server or proxy
609  */
610 
611 /*
612  * Connect to the correct HTTP server or proxy.
613  */
614 static int
615 _http_connect(struct url *URL, struct url *purl, char *flags)
616 {
617     int verbose;
618     int af, fd;
619 
620 #ifdef INET6
621     af = AF_UNSPEC;
622 #else
623     af = AF_INET;
624 #endif
625 
626     verbose = CHECK_FLAG('v');
627     if (CHECK_FLAG('4'))
628 	af = AF_INET;
629 #ifdef INET6
630     else if (CHECK_FLAG('6'))
631 	af = AF_INET6;
632 #endif
633 
634     if (purl) {
635 	URL = purl;
636     } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
637 	/* can't talk http to an ftp server */
638 	/* XXX should set an error code */
639 	return -1;
640     }
641 
642     if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1)
643 	/* _fetch_connect() has already set an error code */
644 	return -1;
645     return fd;
646 }
647 
648 static struct url *
649 _http_get_proxy()
650 {
651     struct url *purl;
652     char *p;
653 
654     if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
655 	(purl = fetchParseURL(p))) {
656 	if (!*purl->scheme)
657 	    strcpy(purl->scheme, SCHEME_HTTP);
658 	if (!purl->port)
659 	    purl->port = _fetch_default_proxy_port(purl->scheme);
660 	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
661 	    return purl;
662 	fetchFreeURL(purl);
663     }
664     return NULL;
665 }
666 
667 
668 /*****************************************************************************
669  * Core
670  */
671 
672 /*
673  * Send a request and process the reply
674  */
675 FILE *
676 _http_request(struct url *URL, char *op, struct url_stat *us,
677 	      struct url *purl, char *flags)
678 {
679     struct url *url, *new;
680     int chunked, direct, need_auth, noredirect, verbose;
681     int code, fd, i, n;
682     off_t offset, clength, length, size;
683     time_t mtime;
684     char *p;
685     FILE *f;
686     hdr h;
687     char *host;
688 #ifdef INET6
689     char hbuf[MAXHOSTNAMELEN + 1];
690 #endif
691 
692     direct = CHECK_FLAG('d');
693     noredirect = CHECK_FLAG('A');
694     verbose = CHECK_FLAG('v');
695 
696     if (direct && purl) {
697 	fetchFreeURL(purl);
698 	purl = NULL;
699     }
700 
701     /* try the provided URL first */
702     url = URL;
703 
704     /* if the A flag is set, we only get one try */
705     n = noredirect ? 1 : MAX_REDIRECT;
706     i = 0;
707 
708     do {
709 	new = NULL;
710 	chunked = 0;
711 	need_auth = 0;
712 	offset = 0;
713 	clength = -1;
714 	length = -1;
715 	size = -1;
716 	mtime = 0;
717     retry:
718 	/* check port */
719 	if (!url->port)
720 	    url->port = _fetch_default_port(url->scheme);
721 
722 	/* connect to server or proxy */
723 	if ((fd = _http_connect(url, purl, flags)) == -1)
724 	    goto ouch;
725 
726 	host = url->host;
727 #ifdef INET6
728 	if (strchr(url->host, ':')) {
729 	    snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
730 	    host = hbuf;
731 	}
732 #endif
733 
734 	/* send request */
735 	if (verbose)
736 	    _fetch_info("requesting %s://%s:%d%s",
737 			url->scheme, host, url->port, url->doc);
738 	if (purl) {
739 	    _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1",
740 		      op, url->scheme, host, url->port, url->doc);
741 	} else {
742 	    _http_cmd(fd, "%s %s HTTP/1.1",
743 		      op, url->doc);
744 	}
745 
746 	/* proxy authorization */
747 	if (purl) {
748 	    if (*purl->user || *purl->pwd)
749 		_http_basic_auth(fd, "Proxy-Authorization",
750 				 purl->user, purl->pwd);
751 	    else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
752 		_http_authorize(fd, "Proxy-Authorization", p);
753 	}
754 
755 	/* server authorization */
756 	if (need_auth) {
757 	    if (*url->user || *url->pwd)
758 		_http_basic_auth(fd, "Authorization", url->user, url->pwd);
759 	    else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
760 		_http_authorize(fd, "Authorization", p);
761 	    else {
762 		_http_seterr(HTTP_NEED_AUTH);
763 		goto ouch;
764 	    }
765 	}
766 
767 	/* other headers */
768 	if (url->port == _fetch_default_port(url->scheme))
769 	    _http_cmd(fd, "Host: %s", host);
770 	else
771 	    _http_cmd(fd, "Host: %s:%d", host, url->port);
772 	_http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname);
773 	if (url->offset)
774 	    _http_cmd(fd, "Range: bytes=%lld-", url->offset);
775 	_http_cmd(fd, "Connection: close");
776 	_http_cmd(fd, "");
777 
778 	/* get reply */
779 	switch ((code = _http_get_reply(fd))) {
780 	case HTTP_OK:
781 	case HTTP_PARTIAL:
782 	    /* fine */
783 	    break;
784 	case HTTP_MOVED_PERM:
785 	case HTTP_MOVED_TEMP:
786 	    /*
787 	     * Not so fine, but we still have to read the headers to
788 	     * get the new location.
789 	     */
790 	    break;
791 	case HTTP_NEED_AUTH:
792 	    if (need_auth) {
793 		/*
794 		 * We already sent out authorization code, so there's
795 		 * nothing more we can do.
796 		 */
797 		_http_seterr(code);
798 		goto ouch;
799 	    }
800 	    /* try again, but send the password this time */
801 	    if (verbose)
802 		_fetch_info("server requires authorization");
803 	    need_auth = 1;
804 	    close(fd);
805 	    goto retry;
806 	case HTTP_NEED_PROXY_AUTH:
807 	    /*
808 	     * If we're talking to a proxy, we already sent our proxy
809 	     * authorization code, so there's nothing more we can do.
810 	     */
811 	    _http_seterr(code);
812 	    goto ouch;
813 	case HTTP_PROTOCOL_ERROR:
814 	    /* fall through */
815 	case -1:
816 	    _fetch_syserr();
817 	    goto ouch;
818 	default:
819 	    _http_seterr(code);
820 	    goto ouch;
821 	}
822 
823 	/* get headers */
824 	do {
825 	    switch ((h = _http_next_header(fd, &p))) {
826 	    case hdr_syserror:
827 		_fetch_syserr();
828 		goto ouch;
829 	    case hdr_error:
830 		_http_seterr(HTTP_PROTOCOL_ERROR);
831 		goto ouch;
832 	    case hdr_content_length:
833 		_http_parse_length(p, &clength);
834 		break;
835 	    case hdr_content_range:
836 		_http_parse_range(p, &offset, &length, &size);
837 		break;
838 	    case hdr_last_modified:
839 		_http_parse_mtime(p, &mtime);
840 		break;
841 	    case hdr_location:
842 		if (!HTTP_REDIRECT(code))
843 		    break;
844 		if (new)
845 		    free(new);
846 		if (verbose)
847 		    _fetch_info("%d redirect to %s", code, p);
848 		if (*p == '/')
849 		    /* absolute path */
850 		    new = fetchMakeURL(url->scheme, url->host, url->port, p,
851 				       url->user, url->pwd);
852 		else
853 		    new = fetchParseURL(p);
854 		if (new == NULL) {
855 		    /* XXX should set an error code */
856 		    DEBUG(fprintf(stderr, "failed to parse new URL\n"));
857 		    goto ouch;
858 		}
859 		if (!*new->user && !*new->pwd) {
860 		    strcpy(new->user, url->user);
861 		    strcpy(new->pwd, url->pwd);
862 		}
863 		new->offset = url->offset;
864 		new->length = url->length;
865 		break;
866 	    case hdr_transfer_encoding:
867 		/* XXX weak test*/
868 		chunked = (strcasecmp(p, "chunked") == 0);
869 		break;
870 	    case hdr_end:
871 		/* fall through */
872 	    case hdr_unknown:
873 		/* ignore */
874 		break;
875 	    }
876 	} while (h > hdr_end);
877 
878 	/* we either have a hit, or a redirect with no Location: header */
879 	if (code == HTTP_OK || code == HTTP_PARTIAL || !new)
880 	    break;
881 
882 	/* we have a redirect */
883 	close(fd);
884 	fd = -1;
885 	if (url != URL)
886 	    fetchFreeURL(url);
887 	url = new;
888     } while (++i < n);
889 
890     /* no success */
891     if (fd == -1) {
892 	_http_seterr(code);
893 	goto ouch;
894     }
895 
896     DEBUG(fprintf(stderr, "offset %lld, length %lld, size %lld, clength %lld\n",
897 		  offset, length, size, clength));
898 
899     /* check for inconsistencies */
900     if (clength != -1 && length != -1 && clength != length) {
901 	_http_seterr(HTTP_PROTOCOL_ERROR);
902 	goto ouch;
903     }
904     if (clength == -1)
905 	clength = length;
906     if (clength != -1)
907 	length = offset + clength;
908     if (length != -1 && size != -1 && length != size) {
909 	_http_seterr(HTTP_PROTOCOL_ERROR);
910 	goto ouch;
911     }
912     if (size == -1)
913 	size = length;
914 
915     /* fill in stats */
916     if (us) {
917 	us->size = size;
918 	us->atime = us->mtime = mtime;
919     }
920 
921     /* too far? */
922     if (offset > URL->offset) {
923 	_http_seterr(HTTP_PROTOCOL_ERROR);
924 	goto ouch;
925     }
926 
927     /* report back real offset and size */
928     URL->offset = offset;
929     URL->length = clength;
930 
931     /* wrap it up in a FILE */
932     if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) {
933 	_fetch_syserr();
934 	goto ouch;
935     }
936 
937     if (url != URL)
938 	fetchFreeURL(url);
939     if (purl)
940 	fetchFreeURL(purl);
941 
942     return f;
943 
944  ouch:
945     if (url != URL)
946 	fetchFreeURL(url);
947     if (purl)
948 	fetchFreeURL(purl);
949     if (fd != -1)
950 	close(fd);
951     return NULL;
952 }
953 
954 
955 /*****************************************************************************
956  * Entry points
957  */
958 
959 /*
960  * Retrieve and stat a file by HTTP
961  */
962 FILE *
963 fetchXGetHTTP(struct url *URL, struct url_stat *us, char *flags)
964 {
965     return _http_request(URL, "GET", us, _http_get_proxy(), flags);
966 }
967 
968 /*
969  * Retrieve a file by HTTP
970  */
971 FILE *
972 fetchGetHTTP(struct url *URL, char *flags)
973 {
974     return fetchXGetHTTP(URL, NULL, flags);
975 }
976 
977 /*
978  * Store a file by HTTP
979  */
980 FILE *
981 fetchPutHTTP(struct url *URL, char *flags)
982 {
983     warnx("fetchPutHTTP(): not implemented");
984     return NULL;
985 }
986 
987 /*
988  * Get an HTTP document's metadata
989  */
990 int
991 fetchStatHTTP(struct url *URL, struct url_stat *us, char *flags)
992 {
993     FILE *f;
994 
995     if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL)
996 	return -1;
997     fclose(f);
998     return 0;
999 }
1000 
1001 /*
1002  * List a directory
1003  */
1004 struct url_ent *
1005 fetchListHTTP(struct url *url, char *flags)
1006 {
1007     warnx("fetchListHTTP(): not implemented");
1008     return NULL;
1009 }
1010