]> sjero.net Git - wget/blobdiff - src/http.c
[svn] When the download is finished, print the time the download took.
[wget] / src / http.c
index 5562b037159dd09899fdda89484b06fe1aea8d65..1a276e66a3b7c869f219d76b517ebc484cf4ce8d 100644 (file)
@@ -31,30 +31,13 @@ so, delete this exception statement from your version.  */
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <sys/types.h>
-#ifdef HAVE_STRING_H
-# include <string.h>
-#else
-# include <strings.h>
-#endif
+#include <string.h>
 #ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #endif
 #include <assert.h>
 #include <errno.h>
-#if TIME_WITH_SYS_TIME
-# include <sys/time.h>
-# include <time.h>
-#else
-# if HAVE_SYS_TIME_H
-#  include <sys/time.h>
-# else
-#  include <time.h>
-# endif
-#endif
-#ifndef errno
-extern int errno;
-#endif
+#include <time.h>
 
 #include "wget.h"
 #include "utils.h"
@@ -76,17 +59,16 @@ extern int errno;
 #include "convert.h"
 
 extern char *version_string;
-extern LARGE_INT total_downloaded_bytes;
 
 extern FILE *output_stream;
-extern int output_stream_regular;
+extern bool output_stream_regular;
 
 #ifndef MIN
 # define MIN(x, y) ((x) > (y) ? (y) : (x))
 #endif
 
 \f
-static int cookies_loaded_p;
+static bool cookies_loaded_p;
 static struct cookie_jar *wget_cookie_jar;
 
 #define TEXTHTML_S "text/html"
@@ -148,7 +130,7 @@ struct request {
    called before the request can be used.  */
 
 static struct request *
-request_new ()
+request_new (void)
 {
   struct request *req = xnew0 (struct request);
   req->hcapacity = 8;
@@ -289,10 +271,10 @@ request_set_user_header (struct request *req, const char *header)
   request_set_header (req, xstrdup (name), (char *) p, rel_name);
 }
 
-/* Remove the header with specified name from REQ.  Returns 1 if the
-   header was actually removed, 0 otherwise.  */
+/* Remove the header with specified name from REQ.  Returns true if
+   the header was actually removed, false otherwise.  */
 
-static int
+static bool
 request_remove_header (struct request *req, char *name)
 {
   int i;
@@ -306,10 +288,10 @@ request_remove_header (struct request *req, char *name)
          if (i < req->hcount - 1)
            memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr));
          --req->hcount;
-         return 1;
+         return true;
        }
     }
-  return 0;
+  return false;
 }
 
 #define APPEND(p, str) do {                    \
@@ -368,7 +350,7 @@ request_send (const struct request *req, int fd)
 
   /* Send the request to the server. */
 
-  write_error = fd_write (fd, request_string, size - 1, -1.0);
+  write_error = fd_write (fd, request_string, size - 1, -1);
   if (write_error < 0)
     logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
               strerror (errno));
@@ -412,7 +394,7 @@ post_file (int sock, const char *file_name, wgint promised_size)
       if (length == 0)
        break;
       towrite = MIN (promised_size - written, length);
