]> sjero.net Git - wget/blob - src/http.c
[svn] If content-type is not given, assume text/html.
[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 content-type is not given, assume text/html.  This is because
1312      of the multitude of broken CGI's that "forget" to generate the
1313      content-type.  */
1314   if (!type || 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1315     *dt |= TEXTHTML;
1316   else
1317     *dt &= ~TEXTHTML;
1318
1319   if (opt.html_extension && (*dt & TEXTHTML))
1320     /* -E / --html-extension / html_extension = on was specified, and this is a
1321        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
1322        already the file's suffix, tack on ".html". */
1323     {
1324       char*  last_period_in_local_filename = strrchr(*hs->local_file, '.');
1325
1326       if (last_period_in_local_filename == NULL ||
1327           !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1328             strcasecmp(last_period_in_local_filename, ".html") == EQ))
1329         {
1330           size_t  local_filename_len = strlen(*hs->local_file);
1331           
1332           *hs->local_file = xrealloc(*hs->local_file,
1333                                      local_filename_len + sizeof(".html"));
1334           strcpy(*hs->local_file + local_filename_len, ".html");
1335
1336           *dt |= ADDED_HTML_EXTENSION;
1337         }
1338     }
1339
1340   if (contrange == -1)
1341     {
1342       /* We did not get a content-range header.  This means that the
1343          server did not honor our `Range' request.  Normally, this
1344          means we should reset hs->restval and continue normally.  */
1345
1346       /* However, if `-c' is used, we need to be a bit more careful:
1347
1348          1. If `-c' is specified and the file already existed when
1349          Wget was started, it would be a bad idea for us to start
1350          downloading it from scratch, effectively truncating it.  I
1351          believe this cannot happen unless `-c' was specified.
1352
1353          2. If `-c' is used on a file that is already fully
1354          downloaded, we're requesting bytes after the end of file,
1355          which can result in server not honoring `Range'.  If this is
1356          the case, `Content-Length' will be equal to the length of the
1357          file.  */
1358       if (opt.always_rest)
1359         {
1360           /* Check for condition #2. */
1361           if (hs->restval > 0               /* restart was requested. */
1362               && contlen != -1              /* we got content-length. */
1363               && hs->restval >= contlen     /* file fully downloaded
1364                                                or has shrunk.  */
1365               )
1366             {
1367               logputs (LOG_VERBOSE, _("\
1368 \n    The file is already fully retrieved; nothing to do.\n\n"));
1369               /* In case the caller inspects. */
1370               hs->len = contlen;
1371               hs->res = 0;
1372               /* Mark as successfully retrieved. */
1373               *dt |= RETROKF;
1374               FREE_MAYBE (type);
1375               FREE_MAYBE (all_headers);
1376               CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1377                                            might be more bytes in the body. */
1378               return RETRUNNEEDED;
1379             }
1380
1381           /* Check for condition #1. */
1382           if (hs->no_truncate)
1383             {
1384               logprintf (LOG_NOTQUIET,
1385                          _("\
1386 \n\
1387 Continued download failed on this file, which conflicts with `-c'.\n\
1388 Refusing to truncate existing file `%s'.\n\n"), *hs->local_file);
1389               FREE_MAYBE (type);
1390               FREE_MAYBE (all_headers);
1391               CLOSE_INVALIDATE (sock);
1392               return CONTNOTSUPPORTED;
1393             }
1394
1395           /* Fallthrough */
1396         }
1397
1398       hs->restval = 0;
1399     }
1400   else if (contrange != hs->restval ||
1401            (H_PARTIAL (statcode) && contrange == -1))
1402     {
1403       /* This means the whole request was somehow misunderstood by the
1404          server.  Bail out.  */
1405       FREE_MAYBE (type);
1406       FREE_MAYBE (all_headers);
1407       CLOSE_INVALIDATE (sock);
1408       return RANGEERR;
1409     }
1410
1411   if (hs->restval)
1412     {
1413       if (contlen != -1)
1414         contlen += contrange;
1415       else
1416         contrange = -1;        /* If conent-length was not sent,
1417                                   content-range will be ignored.  */
1418     }
1419   hs->contlen = contlen;
1420
1421   if (opt.verbose)
1422     {
1423       if ((*dt & RETROKF) && !opt.server_response)
1424         {
1425           /* No need to print this output if the body won't be
1426              downloaded at all, or if the original server response is
1427              printed.  */
1428           logputs (LOG_VERBOSE, _("Length: "));
1429           if (contlen != -1)
1430             {
1431               logputs (LOG_VERBOSE, legible (contlen));
1432               if (contrange != -1)
1433                 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1434                            legible (contlen - contrange));
1435             }
1436           else
1437             logputs (LOG_VERBOSE,
1438                      opt.ignore_length ? _("ignored") : _("unspecified"));
1439           if (type)
1440             logprintf (LOG_VERBOSE, " [%s]\n", type);
1441           else
1442             logputs (LOG_VERBOSE, "\n");
1443         }
1444     }
1445   FREE_MAYBE (type);
1446   type = NULL;                  /* We don't need it any more.  */
1447
1448   /* Return if we have no intention of further downloading.  */
1449   if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1450     {
1451       /* In case the caller cares to look...  */
1452       hs->len = 0L;
1453       hs->res = 0;
1454       FREE_MAYBE (type);
1455       FREE_MAYBE (all_headers);
1456       CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1457                                    might be more bytes in the body. */
1458       return RETRFINISHED;
1459     }
1460
1461   /* Open the local file.  */
1462   if (!opt.dfp)
1463     {
1464       mkalldirs (*hs->local_file);
1465       if (opt.backups)
1466         rotate_backups (*hs->local_file);
1467       fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1468       if (!fp)
1469         {
1470           logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1471           CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1472                                       might be more bytes in the body. */
1473           FREE_MAYBE (all_headers);
1474           return FOPENERR;
1475         }
1476     }
1477   else                          /* opt.dfp */
1478     {
1479       extern int global_download_count;
1480       fp = opt.dfp;
1481       /* To ensure that repeated "from scratch" downloads work for -O
1482          files, we rewind the file pointer, unless restval is
1483          non-zero.  (This works only when -O is used on regular files,
1484          but it's still a valuable feature.)
1485
1486          However, this loses when more than one URL is specified on
1487          the command line the second rewinds eradicates the contents
1488          of the first download.  Thus we disable the above trick for
1489          all the downloads except the very first one.
1490
1491          #### A possible solution to this would be to remember the
1492          file position in the output document and to seek to that
1493          position, instead of rewinding.  */
1494       if (!hs->restval && global_download_count == 0)
1495         {
1496           /* This will silently fail for streams that don't correspond
1497              to regular files, but that's OK.  */
1498           rewind (fp);
1499           /* ftruncate is needed because opt.dfp is opened in append
1500              mode if opt.always_rest is set.  */
1501           ftruncate (fileno (fp), 0);
1502           clearerr (fp);
1503         }
1504     }
1505
1506   /* #### This confuses the code that checks for file size.  There
1507      should be some overhead information.  */
1508   if (opt.save_headers)
1509     fwrite (all_headers, 1, all_length, fp);
1510
1511   /* Get the contents of the document.  */
1512   hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1513                           (contlen != -1 ? contlen : 0),
1514                           &rbuf, keep_alive, &hs->dltime);
1515
1516   if (hs->res >= 0)
1517     CLOSE_FINISH (sock);
1518   else
1519     CLOSE_INVALIDATE (sock);
1520
1521   {
1522     /* Close or flush the file.  We have to be careful to check for
1523        error here.  Checking the result of fwrite() is not enough --
1524        errors could go unnoticed!  */
1525     int flush_res;
1526     if (!opt.dfp)
1527       flush_res = fclose (fp);
1528     else
1529       flush_res = fflush (fp);
1530     if (flush_res == EOF)
1531       hs->res = -2;
1532   }
1533   FREE_MAYBE (all_headers);
1534   if (hs->res == -2)
1535     return FWRITEERR;
1536   return RETRFINISHED;
1537 }
1538
1539 /* The genuine HTTP loop!  This is the part where the retrieval is
1540    retried, and retried, and retried, and...  */
1541 uerr_t
1542 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1543            int *dt, struct url *proxy)
1544 {
1545   int count;
1546   int use_ts, got_head = 0;     /* time-stamping info */
1547   char *filename_plus_orig_suffix;
1548   char *local_filename = NULL;
1549   char *tms, *locf, *tmrate;
1550   uerr_t err;
1551   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
1552   long local_size = 0;          /* the size of the local file */
1553   size_t filename_len;
1554   struct http_stat hstat;       /* HTTP status */
1555   struct stat st;
1556   char *dummy = NULL;
1557
1558   /* This used to be done in main(), but it's a better idea to do it
1559      here so that we don't go through the hoops if we're just using
1560      FTP or whatever. */
1561   if (opt.cookies && opt.cookies_input && !cookies_loaded_p)
1562     {
1563       load_cookies (opt.cookies_input);
1564       cookies_loaded_p = 1;
1565     }
1566
1567   *newloc = NULL;
1568
1569   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
1570      has_wildcards_p because it would also warn on `?', and we know that
1571      shows up in CGI paths a *lot*.  */
1572   if (strchr (u->url, '*'))
1573     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1574
1575   /* Determine the local filename.  */
1576   if (local_file && *local_file)
1577     hstat.local_file = local_file;
1578   else if (local_file)
1579     {
1580       *local_file = url_filename (u);
1581       hstat.local_file = local_file;
1582     }
1583   else
1584     {
1585       dummy = url_filename (u);
1586       hstat.local_file = &dummy;
1587     }
1588
1589   if (!opt.output_document)
1590     locf = *hstat.local_file;
1591   else
1592     locf = opt.output_document;
1593
1594   hstat.referer = referer;
1595
1596   filename_len = strlen (*hstat.local_file);
1597   filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1598
1599   if (opt.noclobber && file_exists_p (*hstat.local_file))
1600     {
1601       /* If opt.noclobber is turned on and file already exists, do not
1602          retrieve the file */
1603       logprintf (LOG_VERBOSE, _("\
1604 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1605       /* If the file is there, we suppose it's retrieved OK.  */
1606       *dt |= RETROKF;
1607
1608       /* #### Bogusness alert.  */
1609       /* If its suffix is "html" or "htm" or similar, assume text/html.  */
1610       if (has_html_suffix_p (*hstat.local_file))
1611         *dt |= TEXTHTML;
1612
1613       FREE_MAYBE (dummy);
1614       return RETROK;
1615     }
1616
1617   use_ts = 0;
1618   if (opt.timestamping)
1619     {
1620       boolean  local_dot_orig_file_exists = FALSE;
1621
1622       if (opt.backup_converted)
1623         /* If -K is specified, we'll act on the assumption that it was specified
1624            last time these files were downloaded as well, and instead of just
1625            comparing local file X against server file X, we'll compare local
1626            file X.orig (if extant, else X) against server file X.  If -K
1627            _wasn't_ specified last time, or the server contains files called
1628            *.orig, -N will be back to not operating correctly with -k. */
1629         {
1630           /* Would a single s[n]printf() call be faster?  --dan
1631
1632              Definitely not.  sprintf() is horribly slow.  It's a
1633              different question whether the difference between the two
1634              affects a program.  Usually I'd say "no", but at one
1635              point I profiled Wget, and found that a measurable and
1636              non-negligible amount of time was lost calling sprintf()
1637              in url.c.  Replacing sprintf with inline calls to
1638              strcpy() and long_to_string() made a difference.
1639              --hniksic */
1640           memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1641           memcpy (filename_plus_orig_suffix + filename_len,
1642                   ".orig", sizeof (".orig"));
1643
1644           /* Try to stat() the .orig file. */
1645           if (stat (filename_plus_orig_suffix, &st) == 0)
1646             {
1647               local_dot_orig_file_exists = TRUE;
1648               local_filename = filename_plus_orig_suffix;
1649             }
1650         }      
1651
1652       if (!local_dot_orig_file_exists)
1653         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1654         if (stat (*hstat.local_file, &st) == 0)
1655           local_filename = *hstat.local_file;
1656
1657       if (local_filename != NULL)
1658         /* There was a local file, so we'll check later to see if the version
1659            the server has is the same version we already have, allowing us to
1660            skip a download. */
1661         {
1662           use_ts = 1;
1663           tml = st.st_mtime;
1664 #ifdef WINDOWS
1665           /* Modification time granularity is 2 seconds for Windows, so
1666              increase local time by 1 second for later comparison. */
1667           tml++;
1668 #endif
1669           local_size = st.st_size;
1670           got_head = 0;
1671         }
1672     }
1673   /* Reset the counter.  */
1674   count = 0;
1675   *dt = 0 | ACCEPTRANGES;
1676   /* THE loop */
1677   do
1678     {
1679       /* Increment the pass counter.  */
1680       ++count;
1681       sleep_between_retrievals (count);
1682       /* Get the current time string.  */
1683       tms = time_str (NULL);
1684       /* Print fetch message, if opt.verbose.  */
1685       if (opt.verbose)
1686         {
1687           char *hurl = url_string (u, 1);
1688           char tmp[15];
1689           strcpy (tmp, "        ");
1690           if (count > 1)
1691             sprintf (tmp, _("(try:%2d)"), count);
1692           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1693                      tms, hurl, tmp, locf);
1694 #ifdef WINDOWS
1695           ws_changetitle (hurl, 1);
1696 #endif
1697           xfree (hurl);
1698         }
1699
1700       /* Default document type is empty.  However, if spider mode is
1701          on or time-stamping is employed, HEAD_ONLY commands is
1702          encoded within *dt.  */
1703       if (opt.spider || (use_ts && !got_head))
1704         *dt |= HEAD_ONLY;
1705       else
1706         *dt &= ~HEAD_ONLY;
1707       /* Assume no restarting.  */
1708       hstat.restval = 0L;
1709       /* Decide whether or not to restart.  */
1710       if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1711           /* #### this calls access() and then stat(); could be optimized. */
1712           && file_exists_p (locf))
1713         if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1714           hstat.restval = st.st_size;
1715
1716       /* In `-c' is used and the file is existing and non-empty,
1717          refuse to truncate it if the server doesn't support continued
1718          downloads.  */
1719       hstat.no_truncate = 0;
1720       if (opt.always_rest && hstat.restval)
1721         hstat.no_truncate = 1;
1722
1723       /* Decide whether to send the no-cache directive.  We send it in
1724          two cases:
1725            a) we're using a proxy, and we're past our first retrieval.
1726               Some proxies are notorious for caching incomplete data, so
1727               we require a fresh get.
1728            b) caching is explicitly inhibited. */
1729       if ((proxy && count > 1)  /* a */
1730           || !opt.allow_cache   /* b */
1731           )
1732         *dt |= SEND_NOCACHE;
1733       else
1734         *dt &= ~SEND_NOCACHE;
1735
1736       /* Try fetching the document, or at least its head.  */
1737       err = gethttp (u, &hstat, dt, proxy);
1738
1739       /* It's unfortunate that wget determines the local filename before finding
1740          out the Content-Type of the file.  Barring a major restructuring of the
1741          code, we need to re-set locf here, since gethttp() may have xrealloc()d
1742          *hstat.local_file to tack on ".html". */
1743       if (!opt.output_document)
1744         locf = *hstat.local_file;
1745       else
1746         locf = opt.output_document;
1747
1748       /* Time?  */
1749       tms = time_str (NULL);
1750       /* Get the new location (with or without the redirection).  */
1751       if (hstat.newloc)
1752         *newloc = xstrdup (hstat.newloc);
1753       switch (err)
1754         {
1755         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1756         case CONERROR: case READERR: case WRITEFAILED:
1757         case RANGEERR:
1758           /* Non-fatal errors continue executing the loop, which will
1759              bring them to "while" statement at the end, to judge
1760              whether the number of tries was exceeded.  */
1761           free_hstat (&hstat);
1762           printwhat (count, opt.ntry);
1763           continue;
1764           break;
1765         case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED: 
1766         case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1767           /* Fatal errors just return from the function.  */
1768           free_hstat (&hstat);
1769           FREE_MAYBE (dummy);
1770           return err;
1771           break;
1772         case FWRITEERR: case FOPENERR:
1773           /* Another fatal error.  */
1774           logputs (LOG_VERBOSE, "\n");
1775           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1776                      *hstat.local_file, strerror (errno));
1777           free_hstat (&hstat);
1778           FREE_MAYBE (dummy);
1779           return err;
1780           break;
1781         case CONSSLERR:
1782           /* Another fatal error.  */
1783           logputs (LOG_VERBOSE, "\n");
1784           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1785           free_hstat (&hstat);
1786           FREE_MAYBE (dummy);
1787           return err;
1788           break;
1789         case NEWLOCATION:
1790           /* Return the new location to the caller.  */
1791           if (!hstat.newloc)
1792             {
1793               logprintf (LOG_NOTQUIET,
1794                          _("ERROR: Redirection (%d) without location.\n"),
1795                          hstat.statcode);
1796               free_hstat (&hstat);
1797               FREE_MAYBE (dummy);
1798               return WRONGCODE;
1799             }
1800           free_hstat (&hstat);
1801           FREE_MAYBE (dummy);
1802           return NEWLOCATION;
1803           break;
1804         case RETRUNNEEDED:
1805           /* The file was already fully retrieved. */
1806           free_hstat (&hstat);
1807           FREE_MAYBE (dummy);
1808           return RETROK;
1809           break;
1810         case RETRFINISHED:
1811           /* Deal with you later.  */
1812           break;
1813         default:
1814           /* All possibilities should have been exhausted.  */
1815           abort ();
1816         }
1817       if (!(*dt & RETROKF))
1818         {
1819           if (!opt.verbose)
1820             {
1821               /* #### Ugly ugly ugly! */
1822               char *hurl = url_string (u, 1);
1823               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1824               xfree (hurl);
1825             }
1826           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1827                      tms, hstat.statcode, hstat.error);
1828           logputs (LOG_VERBOSE, "\n");
1829           free_hstat (&hstat);
1830           FREE_MAYBE (dummy);
1831           return WRONGCODE;
1832         }
1833
1834       /* Did we get the time-stamp?  */
1835       if (!got_head)
1836         {
1837           if (opt.timestamping && !hstat.remote_time)
1838             {
1839               logputs (LOG_NOTQUIET, _("\
1840 Last-modified header missing -- time-stamps turned off.\n"));
1841             }
1842           else if (hstat.remote_time)
1843             {
1844               /* Convert the date-string into struct tm.  */
1845               tmr = http_atotm (hstat.remote_time);
1846               if (tmr == (time_t) (-1))
1847                 logputs (LOG_VERBOSE, _("\
1848 Last-modified header invalid -- time-stamp ignored.\n"));
1849             }
1850         }
1851
1852       /* The time-stamping section.  */
1853       if (use_ts)
1854         {
1855           got_head = 1;
1856           *dt &= ~HEAD_ONLY;
1857           use_ts = 0;           /* no more time-stamping */
1858           count = 0;            /* the retrieve count for HEAD is
1859                                    reset */
1860           if (hstat.remote_time && tmr != (time_t) (-1))
1861             {
1862               /* Now time-stamping can be used validly.  Time-stamping
1863                  means that if the sizes of the local and remote file
1864                  match, and local file is newer than the remote file,
1865                  it will not be retrieved.  Otherwise, the normal
1866                  download procedure is resumed.  */
1867               if (tml >= tmr &&
1868                   (hstat.contlen == -1 || local_size == hstat.contlen))
1869                 {
1870                   logprintf (LOG_VERBOSE, _("\
1871 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1872                              local_filename);
1873                   free_hstat (&hstat);
1874                   FREE_MAYBE (dummy);
1875                   return RETROK;
1876                 }
1877               else if (tml >= tmr)
1878                 logprintf (LOG_VERBOSE, _("\
1879 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1880               else
1881                 logputs (LOG_VERBOSE,
1882                          _("Remote file is newer, retrieving.\n"));
1883             }
1884           free_hstat (&hstat);
1885           continue;
1886         }
1887       if ((tmr != (time_t) (-1))
1888           && !opt.spider
1889           && ((hstat.len == hstat.contlen) ||
1890               ((hstat.res == 0) &&
1891                ((hstat.contlen == -1) ||
1892                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1893         {
1894           /* #### This code repeats in http.c and ftp.c.  Move it to a
1895              function!  */
1896           const char *fl = NULL;
1897           if (opt.output_document)
1898             {
1899               if (opt.od_known_regular)
1900                 fl = opt.output_document;
1901             }
1902           else
1903             fl = *hstat.local_file;
1904           if (fl)
1905             touch (fl, tmr);
1906         }
1907       /* End of time-stamping section.  */
1908
1909       if (opt.spider)
1910         {
1911           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1912           FREE_MAYBE (dummy);
1913           return RETROK;
1914         }
1915
1916       tmrate = retr_rate (hstat.len - hstat.restval, hstat.dltime, 0);
1917
1918       if (hstat.len == hstat.contlen)
1919         {
1920           if (*dt & RETROKF)
1921             {
1922               logprintf (LOG_VERBOSE,
1923                          _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1924                          tms, tmrate, locf, hstat.len, hstat.contlen);
1925               logprintf (LOG_NONVERBOSE,
1926                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1927                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1928             }
1929           ++opt.numurls;
1930           downloaded_increase (hstat.len);
1931
1932           /* Remember that we downloaded the file for later ".orig" code. */
1933           if (*dt & ADDED_HTML_EXTENSION)
1934             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1935           else
1936             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1937
1938           free_hstat (&hstat);
1939           FREE_MAYBE (dummy);
1940           return RETROK;
1941         }
1942       else if (hstat.res == 0) /* No read error */
1943         {
1944           if (hstat.contlen == -1)  /* We don't know how much we were supposed
1945                                        to get, so assume we succeeded. */ 
1946             {
1947               if (*dt & RETROKF)
1948                 {
1949                   logprintf (LOG_VERBOSE,
1950                              _("%s (%s) - `%s' saved [%ld]\n\n"),
1951                              tms, tmrate, locf, hstat.len);
1952                   logprintf (LOG_NONVERBOSE,
1953                              "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1954                              tms, u->url, hstat.len, locf, count);
1955                 }
1956               ++opt.numurls;
1957               downloaded_increase (hstat.len);
1958
1959               /* Remember that we downloaded the file for later ".orig" code. */
1960               if (*dt & ADDED_HTML_EXTENSION)
1961                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1962               else
1963                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1964               
1965               free_hstat (&hstat);
1966               FREE_MAYBE (dummy);
1967               return RETROK;
1968             }
1969           else if (hstat.len < hstat.contlen) /* meaning we lost the
1970                                                  connection too soon */
1971             {
1972               logprintf (LOG_VERBOSE,
1973                          _("%s (%s) - Connection closed at byte %ld. "),
1974                          tms, tmrate, hstat.len);
1975               printwhat (count, opt.ntry);
1976               free_hstat (&hstat);
1977               continue;
1978             }
1979           else if (!opt.kill_longer) /* meaning we got more than expected */
1980             {
1981               logprintf (LOG_VERBOSE,
1982                          _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1983                          tms, tmrate, locf, hstat.len, hstat.contlen);
1984               logprintf (LOG_NONVERBOSE,
1985                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1986                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1987               ++opt.numurls;
1988               downloaded_increase (hstat.len);
1989
1990               /* Remember that we downloaded the file for later ".orig" code. */
1991               if (*dt & ADDED_HTML_EXTENSION)
1992                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1993               else
1994                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1995               
1996               free_hstat (&hstat);
1997               FREE_MAYBE (dummy);
1998               return RETROK;
1999             }
2000           else                  /* the same, but not accepted */
2001             {
2002               logprintf (LOG_VERBOSE,
2003                          _("%s (%s) - Connection closed at byte %ld/%ld. "),
2004                          tms, tmrate, hstat.len, hstat.contlen);
2005               printwhat (count, opt.ntry);
2006               free_hstat (&hstat);
2007               continue;
2008             }
2009         }
2010       else                      /* now hstat.res can only be -1 */
2011         {
2012           if (hstat.contlen == -1)
2013             {
2014               logprintf (LOG_VERBOSE,
2015                          _("%s (%s) - Read error at byte %ld (%s)."),
2016                          tms, tmrate, hstat.len, strerror (errno));
2017               printwhat (count, opt.ntry);
2018               free_hstat (&hstat);
2019               continue;
2020             }
2021           else                  /* hstat.res == -1 and contlen is given */
2022             {
2023               logprintf (LOG_VERBOSE,
2024                          _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2025                          tms, tmrate, hstat.len, hstat.contlen,
2026                          strerror (errno));
2027               printwhat (count, opt.ntry);
2028               free_hstat (&hstat);
2029               continue;
2030             }
2031         }
2032       /* not reached */
2033       break;
2034     }
2035   while (!opt.ntry || (count < opt.ntry));
2036   return TRYLIMEXC;
2037 }
2038 \f
2039 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2040    than local timezone.
2041
2042    mktime is similar but assumes struct tm, also known as the
2043    "broken-down" form of time, is in local time zone.  mktime_from_utc
2044    uses mktime to make the conversion understanding that an offset
2045    will be introduced by the local time assumption.
2046
2047    mktime_from_utc then measures the introduced offset by applying
2048    gmtime to the initial result and applying mktime to the resulting
2049    "broken-down" form.  The difference between the two mktime results
2050    is the measured offset which is then subtracted from the initial
2051    mktime result to yield a calendar time which is the value returned.
2052
2053    tm_isdst in struct tm is set to 0 to force mktime to introduce a
2054    consistent offset (the non DST offset) since tm and tm+o might be
2055    on opposite sides of a DST change.
2056
2057    Some implementations of mktime return -1 for the nonexistent
2058    localtime hour at the beginning of DST.  In this event, use
2059    mktime(tm - 1hr) + 3600.
2060
2061    Schematically
2062      mktime(tm)   --> t+o
2063      gmtime(t+o)  --> tm+o
2064      mktime(tm+o) --> t+2o
2065      t+o - (t+2o - t+o) = t
2066
2067    Note that glibc contains a function of the same purpose named
2068    `timegm' (reverse of gmtime).  But obviously, it is not universally
2069    available, and unfortunately it is not straightforwardly
2070    extractable for use here.  Perhaps configure should detect timegm
2071    and use it where available.
2072
2073    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2074    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2075    Further improved by Roger with assistance from Edward J. Sabol
2076    based on input by Jamie Zawinski.  */
2077
2078 static time_t
2079 mktime_from_utc (struct tm *t)
2080 {
2081   time_t tl, tb;
2082   struct tm *tg;
2083
2084   tl = mktime (t);
2085   if (tl == -1)
2086     {
2087       t->tm_hour--;
2088       tl = mktime (t);
2089       if (tl == -1)
2090         return -1; /* can't deal with output from strptime */
2091       tl += 3600;
2092     }
2093   tg = gmtime (&tl);
2094   tg->tm_isdst = 0;
2095   tb = mktime (tg);
2096   if (tb == -1)
2097     {
2098       tg->tm_hour--;
2099       tb = mktime (tg);
2100       if (tb == -1)
2101         return -1; /* can't deal with output from gmtime */
2102       tb += 3600;
2103     }
2104   return (tl - (tb - tl));
2105 }
2106
2107 /* Check whether the result of strptime() indicates success.
2108    strptime() returns the pointer to how far it got to in the string.
2109    The processing has been successful if the string is at `GMT' or
2110    `+X', or at the end of the string.
2111
2112    In extended regexp parlance, the function returns 1 if P matches
2113    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (which strptime
2114    can return) is considered a failure and 0 is returned.  */
2115 static int
2116 check_end (const char *p)
2117 {
2118   if (!p)
2119     return 0;
2120   while (ISSPACE (*p))
2121     ++p;
2122   if (!*p
2123       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2124       || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2125     return 1;
2126   else
2127     return 0;
2128 }
2129
2130 /* Convert the textual specification of time in TIME_STRING to the
2131    number of seconds since the Epoch.
2132
2133    TIME_STRING can be in any of the three formats RFC2068 allows the
2134    HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2135    Timezones are ignored, and should be GMT.
2136
2137    Return the computed time_t representation, or -1 if the conversion
2138    fails.
2139
2140    This function uses strptime with various string formats for parsing
2141    TIME_STRING.  This results in a parser that is not as lenient in
2142    interpreting TIME_STRING as I would like it to be.  Being based on
2143    strptime, it always allows shortened months, one-digit days, etc.,
2144    but due to the multitude of formats in which time can be
2145    represented, an ideal HTTP time parser would be even more
2146    forgiving.  It should completely ignore things like week days and
2147    concentrate only on the various forms of representing years,
2148    months, days, hours, minutes, and seconds.  For example, it would
2149    be nice if it accepted ISO 8601 out of the box.
2150
2151    I've investigated free and PD code for this purpose, but none was
2152    usable.  getdate was big and unwieldy, and had potential copyright
2153    issues, or so I was informed.  Dr. Marcus Hennecke's atotm(),
2154    distributed with phttpd, is excellent, but we cannot use it because
2155    it is not assigned to the FSF.  So I stuck it with strptime.  */
2156
2157 time_t
2158 http_atotm (char *time_string)
2159 {
2160   /* NOTE: Solaris strptime man page claims that %n and %t match white
2161      space, but that's not universally available.  Instead, we simply
2162      use ` ' to mean "skip all WS", which works under all strptime
2163      implementations I've tested.  */
2164
2165   static const char *time_formats[] = {
2166     "%a, %d %b %Y %T",          /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2167     "%A, %d-%b-%y %T",          /* RFC850:  Thursday, 29-Jan-98 22:12:57 */
2168     "%a, %d-%b-%Y %T",          /* pseudo-RFC850:  Thu, 29-Jan-1998 22:12:57
2169                                    (google.com uses this for their cookies.) */
2170     "%a %b %d %T %Y"            /* asctime: Thu Jan 29 22:12:57 1998 */
2171   };
2172
2173   int i;
2174   struct tm t;
2175
2176   /* According to Roger Beeman, we need to initialize tm_isdst, since
2177      strptime won't do it.  */
2178   t.tm_isdst = 0;
2179
2180   /* Note that under foreign locales Solaris strptime() fails to
2181      recognize English dates, which renders this function useless.  We
2182      solve this by being careful not to affect LC_TIME when
2183      initializing locale.
2184
2185      Another solution would be to temporarily set locale to C, invoke
2186      strptime(), and restore it back.  This is slow and dirty,
2187      however, and locale support other than LC_MESSAGES can mess other
2188      things, so I rather chose to stick with just setting LC_MESSAGES.
2189
2190      GNU strptime does not have this problem because it recognizes
2191      both international and local dates.  */
2192
2193   for (i = 0; i < ARRAY_SIZE (time_formats); i++)
2194     if (check_end (strptime (time_string, time_formats[i], &t)))
2195       return mktime_from_utc (&t);
2196
2197   /* All formats have failed.  */
2198   return -1;
2199 }
2200 \f
2201 /* Authorization support: We support two authorization schemes:
2202
2203    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2204
2205    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2206    consisting of answering to the server's challenge with the proper
2207    MD5 digests.  */
2208
2209 /* How many bytes it will take to store LEN bytes in base64.  */
2210 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2211
2212 /* Encode the string S of length LENGTH to base64 format and place it
2213    to STORE.  STORE will be 0-terminated, and must point to a writable
2214    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
2215 static void
2216 base64_encode (const char *s, char *store, int length)
2217 {
2218   /* Conversion table.  */
2219   static char tbl[64] = {
2220     'A','B','C','D','E','F','G','H',
2221     'I','J','K','L','M','N','O','P',
2222     'Q','R','S','T','U','V','W','X',
2223     'Y','Z','a','b','c','d','e','f',
2224     'g','h','i','j','k','l','m','n',
2225     'o','p','q','r','s','t','u','v',
2226     'w','x','y','z','0','1','2','3',
2227     '4','5','6','7','8','9','+','/'
2228   };
2229   int i;
2230   unsigned char *p = (unsigned char *)store;
2231
2232   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
2233   for (i = 0; i < length; i += 3)
2234     {
2235       *p++ = tbl[s[0] >> 2];
2236       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2237       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2238       *p++ = tbl[s[2] & 0x3f];
2239       s += 3;
2240     }
2241   /* Pad the result if necessary...  */
2242   if (i == length + 1)
2243     *(p - 1) = '=';
2244   else if (i == length + 2)
2245     *(p - 1) = *(p - 2) = '=';
2246   /* ...and zero-terminate it.  */
2247   *p = '\0';
2248 }
2249
2250 /* Create the authentication header contents for the `Basic' scheme.
2251    This is done by encoding the string `USER:PASS' in base64 and
2252    prepending `HEADER: Basic ' to it.  */
2253 static char *
2254 basic_authentication_encode (const char *user, const char *passwd,
2255                              const char *header)
2256 {
2257   char *t1, *t2, *res;
2258   int len1 = strlen (user) + 1 + strlen (passwd);
2259   int len2 = BASE64_LENGTH (len1);
2260
2261   t1 = (char *)alloca (len1 + 1);
2262   sprintf (t1, "%s:%s", user, passwd);
2263   t2 = (char *)alloca (1 + len2);
2264   base64_encode (t1, t2, len1);
2265   res = (char *)xmalloc (len2 + 11 + strlen (header));
2266   sprintf (res, "%s: Basic %s\r\n", header, t2);
2267
2268   return res;
2269 }
2270
2271 #ifdef USE_DIGEST
2272 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
2273    of a field in such a header.  If the field is the one specified by
2274    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2275    digest authorization code), extract its value in the (char*)
2276    variable pointed by RET.  Returns negative on a malformed header,
2277    or number of bytes that have been parsed by this call.  */
2278 static int
2279 extract_header_attr (const char *au, const char *attr_name, char **ret)
2280 {
2281   const char *cp, *ep;
2282
2283   ep = cp = au;
2284
2285   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2286     {
2287       cp += strlen (attr_name);
2288       if (!*cp)
2289         return -1;
2290       cp += skip_lws (cp);
2291       if (*cp != '=')
2292         return -1;
2293       if (!*++cp)
2294         return -1;
2295       cp += skip_lws (cp);
2296       if (*cp != '\"')
2297         return -1;
2298       if (!*++cp)
2299         return -1;
2300       for (ep = cp; *ep && *ep != '\"'; ep++)
2301         ;
2302       if (!*ep)
2303         return -1;
2304       FREE_MAYBE (*ret);
2305       *ret = strdupdelim (cp, ep);
2306       return ep - au + 1;
2307     }
2308   else
2309     return 0;
2310 }
2311
2312 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
2313    an array of 16 bytes containing the hash keys, and BUF should be a
2314    buffer of 33 writable characters (32 for hex digits plus one for
2315    zero termination).  */
2316 static void
2317 dump_hash (unsigned char *buf, const unsigned char *hash)
2318 {
2319   int i;
2320
2321   for (i = 0; i < MD5_HASHLEN; i++, hash++)
2322     {
2323       *buf++ = XDIGIT_TO_xchar (*hash >> 4);
2324       *buf++ = XDIGIT_TO_xchar (*hash & 0xf);
2325     }
2326   *buf = '\0';
2327 }
2328
2329 /* Take the line apart to find the challenge, and compose a digest
2330    authorization header.  See RFC2069 section 2.1.2.  */
2331 static char *
2332 digest_authentication_encode (const char *au, const char *user,
2333                               const char *passwd, const char *method,
2334                               const char *path)
2335 {
2336   static char *realm, *opaque, *nonce;
2337   static struct {
2338     const char *name;
2339     char **variable;
2340   } options[] = {
2341     { "realm", &realm },
2342     { "opaque", &opaque },
2343     { "nonce", &nonce }
2344   };
2345   char *res;
2346
2347   realm = opaque = nonce = NULL;
2348
2349   au += 6;                      /* skip over `Digest' */
2350   while (*au)
2351     {
2352       int i;
2353
2354       au += skip_lws (au);
2355       for (i = 0; i < ARRAY_SIZE (options); i++)
2356         {
2357           int skip = extract_header_attr (au, options[i].name,
2358                                           options[i].variable);
2359           if (skip < 0)
2360             {
2361               FREE_MAYBE (realm);
2362               FREE_MAYBE (opaque);
2363               FREE_MAYBE (nonce);
2364               return NULL;
2365             }
2366           else if (skip)
2367             {
2368               au += skip;
2369               break;
2370             }
2371         }
2372       if (i == ARRAY_SIZE (options))
2373         {
2374           while (*au && *au != '=')
2375             au++;
2376           if (*au && *++au)
2377             {
2378               au += skip_lws (au);
2379               if (*au == '\"')
2380                 {
2381                   au++;
2382                   while (*au && *au != '\"')
2383                     au++;
2384                   if (*au)
2385                     au++;
2386                 }
2387             }
2388         }
2389       while (*au && *au != ',')
2390         au++;
2391       if (*au)
2392         au++;
2393     }
2394   if (!realm || !nonce || !user || !passwd || !path || !method)
2395     {
2396       FREE_MAYBE (realm);
2397       FREE_MAYBE (opaque);
2398       FREE_MAYBE (nonce);
2399       return NULL;
2400     }
2401
2402   /* Calculate the digest value.  */
2403   {
2404     ALLOCA_MD5_CONTEXT (ctx);
2405     unsigned char hash[MD5_HASHLEN];
2406     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2407     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2408
2409     /* A1BUF = H(user ":" realm ":" password) */
2410     gen_md5_init (ctx);
2411     gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2412     gen_md5_update ((unsigned char *)":", 1, ctx);
2413     gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2414     gen_md5_update ((unsigned char *)":", 1, ctx);
2415     gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2416     gen_md5_finish (ctx, hash);
2417     dump_hash (a1buf, hash);
2418
2419     /* A2BUF = H(method ":" path) */
2420     gen_md5_init (ctx);
2421     gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2422     gen_md5_update ((unsigned char *)":", 1, ctx);
2423     gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2424     gen_md5_finish (ctx, hash);
2425     dump_hash (a2buf, hash);
2426
2427     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2428     gen_md5_init (ctx);
2429     gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2430     gen_md5_update ((unsigned char *)":", 1, ctx);
2431     gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2432     gen_md5_update ((unsigned char *)":", 1, ctx);
2433     gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2434     gen_md5_finish (ctx, hash);
2435     dump_hash (response_digest, hash);
2436
2437     res = (char*) xmalloc (strlen (user)
2438                            + strlen (user)
2439                            + strlen (realm)
2440                            + strlen (nonce)
2441                            + strlen (path)
2442                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2443                            + (opaque ? strlen (opaque) : 0)
2444                            + 128);
2445     sprintf (res, "Authorization: Digest \
2446 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2447              user, realm, nonce, path, response_digest);
2448     if (opaque)
2449       {
2450         char *p = res + strlen (res);
2451         strcat (p, ", opaque=\"");
2452         strcat (p, opaque);
2453         strcat (p, "\"");
2454       }
2455     strcat (res, "\r\n");
2456   }
2457   return res;
2458 }
2459 #endif /* USE_DIGEST */
2460
2461
2462 #define BEGINS_WITH(line, string_constant)                              \
2463   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
2464    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
2465        || !line[sizeof (string_constant) - 1]))
2466
2467 static int
2468 known_authentication_scheme_p (const char *au)
2469 {
2470   return BEGINS_WITH (au, "Basic")
2471     || BEGINS_WITH (au, "Digest")
2472     || BEGINS_WITH (au, "NTLM");
2473 }
2474
2475 #undef BEGINS_WITH
2476
2477 /* Create the HTTP authorization request header.  When the
2478    `WWW-Authenticate' response header is seen, according to the
2479    authorization scheme specified in that header (`Basic' and `Digest'
2480    are supported by the current implementation), produce an
2481    appropriate HTTP authorization request header.  */
2482 static char *
2483 create_authorization_line (const char *au, const char *user,
2484                            const char *passwd, const char *method,
2485                            const char *path)
2486 {
2487   char *wwwauth = NULL;
2488
2489   if (!strncasecmp (au, "Basic", 5))
2490     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2491   if (!strncasecmp (au, "NTLM", 4))
2492     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2493 #ifdef USE_DIGEST
2494   else if (!strncasecmp (au, "Digest", 6))
2495     wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2496 #endif /* USE_DIGEST */
2497   return wwwauth;
2498 }
2499 \f
2500 void
2501 http_cleanup (void)
2502 {
2503   if (pc_last_host_ip)
2504     address_list_release (pc_last_host_ip);
2505 }