]> sjero.net Git - wget/blob - src/http.c
[svn] Cosmetic cleanup of SSL stuff.
[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   static int first_retrieval = 1;
1238
1239   int count;
1240   int use_ts, got_head = 0;     /* time-stamping info */
1241   char *filename_plus_orig_suffix;
1242   char *local_filename = NULL;
1243   char *tms, *suf, *locf, *tmrate;
1244   uerr_t err;
1245   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
1246   long local_size = 0;          /* the size of the local file */
1247   size_t filename_len;
1248   struct http_stat hstat;       /* HTTP status */
1249   struct stat st;
1250
1251   *newloc = NULL;
1252
1253   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
1254      has_wildcards_p because it would also warn on `?', and we know that
1255      shows up in CGI paths a *lot*.  */
1256   if (strchr (u->url, '*'))
1257     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1258
1259   /* Determine the local filename.  */
1260   if (!u->local)
1261     u->local = url_filename (u->proxy ? u->proxy : u);
1262
1263   if (!opt.output_document)
1264     locf = u->local;
1265   else
1266     locf = opt.output_document;
1267
1268   /* Yuck.  Multiple returns suck.  We need to remember to free() the space we
1269      xmalloc() here before EACH return.  This is one reason it's better to set
1270      flags that influence flow control and then return once at the end. */
1271   filename_len = strlen(u->local);
1272   filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1273
1274   if (opt.noclobber && file_exists_p (u->local))
1275     {
1276       /* If opt.noclobber is turned on and file already exists, do not
1277          retrieve the file */
1278       logprintf (LOG_VERBOSE, _("\
1279 File `%s' already there, will not retrieve.\n"), u->local);
1280       /* If the file is there, we suppose it's retrieved OK.  */
1281       *dt |= RETROKF;
1282
1283       /* #### Bogusness alert.  */
1284       /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1285          text/html, a harmless lie.  */
1286       if (((suf = suffix (u->local)) != NULL)
1287           && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1288         *dt |= TEXTHTML;
1289       xfree (suf);
1290       xfree (filename_plus_orig_suffix); /* must precede every return! */
1291       /* Another harmless lie: */
1292       return RETROK;
1293     }
1294
1295   use_ts = 0;
1296   if (opt.timestamping)
1297     {
1298       boolean  local_dot_orig_file_exists = FALSE;
1299
1300       if (opt.backup_converted)
1301         /* If -K is specified, we'll act on the assumption that it was specified
1302            last time these files were downloaded as well, and instead of just
1303            comparing local file X against server file X, we'll compare local
1304            file X.orig (if extant, else X) against server file X.  If -K
1305            _wasn't_ specified last time, or the server contains files called
1306            *.orig, -N will be back to not operating correctly with -k. */
1307         {
1308           /* Would a single s[n]printf() call be faster?  --dan
1309
1310              It wouldn't.  sprintf() is horribly slow.  At one point I
1311              profiled Wget, and found that a measurable and
1312              non-negligible amount of time was lost calling sprintf()
1313              in url.c.  Replacing sprintf with inline calls to
1314              strcpy() and long_to_string() made a difference.
1315              --hniksic */
1316           strcpy(filename_plus_orig_suffix, u->local);
1317           strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1318
1319           /* Try to stat() the .orig file. */
1320           if (stat(filename_plus_orig_suffix, &st) == 0)
1321             {
1322               local_dot_orig_file_exists = TRUE;
1323               local_filename = filename_plus_orig_suffix;
1324             }
1325         }      
1326
1327       if (!local_dot_orig_file_exists)
1328         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1329         if (stat (u->local, &st) == 0)
1330           local_filename = u->local;
1331
1332       if (local_filename != NULL)
1333         /* There was a local file, so we'll check later to see if the version
1334            the server has is the same version we already have, allowing us to
1335            skip a download. */
1336         {
1337           use_ts = 1;
1338           tml = st.st_mtime;
1339           local_size = st.st_size;
1340           got_head = 0;
1341         }
1342     }
1343   /* Reset the counter.  */
1344   count = 0;
1345   *dt = 0 | ACCEPTRANGES;
1346   /* THE loop */
1347   do
1348     {
1349       /* Increment the pass counter.  */
1350       ++count;
1351       /* Wait before the retrieval (unless this is the very first
1352          retrieval).
1353          Check if we are retrying or not, wait accordingly - HEH */
1354       if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
1355         {
1356           if (count)
1357             {
1358               if (count<opt.waitretry)
1359                 sleep(count);
1360               else
1361                 sleep(opt.waitretry);
1362             }
1363           else
1364             sleep (opt.wait);
1365         }
1366       if (first_retrieval)
1367         first_retrieval = 0;
1368       /* Get the current time string.  */
1369       tms = time_str (NULL);
1370       /* Print fetch message, if opt.verbose.  */
1371       if (opt.verbose)
1372         {
1373           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1374           char tmp[15];
1375           strcpy (tmp, "        ");
1376           if (count > 1)
1377             sprintf (tmp, _("(try:%2d)"), count);
1378           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1379                      tms, hurl, tmp, locf);
1380 #ifdef WINDOWS
1381           ws_changetitle (hurl, 1);
1382 #endif
1383           xfree (hurl);
1384         }
1385
1386       /* Default document type is empty.  However, if spider mode is
1387          on or time-stamping is employed, HEAD_ONLY commands is
1388          encoded within *dt.  */
1389       if (opt.spider || (use_ts && !got_head))
1390         *dt |= HEAD_ONLY;
1391       else
1392         *dt &= ~HEAD_ONLY;
1393       /* Assume no restarting.  */
1394       hstat.restval = 0L;
1395       /* Decide whether or not to restart.  */
1396       if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1397           && file_exists_p (u->local))
1398         if (stat (u->local, &st) == 0)
1399           hstat.restval = st.st_size;
1400       /* Decide whether to send the no-cache directive.  */
1401       if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1402         *dt |= SEND_NOCACHE;
1403       else
1404         *dt &= ~SEND_NOCACHE;
1405
1406       /* Try fetching the document, or at least its head.  :-) */
1407       err = gethttp (u, &hstat, dt);
1408
1409       /* It's unfortunate that wget determines the local filename before finding
1410          out the Content-Type of the file.  Barring a major restructuring of the
1411          code, we need to re-set locf here, since gethttp() may have xrealloc()d
1412          u->local to tack on ".html". */
1413       if (!opt.output_document)
1414         locf = u->local;
1415       else
1416         locf = opt.output_document;
1417
1418       /* Time?  */
1419       tms = time_str (NULL);
1420       /* Get the new location (with or without the redirection).  */
1421       if (hstat.newloc)
1422         *newloc = xstrdup (hstat.newloc);
1423       switch (err)
1424         {
1425         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1426         case CONERROR: case READERR: case WRITEFAILED:
1427         case RANGEERR:
1428           /* Non-fatal errors continue executing the loop, which will
1429              bring them to "while" statement at the end, to judge
1430              whether the number of tries was exceeded.  */
1431           FREEHSTAT (hstat);
1432           printwhat (count, opt.ntry);
1433           continue;
1434           break;
1435         case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1436           /* Fatal errors just return from the function.  */
1437           FREEHSTAT (hstat);
1438           xfree (filename_plus_orig_suffix); /* must precede every return! */
1439           return err;
1440           break;
1441         case FWRITEERR: case FOPENERR:
1442           /* Another fatal error.  */
1443           logputs (LOG_VERBOSE, "\n");
1444           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1445                      u->local, strerror (errno));
1446           FREEHSTAT (hstat);
1447           return err;
1448           break;
1449    case CONSSLERR:
1450           /* Another fatal error.  */
1451           logputs (LOG_VERBOSE, "\n");
1452           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1453           FREEHSTAT (hstat);
1454           xfree (filename_plus_orig_suffix); /* must precede every return! */
1455           return err;
1456           break;
1457         case NEWLOCATION:
1458           /* Return the new location to the caller.  */
1459           if (!hstat.newloc)
1460             {
1461               logprintf (LOG_NOTQUIET,
1462                          _("ERROR: Redirection (%d) without location.\n"),
1463                          hstat.statcode);
1464               xfree (filename_plus_orig_suffix); /* must precede every return! */
1465               return WRONGCODE;
1466             }
1467           FREEHSTAT (hstat);
1468           xfree (filename_plus_orig_suffix); /* must precede every return! */
1469           return NEWLOCATION;
1470           break;
1471         case RETRFINISHED:
1472           /* Deal with you later.  */
1473           break;
1474         default:
1475           /* All possibilities should have been exhausted.  */
1476           abort ();
1477         }
1478       if (!(*dt & RETROKF))
1479         {
1480           if (!opt.verbose)
1481             {
1482               /* #### Ugly ugly ugly! */
1483               char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1484               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1485               xfree (hurl);
1486             }
1487           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1488                      tms, hstat.statcode, hstat.error);
1489           logputs (LOG_VERBOSE, "\n");
1490           FREEHSTAT (hstat);
1491           xfree (filename_plus_orig_suffix); /* must precede every return! */
1492           return WRONGCODE;
1493         }
1494
1495       /* Did we get the time-stamp?  */
1496       if (!got_head)
1497         {
1498           if (opt.timestamping && !hstat.remote_time)
1499             {
1500               logputs (LOG_NOTQUIET, _("\
1501 Last-modified header missing -- time-stamps turned off.\n"));
1502             }
1503           else if (hstat.remote_time)
1504             {
1505               /* Convert the date-string into struct tm.  */
1506               tmr = http_atotm (hstat.remote_time);
1507               if (tmr == (time_t) (-1))
1508                 logputs (LOG_VERBOSE, _("\
1509 Last-modified header invalid -- time-stamp ignored.\n"));
1510             }
1511         }
1512
1513       /* The time-stamping section.  */
1514       if (use_ts)
1515         {
1516           got_head = 1;
1517           *dt &= ~HEAD_ONLY;
1518           use_ts = 0;           /* no more time-stamping */
1519           count = 0;            /* the retrieve count for HEAD is
1520                                    reset */
1521           if (hstat.remote_time && tmr != (time_t) (-1))
1522             {
1523               /* Now time-stamping can be used validly.  Time-stamping
1524                  means that if the sizes of the local and remote file
1525                  match, and local file is newer than the remote file,
1526                  it will not be retrieved.  Otherwise, the normal
1527                  download procedure is resumed.  */
1528               if (tml >= tmr &&
1529                   (hstat.contlen == -1 || local_size == hstat.contlen))
1530                 {
1531                   logprintf (LOG_VERBOSE, _("\
1532 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1533                              local_filename);
1534                   FREEHSTAT (hstat);
1535                   xfree (filename_plus_orig_suffix); /*must precede every return!*/
1536                   return RETROK;
1537                 }
1538               else if (tml >= tmr)
1539                 logprintf (LOG_VERBOSE, _("\
1540 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1541               else
1542                 logputs (LOG_VERBOSE,
1543                          _("Remote file is newer, retrieving.\n"));
1544             }
1545           FREEHSTAT (hstat);
1546           continue;
1547         }
1548       if (!opt.dfp
1549           && (tmr != (time_t) (-1))
1550           && !opt.spider
1551           && ((hstat.len == hstat.contlen) ||
1552               ((hstat.res == 0) &&
1553                ((hstat.contlen == -1) ||
1554                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1555         {
1556           touch (u->local, tmr);
1557         }
1558       /* End of time-stamping section.  */
1559
1560       if (opt.spider)
1561         {
1562           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1563           xfree (filename_plus_orig_suffix); /* must precede every return! */
1564           return RETROK;
1565         }
1566
1567       /* It is now safe to free the remainder of hstat, since the
1568          strings within it will no longer be used.  */
1569       FREEHSTAT (hstat);
1570
1571       tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1572
1573       if (hstat.len == hstat.contlen)
1574         {
1575           if (*dt & RETROKF)
1576             {
1577               logprintf (LOG_VERBOSE,
1578                          _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1579                          tms, tmrate, locf, hstat.len, hstat.contlen);
1580               logprintf (LOG_NONVERBOSE,
1581                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1582                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1583             }
1584           ++opt.numurls;
1585           downloaded_increase (hstat.len);
1586
1587           /* Remember that we downloaded the file for later ".orig" code. */
1588           if (*dt & ADDED_HTML_EXTENSION)
1589             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1590           else
1591             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1592
1593           xfree(filename_plus_orig_suffix); /* must precede every return! */
1594           return RETROK;
1595         }
1596       else if (hstat.res == 0) /* No read error */
1597         {
1598           if (hstat.contlen == -1)  /* We don't know how much we were supposed
1599                                        to get, so assume we succeeded. */ 
1600             {
1601               if (*dt & RETROKF)
1602                 {
1603                   logprintf (LOG_VERBOSE,
1604                              _("%s (%s) - `%s' saved [%ld]\n\n"),
1605                              tms, tmrate, locf, hstat.len);
1606                   logprintf (LOG_NONVERBOSE,
1607                              "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1608                              tms, u->url, hstat.len, locf, count);
1609                 }
1610               ++opt.numurls;
1611               downloaded_increase (hstat.len);
1612
1613               /* Remember that we downloaded the file for later ".orig" code. */
1614               if (*dt & ADDED_HTML_EXTENSION)
1615                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1616               else
1617                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1618               
1619               xfree (filename_plus_orig_suffix); /* must precede every return! */
1620               return RETROK;
1621             }
1622           else if (hstat.len < hstat.contlen) /* meaning we lost the
1623                                                  connection too soon */
1624             {
1625               logprintf (LOG_VERBOSE,
1626                          _("%s (%s) - Connection closed at byte %ld. "),
1627                          tms, tmrate, hstat.len);
1628               printwhat (count, opt.ntry);
1629               continue;
1630             }
1631           else if (!opt.kill_longer) /* meaning we got more than expected */
1632             {
1633               logprintf (LOG_VERBOSE,
1634                          _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1635                          tms, tmrate, locf, hstat.len, hstat.contlen);
1636               logprintf (LOG_NONVERBOSE,
1637                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1638                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1639               ++opt.numurls;
1640               downloaded_increase (hstat.len);
1641
1642               /* Remember that we downloaded the file for later ".orig" code. */
1643               if (*dt & ADDED_HTML_EXTENSION)
1644                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1645               else
1646                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1647               
1648               xfree (filename_plus_orig_suffix); /* must precede every return! */
1649               return RETROK;
1650             }
1651           else                  /* the same, but not accepted */
1652             {
1653               logprintf (LOG_VERBOSE,
1654                          _("%s (%s) - Connection closed at byte %ld/%ld. "),
1655                          tms, tmrate, hstat.len, hstat.contlen);
1656               printwhat (count, opt.ntry);
1657               continue;
1658             }
1659         }
1660       else                      /* now hstat.res can only be -1 */
1661         {
1662           if (hstat.contlen == -1)
1663             {
1664               logprintf (LOG_VERBOSE,
1665                          _("%s (%s) - Read error at byte %ld (%s)."),
1666                          tms, tmrate, hstat.len, strerror (errno));
1667               printwhat (count, opt.ntry);
1668               continue;
1669             }
1670           else                  /* hstat.res == -1 and contlen is given */
1671             {
1672               logprintf (LOG_VERBOSE,
1673                          _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1674                          tms, tmrate, hstat.len, hstat.contlen,
1675                          strerror (errno));
1676               printwhat (count, opt.ntry);
1677               continue;
1678             }
1679         }
1680       /* not reached */
1681       break;
1682     }
1683   while (!opt.ntry || (count < opt.ntry));
1684   xfree (filename_plus_orig_suffix); /* must precede every return! */
1685   return TRYLIMEXC;
1686 }
1687 \f
1688 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1689    than local timezone (mktime assumes the latter).
1690
1691    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1692    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.  */
1693 static time_t
1694 mktime_from_utc (struct tm *t)
1695 {
1696   time_t tl, tb;
1697
1698   tl = mktime (t);
1699   if (tl == -1)
1700     return -1;
1701   tb = mktime (gmtime (&tl));
1702   return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1703 }
1704
1705 /* Check whether the result of strptime() indicates success.
1706    strptime() returns the pointer to how far it got to in the string.
1707    The processing has been successful if the string is at `GMT' or
1708    `+X', or at the end of the string.
1709
1710    In extended regexp parlance, the function returns 1 if P matches
1711    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (a valid result of
1712    strptime()) is considered a failure and 0 is returned.  */
1713 static int
1714 check_end (const char *p)
1715 {
1716   if (!p)
1717     return 0;
1718   while (ISSPACE (*p))
1719     ++p;
1720   if (!*p
1721       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1722       || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1723     return 1;
1724   else
1725     return 0;
1726 }
1727
1728 /* Convert TIME_STRING time to time_t.  TIME_STRING can be in any of
1729    the three formats RFC2068 allows the HTTP servers to emit --
1730    RFC1123-date, RFC850-date or asctime-date.  Timezones are ignored,
1731    and should be GMT.
1732
1733    We use strptime() to recognize various dates, which makes it a
1734    little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1735    allows shortened dates and months, one-digit days, etc.).  It also
1736    allows more than one space anywhere where the specs require one SP.
1737    The routine should probably be even more forgiving (as recommended
1738    by RFC2068), but I do not have the time to write one.
1739
1740    Return the computed time_t representation, or -1 if all the
1741    schemes fail.
1742
1743    Needless to say, what we *really* need here is something like
1744    Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1745    and does not use strptime().  atotm() is to be found in the sources
1746    of `phttpd', a little-known HTTP server written by Peter Erikson.  */
1747 static time_t
1748 http_atotm (char *time_string)
1749 {
1750   struct tm t;
1751
1752   /* Roger Beeman says: "This function dynamically allocates struct tm
1753      t, but does no initialization.  The only field that actually
1754      needs initialization is tm_isdst, since the others will be set by
1755      strptime.  Since strptime does not set tm_isdst, it will return
1756      the data structure with whatever data was in tm_isdst to begin
1757      with.  For those of us in timezones where DST can occur, there
1758      can be a one hour shift depending on the previous contents of the
1759      data area where the data structure is allocated."  */
1760   t.tm_isdst = -1;
1761
1762   /* Note that under foreign locales Solaris strptime() fails to
1763      recognize English dates, which renders this function useless.  I
1764      assume that other non-GNU strptime's are plagued by the same
1765      disease.  We solve this by setting only LC_MESSAGES in
1766      i18n_initialize(), instead of LC_ALL.
1767
1768      Another solution could be to temporarily set locale to C, invoke
1769      strptime(), and restore it back.  This is slow and dirty,
1770      however, and locale support other than LC_MESSAGES can mess other
1771      things, so I rather chose to stick with just setting LC_MESSAGES.
1772
1773      Also note that none of this is necessary under GNU strptime(),
1774      because it recognizes both international and local dates.  */
1775
1776   /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1777      it to eat all white space up to (and including) a newline, and
1778      the function fails if there is no newline (!).
1779
1780      Let's hope all strptime() implementations use ` ' to skip *all*
1781      whitespace instead of just one (it works that way on all the
1782      systems I've tested it on).  */
1783
1784   /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1785   if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1786     return mktime_from_utc (&t);
1787   /* RFC850:  Thu, 29-Jan-98 22:12:57 */
1788   if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1789     return mktime_from_utc (&t);
1790   /* asctime: Thu Jan 29 22:12:57 1998 */
1791   if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1792     return mktime_from_utc (&t);
1793   /* Failure.  */
1794   return -1;
1795 }
1796 \f
1797 /* Authorization support: We support two authorization schemes:
1798
1799    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1800
1801    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1802    consisting of answering to the server's challenge with the proper
1803    MD5 digests.  */
1804
1805 /* How many bytes it will take to store LEN bytes in base64.  */
1806 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1807
1808 /* Encode the string S of length LENGTH to base64 format and place it
1809    to STORE.  STORE will be 0-terminated, and must point to a writable
1810    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
1811 static void
1812 base64_encode (const char *s, char *store, int length)
1813 {
1814   /* Conversion table.  */
1815   static char tbl[64] = {
1816     'A','B','C','D','E','F','G','H',
1817     'I','J','K','L','M','N','O','P',
1818     'Q','R','S','T','U','V','W','X',
1819     'Y','Z','a','b','c','d','e','f',
1820     'g','h','i','j','k','l','m','n',
1821     'o','p','q','r','s','t','u','v',
1822     'w','x','y','z','0','1','2','3',
1823     '4','5','6','7','8','9','+','/'
1824   };
1825   int i;
1826   unsigned char *p = (unsigned char *)store;
1827
1828   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
1829   for (i = 0; i < length; i += 3)
1830     {
1831       *p++ = tbl[s[0] >> 2];
1832       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1833       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1834       *p++ = tbl[s[2] & 0x3f];
1835       s += 3;
1836     }
1837   /* Pad the result if necessary...  */
1838   if (i == length + 1)
1839     *(p - 1) = '=';
1840   else if (i == length + 2)
1841     *(p - 1) = *(p - 2) = '=';
1842   /* ...and zero-terminate it.  */
1843   *p = '\0';
1844 }
1845
1846 /* Create the authentication header contents for the `Basic' scheme.
1847    This is done by encoding the string `USER:PASS' in base64 and
1848    prepending `HEADER: Basic ' to it.  */
1849 static char *
1850 basic_authentication_encode (const char *user, const char *passwd,
1851                              const char *header)
1852 {
1853   char *t1, *t2, *res;
1854   int len1 = strlen (user) + 1 + strlen (passwd);
1855   int len2 = BASE64_LENGTH (len1);
1856
1857   t1 = (char *)alloca (len1 + 1);
1858   sprintf (t1, "%s:%s", user, passwd);
1859   t2 = (char *)alloca (1 + len2);
1860   base64_encode (t1, t2, len1);
1861   res = (char *)malloc (len2 + 11 + strlen (header));
1862   sprintf (res, "%s: Basic %s\r\n", header, t2);
1863
1864   return res;
1865 }
1866
1867 #ifdef USE_DIGEST
1868 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
1869    of a field in such a header.  If the field is the one specified by
1870    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1871    digest authorization code), extract its value in the (char*)
1872    variable pointed by RET.  Returns negative on a malformed header,
1873    or number of bytes that have been parsed by this call.  */
1874 static int
1875 extract_header_attr (const char *au, const char *attr_name, char **ret)
1876 {
1877   const char *cp, *ep;
1878
1879   ep = cp = au;
1880
1881   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1882     {
1883       cp += strlen (attr_name);
1884       if (!*cp)
1885         return -1;
1886       cp += skip_lws (cp);
1887       if (*cp != '=')
1888         return -1;
1889       if (!*++cp)
1890         return -1;
1891       cp += skip_lws (cp);
1892       if (*cp != '\"')
1893         return -1;
1894       if (!*++cp)
1895         return -1;
1896       for (ep = cp; *ep && *ep != '\"'; ep++)
1897         ;
1898       if (!*ep)
1899         return -1;
1900       FREE_MAYBE (*ret);
1901       *ret = strdupdelim (cp, ep);
1902       return ep - au + 1;
1903     }
1904   else
1905     return 0;
1906 }
1907
1908 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1909    from url.h.  See RFC 2069 2.1.2 for the syntax of response-digest.  */
1910 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1911
1912 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
1913    an array of 16 bytes containing the hash keys, and BUF should be a
1914    buffer of 33 writable characters (32 for hex digits plus one for
1915    zero termination).  */
1916 static void
1917 dump_hash (unsigned char *buf, const unsigned char *hash)
1918 {
1919   int i;
1920
1921   for (i = 0; i < MD5_HASHLEN; i++, hash++)
1922     {
1923       *buf++ = HEXD2asc (*hash >> 4);
1924       *buf++ = HEXD2asc (*hash & 0xf);
1925     }
1926   *buf = '\0';
1927 }
1928
1929 /* Take the line apart to find the challenge, and compose a digest
1930    authorization header.  See RFC2069 section 2.1.2.  */
1931 char *
1932 digest_authentication_encode (const char *au, const char *user,
1933                               const char *passwd, const char *method,
1934                               const char *path)
1935 {
1936   static char *realm, *opaque, *nonce;
1937   static struct {
1938     const char *name;
1939     char **variable;
1940   } options[] = {
1941     { "realm", &realm },
1942     { "opaque", &opaque },
1943     { "nonce", &nonce }
1944   };
1945   char *res;
1946
1947   realm = opaque = nonce = NULL;
1948
1949   au += 6;                      /* skip over `Digest' */
1950   while (*au)
1951     {
1952       int i;
1953
1954       au += skip_lws (au);
1955       for (i = 0; i < ARRAY_SIZE (options); i++)
1956         {
1957           int skip = extract_header_attr (au, options[i].name,
1958                                           options[i].variable);
1959           if (skip < 0)
1960             {
1961               FREE_MAYBE (realm);
1962               FREE_MAYBE (opaque);
1963               FREE_MAYBE (nonce);
1964               return NULL;
1965             }
1966           else if (skip)
1967             {
1968               au += skip;
1969               break;
1970             }
1971         }
1972       if (i == ARRAY_SIZE (options))
1973         {
1974           while (*au && *au != '=')
1975             au++;
1976           if (*au && *++au)
1977             {
1978               au += skip_lws (au);
1979               if (*au == '\"')
1980                 {
1981                   au++;
1982                   while (*au && *au != '\"')
1983                     au++;
1984                   if (*au)
1985                     au++;
1986                 }
1987             }
1988         }
1989       while (*au && *au != ',')
1990         au++;
1991       if (*au)
1992         au++;
1993     }
1994   if (!realm || !nonce || !user || !passwd || !path || !method)
1995     {
1996       FREE_MAYBE (realm);
1997       FREE_MAYBE (opaque);
1998       FREE_MAYBE (nonce);
1999       return NULL;
2000     }
2001
2002   /* Calculate the digest value.  */
2003   {
2004     struct md5_ctx ctx;
2005     unsigned char hash[MD5_HASHLEN];
2006     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2007     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2008
2009     /* A1BUF = H(user ":" realm ":" password) */
2010     md5_init_ctx (&ctx);
2011     md5_process_bytes (user, strlen (user), &ctx);
2012     md5_process_bytes (":", 1, &ctx);
2013     md5_process_bytes (realm, strlen (realm), &ctx);
2014     md5_process_bytes (":", 1, &ctx);
2015     md5_process_bytes (passwd, strlen (passwd), &ctx);
2016     md5_finish_ctx (&ctx, hash);
2017     dump_hash (a1buf, hash);
2018
2019     /* A2BUF = H(method ":" path) */
2020     md5_init_ctx (&ctx);
2021     md5_process_bytes (method, strlen (method), &ctx);
2022     md5_process_bytes (":", 1, &ctx);
2023     md5_process_bytes (path, strlen (path), &ctx);
2024     md5_finish_ctx (&ctx, hash);
2025     dump_hash (a2buf, hash);
2026
2027     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2028     md5_init_ctx (&ctx);
2029     md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2030     md5_process_bytes (":", 1, &ctx);
2031     md5_process_bytes (nonce, strlen (nonce), &ctx);
2032     md5_process_bytes (":", 1, &ctx);
2033     md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2034     md5_finish_ctx (&ctx, hash);
2035     dump_hash (response_digest, hash);
2036
2037     res = (char*) xmalloc (strlen (user)
2038                            + strlen (user)
2039                            + strlen (realm)
2040                            + strlen (nonce)
2041                            + strlen (path)
2042                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2043                            + (opaque ? strlen (opaque) : 0)
2044                            + 128);
2045     sprintf (res, "Authorization: Digest \
2046 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2047              user, realm, nonce, path, response_digest);
2048     if (opaque)
2049       {
2050         char *p = res + strlen (res);
2051         strcat (p, ", opaque=\"");
2052         strcat (p, opaque);
2053         strcat (p, "\"");
2054       }
2055     strcat (res, "\r\n");
2056   }
2057   return res;
2058 }
2059 #endif /* USE_DIGEST */
2060
2061
2062 #define BEGINS_WITH(line, string_constant)                              \
2063   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
2064    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
2065        || !line[sizeof (string_constant) - 1]))
2066
2067 static int
2068 known_authentication_scheme_p (const char *au)
2069 {
2070   return BEGINS_WITH (au, "Basic")
2071     || BEGINS_WITH (au, "Digest")
2072     || BEGINS_WITH (au, "NTLM");
2073 }
2074
2075 #undef BEGINS_WITH
2076
2077 /* Create the HTTP authorization request header.  When the
2078    `WWW-Authenticate' response header is seen, according to the
2079    authorization scheme specified in that header (`Basic' and `Digest'
2080    are supported by the current implementation), produce an
2081    appropriate HTTP authorization request header.  */
2082 static char *
2083 create_authorization_line (const char *au, const char *user,
2084                            const char *passwd, const char *method,
2085                            const char *path)
2086 {
2087   char *wwwauth = NULL;
2088
2089   if (!strncasecmp (au, "Basic", 5))
2090     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2091   if (!strncasecmp (au, "NTLM", 4))
2092     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2093 #ifdef USE_DIGEST
2094   else if (!strncasecmp (au, "Digest", 6))
2095     wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2096 #endif /* USE_DIGEST */
2097   return wwwauth;
2098 }