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