http.c revision 230307
1/*-
2 * Copyright (c) 2000-2011 Dag-Erling 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 230307 2012-01-18 15:13:21Z des $");
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#include <sys/time.h>
67
68#include <ctype.h>
69#include <err.h>
70#include <errno.h>
71#include <locale.h>
72#include <netdb.h>
73#include <stdarg.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <time.h>
78#include <unistd.h>
79#include <md5.h>
80
81#include <netinet/in.h>
82#include <netinet/tcp.h>
83
84#include "fetch.h"
85#include "common.h"
86#include "httperr.h"
87
88/* Maximum number of redirects to follow */
89#define MAX_REDIRECT 5
90
91/* Symbolic names for reply codes we care about */
92#define HTTP_OK			200
93#define HTTP_PARTIAL		206
94#define HTTP_MOVED_PERM		301
95#define HTTP_MOVED_TEMP		302
96#define HTTP_SEE_OTHER		303
97#define HTTP_NOT_MODIFIED	304
98#define HTTP_TEMP_REDIRECT	307
99#define HTTP_NEED_AUTH		401
100#define HTTP_NEED_PROXY_AUTH	407
101#define HTTP_BAD_RANGE		416
102#define HTTP_PROTOCOL_ERROR	999
103
104#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
105			    || (xyz) == HTTP_MOVED_TEMP \
106			    || (xyz) == HTTP_TEMP_REDIRECT \
107			    || (xyz) == HTTP_SEE_OTHER)
108
109#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
110
111
112/*****************************************************************************
113 * I/O functions for decoding chunked streams
114 */
115
116struct httpio
117{
118	conn_t		*conn;		/* connection */
119	int		 chunked;	/* chunked mode */
120	char		*buf;		/* chunk buffer */
121	size_t		 bufsize;	/* size of chunk buffer */
122	ssize_t		 buflen;	/* amount of data currently in buffer */
123	int		 bufpos;	/* current read offset in buffer */
124	int		 eof;		/* end-of-file flag */
125	int		 error;		/* error flag */
126	size_t		 chunksize;	/* remaining size of current chunk */
127#ifndef NDEBUG
128	size_t		 total;
129#endif
130};
131
132/*
133 * Get next chunk header
134 */
135static int
136http_new_chunk(struct httpio *io)
137{
138	char *p;
139
140	if (fetch_getln(io->conn) == -1)
141		return (-1);
142
143	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
144		return (-1);
145
146	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
147		if (*p == ';')
148			break;
149		if (!isxdigit((unsigned char)*p))
150			return (-1);
151		if (isdigit((unsigned char)*p)) {
152			io->chunksize = io->chunksize * 16 +
153			    *p - '0';
154		} else {
155			io->chunksize = io->chunksize * 16 +
156			    10 + tolower((unsigned char)*p) - 'a';
157		}
158	}
159
160#ifndef NDEBUG
161	if (fetchDebug) {
162		io->total += io->chunksize;
163		if (io->chunksize == 0)
164			fprintf(stderr, "%s(): end of last chunk\n", __func__);
165		else
166			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
167			    __func__, (unsigned long)io->chunksize,
168			    (unsigned long)io->total);
169	}
170#endif
171
172	return (io->chunksize);
173}
174
175/*
176 * Grow the input buffer to at least len bytes
177 */
178static inline int
179http_growbuf(struct httpio *io, size_t len)
180{
181	char *tmp;
182
183	if (io->bufsize >= len)
184		return (0);
185
186	if ((tmp = realloc(io->buf, len)) == NULL)
187		return (-1);
188	io->buf = tmp;
189	io->bufsize = len;
190	return (0);
191}
192
193/*
194 * Fill the input buffer, do chunk decoding on the fly
195 */
196static int
197http_fillbuf(struct httpio *io, size_t len)
198{
199	ssize_t nbytes;
200
201	if (io->error)
202		return (-1);
203	if (io->eof)
204		return (0);
205
206	if (io->chunked == 0) {
207		if (http_growbuf(io, len) == -1)
208			return (-1);
209		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
210			io->error = errno;
211			return (-1);
212		}
213		io->buflen = nbytes;
214		io->bufpos = 0;
215		return (io->buflen);
216	}
217
218	if (io->chunksize == 0) {
219		switch (http_new_chunk(io)) {
220		case -1:
221			io->error = 1;
222			return (-1);
223		case 0:
224			io->eof = 1;
225			return (0);
226		}
227	}
228
229	if (len > io->chunksize)
230		len = io->chunksize;
231	if (http_growbuf(io, len) == -1)
232		return (-1);
233	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
234		io->error = errno;
235		return (-1);
236	}
237	io->buflen = nbytes;
238	io->chunksize -= io->buflen;
239
240	if (io->chunksize == 0) {
241		char endl[2];
242
243		if (fetch_read(io->conn, endl, 2) != 2 ||
244		    endl[0] != '\r' || endl[1] != '\n')
245			return (-1);
246	}
247
248	io->bufpos = 0;
249
250	return (io->buflen);
251}
252
253/*
254 * Read function
255 */
256static int
257http_readfn(void *v, char *buf, int len)
258{
259	struct httpio *io = (struct httpio *)v;
260	int l, pos;
261
262	if (io->error)
263		return (-1);
264	if (io->eof)
265		return (0);
266
267	for (pos = 0; len > 0; pos += l, len -= l) {
268		/* empty buffer */
269		if (!io->buf || io->bufpos == io->buflen)
270			if (http_fillbuf(io, len) < 1)
271				break;
272		l = io->buflen - io->bufpos;
273		if (len < l)
274			l = len;
275		memcpy(buf + pos, io->buf + io->bufpos, l);
276		io->bufpos += l;
277	}
278
279	if (!pos && io->error) {
280		if (io->error == EINTR)
281			io->error = 0;
282		return (-1);
283	}
284	return (pos);
285}
286
287/*
288 * Write function
289 */
290static int
291http_writefn(void *v, const char *buf, int len)
292{
293	struct httpio *io = (struct httpio *)v;
294
295	return (fetch_write(io->conn, buf, len));
296}
297
298/*
299 * Close function
300 */
301static int
302http_closefn(void *v)
303{
304	struct httpio *io = (struct httpio *)v;
305	int r;
306
307	r = fetch_close(io->conn);
308	if (io->buf)
309		free(io->buf);
310	free(io);
311	return (r);
312}
313
314/*
315 * Wrap a file descriptor up
316 */
317static FILE *
318http_funopen(conn_t *conn, int chunked)
319{
320	struct httpio *io;
321	FILE *f;
322
323	if ((io = calloc(1, sizeof(*io))) == NULL) {
324		fetch_syserr();
325		return (NULL);
326	}
327	io->conn = conn;
328	io->chunked = chunked;
329	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
330	if (f == NULL) {
331		fetch_syserr();
332		free(io);
333		return (NULL);
334	}
335	return (f);
336}
337
338
339/*****************************************************************************
340 * Helper functions for talking to the server and parsing its replies
341 */
342
343/* Header types */
344typedef enum {
345	hdr_syserror = -2,
346	hdr_error = -1,
347	hdr_end = 0,
348	hdr_unknown = 1,
349	hdr_content_length,
350	hdr_content_range,
351	hdr_last_modified,
352	hdr_location,
353	hdr_transfer_encoding,
354	hdr_www_authenticate,
355	hdr_proxy_authenticate,
356} hdr_t;
357
358/* Names of interesting headers */
359static struct {
360	hdr_t		 num;
361	const char	*name;
362} hdr_names[] = {
363	{ hdr_content_length,		"Content-Length" },
364	{ hdr_content_range,		"Content-Range" },
365	{ hdr_last_modified,		"Last-Modified" },
366	{ hdr_location,			"Location" },
367	{ hdr_transfer_encoding,	"Transfer-Encoding" },
368	{ hdr_www_authenticate,		"WWW-Authenticate" },
369	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
370	{ hdr_unknown,			NULL },
371};
372
373/*
374 * Send a formatted line; optionally echo to terminal
375 */
376static int
377http_cmd(conn_t *conn, const char *fmt, ...)
378{
379	va_list ap;
380	size_t len;
381	char *msg;
382	int r;
383
384	va_start(ap, fmt);
385	len = vasprintf(&msg, fmt, ap);
386	va_end(ap);
387
388	if (msg == NULL) {
389		errno = ENOMEM;
390		fetch_syserr();
391		return (-1);
392	}
393
394	r = fetch_putln(conn, msg, len);
395	free(msg);
396
397	if (r == -1) {
398		fetch_syserr();
399		return (-1);
400	}
401
402	return (0);
403}
404
405/*
406 * Get and parse status line
407 */
408static int
409http_get_reply(conn_t *conn)
410{
411	char *p;
412
413	if (fetch_getln(conn) == -1)
414		return (-1);
415	/*
416	 * A valid status line looks like "HTTP/m.n xyz reason" where m
417	 * and n are the major and minor protocol version numbers and xyz
418	 * is the reply code.
419	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
420	 * just one) that do not send a version number, so we can't rely
421	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
422	 * We don't care about the reason phrase.
423	 */
424	if (strncmp(conn->buf, "HTTP", 4) != 0)
425		return (HTTP_PROTOCOL_ERROR);
426	p = conn->buf + 4;
427	if (*p == '/') {
428		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
429			return (HTTP_PROTOCOL_ERROR);
430		p += 4;
431	}
432	if (*p != ' ' ||
433	    !isdigit((unsigned char)p[1]) ||
434	    !isdigit((unsigned char)p[2]) ||
435	    !isdigit((unsigned char)p[3]))
436		return (HTTP_PROTOCOL_ERROR);
437
438	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
439	return (conn->err);
440}
441
442/*
443 * Check a header; if the type matches the given string, return a pointer
444 * to the beginning of the value.
445 */
446static const char *
447http_match(const char *str, const char *hdr)
448{
449	while (*str && *hdr &&
450	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
451		/* nothing */;
452	if (*str || *hdr != ':')
453		return (NULL);
454	while (*hdr && isspace((unsigned char)*++hdr))
455		/* nothing */;
456	return (hdr);
457}
458
459
460/*
461 * Get the next header and return the appropriate symbolic code.  We
462 * need to read one line ahead for checking for a continuation line
463 * belonging to the current header (continuation lines start with
464 * white space).
465 *
466 * We get called with a fresh line already in the conn buffer, either
467 * from the previous http_next_header() invocation, or, the first
468 * time, from a fetch_getln() performed by our caller.
469 *
470 * This stops when we encounter an empty line (we dont read beyond the header
471 * area).
472 *
473 * Note that the "headerbuf" is just a place to return the result. Its
474 * contents are not used for the next call. This means that no cleanup
475 * is needed when ie doing another connection, just call the cleanup when
476 * fully done to deallocate memory.
477 */
478
479/* Limit the max number of continuation lines to some reasonable value */
480#define HTTP_MAX_CONT_LINES 10
481
482/* Place into which to build a header from one or several lines */
483typedef struct {
484	char	*buf;		/* buffer */
485	size_t	 bufsize;	/* buffer size */
486	size_t	 buflen;	/* length of buffer contents */
487} http_headerbuf_t;
488
489static void
490init_http_headerbuf(http_headerbuf_t *buf)
491{
492	buf->buf = NULL;
493	buf->bufsize = 0;
494	buf->buflen = 0;
495}
496
497static void
498clean_http_headerbuf(http_headerbuf_t *buf)
499{
500	if (buf->buf)
501		free(buf->buf);
502	init_http_headerbuf(buf);
503}
504
505/* Remove whitespace at the end of the buffer */
506static void
507http_conn_trimright(conn_t *conn)
508{
509	while (conn->buflen &&
510	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
511		conn->buflen--;
512	conn->buf[conn->buflen] = '\0';
513}
514
515static hdr_t
516http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
517{
518	unsigned int i, len;
519
520	/*
521	 * Have to do the stripping here because of the first line. So
522	 * it's done twice for the subsequent lines. No big deal
523	 */
524	http_conn_trimright(conn);
525	if (conn->buflen == 0)
526		return (hdr_end);
527
528	/* Copy the line to the headerbuf */
529	if (hbuf->bufsize < conn->buflen + 1) {
530		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
531			return (hdr_syserror);
532		hbuf->bufsize = conn->buflen + 1;
533	}
534	strcpy(hbuf->buf, conn->buf);
535	hbuf->buflen = conn->buflen;
536
537	/*
538	 * Fetch possible continuation lines. Stop at 1st non-continuation
539	 * and leave it in the conn buffer
540	 */
541	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
542		if (fetch_getln(conn) == -1)
543			return (hdr_syserror);
544
545		/*
546		 * Note: we carry on the idea from the previous version
547		 * that a pure whitespace line is equivalent to an empty
548		 * one (so it's not continuation and will be handled when
549		 * we are called next)
550		 */
551		http_conn_trimright(conn);
552		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
553			break;
554
555		/* Got a continuation line. Concatenate to previous */
556		len = hbuf->buflen + conn->buflen;
557		if (hbuf->bufsize < len + 1) {
558			len *= 2;
559			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
560				return (hdr_syserror);
561			hbuf->bufsize = len + 1;
562		}
563		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
564		hbuf->buflen += conn->buflen;
565	}
566
567	/*
568	 * We could check for malformed headers but we don't really care.
569	 * A valid header starts with a token immediately followed by a
570	 * colon; a token is any sequence of non-control, non-whitespace
571	 * characters except "()<>@,;:\\\"{}".
572	 */
573	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
574		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
575			return (hdr_names[i].num);
576
577	return (hdr_unknown);
578}
579
580/**************************
581 * [Proxy-]Authenticate header parsing
582 */
583
584/*
585 * Read doublequote-delimited string into output buffer obuf (allocated
586 * by caller, whose responsibility it is to ensure that it's big enough)
587 * cp points to the first char after the initial '"'
588 * Handles \ quoting
589 * Returns pointer to the first char after the terminating double quote, or
590 * NULL for error.
591 */
592static const char *
593http_parse_headerstring(const char *cp, char *obuf)
594{
595	for (;;) {
596		switch (*cp) {
597		case 0: /* Unterminated string */
598			*obuf = 0;
599			return (NULL);
600		case '"': /* Ending quote */
601			*obuf = 0;
602			return (++cp);
603		case '\\':
604			if (*++cp == 0) {
605				*obuf = 0;
606				return (NULL);
607			}
608			/* FALLTHROUGH */
609		default:
610			*obuf++ = *cp++;
611		}
612	}
613}
614
615/* Http auth challenge schemes */
616typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
617
618/* Data holder for a Basic or Digest challenge. */
619typedef struct {
620	http_auth_schemes_t scheme;
621	char	*realm;
622	char	*qop;
623	char	*nonce;
624	char	*opaque;
625	char	*algo;
626	int	 stale;
627	int	 nc; /* Nonce count */
628} http_auth_challenge_t;
629
630static void
631init_http_auth_challenge(http_auth_challenge_t *b)
632{
633	b->scheme = HTTPAS_UNKNOWN;
634	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
635	b->stale = b->nc = 0;
636}
637
638static void
639clean_http_auth_challenge(http_auth_challenge_t *b)
640{
641	if (b->realm)
642		free(b->realm);
643	if (b->qop)
644		free(b->qop);
645	if (b->nonce)
646		free(b->nonce);
647	if (b->opaque)
648		free(b->opaque);
649	if (b->algo)
650		free(b->algo);
651	init_http_auth_challenge(b);
652}
653
654/* Data holder for an array of challenges offered in an http response. */
655#define MAX_CHALLENGES 10
656typedef struct {
657	http_auth_challenge_t *challenges[MAX_CHALLENGES];
658	int	count; /* Number of parsed challenges in the array */
659	int	valid; /* We did parse an authenticate header */
660} http_auth_challenges_t;
661
662static void
663init_http_auth_challenges(http_auth_challenges_t *cs)
664{
665	int i;
666	for (i = 0; i < MAX_CHALLENGES; i++)
667		cs->challenges[i] = NULL;
668	cs->count = cs->valid = 0;
669}
670
671static void
672clean_http_auth_challenges(http_auth_challenges_t *cs)
673{
674	int i;
675	/* We rely on non-zero pointers being allocated, not on the count */
676	for (i = 0; i < MAX_CHALLENGES; i++) {
677		if (cs->challenges[i] != NULL) {
678			clean_http_auth_challenge(cs->challenges[i]);
679			free(cs->challenges[i]);
680		}
681	}
682	init_http_auth_challenges(cs);
683}
684
685/*
686 * Enumeration for lexical elements. Separators will be returned as their own
687 * ascii value
688 */
689typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
690	      HTTPHL_ERROR = 259} http_header_lex_t;
691
692/*
693 * Determine what kind of token comes next and return possible value
694 * in buf, which is supposed to have been allocated big enough by
695 * caller. Advance input pointer and return element type.
696 */
697static int
698http_header_lex(const char **cpp, char *buf)
699{
700	size_t l;
701	/* Eat initial whitespace */
702	*cpp += strspn(*cpp, " \t");
703	if (**cpp == 0)
704		return (HTTPHL_END);
705
706	/* Separator ? */
707	if (**cpp == ',' || **cpp == '=')
708		return (*((*cpp)++));
709
710	/* String ? */
711	if (**cpp == '"') {
712		*cpp = http_parse_headerstring(++*cpp, buf);
713		if (*cpp == NULL)
714			return (HTTPHL_ERROR);
715		return (HTTPHL_STRING);
716	}
717
718	/* Read other token, until separator or whitespace */
719	l = strcspn(*cpp, " \t,=");
720	memcpy(buf, *cpp, l);
721	buf[l] = 0;
722	*cpp += l;
723	return (HTTPHL_WORD);
724}
725
726/*
727 * Read challenges from http xxx-authenticate header and accumulate them
728 * in the challenges list structure.
729 *
730 * Headers with multiple challenges are specified by rfc2617, but
731 * servers (ie: squid) often send them in separate headers instead,
732 * which in turn is forbidden by the http spec (multiple headers with
733 * the same name are only allowed for pure comma-separated lists, see
734 * rfc2616 sec 4.2).
735 *
736 * We support both approaches anyway
737 */
738static int
739http_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
740{
741	int ret = -1;
742	http_header_lex_t lex;
743	char *key = malloc(strlen(cp) + 1);
744	char *value = malloc(strlen(cp) + 1);
745	char *buf = malloc(strlen(cp) + 1);
746
747	if (key == NULL || value == NULL || buf == NULL) {
748		fetch_syserr();
749		goto out;
750	}
751
752	/* In any case we've seen the header and we set the valid bit */
753	cs->valid = 1;
754
755	/* Need word first */
756	lex = http_header_lex(&cp, key);
757	if (lex != HTTPHL_WORD)
758		goto out;
759
760	/* Loop on challenges */
761	for (; cs->count < MAX_CHALLENGES; cs->count++) {
762		cs->challenges[cs->count] =
763			malloc(sizeof(http_auth_challenge_t));
764		if (cs->challenges[cs->count] == NULL) {
765			fetch_syserr();
766			goto out;
767		}
768		init_http_auth_challenge(cs->challenges[cs->count]);
769		if (!strcasecmp(key, "basic")) {
770			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
771		} else if (!strcasecmp(key, "digest")) {
772			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
773		} else {
774			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
775			/*
776			 * Continue parsing as basic or digest may
777			 * follow, and the syntax is the same for
778			 * all. We'll just ignore this one when
779			 * looking at the list
780			 */
781		}
782
783		/* Loop on attributes */
784		for (;;) {
785			/* Key */
786			lex = http_header_lex(&cp, key);
787			if (lex != HTTPHL_WORD)
788				goto out;
789
790			/* Equal sign */
791			lex = http_header_lex(&cp, buf);
792			if (lex != '=')
793				goto out;
794
795			/* Value */
796			lex = http_header_lex(&cp, value);
797			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
798				goto out;
799
800			if (!strcasecmp(key, "realm"))
801				cs->challenges[cs->count]->realm =
802					strdup(value);
803			else if (!strcasecmp(key, "qop"))
804				cs->challenges[cs->count]->qop =
805					strdup(value);
806			else if (!strcasecmp(key, "nonce"))
807				cs->challenges[cs->count]->nonce =
808					strdup(value);
809			else if (!strcasecmp(key, "opaque"))
810				cs->challenges[cs->count]->opaque =
811					strdup(value);
812			else if (!strcasecmp(key, "algorithm"))
813				cs->challenges[cs->count]->algo =
814					strdup(value);
815			else if (!strcasecmp(key, "stale"))
816				cs->challenges[cs->count]->stale =
817					strcasecmp(value, "no");
818			/* Else ignore unknown attributes */
819
820			/* Comma or Next challenge or End */
821			lex = http_header_lex(&cp, key);
822			/*
823			 * If we get a word here, this is the beginning of the
824			 * next challenge. Break the attributes loop
825			 */
826			if (lex == HTTPHL_WORD)
827				break;
828
829			if (lex == HTTPHL_END) {
830				/* End while looking for ',' is normal exit */
831				cs->count++;
832				ret = 0;
833				goto out;
834			}
835			/* Anything else is an error */
836			if (lex != ',')
837				goto out;
838
839		} /* End attributes loop */
840	} /* End challenge loop */
841
842	/*
843	 * Challenges max count exceeded. This really can't happen
844	 * with normal data, something's fishy -> error
845	 */
846
847out:
848	if (key)
849		free(key);
850	if (value)
851		free(value);
852	if (buf)
853		free(buf);
854	return (ret);
855}
856
857
858/*
859 * Parse a last-modified header
860 */
861static int
862http_parse_mtime(const char *p, time_t *mtime)
863{
864	char locale[64], *r;
865	struct tm tm;
866
867	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
868	setlocale(LC_TIME, "C");
869	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
870	/* XXX should add support for date-2 and date-3 */
871	setlocale(LC_TIME, locale);
872	if (r == NULL)
873		return (-1);
874	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
875		  "%02d:%02d:%02d]\n",
876		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
877		  tm.tm_hour, tm.tm_min, tm.tm_sec));
878	*mtime = timegm(&tm);
879	return (0);
880}
881
882/*
883 * Parse a content-length header
884 */
885static int
886http_parse_length(const char *p, off_t *length)
887{
888	off_t len;
889
890	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
891		len = len * 10 + (*p - '0');
892	if (*p)
893		return (-1);
894	DEBUG(fprintf(stderr, "content length: [%lld]\n",
895	    (long long)len));
896	*length = len;
897	return (0);
898}
899
900/*
901 * Parse a content-range header
902 */
903static int
904http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
905{
906	off_t first, last, len;
907
908	if (strncasecmp(p, "bytes ", 6) != 0)
909		return (-1);
910	p += 6;
911	if (*p == '*') {
912		first = last = -1;
913		++p;
914	} else {
915		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
916			first = first * 10 + *p - '0';
917		if (*p != '-')
918			return (-1);
919		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
920			last = last * 10 + *p - '0';
921	}
922	if (first > last || *p != '/')
923		return (-1);
924	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
925		len = len * 10 + *p - '0';
926	if (*p || len < last - first + 1)
927		return (-1);
928	if (first == -1) {
929		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
930		    (long long)len));
931		*length = 0;
932	} else {
933		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
934		    (long long)first, (long long)last, (long long)len));
935		*length = last - first + 1;
936	}
937	*offset = first;
938	*size = len;
939	return (0);
940}
941
942
943/*****************************************************************************
944 * Helper functions for authorization
945 */
946
947/*
948 * Base64 encoding
949 */
950static char *
951http_base64(const char *src)
952{
953	static const char base64[] =
954	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
955	    "abcdefghijklmnopqrstuvwxyz"
956	    "0123456789+/";
957	char *str, *dst;
958	size_t l;
959	int t, r;
960
961	l = strlen(src);
962	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
963		return (NULL);
964	dst = str;
965	r = 0;
966
967	while (l >= 3) {
968		t = (src[0] << 16) | (src[1] << 8) | src[2];
969		dst[0] = base64[(t >> 18) & 0x3f];
970		dst[1] = base64[(t >> 12) & 0x3f];
971		dst[2] = base64[(t >> 6) & 0x3f];
972		dst[3] = base64[(t >> 0) & 0x3f];
973		src += 3; l -= 3;
974		dst += 4; r += 4;
975	}
976
977	switch (l) {
978	case 2:
979		t = (src[0] << 16) | (src[1] << 8);
980		dst[0] = base64[(t >> 18) & 0x3f];
981		dst[1] = base64[(t >> 12) & 0x3f];
982		dst[2] = base64[(t >> 6) & 0x3f];
983		dst[3] = '=';
984		dst += 4;
985		r += 4;
986		break;
987	case 1:
988		t = src[0] << 16;
989		dst[0] = base64[(t >> 18) & 0x3f];
990		dst[1] = base64[(t >> 12) & 0x3f];
991		dst[2] = dst[3] = '=';
992		dst += 4;
993		r += 4;
994		break;
995	case 0:
996		break;
997	}
998
999	*dst = 0;
1000	return (str);
1001}
1002
1003
1004/*
1005 * Extract authorization parameters from environment value.
1006 * The value is like scheme:realm:user:pass
1007 */
1008typedef struct {
1009	char	*scheme;
1010	char	*realm;
1011	char	*user;
1012	char	*password;
1013} http_auth_params_t;
1014
1015static void
1016init_http_auth_params(http_auth_params_t *s)
1017{
1018	s->scheme = s->realm = s->user = s->password = 0;
1019}
1020
1021static void
1022clean_http_auth_params(http_auth_params_t *s)
1023{
1024	if (s->scheme)
1025		free(s->scheme);
1026	if (s->realm)
1027		free(s->realm);
1028	if (s->user)
1029		free(s->user);
1030	if (s->password)
1031		free(s->password);
1032	init_http_auth_params(s);
1033}
1034
1035static int
1036http_authfromenv(const char *p, http_auth_params_t *parms)
1037{
1038	int ret = -1;
1039	char *v, *ve;
1040	char *str = strdup(p);
1041
1042	if (str == NULL) {
1043		fetch_syserr();
1044		return (-1);
1045	}
1046	v = str;
1047
1048	if ((ve = strchr(v, ':')) == NULL)
1049		goto out;
1050
1051	*ve = 0;
1052	if ((parms->scheme = strdup(v)) == NULL) {
1053		fetch_syserr();
1054		goto out;
1055	}
1056	v = ve + 1;
1057
1058	if ((ve = strchr(v, ':')) == NULL)
1059		goto out;
1060
1061	*ve = 0;
1062	if ((parms->realm = strdup(v)) == NULL) {
1063		fetch_syserr();
1064		goto out;
1065	}
1066	v = ve + 1;
1067
1068	if ((ve = strchr(v, ':')) == NULL)
1069		goto out;
1070
1071	*ve = 0;
1072	if ((parms->user = strdup(v)) == NULL) {
1073		fetch_syserr();
1074		goto out;
1075	}
1076	v = ve + 1;
1077
1078
1079	if ((parms->password = strdup(v)) == NULL) {
1080		fetch_syserr();
1081		goto out;
1082	}
1083	ret = 0;
1084out:
1085	if (ret == -1)
1086		clean_http_auth_params(parms);
1087	if (str)
1088		free(str);
1089	return (ret);
1090}
1091
1092
1093/*
1094 * Digest response: the code to compute the digest is taken from the
1095 * sample implementation in RFC2616
1096 */
1097#define IN const
1098#define OUT
1099
1100#define HASHLEN 16
1101typedef char HASH[HASHLEN];
1102#define HASHHEXLEN 32
1103typedef char HASHHEX[HASHHEXLEN+1];
1104
1105static const char *hexchars = "0123456789abcdef";
1106static void
1107CvtHex(IN HASH Bin, OUT HASHHEX Hex)
1108{
1109	unsigned short i;
1110	unsigned char j;
1111
1112	for (i = 0; i < HASHLEN; i++) {
1113		j = (Bin[i] >> 4) & 0xf;
1114		Hex[i*2] = hexchars[j];
1115		j = Bin[i] & 0xf;
1116		Hex[i*2+1] = hexchars[j];
1117	};
1118	Hex[HASHHEXLEN] = '\0';
1119};
1120
1121/* calculate H(A1) as per spec */
1122static void
1123DigestCalcHA1(
1124	IN char * pszAlg,
1125	IN char * pszUserName,
1126	IN char * pszRealm,
1127	IN char * pszPassword,
1128	IN char * pszNonce,
1129	IN char * pszCNonce,
1130	OUT HASHHEX SessionKey
1131	)
1132{
1133	MD5_CTX Md5Ctx;
1134	HASH HA1;
1135
1136	MD5Init(&Md5Ctx);
1137	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1138	MD5Update(&Md5Ctx, ":", 1);
1139	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1140	MD5Update(&Md5Ctx, ":", 1);
1141	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1142	MD5Final(HA1, &Md5Ctx);
1143	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1144
1145		MD5Init(&Md5Ctx);
1146		MD5Update(&Md5Ctx, HA1, HASHLEN);
1147		MD5Update(&Md5Ctx, ":", 1);
1148		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1149		MD5Update(&Md5Ctx, ":", 1);
1150		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1151		MD5Final(HA1, &Md5Ctx);
1152	};
1153	CvtHex(HA1, SessionKey);
1154}
1155
1156/* calculate request-digest/response-digest as per HTTP Digest spec */
1157static void
1158DigestCalcResponse(
1159	IN HASHHEX HA1,           /* H(A1) */
1160	IN char * pszNonce,       /* nonce from server */
1161	IN char * pszNonceCount,  /* 8 hex digits */
1162	IN char * pszCNonce,      /* client nonce */
1163	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1164	IN char * pszMethod,      /* method from the request */
1165	IN char * pszDigestUri,   /* requested URL */
1166	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1167	OUT HASHHEX Response      /* request-digest or response-digest */
1168	)
1169{
1170/*	DEBUG(fprintf(stderr,
1171		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1172		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1173	MD5_CTX Md5Ctx;
1174	HASH HA2;
1175	HASH RespHash;
1176	HASHHEX HA2Hex;
1177
1178	// calculate H(A2)
1179	MD5Init(&Md5Ctx);
1180	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1181	MD5Update(&Md5Ctx, ":", 1);
1182	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1183	if (strcasecmp(pszQop, "auth-int") == 0) {
1184		MD5Update(&Md5Ctx, ":", 1);
1185		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1186	};
1187	MD5Final(HA2, &Md5Ctx);
1188	CvtHex(HA2, HA2Hex);
1189
1190	// calculate response
1191	MD5Init(&Md5Ctx);
1192	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1193	MD5Update(&Md5Ctx, ":", 1);
1194	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1195	MD5Update(&Md5Ctx, ":", 1);
1196	if (*pszQop) {
1197		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1198		MD5Update(&Md5Ctx, ":", 1);
1199		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1200		MD5Update(&Md5Ctx, ":", 1);
1201		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1202		MD5Update(&Md5Ctx, ":", 1);
1203	};
1204	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1205	MD5Final(RespHash, &Md5Ctx);
1206	CvtHex(RespHash, Response);
1207}
1208
1209/*
1210 * Generate/Send a Digest authorization header
1211 * This looks like: [Proxy-]Authorization: credentials
1212 *
1213 *  credentials      = "Digest" digest-response
1214 *  digest-response  = 1#( username | realm | nonce | digest-uri
1215 *                      | response | [ algorithm ] | [cnonce] |
1216 *                      [opaque] | [message-qop] |
1217 *                          [nonce-count]  | [auth-param] )
1218 *  username         = "username" "=" username-value
1219 *  username-value   = quoted-string
1220 *  digest-uri       = "uri" "=" digest-uri-value
1221 *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1222 *  message-qop      = "qop" "=" qop-value
1223 *  cnonce           = "cnonce" "=" cnonce-value
1224 *  cnonce-value     = nonce-value
1225 *  nonce-count      = "nc" "=" nc-value
1226 *  nc-value         = 8LHEX
1227 *  response         = "response" "=" request-digest
1228 *  request-digest = <"> 32LHEX <">
1229 */
1230static int
1231http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1232		 http_auth_params_t *parms, struct url *url)
1233{
1234	int r;
1235	char noncecount[10];
1236	char cnonce[40];
1237	char *options = 0;
1238
1239	if (!c->realm || !c->nonce) {
1240		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1241		return(-1);
1242	}
1243	if (!c->algo)
1244		c->algo = strdup("");
1245
1246	if (asprintf(&options, "%s%s%s%s",
1247		     *c->algo? ",algorithm=" : "", c->algo,
1248		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1249		return (-1);
1250
1251	if (!c->qop) {
1252		c->qop = strdup("");
1253		*noncecount = 0;
1254		*cnonce = 0;
1255	} else {
1256		c->nc++;
1257		sprintf(noncecount, "%08x", c->nc);
1258		/* We don't try very hard with the cnonce ... */
1259		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1260	}
1261
1262	HASHHEX HA1;
1263	DigestCalcHA1(c->algo, parms->user, c->realm,
1264		      parms->password, c->nonce, cnonce, HA1);
1265	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1266	HASHHEX digest;
1267	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1268			   "GET", url->doc, "", digest);
1269
1270	if (c->qop[0]) {
1271		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1272			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1273			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1274			     hdr, parms->user, c->realm,
1275			     c->nonce, url->doc, digest,
1276			     cnonce, noncecount, options);
1277	} else {
1278		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1279			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1280			     hdr, parms->user, c->realm,
1281			     c->nonce, url->doc, digest, options);
1282	}
1283	if (options)
1284		free(options);
1285	return (r);
1286}
1287
1288/*
1289 * Encode username and password
1290 */
1291static int
1292http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1293{
1294	char *upw, *auth;
1295	int r;
1296
1297	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1298	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
1299	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
1300		return (-1);
1301	auth = http_base64(upw);
1302	free(upw);
1303	if (auth == NULL)
1304		return (-1);
1305	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
1306	free(auth);
1307	return (r);
1308}
1309
1310/*
1311 * Chose the challenge to answer and call the appropriate routine to
1312 * produce the header.
1313 */
1314static int
1315http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1316	       http_auth_params_t *parms, struct url *url)
1317{
1318	http_auth_challenge_t *basic = NULL;
1319	http_auth_challenge_t *digest = NULL;
1320	int i;
1321
1322	/* If user or pass are null we're not happy */
1323	if (!parms->user || !parms->password) {
1324		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1325		return (-1);
1326	}
1327
1328	/* Look for a Digest and a Basic challenge */
1329	for (i = 0; i < cs->count; i++) {
1330		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1331			basic = cs->challenges[i];
1332		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1333			digest = cs->challenges[i];
1334	}
1335
1336	/* Error if "Digest" was specified and there is no Digest challenge */
1337	if (!digest && (parms->scheme &&
1338			!strcasecmp(parms->scheme, "digest"))) {
1339		DEBUG(fprintf(stderr,
1340			      "Digest auth in env, not supported by peer\n"));
1341		return (-1);
1342	}
1343	/*
1344	 * If "basic" was specified in the environment, or there is no Digest
1345	 * challenge, do the basic thing. Don't need a challenge for this,
1346	 * so no need to check basic!=NULL
1347	 */
1348	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1349		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1350
1351	/* Else, prefer digest. We just checked that it's not NULL */
1352	return (http_digest_auth(conn, hdr, digest, parms, url));
1353}
1354
1355/*****************************************************************************
1356 * Helper functions for connecting to a server or proxy
1357 */
1358
1359/*
1360 * Connect to the correct HTTP server or proxy.
1361 */
1362static conn_t *
1363http_connect(struct url *URL, struct url *purl, const char *flags)
1364{
1365	conn_t *conn;
1366	int verbose;
1367	int af, val;
1368
1369#ifdef INET6
1370	af = AF_UNSPEC;
1371#else
1372	af = AF_INET;
1373#endif
1374
1375	verbose = CHECK_FLAG('v');
1376	if (CHECK_FLAG('4'))
1377		af = AF_INET;
1378#ifdef INET6
1379	else if (CHECK_FLAG('6'))
1380		af = AF_INET6;
1381#endif
1382
1383	if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
1384		URL = purl;
1385	} else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
1386		/* can't talk http to an ftp server */
1387		/* XXX should set an error code */
1388		return (NULL);
1389	}
1390
1391	if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
1392		/* fetch_connect() has already set an error code */
1393		return (NULL);
1394	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1395	    fetch_ssl(conn, verbose) == -1) {
1396		fetch_close(conn);
1397		/* grrr */
1398		errno = EAUTH;
1399		fetch_syserr();
1400		return (NULL);
1401	}
1402
1403	val = 1;
1404	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1405
1406	return (conn);
1407}
1408
1409static struct url *
1410http_get_proxy(struct url * url, const char *flags)
1411{
1412	struct url *purl;
1413	char *p;
1414
1415	if (flags != NULL && strchr(flags, 'd') != NULL)
1416		return (NULL);
1417	if (fetch_no_proxy_match(url->host))
1418		return (NULL);
1419	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1420	    *p && (purl = fetchParseURL(p))) {
1421		if (!*purl->scheme)
1422			strcpy(purl->scheme, SCHEME_HTTP);
1423		if (!purl->port)
1424			purl->port = fetch_default_proxy_port(purl->scheme);
1425		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1426			return (purl);
1427		fetchFreeURL(purl);
1428	}
1429	return (NULL);
1430}
1431
1432static void
1433http_print_html(FILE *out, FILE *in)
1434{
1435	size_t len;
1436	char *line, *p, *q;
1437	int comment, tag;
1438
1439	comment = tag = 0;
1440	while ((line = fgetln(in, &len)) != NULL) {
1441		while (len && isspace((unsigned char)line[len - 1]))
1442			--len;
1443		for (p = q = line; q < line + len; ++q) {
1444			if (comment && *q == '-') {
1445				if (q + 2 < line + len &&
1446				    strcmp(q, "-->") == 0) {
1447					tag = comment = 0;
1448					q += 2;
1449				}
1450			} else if (tag && !comment && *q == '>') {
1451				p = q + 1;
1452				tag = 0;
1453			} else if (!tag && *q == '<') {
1454				if (q > p)
1455					fwrite(p, q - p, 1, out);
1456				tag = 1;
1457				if (q + 3 < line + len &&
1458				    strcmp(q, "<!--") == 0) {
1459					comment = 1;
1460					q += 3;
1461				}
1462			}
1463		}
1464		if (!tag && q > p)
1465			fwrite(p, q - p, 1, out);
1466		fputc('\n', out);
1467	}
1468}
1469
1470
1471/*****************************************************************************
1472 * Core
1473 */
1474
1475/*
1476 * Send a request and process the reply
1477 *
1478 * XXX This function is way too long, the do..while loop should be split
1479 * XXX off into a separate function.
1480 */
1481FILE *
1482http_request(struct url *URL, const char *op, struct url_stat *us,
1483	struct url *purl, const char *flags)
1484{
1485	char timebuf[80];
1486	char hbuf[MAXHOSTNAMELEN + 7], *host;
1487	conn_t *conn;
1488	struct url *url, *new;
1489	int chunked, direct, ims, noredirect, verbose;
1490	int e, i, n, val;
1491	off_t offset, clength, length, size;
1492	time_t mtime;
1493	const char *p;
1494	FILE *f;
1495	hdr_t h;
1496	struct tm *timestruct;
1497	http_headerbuf_t headerbuf;
1498	http_auth_challenges_t server_challenges;
1499	http_auth_challenges_t proxy_challenges;
1500
1501	/* The following calls don't allocate anything */
1502	init_http_headerbuf(&headerbuf);
1503	init_http_auth_challenges(&server_challenges);
1504	init_http_auth_challenges(&proxy_challenges);
1505
1506	direct = CHECK_FLAG('d');
1507	noredirect = CHECK_FLAG('A');
1508	verbose = CHECK_FLAG('v');
1509	ims = CHECK_FLAG('i');
1510
1511	if (direct && purl) {
1512		fetchFreeURL(purl);
1513		purl = NULL;
1514	}
1515
1516	/* try the provided URL first */
1517	url = URL;
1518
1519	/* if the A flag is set, we only get one try */
1520	n = noredirect ? 1 : MAX_REDIRECT;
1521	i = 0;
1522
1523	e = HTTP_PROTOCOL_ERROR;
1524	do {
1525		new = NULL;
1526		chunked = 0;
1527		offset = 0;
1528		clength = -1;
1529		length = -1;
1530		size = -1;
1531		mtime = 0;
1532
1533		/* check port */
1534		if (!url->port)
1535			url->port = fetch_default_port(url->scheme);
1536
1537		/* were we redirected to an FTP URL? */
1538		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1539			if (strcmp(op, "GET") == 0)
1540				return (ftp_request(url, "RETR", us, purl, flags));
1541			else if (strcmp(op, "HEAD") == 0)
1542				return (ftp_request(url, "STAT", us, purl, flags));
1543		}
1544
1545		/* connect to server or proxy */
1546		if ((conn = http_connect(url, purl, flags)) == NULL)
1547			goto ouch;
1548
1549		host = url->host;
1550#ifdef INET6
1551		if (strchr(url->host, ':')) {
1552			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
1553			host = hbuf;
1554		}
1555#endif
1556		if (url->port != fetch_default_port(url->scheme)) {
1557			if (host != hbuf) {
1558				strcpy(hbuf, host);
1559				host = hbuf;
1560			}
1561			snprintf(hbuf + strlen(hbuf),
1562			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1563		}
1564
1565		/* send request */
1566		if (verbose)
1567			fetch_info("requesting %s://%s%s",
1568			    url->scheme, host, url->doc);
1569		if (purl) {
1570			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1571			    op, url->scheme, host, url->doc);
1572		} else {
1573			http_cmd(conn, "%s %s HTTP/1.1",
1574			    op, url->doc);
1575		}
1576
1577		if (ims && url->ims_time) {
1578			timestruct = gmtime((time_t *)&url->ims_time);
1579			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1580			    timestruct);
1581			if (verbose)
1582				fetch_info("If-Modified-Since: %s", timebuf);
1583			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1584		}
1585		/* virtual host */
1586		http_cmd(conn, "Host: %s", host);
1587
1588		/*
1589		 * Proxy authorization: we only send auth after we received
1590		 * a 407 error. We do not first try basic anyway (changed
1591		 * when support was added for digest-auth)
1592		 */
1593		if (purl && proxy_challenges.valid) {
1594			http_auth_params_t aparams;
1595			init_http_auth_params(&aparams);
1596			if (*purl->user || *purl->pwd) {
1597				aparams.user = purl->user ?
1598					strdup(purl->user) : strdup("");
1599				aparams.password = purl->pwd?
1600					strdup(purl->pwd) : strdup("");
1601			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1602				   *p != '\0') {
1603				if (http_authfromenv(p, &aparams) < 0) {
1604					http_seterr(HTTP_NEED_PROXY_AUTH);
1605					goto ouch;
1606				}
1607			}
1608			http_authorize(conn, "Proxy-Authorization",
1609				       &proxy_challenges, &aparams, url);
1610			clean_http_auth_params(&aparams);
1611		}
1612
1613		/*
1614		 * Server authorization: we never send "a priori"
1615		 * Basic auth, which used to be done if user/pass were
1616		 * set in the url. This would be weird because we'd send the
1617		 * password in the clear even if Digest is finally to be
1618		 * used (it would have made more sense for the
1619		 * pre-digest version to do this when Basic was specified
1620		 * in the environment)
1621		 */
1622		if (server_challenges.valid) {
1623			http_auth_params_t aparams;
1624			init_http_auth_params(&aparams);
1625			if (*url->user || *url->pwd) {
1626				aparams.user = url->user ?
1627					strdup(url->user) : strdup("");
1628				aparams.password = url->pwd ?
1629					strdup(url->pwd) : strdup("");
1630			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1631				   *p != '\0') {
1632				if (http_authfromenv(p, &aparams) < 0) {
1633					http_seterr(HTTP_NEED_AUTH);
1634					goto ouch;
1635				}
1636			} else if (fetchAuthMethod &&
1637				   fetchAuthMethod(url) == 0) {
1638				aparams.user = url->user ?
1639					strdup(url->user) : strdup("");
1640				aparams.password = url->pwd ?
1641					strdup(url->pwd) : strdup("");
1642			} else {
1643				http_seterr(HTTP_NEED_AUTH);
1644				goto ouch;
1645			}
1646			http_authorize(conn, "Authorization",
1647				       &server_challenges, &aparams, url);
1648			clean_http_auth_params(&aparams);
1649		}
1650
1651		/* other headers */
1652		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1653			if (strcasecmp(p, "auto") == 0)
1654				http_cmd(conn, "Referer: %s://%s%s",
1655				    url->scheme, host, url->doc);
1656			else
1657				http_cmd(conn, "Referer: %s", p);
1658		}
1659		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1660			http_cmd(conn, "User-Agent: %s", p);
1661		else
1662			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1663		if (url->offset > 0)
1664			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1665		http_cmd(conn, "Connection: close");
1666		http_cmd(conn, "");
1667
1668		/*
1669		 * Force the queued request to be dispatched.  Normally, one
1670		 * would do this with shutdown(2) but squid proxies can be
1671		 * configured to disallow such half-closed connections.  To
1672		 * be compatible with such configurations, fiddle with socket
1673		 * options to force the pending data to be written.
1674		 */
1675		val = 0;
1676		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1677			   sizeof(val));
1678		val = 1;
1679		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1680			   sizeof(val));
1681
1682		/* get reply */
1683		switch (http_get_reply(conn)) {
1684		case HTTP_OK:
1685		case HTTP_PARTIAL:
1686		case HTTP_NOT_MODIFIED:
1687			/* fine */
1688			break;
1689		case HTTP_MOVED_PERM:
1690		case HTTP_MOVED_TEMP:
1691		case HTTP_SEE_OTHER:
1692			/*
1693			 * Not so fine, but we still have to read the
1694			 * headers to get the new location.
1695			 */
1696			break;
1697		case HTTP_NEED_AUTH:
1698			if (server_challenges.valid) {
1699				/*
1700				 * We already sent out authorization code,
1701				 * so there's nothing more we can do.
1702				 */
1703				http_seterr(conn->err);
1704				goto ouch;
1705			}
1706			/* try again, but send the password this time */
1707			if (verbose)
1708				fetch_info("server requires authorization");
1709			break;
1710		case HTTP_NEED_PROXY_AUTH:
1711			if (proxy_challenges.valid) {
1712				/*
1713				 * We already sent our proxy
1714				 * authorization code, so there's
1715				 * nothing more we can do. */
1716				http_seterr(conn->err);
1717				goto ouch;
1718			}
1719			/* try again, but send the password this time */
1720			if (verbose)
1721				fetch_info("proxy requires authorization");
1722			break;
1723		case HTTP_BAD_RANGE:
1724			/*
1725			 * This can happen if we ask for 0 bytes because
1726			 * we already have the whole file.  Consider this
1727			 * a success for now, and check sizes later.
1728			 */
1729			break;
1730		case HTTP_PROTOCOL_ERROR:
1731			/* fall through */
1732		case -1:
1733			fetch_syserr();
1734			goto ouch;
1735		default:
1736			http_seterr(conn->err);
1737			if (!verbose)
1738				goto ouch;
1739			/* fall through so we can get the full error message */
1740		}
1741
1742		/* get headers. http_next_header expects one line readahead */
1743		if (fetch_getln(conn) == -1) {
1744		    fetch_syserr();
1745		    goto ouch;
1746		}
1747		do {
1748		    switch ((h = http_next_header(conn, &headerbuf, &p))) {
1749			case hdr_syserror:
1750				fetch_syserr();
1751				goto ouch;
1752			case hdr_error:
1753				http_seterr(HTTP_PROTOCOL_ERROR);
1754				goto ouch;
1755			case hdr_content_length:
1756				http_parse_length(p, &clength);
1757				break;
1758			case hdr_content_range:
1759				http_parse_range(p, &offset, &length, &size);
1760				break;
1761			case hdr_last_modified:
1762				http_parse_mtime(p, &mtime);
1763				break;
1764			case hdr_location:
1765				if (!HTTP_REDIRECT(conn->err))
1766					break;
1767				if (new)
1768					free(new);
1769				if (verbose)
1770					fetch_info("%d redirect to %s", conn->err, p);
1771				if (*p == '/')
1772					/* absolute path */
1773					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1774					    url->user, url->pwd);
1775				else
1776					new = fetchParseURL(p);
1777				if (new == NULL) {
1778					/* XXX should set an error code */
1779					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1780					goto ouch;
1781				}
1782				if (!*new->user && !*new->pwd) {
1783					strcpy(new->user, url->user);
1784					strcpy(new->pwd, url->pwd);
1785				}
1786				new->offset = url->offset;
1787				new->length = url->length;
1788				break;
1789			case hdr_transfer_encoding:
1790				/* XXX weak test*/
1791				chunked = (strcasecmp(p, "chunked") == 0);
1792				break;
1793			case hdr_www_authenticate:
1794				if (conn->err != HTTP_NEED_AUTH)
1795					break;
1796				if (http_parse_authenticate(p, &server_challenges) == 0)
1797					++n;
1798				break;
1799			case hdr_proxy_authenticate:
1800				if (conn->err != HTTP_NEED_PROXY_AUTH)
1801					break;
1802				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1803					++n;
1804				break;
1805			case hdr_end:
1806				/* fall through */
1807			case hdr_unknown:
1808				/* ignore */
1809				break;
1810			}
1811		} while (h > hdr_end);
1812
1813		/* we need to provide authentication */
1814		if (conn->err == HTTP_NEED_AUTH ||
1815		    conn->err == HTTP_NEED_PROXY_AUTH) {
1816			e = conn->err;
1817			if ((conn->err == HTTP_NEED_AUTH &&
1818			     !server_challenges.valid) ||
1819			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1820			     !proxy_challenges.valid)) {
1821				/* 401/7 but no www/proxy-authenticate ?? */
1822				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1823				goto ouch;
1824			}
1825			fetch_close(conn);
1826			conn = NULL;
1827			continue;
1828		}
1829
1830		/* requested range not satisfiable */
1831		if (conn->err == HTTP_BAD_RANGE) {
1832			if (url->offset == size && url->length == 0) {
1833				/* asked for 0 bytes; fake it */
1834				offset = url->offset;
1835				clength = -1;
1836				conn->err = HTTP_OK;
1837				break;
1838			} else {
1839				http_seterr(conn->err);
1840				goto ouch;
1841			}
1842		}
1843
1844		/* we have a hit or an error */
1845		if (conn->err == HTTP_OK
1846		    || conn->err == HTTP_NOT_MODIFIED
1847		    || conn->err == HTTP_PARTIAL
1848		    || HTTP_ERROR(conn->err))
1849			break;
1850
1851		/* all other cases: we got a redirect */
1852		e = conn->err;
1853		clean_http_auth_challenges(&server_challenges);
1854		fetch_close(conn);
1855		conn = NULL;
1856		if (!new) {
1857			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1858			break;
1859		}
1860		if (url != URL)
1861			fetchFreeURL(url);
1862		url = new;
1863	} while (++i < n);
1864
1865	/* we failed, or ran out of retries */
1866	if (conn == NULL) {
1867		http_seterr(e);
1868		goto ouch;
1869	}
1870
1871	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1872		  " size %lld, clength %lld\n",
1873		  (long long)offset, (long long)length,
1874		  (long long)size, (long long)clength));
1875
1876	if (conn->err == HTTP_NOT_MODIFIED) {
1877		http_seterr(HTTP_NOT_MODIFIED);
1878		return (NULL);
1879	}
1880
1881	/* check for inconsistencies */
1882	if (clength != -1 && length != -1 && clength != length) {
1883		http_seterr(HTTP_PROTOCOL_ERROR);
1884		goto ouch;
1885	}
1886	if (clength == -1)
1887		clength = length;
1888	if (clength != -1)
1889		length = offset + clength;
1890	if (length != -1 && size != -1 && length != size) {
1891		http_seterr(HTTP_PROTOCOL_ERROR);
1892		goto ouch;
1893	}
1894	if (size == -1)
1895		size = length;
1896
1897	/* fill in stats */
1898	if (us) {
1899		us->size = size;
1900		us->atime = us->mtime = mtime;
1901	}
1902
1903	/* too far? */
1904	if (URL->offset > 0 && offset > URL->offset) {
1905		http_seterr(HTTP_PROTOCOL_ERROR);
1906		goto ouch;
1907	}
1908
1909	/* report back real offset and size */
1910	URL->offset = offset;
1911	URL->length = clength;
1912
1913	/* wrap it up in a FILE */
1914	if ((f = http_funopen(conn, chunked)) == NULL) {
1915		fetch_syserr();
1916		goto ouch;
1917	}
1918
1919	if (url != URL)
1920		fetchFreeURL(url);
1921	if (purl)
1922		fetchFreeURL(purl);
1923
1924	if (HTTP_ERROR(conn->err)) {
1925		http_print_html(stderr, f);
1926		fclose(f);
1927		f = NULL;
1928	}
1929	clean_http_headerbuf(&headerbuf);
1930	clean_http_auth_challenges(&server_challenges);
1931	clean_http_auth_challenges(&proxy_challenges);
1932	return (f);
1933
1934ouch:
1935	if (url != URL)
1936		fetchFreeURL(url);
1937	if (purl)
1938		fetchFreeURL(purl);
1939	if (conn != NULL)
1940		fetch_close(conn);
1941	clean_http_headerbuf(&headerbuf);
1942	clean_http_auth_challenges(&server_challenges);
1943	clean_http_auth_challenges(&proxy_challenges);
1944	return (NULL);
1945}
1946
1947
1948/*****************************************************************************
1949 * Entry points
1950 */
1951
1952/*
1953 * Retrieve and stat a file by HTTP
1954 */
1955FILE *
1956fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1957{
1958	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1959}
1960
1961/*
1962 * Retrieve a file by HTTP
1963 */
1964FILE *
1965fetchGetHTTP(struct url *URL, const char *flags)
1966{
1967	return (fetchXGetHTTP(URL, NULL, flags));
1968}
1969
1970/*
1971 * Store a file by HTTP
1972 */
1973FILE *
1974fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1975{
1976	warnx("fetchPutHTTP(): not implemented");
1977	return (NULL);
1978}
1979
1980/*
1981 * Get an HTTP document's metadata
1982 */
1983int
1984fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1985{
1986	FILE *f;
1987
1988	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
1989	if (f == NULL)
1990		return (-1);
1991	fclose(f);
1992	return (0);
1993}
1994
1995/*
1996 * List a directory
1997 */
1998struct url_ent *
1999fetchListHTTP(struct url *url __unused, const char *flags __unused)
2000{
2001	warnx("fetchListHTTP(): not implemented");
2002	return (NULL);
2003}
2004