-      write_error = fd_write (sock, chunk, towrite, -1.0);
+      write_error = fd_write (sock, chunk, towrite, -1);
       if (write_error < 0)
        {
          fclose (fp);
@@ -617,12 +599,12 @@ resp_header_locate (const struct response *resp, const char *name, int start,
 
 /* Find and retrieve the header named NAME in the request data.  If
    found, set *BEGPTR to its starting, and *ENDPTR to its ending
-   position, and return 1.  Otherwise return 0.
+   position, and return true.  Otherwise return false.
 
    This function is used as a building block for resp_header_copy
    and resp_header_strdup.  */
 
-static int
+static bool
 resp_header_get (const struct response *resp, const char *name,
                 const char **begptr, const char **endptr)
 {
@@ -632,26 +614,26 @@ resp_header_get (const struct response *resp, const char *name,
 
 /* Copy the response header named NAME to buffer BUF, no longer than
    BUFSIZE (BUFSIZE includes the terminating 0).  If the header
-   exists, 1 is returned, otherwise 0.  If there should be no limit on
-   the size of the header, use resp_header_strdup instead.
+   exists, true is returned, false otherwise.  If there should be no
+   limit on the size of the header, use resp_header_strdup instead.
 
    If BUFSIZE is 0, no data is copied, but the boolean indication of
    whether the header is present is still returned.  */
 
-static int
+static bool
 resp_header_copy (const struct response *resp, const char *name,
                  char *buf, int bufsize)
 {
   const char *b, *e;
   if (!resp_header_get (resp, name, &b, &e))
-    return 0;
+    return false;
   if (bufsize)
     {
       int len = MIN (e - b, bufsize - 1);
       memcpy (buf, b, len);
       buf[len] = '\0';
     }
-  return 1;
+  return true;
 }
 
 /* Return the value of header named NAME in RESP, allocated with
@@ -766,8 +748,8 @@ print_server_response (const struct response *resp, const char *prefix)
 }
 
 /* Parse the `Content-Range' header and extract the information it
-   contains.  Returns 1 if successful, -1 otherwise.  */
-static int
+   contains.  Returns true if successful, false otherwise.  */
+static bool
 parse_content_range (const char *hdr, wgint *first_byte_ptr,
                     wgint *last_byte_ptr, wgint *entity_length_ptr)
 {
@@ -776,7 +758,7 @@ parse_content_range (const char *hdr, wgint *first_byte_ptr,
   /* Ancient versions of Netscape proxy server, presumably predating
      rfc2068, sent out `Content-Range' without the "bytes"
      specifier.  */
-  if (!strncasecmp (hdr, "bytes", 5))
+  if (0 == strncasecmp (hdr, "bytes", 5))
     {
       hdr += 5;
       /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
@@ -786,26 +768,26 @@ parse_content_range (const char *hdr, wgint *first_byte_ptr,
       while (ISSPACE (*hdr))
        ++hdr;
       if (!*hdr)
-       return 0;
+       return false;
     }
   if (!ISDIGIT (*hdr))
-    return 0;
+    return false;
   for (num = 0; ISDIGIT (*hdr); hdr++)
     num = 10 * num + (*hdr - '0');
   if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
-    return 0;
+    return false;
   *first_byte_ptr = num;
   ++hdr;
   for (num = 0; ISDIGIT (*hdr); hdr++)
     num = 10 * num + (*hdr - '0');
   if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
-    return 0;
+    return false;
   *last_byte_ptr = num;
   ++hdr;
   for (num = 0; ISDIGIT (*hdr); hdr++)
     num = 10 * num + (*hdr - '0');
   *entity_length_ptr = num;
-  return 1;
+  return true;
 }
 
 /* Read the body of the request, but don't store it anywhere and don't
@@ -814,10 +796,10 @@ parse_content_range (const char *hdr, wgint *first_byte_ptr,
    request.  The response is not useful to the user, but reading it
    allows us to continue using the same connection to the server.
 
-   If reading fails, 0 is returned, non-zero otherwise.  In debug
+   If reading fails, false is returned, true otherwise.  In debug
    mode, the body is displayed for debugging purposes.  */
 
-static int
+static bool
 skip_short_body (int fd, wgint contlen)
 {
   enum {
@@ -834,20 +816,20 @@ skip_short_body (int fd, wgint contlen)
   /* If the body is too large, it makes more sense to simply close the
      connection than to try to read the body.  */
   if (contlen > SKIP_THRESHOLD)
-    return 0;
+    return false;
 
   DEBUGP (("Skipping %s bytes of body: [", number_to_static_string (contlen)));
 
   while (contlen > 0)
     {
-      int ret = fd_read (fd, dlbuf, MIN (contlen, SKIP_SIZE), -1.0);
+      int ret = fd_read (fd, dlbuf, MIN (contlen, SKIP_SIZE), -1);
       if (ret <= 0)
        {
          /* Don't normally report the error since this is an
             optimization that should be invisible to the user.  */
          DEBUGP (("] aborting (%s).\n",
                   ret < 0 ? strerror (errno) : "EOF received"));
-         return 0;
+         return false;
        }
       contlen -= ret;
       /* Safe even if %.*s bogusly expects terminating \0 because
@@ -856,7 +838,7 @@ skip_short_body (int fd, wgint contlen)
     }
 
   DEBUGP (("] done.\n"));
-  return 1;
+  return true;
 }
 \f
 /* Persistent connections.  Currently, we cache the most recently used
@@ -866,7 +848,7 @@ skip_short_body (int fd, wgint contlen)
    number of these connections.  */
 
 /* Whether a persistent connection is active. */
-static int pconn_active;
+static bool pconn_active;
 
 static struct {
   /* The socket of the connection.  */
@@ -877,13 +859,13 @@ static struct {
   int port;
 
   /* Whether a ssl handshake has occoured on this connection.  */
-  int ssl;
+  bool ssl;
 
   /* Whether the connection was authorized.  This is only done by
      NTLM, which authorizes *connections* rather than individual
      requests.  (That practice is peculiar for HTTP, but it is a
      useful optimization.)  */
-  int authorized;
+  bool authorized;
 
 #ifdef ENABLE_NTLM
   /* NTLM data of the current connection.  */
@@ -899,7 +881,7 @@ static void
 invalidate_persistent (void)
 {
   DEBUGP (("Disabling further reuse of socket %d.\n", pconn.socket));
-  pconn_active = 0;
+  pconn_active = false;
   fd_close (pconn.socket);
   xfree (pconn.host);
   xzero (pconn);
@@ -914,7 +896,7 @@ invalidate_persistent (void)
    If a previous connection was persistent, it is closed. */
 
 static void
-register_persistent (const char *host, int port, int fd, int ssl)
+register_persistent (const char *host, int port, int fd, bool ssl)
 {
   if (pconn_active)
     {
@@ -934,58 +916,58 @@ register_persistent (const char *host, int port, int fd, int ssl)
        }
     }
 
-  pconn_active = 1;
+  pconn_active = true;
   pconn.socket = fd;
   pconn.host = xstrdup (host);
   pconn.port = port;
   pconn.ssl = ssl;
-  pconn.authorized = 0;
+  pconn.authorized = false;
 
   DEBUGP (("Registered socket %d for persistent reuse.\n", fd));
 }
 
-/* Return non-zero if a persistent connection is available for
-   connecting to HOST:PORT.  */
+/* Return true if a persistent connection is available for connecting
+   to HOST:PORT.  */
 
-static int
-persistent_available_p (const char *host, int port, int ssl,
-                       int *host_lookup_failed)
+static bool
+persistent_available_p (const char *host, int port, bool ssl,
+                       bool *host_lookup_failed)
 {
   /* First, check whether a persistent connection is active at all.  */
   if (!pconn_active)
-    return 0;
+    return false;
 
   /* If we want SSL and the last connection wasn't or vice versa,
      don't use it.  Checking for host and port is not enough because
      HTTP and HTTPS can apparently coexist on the same port.  */
   if (ssl != pconn.ssl)
-    return 0;
+    return false;
 
   /* If we're not connecting to the same port, we're not interested. */
   if (port != pconn.port)
-    return 0;
+    return false;
 
   /* If the host is the same, we're in business.  If not, there is
      still hope -- read below.  */
   if (0 != strcasecmp (host, pconn.host))
     {
-      /* If pconn.socket is already talking to HOST, we needn't
-        reconnect.  This happens often when both sites are virtual
-        hosts distinguished only by name and served by the same
-        network interface, and hence the same web server (possibly
-        set up by the ISP and serving many different web sites).
-        This admittedly non-standard optimization does not contradict
+      /* Check if pconn.socket is talking to HOST under another name.
+        This happens often when both sites are virtual hosts
+        distinguished only by name and served by the same network
+        interface, and hence the same web server (possibly set up by
+        the ISP and serving many different web sites).  This
+        admittedly unconventional optimization does not contradict
         HTTP and works well with popular server software.  */
 
-      int found;
+      bool found;
       ip_address ip;
       struct address_list *al;
 
       if (ssl)
        /* Don't try to talk to two different SSL sites over the same
-          secure connection!  (Besides, it's not clear if name-based
-          virtual hosting is even possible with SSL.)  */
-       return 0;
+          secure connection!  (Besides, it's not clear that
+          name-based virtual hosting is even possible with SSL.)  */
+       return false;
 
       /* If pconn.socket's peer is one of the IP addresses HOST
         resolves to, pconn.socket is for all intents and purposes
@@ -996,20 +978,20 @@ persistent_available_p (const char *host, int port, int ssl,
          /* Can't get the peer's address -- something must be very
             wrong with the connection.  */
          invalidate_persistent ();
-         return 0;
+         return false;
        }
       al = lookup_host (host, 0);
       if (!al)
        {
-         *host_lookup_failed = 1;
-         return 0;
+         *host_lookup_failed = true;
+         return false;
        }
 
       found = address_list_contains (al, &ip);
       address_list_release (al);
 
       if (!found)
-       return 0;
+       return false;
 
       /* The persistent connection's peer address was found among the
         addresses HOST resolved to; therefore, pconn.sock is in fact
@@ -1029,10 +1011,10 @@ persistent_available_p (const char *host, int port, int ssl,
          let's invalidate the persistent connection before returning
          0.  */
       invalidate_persistent ();
-      return 0;
+      return false;
     }
 
-  return 1;
+  return true;
 }
 
 /* The idea behind these two CLOSE macros is to distinguish between
@@ -1074,14 +1056,14 @@ persistent_available_p (const char *host, int port, int ssl,
 struct http_stat
 {
   wgint len;                   /* received length */
-  wgint contlen;                       /* expected length */
-  wgint restval;                       /* the restart value */
+  wgint contlen;               /* expected length */
+  wgint restval;               /* the restart value */
   int res;                     /* the result of last read */
   char *newloc;                        /* new location (redirection) */
   char *remote_time;           /* remote time-stamp string */
   char *error;                 /* textual HTTP error */
   int statcode;                        /* status code */
-  wgint rd_size;                       /* amount of data read from socket */
+  wgint rd_size;               /* amount of data read from socket */
   double dltime;               /* time it took to download the data */
   const char *referer;         /* value of the referer header. */
   char **local_file;           /* local file. */
@@ -1100,13 +1082,13 @@ free_hstat (struct http_stat *hs)
   hs->error = NULL;
 }
 
-static char *create_authorization_line PARAMS ((const char *, const char *,
-                                               const char *, const char *,
-                                               const char *, int *));
-static char *basic_authentication_encode PARAMS ((const char *, const char *));
-static int known_authentication_scheme_p PARAMS ((const char *, const char *));
+static char *create_authorization_line (const char *, const char *,
+                                       const char *, const char *,
+                                       const char *, bool *);
+static char *basic_authentication_encode (const char *, const char *);
+static bool known_authentication_scheme_p (const char *, const char *);
 
-time_t http_atotm PARAMS ((const char *));
+time_t http_atotm (const char *);
 
 #define BEGINS_WITH(line, string_constant)                             \
   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)  \
@@ -1121,6 +1103,12 @@ time_t http_atotm PARAMS ((const char *));
     request_set_header (req, "User-Agent", opt.useragent, rel_none);   \
 } while (0)
 
+/* The flags that allow clobbering the file (opening with "wb").
+   Defined here to avoid repetition later.  #### This will require
+   rework.  */
+#define ALLOW_CLOBBER (opt.noclobber || opt.always_rest || opt.timestamping \
+                      || opt.dirstruct || opt.output_document)
+
 /* Retrieve a document through HTTP protocol.  It recognizes status
    code, and correctly handles redirections.  It closes the network
    socket.  If it receives an error from the functions below it, it
@@ -1150,13 +1138,17 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
 
   /* Set to 1 when the authorization has failed permanently and should
      not be tried again. */
-  int auth_finished = 0;
+  bool auth_finished = false;
 
   /* Whether NTLM authentication is used for this request. */
-  int ntlm_seen = 0;
+  bool ntlm_seen = false;
 
   /* Whether our connection to the remote host is through SSL.  */
-  int using_ssl = 0;
+  bool using_ssl = false;
+
+  /* Whether a HEAD request will be issued (as opposed to GET or
+     POST). */
+  bool head_only = !!(*dt & HEAD_ONLY);
 
   char *head;
   struct response *resp;
@@ -1165,7 +1157,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
 
   /* Whether this connection will be kept alive after the HTTP request
      is done. */
-  int keep_alive;
+  bool keep_alive;
 
   /* Whether keep-alive should be inhibited.
 
@@ -1174,13 +1166,13 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
      the Connection header and transfer it to the remote server,
      causing it to not close the connection and leave both the proxy
      and the client hanging.  */
-  int inhibit_keep_alive =
+  bool inhibit_keep_alive =
     !opt.http_keep_alive || opt.ignore_length || proxy != NULL;
 
   /* Headers sent when using POST. */
   wgint post_data_size = 0;
 
-  int host_lookup_failed = 0;
+  bool host_lookup_failed = false;
 
 #ifdef HAVE_SSL
   if (u->scheme == SCHEME_HTTPS)
@@ -1197,7 +1189,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
     }
 #endif /* HAVE_SSL */
 
-  if (!(*dt & HEAD_ONLY))
+  if (!head_only)
     /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
        know the local filename so we can save to it. */
     assert (*hs->local_file != NULL);
@@ -1218,7 +1210,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   {
     char *meth_arg;
     const char *meth = "GET";
-    if (*dt & HEAD_ONLY)
+    if (head_only)
       meth = "HEAD";
     else if (opt.post_file_name || opt.post_data)
       meth = "POST";
@@ -1323,7 +1315,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
     /* Whether we need to print the host header with braces around
        host, e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the
        usual "Host: symbolic-name:1234". */
-    int squares = strchr (u->host, ':') != NULL;
+    bool squares = strchr (u->host, ':') != NULL;
     if (u->port == scheme_default_port (u->scheme))
       request_set_header (req, "Host",
                          aprintf (squares ? "[%s]" : "%s", u->host),
@@ -1361,8 +1353,8 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
          post_data_size = file_size (opt.post_file_name);
          if (post_data_size == -1)
            {
-             logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
-                        opt.post_file_name);
+             logprintf (LOG_NOTQUIET, _("POST data file missing: %s (%s)\n"),
+                        opt.post_file_name, strerror (errno));
              post_data_size = 0;
            }
        }
@@ -1384,7 +1376,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
      without authorization header fails.  (Expected to happen at least
      for the Digest authorization scheme.)  */
 
-  keep_alive = 0;
+  keep_alive = false;
 
   /* Establish the connection.  */
 
@@ -1516,12 +1508,12 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
 
       if (conn->scheme == SCHEME_HTTPS)
        {
-         if (!ssl_connect (sock))
+         if (!ssl_connect (sock) || !ssl_check_certificate (sock, u->host))
            {
              fd_close (sock);
              return CONSSLERR;
            }
-         using_ssl = 1;
+         using_ssl = true;
        }
 #endif /* HAVE_SSL */
     }
@@ -1534,7 +1526,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
       if (opt.post_data)
        {
          DEBUGP (("[POST data: %s]\n", opt.post_data));
-         write_error = fd_write (sock, opt.post_data, post_data_size, -1.0);
+         write_error = fd_write (sock, opt.post_data, post_data_size, -1);
        }
       else if (opt.post_file_name && post_data_size != 0)
        write_error = post_file (sock, opt.post_file_name, post_data_size);
@@ -1610,11 +1602,11 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   if (!inhibit_keep_alive && contlen != -1)
     {
       if (resp_header_copy (resp, "Keep-Alive", NULL, 0))
-       keep_alive = 1;
+       keep_alive = true;
       else if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
        {
          if (0 == strcasecmp (hdrval, "Keep-Alive"))
-           keep_alive = 1;
+           keep_alive = true;
        }
     }
   if (keep_alive)
@@ -1625,14 +1617,11 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   if (statcode == HTTP_STATUS_UNAUTHORIZED)
     {
       /* Authorization is required.  */
-      if (keep_alive)
-       {
-         if (skip_short_body (sock, contlen))
-           CLOSE_FINISH (sock);
-         else
-           CLOSE_INVALIDATE (sock);
-       }
-      pconn.authorized = 0;
+      if (keep_alive && !head_only && skip_short_body (sock, contlen))
+       CLOSE_FINISH (sock);
+      else
+       CLOSE_INVALIDATE (sock);
+      pconn.authorized = false;
       if (!auth_finished && (user && passwd))
        {
          /* IIS sends multiple copies of WWW-Authenticate, one with
@@ -1673,7 +1662,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
                                                             &auth_finished),
                                  rel_value);
              if (BEGINS_WITH (www_authenticate, "NTLM"))
-               ntlm_seen = 1;
+               ntlm_seen = true;
              xfree (pth);
              goto retry_with_auth;
            }
@@ -1686,7 +1675,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
     {
       /* Kludge: if NTLM is used, mark the TCP connection as authorized. */
       if (ntlm_seen)
-       pconn.authorized = 1;
+       pconn.authorized = true;
     }
   request_free (req);
 
@@ -1714,29 +1703,22 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   hs->remote_time = resp_header_strdup (resp, "Last-Modified");
 
   /* Handle (possibly multiple instances of) the Set-Cookie header. */
-  {
-    char *pth = NULL;
-    int scpos;
-    const char *scbeg, *scend;
-    /* The jar should have been created by now. */
-    assert (wget_cookie_jar != NULL);
-    for (scpos = 0;
-        (scpos = resp_header_locate (resp, "Set-Cookie", scpos,
-                                     &scbeg, &scend)) != -1;
-        ++scpos)
-      {
-       char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
-       if (pth == NULL)
-         {
-           /* u->path doesn't begin with /, which cookies.c expects. */
-           pth = (char *) alloca (1 + strlen (u->path) + 1);
-           pth[0] = '/';
-           strcpy (pth + 1, u->path);
-         }
-       cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port, pth,
-                                 set_cookie);
-      }
-  }
+  if (opt.cookies)
+    {
+      int scpos;
+      const char *scbeg, *scend;
+      /* The jar should have been created by now. */
+      assert (wget_cookie_jar != NULL);
+      for (scpos = 0;
+          (scpos = resp_header_locate (resp, "Set-Cookie", scpos,
+                                       &scbeg, &scend)) != -1;
+          ++scpos)
+       {
+         char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
+         cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port,
+                                   u->path, set_cookie);
+       }
+    }
 
   if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
     {
@@ -1746,7 +1728,6 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
        contrange = first_byte_pos;
     }
   resp_free (resp);
-  xfree (head);
 
   /* 20x responses are counted among successful by default.  */
   if (H_20X (statcode))
@@ -1768,13 +1749,10 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
                     _("Location: %s%s\n"),
                     hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
                     hs->newloc ? _(" [following]") : "");
-         if (keep_alive)
-           {
-             if (skip_short_body (sock, contlen))
-               CLOSE_FINISH (sock);
-             else
-               CLOSE_INVALIDATE (sock);
-           }
+         if (keep_alive && !head_only && skip_short_body (sock, contlen))
+           CLOSE_FINISH (sock);
+         else
+           CLOSE_INVALIDATE (sock);
          xfree_null (type);
          return NEWLOCATION;
        }
@@ -1795,18 +1773,28 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
        already the file's suffix, tack on ".html". */
     {
-      char*  last_period_in_local_filename = strrchr(*hs->local_file, '.');
+      char *last_period_in_local_filename = strrchr (*hs->local_file, '.');
 
       if (last_period_in_local_filename == NULL
          || !(0 == strcasecmp (last_period_in_local_filename, ".htm")
               || 0 == strcasecmp (last_period_in_local_filename, ".html")))
        {
-         size_t  local_filename_len = strlen(*hs->local_file);
-         
-         *hs->local_file = xrealloc(*hs->local_file,
-                                    local_filename_len + sizeof(".html"));
+         int local_filename_len = strlen (*hs->local_file);
+         /* Resize the local file, allowing for ".html" preceded by
+            optional ".NUMBER".  */
+         *hs->local_file = xrealloc (*hs->local_file,
+                                     local_filename_len + 24 + sizeof (".html"));
          strcpy(*hs->local_file + local_filename_len, ".html");
-
+         /* If clobbering is not allowed and the file, as named,
+            exists, tack on ".NUMBER.html" instead. */
+         if (!ALLOW_CLOBBER)
+           {
+             int ext_num = 1;
+             do
+               sprintf (*hs->local_file + local_filename_len,
+                        ".%d.html", ext_num++);
+             while (file_exists_p (*hs->local_file));
+           }
          *dt |= ADDED_HTML_EXTENSION;
        }
     }
@@ -1849,7 +1837,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
          logputs (LOG_VERBOSE, _("Length: "));
          if (contlen != -1)
            {
-             logputs (LOG_VERBOSE, with_thousand_seps (contlen + contrange));
+             logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange));
              if (contlen + contrange >= 1024)
                logprintf (LOG_VERBOSE, " (%s)",
                           human_readable (contlen + contrange));
