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