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