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