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