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