http.c revision 253805
1139749Simp/*-
239223Sgibbs * Copyright (c) 2000-2013 Dag-Erling Sm��rgrav
339223Sgibbs * All rights reserved.
439223Sgibbs *
544579Sgibbs * Redistribution and use in source and binary forms, with or without
639223Sgibbs * modification, are permitted provided that the following conditions
739223Sgibbs * are met:
839223Sgibbs * 1. Redistributions of source code must retain the above copyright
939223Sgibbs *    notice, this list of conditions and the following disclaimer
1039223Sgibbs *    in this position and unchanged.
1139223Sgibbs * 2. Redistributions in binary form must reproduce the above copyright
1239223Sgibbs *    notice, this list of conditions and the following disclaimer in the
1339223Sgibbs *    documentation and/or other materials provided with the distribution.
1439223Sgibbs * 3. The name of the author may not be used to endorse or promote products
1539223Sgibbs *    derived from this software without specific prior written permission.
1639223Sgibbs *
1739223Sgibbs * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1839223Sgibbs * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1939223Sgibbs * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2039223Sgibbs * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2139223Sgibbs * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2239223Sgibbs * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2339223Sgibbs * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2439223Sgibbs * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2539223Sgibbs * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2639223Sgibbs * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2739223Sgibbs */
2839223Sgibbs
2939223Sgibbs#include <sys/cdefs.h>
3039223Sgibbs__FBSDID("$FreeBSD: head/lib/libfetch/http.c 253805 2013-07-30 13:07:55Z des $");
31119418Sobrien
32119418Sobrien/*
33119418Sobrien * The following copyright applies to the base64 code:
3439223Sgibbs *
3539223Sgibbs *-
3645791Speter * Copyright 1997 Massachusetts Institute of Technology
3745791Speter *
38117126Sscottl * Permission to use, copy, modify, and distribute this software and
39117126Sscottl * its documentation for any purpose and without fee is hereby
4045791Speter * granted, provided that both the above copyright notice and this
4139223Sgibbs * permission notice appear in all copies, that both the above
4239223Sgibbs * copyright notice and this permission notice appear in all
4345791Speter * supporting documentation, and that the name of M.I.T. not be used
4445791Speter * in advertising or publicity pertaining to distribution of the
4539223Sgibbs * software without specific, written prior permission.  M.I.T. makes
4645791Speter * no representations about the suitability of this software for any
4739223Sgibbs * purpose.  It is provided "as is" without express or implied
4839223Sgibbs * warranty.
4939223Sgibbs *
5039223Sgibbs * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
5139223Sgibbs * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
5239223Sgibbs * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
5339223Sgibbs * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
5445791Speter * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5547399Sdfr * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5639223Sgibbs * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
5745791Speter * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
5845791Speter * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
5945791Speter * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
6045791Speter * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
6139223Sgibbs * SUCH DAMAGE.
6245791Speter */
6345791Speter
6447399Sdfr#include <sys/param.h>
6545791Speter#include <sys/socket.h>
6645791Speter#include <sys/time.h>
6745791Speter
6845791Speter#include <ctype.h>
6945791Speter#include <err.h>
70127135Snjl#include <errno.h>
7145791Speter#include <locale.h>
7245791Speter#include <netdb.h>
7345791Speter#include <stdarg.h>
7445791Speter#include <stdio.h>
7545791Speter#include <stdlib.h>
7645791Speter#include <string.h>
7745791Speter#include <time.h>
78241592Sjhb#include <unistd.h>
7945791Speter
8045791Speter#ifdef WITH_SSL
8145791Speter#include <openssl/md5.h>
82127135Snjl#define MD5Init(c) MD5_Init(c)
8345791Speter#define MD5Update(c, data, len) MD5_Update(c, data, len)
8445791Speter#define MD5Final(md, c) MD5_Final(md, c)
8545791Speter#else
8645791Speter#include <md5.h>
8745791Speter#endif
8845791Speter
8945791Speter#include <netinet/in.h>
9045791Speter#include <netinet/tcp.h>
9145791Speter
9245791Speter#include "fetch.h"
93241592Sjhb#include "common.h"
9445791Speter#include "httperr.h"
9545791Speter
9645791Speter/* Maximum number of redirects to follow */
9745791Speter#define MAX_REDIRECT 20
9845791Speter
9945791Speter/* Symbolic names for reply codes we care about */
10045791Speter#define HTTP_OK			200
10145791Speter#define HTTP_PARTIAL		206
10245791Speter#define HTTP_MOVED_PERM		301
10345791Speter#define HTTP_MOVED_TEMP		302
10445791Speter#define HTTP_SEE_OTHER		303
10545791Speter#define HTTP_NOT_MODIFIED	304
10645791Speter#define HTTP_USE_PROXY		305
10745791Speter#define HTTP_TEMP_REDIRECT	307
10845796Speter#define HTTP_PERM_REDIRECT	308
10945791Speter#define HTTP_NEED_AUTH		401
11045796Speter#define HTTP_NEED_PROXY_AUTH	407
11145791Speter#define HTTP_BAD_RANGE		416
11245791Speter#define HTTP_PROTOCOL_ERROR	999
11345791Speter
11439223Sgibbs#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
11539223Sgibbs			    || (xyz) == HTTP_MOVED_TEMP \
11639223Sgibbs			    || (xyz) == HTTP_TEMP_REDIRECT \
11739223Sgibbs			    || (xyz) == HTTP_USE_PROXY \
11839223Sgibbs			    || (xyz) == HTTP_SEE_OTHER)
11939223Sgibbs
12039223Sgibbs#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
12145791Speter
12239223Sgibbs
12339223Sgibbs/*****************************************************************************
12439223Sgibbs * I/O functions for decoding chunked streams
12539223Sgibbs */
12639223Sgibbs
12739223Sgibbsstruct httpio
12839223Sgibbs{
12947617Sdfr	conn_t		*conn;		/* connection */
13047617Sdfr	int		 chunked;	/* chunked mode */
13147617Sdfr	char		*buf;		/* chunk buffer */
13247617Sdfr	size_t		 bufsize;	/* size of chunk buffer */
13339223Sgibbs	ssize_t		 buflen;	/* amount of data currently in buffer */
13439223Sgibbs	int		 bufpos;	/* current read offset in buffer */
13539223Sgibbs	int		 eof;		/* end-of-file flag */
13639223Sgibbs	int		 error;		/* error flag */
13739223Sgibbs	size_t		 chunksize;	/* remaining size of current chunk */
13839223Sgibbs#ifndef NDEBUG
13945791Speter	size_t		 total;
14039223Sgibbs#endif
14141048Sgibbs};
14245791Speter
14341048Sgibbs/*
14439223Sgibbs * Get next chunk header
14539223Sgibbs */
14644579Sgibbsstatic int
14739223Sgibbshttp_new_chunk(struct httpio *io)
14839223Sgibbs{
14941048Sgibbs	char *p;
15039223Sgibbs
15139223Sgibbs	if (fetch_getln(io->conn) == -1)
15239223Sgibbs		return (-1);
15340265Simp
15439223Sgibbs	if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf))
15539223Sgibbs		return (-1);
15639223Sgibbs
15745791Speter	for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) {
15845791Speter		if (*p == ';')
15947399Sdfr			break;
16047399Sdfr		if (!isxdigit((unsigned char)*p))
16140160Simp			return (-1);
16240160Simp		if (isdigit((unsigned char)*p)) {
16339223Sgibbs			io->chunksize = io->chunksize * 16 +
16439223Sgibbs			    *p - '0';
16539223Sgibbs		} else {
16645791Speter			io->chunksize = io->chunksize * 16 +
16747717Speter			    10 + tolower((unsigned char)*p) - 'a';
16847717Speter		}
16947717Speter	}
17045791Speter
17139223Sgibbs#ifndef NDEBUG
17239223Sgibbs	if (fetchDebug) {
17339223Sgibbs		io->total += io->chunksize;
17445791Speter		if (io->chunksize == 0)
17540160Simp			fprintf(stderr, "%s(): end of last chunk\n", __func__);
17652174Sdfr		else
17752174Sdfr			fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
17845791Speter			    __func__, (unsigned long)io->chunksize,
179241592Sjhb			    (unsigned long)io->total);
18039223Sgibbs	}
18139223Sgibbs#endif
18245791Speter
18339223Sgibbs	return (io->chunksize);
18439223Sgibbs}
18539223Sgibbs
18639223Sgibbs/*
18739223Sgibbs * Grow the input buffer to at least len bytes
18839223Sgibbs */
18945791Speterstatic inline int
19039223Sgibbshttp_growbuf(struct httpio *io, size_t len)
19145791Speter{
19239223Sgibbs	char *tmp;
19339223Sgibbs
19439223Sgibbs	if (io->bufsize >= len)
19545796Speter		return (0);
19639223Sgibbs
19745791Speter	if ((tmp = realloc(io->buf, len)) == NULL)
19847399Sdfr		return (-1);
19945791Speter	io->buf = tmp;
20045791Speter	io->bufsize = len;
20145791Speter	return (0);
20245791Speter}
20339223Sgibbs
20445796Speter/*
20545796Speter * Fill the input buffer, do chunk decoding on the fly
20645796Speter */
20745796Speterstatic int
20839223Sgibbshttp_fillbuf(struct httpio *io, size_t len)
20939223Sgibbs{
21039223Sgibbs	ssize_t nbytes;
21139223Sgibbs
21239223Sgibbs	if (io->error)
21339223Sgibbs		return (-1);
21439223Sgibbs	if (io->eof)
21539223Sgibbs		return (0);
21639223Sgibbs
21739223Sgibbs	if (io->chunked == 0) {
21839223Sgibbs		if (http_growbuf(io, len) == -1)
21939223Sgibbs			return (-1);
22039223Sgibbs		if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
22139223Sgibbs			io->error = errno;
22239223Sgibbs			return (-1);
22339223Sgibbs		}
22439223Sgibbs		io->buflen = nbytes;
22539223Sgibbs		io->bufpos = 0;
22639223Sgibbs		return (io->buflen);
22739223Sgibbs	}
22839223Sgibbs
22939223Sgibbs	if (io->chunksize == 0) {
23039223Sgibbs		switch (http_new_chunk(io)) {
23139223Sgibbs		case -1:
23239223Sgibbs			io->error = 1;
23339223Sgibbs			return (-1);
23439223Sgibbs		case 0:
23539223Sgibbs			io->eof = 1;
236241592Sjhb			return (0);
237112782Smdodd		}
238112782Smdodd	}
239112782Smdodd
240112782Smdodd	if (len > io->chunksize)
241112782Smdodd		len = io->chunksize;
242112782Smdodd	if (http_growbuf(io, len) == -1)
243112782Smdodd		return (-1);
244112782Smdodd	if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) {
245112782Smdodd		io->error = errno;
246112782Smdodd		return (-1);
247241592Sjhb	}
248241592Sjhb	io->buflen = nbytes;
249112782Smdodd	io->chunksize -= io->buflen;
25045791Speter
25145791Speter	if (io->chunksize == 0) {
25239223Sgibbs		char endl[2];
25339223Sgibbs
25445796Speter		if (fetch_read(io->conn, endl, 2) != 2 ||
25545796Speter		    endl[0] != '\r' || endl[1] != '\n')
25645791Speter			return (-1);
25745791Speter	}
25839223Sgibbs
25939223Sgibbs	io->bufpos = 0;
26039223Sgibbs
26139223Sgibbs	return (io->buflen);
262112782Smdodd}
263112782Smdodd
264112782Smdodd/*
265112782Smdodd * Read function
266112782Smdodd */
267112782Smdoddstatic int
268112782Smdoddhttp_readfn(void *v, char *buf, int len)
269112782Smdodd{
270112782Smdodd	struct httpio *io = (struct httpio *)v;
271112782Smdodd	int l, pos;
272112782Smdodd
273112782Smdodd	if (io->error)
274112782Smdodd		return (-1);
275241592Sjhb	if (io->eof)
276241592Sjhb		return (0);
277112782Smdodd
27845791Speter	for (pos = 0; len > 0; pos += l, len -= l) {
27945791Speter		/* empty buffer */
28039223Sgibbs		if (!io->buf || io->bufpos == io->buflen)
28139223Sgibbs			if (http_fillbuf(io, len) < 1)
28239223Sgibbs				break;
28339223Sgibbs		l = io->buflen - io->bufpos;
28439223Sgibbs		if (len < l)
28539223Sgibbs			l = len;
28639223Sgibbs		memcpy(buf + pos, io->buf + io->bufpos, l);
28739223Sgibbs		io->bufpos += l;
28845791Speter	}
28945791Speter
29039223Sgibbs	if (!pos && io->error) {
29139223Sgibbs		if (io->error == EINTR)
29239223Sgibbs			io->error = 0;
29339223Sgibbs		return (-1);
29439223Sgibbs	}
29539223Sgibbs	return (pos);
29639223Sgibbs}
29739223Sgibbs
29839223Sgibbs/*
29939223Sgibbs * Write function
30039223Sgibbs */
30139223Sgibbsstatic int
30239223Sgibbshttp_writefn(void *v, const char *buf, int len)
30345791Speter{
30445791Speter	struct httpio *io = (struct httpio *)v;
30545791Speter
30645791Speter	return (fetch_write(io->conn, buf, len));
30745791Speter}
30839223Sgibbs
30945791Speter/*
31039223Sgibbs * Close function
31139223Sgibbs */
31239223Sgibbsstatic int
31339223Sgibbshttp_closefn(void *v)
31439223Sgibbs{
31539223Sgibbs	struct httpio *io = (struct httpio *)v;
31639223Sgibbs	int r;
31739223Sgibbs
31839223Sgibbs	r = fetch_close(io->conn);
31939223Sgibbs	if (io->buf)
32039223Sgibbs		free(io->buf);
32139223Sgibbs	free(io);
32239223Sgibbs	return (r);
32339223Sgibbs}
32439223Sgibbs
32539223Sgibbs/*
32639223Sgibbs * Wrap a file descriptor up
32739223Sgibbs */
32839223Sgibbsstatic FILE *
32939223Sgibbshttp_funopen(conn_t *conn, int chunked)
33039223Sgibbs{
33139223Sgibbs	struct httpio *io;
33239223Sgibbs	FILE *f;
33339223Sgibbs
33439223Sgibbs	if ((io = calloc(1, sizeof(*io))) == NULL) {
33539223Sgibbs		fetch_syserr();
33639223Sgibbs		return (NULL);
33739223Sgibbs	}
33845791Speter	io->conn = conn;
33945791Speter	io->chunked = chunked;
34045791Speter	f = funopen(io, http_readfn, http_writefn, NULL, http_closefn);
34145791Speter	if (f == NULL) {
34245791Speter		fetch_syserr();
34345791Speter		free(io);
34445791Speter		return (NULL);
34545791Speter	}
34645791Speter	return (f);
34745791Speter}
34845791Speter
34945791Speter
35045791Speter/*****************************************************************************
35145791Speter * Helper functions for talking to the server and parsing its replies
35245791Speter */
35345791Speter
35445791Speter/* Header types */
35545791Spetertypedef enum {
356165102Smjacob	hdr_syserror = -2,
357	hdr_error = -1,
358	hdr_end = 0,
359	hdr_unknown = 1,
360	hdr_content_length,
361	hdr_content_range,
362	hdr_last_modified,
363	hdr_location,
364	hdr_transfer_encoding,
365	hdr_www_authenticate,
366	hdr_proxy_authenticate,
367} hdr_t;
368
369/* Names of interesting headers */
370static struct {
371	hdr_t		 num;
372	const char	*name;
373} hdr_names[] = {
374	{ hdr_content_length,		"Content-Length" },
375	{ hdr_content_range,		"Content-Range" },
376	{ hdr_last_modified,		"Last-Modified" },
377	{ hdr_location,			"Location" },
378	{ hdr_transfer_encoding,	"Transfer-Encoding" },
379	{ hdr_www_authenticate,		"WWW-Authenticate" },
380	{ hdr_proxy_authenticate,	"Proxy-Authenticate" },
381	{ hdr_unknown,			NULL },
382};
383
384/*
385 * Send a formatted line; optionally echo to terminal
386 */
387static int
388http_cmd(conn_t *conn, const char *fmt, ...)
389{
390	va_list ap;
391	size_t len;
392	char *msg;
393	int r;
394
395	va_start(ap, fmt);
396	len = vasprintf(&msg, fmt, ap);
397	va_end(ap);
398
399	if (msg == NULL) {
400		errno = ENOMEM;
401		fetch_syserr();
402		return (-1);
403	}
404
405	r = fetch_putln(conn, msg, len);
406	free(msg);
407
408	if (r == -1) {
409		fetch_syserr();
410		return (-1);
411	}
412
413	return (0);
414}
415
416/*
417 * Get and parse status line
418 */
419static int
420http_get_reply(conn_t *conn)
421{
422	char *p;
423
424	if (fetch_getln(conn) == -1)
425		return (-1);
426	/*
427	 * A valid status line looks like "HTTP/m.n xyz reason" where m
428	 * and n are the major and minor protocol version numbers and xyz
429	 * is the reply code.
430	 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
431	 * just one) that do not send a version number, so we can't rely
432	 * on finding one, but if we do, insist on it being 1.0 or 1.1.
433	 * We don't care about the reason phrase.
434	 */
435	if (strncmp(conn->buf, "HTTP", 4) != 0)
436		return (HTTP_PROTOCOL_ERROR);
437	p = conn->buf + 4;
438	if (*p == '/') {
439		if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
440			return (HTTP_PROTOCOL_ERROR);
441		p += 4;
442	}
443	if (*p != ' ' ||
444	    !isdigit((unsigned char)p[1]) ||
445	    !isdigit((unsigned char)p[2]) ||
446	    !isdigit((unsigned char)p[3]))
447		return (HTTP_PROTOCOL_ERROR);
448
449	conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
450	return (conn->err);
451}
452
453/*
454 * Check a header; if the type matches the given string, return a pointer
455 * to the beginning of the value.
456 */
457static const char *
458http_match(const char *str, const char *hdr)
459{
460	while (*str && *hdr &&
461	    tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++))
462		/* nothing */;
463	if (*str || *hdr != ':')
464		return (NULL);
465	while (*hdr && isspace((unsigned char)*++hdr))
466		/* nothing */;
467	return (hdr);
468}
469
470
471/*
472 * Get the next header and return the appropriate symbolic code.  We
473 * need to read one line ahead for checking for a continuation line
474 * belonging to the current header (continuation lines start with
475 * white space).
476 *
477 * We get called with a fresh line already in the conn buffer, either
478 * from the previous http_next_header() invocation, or, the first
479 * time, from a fetch_getln() performed by our caller.
480 *
481 * This stops when we encounter an empty line (we dont read beyond the header
482 * area).
483 *
484 * Note that the "headerbuf" is just a place to return the result. Its
485 * contents are not used for the next call. This means that no cleanup
486 * is needed when ie doing another connection, just call the cleanup when
487 * fully done to deallocate memory.
488 */
489
490/* Limit the max number of continuation lines to some reasonable value */
491#define HTTP_MAX_CONT_LINES 10
492
493/* Place into which to build a header from one or several lines */
494typedef struct {
495	char	*buf;		/* buffer */
496	size_t	 bufsize;	/* buffer size */
497	size_t	 buflen;	/* length of buffer contents */
498} http_headerbuf_t;
499
500static void
501init_http_headerbuf(http_headerbuf_t *buf)
502{
503	buf->buf = NULL;
504	buf->bufsize = 0;
505	buf->buflen = 0;
506}
507
508static void
509clean_http_headerbuf(http_headerbuf_t *buf)
510{
511	if (buf->buf)
512		free(buf->buf);
513	init_http_headerbuf(buf);
514}
515
516/* Remove whitespace at the end of the buffer */
517static void
518http_conn_trimright(conn_t *conn)
519{
520	while (conn->buflen &&
521	       isspace((unsigned char)conn->buf[conn->buflen - 1]))
522		conn->buflen--;
523	conn->buf[conn->buflen] = '\0';
524}
525
526static hdr_t
527http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p)
528{
529	unsigned int i, len;
530
531	/*
532	 * Have to do the stripping here because of the first line. So
533	 * it's done twice for the subsequent lines. No big deal
534	 */
535	http_conn_trimright(conn);
536	if (conn->buflen == 0)
537		return (hdr_end);
538
539	/* Copy the line to the headerbuf */
540	if (hbuf->bufsize < conn->buflen + 1) {
541		if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL)
542			return (hdr_syserror);
543		hbuf->bufsize = conn->buflen + 1;
544	}
545	strcpy(hbuf->buf, conn->buf);
546	hbuf->buflen = conn->buflen;
547
548	/*
549	 * Fetch possible continuation lines. Stop at 1st non-continuation
550	 * and leave it in the conn buffer
551	 */
552	for (i = 0; i < HTTP_MAX_CONT_LINES; i++) {
553		if (fetch_getln(conn) == -1)
554			return (hdr_syserror);
555
556		/*
557		 * Note: we carry on the idea from the previous version
558		 * that a pure whitespace line is equivalent to an empty
559		 * one (so it's not continuation and will be handled when
560		 * we are called next)
561		 */
562		http_conn_trimright(conn);
563		if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0])
564			break;
565
566		/* Got a continuation line. Concatenate to previous */
567		len = hbuf->buflen + conn->buflen;
568		if (hbuf->bufsize < len + 1) {
569			len *= 2;
570			if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL)
571				return (hdr_syserror);
572			hbuf->bufsize = len + 1;
573		}
574		strcpy(hbuf->buf + hbuf->buflen, conn->buf);
575		hbuf->buflen += conn->buflen;
576	}
577
578	/*
579	 * We could check for malformed headers but we don't really care.
580	 * A valid header starts with a token immediately followed by a
581	 * colon; a token is any sequence of non-control, non-whitespace
582	 * characters except "()<>@,;:\\\"{}".
583	 */
584	for (i = 0; hdr_names[i].num != hdr_unknown; i++)
585		if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL)
586			return (hdr_names[i].num);
587
588	return (hdr_unknown);
589}
590
591/**************************
592 * [Proxy-]Authenticate header parsing
593 */
594
595/*
596 * Read doublequote-delimited string into output buffer obuf (allocated
597 * by caller, whose responsibility it is to ensure that it's big enough)
598 * cp points to the first char after the initial '"'
599 * Handles \ quoting
600 * Returns pointer to the first char after the terminating double quote, or
601 * NULL for error.
602 */
603static const char *
604http_parse_headerstring(const char *cp, char *obuf)
605{
606	for (;;) {
607		switch (*cp) {
608		case 0: /* Unterminated string */
609			*obuf = 0;
610			return (NULL);
611		case '"': /* Ending quote */
612			*obuf = 0;
613			return (++cp);
614		case '\\':
615			if (*++cp == 0) {
616				*obuf = 0;
617				return (NULL);
618			}
619			/* FALLTHROUGH */
620		default:
621			*obuf++ = *cp++;
622		}
623	}
624}
625
626/* Http auth challenge schemes */
627typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t;
628
629/* Data holder for a Basic or Digest challenge. */
630typedef struct {
631	http_auth_schemes_t scheme;
632	char	*realm;
633	char	*qop;
634	char	*nonce;
635	char	*opaque;
636	char	*algo;
637	int	 stale;
638	int	 nc; /* Nonce count */
639} http_auth_challenge_t;
640
641static void
642init_http_auth_challenge(http_auth_challenge_t *b)
643{
644	b->scheme = HTTPAS_UNKNOWN;
645	b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL;
646	b->stale = b->nc = 0;
647}
648
649static void
650clean_http_auth_challenge(http_auth_challenge_t *b)
651{
652	if (b->realm)
653		free(b->realm);
654	if (b->qop)
655		free(b->qop);
656	if (b->nonce)
657		free(b->nonce);
658	if (b->opaque)
659		free(b->opaque);
660	if (b->algo)
661		free(b->algo);
662	init_http_auth_challenge(b);
663}
664
665/* Data holder for an array of challenges offered in an http response. */
666#define MAX_CHALLENGES 10
667typedef struct {
668	http_auth_challenge_t *challenges[MAX_CHALLENGES];
669	int	count; /* Number of parsed challenges in the array */
670	int	valid; /* We did parse an authenticate header */
671} http_auth_challenges_t;
672
673static void
674init_http_auth_challenges(http_auth_challenges_t *cs)
675{
676	int i;
677	for (i = 0; i < MAX_CHALLENGES; i++)
678		cs->challenges[i] = NULL;
679	cs->count = cs->valid = 0;
680}
681
682static void
683clean_http_auth_challenges(http_auth_challenges_t *cs)
684{
685	int i;
686	/* We rely on non-zero pointers being allocated, not on the count */
687	for (i = 0; i < MAX_CHALLENGES; i++) {
688		if (cs->challenges[i] != NULL) {
689			clean_http_auth_challenge(cs->challenges[i]);
690			free(cs->challenges[i]);
691		}
692	}
693	init_http_auth_challenges(cs);
694}
695
696/*
697 * Enumeration for lexical elements. Separators will be returned as their own
698 * ascii value
699 */
700typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258,
701	      HTTPHL_ERROR = 259} http_header_lex_t;
702
703/*
704 * Determine what kind of token comes next and return possible value
705 * in buf, which is supposed to have been allocated big enough by
706 * caller. Advance input pointer and return element type.
707 */
708static int
709http_header_lex(const char **cpp, char *buf)
710{
711	size_t l;
712	/* Eat initial whitespace */
713	*cpp += strspn(*cpp, " \t");
714	if (**cpp == 0)
715		return (HTTPHL_END);
716
717	/* Separator ? */
718	if (**cpp == ',' || **cpp == '=')
719		return (*((*cpp)++));
720
721	/* String ? */
722	if (**cpp == '"') {
723		*cpp = http_parse_headerstring(++*cpp, buf);
724		if (*cpp == NULL)
725			return (HTTPHL_ERROR);
726		return (HTTPHL_STRING);
727	}
728
729	/* Read other token, until separator or whitespace */
730	l = strcspn(*cpp, " \t,=");
731	memcpy(buf, *cpp, l);
732	buf[l] = 0;
733	*cpp += l;
734	return (HTTPHL_WORD);
735}
736
737/*
738 * Read challenges from http xxx-authenticate header and accumulate them
739 * in the challenges list structure.
740 *
741 * Headers with multiple challenges are specified by rfc2617, but
742 * servers (ie: squid) often send them in separate headers instead,
743 * which in turn is forbidden by the http spec (multiple headers with
744 * the same name are only allowed for pure comma-separated lists, see
745 * rfc2616 sec 4.2).
746 *
747 * We support both approaches anyway
748 */
749static int
750http_parse_authenticate(const char *cp, http_auth_challenges_t *cs)
751{
752	int ret = -1;
753	http_header_lex_t lex;
754	char *key = malloc(strlen(cp) + 1);
755	char *value = malloc(strlen(cp) + 1);
756	char *buf = malloc(strlen(cp) + 1);
757
758	if (key == NULL || value == NULL || buf == NULL) {
759		fetch_syserr();
760		goto out;
761	}
762
763	/* In any case we've seen the header and we set the valid bit */
764	cs->valid = 1;
765
766	/* Need word first */
767	lex = http_header_lex(&cp, key);
768	if (lex != HTTPHL_WORD)
769		goto out;
770
771	/* Loop on challenges */
772	for (; cs->count < MAX_CHALLENGES; cs->count++) {
773		cs->challenges[cs->count] =
774			malloc(sizeof(http_auth_challenge_t));
775		if (cs->challenges[cs->count] == NULL) {
776			fetch_syserr();
777			goto out;
778		}
779		init_http_auth_challenge(cs->challenges[cs->count]);
780		if (!strcasecmp(key, "basic")) {
781			cs->challenges[cs->count]->scheme = HTTPAS_BASIC;
782		} else if (!strcasecmp(key, "digest")) {
783			cs->challenges[cs->count]->scheme = HTTPAS_DIGEST;
784		} else {
785			cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN;
786			/*
787			 * Continue parsing as basic or digest may
788			 * follow, and the syntax is the same for
789			 * all. We'll just ignore this one when
790			 * looking at the list
791			 */
792		}
793
794		/* Loop on attributes */
795		for (;;) {
796			/* Key */
797			lex = http_header_lex(&cp, key);
798			if (lex != HTTPHL_WORD)
799				goto out;
800
801			/* Equal sign */
802			lex = http_header_lex(&cp, buf);
803			if (lex != '=')
804				goto out;
805
806			/* Value */
807			lex = http_header_lex(&cp, value);
808			if (lex != HTTPHL_WORD && lex != HTTPHL_STRING)
809				goto out;
810
811			if (!strcasecmp(key, "realm"))
812				cs->challenges[cs->count]->realm =
813					strdup(value);
814			else if (!strcasecmp(key, "qop"))
815				cs->challenges[cs->count]->qop =
816					strdup(value);
817			else if (!strcasecmp(key, "nonce"))
818				cs->challenges[cs->count]->nonce =
819					strdup(value);
820			else if (!strcasecmp(key, "opaque"))
821				cs->challenges[cs->count]->opaque =
822					strdup(value);
823			else if (!strcasecmp(key, "algorithm"))
824				cs->challenges[cs->count]->algo =
825					strdup(value);
826			else if (!strcasecmp(key, "stale"))
827				cs->challenges[cs->count]->stale =
828					strcasecmp(value, "no");
829			/* Else ignore unknown attributes */
830
831			/* Comma or Next challenge or End */
832			lex = http_header_lex(&cp, key);
833			/*
834			 * If we get a word here, this is the beginning of the
835			 * next challenge. Break the attributes loop
836			 */
837			if (lex == HTTPHL_WORD)
838				break;
839
840			if (lex == HTTPHL_END) {
841				/* End while looking for ',' is normal exit */
842				cs->count++;
843				ret = 0;
844				goto out;
845			}
846			/* Anything else is an error */
847			if (lex != ',')
848				goto out;
849
850		} /* End attributes loop */
851	} /* End challenge loop */
852
853	/*
854	 * Challenges max count exceeded. This really can't happen
855	 * with normal data, something's fishy -> error
856	 */
857
858out:
859	if (key)
860		free(key);
861	if (value)
862		free(value);
863	if (buf)
864		free(buf);
865	return (ret);
866}
867
868
869/*
870 * Parse a last-modified header
871 */
872static int
873http_parse_mtime(const char *p, time_t *mtime)
874{
875	char locale[64], *r;
876	struct tm tm;
877
878	strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
879	setlocale(LC_TIME, "C");
880	r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
881	/* XXX should add support for date-2 and date-3 */
882	setlocale(LC_TIME, locale);
883	if (r == NULL)
884		return (-1);
885	DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
886		  "%02d:%02d:%02d]\n",
887		  tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
888		  tm.tm_hour, tm.tm_min, tm.tm_sec));
889	*mtime = timegm(&tm);
890	return (0);
891}
892
893/*
894 * Parse a content-length header
895 */
896static int
897http_parse_length(const char *p, off_t *length)
898{
899	off_t len;
900
901	for (len = 0; *p && isdigit((unsigned char)*p); ++p)
902		len = len * 10 + (*p - '0');
903	if (*p)
904		return (-1);
905	DEBUG(fprintf(stderr, "content length: [%lld]\n",
906	    (long long)len));
907	*length = len;
908	return (0);
909}
910
911/*
912 * Parse a content-range header
913 */
914static int
915http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
916{
917	off_t first, last, len;
918
919	if (strncasecmp(p, "bytes ", 6) != 0)
920		return (-1);
921	p += 6;
922	if (*p == '*') {
923		first = last = -1;
924		++p;
925	} else {
926		for (first = 0; *p && isdigit((unsigned char)*p); ++p)
927			first = first * 10 + *p - '0';
928		if (*p != '-')
929			return (-1);
930		for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
931			last = last * 10 + *p - '0';
932	}
933	if (first > last || *p != '/')
934		return (-1);
935	for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p)
936		len = len * 10 + *p - '0';
937	if (*p || len < last - first + 1)
938		return (-1);
939	if (first == -1) {
940		DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
941		    (long long)len));
942		*length = 0;
943	} else {
944		DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
945		    (long long)first, (long long)last, (long long)len));
946		*length = last - first + 1;
947	}
948	*offset = first;
949	*size = len;
950	return (0);
951}
952
953
954/*****************************************************************************
955 * Helper functions for authorization
956 */
957
958/*
959 * Base64 encoding
960 */
961static char *
962http_base64(const char *src)
963{
964	static const char base64[] =
965	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
966	    "abcdefghijklmnopqrstuvwxyz"
967	    "0123456789+/";
968	char *str, *dst;
969	size_t l;
970	int t, r;
971
972	l = strlen(src);
973	if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
974		return (NULL);
975	dst = str;
976	r = 0;
977
978	while (l >= 3) {
979		t = (src[0] << 16) | (src[1] << 8) | src[2];
980		dst[0] = base64[(t >> 18) & 0x3f];
981		dst[1] = base64[(t >> 12) & 0x3f];
982		dst[2] = base64[(t >> 6) & 0x3f];
983		dst[3] = base64[(t >> 0) & 0x3f];
984		src += 3; l -= 3;
985		dst += 4; r += 4;
986	}
987
988	switch (l) {
989	case 2:
990		t = (src[0] << 16) | (src[1] << 8);
991		dst[0] = base64[(t >> 18) & 0x3f];
992		dst[1] = base64[(t >> 12) & 0x3f];
993		dst[2] = base64[(t >> 6) & 0x3f];
994		dst[3] = '=';
995		dst += 4;
996		r += 4;
997		break;
998	case 1:
999		t = src[0] << 16;
1000		dst[0] = base64[(t >> 18) & 0x3f];
1001		dst[1] = base64[(t >> 12) & 0x3f];
1002		dst[2] = dst[3] = '=';
1003		dst += 4;
1004		r += 4;
1005		break;
1006	case 0:
1007		break;
1008	}
1009
1010	*dst = 0;
1011	return (str);
1012}
1013
1014
1015/*
1016 * Extract authorization parameters from environment value.
1017 * The value is like scheme:realm:user:pass
1018 */
1019typedef struct {
1020	char	*scheme;
1021	char	*realm;
1022	char	*user;
1023	char	*password;
1024} http_auth_params_t;
1025
1026static void
1027init_http_auth_params(http_auth_params_t *s)
1028{
1029	s->scheme = s->realm = s->user = s->password = 0;
1030}
1031
1032static void
1033clean_http_auth_params(http_auth_params_t *s)
1034{
1035	if (s->scheme)
1036		free(s->scheme);
1037	if (s->realm)
1038		free(s->realm);
1039	if (s->user)
1040		free(s->user);
1041	if (s->password)
1042		free(s->password);
1043	init_http_auth_params(s);
1044}
1045
1046static int
1047http_authfromenv(const char *p, http_auth_params_t *parms)
1048{
1049	int ret = -1;
1050	char *v, *ve;
1051	char *str = strdup(p);
1052
1053	if (str == NULL) {
1054		fetch_syserr();
1055		return (-1);
1056	}
1057	v = str;
1058
1059	if ((ve = strchr(v, ':')) == NULL)
1060		goto out;
1061
1062	*ve = 0;
1063	if ((parms->scheme = strdup(v)) == NULL) {
1064		fetch_syserr();
1065		goto out;
1066	}
1067	v = ve + 1;
1068
1069	if ((ve = strchr(v, ':')) == NULL)
1070		goto out;
1071
1072	*ve = 0;
1073	if ((parms->realm = strdup(v)) == NULL) {
1074		fetch_syserr();
1075		goto out;
1076	}
1077	v = ve + 1;
1078
1079	if ((ve = strchr(v, ':')) == NULL)
1080		goto out;
1081
1082	*ve = 0;
1083	if ((parms->user = strdup(v)) == NULL) {
1084		fetch_syserr();
1085		goto out;
1086	}
1087	v = ve + 1;
1088
1089
1090	if ((parms->password = strdup(v)) == NULL) {
1091		fetch_syserr();
1092		goto out;
1093	}
1094	ret = 0;
1095out:
1096	if (ret == -1)
1097		clean_http_auth_params(parms);
1098	if (str)
1099		free(str);
1100	return (ret);
1101}
1102
1103
1104/*
1105 * Digest response: the code to compute the digest is taken from the
1106 * sample implementation in RFC2616
1107 */
1108#define IN const
1109#define OUT
1110
1111#define HASHLEN 16
1112typedef char HASH[HASHLEN];
1113#define HASHHEXLEN 32
1114typedef char HASHHEX[HASHHEXLEN+1];
1115
1116static const char *hexchars = "0123456789abcdef";
1117static void
1118CvtHex(IN HASH Bin, OUT HASHHEX Hex)
1119{
1120	unsigned short i;
1121	unsigned char j;
1122
1123	for (i = 0; i < HASHLEN; i++) {
1124		j = (Bin[i] >> 4) & 0xf;
1125		Hex[i*2] = hexchars[j];
1126		j = Bin[i] & 0xf;
1127		Hex[i*2+1] = hexchars[j];
1128	};
1129	Hex[HASHHEXLEN] = '\0';
1130};
1131
1132/* calculate H(A1) as per spec */
1133static void
1134DigestCalcHA1(
1135	IN char * pszAlg,
1136	IN char * pszUserName,
1137	IN char * pszRealm,
1138	IN char * pszPassword,
1139	IN char * pszNonce,
1140	IN char * pszCNonce,
1141	OUT HASHHEX SessionKey
1142	)
1143{
1144	MD5_CTX Md5Ctx;
1145	HASH HA1;
1146
1147	MD5Init(&Md5Ctx);
1148	MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName));
1149	MD5Update(&Md5Ctx, ":", 1);
1150	MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm));
1151	MD5Update(&Md5Ctx, ":", 1);
1152	MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword));
1153	MD5Final(HA1, &Md5Ctx);
1154	if (strcasecmp(pszAlg, "md5-sess") == 0) {
1155
1156		MD5Init(&Md5Ctx);
1157		MD5Update(&Md5Ctx, HA1, HASHLEN);
1158		MD5Update(&Md5Ctx, ":", 1);
1159		MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1160		MD5Update(&Md5Ctx, ":", 1);
1161		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1162		MD5Final(HA1, &Md5Ctx);
1163	};
1164	CvtHex(HA1, SessionKey);
1165}
1166
1167/* calculate request-digest/response-digest as per HTTP Digest spec */
1168static void
1169DigestCalcResponse(
1170	IN HASHHEX HA1,           /* H(A1) */
1171	IN char * pszNonce,       /* nonce from server */
1172	IN char * pszNonceCount,  /* 8 hex digits */
1173	IN char * pszCNonce,      /* client nonce */
1174	IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
1175	IN char * pszMethod,      /* method from the request */
1176	IN char * pszDigestUri,   /* requested URL */
1177	IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
1178	OUT HASHHEX Response      /* request-digest or response-digest */
1179	)
1180{
1181/*	DEBUG(fprintf(stderr,
1182		      "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n",
1183		      HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/
1184	MD5_CTX Md5Ctx;
1185	HASH HA2;
1186	HASH RespHash;
1187	HASHHEX HA2Hex;
1188
1189	// calculate H(A2)
1190	MD5Init(&Md5Ctx);
1191	MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod));
1192	MD5Update(&Md5Ctx, ":", 1);
1193	MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri));
1194	if (strcasecmp(pszQop, "auth-int") == 0) {
1195		MD5Update(&Md5Ctx, ":", 1);
1196		MD5Update(&Md5Ctx, HEntity, HASHHEXLEN);
1197	};
1198	MD5Final(HA2, &Md5Ctx);
1199	CvtHex(HA2, HA2Hex);
1200
1201	// calculate response
1202	MD5Init(&Md5Ctx);
1203	MD5Update(&Md5Ctx, HA1, HASHHEXLEN);
1204	MD5Update(&Md5Ctx, ":", 1);
1205	MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce));
1206	MD5Update(&Md5Ctx, ":", 1);
1207	if (*pszQop) {
1208		MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount));
1209		MD5Update(&Md5Ctx, ":", 1);
1210		MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce));
1211		MD5Update(&Md5Ctx, ":", 1);
1212		MD5Update(&Md5Ctx, pszQop, strlen(pszQop));
1213		MD5Update(&Md5Ctx, ":", 1);
1214	};
1215	MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN);
1216	MD5Final(RespHash, &Md5Ctx);
1217	CvtHex(RespHash, Response);
1218}
1219
1220/*
1221 * Generate/Send a Digest authorization header
1222 * This looks like: [Proxy-]Authorization: credentials
1223 *
1224 *  credentials      = "Digest" digest-response
1225 *  digest-response  = 1#( username | realm | nonce | digest-uri
1226 *                      | response | [ algorithm ] | [cnonce] |
1227 *                      [opaque] | [message-qop] |
1228 *                          [nonce-count]  | [auth-param] )
1229 *  username         = "username" "=" username-value
1230 *  username-value   = quoted-string
1231 *  digest-uri       = "uri" "=" digest-uri-value
1232 *  digest-uri-value = request-uri   ; As specified by HTTP/1.1
1233 *  message-qop      = "qop" "=" qop-value
1234 *  cnonce           = "cnonce" "=" cnonce-value
1235 *  cnonce-value     = nonce-value
1236 *  nonce-count      = "nc" "=" nc-value
1237 *  nc-value         = 8LHEX
1238 *  response         = "response" "=" request-digest
1239 *  request-digest = <"> 32LHEX <">
1240 */
1241static int
1242http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c,
1243		 http_auth_params_t *parms, struct url *url)
1244{
1245	int r;
1246	char noncecount[10];
1247	char cnonce[40];
1248	char *options = 0;
1249
1250	if (!c->realm || !c->nonce) {
1251		DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n"));
1252		return(-1);
1253	}
1254	if (!c->algo)
1255		c->algo = strdup("");
1256
1257	if (asprintf(&options, "%s%s%s%s",
1258		     *c->algo? ",algorithm=" : "", c->algo,
1259		     c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1)
1260		return (-1);
1261
1262	if (!c->qop) {
1263		c->qop = strdup("");
1264		*noncecount = 0;
1265		*cnonce = 0;
1266	} else {
1267		c->nc++;
1268		sprintf(noncecount, "%08x", c->nc);
1269		/* We don't try very hard with the cnonce ... */
1270		sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0));
1271	}
1272
1273	HASHHEX HA1;
1274	DigestCalcHA1(c->algo, parms->user, c->realm,
1275		      parms->password, c->nonce, cnonce, HA1);
1276	DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1));
1277	HASHHEX digest;
1278	DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop,
1279			   "GET", url->doc, "", digest);
1280
1281	if (c->qop[0]) {
1282		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1283			     "nonce=\"%s\",uri=\"%s\",response=\"%s\","
1284			     "qop=\"auth\", cnonce=\"%s\", nc=%s%s",
1285			     hdr, parms->user, c->realm,
1286			     c->nonce, url->doc, digest,
1287			     cnonce, noncecount, options);
1288	} else {
1289		r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\","
1290			     "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s",
1291			     hdr, parms->user, c->realm,
1292			     c->nonce, url->doc, digest, options);
1293	}
1294	if (options)
1295		free(options);
1296	return (r);
1297}
1298
1299/*
1300 * Encode username and password
1301 */
1302static int
1303http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
1304{
1305	char *upw, *auth;
1306	int r;
1307
1308	DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr));
1309	DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd));
1310	if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
1311		return (-1);
1312	auth = http_base64(upw);
1313	free(upw);
1314	if (auth == NULL)
1315		return (-1);
1316	r = http_cmd(conn, "%s: Basic %s", hdr, auth);
1317	free(auth);
1318	return (r);
1319}
1320
1321/*
1322 * Chose the challenge to answer and call the appropriate routine to
1323 * produce the header.
1324 */
1325static int
1326http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs,
1327	       http_auth_params_t *parms, struct url *url)
1328{
1329	http_auth_challenge_t *basic = NULL;
1330	http_auth_challenge_t *digest = NULL;
1331	int i;
1332
1333	/* If user or pass are null we're not happy */
1334	if (!parms->user || !parms->password) {
1335		DEBUG(fprintf(stderr, "NULL usr or pass\n"));
1336		return (-1);
1337	}
1338
1339	/* Look for a Digest and a Basic challenge */
1340	for (i = 0; i < cs->count; i++) {
1341		if (cs->challenges[i]->scheme == HTTPAS_BASIC)
1342			basic = cs->challenges[i];
1343		if (cs->challenges[i]->scheme == HTTPAS_DIGEST)
1344			digest = cs->challenges[i];
1345	}
1346
1347	/* Error if "Digest" was specified and there is no Digest challenge */
1348	if (!digest && (parms->scheme &&
1349			!strcasecmp(parms->scheme, "digest"))) {
1350		DEBUG(fprintf(stderr,
1351			      "Digest auth in env, not supported by peer\n"));
1352		return (-1);
1353	}
1354	/*
1355	 * If "basic" was specified in the environment, or there is no Digest
1356	 * challenge, do the basic thing. Don't need a challenge for this,
1357	 * so no need to check basic!=NULL
1358	 */
1359	if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic")))
1360		return (http_basic_auth(conn,hdr,parms->user,parms->password));
1361
1362	/* Else, prefer digest. We just checked that it's not NULL */
1363	return (http_digest_auth(conn, hdr, digest, parms, url));
1364}
1365
1366/*****************************************************************************
1367 * Helper functions for connecting to a server or proxy
1368 */
1369
1370/*
1371 * Connect to the correct HTTP server or proxy.
1372 */
1373static conn_t *
1374http_connect(struct url *URL, struct url *purl, const char *flags)
1375{
1376	struct url *curl;
1377	conn_t *conn;
1378	int verbose;
1379	int af, val;
1380
1381#ifdef INET6
1382	af = AF_UNSPEC;
1383#else
1384	af = AF_INET;
1385#endif
1386
1387	verbose = CHECK_FLAG('v');
1388	if (CHECK_FLAG('4'))
1389		af = AF_INET;
1390#ifdef INET6
1391	else if (CHECK_FLAG('6'))
1392		af = AF_INET6;
1393#endif
1394
1395	curl = (purl != NULL) ? purl : URL;
1396
1397	if ((conn = fetch_connect(curl->host, curl->port, af, verbose)) == NULL)
1398		/* fetch_connect() has already set an error code */
1399		return (NULL);
1400	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && purl) {
1401		http_cmd(conn, "CONNECT %s:%d HTTP/1.1",
1402		    URL->host, URL->port);
1403		http_cmd(conn, "");
1404		if (http_get_reply(conn) != HTTP_OK) {
1405			fetch_close(conn);
1406			return (NULL);
1407		}
1408		http_get_reply(conn);
1409	}
1410	if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
1411	    fetch_ssl(conn, URL, verbose) == -1) {
1412		fetch_close(conn);
1413		/* grrr */
1414		errno = EAUTH;
1415		fetch_syserr();
1416		return (NULL);
1417	}
1418
1419	val = 1;
1420	setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
1421
1422	return (conn);
1423}
1424
1425static struct url *
1426http_get_proxy(struct url * url, const char *flags)
1427{
1428	struct url *purl;
1429	char *p;
1430
1431	if (flags != NULL && strchr(flags, 'd') != NULL)
1432		return (NULL);
1433	if (fetch_no_proxy_match(url->host))
1434		return (NULL);
1435	if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1436	    *p && (purl = fetchParseURL(p))) {
1437		if (!*purl->scheme)
1438			strcpy(purl->scheme, SCHEME_HTTP);
1439		if (!purl->port)
1440			purl->port = fetch_default_proxy_port(purl->scheme);
1441		if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1442			return (purl);
1443		fetchFreeURL(purl);
1444	}
1445	return (NULL);
1446}
1447
1448static void
1449http_print_html(FILE *out, FILE *in)
1450{
1451	size_t len;
1452	char *line, *p, *q;
1453	int comment, tag;
1454
1455	comment = tag = 0;
1456	while ((line = fgetln(in, &len)) != NULL) {
1457		while (len && isspace((unsigned char)line[len - 1]))
1458			--len;
1459		for (p = q = line; q < line + len; ++q) {
1460			if (comment && *q == '-') {
1461				if (q + 2 < line + len &&
1462				    strcmp(q, "-->") == 0) {
1463					tag = comment = 0;
1464					q += 2;
1465				}
1466			} else if (tag && !comment && *q == '>') {
1467				p = q + 1;
1468				tag = 0;
1469			} else if (!tag && *q == '<') {
1470				if (q > p)
1471					fwrite(p, q - p, 1, out);
1472				tag = 1;
1473				if (q + 3 < line + len &&
1474				    strcmp(q, "<!--") == 0) {
1475					comment = 1;
1476					q += 3;
1477				}
1478			}
1479		}
1480		if (!tag && q > p)
1481			fwrite(p, q - p, 1, out);
1482		fputc('\n', out);
1483	}
1484}
1485
1486
1487/*****************************************************************************
1488 * Core
1489 */
1490
1491/*
1492 * Send a request and process the reply
1493 *
1494 * XXX This function is way too long, the do..while loop should be split
1495 * XXX off into a separate function.
1496 */
1497FILE *
1498http_request(struct url *URL, const char *op, struct url_stat *us,
1499	struct url *purl, const char *flags)
1500{
1501	char timebuf[80];
1502	char hbuf[MAXHOSTNAMELEN + 7], *host;
1503	conn_t *conn;
1504	struct url *url, *new;
1505	int chunked, direct, ims, noredirect, verbose;
1506	int e, i, n, val;
1507	off_t offset, clength, length, size;
1508	time_t mtime;
1509	const char *p;
1510	FILE *f;
1511	hdr_t h;
1512	struct tm *timestruct;
1513	http_headerbuf_t headerbuf;
1514	http_auth_challenges_t server_challenges;
1515	http_auth_challenges_t proxy_challenges;
1516
1517	/* The following calls don't allocate anything */
1518	init_http_headerbuf(&headerbuf);
1519	init_http_auth_challenges(&server_challenges);
1520	init_http_auth_challenges(&proxy_challenges);
1521
1522	direct = CHECK_FLAG('d');
1523	noredirect = CHECK_FLAG('A');
1524	verbose = CHECK_FLAG('v');
1525	ims = CHECK_FLAG('i');
1526
1527	if (direct && purl) {
1528		fetchFreeURL(purl);
1529		purl = NULL;
1530	}
1531
1532	/* try the provided URL first */
1533	url = URL;
1534
1535	n = MAX_REDIRECT;
1536	i = 0;
1537
1538	e = HTTP_PROTOCOL_ERROR;
1539	do {
1540		new = NULL;
1541		chunked = 0;
1542		offset = 0;
1543		clength = -1;
1544		length = -1;
1545		size = -1;
1546		mtime = 0;
1547
1548		/* check port */
1549		if (!url->port)
1550			url->port = fetch_default_port(url->scheme);
1551
1552		/* were we redirected to an FTP URL? */
1553		if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
1554			if (strcmp(op, "GET") == 0)
1555				return (ftp_request(url, "RETR", us, purl, flags));
1556			else if (strcmp(op, "HEAD") == 0)
1557				return (ftp_request(url, "STAT", us, purl, flags));
1558		}
1559
1560		/* connect to server or proxy */
1561		if ((conn = http_connect(url, purl, flags)) == NULL)
1562			goto ouch;
1563
1564		host = url->host;
1565#ifdef INET6
1566		if (strchr(url->host, ':')) {
1567			snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
1568			host = hbuf;
1569		}
1570#endif
1571		if (url->port != fetch_default_port(url->scheme)) {
1572			if (host != hbuf) {
1573				strcpy(hbuf, host);
1574				host = hbuf;
1575			}
1576			snprintf(hbuf + strlen(hbuf),
1577			    sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
1578		}
1579
1580		/* send request */
1581		if (verbose)
1582			fetch_info("requesting %s://%s%s",
1583			    url->scheme, host, url->doc);
1584		if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
1585			http_cmd(conn, "%s %s://%s%s HTTP/1.1",
1586			    op, url->scheme, host, url->doc);
1587		} else {
1588			http_cmd(conn, "%s %s HTTP/1.1",
1589			    op, url->doc);
1590		}
1591
1592		if (ims && url->ims_time) {
1593			timestruct = gmtime((time_t *)&url->ims_time);
1594			(void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT",
1595			    timestruct);
1596			if (verbose)
1597				fetch_info("If-Modified-Since: %s", timebuf);
1598			http_cmd(conn, "If-Modified-Since: %s", timebuf);
1599		}
1600		/* virtual host */
1601		http_cmd(conn, "Host: %s", host);
1602
1603		/*
1604		 * Proxy authorization: we only send auth after we received
1605		 * a 407 error. We do not first try basic anyway (changed
1606		 * when support was added for digest-auth)
1607		 */
1608		if (purl && proxy_challenges.valid) {
1609			http_auth_params_t aparams;
1610			init_http_auth_params(&aparams);
1611			if (*purl->user || *purl->pwd) {
1612				aparams.user = purl->user ?
1613					strdup(purl->user) : strdup("");
1614				aparams.password = purl->pwd?
1615					strdup(purl->pwd) : strdup("");
1616			} else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL &&
1617				   *p != '\0') {
1618				if (http_authfromenv(p, &aparams) < 0) {
1619					http_seterr(HTTP_NEED_PROXY_AUTH);
1620					goto ouch;
1621				}
1622			}
1623			http_authorize(conn, "Proxy-Authorization",
1624				       &proxy_challenges, &aparams, url);
1625			clean_http_auth_params(&aparams);
1626		}
1627
1628		/*
1629		 * Server authorization: we never send "a priori"
1630		 * Basic auth, which used to be done if user/pass were
1631		 * set in the url. This would be weird because we'd send the
1632		 * password in the clear even if Digest is finally to be
1633		 * used (it would have made more sense for the
1634		 * pre-digest version to do this when Basic was specified
1635		 * in the environment)
1636		 */
1637		if (server_challenges.valid) {
1638			http_auth_params_t aparams;
1639			init_http_auth_params(&aparams);
1640			if (*url->user || *url->pwd) {
1641				aparams.user = url->user ?
1642					strdup(url->user) : strdup("");
1643				aparams.password = url->pwd ?
1644					strdup(url->pwd) : strdup("");
1645			} else if ((p = getenv("HTTP_AUTH")) != NULL &&
1646				   *p != '\0') {
1647				if (http_authfromenv(p, &aparams) < 0) {
1648					http_seterr(HTTP_NEED_AUTH);
1649					goto ouch;
1650				}
1651			} else if (fetchAuthMethod &&
1652				   fetchAuthMethod(url) == 0) {
1653				aparams.user = url->user ?
1654					strdup(url->user) : strdup("");
1655				aparams.password = url->pwd ?
1656					strdup(url->pwd) : strdup("");
1657			} else {
1658				http_seterr(HTTP_NEED_AUTH);
1659				goto ouch;
1660			}
1661			http_authorize(conn, "Authorization",
1662				       &server_challenges, &aparams, url);
1663			clean_http_auth_params(&aparams);
1664		}
1665
1666		/* other headers */
1667		if ((p = getenv("HTTP_ACCEPT")) != NULL) {
1668			if (*p != '\0')
1669				http_cmd(conn, "Accept: %s", p);
1670		} else {
1671			http_cmd(conn, "Accept: */*");
1672		}
1673		if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
1674			if (strcasecmp(p, "auto") == 0)
1675				http_cmd(conn, "Referer: %s://%s%s",
1676				    url->scheme, host, url->doc);
1677			else
1678				http_cmd(conn, "Referer: %s", p);
1679		}
1680		if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
1681			http_cmd(conn, "User-Agent: %s", p);
1682		else
1683			http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
1684		if (url->offset > 0)
1685			http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
1686		http_cmd(conn, "Connection: close");
1687		http_cmd(conn, "");
1688
1689		/*
1690		 * Force the queued request to be dispatched.  Normally, one
1691		 * would do this with shutdown(2) but squid proxies can be
1692		 * configured to disallow such half-closed connections.  To
1693		 * be compatible with such configurations, fiddle with socket
1694		 * options to force the pending data to be written.
1695		 */
1696		val = 0;
1697		setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
1698			   sizeof(val));
1699		val = 1;
1700		setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
1701			   sizeof(val));
1702
1703		/* get reply */
1704		switch (http_get_reply(conn)) {
1705		case HTTP_OK:
1706		case HTTP_PARTIAL:
1707		case HTTP_NOT_MODIFIED:
1708			/* fine */
1709			break;
1710		case HTTP_MOVED_PERM:
1711		case HTTP_MOVED_TEMP:
1712		case HTTP_SEE_OTHER:
1713		case HTTP_USE_PROXY:
1714			/*
1715			 * Not so fine, but we still have to read the
1716			 * headers to get the new location.
1717			 */
1718			break;
1719		case HTTP_NEED_AUTH:
1720			if (server_challenges.valid) {
1721				/*
1722				 * We already sent out authorization code,
1723				 * so there's nothing more we can do.
1724				 */
1725				http_seterr(conn->err);
1726				goto ouch;
1727			}
1728			/* try again, but send the password this time */
1729			if (verbose)
1730				fetch_info("server requires authorization");
1731			break;
1732		case HTTP_NEED_PROXY_AUTH:
1733			if (proxy_challenges.valid) {
1734				/*
1735				 * We already sent our proxy
1736				 * authorization code, so there's
1737				 * nothing more we can do. */
1738				http_seterr(conn->err);
1739				goto ouch;
1740			}
1741			/* try again, but send the password this time */
1742			if (verbose)
1743				fetch_info("proxy requires authorization");
1744			break;
1745		case HTTP_BAD_RANGE:
1746			/*
1747			 * This can happen if we ask for 0 bytes because
1748			 * we already have the whole file.  Consider this
1749			 * a success for now, and check sizes later.
1750			 */
1751			break;
1752		case HTTP_PROTOCOL_ERROR:
1753			/* fall through */
1754		case -1:
1755			fetch_syserr();
1756			goto ouch;
1757		default:
1758			http_seterr(conn->err);
1759			if (!verbose)
1760				goto ouch;
1761			/* fall through so we can get the full error message */
1762		}
1763
1764		/* get headers. http_next_header expects one line readahead */
1765		if (fetch_getln(conn) == -1) {
1766			fetch_syserr();
1767			goto ouch;
1768		}
1769		do {
1770			switch ((h = http_next_header(conn, &headerbuf, &p))) {
1771			case hdr_syserror:
1772				fetch_syserr();
1773				goto ouch;
1774			case hdr_error:
1775				http_seterr(HTTP_PROTOCOL_ERROR);
1776				goto ouch;
1777			case hdr_content_length:
1778				http_parse_length(p, &clength);
1779				break;
1780			case hdr_content_range:
1781				http_parse_range(p, &offset, &length, &size);
1782				break;
1783			case hdr_last_modified:
1784				http_parse_mtime(p, &mtime);
1785				break;
1786			case hdr_location:
1787				if (!HTTP_REDIRECT(conn->err))
1788					break;
1789				/*
1790				 * if the A flag is set, we don't follow
1791				 * temporary redirects.
1792				 */
1793				if (noredirect &&
1794				    conn->err != HTTP_MOVED_PERM &&
1795				    conn->err != HTTP_PERM_REDIRECT &&
1796				    conn->err != HTTP_USE_PROXY) {
1797					n = 1;
1798					break;
1799				}
1800				if (new)
1801					free(new);
1802				if (verbose)
1803					fetch_info("%d redirect to %s", conn->err, p);
1804				if (*p == '/')
1805					/* absolute path */
1806					new = fetchMakeURL(url->scheme, url->host, url->port, p,
1807					    url->user, url->pwd);
1808				else
1809					new = fetchParseURL(p);
1810				if (new == NULL) {
1811					/* XXX should set an error code */
1812					DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1813					goto ouch;
1814				}
1815
1816				/* Only copy credentials if the host matches */
1817				if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) {
1818					strcpy(new->user, url->user);
1819					strcpy(new->pwd, url->pwd);
1820				}
1821				new->offset = url->offset;
1822				new->length = url->length;
1823				break;
1824			case hdr_transfer_encoding:
1825				/* XXX weak test*/
1826				chunked = (strcasecmp(p, "chunked") == 0);
1827				break;
1828			case hdr_www_authenticate:
1829				if (conn->err != HTTP_NEED_AUTH)
1830					break;
1831				if (http_parse_authenticate(p, &server_challenges) == 0)
1832					++n;
1833				break;
1834			case hdr_proxy_authenticate:
1835				if (conn->err != HTTP_NEED_PROXY_AUTH)
1836					break;
1837				if (http_parse_authenticate(p, &proxy_challenges) == 0)
1838					++n;
1839				break;
1840			case hdr_end:
1841				/* fall through */
1842			case hdr_unknown:
1843				/* ignore */
1844				break;
1845			}
1846		} while (h > hdr_end);
1847
1848		/* we need to provide authentication */
1849		if (conn->err == HTTP_NEED_AUTH ||
1850		    conn->err == HTTP_NEED_PROXY_AUTH) {
1851			e = conn->err;
1852			if ((conn->err == HTTP_NEED_AUTH &&
1853			     !server_challenges.valid) ||
1854			    (conn->err == HTTP_NEED_PROXY_AUTH &&
1855			     !proxy_challenges.valid)) {
1856				/* 401/7 but no www/proxy-authenticate ?? */
1857				DEBUG(fprintf(stderr, "401/7 and no auth header\n"));
1858				goto ouch;
1859			}
1860			fetch_close(conn);
1861			conn = NULL;
1862			continue;
1863		}
1864
1865		/* requested range not satisfiable */
1866		if (conn->err == HTTP_BAD_RANGE) {
1867			if (url->offset == size && url->length == 0) {
1868				/* asked for 0 bytes; fake it */
1869				offset = url->offset;
1870				clength = -1;
1871				conn->err = HTTP_OK;
1872				break;
1873			} else {
1874				http_seterr(conn->err);
1875				goto ouch;
1876			}
1877		}
1878
1879		/* we have a hit or an error */
1880		if (conn->err == HTTP_OK
1881		    || conn->err == HTTP_NOT_MODIFIED
1882		    || conn->err == HTTP_PARTIAL
1883		    || HTTP_ERROR(conn->err))
1884			break;
1885
1886		/* all other cases: we got a redirect */
1887		e = conn->err;
1888		clean_http_auth_challenges(&server_challenges);
1889		fetch_close(conn);
1890		conn = NULL;
1891		if (!new) {
1892			DEBUG(fprintf(stderr, "redirect with no new location\n"));
1893			break;
1894		}
1895		if (url != URL)
1896			fetchFreeURL(url);
1897		url = new;
1898	} while (++i < n);
1899
1900	/* we failed, or ran out of retries */
1901	if (conn == NULL) {
1902		http_seterr(e);
1903		goto ouch;
1904	}
1905
1906	DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1907		  " size %lld, clength %lld\n",
1908		  (long long)offset, (long long)length,
1909		  (long long)size, (long long)clength));
1910
1911	if (conn->err == HTTP_NOT_MODIFIED) {
1912		http_seterr(HTTP_NOT_MODIFIED);
1913		return (NULL);
1914	}
1915
1916	/* check for inconsistencies */
1917	if (clength != -1 && length != -1 && clength != length) {
1918		http_seterr(HTTP_PROTOCOL_ERROR);
1919		goto ouch;
1920	}
1921	if (clength == -1)
1922		clength = length;
1923	if (clength != -1)
1924		length = offset + clength;
1925	if (length != -1 && size != -1 && length != size) {
1926		http_seterr(HTTP_PROTOCOL_ERROR);
1927		goto ouch;
1928	}
1929	if (size == -1)
1930		size = length;
1931
1932	/* fill in stats */
1933	if (us) {
1934		us->size = size;
1935		us->atime = us->mtime = mtime;
1936	}
1937
1938	/* too far? */
1939	if (URL->offset > 0 && offset > URL->offset) {
1940		http_seterr(HTTP_PROTOCOL_ERROR);
1941		goto ouch;
1942	}
1943
1944	/* report back real offset and size */
1945	URL->offset = offset;
1946	URL->length = clength;
1947
1948	/* wrap it up in a FILE */
1949	if ((f = http_funopen(conn, chunked)) == NULL) {
1950		fetch_syserr();
1951		goto ouch;
1952	}
1953
1954	if (url != URL)
1955		fetchFreeURL(url);
1956	if (purl)
1957		fetchFreeURL(purl);
1958
1959	if (HTTP_ERROR(conn->err)) {
1960		http_print_html(stderr, f);
1961		fclose(f);
1962		f = NULL;
1963	}
1964	clean_http_headerbuf(&headerbuf);
1965	clean_http_auth_challenges(&server_challenges);
1966	clean_http_auth_challenges(&proxy_challenges);
1967	return (f);
1968
1969ouch:
1970	if (url != URL)
1971		fetchFreeURL(url);
1972	if (purl)
1973		fetchFreeURL(purl);
1974	if (conn != NULL)
1975		fetch_close(conn);
1976	clean_http_headerbuf(&headerbuf);
1977	clean_http_auth_challenges(&server_challenges);
1978	clean_http_auth_challenges(&proxy_challenges);
1979	return (NULL);
1980}
1981
1982
1983/*****************************************************************************
1984 * Entry points
1985 */
1986
1987/*
1988 * Retrieve and stat a file by HTTP
1989 */
1990FILE *
1991fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1992{
1993	return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags));
1994}
1995
1996/*
1997 * Retrieve a file by HTTP
1998 */
1999FILE *
2000fetchGetHTTP(struct url *URL, const char *flags)
2001{
2002	return (fetchXGetHTTP(URL, NULL, flags));
2003}
2004
2005/*
2006 * Store a file by HTTP
2007 */
2008FILE *
2009fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
2010{
2011	warnx("fetchPutHTTP(): not implemented");
2012	return (NULL);
2013}
2014
2015/*
2016 * Get an HTTP document's metadata
2017 */
2018int
2019fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
2020{
2021	FILE *f;
2022
2023	f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags);
2024	if (f == NULL)
2025		return (-1);
2026	fclose(f);
2027	return (0);
2028}
2029
2030/*
2031 * List a directory
2032 */
2033struct url_ent *
2034fetchListHTTP(struct url *url __unused, const char *flags __unused)
2035{
2036	warnx("fetchListHTTP(): not implemented");
2037	return (NULL);
2038}
2039