@@ -1857,11 +1845,11 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
                {
                  if (contlen >= 1024)
                    logprintf (LOG_VERBOSE, _(", %s (%s) remaining"),
-                              with_thousand_seps (contlen),
+                              number_to_static_string (contlen),
                               human_readable (contlen));
                  else
                    logprintf (LOG_VERBOSE, _(", %s remaining"),
-                              with_thousand_seps (contlen));
+                              number_to_static_string (contlen));
                }
            }
          else
@@ -1877,7 +1865,7 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   type = NULL;                 /* We don't need it any more.  */
 
   /* Return if we have no intention of further downloading.  */
-  if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
+  if (!(*dt & RETROKF) || head_only)
     {
       /* In case the caller cares to look...  */
       hs->len = 0;
@@ -1899,12 +1887,11 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
        rotate_backups (*hs->local_file);
       if (hs->restval)
        fp = fopen (*hs->local_file, "ab");
-      else if (opt.noclobber || opt.always_rest || opt.timestamping || opt.dirstruct
-              || opt.output_document)
+      else if (ALLOW_CLOBBER)
        fp = fopen (*hs->local_file, "wb");
       else
        {
-         fp = fopen_excl (*hs->local_file, 1);
+         fp = fopen_excl (*hs->local_file, true);
          if (!fp && errno == EEXIST)
            {
              /* We cannot just invent a new name and use it (which is
@@ -1933,6 +1920,9 @@ gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
   if (opt.save_headers)
     fwrite (head, 1, strlen (head), fp);
 
+  /* Now we no longer need to store the response header. */
+  xfree (head);
+
   /* Download the request body.  */
   flags = 0;
   if (keep_alive)
@@ -1976,10 +1966,11 @@ http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
           int *dt, struct url *proxy)
 {
   int count;
-  int use_ts, got_head = 0;    /* time-stamping info */
+  bool use_ts, got_head = false;/* time-stamping info */
   char *filename_plus_orig_suffix;
   char *local_filename = NULL;
-  char *tms, *locf, *tmrate;
+  char *tms, *locf;
+  const char *tmrate;
   uerr_t err;
   time_t tml = -1, tmr = -1;   /* local and remote time-stamps */
   wgint local_size = 0;                /* the size of the local file */
@@ -1998,16 +1989,14 @@ http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
       if (opt.cookies_input && !cookies_loaded_p)
        {
          cookie_jar_load (wget_cookie_jar, opt.cookies_input);
-         cookies_loaded_p = 1;
+         cookies_loaded_p = true;
        }
     }
 
   *newloc = NULL;
 
-  /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
-     has_wildcards_p because it would also warn on `?', and we know that
-     shows up in CGI paths a *lot*.  */
-  if (strchr (u->url, '*'))
+  /* Warn on (likely bogus) wildcard usage in HTTP.  */
+  if (opt.ftp_glob && has_wildcards_p (u->path))
     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
 
   xzero (hstat);
@@ -2044,7 +2033,7 @@ http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
       /* If opt.noclobber is turned on and file already exists, do not
         retrieve the file */
       logprintf (LOG_VERBOSE, _("\
-File `%s' already there, will not retrieve.\n"), *hstat.local_file);
+File `%s' already there; not retrieving.\n\n"), *hstat.local_file);
       /* If the file is there, we suppose it's retrieved OK.  */
       *dt |= RETROKF;
 
@@ -2057,10 +2046,10 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
       return RETROK;
     }
 
-  use_ts = 0;
+  use_ts = false;
   if (opt.timestamping)
     {
-      int local_dot_orig_file_exists = 0;
+      bool local_dot_orig_file_exists = false;
 
       if (opt.backup_converted)
        /* If -K is specified, we'll act on the assumption that it was specified
@@ -2102,7 +2091,7 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
           the server has is the same version we already have, allowing us to
           skip a download. */
        {
-         use_ts = 1;
+         use_ts = true;
          tml = st.st_mtime;
 #ifdef WINDOWS
          /* Modification time granularity is 2 seconds for Windows, so
@@ -2110,7 +2099,7 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
          tml++;
 #endif
          local_size = st.st_size;
-         got_head = 0;
+         got_head = false;
        }
     }
   /* Reset the counter.  */
@@ -2127,7 +2116,7 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
       /* Print fetch message, if opt.verbose.  */
       if (opt.verbose)
        {
-         char *hurl = url_string (u, 1);
+         char *hurl = url_string (u, true);
          char tmp[256];
          strcpy (tmp, "        ");
          if (count > 1)
@@ -2149,13 +2138,18 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
        *dt &= ~HEAD_ONLY;
 
       /* Decide whether or not to restart.  */
-      hstat.restval = 0;
-      if (count > 1)
-       hstat.restval = hstat.len; /* continue where we left off */
-      else if (opt.always_rest
-              && stat (locf, &st) == 0
-              && S_ISREG (st.st_mode))
+      if (opt.always_rest
+         && stat (locf, &st) == 0
+         && S_ISREG (st.st_mode))
+       /* When -c is used, continue from on-disk size.  (Can't use
+          hstat.len even if count>1 because we don't want a failed
+          first attempt to clobber existing data.)  */
        hstat.restval = st.st_size;
+      else if (count > 1)
+       /* otherwise, continue where the previous try left off */
+       hstat.restval = hstat.len;
+      else
+       hstat.restval = 0;
 
       /* Decide whether to send the no-cache directive.  We send it in
         two cases:
@@ -2235,7 +2229,6 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
          return err;
        case CONSSLERR:
          /* Another fatal error.  */
-         logputs (LOG_VERBOSE, "\n");
          logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
          free_hstat (&hstat);
          xfree_null (dummy);
@@ -2271,7 +2264,7 @@ File `%s' already there, will not retrieve.\n"), *hstat.local_file);
          if (!opt.verbose)
            {
              /* #### Ugly ugly ugly! */
-             char *hurl = url_string (u, 1);
+             char *hurl = url_string (u, true);
              logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
              xfree (hurl);
            }
@@ -2304,9 +2297,9 @@ Last-modified header invalid -- time-stamp ignored.\n"));
       /* The time-stamping section.  */
       if (use_ts)
        {
-         got_head = 1;
+         got_head = true;
          *dt &= ~HEAD_ONLY;
-         use_ts = 0;           /* no more time-stamping */
+         use_ts = false;               /* no more time-stamping */
          count = 0;            /* the retrieve count for HEAD is
                                   reset */
          if (hstat.remote_time && tmr != (time_t) (-1))
@@ -2367,7 +2360,8 @@ The sizes do not match (local %s) -- retrieving.\n"),
          return RETROK;
        }
 
-      tmrate = retr_rate (hstat.rd_size, hstat.dltime, 0);
+      tmrate = retr_rate (hstat.rd_size, hstat.dltime);
+      total_download_time += hstat.dltime;
 
       if (hstat.len == hstat.contlen)
        {
@@ -2440,7 +2434,7 @@ The sizes do not match (local %s) -- retrieving.\n"),
          else if (!opt.kill_longer) /* meaning we got more than expected */
            {
              logprintf (LOG_VERBOSE,
-                        _("%s (%s) - `%s' saved [%s/%s])\n\n"),
+                        _("%s (%s) - `%s' saved [%s/%s]\n\n"),
                         tms, tmrate, locf,
                         number_to_static_string (hstat.len),
                         number_to_static_string (hstat.contlen));
@@ -2582,26 +2576,27 @@ mktime_from_utc (struct tm *t)
    In extended regexp parlance, the function returns 1 if P matches
    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (which strptime
    can return) is considered a failure and 0 is returned.  */
-static int
+static bool
 check_end (const char *p)
 {
   if (!p)
-    return 0;
+    return false;
   while (ISSPACE (*p))
     ++p;
   if (!*p
       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
       || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
-    return 1;
+    return true;
   else
-    return 0;
+    return false;
 }
 
 /* Convert the textual specification of time in TIME_STRING to the
    number of seconds since the Epoch.
 
-   TIME_STRING can be in any of the three formats RFC2068 allows the
-   HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
+   TIME_STRING can be in any of the three formats RFC2616 allows the
+   HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date,
+   as well as the time format used in the Set-Cookie header.
    Timezones are ignored, and should be GMT.
 
    Return the computed time_t representation, or -1 if the conversion
@@ -2635,10 +2630,10 @@ http_atotm (const char *time_string)
   static const char *time_formats[] = {
     "%a, %d %b %Y %T",         /* rfc1123: Thu, 29 Jan 1998 22:12:57 */
     "%A, %d-%b-%y %T",         /* rfc850:  Thursday, 29-Jan-98 22:12:57 */
-    "%a, %d-%b-%Y %T",         /* rfc850+: Thu, 29-Jan-1998 22:12:57
-                                  (post-y2k-rfc850; apparently google
-                                  uses this for their cookies.) */
-    "%a %b %d %T %Y"           /* asctime: Thu Jan 29 22:12:57 1998 */
+    "%a %b %d %T %Y",          /* asctime: Thu Jan 29 22:12:57 1998 */
+    "%a, %d-%b-%Y %T"          /* cookies: Thu, 29-Jan-1998 22:12:57
+                                  (used in Set-Cookie, defined in the
+                                  Netscape cookie specification.) */
   };
   int i;
 
@@ -2869,14 +2864,14 @@ digest_authentication_encode (const char *au, const char *user,
     gen_md5_finish (ctx, hash);
     dump_hash (response_digest, hash);
 
-    res = (char*) xmalloc (strlen (user)
-                          + strlen (user)
-                          + strlen (realm)
-                          + strlen (nonce)
-                          + strlen (path)
-                          + 2 * MD5_HASHLEN /*strlen (response_digest)*/
-                          + (opaque ? strlen (opaque) : 0)
-                          + 128);
+    res = xmalloc (strlen (user)
+                  + strlen (user)
+                  + strlen (realm)
+                  + strlen (nonce)
+                  + strlen (path)
+                  + 2 * MD5_HASHLEN /*strlen (response_digest)*/
+                  + (opaque ? strlen (opaque) : 0)
+                  + 128);
     sprintf (res, "Digest \
 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
             user, realm, nonce, path, response_digest);
@@ -2905,7 +2900,7 @@ username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
    && ((e) - (b) == STRSIZE (literal)                  \
        || ISSPACE (b[STRSIZE (literal)])))
 
-static int
+static bool
 known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
 {
   return STARTS ("Basic", hdrbeg, hdrend)
@@ -2928,25 +2923,25 @@ known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
 static char *
 create_authorization_line (const char *au, const char *user,
                           const char *passwd, const char *method,
-                          const char *path, int *finished)
+                          const char *path, bool *finished)
 {
   /* We are called only with known schemes, so we can dispatch on the
      first letter. */
   switch (TOUPPER (*au))
     {
     case 'B':                  /* Basic */
-      *finished = 1;
+      *finished = true;
       return basic_authentication_encode (user, passwd);
 #ifdef ENABLE_DIGEST
     case 'D':                  /* Digest */
-      *finished = 1;
+      *finished = true;
       return digest_authentication_encode (au, user, passwd, method, path);
 #endif
 #ifdef ENABLE_NTLM
     case 'N':                  /* NTLM */
       if (!ntlm_input (&pconn.ntlm, au))
        {
-         *finished = 1;
+         *finished = true;
          return NULL;
        }
       return ntlm_output (&pconn.ntlm, user, passwd, finished);