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