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