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