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