]> sjero.net Git - wget/blob - src/http.c
Fix some memory leaks.
[wget] / src / http.c
1 /* HTTP support.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008, 2009 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 3 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, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <assert.h>
40 #include <errno.h>
41 #include <time.h>
42 #include <locale.h>
43
44 #include "hash.h"
45 #include "http.h"
46 #include "utils.h"
47 #include "url.h"
48 #include "host.h"
49 #include "retr.h"
50 #include "connect.h"
51 #include "netrc.h"
52 #ifdef HAVE_SSL
53 # include "ssl.h"
54 #endif
55 #ifdef ENABLE_NTLM
56 # include "http-ntlm.h"
57 #endif
58 #include "cookies.h"
59 #ifdef ENABLE_DIGEST
60 # include "gen-md5.h"
61 #endif
62 #include "convert.h"
63 #include "spider.h"
64
65 #ifdef TESTING
66 #include "test.h"
67 #endif
68
69 extern char *version_string;
70
71 /* Forward decls. */
72 struct http_stat;
73 static char *create_authorization_line (const char *, const char *,
74                                         const char *, const char *,
75                                         const char *, bool *);
76 static char *basic_authentication_encode (const char *, const char *);
77 static bool known_authentication_scheme_p (const char *, const char *);
78 static void ensure_extension (struct http_stat *, const char *, int *);
79 static void load_cookies (void);
80
81 #ifndef MIN
82 # define MIN(x, y) ((x) > (y) ? (y) : (x))
83 #endif
84
85 \f
86 static bool cookies_loaded_p;
87 static struct cookie_jar *wget_cookie_jar;
88
89 #define TEXTHTML_S "text/html"
90 #define TEXTXHTML_S "application/xhtml+xml"
91 #define TEXTCSS_S "text/css"
92
93 /* Some status code validation macros: */
94 #define H_20X(x)        (((x) >= 200) && ((x) < 300))
95 #define H_PARTIAL(x)    ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
96 #define H_REDIRECTED(x) ((x) == HTTP_STATUS_MOVED_PERMANENTLY          \
97                          || (x) == HTTP_STATUS_MOVED_TEMPORARILY       \
98                          || (x) == HTTP_STATUS_SEE_OTHER               \
99                          || (x) == HTTP_STATUS_TEMPORARY_REDIRECT)
100
101 /* HTTP/1.0 status codes from RFC1945, provided for reference.  */
102 /* Successful 2xx.  */
103 #define HTTP_STATUS_OK                    200
104 #define HTTP_STATUS_CREATED               201
105 #define HTTP_STATUS_ACCEPTED              202
106 #define HTTP_STATUS_NO_CONTENT            204
107 #define HTTP_STATUS_PARTIAL_CONTENTS      206
108
109 /* Redirection 3xx.  */
110 #define HTTP_STATUS_MULTIPLE_CHOICES      300
111 #define HTTP_STATUS_MOVED_PERMANENTLY     301
112 #define HTTP_STATUS_MOVED_TEMPORARILY     302
113 #define HTTP_STATUS_SEE_OTHER             303 /* from HTTP/1.1 */
114 #define HTTP_STATUS_NOT_MODIFIED          304
115 #define HTTP_STATUS_TEMPORARY_REDIRECT    307 /* from HTTP/1.1 */
116
117 /* Client error 4xx.  */
118 #define HTTP_STATUS_BAD_REQUEST           400
119 #define HTTP_STATUS_UNAUTHORIZED          401
120 #define HTTP_STATUS_FORBIDDEN             403
121 #define HTTP_STATUS_NOT_FOUND             404
122 #define HTTP_STATUS_RANGE_NOT_SATISFIABLE 416
123
124 /* Server errors 5xx.  */
125 #define HTTP_STATUS_INTERNAL              500
126 #define HTTP_STATUS_NOT_IMPLEMENTED       501
127 #define HTTP_STATUS_BAD_GATEWAY           502
128 #define HTTP_STATUS_UNAVAILABLE           503
129 \f
130 enum rp {
131   rel_none, rel_name, rel_value, rel_both
132 };
133
134 struct request {
135   const char *method;
136   char *arg;
137
138   struct request_header {
139     char *name, *value;
140     enum rp release_policy;
141   } *headers;
142   int hcount, hcapacity;
143 };
144
145 extern int numurls;
146
147 /* Create a new, empty request.  At least request_set_method must be
148    called before the request can be used.  */
149
150 static struct request *
151 request_new (void)
152 {
153   struct request *req = xnew0 (struct request);
154   req->hcapacity = 8;
155   req->headers = xnew_array (struct request_header, req->hcapacity);
156   return req;
157 }
158
159 /* Set the request's method and its arguments.  METH should be a
160    literal string (or it should outlive the request) because it will
161    not be freed.  ARG will be freed by request_free.  */
162
163 static void
164 request_set_method (struct request *req, const char *meth, char *arg)
165 {
166   req->method = meth;
167   req->arg = arg;
168 }
169
170 /* Return the method string passed with the last call to
171    request_set_method.  */
172
173 static const char *
174 request_method (const struct request *req)
175 {
176   return req->method;
177 }
178
179 /* Free one header according to the release policy specified with
180    request_set_header.  */
181
182 static void
183 release_header (struct request_header *hdr)
184 {
185   switch (hdr->release_policy)
186     {
187     case rel_none:
188       break;
189     case rel_name:
190       xfree (hdr->name);
191       break;
192     case rel_value:
193       xfree (hdr->value);
194       break;
195     case rel_both:
196       xfree (hdr->name);
197       xfree (hdr->value);
198       break;
199     }
200 }
201
202 /* Set the request named NAME to VALUE.  Specifically, this means that
203    a "NAME: VALUE\r\n" header line will be used in the request.  If a
204    header with the same name previously existed in the request, its
205    value will be replaced by this one.  A NULL value means do nothing.
206
207    RELEASE_POLICY determines whether NAME and VALUE should be released
208    (freed) with request_free.  Allowed values are:
209
210     - rel_none     - don't free NAME or VALUE
211     - rel_name     - free NAME when done
212     - rel_value    - free VALUE when done
213     - rel_both     - free both NAME and VALUE when done
214
215    Setting release policy is useful when arguments come from different
216    sources.  For example:
217
218      // Don't free literal strings!
219      request_set_header (req, "Pragma", "no-cache", rel_none);
220
221      // Don't free a global variable, we'll need it later.
222      request_set_header (req, "Referer", opt.referer, rel_none);
223
224      // Value freshly allocated, free it when done.
225      request_set_header (req, "Range",
226                          aprintf ("bytes=%s-", number_to_static_string (hs->restval)),
227                          rel_value);
228    */
229
230 static void
231 request_set_header (struct request *req, char *name, char *value,
232                     enum rp release_policy)
233 {
234   struct request_header *hdr;
235   int i;
236
237   if (!value)
238     {
239       /* A NULL value is a no-op; if freeing the name is requested,
240          free it now to avoid leaks.  */
241       if (release_policy == rel_name || release_policy == rel_both)
242         xfree (name);
243       return;
244     }
245
246   for (i = 0; i < req->hcount; i++)
247     {
248       hdr = &req->headers[i];
249       if (0 == strcasecmp (name, hdr->name))
250         {
251           /* Replace existing header. */
252           release_header (hdr);
253           hdr->name = name;
254           hdr->value = value;
255           hdr->release_policy = release_policy;
256           return;
257         }
258     }
259
260   /* Install new header. */
261
262   if (req->hcount >= req->hcapacity)
263     {
264       req->hcapacity <<= 1;
265       req->headers = xrealloc (req->headers, req->hcapacity * sizeof (*hdr));
266     }
267   hdr = &req->headers[req->hcount++];
268   hdr->name = name;
269   hdr->value = value;
270   hdr->release_policy = release_policy;
271 }
272
273 /* Like request_set_header, but sets the whole header line, as
274    provided by the user using the `--header' option.  For example,
275    request_set_user_header (req, "Foo: bar") works just like
276    request_set_header (req, "Foo", "bar").  */
277
278 static void
279 request_set_user_header (struct request *req, const char *header)
280 {
281   char *name;
282   const char *p = strchr (header, ':');
283   if (!p)
284     return;
285   BOUNDED_TO_ALLOCA (header, p, name);
286   ++p;
287   while (c_isspace (*p))
288     ++p;
289   request_set_header (req, xstrdup (name), (char *) p, rel_name);
290 }
291
292 /* Remove the header with specified name from REQ.  Returns true if
293    the header was actually removed, false otherwise.  */
294
295 static bool
296 request_remove_header (struct request *req, char *name)
297 {
298   int i;
299   for (i = 0; i < req->hcount; i++)
300     {
301       struct request_header *hdr = &req->headers[i];
302       if (0 == strcasecmp (name, hdr->name))
303         {
304           release_header (hdr);
305           /* Move the remaining headers by one. */
306           if (i < req->hcount - 1)
307             memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr));
308           --req->hcount;
309           return true;
310         }
311     }
312   return false;
313 }
314
315 #define APPEND(p, str) do {                     \
316   int A_len = strlen (str);                     \
317   memcpy (p, str, A_len);                       \
318   p += A_len;                                   \
319 } while (0)
320
321 /* Construct the request and write it to FD using fd_write.  */
322
323 static int
324 request_send (const struct request *req, int fd)
325 {
326   char *request_string, *p;
327   int i, size, write_error;
328
329   /* Count the request size. */
330   size = 0;
331
332   /* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
333   size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
334
335   for (i = 0; i < req->hcount; i++)
336     {
337       struct request_header *hdr = &req->headers[i];
338       /* NAME ": " VALUE "\r\n" */
339       size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
340     }
341
342   /* "\r\n\0" */
343   size += 3;
344
345   p = request_string = alloca_array (char, size);
346
347   /* Generate the request. */
348
349   APPEND (p, req->method); *p++ = ' ';
350   APPEND (p, req->arg);    *p++ = ' ';
351   memcpy (p, "HTTP/1.0\r\n", 10); p += 10;
352
353   for (i = 0; i < req->hcount; i++)
354     {
355       struct request_header *hdr = &req->headers[i];
356       APPEND (p, hdr->name);
357       *p++ = ':', *p++ = ' ';
358       APPEND (p, hdr->value);
359       *p++ = '\r', *p++ = '\n';
360     }
361
362   *p++ = '\r', *p++ = '\n', *p++ = '\0';
363   assert (p - request_string == size);
364
365 #undef APPEND
366
367   DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
368
369   /* Send the request to the server. */
370
371   write_error = fd_write (fd, request_string, size - 1, -1);
372   if (write_error < 0)
373     logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
374                fd_errstr (fd));
375   return write_error;
376 }
377
378 /* Release the resources used by REQ. */
379
380 static void
381 request_free (struct request *req)
382 {
383   int i;
384   xfree_null (req->arg);
385   for (i = 0; i < req->hcount; i++)
386     release_header (&req->headers[i]);
387   xfree_null (req->headers);
388   xfree (req);
389 }
390
391 static struct hash_table *basic_authed_hosts;
392
393 /* Find out if this host has issued a Basic challenge yet; if so, give
394  * it the username, password. A temporary measure until we can get
395  * proper authentication in place. */
396
397 static bool
398 maybe_send_basic_creds (const char *hostname, const char *user,
399                         const char *passwd, struct request *req)
400 {
401   bool do_challenge = false;
402
403   if (opt.auth_without_challenge)
404     {
405       DEBUGP(("Auth-without-challenge set, sending Basic credentials.\n"));
406       do_challenge = true;
407     }
408   else if (basic_authed_hosts
409       && hash_table_contains(basic_authed_hosts, hostname))
410     {
411       DEBUGP(("Found %s in basic_authed_hosts.\n", quote (hostname)));
412       do_challenge = true;
413     }
414   else
415     {
416       DEBUGP(("Host %s has not issued a general basic challenge.\n",
417               quote (hostname)));
418     }
419   if (do_challenge)
420     {
421       request_set_header (req, "Authorization",
422                           basic_authentication_encode (user, passwd),
423                           rel_value);
424     }
425   return do_challenge;
426 }
427
428 static void
429 register_basic_auth_host (const char *hostname)
430 {
431   if (!basic_authed_hosts)
432     {
433       basic_authed_hosts = make_nocase_string_hash_table (1);
434     }
435   if (!hash_table_contains(basic_authed_hosts, hostname))
436     {
437       hash_table_put (basic_authed_hosts, xstrdup(hostname), NULL);
438       DEBUGP(("Inserted %s into basic_authed_hosts\n", quote (hostname)));
439     }
440 }
441
442
443 /* Send the contents of FILE_NAME to SOCK.  Make sure that exactly
444    PROMISED_SIZE bytes are sent over the wire -- if the file is
445    longer, read only that much; if the file is shorter, report an error.  */
446
447 static int
448 post_file (int sock, const char *file_name, wgint promised_size)
449 {
450   static char chunk[8192];
451   wgint written = 0;
452   int write_error;
453   FILE *fp;
454
455   DEBUGP (("[writing POST file %s ... ", file_name));
456
457   fp = fopen (file_name, "rb");
458   if (!fp)
459     return -1;
460   while (!feof (fp) && written < promised_size)
461     {
462       int towrite;
463       int length = fread (chunk, 1, sizeof (chunk), fp);
464       if (length == 0)
465         break;
466       towrite = MIN (promised_size - written, length);
467       write_error = fd_write (sock, chunk, towrite, -1);
468       if (write_error < 0)
469         {
470           fclose (fp);
471           return -1;
472         }
473       written += towrite;
474     }
475   fclose (fp);
476
477   /* If we've written less than was promised, report a (probably
478      nonsensical) error rather than break the promise.  */
479   if (written < promised_size)
480     {
481       errno = EINVAL;
482       return -1;
483     }
484
485   assert (written == promised_size);
486   DEBUGP (("done]\n"));
487   return 0;
488 }
489 \f
490 /* Determine whether [START, PEEKED + PEEKLEN) contains an empty line.
491    If so, return the pointer to the position after the line, otherwise
492    return NULL.  This is used as callback to fd_read_hunk.  The data
493    between START and PEEKED has been read and cannot be "unread"; the
494    data after PEEKED has only been peeked.  */
495
496 static const char *
497 response_head_terminator (const char *start, const char *peeked, int peeklen)
498 {
499   const char *p, *end;
500
501   /* If at first peek, verify whether HUNK starts with "HTTP".  If
502      not, this is a HTTP/0.9 request and we must bail out without
503      reading anything.  */
504   if (start == peeked && 0 != memcmp (start, "HTTP", MIN (peeklen, 4)))
505     return start;
506
507   /* Look for "\n[\r]\n", and return the following position if found.
508      Start two chars before the current to cover the possibility that
509      part of the terminator (e.g. "\n\r") arrived in the previous
510      batch.  */
511   p = peeked - start < 2 ? start : peeked - 2;
512   end = peeked + peeklen;
513
514   /* Check for \n\r\n or \n\n anywhere in [p, end-2). */
515   for (; p < end - 2; p++)
516     if (*p == '\n')
517       {
518         if (p[1] == '\r' && p[2] == '\n')
519           return p + 3;
520         else if (p[1] == '\n')
521           return p + 2;
522       }
523   /* p==end-2: check for \n\n directly preceding END. */
524   if (p[0] == '\n' && p[1] == '\n')
525     return p + 2;
526
527   return NULL;
528 }
529
530 /* The maximum size of a single HTTP response we care to read.  Rather
531    than being a limit of the reader implementation, this limit
532    prevents Wget from slurping all available memory upon encountering
533    malicious or buggy server output, thus protecting the user.  Define
534    it to 0 to remove the limit.  */
535
536 #define HTTP_RESPONSE_MAX_SIZE 65536
537
538 /* Read the HTTP request head from FD and return it.  The error
539    conditions are the same as with fd_read_hunk.
540
541    To support HTTP/0.9 responses, this function tries to make sure
542    that the data begins with "HTTP".  If this is not the case, no data
543    is read and an empty request is returned, so that the remaining
544    data can be treated as body.  */
545
546 static char *
547 read_http_response_head (int fd)
548 {
549   return fd_read_hunk (fd, response_head_terminator, 512,
550                        HTTP_RESPONSE_MAX_SIZE);
551 }
552
553 struct response {
554   /* The response data. */
555   const char *data;
556
557   /* The array of pointers that indicate where each header starts.
558      For example, given this HTTP response:
559
560        HTTP/1.0 200 Ok
561        Description: some
562         text
563        Etag: x
564
565      The headers are located like this:
566
567      "HTTP/1.0 200 Ok\r\nDescription: some\r\n text\r\nEtag: x\r\n\r\n"
568      ^                   ^                             ^          ^
569      headers[0]          headers[1]                    headers[2] headers[3]
570
571      I.e. headers[0] points to the beginning of the request,
572      headers[1] points to the end of the first header and the
573      beginning of the second one, etc.  */
574
575   const char **headers;
576 };
577
578 /* Create a new response object from the text of the HTTP response,
579    available in HEAD.  That text is automatically split into
580    constituent header lines for fast retrieval using
581    resp_header_*.  */
582
583 static struct response *
584 resp_new (const char *head)
585 {
586   const char *hdr;
587   int count, size;
588
589   struct response *resp = xnew0 (struct response);
590   resp->data = head;
591
592   if (*head == '\0')
593     {
594       /* Empty head means that we're dealing with a headerless
595          (HTTP/0.9) response.  In that case, don't set HEADERS at
596          all.  */
597       return resp;
598     }
599
600   /* Split HEAD into header lines, so that resp_header_* functions
601      don't need to do this over and over again.  */
602
603   size = count = 0;
604   hdr = head;
605   while (1)
606     {
607       DO_REALLOC (resp->headers, size, count + 1, const char *);
608       resp->headers[count++] = hdr;
609
610       /* Break upon encountering an empty line. */
611       if (!hdr[0] || (hdr[0] == '\r' && hdr[1] == '\n') || hdr[0] == '\n')
612         break;
613
614       /* Find the end of HDR, including continuations. */
615       do
616         {
617           const char *end = strchr (hdr, '\n');
618           if (end)
619             hdr = end + 1;
620           else
621             hdr += strlen (hdr);
622         }
623       while (*hdr == ' ' || *hdr == '\t');
624     }
625   DO_REALLOC (resp->headers, size, count + 1, const char *);
626   resp->headers[count] = NULL;
627
628   return resp;
629 }
630
631 /* Locate the header named NAME in the request data, starting with
632    position START.  This allows the code to loop through the request
633    data, filtering for all requests of a given name.  Returns the
634    found position, or -1 for failure.  The code that uses this
635    function typically looks like this:
636
637      for (pos = 0; (pos = resp_header_locate (...)) != -1; pos++)
638        ... do something with header ...
639
640    If you only care about one header, use resp_header_get instead of
641    this function.  */
642
643 static int
644 resp_header_locate (const struct response *resp, const char *name, int start,
645                     const char **begptr, const char **endptr)
646 {
647   int i;
648   const char **headers = resp->headers;
649   int name_len;
650
651   if (!headers || !headers[1])
652     return -1;
653
654   name_len = strlen (name);
655   if (start > 0)
656     i = start;
657   else
658     i = 1;
659
660   for (; headers[i + 1]; i++)
661     {
662       const char *b = headers[i];
663       const char *e = headers[i + 1];
664       if (e - b > name_len
665           && b[name_len] == ':'
666           && 0 == strncasecmp (b, name, name_len))
667         {
668           b += name_len + 1;
669           while (b < e && c_isspace (*b))
670             ++b;
671           while (b < e && c_isspace (e[-1]))
672             --e;
673           *begptr = b;
674           *endptr = e;
675           return i;
676         }
677     }
678   return -1;
679 }
680
681 /* Find and retrieve the header named NAME in the request data.  If
682    found, set *BEGPTR to its starting, and *ENDPTR to its ending
683    position, and return true.  Otherwise return false.
684
685    This function is used as a building block for resp_header_copy
686    and resp_header_strdup.  */
687
688 static bool
689 resp_header_get (const struct response *resp, const char *name,
690                  const char **begptr, const char **endptr)
691 {
692   int pos = resp_header_locate (resp, name, 0, begptr, endptr);
693   return pos != -1;
694 }
695
696 /* Copy the response header named NAME to buffer BUF, no longer than
697    BUFSIZE (BUFSIZE includes the terminating 0).  If the header
698    exists, true is returned, false otherwise.  If there should be no
699    limit on the size of the header, use resp_header_strdup instead.
700
701    If BUFSIZE is 0, no data is copied, but the boolean indication of
702    whether the header is present is still returned.  */
703
704 static bool
705 resp_header_copy (const struct response *resp, const char *name,
706                   char *buf, int bufsize)
707 {
708   const char *b, *e;
709   if (!resp_header_get (resp, name, &b, &e))
710     return false;
711   if (bufsize)
712     {
713       int len = MIN (e - b, bufsize - 1);
714       memcpy (buf, b, len);
715       buf[len] = '\0';
716     }
717   return true;
718 }
719
720 /* Return the value of header named NAME in RESP, allocated with
721    malloc.  If such a header does not exist in RESP, return NULL.  */
722
723 static char *
724 resp_header_strdup (const struct response *resp, const char *name)
725 {
726   const char *b, *e;
727   if (!resp_header_get (resp, name, &b, &e))
728     return NULL;
729   return strdupdelim (b, e);
730 }
731
732 /* Parse the HTTP status line, which is of format:
733
734    HTTP-Version SP Status-Code SP Reason-Phrase
735
736    The function returns the status-code, or -1 if the status line
737    appears malformed.  The pointer to "reason-phrase" message is
738    returned in *MESSAGE.  */
739
740 static int
741 resp_status (const struct response *resp, char **message)
742 {
743   int status;
744   const char *p, *end;
745
746   if (!resp->headers)
747     {
748       /* For a HTTP/0.9 response, assume status 200. */
749       if (message)
750         *message = xstrdup (_("No headers, assuming HTTP/0.9"));
751       return 200;
752     }
753
754   p = resp->headers[0];
755   end = resp->headers[1];
756
757   if (!end)
758     return -1;
759
760   /* "HTTP" */
761   if (end - p < 4 || 0 != strncmp (p, "HTTP", 4))
762     return -1;
763   p += 4;
764
765   /* Match the HTTP version.  This is optional because Gnutella
766      servers have been reported to not specify HTTP version.  */
767   if (p < end && *p == '/')
768     {
769       ++p;
770       while (p < end && c_isdigit (*p))
771         ++p;
772       if (p < end && *p == '.')
773         ++p; 
774       while (p < end && c_isdigit (*p))
775         ++p;
776     }
777
778   while (p < end && c_isspace (*p))
779     ++p;
780   if (end - p < 3 || !c_isdigit (p[0]) || !c_isdigit (p[1]) || !c_isdigit (p[2]))
781     return -1;
782
783   status = 100 * (p[0] - '0') + 10 * (p[1] - '0') + (p[2] - '0');
784   p += 3;
785
786   if (message)
787     {
788       while (p < end && c_isspace (*p))
789         ++p;
790       while (p < end && c_isspace (end[-1]))
791         --end;
792       *message = strdupdelim (p, end);
793     }
794
795   return status;
796 }
797
798 /* Release the resources used by RESP.  */
799
800 static void
801 resp_free (struct response *resp)
802 {
803   xfree_null (resp->headers);
804   xfree (resp);
805 }
806
807 /* Print a single line of response, the characters [b, e).  We tried
808    getting away with
809       logprintf (LOG_VERBOSE, "%s%.*s\n", prefix, (int) (e - b), b);
810    but that failed to escape the non-printable characters and, in fact,
811    caused crashes in UTF-8 locales.  */
812
813 static void
814 print_response_line(const char *prefix, const char *b, const char *e)
815 {
816   char *copy;
817   BOUNDED_TO_ALLOCA(b, e, copy);
818   logprintf (LOG_ALWAYS, "%s%s\n", prefix, 
819              quotearg_style (escape_quoting_style, copy));
820 }
821
822 /* Print the server response, line by line, omitting the trailing CRLF
823    from individual header lines, and prefixed with PREFIX.  */
824
825 static void
826 print_server_response (const struct response *resp, const char *prefix)
827 {
828   int i;
829   if (!resp->headers)
830     return;
831   for (i = 0; resp->headers[i + 1]; i++)
832     {
833       const char *b = resp->headers[i];
834       const char *e = resp->headers[i + 1];
835       /* Skip CRLF */
836       if (b < e && e[-1] == '\n')
837         --e;
838       if (b < e && e[-1] == '\r')
839         --e;
840       print_response_line(prefix, b, e);
841     }
842 }
843
844 /* Parse the `Content-Range' header and extract the information it
845    contains.  Returns true if successful, false otherwise.  */
846 static bool
847 parse_content_range (const char *hdr, wgint *first_byte_ptr,
848                      wgint *last_byte_ptr, wgint *entity_length_ptr)
849 {
850   wgint num;
851
852   /* Ancient versions of Netscape proxy server, presumably predating
853      rfc2068, sent out `Content-Range' without the "bytes"
854      specifier.  */
855   if (0 == strncasecmp (hdr, "bytes", 5))
856     {
857       hdr += 5;
858       /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
859          HTTP spec. */
860       if (*hdr == ':')
861         ++hdr;
862       while (c_isspace (*hdr))
863         ++hdr;
864       if (!*hdr)
865         return false;
866     }
867   if (!c_isdigit (*hdr))
868     return false;
869   for (num = 0; c_isdigit (*hdr); hdr++)
870     num = 10 * num + (*hdr - '0');
871   if (*hdr != '-' || !c_isdigit (*(hdr + 1)))
872     return false;
873   *first_byte_ptr = num;
874   ++hdr;
875   for (num = 0; c_isdigit (*hdr); hdr++)
876     num = 10 * num + (*hdr - '0');
877   if (*hdr != '/' || !c_isdigit (*(hdr + 1)))
878     return false;
879   *last_byte_ptr = num;
880   ++hdr;
881   if (*hdr == '*')
882     num = -1;
883   else
884     for (num = 0; c_isdigit (*hdr); hdr++)
885       num = 10 * num + (*hdr - '0');
886   *entity_length_ptr = num;
887   return true;
888 }
889
890 /* Read the body of the request, but don't store it anywhere and don't
891    display a progress gauge.  This is useful for reading the bodies of
892    administrative responses to which we will soon issue another
893    request.  The response is not useful to the user, but reading it
894    allows us to continue using the same connection to the server.
895
896    If reading fails, false is returned, true otherwise.  In debug
897    mode, the body is displayed for debugging purposes.  */
898
899 static bool
900 skip_short_body (int fd, wgint contlen)
901 {
902   enum {
903     SKIP_SIZE = 512,                /* size of the download buffer */
904     SKIP_THRESHOLD = 4096        /* the largest size we read */
905   };
906   char dlbuf[SKIP_SIZE + 1];
907   dlbuf[SKIP_SIZE] = '\0';        /* so DEBUGP can safely print it */
908
909   /* We shouldn't get here with unknown contlen.  (This will change
910      with HTTP/1.1, which supports "chunked" transfer.)  */
911   assert (contlen != -1);
912
913   /* If the body is too large, it makes more sense to simply close the
914      connection than to try to read the body.  */
915   if (contlen > SKIP_THRESHOLD)
916     return false;
917
918   DEBUGP (("Skipping %s bytes of body: [", number_to_static_string (contlen)));
919
920   while (contlen > 0)
921     {
922       int ret = fd_read (fd, dlbuf, MIN (contlen, SKIP_SIZE), -1);
923       if (ret <= 0)
924         {
925           /* Don't normally report the error since this is an
926              optimization that should be invisible to the user.  */
927           DEBUGP (("] aborting (%s).\n",
928                    ret < 0 ? fd_errstr (fd) : "EOF received"));
929           return false;
930         }
931       contlen -= ret;
932       /* Safe even if %.*s bogusly expects terminating \0 because
933          we've zero-terminated dlbuf above.  */
934       DEBUGP (("%.*s", ret, dlbuf));
935     }
936
937   DEBUGP (("] done.\n"));
938   return true;
939 }
940
941 /* Extract a parameter from the string (typically an HTTP header) at
942    **SOURCE and advance SOURCE to the next parameter.  Return false
943    when there are no more parameters to extract.  The name of the
944    parameter is returned in NAME, and the value in VALUE.  If the
945    parameter has no value, the token's value is zeroed out.
946
947    For example, if *SOURCE points to the string "attachment;
948    filename=\"foo bar\"", the first call to this function will return
949    the token named "attachment" and no value, and the second call will
950    return the token named "filename" and value "foo bar".  The third
951    call will return false, indicating no more valid tokens.  */
952
953 bool
954 extract_param (const char **source, param_token *name, param_token *value,
955                char separator)
956 {
957   const char *p = *source;
958
959   while (c_isspace (*p)) ++p;
960   if (!*p)
961     {
962       *source = p;
963       return false;             /* no error; nothing more to extract */
964     }
965
966   /* Extract name. */
967   name->b = p;
968   while (*p && !c_isspace (*p) && *p != '=' && *p != separator) ++p;
969   name->e = p;
970   if (name->b == name->e)
971     return false;               /* empty name: error */
972   while (c_isspace (*p)) ++p;
973   if (*p == separator || !*p)           /* no value */
974     {
975       xzero (*value);
976       if (*p == separator) ++p;
977       *source = p;
978       return true;
979     }
980   if (*p != '=')
981     return false;               /* error */
982
983   /* *p is '=', extract value */
984   ++p;
985   while (c_isspace (*p)) ++p;
986   if (*p == '"')                /* quoted */
987     {
988       value->b = ++p;
989       while (*p && *p != '"') ++p;
990       if (!*p)
991         return false;
992       value->e = p++;
993       /* Currently at closing quote; find the end of param. */
994       while (c_isspace (*p)) ++p;
995       while (*p && *p != separator) ++p;
996       if (*p == separator)
997         ++p;
998       else if (*p)
999         /* garbage after closed quote, e.g. foo="bar"baz */
1000         return false;
1001     }
1002   else                          /* unquoted */
1003     {
1004       value->b = p;
1005       while (*p && *p != separator) ++p;
1006       value->e = p;
1007       while (value->e != value->b && c_isspace (value->e[-1]))
1008         --value->e;
1009       if (*p == separator) ++p;
1010     }
1011   *source = p;
1012   return true;
1013 }
1014
1015 #undef MAX
1016 #define MAX(p, q) ((p) > (q) ? (p) : (q))
1017
1018 /* Parse the contents of the `Content-Disposition' header, extracting
1019    the information useful to Wget.  Content-Disposition is a header
1020    borrowed from MIME; when used in HTTP, it typically serves for
1021    specifying the desired file name of the resource.  For example:
1022
1023        Content-Disposition: attachment; filename="flora.jpg"
1024
1025    Wget will skip the tokens it doesn't care about, such as
1026    "attachment" in the previous example; it will also skip other
1027    unrecognized params.  If the header is syntactically correct and
1028    contains a file name, a copy of the file name is stored in
1029    *filename and true is returned.  Otherwise, the function returns
1030    false.
1031
1032    The file name is stripped of directory components and must not be
1033    empty.  */
1034
1035 static bool
1036 parse_content_disposition (const char *hdr, char **filename)
1037 {
1038   param_token name, value;
1039   while (extract_param (&hdr, &name, &value, ';'))
1040     if (BOUNDED_EQUAL_NO_CASE (name.b, name.e, "filename") && value.b != NULL)
1041       {
1042         /* Make the file name begin at the last slash or backslash. */
1043         const char *last_slash = memrchr (value.b, '/', value.e - value.b);
1044         const char *last_bs = memrchr (value.b, '\\', value.e - value.b);
1045         if (last_slash && last_bs)
1046           value.b = 1 + MAX (last_slash, last_bs);
1047         else if (last_slash || last_bs)
1048           value.b = 1 + (last_slash ? last_slash : last_bs);
1049         if (value.b == value.e)
1050           continue;
1051         /* Start with the directory prefix, if specified. */
1052         if (opt.dir_prefix)
1053           {
1054             int prefix_length = strlen (opt.dir_prefix);
1055             bool add_slash = (opt.dir_prefix[prefix_length - 1] != '/');
1056             int total_length;
1057
1058             if (add_slash) 
1059               ++prefix_length;
1060             total_length = prefix_length + (value.e - value.b);            
1061             *filename = xmalloc (total_length + 1);
1062             strcpy (*filename, opt.dir_prefix);
1063             if (add_slash) 
1064               (*filename)[prefix_length - 1] = '/';
1065             memcpy (*filename + prefix_length, value.b, (value.e - value.b));
1066             (*filename)[total_length] = '\0';
1067           }
1068         else
1069           *filename = strdupdelim (value.b, value.e);
1070         return true;
1071       }
1072   return false;
1073 }
1074 \f
1075 /* Persistent connections.  Currently, we cache the most recently used
1076    connection as persistent, provided that the HTTP server agrees to
1077    make it such.  The persistence data is stored in the variables
1078    below.  Ideally, it should be possible to cache an arbitrary fixed
1079    number of these connections.  */
1080
1081 /* Whether a persistent connection is active. */
1082 static bool pconn_active;
1083
1084 static struct {
1085   /* The socket of the connection.  */
1086   int socket;
1087
1088   /* Host and port of the currently active persistent connection. */
1089   char *host;
1090   int port;
1091
1092   /* Whether a ssl handshake has occoured on this connection.  */
1093   bool ssl;
1094
1095   /* Whether the connection was authorized.  This is only done by
1096      NTLM, which authorizes *connections* rather than individual
1097      requests.  (That practice is peculiar for HTTP, but it is a
1098      useful optimization.)  */
1099   bool authorized;
1100
1101 #ifdef ENABLE_NTLM
1102   /* NTLM data of the current connection.  */
1103   struct ntlmdata ntlm;
1104 #endif
1105 } pconn;
1106
1107 /* Mark the persistent connection as invalid and free the resources it
1108    uses.  This is used by the CLOSE_* macros after they forcefully
1109    close a registered persistent connection.  */
1110
1111 static void
1112 invalidate_persistent (void)
1113 {
1114   DEBUGP (("Disabling further reuse of socket %d.\n", pconn.socket));
1115   pconn_active = false;
1116   fd_close (pconn.socket);
1117   xfree (pconn.host);
1118   xzero (pconn);
1119 }
1120
1121 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
1122    persistent.  This will enable someone to use the same connection
1123    later.  In the context of HTTP, this must be called only AFTER the
1124    response has been received and the server has promised that the
1125    connection will remain alive.
1126
1127    If a previous connection was persistent, it is closed. */
1128
1129 static void
1130 register_persistent (const char *host, int port, int fd, bool ssl)
1131 {
1132   if (pconn_active)
1133     {
1134       if (pconn.socket == fd)
1135         {
1136           /* The connection FD is already registered. */
1137           return;
1138         }
1139       else
1140         {
1141           /* The old persistent connection is still active; close it
1142              first.  This situation arises whenever a persistent
1143              connection exists, but we then connect to a different
1144              host, and try to register a persistent connection to that
1145              one.  */
1146           invalidate_persistent ();
1147         }
1148     }
1149
1150   pconn_active = true;
1151   pconn.socket = fd;
1152   pconn.host = xstrdup (host);
1153   pconn.port = port;
1154   pconn.ssl = ssl;
1155   pconn.authorized = false;
1156
1157   DEBUGP (("Registered socket %d for persistent reuse.\n", fd));
1158 }
1159
1160 /* Return true if a persistent connection is available for connecting
1161    to HOST:PORT.  */
1162
1163 static bool
1164 persistent_available_p (const char *host, int port, bool ssl,
1165                         bool *host_lookup_failed)
1166 {
1167   /* First, check whether a persistent connection is active at all.  */
1168   if (!pconn_active)
1169     return false;
1170
1171   /* If we want SSL and the last connection wasn't or vice versa,
1172      don't use it.  Checking for host and port is not enough because
1173      HTTP and HTTPS can apparently coexist on the same port.  */
1174   if (ssl != pconn.ssl)
1175     return false;
1176
1177   /* If we're not connecting to the same port, we're not interested. */
1178   if (port != pconn.port)
1179     return false;
1180
1181   /* If the host is the same, we're in business.  If not, there is
1182      still hope -- read below.  */
1183   if (0 != strcasecmp (host, pconn.host))
1184     {
1185       /* Check if pconn.socket is talking to HOST under another name.
1186          This happens often when both sites are virtual hosts
1187          distinguished only by name and served by the same network
1188          interface, and hence the same web server (possibly set up by
1189          the ISP and serving many different web sites).  This
1190          admittedly unconventional optimization does not contradict
1191          HTTP and works well with popular server software.  */
1192
1193       bool found;
1194       ip_address ip;
1195       struct address_list *al;
1196
1197       if (ssl)
1198         /* Don't try to talk to two different SSL sites over the same
1199            secure connection!  (Besides, it's not clear that
1200            name-based virtual hosting is even possible with SSL.)  */
1201         return false;
1202
1203       /* If pconn.socket's peer is one of the IP addresses HOST
1204          resolves to, pconn.socket is for all intents and purposes
1205          already talking to HOST.  */
1206
1207       if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER))
1208         {
1209           /* Can't get the peer's address -- something must be very
1210              wrong with the connection.  */
1211           invalidate_persistent ();
1212           return false;
1213         }
1214       al = lookup_host (host, 0);
1215       if (!al)
1216         {
1217           *host_lookup_failed = true;
1218           return false;
1219         }
1220
1221       found = address_list_contains (al, &ip);
1222       address_list_release (al);
1223
1224       if (!found)
1225         return false;
1226
1227       /* The persistent connection's peer address was found among the
1228          addresses HOST resolved to; therefore, pconn.sock is in fact
1229          already talking to HOST -- no need to reconnect.  */
1230     }
1231
1232   /* Finally, check whether the connection is still open.  This is
1233      important because most servers implement liberal (short) timeout
1234      on persistent connections.  Wget can of course always reconnect
1235      if the connection doesn't work out, but it's nicer to know in
1236      advance.  This test is a logical followup of the first test, but
1237      is "expensive" and therefore placed at the end of the list.
1238
1239      (Current implementation of test_socket_open has a nice side
1240      effect that it treats sockets with pending data as "closed".
1241      This is exactly what we want: if a broken server sends message
1242      body in response to HEAD, or if it sends more than conent-length
1243      data, we won't reuse the corrupted connection.)  */
1244
1245   if (!test_socket_open (pconn.socket))
1246     {
1247       /* Oops, the socket is no longer open.  Now that we know that,
1248          let's invalidate the persistent connection before returning
1249          0.  */
1250       invalidate_persistent ();
1251       return false;
1252     }
1253
1254   return true;
1255 }
1256
1257 /* The idea behind these two CLOSE macros is to distinguish between
1258    two cases: one when the job we've been doing is finished, and we
1259    want to close the connection and leave, and two when something is
1260    seriously wrong and we're closing the connection as part of
1261    cleanup.
1262
1263    In case of keep_alive, CLOSE_FINISH should leave the connection
1264    open, while CLOSE_INVALIDATE should still close it.
1265
1266    Note that the semantics of the flag `keep_alive' is "this
1267    connection *will* be reused (the server has promised not to close
1268    the connection once we're done)", while the semantics of
1269    `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
1270    active, registered connection".  */
1271
1272 #define CLOSE_FINISH(fd) do {                   \
1273   if (!keep_alive)                              \
1274     {                                           \
1275       if (pconn_active && (fd) == pconn.socket) \
1276         invalidate_persistent ();               \
1277       else                                      \
1278         {                                       \
1279           fd_close (fd);                        \
1280           fd = -1;                              \
1281         }                                       \
1282     }                                           \
1283 } while (0)
1284
1285 #define CLOSE_INVALIDATE(fd) do {               \
1286   if (pconn_active && (fd) == pconn.socket)     \
1287     invalidate_persistent ();                   \
1288   else                                          \
1289     fd_close (fd);                              \
1290   fd = -1;                                      \
1291 } while (0)
1292 \f
1293 struct http_stat
1294 {
1295   wgint len;                    /* received length */
1296   wgint contlen;                /* expected length */
1297   wgint restval;                /* the restart value */
1298   int res;                      /* the result of last read */
1299   char *rderrmsg;               /* error message from read error */
1300   char *newloc;                 /* new location (redirection) */
1301   char *remote_time;            /* remote time-stamp string */
1302   char *error;                  /* textual HTTP error */
1303   int statcode;                 /* status code */
1304   char *message;                /* status message */
1305   wgint rd_size;                /* amount of data read from socket */
1306   double dltime;                /* time it took to download the data */
1307   const char *referer;          /* value of the referer header. */
1308   char *local_file;             /* local file name. */
1309   bool existence_checked;       /* true if we already checked for a file's
1310                                    existence after having begun to download
1311                                    (needed in gethttp for when connection is
1312                                    interrupted/restarted. */
1313   bool timestamp_checked;       /* true if pre-download time-stamping checks 
1314                                  * have already been performed */
1315   char *orig_file_name;         /* name of file to compare for time-stamping
1316                                  * (might be != local_file if -K is set) */
1317   wgint orig_file_size;         /* size of file to compare for time-stamping */
1318   time_t orig_file_tstamp;      /* time-stamp of file to compare for 
1319                                  * time-stamping */
1320 };
1321
1322 static void
1323 free_hstat (struct http_stat *hs)
1324 {
1325   xfree_null (hs->newloc);
1326   xfree_null (hs->remote_time);
1327   xfree_null (hs->error);
1328   xfree_null (hs->rderrmsg);
1329   xfree_null (hs->local_file);
1330   xfree_null (hs->orig_file_name);
1331   xfree_null (hs->message);
1332
1333   /* Guard against being called twice. */
1334   hs->newloc = NULL;
1335   hs->remote_time = NULL;
1336   hs->error = NULL;
1337 }
1338
1339 #define BEGINS_WITH(line, string_constant)                               \
1340   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)    \
1341    && (c_isspace (line[sizeof (string_constant) - 1])                      \
1342        || !line[sizeof (string_constant) - 1]))
1343
1344 #define SET_USER_AGENT(req) do {                                         \
1345   if (!opt.useragent)                                                    \
1346     request_set_header (req, "User-Agent",                               \
1347                         aprintf ("Wget/%s", version_string), rel_value); \
1348   else if (*opt.useragent)                                               \
1349     request_set_header (req, "User-Agent", opt.useragent, rel_none);     \
1350 } while (0)
1351
1352 /* The flags that allow clobbering the file (opening with "wb").
1353    Defined here to avoid repetition later.  #### This will require
1354    rework.  */
1355 #define ALLOW_CLOBBER (opt.noclobber || opt.always_rest || opt.timestamping \
1356                        || opt.dirstruct || opt.output_document)
1357
1358 /* Retrieve a document through HTTP protocol.  It recognizes status
1359    code, and correctly handles redirections.  It closes the network
1360    socket.  If it receives an error from the functions below it, it
1361    will print it if there is enough information to do so (almost
1362    always), returning the error to the caller (i.e. http_loop).
1363
1364    Various HTTP parameters are stored to hs.
1365
1366    If PROXY is non-NULL, the connection will be made to the proxy
1367    server, and u->url will be requested.  */
1368 static uerr_t
1369 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
1370 {
1371   struct request *req;
1372
1373   char *type;
1374   char *user, *passwd;
1375   char *proxyauth;
1376   int statcode;
1377   int write_error;
1378   wgint contlen, contrange;
1379   struct url *conn;
1380   FILE *fp;
1381
1382   int sock = -1;
1383   int flags;
1384
1385   /* Set to 1 when the authorization has already been sent and should
1386      not be tried again. */
1387   bool auth_finished = false;
1388
1389   /* Set to 1 when just globally-set Basic authorization has been sent;
1390    * should prevent further Basic negotiations, but not other
1391    * mechanisms. */
1392   bool basic_auth_finished = false;
1393
1394   /* Whether NTLM authentication is used for this request. */
1395   bool ntlm_seen = false;
1396
1397   /* Whether our connection to the remote host is through SSL.  */
1398   bool using_ssl = false;
1399
1400   /* Whether a HEAD request will be issued (as opposed to GET or
1401      POST). */
1402   bool head_only = !!(*dt & HEAD_ONLY);
1403
1404   char *head;
1405   struct response *resp;
1406   char hdrval[256];
1407   char *message;
1408
1409   /* Whether this connection will be kept alive after the HTTP request
1410      is done. */
1411   bool keep_alive;
1412
1413   /* Whether keep-alive should be inhibited.
1414
1415      RFC 2068 requests that 1.0 clients not send keep-alive requests
1416      to proxies.  This is because many 1.0 proxies do not interpret
1417      the Connection header and transfer it to the remote server,
1418      causing it to not close the connection and leave both the proxy
1419      and the client hanging.  */
1420   bool inhibit_keep_alive =
1421     !opt.http_keep_alive || opt.ignore_length || proxy != NULL;
1422
1423   /* Headers sent when using POST. */
1424   wgint post_data_size = 0;
1425
1426   bool host_lookup_failed = false;
1427
1428 #ifdef HAVE_SSL
1429   if (u->scheme == SCHEME_HTTPS)
1430     {
1431       /* Initialize the SSL context.  After this has once been done,
1432          it becomes a no-op.  */
1433       if (!ssl_init ())
1434         {
1435           scheme_disable (SCHEME_HTTPS);
1436           logprintf (LOG_NOTQUIET,
1437                      _("Disabling SSL due to encountered errors.\n"));
1438           return SSLINITFAILED;
1439         }
1440     }
1441 #endif /* HAVE_SSL */
1442
1443   /* Initialize certain elements of struct http_stat.  */
1444   hs->len = 0;
1445   hs->contlen = -1;
1446   hs->res = -1;
1447   hs->rderrmsg = NULL;
1448   hs->newloc = NULL;
1449   hs->remote_time = NULL;
1450   hs->error = NULL;
1451   hs->message = NULL;
1452
1453   conn = u;
1454
1455   /* Prepare the request to send. */
1456
1457   req = request_new ();
1458   {
1459     char *meth_arg;
1460     const char *meth = "GET";
1461     if (head_only)
1462       meth = "HEAD";
1463     else if (opt.post_file_name || opt.post_data)
1464       meth = "POST";
1465     /* Use the full path, i.e. one that includes the leading slash and
1466        the query string.  E.g. if u->path is "foo/bar" and u->query is
1467        "param=value", full_path will be "/foo/bar?param=value".  */
1468     if (proxy
1469 #ifdef HAVE_SSL
1470         /* When using SSL over proxy, CONNECT establishes a direct
1471            connection to the HTTPS server.  Therefore use the same
1472            argument as when talking to the server directly. */
1473         && u->scheme != SCHEME_HTTPS
1474 #endif
1475         )
1476       meth_arg = xstrdup (u->url);
1477     else
1478       meth_arg = url_full_path (u);
1479     request_set_method (req, meth, meth_arg);
1480   }
1481
1482   request_set_header (req, "Referer", (char *) hs->referer, rel_none);
1483   if (*dt & SEND_NOCACHE)
1484     request_set_header (req, "Pragma", "no-cache", rel_none);
1485   if (hs->restval)
1486     request_set_header (req, "Range",
1487                         aprintf ("bytes=%s-",
1488                                  number_to_static_string (hs->restval)),
1489                         rel_value);
1490   SET_USER_AGENT (req);
1491   request_set_header (req, "Accept", "*/*", rel_none);
1492
1493   /* Find the username and password for authentication. */
1494   user = u->user;
1495   passwd = u->passwd;
1496   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
1497   user = user ? user : (opt.http_user ? opt.http_user : opt.user);
1498   passwd = passwd ? passwd : (opt.http_passwd ? opt.http_passwd : opt.passwd);
1499
1500   /* We only do "site-wide" authentication with "global" user/password
1501    * values unless --auth-no-challange has been requested; URL user/password
1502    * info overrides. */
1503   if (user && passwd && (!u->user || opt.auth_without_challenge))
1504     {
1505       /* If this is a host for which we've already received a Basic
1506        * challenge, we'll go ahead and send Basic authentication creds. */
1507       basic_auth_finished = maybe_send_basic_creds(u->host, user, passwd, req);
1508     }
1509
1510   /* Generate the Host header, HOST:PORT.  Take into account that:
1511
1512      - Broken server-side software often doesn't recognize the PORT
1513        argument, so we must generate "Host: www.server.com" instead of
1514        "Host: www.server.com:80" (and likewise for https port).
1515
1516      - IPv6 addresses contain ":", so "Host: 3ffe:8100:200:2::2:1234"
1517        becomes ambiguous and needs to be rewritten as "Host:
1518        [3ffe:8100:200:2::2]:1234".  */
1519   {
1520     /* Formats arranged for hfmt[add_port][add_squares].  */
1521     static const char *hfmt[][2] = {
1522       { "%s", "[%s]" }, { "%s:%d", "[%s]:%d" }
1523     };
1524     int add_port = u->port != scheme_default_port (u->scheme);
1525     int add_squares = strchr (u->host, ':') != NULL;
1526     request_set_header (req, "Host",
1527                         aprintf (hfmt[add_port][add_squares], u->host, u->port),
1528                         rel_value);
1529   }
1530
1531   if (!inhibit_keep_alive)
1532     request_set_header (req, "Connection", "Keep-Alive", rel_none);
1533
1534   if (opt.cookies)
1535     request_set_header (req, "Cookie",
1536                         cookie_header (wget_cookie_jar,
1537                                        u->host, u->port, u->path,
1538 #ifdef HAVE_SSL
1539                                        u->scheme == SCHEME_HTTPS
1540 #else
1541                                        0
1542 #endif
1543                                        ),
1544                         rel_value);
1545
1546   if (opt.post_data || opt.post_file_name)
1547     {
1548       request_set_header (req, "Content-Type",
1549                           "application/x-www-form-urlencoded", rel_none);
1550       if (opt.post_data)
1551         post_data_size = strlen (opt.post_data);
1552       else
1553         {
1554           post_data_size = file_size (opt.post_file_name);
1555           if (post_data_size == -1)
1556             {
1557               logprintf (LOG_NOTQUIET, _("POST data file %s missing: %s\n"),
1558                          quote (opt.post_file_name), strerror (errno));
1559               post_data_size = 0;
1560             }
1561         }
1562       request_set_header (req, "Content-Length",
1563                           xstrdup (number_to_static_string (post_data_size)),
1564                           rel_value);
1565     }
1566
1567   /* Add the user headers. */
1568   if (opt.user_headers)
1569     {
1570       int i;
1571       for (i = 0; opt.user_headers[i]; i++)
1572         request_set_user_header (req, opt.user_headers[i]);
1573     }
1574
1575  retry_with_auth:
1576   /* We need to come back here when the initial attempt to retrieve
1577      without authorization header fails.  (Expected to happen at least
1578      for the Digest authorization scheme.)  */
1579
1580   proxyauth = NULL;
1581   if (proxy)
1582     {
1583       char *proxy_user, *proxy_passwd;
1584       /* For normal username and password, URL components override
1585          command-line/wgetrc parameters.  With proxy
1586          authentication, it's the reverse, because proxy URLs are
1587          normally the "permanent" ones, so command-line args
1588          should take precedence.  */
1589       if (opt.proxy_user && opt.proxy_passwd)
1590         {
1591           proxy_user = opt.proxy_user;
1592           proxy_passwd = opt.proxy_passwd;
1593         }
1594       else
1595         {
1596           proxy_user = proxy->user;
1597           proxy_passwd = proxy->passwd;
1598         }
1599       /* #### This does not appear right.  Can't the proxy request,
1600          say, `Digest' authentication?  */
1601       if (proxy_user && proxy_passwd)
1602         proxyauth = basic_authentication_encode (proxy_user, proxy_passwd);
1603
1604       /* If we're using a proxy, we will be connecting to the proxy
1605          server.  */
1606       conn = proxy;
1607
1608       /* Proxy authorization over SSL is handled below. */
1609 #ifdef HAVE_SSL
1610       if (u->scheme != SCHEME_HTTPS)
1611 #endif
1612         request_set_header (req, "Proxy-Authorization", proxyauth, rel_value);
1613     }
1614
1615   keep_alive = false;
1616
1617   /* Establish the connection.  */
1618
1619   if (!inhibit_keep_alive)
1620     {
1621       /* Look for a persistent connection to target host, unless a
1622          proxy is used.  The exception is when SSL is in use, in which
1623          case the proxy is nothing but a passthrough to the target
1624          host, registered as a connection to the latter.  */
1625       struct url *relevant = conn;
1626 #ifdef HAVE_SSL
1627       if (u->scheme == SCHEME_HTTPS)
1628         relevant = u;
1629 #endif
1630
1631       if (persistent_available_p (relevant->host, relevant->port,
1632 #ifdef HAVE_SSL
1633                                   relevant->scheme == SCHEME_HTTPS,
1634 #else
1635                                   0,
1636 #endif
1637                                   &host_lookup_failed))
1638         {
1639           sock = pconn.socket;
1640           using_ssl = pconn.ssl;
1641           logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
1642                      quotearg_style (escape_quoting_style, pconn.host), 
1643                      pconn.port);
1644           DEBUGP (("Reusing fd %d.\n", sock));
1645           if (pconn.authorized)
1646             /* If the connection is already authorized, the "Basic"
1647                authorization added by code above is unnecessary and
1648                only hurts us.  */
1649             request_remove_header (req, "Authorization");
1650         }
1651       else if (host_lookup_failed)
1652         {
1653           request_free (req);
1654           logprintf(LOG_NOTQUIET,
1655                     _("%s: unable to resolve host address %s\n"),
1656                     exec_name, quote (relevant->host));
1657           return HOSTERR;
1658         }
1659     }
1660
1661   if (sock < 0)
1662     {
1663       sock = connect_to_host (conn->host, conn->port);
1664       if (sock == E_HOST)
1665         {
1666           request_free (req);
1667           return HOSTERR;
1668         }
1669       else if (sock < 0)
1670         {
1671           request_free (req);
1672           return (retryable_socket_connect_error (errno)
1673                   ? CONERROR : CONIMPOSSIBLE);
1674         }
1675
1676 #ifdef HAVE_SSL
1677       if (proxy && u->scheme == SCHEME_HTTPS)
1678         {
1679           /* When requesting SSL URLs through proxies, use the
1680              CONNECT method to request passthrough.  */
1681           struct request *connreq = request_new ();
1682           request_set_method (connreq, "CONNECT",
1683                               aprintf ("%s:%d", u->host, u->port));
1684           SET_USER_AGENT (connreq);
1685           if (proxyauth)
1686             {
1687               request_set_header (connreq, "Proxy-Authorization",
1688                                   proxyauth, rel_value);
1689               /* Now that PROXYAUTH is part of the CONNECT request,
1690                  zero it out so we don't send proxy authorization with
1691                  the regular request below.  */
1692               proxyauth = NULL;
1693             }
1694           /* Examples in rfc2817 use the Host header in CONNECT
1695              requests.  I don't see how that gains anything, given
1696              that the contents of Host would be exactly the same as
1697              the contents of CONNECT.  */
1698
1699           write_error = request_send (connreq, sock);
1700           request_free (connreq);
1701           if (write_error < 0)
1702             {
1703               CLOSE_INVALIDATE (sock);
1704               return WRITEFAILED;
1705             }
1706
1707           head = read_http_response_head (sock);
1708           if (!head)
1709             {
1710               logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
1711                          fd_errstr (sock));
1712               CLOSE_INVALIDATE (sock);
1713               return HERR;
1714             }
1715           message = NULL;
1716           if (!*head)
1717             {
1718               xfree (head);
1719               goto failed_tunnel;
1720             }
1721           DEBUGP (("proxy responded with: [%s]\n", head));
1722
1723           resp = resp_new (head);
1724           statcode = resp_status (resp, &message);
1725           hs->message = xstrdup (message);
1726           resp_free (resp);
1727           xfree (head);
1728           if (statcode != 200)
1729             {
1730             failed_tunnel:
1731               logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
1732                          message ? quotearg_style (escape_quoting_style, message) : "?");
1733               xfree_null (message);
1734               return CONSSLERR;
1735             }
1736           xfree_null (message);
1737
1738           /* SOCK is now *really* connected to u->host, so update CONN
1739              to reflect this.  That way register_persistent will
1740              register SOCK as being connected to u->host:u->port.  */
1741           conn = u;
1742         }
1743
1744       if (conn->scheme == SCHEME_HTTPS)
1745         {
1746           if (!ssl_connect (sock) || !ssl_check_certificate (sock, u->host))
1747             {
1748               fd_close (sock);
1749               return CONSSLERR;
1750             }
1751           using_ssl = true;
1752         }
1753 #endif /* HAVE_SSL */
1754     }
1755
1756   /* Send the request to server.  */
1757   write_error = request_send (req, sock);
1758
1759   if (write_error >= 0)
1760     {
1761       if (opt.post_data)
1762         {
1763           DEBUGP (("[POST data: %s]\n", opt.post_data));
1764           write_error = fd_write (sock, opt.post_data, post_data_size, -1);
1765         }
1766       else if (opt.post_file_name && post_data_size != 0)
1767         write_error = post_file (sock, opt.post_file_name, post_data_size);
1768     }
1769
1770   if (write_error < 0)
1771     {
1772       CLOSE_INVALIDATE (sock);
1773       request_free (req);
1774       return WRITEFAILED;
1775     }
1776   logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1777              proxy ? "Proxy" : "HTTP");
1778   contlen = -1;
1779   contrange = 0;
1780   *dt &= ~RETROKF;
1781
1782   head = read_http_response_head (sock);
1783   if (!head)
1784     {
1785       if (errno == 0)
1786         {
1787           logputs (LOG_NOTQUIET, _("No data received.\n"));
1788           CLOSE_INVALIDATE (sock);
1789           request_free (req);
1790           return HEOF;
1791         }
1792       else
1793         {
1794           logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1795                      fd_errstr (sock));
1796           CLOSE_INVALIDATE (sock);
1797           request_free (req);
1798           return HERR;
1799         }
1800     }
1801   DEBUGP (("\n---response begin---\n%s---response end---\n", head));
1802
1803   resp = resp_new (head);
1804
1805   /* Check for status line.  */
1806   message = NULL;
1807   statcode = resp_status (resp, &message);
1808   hs->message = xstrdup (message);
1809   if (!opt.server_response)
1810     logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
1811                message ? quotearg_style (escape_quoting_style, message) : "");
1812   else
1813     {
1814       logprintf (LOG_VERBOSE, "\n");
1815       print_server_response (resp, "  ");
1816     }
1817
1818   /* Check for keep-alive related responses. */
1819   if (!inhibit_keep_alive && contlen != -1)
1820     {
1821       if (resp_header_copy (resp, "Keep-Alive", NULL, 0))
1822         keep_alive = true;
1823       else if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
1824         {
1825           if (0 == strcasecmp (hdrval, "Keep-Alive"))
1826             keep_alive = true;
1827         }
1828     }
1829
1830   if (keep_alive)
1831     /* The server has promised that it will not close the connection
1832        when we're done.  This means that we can register it.  */
1833     register_persistent (conn->host, conn->port, sock, using_ssl);
1834
1835   if (statcode == HTTP_STATUS_UNAUTHORIZED)
1836     {
1837       /* Authorization is required.  */
1838       if (keep_alive && !head_only && skip_short_body (sock, contlen))
1839         CLOSE_FINISH (sock);
1840       else
1841         CLOSE_INVALIDATE (sock);
1842       pconn.authorized = false;
1843       if (!auth_finished && (user && passwd))
1844         {
1845           /* IIS sends multiple copies of WWW-Authenticate, one with
1846              the value "negotiate", and other(s) with data.  Loop over
1847              all the occurrences and pick the one we recognize.  */
1848           int wapos;
1849           const char *wabeg, *waend;
1850           char *www_authenticate = NULL;
1851           for (wapos = 0;
1852                (wapos = resp_header_locate (resp, "WWW-Authenticate", wapos,
1853                                             &wabeg, &waend)) != -1;
1854                ++wapos)
1855             if (known_authentication_scheme_p (wabeg, waend))
1856               {
1857                 BOUNDED_TO_ALLOCA (wabeg, waend, www_authenticate);
1858                 break;
1859               }
1860
1861           if (!www_authenticate)
1862             {
1863               /* If the authentication header is missing or
1864                  unrecognized, there's no sense in retrying.  */
1865               logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1866             }
1867           else if (!basic_auth_finished
1868                    || !BEGINS_WITH (www_authenticate, "Basic"))
1869             {
1870               char *pth;
1871               pth = url_full_path (u);
1872               request_set_header (req, "Authorization",
1873                                   create_authorization_line (www_authenticate,
1874                                                              user, passwd,
1875                                                              request_method (req),
1876                                                              pth,
1877                                                              &auth_finished),
1878                                   rel_value);
1879               if (BEGINS_WITH (www_authenticate, "NTLM"))
1880                 ntlm_seen = true;
1881               else if (!u->user && BEGINS_WITH (www_authenticate, "Basic"))
1882                 {
1883                   /* Need to register this host as using basic auth,
1884                    * so we automatically send creds next time. */
1885                   register_basic_auth_host (u->host);
1886                 }
1887               xfree (pth);
1888               xfree_null (message);
1889               resp_free (resp);
1890               xfree (head);
1891               goto retry_with_auth;
1892             }
1893           else
1894             {
1895               /* We already did Basic auth, and it failed. Gotta
1896                * give up. */
1897             }
1898         }
1899       logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1900       request_free (req);
1901       xfree_null (message);
1902       resp_free (resp);
1903       xfree (head);
1904       return AUTHFAILED;
1905     }
1906   else /* statcode != HTTP_STATUS_UNAUTHORIZED */
1907     {
1908       /* Kludge: if NTLM is used, mark the TCP connection as authorized. */
1909       if (ntlm_seen)
1910         pconn.authorized = true;
1911     }
1912
1913   /* Determine the local filename if needed. Notice that if -O is used 
1914    * hstat.local_file is set by http_loop to the argument of -O. */
1915   if (!hs->local_file)
1916     {
1917       /* Honor Content-Disposition whether possible. */
1918       if (!opt.content_disposition
1919           || !resp_header_copy (resp, "Content-Disposition", 
1920                                 hdrval, sizeof (hdrval))
1921           || !parse_content_disposition (hdrval, &hs->local_file))
1922         {
1923           /* The Content-Disposition header is missing or broken. 
1924            * Choose unique file name according to given URL. */
1925           hs->local_file = url_file_name (u);
1926         }
1927     }
1928   
1929   /* TODO: perform this check only once. */
1930   if (!hs->existence_checked && file_exists_p (hs->local_file))
1931     {
1932       if (opt.noclobber && !opt.output_document)
1933         {
1934           /* If opt.noclobber is turned on and file already exists, do not
1935              retrieve the file. But if the output_document was given, then this
1936              test was already done and the file didn't exist. Hence the !opt.output_document */
1937           logprintf (LOG_VERBOSE, _("\
1938 File %s already there; not retrieving.\n\n"), quote (hs->local_file));
1939           /* If the file is there, we suppose it's retrieved OK.  */
1940           *dt |= RETROKF;
1941
1942           /* #### Bogusness alert.  */
1943           /* If its suffix is "html" or "htm" or similar, assume text/html.  */
1944           if (has_html_suffix_p (hs->local_file))
1945             *dt |= TEXTHTML;
1946
1947           xfree (head);
1948           xfree_null (message);
1949           return RETRUNNEEDED;
1950         }
1951       else if (!ALLOW_CLOBBER)
1952         {
1953           char *unique = unique_name (hs->local_file, true);
1954           if (unique != hs->local_file)
1955             xfree (hs->local_file);
1956           hs->local_file = unique;
1957         }
1958     }
1959   hs->existence_checked = true;
1960
1961   /* Support timestamping */
1962   /* TODO: move this code out of gethttp. */
1963   if (opt.timestamping && !hs->timestamp_checked)
1964     {
1965       size_t filename_len = strlen (hs->local_file);
1966       char *filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1967       bool local_dot_orig_file_exists = false;
1968       char *local_filename = NULL;
1969       struct_stat st;
1970
1971       if (opt.backup_converted)
1972         /* If -K is specified, we'll act on the assumption that it was specified
1973            last time these files were downloaded as well, and instead of just
1974            comparing local file X against server file X, we'll compare local
1975            file X.orig (if extant, else X) against server file X.  If -K
1976            _wasn't_ specified last time, or the server contains files called
1977            *.orig, -N will be back to not operating correctly with -k. */
1978         {
1979           /* Would a single s[n]printf() call be faster?  --dan
1980
1981              Definitely not.  sprintf() is horribly slow.  It's a
1982              different question whether the difference between the two
1983              affects a program.  Usually I'd say "no", but at one
1984              point I profiled Wget, and found that a measurable and
1985              non-negligible amount of time was lost calling sprintf()
1986              in url.c.  Replacing sprintf with inline calls to
1987              strcpy() and number_to_string() made a difference.
1988              --hniksic */
1989           memcpy (filename_plus_orig_suffix, hs->local_file, filename_len);
1990           memcpy (filename_plus_orig_suffix + filename_len,
1991                   ".orig", sizeof (".orig"));
1992
1993           /* Try to stat() the .orig file. */
1994           if (stat (filename_plus_orig_suffix, &st) == 0)
1995             {
1996               local_dot_orig_file_exists = true;
1997               local_filename = filename_plus_orig_suffix;
1998             }
1999         }      
2000
2001       if (!local_dot_orig_file_exists)
2002         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
2003         if (stat (hs->local_file, &st) == 0)
2004           local_filename = hs->local_file;
2005
2006       if (local_filename != NULL)
2007         /* There was a local file, so we'll check later to see if the version
2008            the server has is the same version we already have, allowing us to
2009            skip a download. */
2010         {
2011           hs->orig_file_name = xstrdup (local_filename);
2012           hs->orig_file_size = st.st_size;
2013           hs->orig_file_tstamp = st.st_mtime;
2014 #ifdef WINDOWS
2015           /* Modification time granularity is 2 seconds for Windows, so
2016              increase local time by 1 second for later comparison. */
2017           ++hs->orig_file_tstamp;
2018 #endif
2019         }
2020     }
2021
2022   if (!opt.ignore_length
2023       && resp_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
2024     {
2025       wgint parsed;
2026       errno = 0;
2027       parsed = str_to_wgint (hdrval, NULL, 10);
2028       if (parsed == WGINT_MAX && errno == ERANGE)
2029         {
2030           /* Out of range.
2031              #### If Content-Length is out of range, it most likely
2032              means that the file is larger than 2G and that we're
2033              compiled without LFS.  In that case we should probably
2034              refuse to even attempt to download the file.  */
2035           contlen = -1;
2036         }
2037       else if (parsed < 0)
2038         {
2039           /* Negative Content-Length; nonsensical, so we can't
2040              assume any information about the content to receive. */
2041           contlen = -1;
2042         }
2043       else
2044         contlen = parsed;
2045     }
2046
2047   request_free (req);
2048
2049   hs->statcode = statcode;
2050   if (statcode == -1)
2051     hs->error = xstrdup (_("Malformed status line"));
2052   else if (!*message)
2053     hs->error = xstrdup (_("(no description)"));
2054   else
2055     hs->error = xstrdup (message);
2056   xfree_null (message);
2057
2058   type = resp_header_strdup (resp, "Content-Type");
2059   if (type)
2060     {
2061       char *tmp = strchr (type, ';');
2062       if (tmp)
2063         {
2064           while (tmp > type && c_isspace (tmp[-1]))
2065             --tmp;
2066           *tmp = '\0';
2067         }
2068     }
2069   hs->newloc = resp_header_strdup (resp, "Location");
2070   hs->remote_time = resp_header_strdup (resp, "Last-Modified");
2071
2072   /* Handle (possibly multiple instances of) the Set-Cookie header. */
2073   if (opt.cookies)
2074     {
2075       int scpos;
2076       const char *scbeg, *scend;
2077       /* The jar should have been created by now. */
2078       assert (wget_cookie_jar != NULL);
2079       for (scpos = 0;
2080            (scpos = resp_header_locate (resp, "Set-Cookie", scpos,
2081                                         &scbeg, &scend)) != -1;
2082            ++scpos)
2083         {
2084           char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
2085           cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port,
2086                                     u->path, set_cookie);
2087         }
2088     }
2089
2090   if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
2091     {
2092       wgint first_byte_pos, last_byte_pos, entity_length;
2093       if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
2094                                &entity_length))
2095         {
2096           contrange = first_byte_pos;
2097           contlen = last_byte_pos - first_byte_pos + 1;
2098         }
2099     }
2100   resp_free (resp);
2101
2102   /* 20x responses are counted among successful by default.  */
2103   if (H_20X (statcode))
2104     *dt |= RETROKF;
2105
2106   /* Return if redirected.  */
2107   if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
2108     {
2109       /* RFC2068 says that in case of the 300 (multiple choices)
2110          response, the server can output a preferred URL through
2111          `Location' header; otherwise, the request should be treated
2112          like GET.  So, if the location is set, it will be a
2113          redirection; otherwise, just proceed normally.  */
2114       if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
2115         *dt |= RETROKF;
2116       else
2117         {
2118           logprintf (LOG_VERBOSE,
2119                      _("Location: %s%s\n"),
2120                      hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
2121                      hs->newloc ? _(" [following]") : "");
2122           if (keep_alive && !head_only && skip_short_body (sock, contlen))
2123             CLOSE_FINISH (sock);
2124           else
2125             CLOSE_INVALIDATE (sock);
2126           xfree_null (type);
2127           xfree (head);
2128           return NEWLOCATION;
2129         }
2130     }
2131
2132   /* If content-type is not given, assume text/html.  This is because
2133      of the multitude of broken CGI's that "forget" to generate the
2134      content-type.  */
2135   if (!type ||
2136         0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)) ||
2137         0 == strncasecmp (type, TEXTXHTML_S, strlen (TEXTXHTML_S)))    
2138     *dt |= TEXTHTML;
2139   else
2140     *dt &= ~TEXTHTML;
2141
2142   if (type &&
2143       0 == strncasecmp (type, TEXTCSS_S, strlen (TEXTCSS_S)))
2144     *dt |= TEXTCSS;
2145   else
2146     *dt &= ~TEXTCSS;
2147
2148   if (opt.html_extension)
2149     {
2150       if (*dt & TEXTHTML)
2151         /* -E / --html-extension / html_extension = on was specified,
2152            and this is a text/html file.  If some case-insensitive
2153            variation on ".htm[l]" isn't already the file's suffix,
2154            tack on ".html". */
2155         {
2156           ensure_extension (hs, ".html", dt);
2157         }
2158       else if (*dt & TEXTCSS)
2159         {
2160           ensure_extension (hs, ".css", dt);
2161         }
2162     }
2163
2164   if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
2165       || (hs->restval > 0 && statcode == HTTP_STATUS_OK
2166           && contrange == 0 && hs->restval >= contlen)
2167      )
2168     {
2169       /* If `-c' is in use and the file has been fully downloaded (or
2170          the remote file has shrunk), Wget effectively requests bytes
2171          after the end of file and the server response with 416
2172          (or 200 with a <= Content-Length.  */
2173       logputs (LOG_VERBOSE, _("\
2174 \n    The file is already fully retrieved; nothing to do.\n\n"));
2175       /* In case the caller inspects. */
2176       hs->len = contlen;
2177       hs->res = 0;
2178       /* Mark as successfully retrieved. */
2179       *dt |= RETROKF;
2180       xfree_null (type);
2181       CLOSE_INVALIDATE (sock);        /* would be CLOSE_FINISH, but there
2182                                    might be more bytes in the body. */
2183       xfree (head);
2184       return RETRUNNEEDED;
2185     }
2186   if ((contrange != 0 && contrange != hs->restval)
2187       || (H_PARTIAL (statcode) && !contrange))
2188     {
2189       /* The Range request was somehow misunderstood by the server.
2190          Bail out.  */
2191       xfree_null (type);
2192       CLOSE_INVALIDATE (sock);
2193       xfree (head);
2194       return RANGEERR;
2195     }
2196   if (contlen == -1)
2197     hs->contlen = -1;
2198   else
2199     hs->contlen = contlen + contrange;
2200
2201   if (opt.verbose)
2202     {
2203       if (*dt & RETROKF)
2204         {
2205           /* No need to print this output if the body won't be
2206              downloaded at all, or if the original server response is
2207              printed.  */
2208           logputs (LOG_VERBOSE, _("Length: "));
2209           if (contlen != -1)
2210             {
2211               logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange));
2212               if (contlen + contrange >= 1024)
2213                 logprintf (LOG_VERBOSE, " (%s)",
2214                            human_readable (contlen + contrange));
2215               if (contrange)
2216                 {
2217                   if (contlen >= 1024)
2218                     logprintf (LOG_VERBOSE, _(", %s (%s) remaining"),
2219                                number_to_static_string (contlen),
2220                                human_readable (contlen));
2221                   else
2222                     logprintf (LOG_VERBOSE, _(", %s remaining"),
2223                                number_to_static_string (contlen));
2224                 }
2225             }
2226           else
2227             logputs (LOG_VERBOSE,
2228                      opt.ignore_length ? _("ignored") : _("unspecified"));
2229           if (type)
2230             logprintf (LOG_VERBOSE, " [%s]\n", quotearg_style (escape_quoting_style, type));
2231           else
2232             logputs (LOG_VERBOSE, "\n");
2233         }
2234     }
2235   xfree_null (type);
2236   type = NULL;                        /* We don't need it any more.  */
2237
2238   /* Return if we have no intention of further downloading.  */
2239   if (!(*dt & RETROKF) || head_only)
2240     {
2241       /* In case the caller cares to look...  */
2242       hs->len = 0;
2243       hs->res = 0;
2244       xfree_null (type);
2245       if (head_only)
2246         /* Pre-1.10 Wget used CLOSE_INVALIDATE here.  Now we trust the
2247            servers not to send body in response to a HEAD request, and
2248            those that do will likely be caught by test_socket_open.
2249            If not, they can be worked around using
2250            `--no-http-keep-alive'.  */
2251         CLOSE_FINISH (sock);
2252       else if (keep_alive && skip_short_body (sock, contlen))
2253         /* Successfully skipped the body; also keep using the socket. */
2254         CLOSE_FINISH (sock);
2255       else
2256         CLOSE_INVALIDATE (sock);
2257       xfree (head);
2258       return RETRFINISHED;
2259     }
2260
2261   /* Open the local file.  */
2262   if (!output_stream)
2263     {
2264       mkalldirs (hs->local_file);
2265       if (opt.backups)
2266         rotate_backups (hs->local_file);
2267       if (hs->restval)
2268         fp = fopen (hs->local_file, "ab");
2269       else if (ALLOW_CLOBBER)
2270         fp = fopen (hs->local_file, "wb");
2271       else
2272         {
2273           fp = fopen_excl (hs->local_file, true);
2274           if (!fp && errno == EEXIST)
2275             {
2276               /* We cannot just invent a new name and use it (which is
2277                  what functions like unique_create typically do)
2278                  because we told the user we'd use this name.
2279                  Instead, return and retry the download.  */
2280               logprintf (LOG_NOTQUIET,
2281                          _("%s has sprung into existence.\n"),
2282                          hs->local_file);
2283               CLOSE_INVALIDATE (sock);
2284               xfree (head);
2285               return FOPEN_EXCL_ERR;
2286             }
2287         }
2288       if (!fp)
2289         {
2290           logprintf (LOG_NOTQUIET, "%s: %s\n", hs->local_file, strerror (errno));
2291           CLOSE_INVALIDATE (sock);
2292           xfree (head);
2293           return FOPENERR;
2294         }
2295     }
2296   else
2297     fp = output_stream;
2298
2299   /* Print fetch message, if opt.verbose.  */
2300   if (opt.verbose)
2301     {
2302       logprintf (LOG_NOTQUIET, _("Saving to: %s\n"), 
2303                  HYPHENP (hs->local_file) ? quote ("STDOUT") : quote (hs->local_file));
2304     }
2305     
2306   /* This confuses the timestamping code that checks for file size.
2307      #### The timestamping code should be smarter about file size.  */
2308   if (opt.save_headers && hs->restval == 0)
2309     fwrite (head, 1, strlen (head), fp);
2310
2311   /* Now we no longer need to store the response header. */
2312   xfree (head);
2313
2314   /* Download the request body.  */
2315   flags = 0;
2316   if (contlen != -1)
2317     /* If content-length is present, read that much; otherwise, read
2318        until EOF.  The HTTP spec doesn't require the server to
2319        actually close the connection when it's done sending data. */
2320     flags |= rb_read_exactly;
2321   if (hs->restval > 0 && contrange == 0)
2322     /* If the server ignored our range request, instruct fd_read_body
2323        to skip the first RESTVAL bytes of body.  */
2324     flags |= rb_skip_startpos;
2325   hs->len = hs->restval;
2326   hs->rd_size = 0;
2327   hs->res = fd_read_body (sock, fp, contlen != -1 ? contlen : 0,
2328                           hs->restval, &hs->rd_size, &hs->len, &hs->dltime,
2329                           flags);
2330
2331   if (hs->res >= 0)
2332     CLOSE_FINISH (sock);
2333   else
2334     {
2335       if (hs->res < 0)
2336         hs->rderrmsg = xstrdup (fd_errstr (sock));
2337       CLOSE_INVALIDATE (sock);
2338     }
2339
2340   if (!output_stream)
2341     fclose (fp);
2342   if (hs->res == -2)
2343     return FWRITEERR;
2344   return RETRFINISHED;
2345 }
2346
2347 /* The genuine HTTP loop!  This is the part where the retrieval is
2348    retried, and retried, and retried, and...  */
2349 uerr_t
2350 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
2351            int *dt, struct url *proxy)
2352 {
2353   int count;
2354   bool got_head = false;         /* used for time-stamping and filename detection */
2355   bool time_came_from_head = false;
2356   bool got_name = false;
2357   char *tms;
2358   const char *tmrate;
2359   uerr_t err, ret = TRYLIMEXC;
2360   time_t tmr = -1;               /* remote time-stamp */
2361   struct http_stat hstat;        /* HTTP status */
2362   struct_stat st;  
2363   bool send_head_first = true;
2364   char *file_name;
2365
2366   /* Assert that no value for *LOCAL_FILE was passed. */
2367   assert (local_file == NULL || *local_file == NULL);
2368   
2369   /* Set LOCAL_FILE parameter. */
2370   if (local_file && opt.output_document)
2371     *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);
2372   
2373   /* Reset NEWLOC parameter. */
2374   *newloc = NULL;
2375
2376   /* This used to be done in main(), but it's a better idea to do it
2377      here so that we don't go through the hoops if we're just using
2378      FTP or whatever. */
2379   if (opt.cookies)
2380     load_cookies();
2381
2382   /* Warn on (likely bogus) wildcard usage in HTTP. */
2383   if (opt.ftp_glob && has_wildcards_p (u->path))
2384     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
2385
2386   /* Setup hstat struct. */
2387   xzero (hstat);
2388   hstat.referer = referer;
2389
2390   if (opt.output_document)
2391     {
2392       hstat.local_file = xstrdup (opt.output_document);
2393       got_name = true;
2394     }
2395   else if (!opt.content_disposition)
2396     {
2397       hstat.local_file = url_file_name (u);
2398       got_name = true;
2399     }
2400
2401   /* TODO: Ick! This code is now in both gethttp and http_loop, and is
2402    * screaming for some refactoring. */
2403   if (got_name && file_exists_p (hstat.local_file) && opt.noclobber && !opt.output_document)
2404     {
2405       /* If opt.noclobber is turned on and file already exists, do not
2406          retrieve the file. But if the output_document was given, then this
2407          test was already done and the file didn't exist. Hence the !opt.output_document */
2408       logprintf (LOG_VERBOSE, _("\
2409 File %s already there; not retrieving.\n\n"), 
2410                  quote (hstat.local_file));
2411       /* If the file is there, we suppose it's retrieved OK.  */
2412       *dt |= RETROKF;
2413
2414       /* #### Bogusness alert.  */
2415       /* If its suffix is "html" or "htm" or similar, assume text/html.  */
2416       if (has_html_suffix_p (hstat.local_file))
2417         *dt |= TEXTHTML;
2418
2419       ret = RETROK;
2420       goto exit;
2421     }
2422
2423   /* Reset the counter. */
2424   count = 0;
2425   
2426   /* Reset the document type. */
2427   *dt = 0;
2428   
2429   /* Skip preliminary HEAD request if we're not in spider mode AND
2430    * if -O was given or HTTP Content-Disposition support is disabled. */
2431   if (!opt.spider
2432       && (got_name || !opt.content_disposition))
2433     send_head_first = false;
2434
2435   /* Send preliminary HEAD request if -N is given and we have an existing 
2436    * destination file. */
2437   file_name = url_file_name (u);
2438   if (opt.timestamping 
2439       && !opt.content_disposition
2440       && file_exists_p (file_name))
2441     send_head_first = true;
2442   xfree (file_name);
2443   
2444   /* THE loop */
2445   do
2446     {
2447       /* Increment the pass counter.  */
2448       ++count;
2449       sleep_between_retrievals (count);
2450       
2451       /* Get the current time string.  */
2452       tms = datetime_str (time (NULL));
2453       
2454       if (opt.spider && !got_head)
2455         logprintf (LOG_VERBOSE, _("\
2456 Spider mode enabled. Check if remote file exists.\n"));
2457
2458       /* Print fetch message, if opt.verbose.  */
2459       if (opt.verbose)
2460         {
2461           char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD);
2462           
2463           if (count > 1) 
2464             {
2465               char tmp[256];
2466               sprintf (tmp, _("(try:%2d)"), count);
2467               logprintf (LOG_NOTQUIET, "--%s--  %s  %s\n",
2468                          tms, tmp, hurl);
2469             }
2470           else 
2471             {
2472               logprintf (LOG_NOTQUIET, "--%s--  %s\n",
2473                          tms, hurl);
2474             }
2475           
2476 #ifdef WINDOWS
2477           ws_changetitle (hurl);
2478 #endif
2479           xfree (hurl);
2480         }
2481
2482       /* Default document type is empty.  However, if spider mode is
2483          on or time-stamping is employed, HEAD_ONLY commands is
2484          encoded within *dt.  */
2485       if (send_head_first && !got_head) 
2486         *dt |= HEAD_ONLY;
2487       else
2488         *dt &= ~HEAD_ONLY;
2489
2490       /* Decide whether or not to restart.  */
2491       if (opt.always_rest
2492           && got_name
2493           && stat (hstat.local_file, &st) == 0
2494           && S_ISREG (st.st_mode))
2495         /* When -c is used, continue from on-disk size.  (Can't use
2496            hstat.len even if count>1 because we don't want a failed
2497            first attempt to clobber existing data.)  */
2498         hstat.restval = st.st_size;
2499       else if (count > 1)
2500         /* otherwise, continue where the previous try left off */
2501         hstat.restval = hstat.len;
2502       else
2503         hstat.restval = 0;
2504
2505       /* Decide whether to send the no-cache directive.  We send it in
2506          two cases:
2507            a) we're using a proxy, and we're past our first retrieval.
2508               Some proxies are notorious for caching incomplete data, so
2509               we require a fresh get.
2510            b) caching is explicitly inhibited. */
2511       if ((proxy && count > 1)        /* a */
2512           || !opt.allow_cache)        /* b */
2513         *dt |= SEND_NOCACHE;
2514       else
2515         *dt &= ~SEND_NOCACHE;
2516
2517       /* Try fetching the document, or at least its head.  */
2518       err = gethttp (u, &hstat, dt, proxy);
2519
2520       /* Time?  */
2521       tms = datetime_str (time (NULL));
2522       
2523       /* Get the new location (with or without the redirection).  */
2524       if (hstat.newloc)
2525         *newloc = xstrdup (hstat.newloc);
2526
2527       switch (err)
2528         {
2529         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
2530         case CONERROR: case READERR: case WRITEFAILED:
2531         case RANGEERR: case FOPEN_EXCL_ERR:
2532           /* Non-fatal errors continue executing the loop, which will
2533              bring them to "while" statement at the end, to judge
2534              whether the number of tries was exceeded.  */
2535           printwhat (count, opt.ntry);
2536           continue;
2537         case FWRITEERR: case FOPENERR:
2538           /* Another fatal error.  */
2539           logputs (LOG_VERBOSE, "\n");
2540           logprintf (LOG_NOTQUIET, _("Cannot write to %s (%s).\n"),
2541                      quote (hstat.local_file), strerror (errno));
2542         case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case AUTHFAILED: 
2543         case SSLINITFAILED: case CONTNOTSUPPORTED:
2544           /* Fatal errors just return from the function.  */
2545           ret = err;
2546           goto exit;
2547         case CONSSLERR:
2548           /* Another fatal error.  */
2549           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
2550           ret = err;
2551           goto exit;
2552         case NEWLOCATION:
2553           /* Return the new location to the caller.  */
2554           if (!*newloc)
2555             {
2556               logprintf (LOG_NOTQUIET,
2557                          _("ERROR: Redirection (%d) without location.\n"),
2558                          hstat.statcode);
2559               ret = WRONGCODE;
2560             }
2561           else 
2562             {
2563               ret = NEWLOCATION;
2564             }
2565           goto exit;
2566         case RETRUNNEEDED:
2567           /* The file was already fully retrieved. */
2568           ret = RETROK;
2569           goto exit;
2570         case RETRFINISHED:
2571           /* Deal with you later.  */
2572           break;
2573         default:
2574           /* All possibilities should have been exhausted.  */
2575           abort ();
2576         }
2577       
2578       if (!(*dt & RETROKF))
2579         {
2580           char *hurl = NULL;
2581           if (!opt.verbose)
2582             {
2583               /* #### Ugly ugly ugly! */
2584               hurl = url_string (u, URL_AUTH_HIDE_PASSWD);
2585               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
2586             }
2587
2588           /* Fall back to GET if HEAD fails with a 500 or 501 error code. */
2589           if (*dt & HEAD_ONLY
2590               && (hstat.statcode == 500 || hstat.statcode == 501))
2591             {
2592               got_head = true;
2593               continue;
2594             }
2595           /* Maybe we should always keep track of broken links, not just in
2596            * spider mode.  */
2597           else if (opt.spider)
2598             {
2599               /* #### Again: ugly ugly ugly! */
2600               if (!hurl) 
2601                 hurl = url_string (u, URL_AUTH_HIDE_PASSWD);
2602               nonexisting_url (hurl);
2603               logprintf (LOG_NOTQUIET, _("\
2604 Remote file does not exist -- broken link!!!\n"));
2605             }
2606           else
2607             {
2608               logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
2609                          tms, hstat.statcode, 
2610                          quotearg_style (escape_quoting_style, hstat.error));
2611             }
2612           logputs (LOG_VERBOSE, "\n");
2613           ret = WRONGCODE;
2614           xfree_null (hurl);
2615           goto exit;
2616         }
2617
2618       /* Did we get the time-stamp? */
2619       if (!got_head)
2620         {
2621           got_head = true;    /* no more time-stamping */
2622
2623           if (opt.timestamping && !hstat.remote_time)
2624             {
2625               logputs (LOG_NOTQUIET, _("\
2626 Last-modified header missing -- time-stamps turned off.\n"));
2627             }
2628           else if (hstat.remote_time)
2629             {
2630               /* Convert the date-string into struct tm.  */
2631               tmr = http_atotm (hstat.remote_time);
2632               if (tmr == (time_t) (-1))
2633                 logputs (LOG_VERBOSE, _("\
2634 Last-modified header invalid -- time-stamp ignored.\n"));
2635               if (*dt & HEAD_ONLY)
2636                 time_came_from_head = true;
2637             }
2638       
2639           if (send_head_first)
2640             {
2641               /* The time-stamping section.  */
2642               if (opt.timestamping)
2643                 {
2644                   if (hstat.orig_file_name) /* Perform the following
2645                                                checks only if the file
2646                                                we're supposed to
2647                                                download already exists.  */
2648                     {
2649                       if (hstat.remote_time && 
2650                           tmr != (time_t) (-1))
2651                         {
2652                           /* Now time-stamping can be used validly.
2653                              Time-stamping means that if the sizes of
2654                              the local and remote file match, and local
2655                              file is newer than the remote file, it will
2656                              not be retrieved.  Otherwise, the normal
2657                              download procedure is resumed.  */
2658                           if (hstat.orig_file_tstamp >= tmr)
2659                             {
2660                               if (hstat.contlen == -1 
2661                                   || hstat.orig_file_size == hstat.contlen)
2662                                 {
2663                                   logprintf (LOG_VERBOSE, _("\
2664 Server file no newer than local file %s -- not retrieving.\n\n"),
2665                                              quote (hstat.orig_file_name));
2666                                   ret = RETROK;
2667                                   goto exit;
2668                                 }
2669                               else
2670                                 {
2671                                   logprintf (LOG_VERBOSE, _("\
2672 The sizes do not match (local %s) -- retrieving.\n"),
2673                                              number_to_static_string (hstat.orig_file_size));
2674                                 }
2675                             }
2676                           else
2677                             logputs (LOG_VERBOSE,
2678                                      _("Remote file is newer, retrieving.\n"));
2679
2680                           logputs (LOG_VERBOSE, "\n");
2681                         }
2682                     }
2683                   
2684                   /* free_hstat (&hstat); */
2685                   hstat.timestamp_checked = true;
2686                 }
2687               
2688               if (opt.spider)
2689                 {
2690                   bool finished = true;
2691                   if (opt.recursive)
2692                     {
2693                       if (*dt & TEXTHTML)
2694                         {
2695                           logputs (LOG_VERBOSE, _("\
2696 Remote file exists and could contain links to other resources -- retrieving.\n\n"));
2697                           finished = false;
2698                         }
2699                       else 
2700                         {
2701                           logprintf (LOG_VERBOSE, _("\
2702 Remote file exists but does not contain any link -- not retrieving.\n\n"));
2703                           ret = RETROK; /* RETRUNNEEDED is not for caller. */
2704                         }
2705                     }
2706                   else
2707                     {
2708                       if (*dt & TEXTHTML)
2709                         {
2710                           logprintf (LOG_VERBOSE, _("\
2711 Remote file exists and could contain further links,\n\
2712 but recursion is disabled -- not retrieving.\n\n"));
2713                         }
2714                       else 
2715                         {
2716                           logprintf (LOG_VERBOSE, _("\
2717 Remote file exists.\n\n"));
2718                         }
2719                       ret = RETROK; /* RETRUNNEEDED is not for caller. */
2720                     }
2721                   
2722                   if (finished)
2723                     {
2724                       logprintf (LOG_NONVERBOSE, 
2725                                  _("%s URL:%s %2d %s\n"), 
2726                                  tms, u->url, hstat.statcode,
2727                                  hstat.message ? quotearg_style (escape_quoting_style, hstat.message) : "");
2728                       goto exit;
2729                     }
2730                 }
2731
2732               got_name = true;
2733               *dt &= ~HEAD_ONLY;
2734               count = 0;          /* the retrieve count for HEAD is reset */
2735               continue;
2736             } /* send_head_first */
2737         } /* !got_head */
2738           
2739       if ((tmr != (time_t) (-1))
2740           && ((hstat.len == hstat.contlen) ||
2741               ((hstat.res == 0) && (hstat.contlen == -1))))
2742         {
2743           const char *fl = NULL;
2744           set_local_file (&fl, hstat.local_file);
2745           if (fl)
2746             {
2747               time_t newtmr = -1;
2748               /* Reparse time header, in case it's changed. */
2749               if (time_came_from_head
2750                   && hstat.remote_time && hstat.remote_time[0])
2751                 {
2752                   newtmr = http_atotm (hstat.remote_time);
2753                   if (newtmr != -1)
2754                     tmr = newtmr;
2755                 }
2756               touch (fl, tmr);
2757             }
2758         }
2759       /* End of time-stamping section. */
2760
2761       tmrate = retr_rate (hstat.rd_size, hstat.dltime);
2762       total_download_time += hstat.dltime;
2763
2764       if (hstat.len == hstat.contlen)
2765         {
2766           if (*dt & RETROKF)
2767             {
2768               bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document));
2769
2770               logprintf (LOG_VERBOSE,
2771                          write_to_stdout 
2772                          ? _("%s (%s) - written to stdout %s[%s/%s]\n\n")
2773                          : _("%s (%s) - %s saved [%s/%s]\n\n"),
2774                          tms, tmrate,
2775                          write_to_stdout ? "" : quote (hstat.local_file),
2776                          number_to_static_string (hstat.len),
2777                          number_to_static_string (hstat.contlen));
2778               logprintf (LOG_NONVERBOSE,
2779                          "%s URL:%s [%s/%s] -> \"%s\" [%d]\n",
2780                          tms, u->url,
2781                          number_to_static_string (hstat.len),
2782                          number_to_static_string (hstat.contlen),
2783                          hstat.local_file, count);
2784             }
2785           ++numurls;
2786           total_downloaded_bytes += hstat.len;
2787
2788           /* Remember that we downloaded the file for later ".orig" code. */
2789           if (*dt & ADDED_HTML_EXTENSION)
2790             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file);
2791           else
2792             downloaded_file(FILE_DOWNLOADED_NORMALLY, hstat.local_file);
2793
2794           ret = RETROK;
2795           goto exit;
2796         }
2797       else if (hstat.res == 0) /* No read error */
2798         {
2799           if (hstat.contlen == -1)  /* We don't know how much we were supposed
2800                                        to get, so assume we succeeded. */ 
2801             {
2802               if (*dt & RETROKF)
2803                 {
2804                   bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document));
2805
2806                   logprintf (LOG_VERBOSE,
2807                              write_to_stdout
2808                              ? _("%s (%s) - written to stdout %s[%s]\n\n")
2809                              : _("%s (%s) - %s saved [%s]\n\n"),
2810                              tms, tmrate, 
2811                              write_to_stdout ? "" : quote (hstat.local_file),
2812                              number_to_static_string (hstat.len));
2813                   logprintf (LOG_NONVERBOSE,
2814                              "%s URL:%s [%s] -> \"%s\" [%d]\n",
2815                              tms, u->url, number_to_static_string (hstat.len),
2816                              hstat.local_file, count);
2817                 }
2818               ++numurls;
2819               total_downloaded_bytes += hstat.len;
2820
2821               /* Remember that we downloaded the file for later ".orig" code. */
2822               if (*dt & ADDED_HTML_EXTENSION)
2823                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, hstat.local_file);
2824               else
2825                 downloaded_file(FILE_DOWNLOADED_NORMALLY, hstat.local_file);
2826               
2827               ret = RETROK;
2828               goto exit;
2829             }
2830           else if (hstat.len < hstat.contlen) /* meaning we lost the
2831                                                  connection too soon */
2832             {
2833               logprintf (LOG_VERBOSE,
2834                          _("%s (%s) - Connection closed at byte %s. "),
2835                          tms, tmrate, number_to_static_string (hstat.len));
2836               printwhat (count, opt.ntry);
2837               continue;
2838             }
2839           else if (hstat.len != hstat.restval)
2840             /* Getting here would mean reading more data than
2841                requested with content-length, which we never do.  */
2842             abort ();
2843           else
2844             {
2845               /* Getting here probably means that the content-length was
2846                * _less_ than the original, local size. We should probably
2847                * truncate or re-read, or something. FIXME */
2848               ret = RETROK;
2849               goto exit;
2850             }
2851         }
2852       else /* from now on hstat.res can only be -1 */
2853         {
2854           if (hstat.contlen == -1)
2855             {
2856               logprintf (LOG_VERBOSE,
2857                          _("%s (%s) - Read error at byte %s (%s)."),
2858                          tms, tmrate, number_to_static_string (hstat.len),
2859                          hstat.rderrmsg);
2860               printwhat (count, opt.ntry);
2861               continue;
2862             }
2863           else /* hstat.res == -1 and contlen is given */
2864             {
2865               logprintf (LOG_VERBOSE,
2866                          _("%s (%s) - Read error at byte %s/%s (%s). "),
2867                          tms, tmrate,
2868                          number_to_static_string (hstat.len),
2869                          number_to_static_string (hstat.contlen),
2870                          hstat.rderrmsg);
2871               printwhat (count, opt.ntry);
2872               continue;
2873             }
2874         }
2875       /* not reached */
2876     }
2877   while (!opt.ntry || (count < opt.ntry));
2878
2879 exit:
2880   if (ret == RETROK) 
2881     *local_file = xstrdup (hstat.local_file);
2882   free_hstat (&hstat);
2883   
2884   return ret;
2885 }
2886 \f
2887 /* Check whether the result of strptime() indicates success.
2888    strptime() returns the pointer to how far it got to in the string.
2889    The processing has been successful if the string is at `GMT' or
2890    `+X', or at the end of the string.
2891
2892    In extended regexp parlance, the function returns 1 if P matches
2893    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (which strptime
2894    can return) is considered a failure and 0 is returned.  */
2895 static bool
2896 check_end (const char *p)
2897 {
2898   if (!p)
2899     return false;
2900   while (c_isspace (*p))
2901     ++p;
2902   if (!*p
2903       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2904       || ((p[0] == '+' || p[0] == '-') && c_isdigit (p[1])))
2905     return true;
2906   else
2907     return false;
2908 }
2909
2910 /* Convert the textual specification of time in TIME_STRING to the
2911    number of seconds since the Epoch.
2912
2913    TIME_STRING can be in any of the three formats RFC2616 allows the
2914    HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date,
2915    as well as the time format used in the Set-Cookie header.
2916    Timezones are ignored, and should be GMT.
2917
2918    Return the computed time_t representation, or -1 if the conversion
2919    fails.
2920
2921    This function uses strptime with various string formats for parsing
2922    TIME_STRING.  This results in a parser that is not as lenient in
2923    interpreting TIME_STRING as I would like it to be.  Being based on
2924    strptime, it always allows shortened months, one-digit days, etc.,
2925    but due to the multitude of formats in which time can be
2926    represented, an ideal HTTP time parser would be even more
2927    forgiving.  It should completely ignore things like week days and
2928    concentrate only on the various forms of representing years,
2929    months, days, hours, minutes, and seconds.  For example, it would
2930    be nice if it accepted ISO 8601 out of the box.
2931
2932    I've investigated free and PD code for this purpose, but none was
2933    usable.  getdate was big and unwieldy, and had potential copyright
2934    issues, or so I was informed.  Dr. Marcus Hennecke's atotm(),
2935    distributed with phttpd, is excellent, but we cannot use it because
2936    it is not assigned to the FSF.  So I stuck it with strptime.  */
2937
2938 time_t
2939 http_atotm (const char *time_string)
2940 {
2941   /* NOTE: Solaris strptime man page claims that %n and %t match white
2942      space, but that's not universally available.  Instead, we simply
2943      use ` ' to mean "skip all WS", which works under all strptime
2944      implementations I've tested.  */
2945
2946   static const char *time_formats[] = {
2947     "%a, %d %b %Y %T",          /* rfc1123: Thu, 29 Jan 1998 22:12:57 */
2948     "%A, %d-%b-%y %T",          /* rfc850:  Thursday, 29-Jan-98 22:12:57 */
2949     "%a %b %d %T %Y",           /* asctime: Thu Jan 29 22:12:57 1998 */
2950     "%a, %d-%b-%Y %T"           /* cookies: Thu, 29-Jan-1998 22:12:57
2951                                    (used in Set-Cookie, defined in the
2952                                    Netscape cookie specification.) */
2953   };
2954   const char *oldlocale;
2955   char savedlocale[256];
2956   size_t i;
2957   time_t ret = (time_t) -1;
2958
2959   /* Solaris strptime fails to recognize English month names in
2960      non-English locales, which we work around by temporarily setting
2961      locale to C before invoking strptime.  */
2962   oldlocale = setlocale (LC_TIME, NULL);
2963   if (oldlocale)
2964     {
2965       size_t l = strlen (oldlocale);
2966       if (l >= sizeof savedlocale)
2967         savedlocale[0] = '\0';
2968       else
2969         memcpy (savedlocale, oldlocale, l);
2970     }
2971   else savedlocale[0] = '\0';
2972
2973   setlocale (LC_TIME, "C");
2974
2975   for (i = 0; i < countof (time_formats); i++)
2976     {
2977       struct tm t;
2978
2979       /* Some versions of strptime use the existing contents of struct
2980          tm to recalculate the date according to format.  Zero it out
2981          to prevent stack garbage from influencing strptime.  */
2982       xzero (t);
2983
2984       if (check_end (strptime (time_string, time_formats[i], &t)))
2985         {
2986           ret = timegm (&t);
2987           break;
2988         }
2989     }
2990
2991   /* Restore the previous locale. */
2992   if (savedlocale[0])
2993     setlocale (LC_TIME, savedlocale);
2994
2995   return ret;
2996 }
2997 \f
2998 /* Authorization support: We support three authorization schemes:
2999
3000    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
3001
3002    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
3003    consisting of answering to the server's challenge with the proper
3004    MD5 digests.
3005
3006    * `NTLM' ("NT Lan Manager") scheme, based on code written by Daniel
3007    Stenberg for libcurl.  Like digest, NTLM is based on a
3008    challenge-response mechanism, but unlike digest, it is non-standard
3009    (authenticates TCP connections rather than requests), undocumented
3010    and Microsoft-specific.  */
3011
3012 /* Create the authentication header contents for the `Basic' scheme.
3013    This is done by encoding the string "USER:PASS" to base64 and
3014    prepending the string "Basic " in front of it.  */
3015
3016 static char *
3017 basic_authentication_encode (const char *user, const char *passwd)
3018 {
3019   char *t1, *t2;
3020   int len1 = strlen (user) + 1 + strlen (passwd);
3021
3022   t1 = (char *)alloca (len1 + 1);
3023   sprintf (t1, "%s:%s", user, passwd);
3024
3025   t2 = (char *)alloca (BASE64_LENGTH (len1) + 1);
3026   base64_encode (t1, len1, t2);
3027
3028   return concat_strings ("Basic ", t2, (char *) 0);
3029 }
3030
3031 #define SKIP_WS(x) do {                         \
3032   while (c_isspace (*(x)))                        \
3033     ++(x);                                      \
3034 } while (0)
3035
3036 #ifdef ENABLE_DIGEST
3037 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
3038    an array of 16 bytes containing the hash keys, and BUF should be a
3039    buffer of 33 writable characters (32 for hex digits plus one for
3040    zero termination).  */
3041 static void
3042 dump_hash (char *buf, const unsigned char *hash)
3043 {
3044   int i;
3045
3046   for (i = 0; i < MD5_HASHLEN; i++, hash++)
3047     {
3048       *buf++ = XNUM_TO_digit (*hash >> 4);
3049       *buf++ = XNUM_TO_digit (*hash & 0xf);
3050     }
3051   *buf = '\0';
3052 }
3053
3054 /* Take the line apart to find the challenge, and compose a digest
3055    authorization header.  See RFC2069 section 2.1.2.  */
3056 static char *
3057 digest_authentication_encode (const char *au, const char *user,
3058                               const char *passwd, const char *method,
3059                               const char *path)
3060 {
3061   static char *realm, *opaque, *nonce;
3062   static struct {
3063     const char *name;
3064     char **variable;
3065   } options[] = {
3066     { "realm", &realm },
3067     { "opaque", &opaque },
3068     { "nonce", &nonce }
3069   };
3070   char *res;
3071   param_token name, value;
3072
3073   realm = opaque = nonce = NULL;
3074
3075   au += 6;                      /* skip over `Digest' */
3076   while (extract_param (&au, &name, &value, ','))
3077     {
3078       size_t i;
3079       size_t namelen = name.e - name.b;
3080       for (i = 0; i < countof (options); i++)
3081         if (namelen == strlen (options[i].name)
3082             && 0 == strncmp (name.b, options[i].name,
3083                              namelen))
3084           {
3085             *options[i].variable = strdupdelim (value.b, value.e);
3086             break;
3087           }
3088     }
3089   if (!realm || !nonce || !user || !passwd || !path || !method)
3090     {
3091       xfree_null (realm);
3092       xfree_null (opaque);
3093       xfree_null (nonce);
3094       return NULL;
3095     }
3096
3097   /* Calculate the digest value.  */
3098   {
3099     ALLOCA_MD5_CONTEXT (ctx);
3100     unsigned char hash[MD5_HASHLEN];
3101     char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
3102     char response_digest[MD5_HASHLEN * 2 + 1];
3103
3104     /* A1BUF = H(user ":" realm ":" password) */
3105     gen_md5_init (ctx);
3106     gen_md5_update ((unsigned char *)user, strlen (user), ctx);
3107     gen_md5_update ((unsigned char *)":", 1, ctx);
3108     gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
3109     gen_md5_update ((unsigned char *)":", 1, ctx);
3110     gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
3111     gen_md5_finish (ctx, hash);
3112     dump_hash (a1buf, hash);
3113
3114     /* A2BUF = H(method ":" path) */
3115     gen_md5_init (ctx);
3116     gen_md5_update ((unsigned char *)method, strlen (method), ctx);
3117     gen_md5_update ((unsigned char *)":", 1, ctx);
3118     gen_md5_update ((unsigned char *)path, strlen (path), ctx);
3119     gen_md5_finish (ctx, hash);
3120     dump_hash (a2buf, hash);
3121
3122     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
3123     gen_md5_init (ctx);
3124     gen_md5_update ((unsigned char *)a1buf, MD5_HASHLEN * 2, ctx);
3125     gen_md5_update ((unsigned char *)":", 1, ctx);
3126     gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
3127     gen_md5_update ((unsigned char *)":", 1, ctx);
3128     gen_md5_update ((unsigned char *)a2buf, MD5_HASHLEN * 2, ctx);
3129     gen_md5_finish (ctx, hash);
3130     dump_hash (response_digest, hash);
3131
3132     res = xmalloc (strlen (user)
3133                    + strlen (user)
3134                    + strlen (realm)
3135                    + strlen (nonce)
3136                    + strlen (path)
3137                    + 2 * MD5_HASHLEN /*strlen (response_digest)*/
3138                    + (opaque ? strlen (opaque) : 0)
3139                    + 128);
3140     sprintf (res, "Digest \
3141 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
3142              user, realm, nonce, path, response_digest);
3143     if (opaque)
3144       {
3145         char *p = res + strlen (res);
3146         strcat (p, ", opaque=\"");
3147         strcat (p, opaque);
3148         strcat (p, "\"");
3149       }
3150   }
3151   return res;
3152 }
3153 #endif /* ENABLE_DIGEST */
3154
3155 /* Computing the size of a string literal must take into account that
3156    value returned by sizeof includes the terminating \0.  */
3157 #define STRSIZE(literal) (sizeof (literal) - 1)
3158
3159 /* Whether chars in [b, e) begin with the literal string provided as
3160    first argument and are followed by whitespace or terminating \0.
3161    The comparison is case-insensitive.  */
3162 #define STARTS(literal, b, e)                           \
3163   ((e > b) \
3164    && ((size_t) ((e) - (b))) >= STRSIZE (literal)   \
3165    && 0 == strncasecmp (b, literal, STRSIZE (literal))  \
3166    && ((size_t) ((e) - (b)) == STRSIZE (literal)          \
3167        || c_isspace (b[STRSIZE (literal)])))
3168
3169 static bool
3170 known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
3171 {
3172   return STARTS ("Basic", hdrbeg, hdrend)
3173 #ifdef ENABLE_DIGEST
3174     || STARTS ("Digest", hdrbeg, hdrend)
3175 #endif
3176 #ifdef ENABLE_NTLM
3177     || STARTS ("NTLM", hdrbeg, hdrend)
3178 #endif
3179     ;
3180 }
3181
3182 #undef STARTS
3183
3184 /* Create the HTTP authorization request header.  When the
3185    `WWW-Authenticate' response header is seen, according to the
3186    authorization scheme specified in that header (`Basic' and `Digest'
3187    are supported by the current implementation), produce an
3188    appropriate HTTP authorization request header.  */
3189 static char *
3190 create_authorization_line (const char *au, const char *user,
3191                            const char *passwd, const char *method,
3192                            const char *path, bool *finished)
3193 {
3194   /* We are called only with known schemes, so we can dispatch on the
3195      first letter. */
3196   switch (c_toupper (*au))
3197     {
3198     case 'B':                   /* Basic */
3199       *finished = true;
3200       return basic_authentication_encode (user, passwd);
3201 #ifdef ENABLE_DIGEST
3202     case 'D':                   /* Digest */
3203       *finished = true;
3204       return digest_authentication_encode (au, user, passwd, method, path);
3205 #endif
3206 #ifdef ENABLE_NTLM
3207     case 'N':                   /* NTLM */
3208       if (!ntlm_input (&pconn.ntlm, au))
3209         {
3210           *finished = true;
3211           return NULL;
3212         }
3213       return ntlm_output (&pconn.ntlm, user, passwd, finished);
3214 #endif
3215     default:
3216       /* We shouldn't get here -- this function should be only called
3217          with values approved by known_authentication_scheme_p.  */
3218       abort ();
3219     }
3220 }
3221 \f
3222 static void
3223 load_cookies (void)
3224 {
3225   if (!wget_cookie_jar)
3226     wget_cookie_jar = cookie_jar_new ();
3227   if (opt.cookies_input && !cookies_loaded_p)
3228     {
3229       cookie_jar_load (wget_cookie_jar, opt.cookies_input);
3230       cookies_loaded_p = true;
3231     }
3232 }
3233
3234 void
3235 save_cookies (void)
3236 {
3237   if (wget_cookie_jar)
3238     cookie_jar_save (wget_cookie_jar, opt.cookies_output);
3239 }
3240
3241 void
3242 http_cleanup (void)
3243 {
3244   xfree_null (pconn.host);
3245   if (wget_cookie_jar)
3246     cookie_jar_delete (wget_cookie_jar);
3247 }
3248
3249 void
3250 ensure_extension (struct http_stat *hs, const char *ext, int *dt)
3251 {
3252   char *last_period_in_local_filename = strrchr (hs->local_file, '.');
3253   char shortext[8];
3254   int len = strlen (ext);
3255   if (len == 5)
3256     {
3257       strncpy (shortext, ext, len - 1);
3258       shortext[len - 2] = '\0';
3259     }
3260
3261   if (last_period_in_local_filename == NULL
3262       || !(0 == strcasecmp (last_period_in_local_filename, shortext)
3263            || 0 == strcasecmp (last_period_in_local_filename, ext)))
3264     {
3265       int local_filename_len = strlen (hs->local_file);
3266       /* Resize the local file, allowing for ".html" preceded by
3267          optional ".NUMBER".  */
3268       hs->local_file = xrealloc (hs->local_file,
3269                                  local_filename_len + 24 + len);
3270       strcpy (hs->local_file + local_filename_len, ext);
3271       /* If clobbering is not allowed and the file, as named,
3272          exists, tack on ".NUMBER.html" instead. */
3273       if (!ALLOW_CLOBBER && file_exists_p (hs->local_file))
3274         {
3275           int ext_num = 1;
3276           do
3277             sprintf (hs->local_file + local_filename_len,
3278                      ".%d%s", ext_num++, ext);
3279           while (file_exists_p (hs->local_file));
3280         }
3281       *dt |= ADDED_HTML_EXTENSION;
3282     }
3283 }
3284
3285
3286 #ifdef TESTING
3287
3288 const char *
3289 test_parse_content_disposition()
3290 {
3291   int i;
3292   struct {
3293     char *hdrval;    
3294     char *opt_dir_prefix;
3295     char *filename;
3296     bool result;
3297   } test_array[] = {
3298     { "filename=\"file.ext\"", NULL, "file.ext", true },
3299     { "filename=\"file.ext\"", "somedir", "somedir/file.ext", true },
3300     { "attachment; filename=\"file.ext\"", NULL, "file.ext", true },
3301     { "attachment; filename=\"file.ext\"", "somedir", "somedir/file.ext", true },
3302     { "attachment; filename=\"file.ext\"; dummy", NULL, "file.ext", true },
3303     { "attachment; filename=\"file.ext\"; dummy", "somedir", "somedir/file.ext", true },
3304     { "attachment", NULL, NULL, false },
3305     { "attachment", "somedir", NULL, false },
3306   };
3307   
3308   for (i = 0; i < sizeof(test_array)/sizeof(test_array[0]); ++i) 
3309     {
3310       char *filename;
3311       bool res;
3312
3313       opt.dir_prefix = test_array[i].opt_dir_prefix;
3314       res = parse_content_disposition (test_array[i].hdrval, &filename);
3315
3316       mu_assert ("test_parse_content_disposition: wrong result", 
3317                  res == test_array[i].result
3318                  && (res == false 
3319                      || 0 == strcmp (test_array[i].filename, filename)));
3320     }
3321
3322   return NULL;
3323 }
3324
3325 #endif /* TESTING */
3326
3327 /*
3328  * vim: et sts=2 sw=2 cino+={s
3329  */
3330