]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libfetch/http.c
This commit was generated by cvs2svn to compensate for changes in r165743,
[FreeBSD/FreeBSD.git] / lib / libfetch / http.c
1 /*-
2  * Copyright (c) 2000-2004 Dag-Erling Coïdan 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
67 #include <ctype.h>
68 #include <err.h>
69 #include <errno.h>
70 #include <locale.h>
71 #include <netdb.h>
72 #include <stdarg.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <time.h>
77 #include <unistd.h>
78
79 #include <netinet/in.h>
80 #include <netinet/tcp.h>
81
82 #include "fetch.h"
83 #include "common.h"
84 #include "httperr.h"
85
86 /* Maximum number of redirects to follow */
87 #define MAX_REDIRECT 5
88
89 /* Symbolic names for reply codes we care about */
90 #define HTTP_OK                 200
91 #define HTTP_PARTIAL            206
92 #define HTTP_MOVED_PERM         301
93 #define HTTP_MOVED_TEMP         302
94 #define HTTP_SEE_OTHER          303
95 #define HTTP_NEED_AUTH          401
96 #define HTTP_NEED_PROXY_AUTH    407
97 #define HTTP_BAD_RANGE          416
98 #define HTTP_PROTOCOL_ERROR     999
99
100 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
101                             || (xyz) == HTTP_MOVED_TEMP \
102                             || (xyz) == HTTP_SEE_OTHER)
103
104 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
105
106
107 /*****************************************************************************
108  * I/O functions for decoding chunked streams
109  */
110
111 struct httpio
112 {
113         conn_t          *conn;          /* connection */
114         int              chunked;       /* chunked mode */
115         char            *buf;           /* chunk buffer */
116         size_t           bufsize;       /* size of chunk buffer */
117         ssize_t          buflen;        /* amount of data currently in buffer */
118         int              bufpos;        /* current read offset in buffer */
119         int              eof;           /* end-of-file flag */
120         int              error;         /* error flag */
121         size_t           chunksize;     /* remaining size of current chunk */
122 #ifndef NDEBUG
123         size_t           total;
124 #endif
125 };
126
127 /*
128  * Get next chunk header
129  */
130 static int
131 _http_new_chunk(struct httpio *io)
132 {
133         char *p;
134
135         if (_fetch_getln(io->conn) == -1)
136                 return (-1);
137
138         if (io->conn->buflen < 2 || !ishexnumber(*io->conn->buf))
139                 return (-1);
140
141         for (p = io->conn->buf; *p && !isspace(*p); ++p) {
142                 if (*p == ';')
143                         break;
144                 if (!ishexnumber(*p))
145                         return (-1);
146                 if (isdigit(*p)) {
147                         io->chunksize = io->chunksize * 16 +
148                             *p - '0';
149                 } else {
150                         io->chunksize = io->chunksize * 16 +
151                             10 + tolower(*p) - 'a';
152                 }
153         }
154
155 #ifndef NDEBUG
156         if (fetchDebug) {
157                 io->total += io->chunksize;
158                 if (io->chunksize == 0)
159                         fprintf(stderr, "%s(): end of last chunk\n", __func__);
160                 else
161                         fprintf(stderr, "%s(): new chunk: %lu (%lu)\n",
162                             __func__, (unsigned long)io->chunksize,
163                             (unsigned long)io->total);
164         }
165 #endif
166
167         return (io->chunksize);
168 }
169
170 /*
171  * Grow the input buffer to at least len bytes
172  */
173 static inline int
174 _http_growbuf(struct httpio *io, size_t len)
175 {
176         char *tmp;
177
178         if (io->bufsize >= len)
179                 return (0);
180
181         if ((tmp = realloc(io->buf, len)) == NULL)
182                 return (-1);
183         io->buf = tmp;
184         io->bufsize = len;
185         return (0);
186 }
187
188 /*
189  * Fill the input buffer, do chunk decoding on the fly
190  */
191 static int
192 _http_fillbuf(struct httpio *io, size_t len)
193 {
194         if (io->error)
195                 return (-1);
196         if (io->eof)
197                 return (0);
198
199         if (io->chunked == 0) {
200                 if (_http_growbuf(io, len) == -1)
201                         return (-1);
202                 if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) {
203                         io->error = 1;
204                         return (-1);
205                 }
206                 io->bufpos = 0;
207                 return (io->buflen);
208         }
209
210         if (io->chunksize == 0) {
211                 switch (_http_new_chunk(io)) {
212                 case -1:
213                         io->error = 1;
214                         return (-1);
215                 case 0:
216                         io->eof = 1;
217                         return (0);
218                 }
219         }
220
221         if (len > io->chunksize)
222                 len = io->chunksize;
223         if (_http_growbuf(io, len) == -1)
224                 return (-1);
225         if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) {
226                 io->error = 1;
227                 return (-1);
228         }
229         io->chunksize -= io->buflen;
230
231         if (io->chunksize == 0) {
232                 char endl[2];
233
234                 if (_fetch_read(io->conn, endl, 2) != 2 ||
235                     endl[0] != '\r' || endl[1] != '\n')
236                         return (-1);
237         }
238
239         io->bufpos = 0;
240
241         return (io->buflen);
242 }
243
244 /*
245  * Read function
246  */
247 static int
248 _http_readfn(void *v, char *buf, int len)
249 {
250         struct httpio *io = (struct httpio *)v;
251         int l, pos;
252
253         if (io->error)
254                 return (-1);
255         if (io->eof)
256                 return (0);
257
258         for (pos = 0; len > 0; pos += l, len -= l) {
259                 /* empty buffer */
260                 if (!io->buf || io->bufpos == io->buflen)
261                         if (_http_fillbuf(io, len) < 1)
262                                 break;
263                 l = io->buflen - io->bufpos;
264                 if (len < l)
265                         l = len;
266                 bcopy(io->buf + io->bufpos, buf + pos, l);
267                 io->bufpos += l;
268         }
269
270         if (!pos && io->error)
271                 return (-1);
272         return (pos);
273 }
274
275 /*
276  * Write function
277  */
278 static int
279 _http_writefn(void *v, const char *buf, int len)
280 {
281         struct httpio *io = (struct httpio *)v;
282
283         return (_fetch_write(io->conn, buf, len));
284 }
285
286 /*
287  * Close function
288  */
289 static int
290 _http_closefn(void *v)
291 {
292         struct httpio *io = (struct httpio *)v;
293         int r;
294
295         r = _fetch_close(io->conn);
296         if (io->buf)
297                 free(io->buf);
298         free(io);
299         return (r);
300 }
301
302 /*
303  * Wrap a file descriptor up
304  */
305 static FILE *
306 _http_funopen(conn_t *conn, int chunked)
307 {
308         struct httpio *io;
309         FILE *f;
310
311         if ((io = calloc(1, sizeof(*io))) == NULL) {
312                 _fetch_syserr();
313                 return (NULL);
314         }
315         io->conn = conn;
316         io->chunked = chunked;
317         f = funopen(io, _http_readfn, _http_writefn, NULL, _http_closefn);
318         if (f == NULL) {
319                 _fetch_syserr();
320                 free(io);
321                 return (NULL);
322         }
323         return (f);
324 }
325
326
327 /*****************************************************************************
328  * Helper functions for talking to the server and parsing its replies
329  */
330
331 /* Header types */
332 typedef enum {
333         hdr_syserror = -2,
334         hdr_error = -1,
335         hdr_end = 0,
336         hdr_unknown = 1,
337         hdr_content_length,
338         hdr_content_range,
339         hdr_last_modified,
340         hdr_location,
341         hdr_transfer_encoding,
342         hdr_www_authenticate
343 } hdr_t;
344
345 /* Names of interesting headers */
346 static struct {
347         hdr_t            num;
348         const char      *name;
349 } hdr_names[] = {
350         { hdr_content_length,           "Content-Length" },
351         { hdr_content_range,            "Content-Range" },
352         { hdr_last_modified,            "Last-Modified" },
353         { hdr_location,                 "Location" },
354         { hdr_transfer_encoding,        "Transfer-Encoding" },
355         { hdr_www_authenticate,         "WWW-Authenticate" },
356         { hdr_unknown,                  NULL },
357 };
358
359 /*
360  * Send a formatted line; optionally echo to terminal
361  */
362 static int
363 _http_cmd(conn_t *conn, const char *fmt, ...)
364 {
365         va_list ap;
366         size_t len;
367         char *msg;
368         int r;
369
370         va_start(ap, fmt);
371         len = vasprintf(&msg, fmt, ap);
372         va_end(ap);
373
374         if (msg == NULL) {
375                 errno = ENOMEM;
376                 _fetch_syserr();
377                 return (-1);
378         }
379
380         r = _fetch_putln(conn, msg, len);
381         free(msg);
382
383         if (r == -1) {
384                 _fetch_syserr();
385                 return (-1);
386         }
387
388         return (0);
389 }
390
391 /*
392  * Get and parse status line
393  */
394 static int
395 _http_get_reply(conn_t *conn)
396 {
397         char *p;
398
399         if (_fetch_getln(conn) == -1)
400                 return (-1);
401         /*
402          * A valid status line looks like "HTTP/m.n xyz reason" where m
403          * and n are the major and minor protocol version numbers and xyz
404          * is the reply code.
405          * Unfortunately, there are servers out there (NCSA 1.5.1, to name
406          * just one) that do not send a version number, so we can't rely
407          * on finding one, but if we do, insist on it being 1.0 or 1.1.
408          * We don't care about the reason phrase.
409          */
410         if (strncmp(conn->buf, "HTTP", 4) != 0)
411                 return (HTTP_PROTOCOL_ERROR);
412         p = conn->buf + 4;
413         if (*p == '/') {
414                 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1'))
415                         return (HTTP_PROTOCOL_ERROR);
416                 p += 4;
417         }
418         if (*p != ' ' || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3]))
419                 return (HTTP_PROTOCOL_ERROR);
420
421         conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');
422         return (conn->err);
423 }
424
425 /*
426  * Check a header; if the type matches the given string, return a pointer
427  * to the beginning of the value.
428  */
429 static const char *
430 _http_match(const char *str, const char *hdr)
431 {
432         while (*str && *hdr && tolower(*str++) == tolower(*hdr++))
433                 /* nothing */;
434         if (*str || *hdr != ':')
435                 return (NULL);
436         while (*hdr && isspace(*++hdr))
437                 /* nothing */;
438         return (hdr);
439 }
440
441 /*
442  * Get the next header and return the appropriate symbolic code.
443  */
444 static hdr_t
445 _http_next_header(conn_t *conn, const char **p)
446 {
447         int i;
448
449         if (_fetch_getln(conn) == -1)
450                 return (hdr_syserror);
451         while (conn->buflen && isspace(conn->buf[conn->buflen - 1]))
452                 conn->buflen--;
453         conn->buf[conn->buflen] = '\0';
454         if (conn->buflen == 0)
455                 return (hdr_end);
456         /*
457          * We could check for malformed headers but we don't really care.
458          * A valid header starts with a token immediately followed by a
459          * colon; a token is any sequence of non-control, non-whitespace
460          * characters except "()<>@,;:\\\"{}".
461          */
462         for (i = 0; hdr_names[i].num != hdr_unknown; i++)
463                 if ((*p = _http_match(hdr_names[i].name, conn->buf)) != NULL)
464                         return (hdr_names[i].num);
465         return (hdr_unknown);
466 }
467
468 /*
469  * Parse a last-modified header
470  */
471 static int
472 _http_parse_mtime(const char *p, time_t *mtime)
473 {
474         char locale[64], *r;
475         struct tm tm;
476
477         strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale));
478         setlocale(LC_TIME, "C");
479         r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm);
480         /* XXX should add support for date-2 and date-3 */
481         setlocale(LC_TIME, locale);
482         if (r == NULL)
483                 return (-1);
484         DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d "
485                   "%02d:%02d:%02d]\n",
486                   tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
487                   tm.tm_hour, tm.tm_min, tm.tm_sec));
488         *mtime = timegm(&tm);
489         return (0);
490 }
491
492 /*
493  * Parse a content-length header
494  */
495 static int
496 _http_parse_length(const char *p, off_t *length)
497 {
498         off_t len;
499
500         for (len = 0; *p && isdigit(*p); ++p)
501                 len = len * 10 + (*p - '0');
502         if (*p)
503                 return (-1);
504         DEBUG(fprintf(stderr, "content length: [%lld]\n",
505             (long long)len));
506         *length = len;
507         return (0);
508 }
509
510 /*
511  * Parse a content-range header
512  */
513 static int
514 _http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size)
515 {
516         off_t first, last, len;
517
518         if (strncasecmp(p, "bytes ", 6) != 0)
519                 return (-1);
520         p += 6;
521         if (*p == '*') {
522                 first = last = -1;
523                 ++p;
524         } else {
525                 for (first = 0; *p && isdigit(*p); ++p)
526                         first = first * 10 + *p - '0';
527                 if (*p != '-')
528                         return (-1);
529                 for (last = 0, ++p; *p && isdigit(*p); ++p)
530                         last = last * 10 + *p - '0';
531         }
532         if (first > last || *p != '/')
533                 return (-1);
534         for (len = 0, ++p; *p && isdigit(*p); ++p)
535                 len = len * 10 + *p - '0';
536         if (*p || len < last - first + 1)
537                 return (-1);
538         if (first == -1) {
539                 DEBUG(fprintf(stderr, "content range: [*/%lld]\n",
540                     (long long)len));
541                 *length = 0;
542         } else {
543                 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n",
544                     (long long)first, (long long)last, (long long)len));
545                 *length = last - first + 1;
546         }
547         *offset = first;
548         *size = len;
549         return (0);
550 }
551
552
553 /*****************************************************************************
554  * Helper functions for authorization
555  */
556
557 /*
558  * Base64 encoding
559  */
560 static char *
561 _http_base64(const char *src)
562 {
563         static const char base64[] =
564             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
565             "abcdefghijklmnopqrstuvwxyz"
566             "0123456789+/";
567         char *str, *dst;
568         size_t l;
569         int t, r;
570
571         l = strlen(src);
572         if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
573                 return (NULL);
574         dst = str;
575         r = 0;
576
577         while (l >= 3) {
578                 t = (src[0] << 16) | (src[1] << 8) | src[2];
579                 dst[0] = base64[(t >> 18) & 0x3f];
580                 dst[1] = base64[(t >> 12) & 0x3f];
581                 dst[2] = base64[(t >> 6) & 0x3f];
582                 dst[3] = base64[(t >> 0) & 0x3f];
583                 src += 3; l -= 3;
584                 dst += 4; r += 4;
585         }
586
587         switch (l) {
588         case 2:
589                 t = (src[0] << 16) | (src[1] << 8);
590                 dst[0] = base64[(t >> 18) & 0x3f];
591                 dst[1] = base64[(t >> 12) & 0x3f];
592                 dst[2] = base64[(t >> 6) & 0x3f];
593                 dst[3] = '=';
594                 dst += 4;
595                 r += 4;
596                 break;
597         case 1:
598                 t = src[0] << 16;
599                 dst[0] = base64[(t >> 18) & 0x3f];
600                 dst[1] = base64[(t >> 12) & 0x3f];
601                 dst[2] = dst[3] = '=';
602                 dst += 4;
603                 r += 4;
604                 break;
605         case 0:
606                 break;
607         }
608
609         *dst = 0;
610         return (str);
611 }
612
613 /*
614  * Encode username and password
615  */
616 static int
617 _http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd)
618 {
619         char *upw, *auth;
620         int r;
621
622         DEBUG(fprintf(stderr, "usr: [%s]\n", usr));
623         DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
624         if (asprintf(&upw, "%s:%s", usr, pwd) == -1)
625                 return (-1);
626         auth = _http_base64(upw);
627         free(upw);
628         if (auth == NULL)
629                 return (-1);
630         r = _http_cmd(conn, "%s: Basic %s", hdr, auth);
631         free(auth);
632         return (r);
633 }
634
635 /*
636  * Send an authorization header
637  */
638 static int
639 _http_authorize(conn_t *conn, const char *hdr, const char *p)
640 {
641         /* basic authorization */
642         if (strncasecmp(p, "basic:", 6) == 0) {
643                 char *user, *pwd, *str;
644                 int r;
645
646                 /* skip realm */
647                 for (p += 6; *p && *p != ':'; ++p)
648                         /* nothing */ ;
649                 if (!*p || strchr(++p, ':') == NULL)
650                         return (-1);
651                 if ((str = strdup(p)) == NULL)
652                         return (-1); /* XXX */
653                 user = str;
654                 pwd = strchr(str, ':');
655                 *pwd++ = '\0';
656                 r = _http_basic_auth(conn, hdr, user, pwd);
657                 free(str);
658                 return (r);
659         }
660         return (-1);
661 }
662
663
664 /*****************************************************************************
665  * Helper functions for connecting to a server or proxy
666  */
667
668 /*
669  * Connect to the correct HTTP server or proxy.
670  */
671 static conn_t *
672 _http_connect(struct url *URL, struct url *purl, const char *flags)
673 {
674         conn_t *conn;
675         int verbose;
676         int af, val;
677
678 #ifdef INET6
679         af = AF_UNSPEC;
680 #else
681         af = AF_INET;
682 #endif
683
684         verbose = CHECK_FLAG('v');
685         if (CHECK_FLAG('4'))
686                 af = AF_INET;
687 #ifdef INET6
688         else if (CHECK_FLAG('6'))
689                 af = AF_INET6;
690 #endif
691
692         if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) {
693                 URL = purl;
694         } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) {
695                 /* can't talk http to an ftp server */
696                 /* XXX should set an error code */
697                 return (NULL);
698         }
699
700         if ((conn = _fetch_connect(URL->host, URL->port, af, verbose)) == NULL)
701                 /* _fetch_connect() has already set an error code */
702                 return (NULL);
703         if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 &&
704             _fetch_ssl(conn, verbose) == -1) {
705                 _fetch_close(conn);
706                 /* grrr */
707                 errno = EAUTH;
708                 _fetch_syserr();
709                 return (NULL);
710         }
711
712         val = 1;
713         setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val));
714
715         return (conn);
716 }
717
718 static struct url *
719 _http_get_proxy(const char *flags)
720 {
721         struct url *purl;
722         char *p;
723
724         if (flags != NULL && strchr(flags, 'd') != NULL)
725                 return (NULL);
726         if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
727             *p && (purl = fetchParseURL(p))) {
728                 if (!*purl->scheme)
729                         strcpy(purl->scheme, SCHEME_HTTP);
730                 if (!purl->port)
731                         purl->port = _fetch_default_proxy_port(purl->scheme);
732                 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
733                         return (purl);
734                 fetchFreeURL(purl);
735         }
736         return (NULL);
737 }
738
739 static void
740 _http_print_html(FILE *out, FILE *in)
741 {
742         size_t len;
743         char *line, *p, *q;
744         int comment, tag;
745
746         comment = tag = 0;
747         while ((line = fgetln(in, &len)) != NULL) {
748                 while (len && isspace(line[len - 1]))
749                         --len;
750                 for (p = q = line; q < line + len; ++q) {
751                         if (comment && *q == '-') {
752                                 if (q + 2 < line + len &&
753                                     strcmp(q, "-->") == 0) {
754                                         tag = comment = 0;
755                                         q += 2;
756                                 }
757                         } else if (tag && !comment && *q == '>') {
758                                 p = q + 1;
759                                 tag = 0;
760                         } else if (!tag && *q == '<') {
761                                 if (q > p)
762                                         fwrite(p, q - p, 1, out);
763                                 tag = 1;
764                                 if (q + 3 < line + len &&
765                                     strcmp(q, "<!--") == 0) {
766                                         comment = 1;
767                                         q += 3;
768                                 }
769                         }
770                 }
771                 if (!tag && q > p)
772                         fwrite(p, q - p, 1, out);
773                 fputc('\n', out);
774         }
775 }
776
777
778 /*****************************************************************************
779  * Core
780  */
781
782 /*
783  * Send a request and process the reply
784  *
785  * XXX This function is way too long, the do..while loop should be split
786  * XXX off into a separate function.
787  */
788 FILE *
789 _http_request(struct url *URL, const char *op, struct url_stat *us,
790     struct url *purl, const char *flags)
791 {
792         conn_t *conn;
793         struct url *url, *new;
794         int chunked, direct, need_auth, noredirect, verbose;
795         int e, i, n, val;
796         off_t offset, clength, length, size;
797         time_t mtime;
798         const char *p;
799         FILE *f;
800         hdr_t h;
801         char hbuf[MAXHOSTNAMELEN + 7], *host;
802
803         direct = CHECK_FLAG('d');
804         noredirect = CHECK_FLAG('A');
805         verbose = CHECK_FLAG('v');
806
807         if (direct && purl) {
808                 fetchFreeURL(purl);
809                 purl = NULL;
810         }
811
812         /* try the provided URL first */
813         url = URL;
814
815         /* if the A flag is set, we only get one try */
816         n = noredirect ? 1 : MAX_REDIRECT;
817         i = 0;
818
819         e = HTTP_PROTOCOL_ERROR;
820         need_auth = 0;
821         do {
822                 new = NULL;
823                 chunked = 0;
824                 offset = 0;
825                 clength = -1;
826                 length = -1;
827                 size = -1;
828                 mtime = 0;
829
830                 /* check port */
831                 if (!url->port)
832                         url->port = _fetch_default_port(url->scheme);
833
834                 /* were we redirected to an FTP URL? */
835                 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) {
836                         if (strcmp(op, "GET") == 0)
837                                 return (_ftp_request(url, "RETR", us, purl, flags));
838                         else if (strcmp(op, "HEAD") == 0)
839                                 return (_ftp_request(url, "STAT", us, purl, flags));
840                 }
841
842                 /* connect to server or proxy */
843                 if ((conn = _http_connect(url, purl, flags)) == NULL)
844                         goto ouch;
845
846                 host = url->host;
847 #ifdef INET6
848                 if (strchr(url->host, ':')) {
849                         snprintf(hbuf, sizeof(hbuf), "[%s]", url->host);
850                         host = hbuf;
851                 }
852 #endif
853                 if (url->port != _fetch_default_port(url->scheme)) {
854                         if (host != hbuf) {
855                                 strcpy(hbuf, host);
856                                 host = hbuf;
857                         }
858                         snprintf(hbuf + strlen(hbuf),
859                             sizeof(hbuf) - strlen(hbuf), ":%d", url->port);
860                 }
861
862                 /* send request */
863                 if (verbose)
864                         _fetch_info("requesting %s://%s%s",
865                             url->scheme, host, url->doc);
866                 if (purl) {
867                         _http_cmd(conn, "%s %s://%s%s HTTP/1.1",
868                             op, url->scheme, host, url->doc);
869                 } else {
870                         _http_cmd(conn, "%s %s HTTP/1.1",
871                             op, url->doc);
872                 }
873
874                 /* virtual host */
875                 _http_cmd(conn, "Host: %s", host);
876
877                 /* proxy authorization */
878                 if (purl) {
879                         if (*purl->user || *purl->pwd)
880                                 _http_basic_auth(conn, "Proxy-Authorization",
881                                     purl->user, purl->pwd);
882                         else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0')
883                                 _http_authorize(conn, "Proxy-Authorization", p);
884                 }
885
886                 /* server authorization */
887                 if (need_auth || *url->user || *url->pwd) {
888                         if (*url->user || *url->pwd)
889                                 _http_basic_auth(conn, "Authorization", url->user, url->pwd);
890                         else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0')
891                                 _http_authorize(conn, "Authorization", p);
892                         else if (fetchAuthMethod && fetchAuthMethod(url) == 0) {
893                                 _http_basic_auth(conn, "Authorization", url->user, url->pwd);
894                         } else {
895                                 _http_seterr(HTTP_NEED_AUTH);
896                                 goto ouch;
897                         }
898                 }
899
900                 /* other headers */
901                 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') {
902                         if (strcasecmp(p, "auto") == 0)
903                                 _http_cmd(conn, "Referer: %s://%s%s",
904                                     url->scheme, host, url->doc);
905                         else
906                                 _http_cmd(conn, "Referer: %s", p);
907                 }
908                 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0')
909                         _http_cmd(conn, "User-Agent: %s", p);
910                 else
911                         _http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname());
912                 if (url->offset > 0)
913                         _http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset);
914                 _http_cmd(conn, "Connection: close");
915                 _http_cmd(conn, "");
916
917                 /*
918                  * Force the queued request to be dispatched.  Normally, one
919                  * would do this with shutdown(2) but squid proxies can be
920                  * configured to disallow such half-closed connections.  To
921                  * be compatible with such configurations, fiddle with socket
922                  * options to force the pending data to be written.
923                  */
924                 val = 0;
925                 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val,
926                            sizeof(val));
927                 val = 1;
928                 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val,
929                            sizeof(val));
930
931                 /* get reply */
932                 switch (_http_get_reply(conn)) {
933                 case HTTP_OK:
934                 case HTTP_PARTIAL:
935                         /* fine */
936                         break;
937                 case HTTP_MOVED_PERM:
938                 case HTTP_MOVED_TEMP:
939                 case HTTP_SEE_OTHER:
940                         /*
941                          * Not so fine, but we still have to read the
942                          * headers to get the new location.
943                          */
944                         break;
945                 case HTTP_NEED_AUTH:
946                         if (need_auth) {
947                                 /*
948                                  * We already sent out authorization code,
949                                  * so there's nothing more we can do.
950                                  */
951                                 _http_seterr(conn->err);
952                                 goto ouch;
953                         }
954                         /* try again, but send the password this time */
955                         if (verbose)
956                                 _fetch_info("server requires authorization");
957                         break;
958                 case HTTP_NEED_PROXY_AUTH:
959                         /*
960                          * If we're talking to a proxy, we already sent
961                          * our proxy authorization code, so there's
962                          * nothing more we can do.
963                          */
964                         _http_seterr(conn->err);
965                         goto ouch;
966                 case HTTP_BAD_RANGE:
967                         /*
968                          * This can happen if we ask for 0 bytes because
969                          * we already have the whole file.  Consider this
970                          * a success for now, and check sizes later.
971                          */
972                         break;
973                 case HTTP_PROTOCOL_ERROR:
974                         /* fall through */
975                 case -1:
976                         _fetch_syserr();
977                         goto ouch;
978                 default:
979                         _http_seterr(conn->err);
980                         if (!verbose)
981                                 goto ouch;
982                         /* fall through so we can get the full error message */
983                 }
984
985                 /* get headers */
986                 do {
987                         switch ((h = _http_next_header(conn, &p))) {
988                         case hdr_syserror:
989                                 _fetch_syserr();
990                                 goto ouch;
991                         case hdr_error:
992                                 _http_seterr(HTTP_PROTOCOL_ERROR);
993                                 goto ouch;
994                         case hdr_content_length:
995                                 _http_parse_length(p, &clength);
996                                 break;
997                         case hdr_content_range:
998                                 _http_parse_range(p, &offset, &length, &size);
999                                 break;
1000                         case hdr_last_modified:
1001                                 _http_parse_mtime(p, &mtime);
1002                                 break;
1003                         case hdr_location:
1004                                 if (!HTTP_REDIRECT(conn->err))
1005                                         break;
1006                                 if (new)
1007                                         free(new);
1008                                 if (verbose)
1009                                         _fetch_info("%d redirect to %s", conn->err, p);
1010                                 if (*p == '/')
1011                                         /* absolute path */
1012                                         new = fetchMakeURL(url->scheme, url->host, url->port, p,
1013                                             url->user, url->pwd);
1014                                 else
1015                                         new = fetchParseURL(p);
1016                                 if (new == NULL) {
1017                                         /* XXX should set an error code */
1018                                         DEBUG(fprintf(stderr, "failed to parse new URL\n"));
1019                                         goto ouch;
1020                                 }
1021                                 if (!*new->user && !*new->pwd) {
1022                                         strcpy(new->user, url->user);
1023                                         strcpy(new->pwd, url->pwd);
1024                                 }
1025                                 new->offset = url->offset;
1026                                 new->length = url->length;
1027                                 break;
1028                         case hdr_transfer_encoding:
1029                                 /* XXX weak test*/
1030                                 chunked = (strcasecmp(p, "chunked") == 0);
1031                                 break;
1032                         case hdr_www_authenticate:
1033                                 if (conn->err != HTTP_NEED_AUTH)
1034                                         break;
1035                                 /* if we were smarter, we'd check the method and realm */
1036                                 break;
1037                         case hdr_end:
1038                                 /* fall through */
1039                         case hdr_unknown:
1040                                 /* ignore */
1041                                 break;
1042                         }
1043                 } while (h > hdr_end);
1044
1045                 /* we need to provide authentication */
1046                 if (conn->err == HTTP_NEED_AUTH) {
1047                         e = conn->err;
1048                         need_auth = 1;
1049                         _fetch_close(conn);
1050                         conn = NULL;
1051                         continue;
1052                 }
1053
1054                 /* requested range not satisfiable */
1055                 if (conn->err == HTTP_BAD_RANGE) {
1056                         if (url->offset == size && url->length == 0) {
1057                                 /* asked for 0 bytes; fake it */
1058                                 offset = url->offset;
1059                                 conn->err = HTTP_OK;
1060                                 break;
1061                         } else {
1062                                 _http_seterr(conn->err);
1063                                 goto ouch;
1064                         }
1065                 }
1066
1067                 /* we have a hit or an error */
1068                 if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err))
1069                         break;
1070
1071                 /* all other cases: we got a redirect */
1072                 e = conn->err;
1073                 need_auth = 0;
1074                 _fetch_close(conn);
1075                 conn = NULL;
1076                 if (!new) {
1077                         DEBUG(fprintf(stderr, "redirect with no new location\n"));
1078                         break;
1079                 }
1080                 if (url != URL)
1081                         fetchFreeURL(url);
1082                 url = new;
1083         } while (++i < n);
1084
1085         /* we failed, or ran out of retries */
1086         if (conn == NULL) {
1087                 _http_seterr(e);
1088                 goto ouch;
1089         }
1090
1091         DEBUG(fprintf(stderr, "offset %lld, length %lld,"
1092                   " size %lld, clength %lld\n",
1093                   (long long)offset, (long long)length,
1094                   (long long)size, (long long)clength));
1095
1096         /* check for inconsistencies */
1097         if (clength != -1 && length != -1 && clength != length) {
1098                 _http_seterr(HTTP_PROTOCOL_ERROR);
1099                 goto ouch;
1100         }
1101         if (clength == -1)
1102                 clength = length;
1103         if (clength != -1)
1104                 length = offset + clength;
1105         if (length != -1 && size != -1 && length != size) {
1106                 _http_seterr(HTTP_PROTOCOL_ERROR);
1107                 goto ouch;
1108         }
1109         if (size == -1)
1110                 size = length;
1111
1112         /* fill in stats */
1113         if (us) {
1114                 us->size = size;
1115                 us->atime = us->mtime = mtime;
1116         }
1117
1118         /* too far? */
1119         if (URL->offset > 0 && offset > URL->offset) {
1120                 _http_seterr(HTTP_PROTOCOL_ERROR);
1121                 goto ouch;
1122         }
1123
1124         /* report back real offset and size */
1125         URL->offset = offset;
1126         URL->length = clength;
1127
1128         /* wrap it up in a FILE */
1129         if ((f = _http_funopen(conn, chunked)) == NULL) {
1130                 _fetch_syserr();
1131                 goto ouch;
1132         }
1133
1134         if (url != URL)
1135                 fetchFreeURL(url);
1136         if (purl)
1137                 fetchFreeURL(purl);
1138
1139         if (HTTP_ERROR(conn->err)) {
1140                 _http_print_html(stderr, f);
1141                 fclose(f);
1142                 f = NULL;
1143         }
1144
1145         return (f);
1146
1147 ouch:
1148         if (url != URL)
1149                 fetchFreeURL(url);
1150         if (purl)
1151                 fetchFreeURL(purl);
1152         if (conn != NULL)
1153                 _fetch_close(conn);
1154         return (NULL);
1155 }
1156
1157
1158 /*****************************************************************************
1159  * Entry points
1160  */
1161
1162 /*
1163  * Retrieve and stat a file by HTTP
1164  */
1165 FILE *
1166 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags)
1167 {
1168         return (_http_request(URL, "GET", us, _http_get_proxy(flags), flags));
1169 }
1170
1171 /*
1172  * Retrieve a file by HTTP
1173  */
1174 FILE *
1175 fetchGetHTTP(struct url *URL, const char *flags)
1176 {
1177         return (fetchXGetHTTP(URL, NULL, flags));
1178 }
1179
1180 /*
1181  * Store a file by HTTP
1182  */
1183 FILE *
1184 fetchPutHTTP(struct url *URL __unused, const char *flags __unused)
1185 {
1186         warnx("fetchPutHTTP(): not implemented");
1187         return (NULL);
1188 }
1189
1190 /*
1191  * Get an HTTP document's metadata
1192  */
1193 int
1194 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags)
1195 {
1196         FILE *f;
1197
1198         f = _http_request(URL, "HEAD", us, _http_get_proxy(flags), flags);
1199         if (f == NULL)
1200                 return (-1);
1201         fclose(f);
1202         return (0);
1203 }
1204
1205 /*
1206  * List a directory
1207  */
1208 struct url_ent *
1209 fetchListHTTP(struct url *url __unused, const char *flags __unused)
1210 {
1211         warnx("fetchListHTTP(): not implemented");
1212         return (NULL);
1213 }