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