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