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