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