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