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