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