]> sjero.net Git - wget/blob - src/http.c
[svn] Fix escape chars in server response vulnerability. Server response is
[wget] / src / http.c
1 /* HTTP support.
2    Copyright (C) 2003 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables.  You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL".  If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so.  If you do not wish to do
28 so, delete this exception statement from your version.  */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <sys/types.h>
35 #ifdef HAVE_STRING_H
36 # include <string.h>
37 #else
38 # include <strings.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43 #include <assert.h>
44 #include <errno.h>
45 #if TIME_WITH_SYS_TIME
46 # include <sys/time.h>
47 # include <time.h>
48 #else
49 # if HAVE_SYS_TIME_H
50 #  include <sys/time.h>
51 # else
52 #  include <time.h>
53 # endif
54 #endif
55 #ifndef errno
56 extern int errno;
57 #endif
58
59 #include "wget.h"
60 #include "utils.h"
61 #include "url.h"
62 #include "host.h"
63 #include "retr.h"
64 #include "connect.h"
65 #include "netrc.h"
66 #ifdef HAVE_SSL
67 # include "gen_sslfunc.h"
68 #endif /* HAVE_SSL */
69 #include "cookies.h"
70 #ifdef USE_DIGEST
71 # include "gen-md5.h"
72 #endif
73 #include "convert.h"
74
75 extern char *version_string;
76 extern LARGE_INT total_downloaded_bytes;
77
78 extern FILE *output_stream;
79 extern int output_stream_regular;
80
81 #ifndef MIN
82 # define MIN(x, y) ((x) > (y) ? (y) : (x))
83 #endif
84
85 \f
86 static int cookies_loaded_p;
87 struct cookie_jar *wget_cookie_jar;
88
89 #define TEXTHTML_S "text/html"
90 #define TEXTXHTML_S "application/xhtml+xml"
91
92 /* Some status code validation macros: */
93 #define H_20X(x)        (((x) >= 200) && ((x) < 300))
94 #define H_PARTIAL(x)    ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
95 #define H_REDIRECTED(x) ((x) == HTTP_STATUS_MOVED_PERMANENTLY           \
96                          || (x) == HTTP_STATUS_MOVED_TEMPORARILY        \
97                          || (x) == HTTP_STATUS_SEE_OTHER                \
98                          || (x) == HTTP_STATUS_TEMPORARY_REDIRECT)
99
100 /* HTTP/1.0 status codes from RFC1945, provided for reference.  */
101 /* Successful 2xx.  */
102 #define HTTP_STATUS_OK                  200
103 #define HTTP_STATUS_CREATED             201
104 #define HTTP_STATUS_ACCEPTED            202
105 #define HTTP_STATUS_NO_CONTENT          204
106 #define HTTP_STATUS_PARTIAL_CONTENTS    206
107
108 /* Redirection 3xx.  */
109 #define HTTP_STATUS_MULTIPLE_CHOICES    300
110 #define HTTP_STATUS_MOVED_PERMANENTLY   301
111 #define HTTP_STATUS_MOVED_TEMPORARILY   302
112 #define HTTP_STATUS_SEE_OTHER           303 /* from HTTP/1.1 */
113 #define HTTP_STATUS_NOT_MODIFIED        304
114 #define HTTP_STATUS_TEMPORARY_REDIRECT  307 /* from HTTP/1.1 */
115
116 /* Client error 4xx.  */
117 #define HTTP_STATUS_BAD_REQUEST         400
118 #define HTTP_STATUS_UNAUTHORIZED        401
119 #define HTTP_STATUS_FORBIDDEN           403
120 #define HTTP_STATUS_NOT_FOUND           404
121 #define HTTP_STATUS_RANGE_NOT_SATISFIABLE 416
122
123 /* Server errors 5xx.  */
124 #define HTTP_STATUS_INTERNAL            500
125 #define HTTP_STATUS_NOT_IMPLEMENTED     501
126 #define HTTP_STATUS_BAD_GATEWAY         502
127 #define HTTP_STATUS_UNAVAILABLE         503
128 \f
129 enum rp {
130   rel_none, rel_name, rel_value, rel_both
131 };
132
133 struct request {
134   const char *method;
135   char *arg;
136
137   struct request_header {
138     char *name, *value;
139     enum rp release_policy;
140   } *headers;
141   int hcount, hcapacity;
142 };
143
144 /* Create a new, empty request.  At least request_set_method must be
145    called before the request can be used.  */
146
147 static struct request *
148 request_new ()
149 {
150   struct request *req = xnew0 (struct request);
151   req->hcapacity = 8;
152   req->headers = xnew_array (struct request_header, req->hcapacity);
153   return req;
154 }
155
156 /* Set the request's method and its arguments.  METH should be a
157    literal string (or it should outlive the request) because it will
158    not be freed.  ARG will be freed by request_free.  */
159
160 static void
161 request_set_method (struct request *req, const char *meth, char *arg)
162 {
163   req->method = meth;
164   req->arg = arg;
165 }
166
167 /* Return the method string passed with the last call to
168    request_set_method.  */
169
170 static const char *
171 request_method (const struct request *req)
172 {
173   return req->method;
174 }
175
176 /* Free one header according to the release policy specified with
177    request_set_header.  */
178
179 static void
180 release_header (struct request_header *hdr)
181 {
182   switch (hdr->release_policy)
183     {
184     case rel_none:
185       break;
186     case rel_name:
187       xfree (hdr->name);
188       break;
189     case rel_value:
190       xfree (hdr->value);
191       break;
192     case rel_both:
193       xfree (hdr->name);
194       xfree (hdr->value);
195       break;
196     }
197 }
198
199 /* Set the request named NAME to VALUE.  Specifically, this means that
200    a "NAME: VALUE\r\n" header line will be used in the request.  If a
201    header with the same name previously existed in the request, its
202    value will be replaced by this one.
203
204    RELEASE_POLICY determines whether NAME and VALUE should be released
205    (freed) with request_free.  Allowed values are:
206
207     - rel_none     - don't free NAME or VALUE
208     - rel_name     - free NAME when done
209     - rel_value    - free VALUE when done
210     - rel_both     - free both NAME and VALUE when done
211
212    Setting release policy is useful when arguments come from different
213    sources.  For example:
214
215      // Don't free literal strings!
216      request_set_header (req, "Pragma", "no-cache", rel_none);
217
218      // Don't free a global variable, we'll need it later.
219      request_set_header (req, "Referer", opt.referer, rel_none);
220
221      // Value freshly allocated, free it when done.
222      request_set_header (req, "Range",
223                          aprintf ("bytes=%s-", number_to_static_string (hs->restval)),
224                          rel_value);
225    */
226
227 static void
228 request_set_header (struct request *req, char *name, char *value,
229                     enum rp release_policy)
230 {
231   struct request_header *hdr;
232   int i;
233   if (!value)
234     return;
235   for (i = 0; i < req->hcount; i++)
236     {
237       hdr = &req->headers[i];
238       if (0 == strcasecmp (name, hdr->name))
239         {
240           /* Replace existing header. */
241           release_header (hdr);
242           hdr->name = name;
243           hdr->value = value;
244           hdr->release_policy = release_policy;
245           return;
246         }
247     }
248
249   /* Install new header. */
250
251   if (req->hcount >= req->hcount)
252     {
253       req->hcapacity <<= 1;
254       req->headers = xrealloc (req->headers,
255                                req->hcapacity * sizeof (struct request_header));
256     }
257   hdr = &req->headers[req->hcount++];
258   hdr->name = name;
259   hdr->value = value;
260   hdr->release_policy = release_policy;
261 }
262
263 /* Like request_set_header, but sets the whole header line, as
264    provided by the user using the `--header' option.  For example,
265    request_set_user_header (req, "Foo: bar") works just like
266    request_set_header (req, "Foo", "bar").  */
267
268 static void
269 request_set_user_header (struct request *req, const char *header)
270 {
271   char *name;
272   const char *p = strchr (header, ':');
273   if (!p)
274     return;
275   BOUNDED_TO_ALLOCA (header, p, name);
276   ++p;
277   while (ISSPACE (*p))
278     ++p;
279   request_set_header (req, xstrdup (name), (char *) p, rel_name);
280 }
281
282 #define APPEND(p, str) do {                     \
283   int A_len = strlen (str);                     \
284   memcpy (p, str, A_len);                       \
285   p += A_len;                                   \
286 } while (0)
287
288 /* Construct the request and write it to FD using fd_write.  */
289
290 static int
291 request_send (const struct request *req, int fd)
292 {
293   char *request_string, *p;
294   int i, size, write_error;
295
296   /* Count the request size. */
297   size = 0;
298
299   /* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
300   size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
301
302   for (i = 0; i < req->hcount; i++)
303     {
304       struct request_header *hdr = &req->headers[i];
305       /* NAME ": " VALUE "\r\n" */
306       size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
307     }
308
309   /* "\r\n\0" */
310   size += 3;
311
312   p = request_string = alloca_array (char, size);
313
314   /* Generate the request. */
315
316   APPEND (p, req->method); *p++ = ' ';
317   APPEND (p, req->arg);    *p++ = ' ';
318   memcpy (p, "HTTP/1.0\r\n", 10); p += 10;
319
320   for (i = 0; i < req->hcount; i++)
321     {
322       struct request_header *hdr = &req->headers[i];
323       APPEND (p, hdr->name);
324       *p++ = ':', *p++ = ' ';
325       APPEND (p, hdr->value);
326       *p++ = '\r', *p++ = '\n';
327     }
328
329   *p++ = '\r', *p++ = '\n', *p++ = '\0';
330   assert (p - request_string == size);
331
332 #undef APPEND
333
334   DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
335
336   /* Send the request to the server. */
337
338   write_error = fd_write (fd, request_string, size - 1, -1);
339   if (write_error < 0)
340     logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
341                strerror (errno));
342   return write_error;
343 }
344
345 /* Release the resources used by REQ. */
346
347 static void
348 request_free (struct request *req)
349 {
350   int i;
351   xfree_null (req->arg);
352   for (i = 0; i < req->hcount; i++)
353     release_header (&req->headers[i]);
354   xfree_null (req->headers);
355   xfree (req);
356 }
357
358 /* Send the contents of FILE_NAME to SOCK/SSL.  Make sure that exactly
359    PROMISED_SIZE bytes are sent over the wire -- if the file is
360    longer, read only that much; if the file is shorter, report an error.  */
361
362 static int
363 post_file (int sock, const char *file_name, wgint promised_size)
364 {
365   static char chunk[8192];
366   wgint written = 0;
367   int write_error;
368   FILE *fp;
369
370   DEBUGP (("[writing POST file %s ... ", file_name));
371
372   fp = fopen (file_name, "rb");
373   if (!fp)
374     return -1;
375   while (!feof (fp) && written < promised_size)
376     {
377       int towrite;
378       int length = fread (chunk, 1, sizeof (chunk), fp);
379       if (length == 0)
380         break;
381       towrite = MIN (promised_size - written, length);
382       write_error = fd_write (sock, chunk, towrite, -1);
383       if (write_error < 0)
384         {
385           fclose (fp);
386           return -1;
387         }
388       written += towrite;
389     }
390   fclose (fp);
391
392   /* If we've written less than was promised, report a (probably
393      nonsensical) error rather than break the promise.  */
394   if (written < promised_size)
395     {
396       errno = EINVAL;
397       return -1;
398     }
399
400   assert (written == promised_size);
401   DEBUGP (("done]\n"));
402   return 0;
403 }
404 \f
405 static const char *
406 head_terminator (const char *hunk, int oldlen, int peeklen)
407 {
408   const char *start, *end;
409
410   /* If at first peek, verify whether HUNK starts with "HTTP".  If
411      not, this is a HTTP/0.9 request and we must bail out without
412      reading anything.  */
413   if (oldlen == 0 && 0 != memcmp (hunk, "HTTP", MIN (peeklen, 4)))
414     return hunk;
415
416   if (oldlen < 4)
417     start = hunk;
418   else
419     start = hunk + oldlen - 4;
420   end = hunk + oldlen + peeklen;
421
422   for (; start < end - 1; start++)
423     if (*start == '\n')
424       {
425         if (start < end - 2
426             && start[1] == '\r'
427             && start[2] == '\n')
428           return start + 3;
429         if (start[1] == '\n')
430           return start + 2;
431       }
432   return NULL;
433 }
434
435 /* Read the HTTP request head from FD and return it.  The error
436    conditions are the same as with fd_read_hunk.
437
438    To support HTTP/0.9 responses, this function tries to make sure
439    that the data begins with "HTTP".  If this is not the case, no data
440    is read and an empty request is returned, so that the remaining
441    data can be treated as body.  */
442
443 static char *
444 fd_read_http_head (int fd)
445 {
446   return fd_read_hunk (fd, head_terminator, 512);
447 }
448
449 struct response {
450   /* The response data. */
451   const char *data;
452
453   /* The array of pointers that indicate where each header starts.
454      For example, given this HTTP response:
455
456        HTTP/1.0 200 Ok
457        Description: some
458         text
459        Etag: x
460
461      The headers are located like this:
462
463      "HTTP/1.0 200 Ok\r\nDescription: some\r\n text\r\nEtag: x\r\n\r\n"
464      ^                   ^                             ^          ^
465      headers[0]          headers[1]                    headers[2] headers[3]
466
467      I.e. headers[0] points to the beginning of the request,
468      headers[1] points to the end of the first header and the
469      beginning of the second one, etc.  */
470
471   const char **headers;
472 };
473
474 /* Create a new response object from the text of the HTTP response,
475    available in HEAD.  That text is automatically split into
476    constituent header lines for fast retrieval using
477    response_header_*.  */
478
479 static struct response *
480 response_new (const char *head)
481 {
482   const char *hdr;
483   int count, size;
484
485   struct response *resp = xnew0 (struct response);
486   resp->data = head;
487
488   if (*head == '\0')
489     {
490       /* Empty head means that we're dealing with a headerless
491          (HTTP/0.9) response.  In that case, don't set HEADERS at
492          all.  */
493       return resp;
494     }
495
496   /* Split HEAD into header lines, so that response_header_* functions
497      don't need to do this over and over again.  */
498
499   size = count = 0;
500   hdr = head;
501   while (1)
502     {
503       DO_REALLOC (resp->headers, size, count + 1, const char *);
504       resp->headers[count++] = hdr;
505
506       /* Break upon encountering an empty line. */
507       if (!hdr[0] || (hdr[0] == '\r' && hdr[1] == '\n') || hdr[0] == '\n')
508         break;
509
510       /* Find the end of HDR, including continuations. */
511       do
512         {
513           const char *end = strchr (hdr, '\n');
514           if (end)
515             hdr = end + 1;
516           else
517             hdr += strlen (hdr);
518         }
519       while (*hdr == ' ' || *hdr == '\t');
520     }
521   DO_REALLOC (resp->headers, size, count + 1, const char *);
522   resp->headers[count++] = NULL;
523
524   return resp;
525 }
526
527 /* Locate the header named NAME in the request data.  If found, set
528    *BEGPTR to its starting, and *ENDPTR to its ending position, and
529    return 1.  Otherwise return 0.
530
531    This function is used as a building block for response_header_copy
532    and response_header_strdup.  */
533
534 static int
535 response_header_bounds (const struct response *resp, const char *name,
536                         const char **begptr, const char **endptr)
537 {
538   int i;
539   const char **headers = resp->headers;
540   int name_len;
541
542   if (!headers || !headers[1])
543     return 0;
544
545   name_len = strlen (name);
546
547   for (i = 1; headers[i + 1]; i++)
548     {
549       const char *b = headers[i];
550       const char *e = headers[i + 1];
551       if (e - b > name_len
552           && b[name_len] == ':'
553           && 0 == strncasecmp (b, name, name_len))
554         {
555           b += name_len + 1;
556           while (b < e && ISSPACE (*b))
557             ++b;
558           while (b < e && ISSPACE (e[-1]))
559             --e;
560           *begptr = b;
561           *endptr = e;
562           return 1;
563         }
564     }
565   return 0;
566 }
567
568 /* Copy the response header named NAME to buffer BUF, no longer than
569    BUFSIZE (BUFSIZE includes the terminating 0).  If the header
570    exists, 1 is returned, otherwise 0.  If there should be no limit on
571    the size of the header, use response_header_strdup instead.
572
573    If BUFSIZE is 0, no data is copied, but the boolean indication of
574    whether the header is present is still returned.  */
575
576 static int
577 response_header_copy (const struct response *resp, const char *name,
578                       char *buf, int bufsize)
579 {
580   const char *b, *e;
581   if (!response_header_bounds (resp, name, &b, &e))
582     return 0;
583   if (bufsize)
584     {
585       int len = MIN (e - b, bufsize - 1);
586       memcpy (buf, b, len);
587       buf[len] = '\0';
588     }
589   return 1;
590 }
591
592 /* Return the value of header named NAME in RESP, allocated with
593    malloc.  If such a header does not exist in RESP, return NULL.  */
594
595 static char *
596 response_header_strdup (const struct response *resp, const char *name)
597 {
598   const char *b, *e;
599   if (!response_header_bounds (resp, name, &b, &e))
600     return NULL;
601   return strdupdelim (b, e);
602 }
603
604 /* Parse the HTTP status line, which is of format:
605
606    HTTP-Version SP Status-Code SP Reason-Phrase
607
608    The function returns the status-code, or -1 if the status line
609    appears malformed.  The pointer to "reason-phrase" message is
610    returned in *MESSAGE.  */
611
612 static int
613 response_status (const struct response *resp, char **message)
614 {
615   int status;
616   const char *p, *end;
617
618   if (!resp->headers)
619     {
620       /* For a HTTP/0.9 response, assume status 200. */
621       if (message)
622         *message = xstrdup (_("No headers, assuming HTTP/0.9"));
623       return 200;
624     }
625
626   p = resp->headers[0];
627   end = resp->headers[1];
628
629   if (!end)
630     return -1;
631
632   /* "HTTP" */
633   if (end - p < 4 || 0 != strncmp (p, "HTTP", 4))
634     return -1;
635   p += 4;
636
637   /* Match the HTTP version.  This is optional because Gnutella
638      servers have been reported to not specify HTTP version.  */
639   if (p < end && *p == '/')
640     {
641       ++p;
642       while (p < end && ISDIGIT (*p))
643         ++p;
644       if (p < end && *p == '.')
645         ++p; 
646       while (p < end && ISDIGIT (*p))
647         ++p;
648     }
649
650   while (p < end && ISSPACE (*p))
651     ++p;
652   if (end - p < 3 || !ISDIGIT (p[0]) || !ISDIGIT (p[1]) || !ISDIGIT (p[2]))
653     return -1;
654
655   status = 100 * (p[0] - '0') + 10 * (p[1] - '0') + (p[2] - '0');
656   p += 3;
657
658   if (message)
659     {
660       while (p < end && ISSPACE (*p))
661         ++p;
662       while (p < end && ISSPACE (end[-1]))
663         --end;
664       *message = strdupdelim (p, end);
665     }
666
667   return status;
668 }
669
670 /* Release the resources used by RESP.  */
671
672 static void
673 response_free (struct response *resp)
674 {
675   xfree_null (resp->headers);
676   xfree (resp);
677 }
678
679 /* Print [b, e) to the log, omitting the trailing CRLF.  */
680
681 static void
682 print_server_response_1 (const char *prefix, const char *b, const char *e)
683 {
684   char *ln;
685   if (b < e && e[-1] == '\n')
686     --e;
687   if (b < e && e[-1] == '\r')
688     --e;
689   BOUNDED_TO_ALLOCA (b, e, ln);
690   logprintf (LOG_VERBOSE, "%s%s\n", prefix, escnonprint (ln));
691 }
692
693 /* Print the server response, line by line, omitting the trailing CR
694    characters, prefixed with PREFIX.  */
695
696 static void
697 print_server_response (const struct response *resp, const char *prefix)
698 {
699   int i;
700   if (!resp->headers)
701     return;
702   for (i = 0; resp->headers[i + 1]; i++)
703     print_server_response_1 (prefix, resp->headers[i], resp->headers[i + 1]);
704 }
705
706 /* Parse the `Content-Range' header and extract the information it
707    contains.  Returns 1 if successful, -1 otherwise.  */
708 static int
709 parse_content_range (const char *hdr, wgint *first_byte_ptr,
710                      wgint *last_byte_ptr, wgint *entity_length_ptr)
711 {
712   wgint num;
713
714   /* Ancient versions of Netscape proxy server, presumably predating
715      rfc2068, sent out `Content-Range' without the "bytes"
716      specifier.  */
717   if (!strncasecmp (hdr, "bytes", 5))
718     {
719       hdr += 5;
720       /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
721          HTTP spec. */
722       if (*hdr == ':')
723         ++hdr;
724       while (ISSPACE (*hdr))
725         ++hdr;
726       if (!*hdr)
727         return 0;
728     }
729   if (!ISDIGIT (*hdr))
730     return 0;
731   for (num = 0; ISDIGIT (*hdr); hdr++)
732     num = 10 * num + (*hdr - '0');
733   if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
734     return 0;
735   *first_byte_ptr = num;
736   ++hdr;
737   for (num = 0; ISDIGIT (*hdr); hdr++)
738     num = 10 * num + (*hdr - '0');
739   if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
740     return 0;
741   *last_byte_ptr = num;
742   ++hdr;
743   for (num = 0; ISDIGIT (*hdr); hdr++)
744     num = 10 * num + (*hdr - '0');
745   *entity_length_ptr = num;
746   return 1;
747 }
748
749 /* Read the body of the request, but don't store it anywhere and don't
750    display a progress gauge.  This is useful for reading the error
751    responses whose bodies don't need to be displayed or logged, but
752    which need to be read anyway.  */
753
754 static void
755 skip_short_body (int fd, wgint contlen)
756 {
757   /* Skipping the body doesn't make sense if the content length is
758      unknown because, in that case, persistent connections cannot be
759      used.  (#### This is not the case with HTTP/1.1 where they can
760      still be used with the magic of the "chunked" transfer!)  */
761   if (contlen == -1)
762     return;
763   DEBUGP (("Skipping %s bytes of body data... ", number_to_static_string (contlen)));
764
765   while (contlen > 0)
766     {
767       char dlbuf[512];
768       int ret = fd_read (fd, dlbuf, MIN (contlen, sizeof (dlbuf)), -1);
769       if (ret <= 0)
770         return;
771       contlen -= ret;
772     }
773   DEBUGP (("done.\n"));
774 }
775 \f
776 /* Persistent connections.  Currently, we cache the most recently used
777    connection as persistent, provided that the HTTP server agrees to
778    make it such.  The persistence data is stored in the variables
779    below.  Ideally, it should be possible to cache an arbitrary fixed
780    number of these connections.  */
781
782 /* Whether a persistent connection is active. */
783 static int pconn_active;
784
785 static struct {
786   /* The socket of the connection.  */
787   int socket;
788
789   /* Host and port of the currently active persistent connection. */
790   char *host;
791   int port;
792
793   /* Whether a ssl handshake has occoured on this connection.  */
794   int ssl;
795 } pconn;
796
797 /* Mark the persistent connection as invalid and free the resources it
798    uses.  This is used by the CLOSE_* macros after they forcefully
799    close a registered persistent connection.  */
800
801 static void
802 invalidate_persistent (void)
803 {
804   DEBUGP (("Disabling further reuse of socket %d.\n", pconn.socket));
805   pconn_active = 0;
806   fd_close (pconn.socket);
807   xfree (pconn.host);
808   xzero (pconn);
809 }
810
811 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
812    persistent.  This will enable someone to use the same connection
813    later.  In the context of HTTP, this must be called only AFTER the
814    response has been received and the server has promised that the
815    connection will remain alive.
816
817    If a previous connection was persistent, it is closed. */
818
819 static void
820 register_persistent (const char *host, int port, int fd, int ssl)
821 {
822   if (pconn_active)
823     {
824       if (pconn.socket == fd)
825         {
826           /* The connection FD is already registered. */
827           return;
828         }
829       else
830         {
831           /* The old persistent connection is still active; close it
832              first.  This situation arises whenever a persistent
833              connection exists, but we then connect to a different
834              host, and try to register a persistent connection to that
835              one.  */
836           invalidate_persistent ();
837         }
838     }
839
840   pconn_active = 1;
841   pconn.socket = fd;
842   pconn.host = xstrdup (host);
843   pconn.port = port;
844   pconn.ssl = ssl;
845
846   DEBUGP (("Registered socket %d for persistent reuse.\n", fd));
847 }
848
849 /* Return non-zero if a persistent connection is available for
850    connecting to HOST:PORT.  */
851
852 static int
853 persistent_available_p (const char *host, int port, int ssl,
854                         int *host_lookup_failed)
855 {
856   /* First, check whether a persistent connection is active at all.  */
857   if (!pconn_active)
858     return 0;
859
860   /* If we want SSL and the last connection wasn't or vice versa,
861      don't use it.  Checking for host and port is not enough because
862      HTTP and HTTPS can apparently coexist on the same port.  */
863   if (ssl != pconn.ssl)
864     return 0;
865
866   /* If we're not connecting to the same port, we're not interested. */
867   if (port != pconn.port)
868     return 0;
869
870   /* If the host is the same, we're in business.  If not, there is
871      still hope -- read below.  */
872   if (0 != strcasecmp (host, pconn.host))
873     {
874       /* If pconn.socket is already talking to HOST, we needn't
875          reconnect.  This happens often when both sites are virtual
876          hosts distinguished only by name and served by the same
877          network interface, and hence the same web server (possibly
878          set up by the ISP and serving many different web sites).
879          This admittedly non-standard optimization does not contradict
880          HTTP and works well with popular server software.  */
881
882       int found;
883       ip_address ip;
884       struct address_list *al;
885
886       if (ssl)
887         /* Don't try to talk to two different SSL sites over the same
888            secure connection!  (Besides, it's not clear if name-based
889            virtual hosting is even possible with SSL.)  */
890         return 0;
891
892       /* If pconn.socket's peer is one of the IP addresses HOST
893          resolves to, pconn.socket is for all intents and purposes
894          already talking to HOST.  */
895
896       if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER))
897         {
898           /* Can't get the peer's address -- something must be very
899              wrong with the connection.  */
900           invalidate_persistent ();
901           return 0;
902         }
903       al = lookup_host (host, 0);
904       if (!al)
905         {
906           *host_lookup_failed = 1;
907           return 0;
908         }
909
910       found = address_list_contains (al, &ip);
911       address_list_release (al);
912
913       if (!found)
914         return 0;
915
916       /* The persistent connection's peer address was found among the
917          addresses HOST resolved to; therefore, pconn.sock is in fact
918          already talking to HOST -- no need to reconnect.  */
919     }
920
921   /* Finally, check whether the connection is still open.  This is
922      important because most server implement a liberal (short) timeout
923      on persistent connections.  Wget can of course always reconnect
924      if the connection doesn't work out, but it's nicer to know in
925      advance.  This test is a logical followup of the first test, but
926      is "expensive" and therefore placed at the end of the list.  */
927
928   if (!test_socket_open (pconn.socket))
929     {
930       /* Oops, the socket is no longer open.  Now that we know that,
931          let's invalidate the persistent connection before returning
932          0.  */
933       invalidate_persistent ();
934       return 0;
935     }
936
937   return 1;
938 }
939
940 /* The idea behind these two CLOSE macros is to distinguish between
941    two cases: one when the job we've been doing is finished, and we
942    want to close the connection and leave, and two when something is
943    seriously wrong and we're closing the connection as part of
944    cleanup.
945
946    In case of keep_alive, CLOSE_FINISH should leave the connection
947    open, while CLOSE_INVALIDATE should still close it.
948
949    Note that the semantics of the flag `keep_alive' is "this
950    connection *will* be reused (the server has promised not to close
951    the connection once we're done)", while the semantics of
952    `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
953    active, registered connection".  */
954
955 #define CLOSE_FINISH(fd) do {                   \
956   if (!keep_alive)                              \
957     {                                           \
958       if (pconn_active && (fd) == pconn.socket) \
959         invalidate_persistent ();               \
960       else                                      \
961         {                                       \
962           fd_close (fd);                        \
963           fd = -1;                              \
964         }                                       \
965     }                                           \
966 } while (0)
967
968 #define CLOSE_INVALIDATE(fd) do {               \
969   if (pconn_active && (fd) == pconn.socket)     \
970     invalidate_persistent ();                   \
971   else                                          \
972     fd_close (fd);                              \
973   fd = -1;                                      \
974 } while (0)
975 \f
976 struct http_stat
977 {
978   wgint len;                    /* received length */
979   wgint contlen;                        /* expected length */
980   wgint restval;                        /* the restart value */
981   int res;                      /* the result of last read */
982   char *newloc;                 /* new location (redirection) */
983   char *remote_time;            /* remote time-stamp string */
984   char *error;                  /* textual HTTP error */
985   int statcode;                 /* status code */
986   wgint rd_size;                        /* amount of data read from socket */
987   double dltime;                /* time it took to download the data */
988   const char *referer;          /* value of the referer header. */
989   char **local_file;            /* local file. */
990 };
991
992 static void
993 free_hstat (struct http_stat *hs)
994 {
995   xfree_null (hs->newloc);
996   xfree_null (hs->remote_time);
997   xfree_null (hs->error);
998
999   /* Guard against being called twice. */
1000   hs->newloc = NULL;
1001   hs->remote_time = NULL;
1002   hs->error = NULL;
1003 }
1004
1005 static char *create_authorization_line PARAMS ((const char *, const char *,
1006                                                 const char *, const char *,
1007                                                 const char *));
1008 static char *basic_authentication_encode PARAMS ((const char *, const char *));
1009 static int known_authentication_scheme_p PARAMS ((const char *));
1010
1011 time_t http_atotm PARAMS ((const char *));
1012
1013 #define BEGINS_WITH(line, string_constant)                              \
1014   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
1015    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
1016        || !line[sizeof (string_constant) - 1]))
1017
1018 /* Retrieve a document through HTTP protocol.  It recognizes status
1019    code, and correctly handles redirections.  It closes the network
1020    socket.  If it receives an error from the functions below it, it
1021    will print it if there is enough information to do so (almost
1022    always), returning the error to the caller (i.e. http_loop).
1023
1024    Various HTTP parameters are stored to hs.
1025
1026    If PROXY is non-NULL, the connection will be made to the proxy
1027    server, and u->url will be requested.  */
1028 static uerr_t
1029 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
1030 {
1031   struct request *req;
1032
1033   char *type;
1034   char *user, *passwd;
1035   char *proxyauth;
1036   int statcode;
1037   int write_error;
1038   wgint contlen, contrange;
1039   struct url *conn;
1040   FILE *fp;
1041
1042   int sock = -1;
1043   int flags;
1044
1045   /* Whether authorization has been already tried. */
1046   int auth_tried_already = 0;
1047
1048   /* Whether our connection to the remote host is through SSL.  */
1049   int using_ssl = 0;
1050
1051   char *head;
1052   struct response *resp;
1053   char hdrval[256];
1054   char *message;
1055
1056   /* Whether this connection will be kept alive after the HTTP request
1057      is done. */
1058   int keep_alive;
1059
1060   /* Whether keep-alive should be inhibited. */
1061   int inhibit_keep_alive = !opt.http_keep_alive || opt.ignore_length;
1062
1063   /* Headers sent when using POST. */
1064   wgint post_data_size = 0;
1065
1066   int host_lookup_failed = 0;
1067
1068 #ifdef HAVE_SSL
1069   if (u->scheme == SCHEME_HTTPS)
1070     {
1071       /* Initialize the SSL context.  After this has once been done,
1072          it becomes a no-op.  */
1073       switch (ssl_init ())
1074         {
1075         case SSLERRCTXCREATE:
1076           /* this is fatal */
1077           logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
1078           return SSLERRCTXCREATE;
1079         case SSLERRCERTFILE:
1080           /* try without certfile */
1081           logprintf (LOG_NOTQUIET,
1082                      _("Failed to load certificates from %s\n"),
1083                      opt.sslcertfile);
1084           logprintf (LOG_NOTQUIET,
1085                      _("Trying without the specified certificate\n"));
1086           break;
1087         case SSLERRCERTKEY:
1088           logprintf (LOG_NOTQUIET,
1089                      _("Failed to get certificate key from %s\n"),
1090                      opt.sslcertkey);
1091           logprintf (LOG_NOTQUIET,
1092                      _("Trying without the specified certificate\n"));
1093           break;
1094         default:
1095           break;
1096         }
1097     }
1098 #endif /* HAVE_SSL */
1099
1100   if (!(*dt & HEAD_ONLY))
1101     /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
1102        know the local filename so we can save to it. */
1103     assert (*hs->local_file != NULL);
1104
1105   auth_tried_already = 0;
1106
1107   /* Initialize certain elements of struct http_stat.  */
1108   hs->len = 0L;
1109   hs->contlen = -1;
1110   hs->res = -1;
1111   hs->newloc = NULL;
1112   hs->remote_time = NULL;
1113   hs->error = NULL;
1114
1115   conn = u;
1116
1117   /* Prepare the request to send. */
1118
1119   req = request_new ();
1120   {
1121     const char *meth = "GET";
1122     if (*dt & HEAD_ONLY)
1123       meth = "HEAD";
1124     else if (opt.post_file_name || opt.post_data)
1125       meth = "POST";
1126     /* Use the full path, i.e. one that includes the leading slash and
1127        the query string.  E.g. if u->path is "foo/bar" and u->query is
1128        "param=value", full_path will be "/foo/bar?param=value".  */
1129     request_set_method (req, meth,
1130                         proxy ? xstrdup (u->url) : url_full_path (u));
1131   }
1132
1133   request_set_header (req, "Referer", (char *) hs->referer, rel_none);
1134   if (*dt & SEND_NOCACHE)
1135     request_set_header (req, "Pragma", "no-cache", rel_none);
1136   if (hs->restval)
1137     request_set_header (req, "Range",
1138                         aprintf ("bytes=%s-",
1139                                  number_to_static_string (hs->restval)),
1140                         rel_value);
1141   if (opt.useragent)
1142     request_set_header (req, "User-Agent", opt.useragent, rel_none);
1143   else
1144     request_set_header (req, "User-Agent",
1145                         aprintf ("Wget/%s", version_string), rel_value);
1146   request_set_header (req, "Accept", "*/*", rel_none);
1147
1148   /* Find the username and password for authentication. */
1149   user = u->user;
1150   passwd = u->passwd;
1151   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
1152   user = user ? user : opt.http_user;
1153   passwd = passwd ? passwd : opt.http_passwd;
1154
1155   if (user && passwd)
1156     {
1157       /* We have the username and the password, but haven't tried
1158          any authorization yet.  Let's see if the "Basic" method
1159          works.  If not, we'll come back here and construct a
1160          proper authorization method with the right challenges.
1161
1162          If we didn't employ this kind of logic, every URL that
1163          requires authorization would have to be processed twice,
1164          which is very suboptimal and generates a bunch of false
1165          "unauthorized" errors in the server log.
1166
1167          #### But this logic also has a serious problem when used
1168          with stronger authentications: we *first* transmit the
1169          username and the password in clear text, and *then* attempt a
1170          stronger authentication scheme.  That cannot be right!  We
1171          are only fortunate that almost everyone still uses the
1172          `Basic' scheme anyway.
1173
1174          There should be an option to prevent this from happening, for
1175          those who use strong authentication schemes and value their
1176          passwords.  */
1177       request_set_header (req, "Authorization",
1178                           basic_authentication_encode (user, passwd),
1179                           rel_value);
1180     }
1181
1182   proxyauth = NULL;
1183   if (proxy)
1184     {
1185       char *proxy_user, *proxy_passwd;
1186       /* For normal username and password, URL components override
1187          command-line/wgetrc parameters.  With proxy
1188          authentication, it's the reverse, because proxy URLs are
1189          normally the "permanent" ones, so command-line args
1190          should take precedence.  */
1191       if (opt.proxy_user && opt.proxy_passwd)
1192         {
1193           proxy_user = opt.proxy_user;
1194           proxy_passwd = opt.proxy_passwd;
1195         }
1196       else
1197         {
1198           proxy_user = proxy->user;
1199           proxy_passwd = proxy->passwd;
1200         }
1201       /* #### This does not appear right.  Can't the proxy request,
1202          say, `Digest' authentication?  */
1203       if (proxy_user && proxy_passwd)
1204         proxyauth = basic_authentication_encode (proxy_user, proxy_passwd);
1205
1206       /* If we're using a proxy, we will be connecting to the proxy
1207          server.  */
1208       conn = proxy;
1209
1210       /* Proxy authorization over SSL is handled below. */
1211 #ifdef HAVE_SSL
1212       if (u->scheme != SCHEME_HTTPS)
1213 #endif
1214         request_set_header (req, "Proxy-Authorization", proxyauth, rel_value);
1215     }
1216
1217   {
1218     /* Whether we need to print the host header with braces around
1219        host, e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the
1220        usual "Host: symbolic-name:1234". */
1221     int squares = strchr (u->host, ':') != NULL;
1222     if (u->port == scheme_default_port (u->scheme))
1223       request_set_header (req, "Host",
1224                           aprintf (squares ? "[%s]" : "%s", u->host),
1225                           rel_value);
1226     else
1227       request_set_header (req, "Host",
1228                           aprintf (squares ? "[%s]:%d" : "%s:%d",
1229                                    u->host, u->port),
1230                           rel_value);
1231   }
1232
1233   if (!inhibit_keep_alive)
1234     request_set_header (req, "Connection", "Keep-Alive", rel_none);
1235
1236   if (opt.cookies)
1237     request_set_header (req, "Cookie",
1238                         cookie_header (wget_cookie_jar,
1239                                        u->host, u->port, u->path,
1240 #ifdef HAVE_SSL
1241                                        u->scheme == SCHEME_HTTPS
1242 #else
1243                                        0
1244 #endif
1245                                        ),
1246                         rel_value);
1247
1248   if (opt.post_data || opt.post_file_name)
1249     {
1250       request_set_header (req, "Content-Type",
1251                           "application/x-www-form-urlencoded", rel_none);
1252       if (opt.post_data)
1253         post_data_size = strlen (opt.post_data);
1254       else
1255         {
1256           post_data_size = file_size (opt.post_file_name);
1257           if (post_data_size == -1)
1258             {
1259               logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
1260                          opt.post_file_name);
1261               post_data_size = 0;
1262             }
1263         }
1264       request_set_header (req, "Content-Length",
1265                           xstrdup (number_to_static_string (post_data_size)),
1266                           rel_value);
1267     }
1268
1269   /* Add the user headers. */
1270   if (opt.user_headers)
1271     {
1272       int i;
1273       for (i = 0; opt.user_headers[i]; i++)
1274         request_set_user_header (req, opt.user_headers[i]);
1275     }
1276
1277  retry_with_auth:
1278   /* We need to come back here when the initial attempt to retrieve
1279      without authorization header fails.  (Expected to happen at least
1280      for the Digest authorization scheme.)  */
1281
1282   keep_alive = 0;
1283
1284   /* Establish the connection.  */
1285
1286   if (!inhibit_keep_alive)
1287     {
1288       /* Look for a persistent connection to target host, unless a
1289          proxy is used.  The exception is when SSL is in use, in which
1290          case the proxy is nothing but a passthrough to the target
1291          host, registered as a connection to the latter.  */
1292       struct url *relevant = conn;
1293 #ifdef HAVE_SSL
1294       if (u->scheme == SCHEME_HTTPS)
1295         relevant = u;
1296 #endif
1297
1298       if (persistent_available_p (relevant->host, relevant->port,
1299 #ifdef HAVE_SSL
1300                                   relevant->scheme == SCHEME_HTTPS,
1301 #else
1302                                   0,
1303 #endif
1304                                   &host_lookup_failed))
1305         {
1306           sock = pconn.socket;
1307           using_ssl = pconn.ssl;
1308           logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
1309                      escnonprint (pconn.host), pconn.port);
1310           DEBUGP (("Reusing fd %d.\n", sock));
1311         }
1312     }
1313
1314   if (sock < 0)
1315     {
1316       /* In its current implementation, persistent_available_p will
1317          look up conn->host in some cases.  If that lookup failed, we
1318          don't need to bother with connect_to_host.  */
1319       if (host_lookup_failed)
1320         return HOSTERR;
1321
1322       sock = connect_to_host (conn->host, conn->port);
1323       if (sock == E_HOST)
1324         return HOSTERR;
1325       else if (sock < 0)
1326         return (retryable_socket_connect_error (errno)
1327                 ? CONERROR : CONIMPOSSIBLE);
1328
1329 #ifdef HAVE_SSL
1330       if (proxy && u->scheme == SCHEME_HTTPS)
1331         {
1332           /* When requesting SSL URLs through proxies, use the
1333              CONNECT method to request passthrough.  */
1334           struct request *connreq = request_new ();
1335           request_set_method (connreq, "CONNECT",
1336                               aprintf ("%s:%d", u->host, u->port));
1337           if (proxyauth)
1338             {
1339               request_set_header (connreq, "Proxy-Authorization",
1340                                   proxyauth, rel_value);
1341               /* Now that PROXYAUTH is part of the CONNECT request,
1342                  zero it out so we don't send proxy authorization with
1343                  the regular request below.  */
1344               proxyauth = NULL;
1345             }
1346
1347           write_error = request_send (connreq, sock);
1348           request_free (connreq);
1349           if (write_error < 0)
1350             {
1351               logprintf (LOG_VERBOSE, _("Failed writing to proxy: %s.\n"),
1352                          strerror (errno));
1353               CLOSE_INVALIDATE (sock);
1354               return WRITEFAILED;
1355             }
1356
1357           head = fd_read_http_head (sock);
1358           if (!head)
1359             {
1360               logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
1361                          strerror (errno));
1362               CLOSE_INVALIDATE (sock);
1363               return HERR;
1364             }
1365           message = NULL;
1366           if (!*head)
1367             {
1368               xfree (head);
1369               goto failed_tunnel;
1370             }
1371           DEBUGP (("proxy responded with: [%s]\n", head));
1372
1373           resp = response_new (head);
1374           statcode = response_status (resp, &message);
1375           response_free (resp);
1376           if (statcode != 200)
1377             {
1378             failed_tunnel:
1379               logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
1380                          message ? escnonprint (message) : "?");
1381               xfree_null (message);
1382               return CONSSLERR;
1383             }
1384           xfree_null (message);
1385
1386           /* SOCK is now *really* connected to u->host, so update CONN
1387              to reflect this.  That way register_persistent will
1388              register SOCK as being connected to u->host:u->port.  */
1389           conn = u;
1390         }
1391
1392       if (conn->scheme == SCHEME_HTTPS)
1393         {
1394           if (!ssl_connect (sock))
1395             {
1396               fd_close (sock);
1397               return CONSSLERR;
1398             }
1399           using_ssl = 1;
1400         }
1401 #endif /* HAVE_SSL */
1402     }
1403
1404   /* Send the request to server.  */
1405   write_error = request_send (req, sock);
1406
1407   if (write_error >= 0)
1408     {
1409       if (opt.post_data)
1410         {
1411           DEBUGP (("[POST data: %s]\n", opt.post_data));
1412           write_error = fd_write (sock, opt.post_data, post_data_size, -1);
1413         }
1414       else if (opt.post_file_name && post_data_size != 0)
1415         write_error = post_file (sock, opt.post_file_name, post_data_size);
1416     }
1417
1418   if (write_error < 0)
1419     {
1420       logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1421                  strerror (errno));
1422       CLOSE_INVALIDATE (sock);
1423       request_free (req);
1424       return WRITEFAILED;
1425     }
1426   logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1427              proxy ? "Proxy" : "HTTP");
1428   contlen = -1;
1429   contrange = 0;
1430   type = NULL;
1431   statcode = -1;
1432   *dt &= ~RETROKF;
1433
1434   head = fd_read_http_head (sock);
1435   if (!head)
1436     {
1437       if (errno == 0)
1438         {
1439           logputs (LOG_NOTQUIET, _("No data received.\n"));
1440           CLOSE_INVALIDATE (sock);
1441           request_free (req);
1442           return HEOF;
1443         }
1444       else
1445         {
1446           logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1447                      strerror (errno));
1448           CLOSE_INVALIDATE (sock);
1449           request_free (req);
1450           return HERR;
1451         }
1452     }
1453   DEBUGP (("\n---response begin---\n%s---response end---\n", head));
1454
1455   resp = response_new (head);
1456
1457   /* Check for status line.  */
1458   message = NULL;
1459   statcode = response_status (resp, &message);
1460   if (!opt.server_response)
1461     logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
1462                message ? escnonprint (message) : "");
1463   else
1464     {
1465       logprintf (LOG_VERBOSE, "\n");
1466       print_server_response (resp, "  ");
1467     }
1468
1469   if (!opt.ignore_length
1470       && response_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
1471     {
1472       wgint parsed;
1473       errno = 0;
1474       parsed = str_to_wgint (hdrval, NULL, 10);
1475       if (parsed == WGINT_MAX && errno == ERANGE)
1476         /* Out of range.
1477            #### If Content-Length is out of range, it most likely
1478            means that the file is larger than 2G and that we're
1479            compiled without LFS.  In that case we should probably
1480            refuse to even attempt to download the file.  */
1481         contlen = -1;
1482       else
1483         contlen = parsed;
1484     }
1485
1486   /* Check for keep-alive related responses. */
1487   if (!inhibit_keep_alive && contlen != -1)
1488     {
1489       if (response_header_copy (resp, "Keep-Alive", NULL, 0))
1490         keep_alive = 1;
1491       else if (response_header_copy (resp, "Connection", hdrval,
1492                                      sizeof (hdrval)))
1493         {
1494           if (0 == strcasecmp (hdrval, "Keep-Alive"))
1495             keep_alive = 1;
1496         }
1497     }
1498   if (keep_alive)
1499     /* The server has promised that it will not close the connection
1500        when we're done.  This means that we can register it.  */
1501     register_persistent (conn->host, conn->port, sock, using_ssl);
1502
1503   if (statcode == HTTP_STATUS_UNAUTHORIZED)
1504     {
1505       /* Authorization is required.  */
1506       skip_short_body (sock, contlen);
1507       CLOSE_FINISH (sock);
1508       if (auth_tried_already || !(user && passwd))
1509         {
1510           /* If we have tried it already, then there is not point
1511              retrying it.  */
1512           logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1513         }
1514       else
1515         {
1516           char *www_authenticate = response_header_strdup (resp,
1517                                                            "WWW-Authenticate");
1518           /* If the authentication scheme is unknown or if it's the
1519              "Basic" authentication (which we try by default), there's
1520              no sense in retrying.  */
1521           if (!www_authenticate
1522               || !known_authentication_scheme_p (www_authenticate)
1523               || BEGINS_WITH (www_authenticate, "Basic"))
1524             {
1525               xfree_null (www_authenticate);
1526               logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1527             }
1528           else
1529             {
1530               char *pth;
1531               auth_tried_already = 1;
1532               pth = url_full_path (u);
1533               request_set_header (req, "Authorization",
1534                                   create_authorization_line (www_authenticate,
1535                                                              user, passwd,
1536                                                              request_method (req),
1537                                                              pth),
1538                                   rel_value);
1539               xfree (pth);
1540               xfree (www_authenticate);
1541               goto retry_with_auth;
1542             }
1543         }
1544       request_free (req);
1545       return AUTHFAILED;
1546     }
1547   request_free (req);
1548
1549   hs->statcode = statcode;
1550   if (statcode == -1)
1551     hs->error = xstrdup (_("Malformed status line"));
1552   else if (!*message)
1553     hs->error = xstrdup (_("(no description)"));
1554   else
1555     hs->error = xstrdup (message);
1556
1557   type = response_header_strdup (resp, "Content-Type");
1558   if (type)
1559     {
1560       char *tmp = strchr (type, ';');
1561       if (tmp)
1562         {
1563           while (tmp > type && ISSPACE (tmp[-1]))
1564             --tmp;
1565           *tmp = '\0';
1566         }
1567     }
1568   hs->newloc = response_header_strdup (resp, "Location");
1569   hs->remote_time = response_header_strdup (resp, "Last-Modified");
1570   {
1571     char *set_cookie = response_header_strdup (resp, "Set-Cookie");
1572     if (set_cookie)
1573       {
1574         /* The jar should have been created by now. */
1575         assert (wget_cookie_jar != NULL);
1576         cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port, u->path,
1577                                   set_cookie);
1578         xfree (set_cookie);
1579       }
1580   }
1581   if (response_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
1582     {
1583       wgint first_byte_pos, last_byte_pos, entity_length;
1584       if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
1585                                &entity_length))
1586         contrange = first_byte_pos;
1587     }
1588   response_free (resp);
1589
1590   /* 20x responses are counted among successful by default.  */
1591   if (H_20X (statcode))
1592     *dt |= RETROKF;
1593
1594   /* Return if redirected.  */
1595   if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1596     {
1597       /* RFC2068 says that in case of the 300 (multiple choices)
1598          response, the server can output a preferred URL through
1599          `Location' header; otherwise, the request should be treated
1600          like GET.  So, if the location is set, it will be a
1601          redirection; otherwise, just proceed normally.  */
1602       if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1603         *dt |= RETROKF;
1604       else
1605         {
1606           logprintf (LOG_VERBOSE,
1607                      _("Location: %s%s\n"),
1608                      hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
1609                      hs->newloc ? _(" [following]") : "");
1610           if (keep_alive)
1611             skip_short_body (sock, contlen);
1612           CLOSE_FINISH (sock);
1613           xfree_null (type);
1614           return NEWLOCATION;
1615         }
1616     }
1617
1618   /* If content-type is not given, assume text/html.  This is because
1619      of the multitude of broken CGI's that "forget" to generate the
1620      content-type.  */
1621   if (!type ||
1622         0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)) ||
1623         0 == strncasecmp (type, TEXTXHTML_S, strlen (TEXTXHTML_S)))
1624     *dt |= TEXTHTML;
1625   else
1626     *dt &= ~TEXTHTML;
1627
1628   if (opt.html_extension && (*dt & TEXTHTML))
1629     /* -E / --html-extension / html_extension = on was specified, and this is a
1630        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
1631        already the file's suffix, tack on ".html". */
1632     {
1633       char*  last_period_in_local_filename = strrchr(*hs->local_file, '.');
1634
1635       if (last_period_in_local_filename == NULL
1636           || !(0 == strcasecmp (last_period_in_local_filename, ".htm")
1637                || 0 == strcasecmp (last_period_in_local_filename, ".html")))
1638         {
1639           size_t  local_filename_len = strlen(*hs->local_file);
1640           
1641           *hs->local_file = xrealloc(*hs->local_file,
1642                                      local_filename_len + sizeof(".html"));
1643           strcpy(*hs->local_file + local_filename_len, ".html");
1644
1645           *dt |= ADDED_HTML_EXTENSION;
1646         }
1647     }
1648
1649   if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE)
1650     {
1651       /* If `-c' is in use and the file has been fully downloaded (or
1652          the remote file has shrunk), Wget effectively requests bytes
1653          after the end of file and the server response with 416.  */
1654       logputs (LOG_VERBOSE, _("\
1655 \n    The file is already fully retrieved; nothing to do.\n\n"));
1656       /* In case the caller inspects. */
1657       hs->len = contlen;
1658       hs->res = 0;
1659       /* Mark as successfully retrieved. */
1660       *dt |= RETROKF;
1661       xfree_null (type);
1662       CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1663                                    might be more bytes in the body. */
1664       return RETRUNNEEDED;
1665     }
1666   if ((contrange != 0 && contrange != hs->restval)
1667       || (H_PARTIAL (statcode) && !contrange))
1668     {
1669       /* The Range request was somehow misunderstood by the server.
1670          Bail out.  */
1671       xfree_null (type);
1672       CLOSE_INVALIDATE (sock);
1673       return RANGEERR;
1674     }
1675   hs->contlen = contlen + contrange;
1676
1677   if (opt.verbose)
1678     {
1679       if (*dt & RETROKF)
1680         {
1681           /* No need to print this output if the body won't be
1682              downloaded at all, or if the original server response is
1683              printed.  */
1684           logputs (LOG_VERBOSE, _("Length: "));
1685           if (contlen != -1)
1686             {
1687               logputs (LOG_VERBOSE, legible (contlen + contrange));
1688               if (contrange)
1689                 logprintf (LOG_VERBOSE, _(" (%s to go)"), legible (contlen));
1690             }
1691           else
1692             logputs (LOG_VERBOSE,
1693                      opt.ignore_length ? _("ignored") : _("unspecified"));
1694           if (type)
1695             logprintf (LOG_VERBOSE, " [%s]\n", escnonprint (type));
1696           else
1697             logputs (LOG_VERBOSE, "\n");
1698         }
1699     }
1700   xfree_null (type);
1701   type = NULL;                  /* We don't need it any more.  */
1702
1703   /* Return if we have no intention of further downloading.  */
1704   if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1705     {
1706       /* In case the caller cares to look...  */
1707       hs->len = 0L;
1708       hs->res = 0;
1709       xfree_null (type);
1710       /* Pre-1.10 Wget used CLOSE_INVALIDATE here.  Now we trust the
1711          servers not to send body in response to a HEAD request.  If
1712          you encounter such a server (more likely a broken CGI), use
1713          `--no-http-keep-alive'.  */
1714       CLOSE_FINISH (sock);
1715       return RETRFINISHED;
1716     }
1717
1718   /* Open the local file.  */
1719   if (!output_stream)
1720     {
1721       mkalldirs (*hs->local_file);
1722       if (opt.backups)
1723         rotate_backups (*hs->local_file);
1724       if (hs->restval)
1725         fp = fopen (*hs->local_file, "ab");
1726       else if (opt.noclobber || opt.always_rest || opt.timestamping || opt.dirstruct
1727                || opt.output_document)
1728         fp = fopen (*hs->local_file, "wb");
1729       else
1730         {
1731           fp = fopen_excl (*hs->local_file, 0);
1732           if (!fp && errno == EEXIST)
1733             {
1734               /* We cannot just invent a new name and use it (which is
1735                  what functions like unique_create typically do)
1736                  because we told the user we'd use this name.
1737                  Instead, return and retry the download.  */
1738               logprintf (LOG_NOTQUIET,
1739                          _("%s has sprung into existence.\n"),
1740                          *hs->local_file);
1741               CLOSE_INVALIDATE (sock);
1742               return FOPEN_EXCL_ERR;
1743             }
1744         }
1745       if (!fp)
1746         {
1747           logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1748           CLOSE_INVALIDATE (sock);
1749           return FOPENERR;
1750         }
1751     }
1752   else
1753     fp = output_stream;
1754
1755   /* #### This confuses the timestamping code that checks for file
1756      size.  Maybe we should save some additional information?  */
1757   if (opt.save_headers)
1758     fwrite (head, 1, strlen (head), fp);
1759
1760   /* Download the request body.  */
1761   flags = 0;
1762   if (keep_alive)
1763     flags |= rb_read_exactly;
1764   if (hs->restval > 0 && contrange == 0)
1765     /* If the server ignored our range request, instruct fd_read_body
1766        to skip the first RESTVAL bytes of body.  */
1767     flags |= rb_skip_startpos;
1768   hs->len = hs->restval;
1769   hs->rd_size = 0;
1770   hs->res = fd_read_body (sock, fp, contlen != -1 ? contlen : 0,
1771                           hs->restval, &hs->rd_size, &hs->len, &hs->dltime,
1772                           flags);
1773
1774   if (hs->res >= 0)
1775     CLOSE_FINISH (sock);
1776   else
1777     CLOSE_INVALIDATE (sock);
1778
1779   {
1780     /* Close or flush the file.  We have to be careful to check for
1781        error here.  Checking the result of fwrite() is not enough --
1782        errors could go unnoticed!  */
1783     int flush_res;
1784     if (!output_stream)
1785       flush_res = fclose (fp);
1786     else
1787       flush_res = fflush (fp);
1788     if (flush_res == EOF)
1789       hs->res = -2;
1790   }
1791   if (hs->res == -2)
1792     return FWRITEERR;
1793   return RETRFINISHED;
1794 }
1795
1796 /* The genuine HTTP loop!  This is the part where the retrieval is
1797    retried, and retried, and retried, and...  */
1798 uerr_t
1799 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1800            int *dt, struct url *proxy)
1801 {
1802   int count;
1803   int use_ts, got_head = 0;     /* time-stamping info */
1804   char *filename_plus_orig_suffix;
1805   char *local_filename = NULL;
1806   char *tms, *locf, *tmrate;
1807   uerr_t err;
1808   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
1809   wgint local_size = 0;         /* the size of the local file */
1810   size_t filename_len;
1811   struct http_stat hstat;       /* HTTP status */
1812   struct_stat st;
1813   char *dummy = NULL;
1814
1815   /* This used to be done in main(), but it's a better idea to do it
1816      here so that we don't go through the hoops if we're just using
1817      FTP or whatever. */
1818   if (opt.cookies)
1819     {
1820       if (!wget_cookie_jar)
1821         wget_cookie_jar = cookie_jar_new ();
1822       if (opt.cookies_input && !cookies_loaded_p)
1823         {
1824           cookie_jar_load (wget_cookie_jar, opt.cookies_input);
1825           cookies_loaded_p = 1;
1826         }
1827     }
1828
1829   *newloc = NULL;
1830
1831   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
1832      has_wildcards_p because it would also warn on `?', and we know that
1833      shows up in CGI paths a *lot*.  */
1834   if (strchr (u->url, '*'))
1835     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1836
1837   xzero (hstat);
1838
1839   /* Determine the local filename.  */
1840   if (local_file && *local_file)
1841     hstat.local_file = local_file;
1842   else if (local_file && !opt.output_document)
1843     {
1844       *local_file = url_file_name (u);
1845       hstat.local_file = local_file;
1846     }
1847   else
1848     {
1849       dummy = url_file_name (u);
1850       hstat.local_file = &dummy;
1851       /* be honest about where we will save the file */
1852       if (local_file && opt.output_document)
1853         *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);
1854     }
1855
1856   if (!opt.output_document)
1857     locf = *hstat.local_file;
1858   else
1859     locf = opt.output_document;
1860
1861   hstat.referer = referer;
1862
1863   filename_len = strlen (*hstat.local_file);
1864   filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1865
1866   if (opt.noclobber && file_exists_p (*hstat.local_file))
1867     {
1868       /* If opt.noclobber is turned on and file already exists, do not
1869          retrieve the file */
1870       logprintf (LOG_VERBOSE, _("\
1871 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1872       /* If the file is there, we suppose it's retrieved OK.  */
1873       *dt |= RETROKF;
1874
1875       /* #### Bogusness alert.  */
1876       /* If its suffix is "html" or "htm" or similar, assume text/html.  */
1877       if (has_html_suffix_p (*hstat.local_file))
1878         *dt |= TEXTHTML;
1879
1880       xfree_null (dummy);
1881       return RETROK;
1882     }
1883
1884   use_ts = 0;
1885   if (opt.timestamping)
1886     {
1887       int local_dot_orig_file_exists = 0;
1888
1889       if (opt.backup_converted)
1890         /* If -K is specified, we'll act on the assumption that it was specified
1891            last time these files were downloaded as well, and instead of just
1892            comparing local file X against server file X, we'll compare local
1893            file X.orig (if extant, else X) against server file X.  If -K
1894            _wasn't_ specified last time, or the server contains files called
1895            *.orig, -N will be back to not operating correctly with -k. */
1896         {
1897           /* Would a single s[n]printf() call be faster?  --dan
1898
1899              Definitely not.  sprintf() is horribly slow.  It's a
1900              different question whether the difference between the two
1901              affects a program.  Usually I'd say "no", but at one
1902              point I profiled Wget, and found that a measurable and
1903              non-negligible amount of time was lost calling sprintf()
1904              in url.c.  Replacing sprintf with inline calls to
1905              strcpy() and number_to_string() made a difference.
1906              --hniksic */
1907           memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1908           memcpy (filename_plus_orig_suffix + filename_len,
1909                   ".orig", sizeof (".orig"));
1910
1911           /* Try to stat() the .orig file. */
1912           if (stat (filename_plus_orig_suffix, &st) == 0)
1913             {
1914               local_dot_orig_file_exists = 1;
1915               local_filename = filename_plus_orig_suffix;
1916             }
1917         }      
1918
1919       if (!local_dot_orig_file_exists)
1920         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1921         if (stat (*hstat.local_file, &st) == 0)
1922           local_filename = *hstat.local_file;
1923
1924       if (local_filename != NULL)
1925         /* There was a local file, so we'll check later to see if the version
1926            the server has is the same version we already have, allowing us to
1927            skip a download. */
1928         {
1929           use_ts = 1;
1930           tml = st.st_mtime;
1931 #ifdef WINDOWS
1932           /* Modification time granularity is 2 seconds for Windows, so
1933              increase local time by 1 second for later comparison. */
1934           tml++;
1935 #endif
1936           local_size = st.st_size;
1937           got_head = 0;
1938         }
1939     }
1940   /* Reset the counter.  */
1941   count = 0;
1942   *dt = 0;
1943   /* THE loop */
1944   do
1945     {
1946       /* Increment the pass counter.  */
1947       ++count;
1948       sleep_between_retrievals (count);
1949       /* Get the current time string.  */
1950       tms = time_str (NULL);
1951       /* Print fetch message, if opt.verbose.  */
1952       if (opt.verbose)
1953         {
1954           char *hurl = url_string (u, 1);
1955           char tmp[256];
1956           strcpy (tmp, "        ");
1957           if (count > 1)
1958             sprintf (tmp, _("(try:%2d)"), count);
1959           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1960                      tms, hurl, tmp, locf);
1961 #ifdef WINDOWS
1962           ws_changetitle (hurl);
1963 #endif
1964           xfree (hurl);
1965         }
1966
1967       /* Default document type is empty.  However, if spider mode is
1968          on or time-stamping is employed, HEAD_ONLY commands is
1969          encoded within *dt.  */
1970       if (opt.spider || (use_ts && !got_head))
1971         *dt |= HEAD_ONLY;
1972       else
1973         *dt &= ~HEAD_ONLY;
1974
1975       /* Decide whether or not to restart.  */
1976       hstat.restval = 0;
1977       if (count > 1)
1978         hstat.restval = hstat.len; /* continue where we left off */
1979       else if (opt.always_rest
1980                && stat (locf, &st) == 0
1981                && S_ISREG (st.st_mode))
1982         hstat.restval = st.st_size;
1983
1984       /* Decide whether to send the no-cache directive.  We send it in
1985          two cases:
1986            a) we're using a proxy, and we're past our first retrieval.
1987               Some proxies are notorious for caching incomplete data, so
1988               we require a fresh get.
1989            b) caching is explicitly inhibited. */
1990       if ((proxy && count > 1)  /* a */
1991           || !opt.allow_cache   /* b */
1992           )
1993         *dt |= SEND_NOCACHE;
1994       else
1995         *dt &= ~SEND_NOCACHE;
1996
1997       /* Try fetching the document, or at least its head.  */
1998       err = gethttp (u, &hstat, dt, proxy);
1999
2000       /* It's unfortunate that wget determines the local filename before finding
2001          out the Content-Type of the file.  Barring a major restructuring of the
2002          code, we need to re-set locf here, since gethttp() may have xrealloc()d
2003          *hstat.local_file to tack on ".html". */
2004       if (!opt.output_document)
2005         locf = *hstat.local_file;
2006
2007       /* Time?  */
2008       tms = time_str (NULL);
2009       /* Get the new location (with or without the redirection).  */
2010       if (hstat.newloc)
2011         *newloc = xstrdup (hstat.newloc);
2012       switch (err)
2013         {
2014         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
2015         case CONERROR: case READERR: case WRITEFAILED:
2016         case RANGEERR: case FOPEN_EXCL_ERR:
2017           /* Non-fatal errors continue executing the loop, which will
2018              bring them to "while" statement at the end, to judge
2019              whether the number of tries was exceeded.  */
2020           free_hstat (&hstat);
2021           printwhat (count, opt.ntry);
2022           if (err == FOPEN_EXCL_ERR)
2023             {
2024               /* Re-determine the file name. */
2025               if (local_file && *local_file)
2026                 {
2027                   xfree (*local_file);
2028                   *local_file = url_file_name (u);
2029                   hstat.local_file = local_file;
2030                 }
2031               else
2032                 {
2033                   xfree (dummy);
2034                   dummy = url_file_name (u);
2035                   hstat.local_file = &dummy;
2036                 }
2037               /* be honest about where we will save the file */
2038               if (local_file && opt.output_document)
2039                 *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);
2040               if (!opt.output_document)
2041                 locf = *hstat.local_file;
2042               else
2043                 locf = opt.output_document;
2044             }
2045           continue;
2046           break;
2047         case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case AUTHFAILED: 
2048         case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
2049           /* Fatal errors just return from the function.  */
2050           free_hstat (&hstat);
2051           xfree_null (dummy);
2052           return err;
2053           break;
2054         case FWRITEERR: case FOPENERR:
2055           /* Another fatal error.  */
2056           logputs (LOG_VERBOSE, "\n");
2057           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
2058                      *hstat.local_file, strerror (errno));
2059           free_hstat (&hstat);
2060           xfree_null (dummy);
2061           return err;
2062           break;
2063         case CONSSLERR:
2064           /* Another fatal error.  */
2065           logputs (LOG_VERBOSE, "\n");
2066           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
2067           free_hstat (&hstat);
2068           xfree_null (dummy);
2069           return err;
2070           break;
2071         case NEWLOCATION:
2072           /* Return the new location to the caller.  */
2073           if (!hstat.newloc)
2074             {
2075               logprintf (LOG_NOTQUIET,
2076                          _("ERROR: Redirection (%d) without location.\n"),
2077                          hstat.statcode);
2078               free_hstat (&hstat);
2079               xfree_null (dummy);
2080               return WRONGCODE;
2081             }
2082           free_hstat (&hstat);
2083           xfree_null (dummy);
2084           return NEWLOCATION;
2085           break;
2086         case RETRUNNEEDED:
2087           /* The file was already fully retrieved. */
2088           free_hstat (&hstat);
2089           xfree_null (dummy);
2090           return RETROK;
2091           break;
2092         case RETRFINISHED:
2093           /* Deal with you later.  */
2094           break;
2095         default:
2096           /* All possibilities should have been exhausted.  */
2097           abort ();
2098         }
2099       if (!(*dt & RETROKF))
2100         {
2101           if (!opt.verbose)
2102             {
2103               /* #### Ugly ugly ugly! */
2104               char *hurl = url_string (u, 1);
2105               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
2106               xfree (hurl);
2107             }
2108           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
2109                      tms, hstat.statcode, escnonprint (hstat.error));
2110           logputs (LOG_VERBOSE, "\n");
2111           free_hstat (&hstat);
2112           xfree_null (dummy);
2113           return WRONGCODE;
2114         }
2115
2116       /* Did we get the time-stamp?  */
2117       if (!got_head)
2118         {
2119           if (opt.timestamping && !hstat.remote_time)
2120             {
2121               logputs (LOG_NOTQUIET, _("\
2122 Last-modified header missing -- time-stamps turned off.\n"));
2123             }
2124           else if (hstat.remote_time)
2125             {
2126               /* Convert the date-string into struct tm.  */
2127               tmr = http_atotm (hstat.remote_time);
2128               if (tmr == (time_t) (-1))
2129                 logputs (LOG_VERBOSE, _("\
2130 Last-modified header invalid -- time-stamp ignored.\n"));
2131             }
2132         }
2133
2134       /* The time-stamping section.  */
2135       if (use_ts)
2136         {
2137           got_head = 1;
2138           *dt &= ~HEAD_ONLY;
2139           use_ts = 0;           /* no more time-stamping */
2140           count = 0;            /* the retrieve count for HEAD is
2141                                    reset */
2142           if (hstat.remote_time && tmr != (time_t) (-1))
2143             {
2144               /* Now time-stamping can be used validly.  Time-stamping
2145                  means that if the sizes of the local and remote file
2146                  match, and local file is newer than the remote file,
2147                  it will not be retrieved.  Otherwise, the normal
2148                  download procedure is resumed.  */
2149               if (tml >= tmr &&
2150                   (hstat.contlen == -1 || local_size == hstat.contlen))
2151                 {
2152                   logprintf (LOG_VERBOSE, _("\
2153 Server file no newer than local file `%s' -- not retrieving.\n\n"),
2154                              local_filename);
2155                   free_hstat (&hstat);
2156                   xfree_null (dummy);
2157                   return RETROK;
2158                 }
2159               else if (tml >= tmr)
2160                 logprintf (LOG_VERBOSE, _("\
2161 The sizes do not match (local %s) -- retrieving.\n"),
2162                            number_to_static_string (local_size));
2163               else
2164                 logputs (LOG_VERBOSE,
2165                          _("Remote file is newer, retrieving.\n"));
2166             }
2167           free_hstat (&hstat);
2168           continue;
2169         }
2170       if ((tmr != (time_t) (-1))
2171           && !opt.spider
2172           && ((hstat.len == hstat.contlen) ||
2173               ((hstat.res == 0) &&
2174                ((hstat.contlen == -1) ||
2175                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
2176         {
2177           /* #### This code repeats in http.c and ftp.c.  Move it to a
2178              function!  */
2179           const char *fl = NULL;
2180           if (opt.output_document)
2181             {
2182               if (output_stream_regular)
2183                 fl = opt.output_document;
2184             }
2185           else
2186             fl = *hstat.local_file;
2187           if (fl)
2188             touch (fl, tmr);
2189         }
2190       /* End of time-stamping section.  */
2191
2192       if (opt.spider)
2193         {
2194           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode,
2195                      escnonprint (hstat.error));
2196           xfree_null (dummy);
2197           return RETROK;
2198         }
2199
2200       tmrate = retr_rate (hstat.rd_size, hstat.dltime, 0);
2201
2202       if (hstat.len == hstat.contlen)
2203         {
2204           if (*dt & RETROKF)
2205             {
2206               logprintf (LOG_VERBOSE,
2207                          _("%s (%s) - `%s' saved [%s/%s]\n\n"),
2208                          tms, tmrate, locf,
2209                          number_to_static_string (hstat.len),
2210                          number_to_static_string (hstat.contlen));
2211               logprintf (LOG_NONVERBOSE,
2212                          "%s URL:%s [%s/%s] -> \"%s\" [%d]\n",
2213                          tms, u->url,
2214                          number_to_static_string (hstat.len),
2215                          number_to_static_string (hstat.contlen),
2216                          locf, count);
2217             }
2218           ++opt.numurls;
2219           total_downloaded_bytes += hstat.len;
2220
2221           /* Remember that we downloaded the file for later ".orig" code. */
2222           if (*dt & ADDED_HTML_EXTENSION)
2223             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2224           else
2225             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2226
2227           free_hstat (&hstat);
2228           xfree_null (dummy);
2229           return RETROK;
2230         }
2231       else if (hstat.res == 0) /* No read error */
2232         {
2233           if (hstat.contlen == -1)  /* We don't know how much we were supposed
2234                                        to get, so assume we succeeded. */ 
2235             {
2236               if (*dt & RETROKF)
2237                 {
2238                   logprintf (LOG_VERBOSE,
2239                              _("%s (%s) - `%s' saved [%s]\n\n"),
2240                              tms, tmrate, locf,
2241                              number_to_static_string (hstat.len));
2242                   logprintf (LOG_NONVERBOSE,
2243                              "%s URL:%s [%s] -> \"%s\" [%d]\n",
2244                              tms, u->url, number_to_static_string (hstat.len),
2245                              locf, count);
2246                 }
2247               ++opt.numurls;
2248               total_downloaded_bytes += hstat.len;
2249
2250               /* Remember that we downloaded the file for later ".orig" code. */
2251               if (*dt & ADDED_HTML_EXTENSION)
2252                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2253               else
2254                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2255               
2256               free_hstat (&hstat);
2257               xfree_null (dummy);
2258               return RETROK;
2259             }
2260           else if (hstat.len < hstat.contlen) /* meaning we lost the
2261                                                  connection too soon */
2262             {
2263               logprintf (LOG_VERBOSE,
2264                          _("%s (%s) - Connection closed at byte %s. "),
2265                          tms, tmrate, number_to_static_string (hstat.len));
2266               printwhat (count, opt.ntry);
2267               free_hstat (&hstat);
2268               continue;
2269             }
2270           else if (!opt.kill_longer) /* meaning we got more than expected */
2271             {
2272               logprintf (LOG_VERBOSE,
2273                          _("%s (%s) - `%s' saved [%s/%s])\n\n"),
2274                          tms, tmrate, locf,
2275                          number_to_static_string (hstat.len),
2276                          number_to_static_string (hstat.contlen));
2277               logprintf (LOG_NONVERBOSE,
2278                          "%s URL:%s [%s/%s] -> \"%s\" [%d]\n",
2279                          tms, u->url,
2280                          number_to_static_string (hstat.len),
2281                          number_to_static_string (hstat.contlen),
2282                          locf, count);
2283               ++opt.numurls;
2284               total_downloaded_bytes += hstat.len;
2285
2286               /* Remember that we downloaded the file for later ".orig" code. */
2287               if (*dt & ADDED_HTML_EXTENSION)
2288                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2289               else
2290                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2291               
2292               free_hstat (&hstat);
2293               xfree_null (dummy);
2294               return RETROK;
2295             }
2296           else                  /* the same, but not accepted */
2297             {
2298               logprintf (LOG_VERBOSE,
2299                          _("%s (%s) - Connection closed at byte %s/%s. "),
2300                          tms, tmrate,
2301                          number_to_static_string (hstat.len),
2302                          number_to_static_string (hstat.contlen));
2303               printwhat (count, opt.ntry);
2304               free_hstat (&hstat);
2305               continue;
2306             }
2307         }
2308       else                      /* now hstat.res can only be -1 */
2309         {
2310           if (hstat.contlen == -1)
2311             {
2312               logprintf (LOG_VERBOSE,
2313                          _("%s (%s) - Read error at byte %s (%s)."),
2314                          tms, tmrate, number_to_static_string (hstat.len),
2315                          strerror (errno));
2316               printwhat (count, opt.ntry);
2317               free_hstat (&hstat);
2318               continue;
2319             }
2320           else                  /* hstat.res == -1 and contlen is given */
2321             {
2322               logprintf (LOG_VERBOSE,
2323                          _("%s (%s) - Read error at byte %s/%s (%s). "),
2324                          tms, tmrate,
2325                          number_to_static_string (hstat.len),
2326                          number_to_static_string (hstat.contlen),
2327                          strerror (errno));
2328               printwhat (count, opt.ntry);
2329               free_hstat (&hstat);
2330               continue;
2331             }
2332         }
2333       /* not reached */
2334       break;
2335     }
2336   while (!opt.ntry || (count < opt.ntry));
2337   return TRYLIMEXC;
2338 }
2339 \f
2340 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2341    than local timezone.
2342
2343    mktime is similar but assumes struct tm, also known as the
2344    "broken-down" form of time, is in local time zone.  mktime_from_utc
2345    uses mktime to make the conversion understanding that an offset
2346    will be introduced by the local time assumption.
2347
2348    mktime_from_utc then measures the introduced offset by applying
2349    gmtime to the initial result and applying mktime to the resulting
2350    "broken-down" form.  The difference between the two mktime results
2351    is the measured offset which is then subtracted from the initial
2352    mktime result to yield a calendar time which is the value returned.
2353
2354    tm_isdst in struct tm is set to 0 to force mktime to introduce a
2355    consistent offset (the non DST offset) since tm and tm+o might be
2356    on opposite sides of a DST change.
2357
2358    Some implementations of mktime return -1 for the nonexistent
2359    localtime hour at the beginning of DST.  In this event, use
2360    mktime(tm - 1hr) + 3600.
2361
2362    Schematically
2363      mktime(tm)   --> t+o
2364      gmtime(t+o)  --> tm+o
2365      mktime(tm+o) --> t+2o
2366      t+o - (t+2o - t+o) = t
2367
2368    Note that glibc contains a function of the same purpose named
2369    `timegm' (reverse of gmtime).  But obviously, it is not universally
2370    available, and unfortunately it is not straightforwardly
2371    extractable for use here.  Perhaps configure should detect timegm
2372    and use it where available.
2373
2374    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2375    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2376    Further improved by Roger with assistance from Edward J. Sabol
2377    based on input by Jamie Zawinski.  */
2378
2379 static time_t
2380 mktime_from_utc (struct tm *t)
2381 {
2382   time_t tl, tb;
2383   struct tm *tg;
2384
2385   tl = mktime (t);
2386   if (tl == -1)
2387     {
2388       t->tm_hour--;
2389       tl = mktime (t);
2390       if (tl == -1)
2391         return -1; /* can't deal with output from strptime */
2392       tl += 3600;
2393     }
2394   tg = gmtime (&tl);
2395   tg->tm_isdst = 0;
2396   tb = mktime (tg);
2397   if (tb == -1)
2398     {
2399       tg->tm_hour--;
2400       tb = mktime (tg);
2401       if (tb == -1)
2402         return -1; /* can't deal with output from gmtime */
2403       tb += 3600;
2404     }
2405   return (tl - (tb - tl));
2406 }
2407
2408 /* Check whether the result of strptime() indicates success.
2409    strptime() returns the pointer to how far it got to in the string.
2410    The processing has been successful if the string is at `GMT' or
2411    `+X', or at the end of the string.
2412
2413    In extended regexp parlance, the function returns 1 if P matches
2414    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (which strptime
2415    can return) is considered a failure and 0 is returned.  */
2416 static int
2417 check_end (const char *p)
2418 {
2419   if (!p)
2420     return 0;
2421   while (ISSPACE (*p))
2422     ++p;
2423   if (!*p
2424       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2425       || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2426     return 1;
2427   else
2428     return 0;
2429 }
2430
2431 /* Convert the textual specification of time in TIME_STRING to the
2432    number of seconds since the Epoch.
2433
2434    TIME_STRING can be in any of the three formats RFC2068 allows the
2435    HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2436    Timezones are ignored, and should be GMT.
2437
2438    Return the computed time_t representation, or -1 if the conversion
2439    fails.
2440
2441    This function uses strptime with various string formats for parsing
2442    TIME_STRING.  This results in a parser that is not as lenient in
2443    interpreting TIME_STRING as I would like it to be.  Being based on
2444    strptime, it always allows shortened months, one-digit days, etc.,
2445    but due to the multitude of formats in which time can be
2446    represented, an ideal HTTP time parser would be even more
2447    forgiving.  It should completely ignore things like week days and
2448    concentrate only on the various forms of representing years,
2449    months, days, hours, minutes, and seconds.  For example, it would
2450    be nice if it accepted ISO 8601 out of the box.
2451
2452    I've investigated free and PD code for this purpose, but none was
2453    usable.  getdate was big and unwieldy, and had potential copyright
2454    issues, or so I was informed.  Dr. Marcus Hennecke's atotm(),
2455    distributed with phttpd, is excellent, but we cannot use it because
2456    it is not assigned to the FSF.  So I stuck it with strptime.  */
2457
2458 time_t
2459 http_atotm (const char *time_string)
2460 {
2461   /* NOTE: Solaris strptime man page claims that %n and %t match white
2462      space, but that's not universally available.  Instead, we simply
2463      use ` ' to mean "skip all WS", which works under all strptime
2464      implementations I've tested.  */
2465
2466   static const char *time_formats[] = {
2467     "%a, %d %b %Y %T",          /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2468     "%A, %d-%b-%y %T",          /* RFC850:  Thursday, 29-Jan-98 22:12:57 */
2469     "%a, %d-%b-%Y %T",          /* pseudo-RFC850:  Thu, 29-Jan-1998 22:12:57
2470                                    (google.com uses this for their cookies.) */
2471     "%a %b %d %T %Y"            /* asctime: Thu Jan 29 22:12:57 1998 */
2472   };
2473
2474   int i;
2475   struct tm t;
2476
2477   /* According to Roger Beeman, we need to initialize tm_isdst, since
2478      strptime won't do it.  */
2479   t.tm_isdst = 0;
2480
2481   /* Note that under foreign locales Solaris strptime() fails to
2482      recognize English dates, which renders this function useless.  We
2483      solve this by being careful not to affect LC_TIME when
2484      initializing locale.
2485
2486      Another solution would be to temporarily set locale to C, invoke
2487      strptime(), and restore it back.  This is slow and dirty,
2488      however, and locale support other than LC_MESSAGES can mess other
2489      things, so I rather chose to stick with just setting LC_MESSAGES.
2490
2491      GNU strptime does not have this problem because it recognizes
2492      both international and local dates.  */
2493
2494   for (i = 0; i < countof (time_formats); i++)
2495     if (check_end (strptime (time_string, time_formats[i], &t)))
2496       return mktime_from_utc (&t);
2497
2498   /* All formats have failed.  */
2499   return -1;
2500 }
2501 \f
2502 /* Authorization support: We support two authorization schemes:
2503
2504    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2505
2506    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2507    consisting of answering to the server's challenge with the proper
2508    MD5 digests.  */
2509
2510 /* How many bytes it will take to store LEN bytes in base64.  */
2511 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2512
2513 /* Encode the string S of length LENGTH to base64 format and place it
2514    to STORE.  STORE will be 0-terminated, and must point to a writable
2515    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
2516 static void
2517 base64_encode (const char *s, char *store, int length)
2518 {
2519   /* Conversion table.  */
2520   static char tbl[64] = {
2521     'A','B','C','D','E','F','G','H',
2522     'I','J','K','L','M','N','O','P',
2523     'Q','R','S','T','U','V','W','X',
2524     'Y','Z','a','b','c','d','e','f',
2525     'g','h','i','j','k','l','m','n',
2526     'o','p','q','r','s','t','u','v',
2527     'w','x','y','z','0','1','2','3',
2528     '4','5','6','7','8','9','+','/'
2529   };
2530   int i;
2531   unsigned char *p = (unsigned char *)store;
2532
2533   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
2534   for (i = 0; i < length; i += 3)
2535     {
2536       *p++ = tbl[s[0] >> 2];
2537       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2538       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2539       *p++ = tbl[s[2] & 0x3f];
2540       s += 3;
2541     }
2542   /* Pad the result if necessary...  */
2543   if (i == length + 1)
2544     *(p - 1) = '=';
2545   else if (i == length + 2)
2546     *(p - 1) = *(p - 2) = '=';
2547   /* ...and zero-terminate it.  */
2548   *p = '\0';
2549 }
2550
2551 /* Create the authentication header contents for the `Basic' scheme.
2552    This is done by encoding the string `USER:PASS' in base64 and
2553    prepending `HEADER: Basic ' to it.  */
2554 static char *
2555 basic_authentication_encode (const char *user, const char *passwd)
2556 {
2557   char *t1, *t2, *res;
2558   int len1 = strlen (user) + 1 + strlen (passwd);
2559   int len2 = BASE64_LENGTH (len1);
2560
2561   t1 = (char *)alloca (len1 + 1);
2562   sprintf (t1, "%s:%s", user, passwd);
2563
2564   t2 = (char *)alloca (len2 + 1);
2565   base64_encode (t1, t2, len1);
2566
2567   res = (char *)xmalloc (6 + len2 + 1);
2568   sprintf (res, "Basic %s", t2);
2569
2570   return res;
2571 }
2572
2573 #define SKIP_WS(x) do {                         \
2574   while (ISSPACE (*(x)))                        \
2575     ++(x);                                      \
2576 } while (0)
2577
2578 #ifdef USE_DIGEST
2579 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
2580    of a field in such a header.  If the field is the one specified by
2581    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2582    digest authorization code), extract its value in the (char*)
2583    variable pointed by RET.  Returns negative on a malformed header,
2584    or number of bytes that have been parsed by this call.  */
2585 static int
2586 extract_header_attr (const char *au, const char *attr_name, char **ret)
2587 {
2588   const char *cp, *ep;
2589
2590   ep = cp = au;
2591
2592   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2593     {
2594       cp += strlen (attr_name);
2595       if (!*cp)
2596         return -1;
2597       SKIP_WS (cp);
2598       if (*cp != '=')
2599         return -1;
2600       if (!*++cp)
2601         return -1;
2602       SKIP_WS (cp);
2603       if (*cp != '\"')
2604         return -1;
2605       if (!*++cp)
2606         return -1;
2607       for (ep = cp; *ep && *ep != '\"'; ep++)
2608         ;
2609       if (!*ep)
2610         return -1;
2611       xfree_null (*ret);
2612       *ret = strdupdelim (cp, ep);
2613       return ep - au + 1;
2614     }
2615   else
2616     return 0;
2617 }
2618
2619 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
2620    an array of 16 bytes containing the hash keys, and BUF should be a
2621    buffer of 33 writable characters (32 for hex digits plus one for
2622    zero termination).  */
2623 static void
2624 dump_hash (unsigned char *buf, const unsigned char *hash)
2625 {
2626   int i;
2627
2628   for (i = 0; i < MD5_HASHLEN; i++, hash++)
2629     {
2630       *buf++ = XNUM_TO_digit (*hash >> 4);
2631       *buf++ = XNUM_TO_digit (*hash & 0xf);
2632     }
2633   *buf = '\0';
2634 }
2635
2636 /* Take the line apart to find the challenge, and compose a digest
2637    authorization header.  See RFC2069 section 2.1.2.  */
2638 static char *
2639 digest_authentication_encode (const char *au, const char *user,
2640                               const char *passwd, const char *method,
2641                               const char *path)
2642 {
2643   static char *realm, *opaque, *nonce;
2644   static struct {
2645     const char *name;
2646     char **variable;
2647   } options[] = {
2648     { "realm", &realm },
2649     { "opaque", &opaque },
2650     { "nonce", &nonce }
2651   };
2652   char *res;
2653
2654   realm = opaque = nonce = NULL;
2655
2656   au += 6;                      /* skip over `Digest' */
2657   while (*au)
2658     {
2659       int i;
2660
2661       SKIP_WS (au);
2662       for (i = 0; i < countof (options); i++)
2663         {
2664           int skip = extract_header_attr (au, options[i].name,
2665                                           options[i].variable);
2666           if (skip < 0)
2667             {
2668               xfree_null (realm);
2669               xfree_null (opaque);
2670               xfree_null (nonce);
2671               return NULL;
2672             }
2673           else if (skip)
2674             {
2675               au += skip;
2676               break;
2677             }
2678         }
2679       if (i == countof (options))
2680         {
2681           while (*au && *au != '=')
2682             au++;
2683           if (*au && *++au)
2684             {
2685               SKIP_WS (au);
2686               if (*au == '\"')
2687                 {
2688                   au++;
2689                   while (*au && *au != '\"')
2690                     au++;
2691                   if (*au)
2692                     au++;
2693                 }
2694             }
2695         }
2696       while (*au && *au != ',')
2697         au++;
2698       if (*au)
2699         au++;
2700     }
2701   if (!realm || !nonce || !user || !passwd || !path || !method)
2702     {
2703       xfree_null (realm);
2704       xfree_null (opaque);
2705       xfree_null (nonce);
2706       return NULL;
2707     }
2708
2709   /* Calculate the digest value.  */
2710   {
2711     ALLOCA_MD5_CONTEXT (ctx);
2712     unsigned char hash[MD5_HASHLEN];
2713     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2714     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2715
2716     /* A1BUF = H(user ":" realm ":" password) */
2717     gen_md5_init (ctx);
2718     gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2719     gen_md5_update ((unsigned char *)":", 1, ctx);
2720     gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2721     gen_md5_update ((unsigned char *)":", 1, ctx);
2722     gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2723     gen_md5_finish (ctx, hash);
2724     dump_hash (a1buf, hash);
2725
2726     /* A2BUF = H(method ":" path) */
2727     gen_md5_init (ctx);
2728     gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2729     gen_md5_update ((unsigned char *)":", 1, ctx);
2730     gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2731     gen_md5_finish (ctx, hash);
2732     dump_hash (a2buf, hash);
2733
2734     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2735     gen_md5_init (ctx);
2736     gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2737     gen_md5_update ((unsigned char *)":", 1, ctx);
2738     gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2739     gen_md5_update ((unsigned char *)":", 1, ctx);
2740     gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2741     gen_md5_finish (ctx, hash);
2742     dump_hash (response_digest, hash);
2743
2744     res = (char*) xmalloc (strlen (user)
2745                            + strlen (user)
2746                            + strlen (realm)
2747                            + strlen (nonce)
2748                            + strlen (path)
2749                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2750                            + (opaque ? strlen (opaque) : 0)
2751                            + 128);
2752     sprintf (res, "Digest \
2753 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2754              user, realm, nonce, path, response_digest);
2755     if (opaque)
2756       {
2757         char *p = res + strlen (res);
2758         strcat (p, ", opaque=\"");
2759         strcat (p, opaque);
2760         strcat (p, "\"");
2761       }
2762   }
2763   return res;
2764 }
2765 #endif /* USE_DIGEST */
2766
2767
2768 #define BEGINS_WITH(line, string_constant)                              \
2769   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
2770    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
2771        || !line[sizeof (string_constant) - 1]))
2772
2773 static int
2774 known_authentication_scheme_p (const char *au)
2775 {
2776   return BEGINS_WITH (au, "Basic")
2777     || BEGINS_WITH (au, "Digest")
2778     || BEGINS_WITH (au, "NTLM");
2779 }
2780
2781 #undef BEGINS_WITH
2782
2783 /* Create the HTTP authorization request header.  When the
2784    `WWW-Authenticate' response header is seen, according to the
2785    authorization scheme specified in that header (`Basic' and `Digest'
2786    are supported by the current implementation), produce an
2787    appropriate HTTP authorization request header.  */
2788 static char *
2789 create_authorization_line (const char *au, const char *user,
2790                            const char *passwd, const char *method,
2791                            const char *path)
2792 {
2793   if (0 == strncasecmp (au, "Basic", 5))
2794     return basic_authentication_encode (user, passwd);
2795 #ifdef USE_DIGEST
2796   if (0 == strncasecmp (au, "Digest", 6))
2797     return digest_authentication_encode (au, user, passwd, method, path);
2798 #endif /* USE_DIGEST */
2799   return NULL;
2800 }
2801 \f
2802 void
2803 http_cleanup (void)
2804 {
2805 }