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