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