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