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