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