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