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