]> sjero.net Git - wget/blob - src/http.c
[svn] Rewrite SSL #ifdef for better indentation.
[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 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <assert.h>
34 #include <errno.h>
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #ifdef WINDOWS
47 # include <winsock.h>
48 #else
49 # include <netdb.h>             /* for h_errno */
50 #endif
51
52 #include "wget.h"
53 #include "utils.h"
54 #include "url.h"
55 #include "host.h"
56 #include "rbuf.h"
57 #include "retr.h"
58 #include "headers.h"
59 #include "connect.h"
60 #include "fnmatch.h"
61 #include "netrc.h"
62 #if USE_DIGEST
63 # include "md5.h"
64 #endif
65 #ifdef HAVE_SSL
66 # include "gen_sslfunc.h"
67 #endif /* HAVE_SSL */
68 #include "cookies.h"
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   int no_truncate;              /* whether truncating the file is
467                                    forbidden. */
468 };
469
470 /* Free the elements of hstat X.  */
471 #define FREEHSTAT(x) do                                 \
472 {                                                       \
473   FREE_MAYBE ((x).newloc);                              \
474   FREE_MAYBE ((x).remote_time);                         \
475   FREE_MAYBE ((x).error);                               \
476   (x).newloc = (x).remote_time = (x).error = NULL;      \
477 } while (0)
478
479 static char *create_authorization_line PARAMS ((const char *, const char *,
480                                                 const char *, const char *,
481                                                 const char *));
482 static char *basic_authentication_encode PARAMS ((const char *, const char *,
483                                                   const char *));
484 static int known_authentication_scheme_p PARAMS ((const char *));
485
486 time_t http_atotm PARAMS ((char *));
487
488 #define BEGINS_WITH(line, string_constant)                              \
489   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
490    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
491        || !line[sizeof (string_constant) - 1]))
492
493 /* Retrieve a document through HTTP protocol.  It recognizes status
494    code, and correctly handles redirections.  It closes the network
495    socket.  If it receives an error from the functions below it, it
496    will print it if there is enough information to do so (almost
497    always), returning the error to the caller (i.e. http_loop).
498
499    Various HTTP parameters are stored to hs.  Although it parses the
500    response code correctly, it is not used in a sane way.  The caller
501    can do that, though.
502
503    If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
504    and u->proxy->url will be given to the proxy server (bad naming,
505    I'm afraid).  */
506 static uerr_t
507 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
508 {
509   char *request, *type, *command, *path;
510   char *user, *passwd;
511   char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
512   char *authenticate_h;
513   char *proxyauth;
514   char *all_headers;
515   char *port_maybe;
516   char *request_keep_alive;
517   int sock, hcount, num_written, all_length, remport, statcode;
518   long contlen, contrange;
519   struct urlinfo *ou;
520   uerr_t err;
521   FILE *fp;
522   int auth_tried_already;
523   struct rbuf rbuf;
524 #ifdef HAVE_SSL
525   static SSL_CTX *ssl_ctx = NULL;
526   SSL *ssl = NULL;
527 #endif /* HAVE_SSL */
528   char *cookies = NULL;
529
530   /* Whether this connection will be kept alive after the HTTP request
531      is done. */
532   int keep_alive;
533
534   /* Flags that detect the two ways of specifying HTTP keep-alive
535      response.  */
536   int http_keep_alive_1, http_keep_alive_2;
537
538   /* Whether keep-alive should be inhibited. */
539   int inhibit_keep_alive;
540
541 #ifdef HAVE_SSL
542   /* initialize ssl_ctx on first run */
543   if (!ssl_ctx)
544     {
545       err=init_ssl (&ssl_ctx);
546       if (err != 0)
547         {
548           switch (err)
549             {
550             case SSLERRCTXCREATE:
551               /* this is fatal */
552               logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
553               ssl_printerrors ();
554               return err;
555             case SSLERRCERTFILE:
556               /* try without certfile */
557               logprintf (LOG_NOTQUIET,
558                          _("Failed to load certificates from %s\n"),
559                          opt.sslcertfile);
560               ssl_printerrors ();
561               logprintf (LOG_NOTQUIET,
562                          _("Trying without the specified certificate\n"));
563               break;
564             case SSLERRCERTKEY:
565               logprintf (LOG_NOTQUIET,
566                          _("Failed to get certificate key from %s\n"),
567                          opt.sslcertkey);
568               ssl_printerrors ();
569               logprintf (LOG_NOTQUIET,
570                          _("Trying without the specified certificate\n"));
571               break;
572             default:
573               break;
574             }
575         }
576     }
577 #endif /* HAVE_SSL */
578
579   if (!(*dt & HEAD_ONLY))
580     /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
581        know the local filename so we can save to it. */
582     assert (u->local != NULL);
583
584   authenticate_h = 0;
585   auth_tried_already = 0;
586
587   inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
588
589  again:
590   /* We need to come back here when the initial attempt to retrieve
591      without authorization header fails.  (Expected to happen at least
592      for the Digest authorization scheme.)  */
593
594   keep_alive = 0;
595   http_keep_alive_1 = http_keep_alive_2 = 0;
596
597   if (opt.cookies)
598     cookies = build_cookies_request (u->host, u->port, u->path,
599                                      u->proto == URLHTTPS);
600
601   /* Initialize certain elements of struct http_stat.  */
602   hs->len = 0L;
603   hs->contlen = -1;
604   hs->res = -1;
605   hs->newloc = NULL;
606   hs->remote_time = NULL;
607   hs->error = NULL;
608
609   /* Which structure to use to retrieve the original URL data.  */
610   if (u->proxy)
611     ou = u->proxy;
612   else
613     ou = u;
614
615   /* First: establish the connection.  */
616   if (inhibit_keep_alive
617       ||
618 #ifndef HAVE_SSL
619       !persistent_available_p (u->host, u->port)
620 #else
621       !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
622 #endif /* HAVE_SSL */
623       )
624     {
625       logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
626       err = make_connection (&sock, u->host, u->port);
627       switch (err)
628         {
629         case HOSTERR:
630           logputs (LOG_VERBOSE, "\n");
631           logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
632           return HOSTERR;
633           break;
634         case CONSOCKERR:
635           logputs (LOG_VERBOSE, "\n");
636           logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
637           return CONSOCKERR;
638           break;
639         case CONREFUSED:
640           logputs (LOG_VERBOSE, "\n");
641           logprintf (LOG_NOTQUIET,
642                      _("Connection to %s:%hu refused.\n"), u->host, u->port);
643           CLOSE (sock);
644           return CONREFUSED;
645         case CONERROR:
646           logputs (LOG_VERBOSE, "\n");
647           logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
648           CLOSE (sock);
649           return CONERROR;
650           break;
651         case NOCONERROR:
652           /* Everything is fine!  */
653           logputs (LOG_VERBOSE, _("connected!\n"));
654           break;
655         default:
656           abort ();
657           break;
658         }
659 #ifdef HAVE_SSL
660      if (u->proto == URLHTTPS)
661        if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
662          {
663            logputs (LOG_VERBOSE, "\n");
664            logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
665            CLOSE (sock);
666            return CONSSLERR;
667          }
668 #endif /* HAVE_SSL */
669     }
670   else
671     {
672       logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
673       /* #### pc_last_fd should be accessed through an accessor
674          function.  */
675       sock = pc_last_fd;
676 #ifdef HAVE_SSL
677       ssl = pc_last_ssl;
678 #endif /* HAVE_SSL */
679       DEBUGP (("Reusing fd %d.\n", sock));
680     }
681
682   if (u->proxy)
683     path = u->proxy->url;
684   else
685     path = u->path;
686   
687   command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
688   referer = NULL;
689   if (ou->referer)
690     {
691       referer = (char *)alloca (9 + strlen (ou->referer) + 3);
692       sprintf (referer, "Referer: %s\r\n", ou->referer);
693     }
694   if (*dt & SEND_NOCACHE)
695     pragma_h = "Pragma: no-cache\r\n";
696   else
697     pragma_h = "";
698   if (hs->restval)
699     {
700       range = (char *)alloca (13 + numdigit (hs->restval) + 4);
701       /* Gag me!  Some servers (e.g. WebSitePro) have been known to
702          respond to the following `Range' format by generating a
703          multipart/x-byte-ranges MIME document!  This MIME type was
704          present in an old draft of the byteranges specification.
705          HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
706          only if multiple non-overlapping ranges are requested --
707          which Wget never does.  */
708       sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
709     }
710   else
711     range = NULL;
712   if (opt.useragent)
713     STRDUP_ALLOCA (useragent, opt.useragent);
714   else
715     {
716       useragent = (char *)alloca (10 + strlen (version_string));
717       sprintf (useragent, "Wget/%s", version_string);
718     }
719   /* Construct the authentication, if userid is present.  */
720   user = ou->user;
721   passwd = ou->passwd;
722   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
723   user = user ? user : opt.http_user;
724   passwd = passwd ? passwd : opt.http_passwd;
725
726   wwwauth = NULL;
727   if (user && passwd)
728     {
729       if (!authenticate_h)
730         {
731           /* We have the username and the password, but haven't tried
732              any authorization yet.  Let's see if the "Basic" method
733              works.  If not, we'll come back here and construct a
734              proper authorization method with the right challenges.
735
736              If we didn't employ this kind of logic, every URL that
737              requires authorization would have to be processed twice,
738              which is very suboptimal and generates a bunch of false
739              "unauthorized" errors in the server log.
740
741              #### But this logic also has a serious problem when used
742              with stronger authentications: we *first* transmit the
743              username and the password in clear text, and *then*
744              attempt a stronger authentication scheme.  That cannot be
745              right!  We are only fortunate that almost everyone still
746              uses the `Basic' scheme anyway.
747
748              There should be an option to prevent this from happening,
749              for those who use strong authentication schemes and value
750              their passwords.  */
751           wwwauth = basic_authentication_encode (user, passwd, "Authorization");
752         }
753       else
754         {
755           wwwauth = create_authorization_line (authenticate_h, user, passwd,
756                                                command, ou->path);
757         }
758     }
759
760   proxyauth = NULL;
761   if (u->proxy)
762     {
763       char *proxy_user, *proxy_passwd;
764       /* For normal username and password, URL components override
765          command-line/wgetrc parameters.  With proxy authentication,
766          it's the reverse, because proxy URLs are normally the
767          "permanent" ones, so command-line args should take
768          precedence.  */
769       if (opt.proxy_user && opt.proxy_passwd)
770         {
771           proxy_user = opt.proxy_user;
772           proxy_passwd = opt.proxy_passwd;
773         }
774       else
775         {
776           proxy_user = u->user;
777           proxy_passwd = u->passwd;
778         }
779       /* #### This is junky.  Can't the proxy request, say, `Digest'
780          authentication?  */
781       if (proxy_user && proxy_passwd)
782         proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
783                                                  "Proxy-Authorization");
784     }
785   remhost = ou->host;
786   remport = ou->port;
787
788   /* String of the form :PORT.  Used only for non-standard ports. */
789   port_maybe = NULL;
790   if (1
791 #ifdef HAVE_SSL
792       && remport != (u->proto == URLHTTPS
793                      ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT)
794 #else
795       && remport != DEFAULT_HTTP_PORT
796 #endif
797       )
798     {
799       port_maybe = (char *)alloca (numdigit (remport) + 2);
800       sprintf (port_maybe, ":%d", remport);
801     }
802
803   if (!inhibit_keep_alive)
804     request_keep_alive = "Connection: Keep-Alive\r\n";
805   else
806     request_keep_alive = NULL;
807
808   /* Allocate the memory for the request.  */
809   request = (char *)alloca (strlen (command) + strlen (path)
810                             + strlen (useragent)
811                             + strlen (remhost)
812                             + (port_maybe ? strlen (port_maybe) : 0)
813                             + strlen (HTTP_ACCEPT)
814                             + (request_keep_alive
815                                ? strlen (request_keep_alive) : 0)
816                             + (referer ? strlen (referer) : 0)
817                             + (cookies ? strlen (cookies) : 0)
818                             + (wwwauth ? strlen (wwwauth) : 0)
819                             + (proxyauth ? strlen (proxyauth) : 0)
820                             + (range ? strlen (range) : 0)
821                             + strlen (pragma_h)
822                             + (opt.user_header ? strlen (opt.user_header) : 0)
823                             + 64);
824   /* Construct the request.  */
825   sprintf (request, "\
826 %s %s HTTP/1.0\r\n\
827 User-Agent: %s\r\n\
828 Host: %s%s\r\n\
829 Accept: %s\r\n\
830 %s%s%s%s%s%s%s%s\r\n",
831            command, path, useragent, remhost,
832            port_maybe ? port_maybe : "",
833            HTTP_ACCEPT,
834            request_keep_alive ? request_keep_alive : "",
835            referer ? referer : "",
836            cookies ? cookies : "", 
837            wwwauth ? wwwauth : "", 
838            proxyauth ? proxyauth : "", 
839            range ? range : "",
840            pragma_h, 
841            opt.user_header ? opt.user_header : "");
842   DEBUGP (("---request begin---\n%s---request end---\n", request));
843    /* Free the temporary memory.  */
844   FREE_MAYBE (wwwauth);
845   FREE_MAYBE (proxyauth);
846   FREE_MAYBE (cookies);
847
848   /* Send the request to server.  */
849 #ifdef HAVE_SSL
850   if (u->proto == URLHTTPS)
851     num_written = ssl_iwrite (ssl, request, strlen (request));
852   else
853 #endif /* HAVE_SSL */
854     num_written = iwrite (sock, request, strlen (request));
855
856   if (num_written < 0)
857     {
858       logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
859                  strerror (errno));
860       CLOSE_INVALIDATE (sock);
861       return WRITEFAILED;
862     }
863   logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
864              u->proxy ? "Proxy" : "HTTP");
865   contlen = contrange = -1;
866   type = NULL;
867   statcode = -1;
868   *dt &= ~RETROKF;
869
870   /* Before reading anything, initialize the rbuf.  */
871   rbuf_initialize (&rbuf, sock);
872 #ifdef HAVE_SSL
873   if (u->proto == URLHTTPS)
874     rbuf.ssl = ssl;
875   else
876     rbuf.ssl = NULL;
877 #endif /* HAVE_SSL */
878   all_headers = NULL;
879   all_length = 0;
880   /* Header-fetching loop.  */
881   hcount = 0;
882   while (1)
883     {
884       char *hdr;
885       int status;
886
887       ++hcount;
888       /* Get the header.  */
889       status = header_get (&rbuf, &hdr,
890                            /* Disallow continuations for status line.  */
891                            (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
892
893       /* Check for errors.  */
894       if (status == HG_EOF && *hdr)
895         {
896           /* This used to be an unconditional error, but that was
897              somewhat controversial, because of a large number of
898              broken CGI's that happily "forget" to send the second EOL
899              before closing the connection of a HEAD request.
900
901              So, the deal is to check whether the header is empty
902              (*hdr is zero if it is); if yes, it means that the
903              previous header was fully retrieved, and that -- most
904              probably -- the request is complete.  "...be liberal in
905              what you accept."  Oh boy.  */
906           logputs (LOG_VERBOSE, "\n");
907           logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
908           xfree (hdr);
909           FREE_MAYBE (type);
910           FREE_MAYBE (hs->newloc);
911           FREE_MAYBE (all_headers);
912           CLOSE_INVALIDATE (sock);
913           return HEOF;
914         }
915       else if (status == HG_ERROR)
916         {
917           logputs (LOG_VERBOSE, "\n");
918           logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
919                      strerror (errno));
920           xfree (hdr);
921           FREE_MAYBE (type);
922           FREE_MAYBE (hs->newloc);
923           FREE_MAYBE (all_headers);
924           CLOSE_INVALIDATE (sock);
925           return HERR;
926         }
927
928       /* If the headers are to be saved to a file later, save them to
929          memory now.  */
930       if (opt.save_headers)
931         {
932           int lh = strlen (hdr);
933           all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
934           memcpy (all_headers + all_length, hdr, lh);
935           all_length += lh;
936           all_headers[all_length++] = '\n';
937           all_headers[all_length] = '\0';
938         }
939
940       /* Print the header if requested.  */
941       if (opt.server_response && hcount != 1)
942         logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
943
944       /* Check for status line.  */
945       if (hcount == 1)
946         {
947           const char *error;
948           /* Parse the first line of server response.  */
949           statcode = parse_http_status_line (hdr, &error);
950           hs->statcode = statcode;
951           /* Store the descriptive response.  */
952           if (statcode == -1) /* malformed response */
953             {
954               /* A common reason for "malformed response" error is the
955                  case when no data was actually received.  Handle this
956                  special case.  */
957               if (!*hdr)
958                 hs->error = xstrdup (_("No data received"));
959               else
960                 hs->error = xstrdup (_("Malformed status line"));
961               xfree (hdr);
962               break;
963             }
964           else if (!*error)
965             hs->error = xstrdup (_("(no description)"));
966           else
967             hs->error = xstrdup (error);
968
969           if ((statcode != -1)
970 #ifdef DEBUG
971               && !opt.debug
972 #endif
973               )
974             logprintf (LOG_VERBOSE, "%d %s", statcode, error);
975
976           goto done_header;
977         }
978
979       /* Exit on empty header.  */
980       if (!*hdr)
981         {
982           xfree (hdr);
983           break;
984         }
985
986       /* Try getting content-length.  */
987       if (contlen == -1 && !opt.ignore_length)
988         if (header_process (hdr, "Content-Length", header_extract_number,
989                             &contlen))
990           goto done_header;
991       /* Try getting content-type.  */
992       if (!type)
993         if (header_process (hdr, "Content-Type", http_process_type, &type))
994           goto done_header;
995       /* Try getting location.  */
996       if (!hs->newloc)
997         if (header_process (hdr, "Location", header_strdup, &hs->newloc))
998           goto done_header;
999       /* Try getting last-modified.  */
1000       if (!hs->remote_time)
1001         if (header_process (hdr, "Last-Modified", header_strdup,
1002                             &hs->remote_time))
1003           goto done_header;
1004       /* Try getting cookies. */
1005       if (opt.cookies)
1006         if (header_process (hdr, "Set-Cookie", set_cookie_header_cb, u))
1007           goto done_header;
1008       /* Try getting www-authentication.  */
1009       if (!authenticate_h)
1010         if (header_process (hdr, "WWW-Authenticate", header_strdup,
1011                             &authenticate_h))
1012           goto done_header;
1013       /* Check for accept-ranges header.  If it contains the word
1014          `none', disable the ranges.  */
1015       if (*dt & ACCEPTRANGES)
1016         {
1017           int nonep;
1018           if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1019             {
1020               if (nonep)
1021                 *dt &= ~ACCEPTRANGES;
1022               goto done_header;
1023             }
1024         }
1025       /* Try getting content-range.  */
1026       if (contrange == -1)
1027         {
1028           struct http_process_range_closure closure;
1029           if (header_process (hdr, "Content-Range", http_process_range, &closure))
1030             {
1031               contrange = closure.first_byte_pos;
1032               goto done_header;
1033             }
1034         }
1035       /* Check for keep-alive related responses. */
1036       if (!inhibit_keep_alive)
1037         {
1038           /* Check for the `Keep-Alive' header. */
1039           if (!http_keep_alive_1)
1040             {
1041               if (header_process (hdr, "Keep-Alive", header_exists,
1042                                   &http_keep_alive_1))
1043                 goto done_header;
1044             }
1045           /* Check for `Connection: Keep-Alive'. */
1046           if (!http_keep_alive_2)
1047             {
1048               if (header_process (hdr, "Connection", http_process_connection,
1049                                   &http_keep_alive_2))
1050                 goto done_header;
1051             }
1052         }
1053     done_header:
1054       xfree (hdr);
1055     }
1056
1057   logputs (LOG_VERBOSE, "\n");
1058
1059   if (contlen != -1
1060       && (http_keep_alive_1 || http_keep_alive_2))
1061     {
1062       assert (inhibit_keep_alive == 0);
1063       keep_alive = 1;
1064     }
1065   if (keep_alive)
1066     /* The server has promised that it will not close the connection
1067        when we're done.  This means that we can register it.  */
1068 #ifndef HAVE_SSL
1069     register_persistent (u->host, u->port, sock);
1070 #else
1071     register_persistent (u->host, u->port, sock, ssl);
1072 #endif /* HAVE_SSL */
1073
1074   if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1075       && authenticate_h)
1076     {
1077       /* Authorization is required.  */
1078       FREE_MAYBE (type);
1079       type = NULL;
1080       FREEHSTAT (*hs);
1081       CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1082                                    might be more bytes in the body. */
1083       if (auth_tried_already)
1084         {
1085           /* If we have tried it already, then there is not point
1086              retrying it.  */
1087         failed:
1088           logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1089           xfree (authenticate_h);
1090           return AUTHFAILED;
1091         }
1092       else if (!known_authentication_scheme_p (authenticate_h))
1093         {
1094           xfree (authenticate_h);
1095           logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1096           return AUTHFAILED;
1097         }
1098       else if (BEGINS_WITH (authenticate_h, "Basic"))
1099         {
1100           /* The authentication scheme is basic, the one we try by
1101              default, and it failed.  There's no sense in trying
1102              again.  */
1103           goto failed;
1104         }
1105       else
1106         {
1107           auth_tried_already = 1;
1108           goto again;
1109         }
1110     }
1111   /* We do not need this anymore.  */
1112   if (authenticate_h)
1113     {
1114       xfree (authenticate_h);
1115       authenticate_h = NULL;
1116     }
1117
1118   /* 20x responses are counted among successful by default.  */
1119   if (H_20X (statcode))
1120     *dt |= RETROKF;
1121
1122   if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1123     *dt |= TEXTHTML;
1124   else
1125     /* We don't assume text/html by default.  */
1126     *dt &= ~TEXTHTML;
1127
1128   if (opt.html_extension && (*dt & TEXTHTML))
1129     /* -E / --html-extension / html_extension = on was specified, and this is a
1130        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
1131        already the file's suffix, tack on ".html". */
1132     {
1133       char*  last_period_in_local_filename = strrchr(u->local, '.');
1134
1135       if (last_period_in_local_filename == NULL ||
1136           !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1137             strcasecmp(last_period_in_local_filename, ".html") == EQ))
1138         {
1139           size_t  local_filename_len = strlen(u->local);
1140           
1141           u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1142           strcpy(u->local + local_filename_len, ".html");
1143
1144           *dt |= ADDED_HTML_EXTENSION;
1145         }
1146     }
1147
1148   if (contrange == -1)
1149     {
1150       /* We did not get a content-range header.  This means that the
1151          server did not honor our `Range' request.  Normally, this
1152          means we should reset hs->restval and continue normally.  */
1153
1154       /* However, if `-c' is used, we need to be a bit more careful:
1155
1156          1. If `-c' is specified and the file already existed when
1157          Wget was started, it would be a bad idea for us to start
1158          downloading it from scratch, effectively truncating it.  I
1159          believe this cannot happen unless `-c' was specified.
1160
1161          2. If `-c' is used on a file that is already fully
1162          downloaded, we're requesting bytes after the end of file,
1163          which can result in server not honoring `Range'.  If this is
1164          the case, `Content-Length' will be equal to the length of the
1165          file.  */
1166       if (opt.always_rest)
1167         {
1168           /* Check for condition #2. */
1169           if (hs->restval == contlen)
1170             {
1171               logputs (LOG_VERBOSE, _("\
1172 \n    The file is already fully retrieved; nothing to do.\n\n"));
1173               /* In case the caller inspects. */
1174               hs->len = contlen;
1175               hs->res = 0;
1176               FREE_MAYBE (type);
1177               FREE_MAYBE (hs->newloc);
1178               FREE_MAYBE (all_headers);
1179               CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1180                                            might be more bytes in the body. */
1181               return RETRFINISHED;
1182             }
1183
1184           /* Check for condition #1. */
1185           if (hs->no_truncate)
1186             {
1187               logprintf (LOG_NOTQUIET,
1188                          _("\
1189 \n\
1190     The server does not support continued download;\n\
1191     refusing to truncate `%s'.\n\n"), u->local);
1192               return CONTNOTSUPPORTED;
1193             }
1194
1195           /* Fallthrough */
1196         }
1197
1198       hs->restval = 0;
1199     }
1200
1201   else if (contrange != hs->restval ||
1202            (H_PARTIAL (statcode) && contrange == -1))
1203     {
1204       /* This means the whole request was somehow misunderstood by the
1205          server.  Bail out.  */
1206       FREE_MAYBE (type);
1207       FREE_MAYBE (hs->newloc);
1208       FREE_MAYBE (all_headers);
1209       CLOSE_INVALIDATE (sock);
1210       return RANGEERR;
1211     }
1212
1213   if (hs->restval)
1214     {
1215       if (contlen != -1)
1216         contlen += contrange;
1217       else
1218         contrange = -1;        /* If conent-length was not sent,
1219                                   content-range will be ignored.  */
1220     }
1221   hs->contlen = contlen;
1222
1223   /* Return if redirected.  */
1224   if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1225     {
1226       /* RFC2068 says that in case of the 300 (multiple choices)
1227          response, the server can output a preferred URL through
1228          `Location' header; otherwise, the request should be treated
1229          like GET.  So, if the location is set, it will be a
1230          redirection; otherwise, just proceed normally.  */
1231       if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1232         *dt |= RETROKF;
1233       else
1234         {
1235           logprintf (LOG_VERBOSE,
1236                      _("Location: %s%s\n"),
1237                      hs->newloc ? hs->newloc : _("unspecified"),
1238                      hs->newloc ? _(" [following]") : "");
1239           CLOSE_INVALIDATE (sock);      /* would be CLOSE_FINISH, but there
1240                                            might be more bytes in the body. */
1241           FREE_MAYBE (type);
1242           FREE_MAYBE (all_headers);
1243           return NEWLOCATION;
1244         }
1245     }
1246   if (opt.verbose)
1247     {
1248       if ((*dt & RETROKF) && !opt.server_response)
1249         {
1250           /* No need to print this output if the body won't be
1251              downloaded at all, or if the original server response is
1252              printed.  */
1253           logputs (LOG_VERBOSE, _("Length: "));
1254           if (contlen != -1)
1255             {
1256               logputs (LOG_VERBOSE, legible (contlen));
1257               if (contrange != -1)
1258                 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1259                            legible (contlen - contrange));
1260             }
1261           else
1262             logputs (LOG_VERBOSE,
1263                      opt.ignore_length ? _("ignored") : _("unspecified"));
1264           if (type)
1265             logprintf (LOG_VERBOSE, " [%s]\n", type);
1266           else
1267             logputs (LOG_VERBOSE, "\n");
1268         }
1269     }
1270   FREE_MAYBE (type);
1271   type = NULL;                  /* We don't need it any more.  */
1272
1273   /* Return if we have no intention of further downloading.  */
1274   if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1275     {
1276       /* In case the caller cares to look...  */
1277       hs->len = 0L;
1278       hs->res = 0;
1279       FREE_MAYBE (type);
1280       FREE_MAYBE (all_headers);
1281       CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1282                                    might be more bytes in the body. */
1283       return RETRFINISHED;
1284     }
1285
1286   /* Open the local file.  */
1287   if (!opt.dfp)
1288     {
1289       mkalldirs (u->local);
1290       if (opt.backups)
1291         rotate_backups (u->local);
1292       fp = fopen (u->local, hs->restval ? "ab" : "wb");
1293       if (!fp)
1294         {
1295           logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1296           CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1297                                       might be more bytes in the body. */
1298           FREE_MAYBE (all_headers);
1299           return FOPENERR;
1300         }
1301     }
1302   else                          /* opt.dfp */
1303     {
1304       extern int global_download_count;
1305       fp = opt.dfp;
1306       /* To ensure that repeated "from scratch" downloads work for -O
1307          files, we rewind the file pointer, unless restval is
1308          non-zero.  (This works only when -O is used on regular files,
1309          but it's still a valuable feature.)
1310
1311          However, this loses when more than one URL is specified on
1312          the command line the second rewinds eradicates the contents
1313          of the first download.  Thus we disable the above trick for
1314          all the downloads except the very first one.
1315
1316          #### A possible solution to this would be to remember the
1317          file position in the output document and to seek to that
1318          position, instead of rewinding.  */
1319       if (!hs->restval && global_download_count == 0)
1320         {
1321           /* This will silently fail for streams that don't correspond
1322              to regular files, but that's OK.  */
1323           rewind (fp);
1324           /* ftruncate is needed because opt.dfp is opened in append
1325              mode if opt.always_rest is set.  */
1326           ftruncate (fileno (fp), 0);
1327           clearerr (fp);
1328         }
1329     }
1330
1331   /* #### This confuses the code that checks for file size.  There
1332      should be some overhead information.  */
1333   if (opt.save_headers)
1334     fwrite (all_headers, 1, all_length, fp);
1335   reset_timer ();
1336   /* Get the contents of the document.  */
1337   hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1338                           (contlen != -1 ? contlen : 0),
1339                           &rbuf, keep_alive);
1340   hs->dltime = elapsed_time ();
1341   {
1342     /* Close or flush the file.  We have to be careful to check for
1343        error here.  Checking the result of fwrite() is not enough --
1344        errors could go unnoticed!  */
1345     int flush_res;
1346     if (!opt.dfp)
1347       flush_res = fclose (fp);
1348     else
1349       flush_res = fflush (fp);
1350     if (flush_res == EOF)
1351       hs->res = -2;
1352   }
1353   FREE_MAYBE (all_headers);
1354   CLOSE_FINISH (sock);
1355   if (hs->res == -2)
1356     return FWRITEERR;
1357   return RETRFINISHED;
1358 }
1359
1360 /* The genuine HTTP loop!  This is the part where the retrieval is
1361    retried, and retried, and retried, and...  */
1362 uerr_t
1363 http_loop (struct urlinfo *u, char **newloc, int *dt)
1364 {
1365   int count;
1366   int use_ts, got_head = 0;     /* time-stamping info */
1367   char *filename_plus_orig_suffix;
1368   char *local_filename = NULL;
1369   char *tms, *suf, *locf, *tmrate;
1370   uerr_t err;
1371   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
1372   long local_size = 0;          /* the size of the local file */
1373   size_t filename_len;
1374   struct http_stat hstat;       /* HTTP status */
1375   struct stat st;
1376
1377   *newloc = NULL;
1378
1379   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
1380      has_wildcards_p because it would also warn on `?', and we know that
1381      shows up in CGI paths a *lot*.  */
1382   if (strchr (u->url, '*'))
1383     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1384
1385   /* Determine the local filename.  */
1386   if (!u->local)
1387     u->local = url_filename (u->proxy ? u->proxy : u);
1388
1389   if (!opt.output_document)
1390     locf = u->local;
1391   else
1392     locf = opt.output_document;
1393
1394   /* Yuck.  Multiple returns suck.  We need to remember to free() the space we
1395      xmalloc() here before EACH return.  This is one reason it's better to set
1396      flags that influence flow control and then return once at the end. */
1397   filename_len = strlen(u->local);
1398   filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1399
1400   if (opt.noclobber && file_exists_p (u->local))
1401     {
1402       /* If opt.noclobber is turned on and file already exists, do not
1403          retrieve the file */
1404       logprintf (LOG_VERBOSE, _("\
1405 File `%s' already there, will not retrieve.\n"), u->local);
1406       /* If the file is there, we suppose it's retrieved OK.  */
1407       *dt |= RETROKF;
1408
1409       /* #### Bogusness alert.  */
1410       /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1411          text/html, a harmless lie.  */
1412       if (((suf = suffix (u->local)) != NULL)
1413           && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1414         *dt |= TEXTHTML;
1415       xfree (suf);
1416       xfree (filename_plus_orig_suffix); /* must precede every return! */
1417       /* Another harmless lie: */
1418       return RETROK;
1419     }
1420
1421   use_ts = 0;
1422   if (opt.timestamping)
1423     {
1424       boolean  local_dot_orig_file_exists = FALSE;
1425
1426       if (opt.backup_converted)
1427         /* If -K is specified, we'll act on the assumption that it was specified
1428            last time these files were downloaded as well, and instead of just
1429            comparing local file X against server file X, we'll compare local
1430            file X.orig (if extant, else X) against server file X.  If -K
1431            _wasn't_ specified last time, or the server contains files called
1432            *.orig, -N will be back to not operating correctly with -k. */
1433         {
1434           /* Would a single s[n]printf() call be faster?  --dan
1435
1436              Definitely not.  sprintf() is horribly slow.  It's a
1437              different question whether the difference between the two
1438              affects a program.  Usually I'd say "no", but at one
1439              point I profiled Wget, and found that a measurable and
1440              non-negligible amount of time was lost calling sprintf()
1441              in url.c.  Replacing sprintf with inline calls to
1442              strcpy() and long_to_string() made a difference.
1443              --hniksic */
1444           strcpy(filename_plus_orig_suffix, u->local);
1445           strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1446
1447           /* Try to stat() the .orig file. */
1448           if (stat(filename_plus_orig_suffix, &st) == 0)
1449             {
1450               local_dot_orig_file_exists = TRUE;
1451               local_filename = filename_plus_orig_suffix;
1452             }
1453         }      
1454
1455       if (!local_dot_orig_file_exists)
1456         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1457         if (stat (u->local, &st) == 0)
1458           local_filename = u->local;
1459
1460       if (local_filename != NULL)
1461         /* There was a local file, so we'll check later to see if the version
1462            the server has is the same version we already have, allowing us to
1463            skip a download. */
1464         {
1465           use_ts = 1;
1466           tml = st.st_mtime;
1467           local_size = st.st_size;
1468           got_head = 0;
1469         }
1470     }
1471   /* Reset the counter.  */
1472   count = 0;
1473   *dt = 0 | ACCEPTRANGES;
1474   /* THE loop */
1475   do
1476     {
1477       /* Increment the pass counter.  */
1478       ++count;
1479       sleep_between_retrievals (count);
1480       /* Get the current time string.  */
1481       tms = time_str (NULL);
1482       /* Print fetch message, if opt.verbose.  */
1483       if (opt.verbose)
1484         {
1485           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1486           char tmp[15];
1487           strcpy (tmp, "        ");
1488           if (count > 1)
1489             sprintf (tmp, _("(try:%2d)"), count);
1490           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1491                      tms, hurl, tmp, locf);
1492 #ifdef WINDOWS
1493           ws_changetitle (hurl, 1);
1494 #endif
1495           xfree (hurl);
1496         }
1497
1498       /* Default document type is empty.  However, if spider mode is
1499          on or time-stamping is employed, HEAD_ONLY commands is
1500          encoded within *dt.  */
1501       if (opt.spider || (use_ts && !got_head))
1502         *dt |= HEAD_ONLY;
1503       else
1504         *dt &= ~HEAD_ONLY;
1505       /* Assume no restarting.  */
1506       hstat.restval = 0L;
1507       /* Decide whether or not to restart.  */
1508       if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1509           && file_exists_p (locf))
1510         if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1511           hstat.restval = st.st_size;
1512       /* Decide whether to send the no-cache directive.  */
1513       if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1514         *dt |= SEND_NOCACHE;
1515       else
1516         *dt &= ~SEND_NOCACHE;
1517
1518       /* Try fetching the document, or at least its head.  :-) */
1519       err = gethttp (u, &hstat, dt);
1520
1521       /* It's unfortunate that wget determines the local filename before finding
1522          out the Content-Type of the file.  Barring a major restructuring of the
1523          code, we need to re-set locf here, since gethttp() may have xrealloc()d
1524          u->local to tack on ".html". */
1525       if (!opt.output_document)
1526         locf = u->local;
1527       else
1528         locf = opt.output_document;
1529
1530       /* In `-c' is used, check whether the file we're writing to
1531          exists before we've done anything.  If so, we'll refuse to
1532          truncate it if the server doesn't support continued
1533          downloads.  */
1534       if (opt.always_rest)
1535         hstat.no_truncate = file_exists_p (locf);
1536
1537       /* Time?  */
1538       tms = time_str (NULL);
1539       /* Get the new location (with or without the redirection).  */
1540       if (hstat.newloc)
1541         *newloc = xstrdup (hstat.newloc);
1542       switch (err)
1543         {
1544         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1545         case CONERROR: case READERR: case WRITEFAILED:
1546         case RANGEERR:
1547           /* Non-fatal errors continue executing the loop, which will
1548              bring them to "while" statement at the end, to judge
1549              whether the number of tries was exceeded.  */
1550           FREEHSTAT (hstat);
1551           printwhat (count, opt.ntry);
1552           continue;
1553           break;
1554         case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED: 
1555         case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1556           /* Fatal errors just return from the function.  */
1557           FREEHSTAT (hstat);
1558           xfree (filename_plus_orig_suffix); /* must precede every return! */
1559           return err;
1560           break;
1561         case FWRITEERR: case FOPENERR:
1562           /* Another fatal error.  */
1563           logputs (LOG_VERBOSE, "\n");
1564           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1565                      u->local, strerror (errno));
1566           FREEHSTAT (hstat);
1567           return err;
1568           break;
1569         case CONSSLERR:
1570           /* Another fatal error.  */
1571           logputs (LOG_VERBOSE, "\n");
1572           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1573           FREEHSTAT (hstat);
1574           xfree (filename_plus_orig_suffix); /* must precede every return! */
1575           return err;
1576           break;
1577         case NEWLOCATION:
1578           /* Return the new location to the caller.  */
1579           if (!hstat.newloc)
1580             {
1581               logprintf (LOG_NOTQUIET,
1582                          _("ERROR: Redirection (%d) without location.\n"),
1583                          hstat.statcode);
1584               xfree (filename_plus_orig_suffix); /* must precede every return! */
1585               return WRONGCODE;
1586             }
1587           FREEHSTAT (hstat);
1588           xfree (filename_plus_orig_suffix); /* must precede every return! */
1589           return NEWLOCATION;
1590           break;
1591         case RETRFINISHED:
1592           /* Deal with you later.  */
1593           break;
1594         default:
1595           /* All possibilities should have been exhausted.  */
1596           abort ();
1597         }
1598       if (!(*dt & RETROKF))
1599         {
1600           if (!opt.verbose)
1601             {
1602               /* #### Ugly ugly ugly! */
1603               char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1604               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1605               xfree (hurl);
1606             }
1607           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1608                      tms, hstat.statcode, hstat.error);
1609           logputs (LOG_VERBOSE, "\n");
1610           FREEHSTAT (hstat);
1611           xfree (filename_plus_orig_suffix); /* must precede every return! */
1612           return WRONGCODE;
1613         }
1614
1615       /* Did we get the time-stamp?  */
1616       if (!got_head)
1617         {
1618           if (opt.timestamping && !hstat.remote_time)
1619             {
1620               logputs (LOG_NOTQUIET, _("\
1621 Last-modified header missing -- time-stamps turned off.\n"));
1622             }
1623           else if (hstat.remote_time)
1624             {
1625               /* Convert the date-string into struct tm.  */
1626               tmr = http_atotm (hstat.remote_time);
1627               if (tmr == (time_t) (-1))
1628                 logputs (LOG_VERBOSE, _("\
1629 Last-modified header invalid -- time-stamp ignored.\n"));
1630             }
1631         }
1632
1633       /* The time-stamping section.  */
1634       if (use_ts)
1635         {
1636           got_head = 1;
1637           *dt &= ~HEAD_ONLY;
1638           use_ts = 0;           /* no more time-stamping */
1639           count = 0;            /* the retrieve count for HEAD is
1640                                    reset */
1641           if (hstat.remote_time && tmr != (time_t) (-1))
1642             {
1643               /* Now time-stamping can be used validly.  Time-stamping
1644                  means that if the sizes of the local and remote file
1645                  match, and local file is newer than the remote file,
1646                  it will not be retrieved.  Otherwise, the normal
1647                  download procedure is resumed.  */
1648               if (tml >= tmr &&
1649                   (hstat.contlen == -1 || local_size == hstat.contlen))
1650                 {
1651                   logprintf (LOG_VERBOSE, _("\
1652 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1653                              local_filename);
1654                   FREEHSTAT (hstat);
1655                   xfree (filename_plus_orig_suffix); /*must precede every return!*/
1656                   return RETROK;
1657                 }
1658               else if (tml >= tmr)
1659                 logprintf (LOG_VERBOSE, _("\
1660 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1661               else
1662                 logputs (LOG_VERBOSE,
1663                          _("Remote file is newer, retrieving.\n"));
1664             }
1665           FREEHSTAT (hstat);
1666           continue;
1667         }
1668       if ((tmr != (time_t) (-1))
1669           && !opt.spider
1670           && ((hstat.len == hstat.contlen) ||
1671               ((hstat.res == 0) &&
1672                ((hstat.contlen == -1) ||
1673                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1674         {
1675           /* #### This code repeats in http.c and ftp.c.  Move it to a
1676              function!  */
1677           const char *fl = NULL;
1678           if (opt.output_document)
1679             {
1680               if (opt.od_known_regular)
1681                 fl = opt.output_document;
1682             }
1683           else
1684             fl = u->local;
1685           if (fl)
1686             touch (fl, tmr);
1687         }
1688       /* End of time-stamping section.  */
1689
1690       if (opt.spider)
1691         {
1692           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1693           xfree (filename_plus_orig_suffix); /* must precede every return! */
1694           return RETROK;
1695         }
1696
1697       /* It is now safe to free the remainder of hstat, since the
1698          strings within it will no longer be used.  */
1699       FREEHSTAT (hstat);
1700
1701       tmrate = rate (hstat.len - hstat.restval, hstat.dltime, 0);
1702
1703       if (hstat.len == hstat.contlen)
1704         {
1705           if (*dt & RETROKF)
1706             {
1707               logprintf (LOG_VERBOSE,
1708                          _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1709                          tms, tmrate, locf, hstat.len, hstat.contlen);
1710               logprintf (LOG_NONVERBOSE,
1711                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1712                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1713             }
1714           ++opt.numurls;
1715           downloaded_increase (hstat.len);
1716
1717           /* Remember that we downloaded the file for later ".orig" code. */
1718           if (*dt & ADDED_HTML_EXTENSION)
1719             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1720           else
1721             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1722
1723           xfree(filename_plus_orig_suffix); /* must precede every return! */
1724           return RETROK;
1725         }
1726       else if (hstat.res == 0) /* No read error */
1727         {
1728           if (hstat.contlen == -1)  /* We don't know how much we were supposed
1729                                        to get, so assume we succeeded. */ 
1730             {
1731               if (*dt & RETROKF)
1732                 {
1733                   logprintf (LOG_VERBOSE,
1734                              _("%s (%s) - `%s' saved [%ld]\n\n"),
1735                              tms, tmrate, locf, hstat.len);
1736                   logprintf (LOG_NONVERBOSE,
1737                              "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1738                              tms, u->url, hstat.len, locf, count);
1739                 }
1740               ++opt.numurls;
1741               downloaded_increase (hstat.len);
1742
1743               /* Remember that we downloaded the file for later ".orig" code. */
1744               if (*dt & ADDED_HTML_EXTENSION)
1745                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1746               else
1747                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1748               
1749               xfree (filename_plus_orig_suffix); /* must precede every return! */
1750               return RETROK;
1751             }
1752           else if (hstat.len < hstat.contlen) /* meaning we lost the
1753                                                  connection too soon */
1754             {
1755               logprintf (LOG_VERBOSE,
1756                          _("%s (%s) - Connection closed at byte %ld. "),
1757                          tms, tmrate, hstat.len);
1758               printwhat (count, opt.ntry);
1759               continue;
1760             }
1761           else if (!opt.kill_longer) /* meaning we got more than expected */
1762             {
1763               logprintf (LOG_VERBOSE,
1764                          _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1765                          tms, tmrate, locf, hstat.len, hstat.contlen);
1766               logprintf (LOG_NONVERBOSE,
1767                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1768                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1769               ++opt.numurls;
1770               downloaded_increase (hstat.len);
1771
1772               /* Remember that we downloaded the file for later ".orig" code. */
1773               if (*dt & ADDED_HTML_EXTENSION)
1774                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1775               else
1776                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1777               
1778               xfree (filename_plus_orig_suffix); /* must precede every return! */
1779               return RETROK;
1780             }
1781           else                  /* the same, but not accepted */
1782             {
1783               logprintf (LOG_VERBOSE,
1784                          _("%s (%s) - Connection closed at byte %ld/%ld. "),
1785                          tms, tmrate, hstat.len, hstat.contlen);
1786               printwhat (count, opt.ntry);
1787               continue;
1788             }
1789         }
1790       else                      /* now hstat.res can only be -1 */
1791         {
1792           if (hstat.contlen == -1)
1793             {
1794               logprintf (LOG_VERBOSE,
1795                          _("%s (%s) - Read error at byte %ld (%s)."),
1796                          tms, tmrate, hstat.len, strerror (errno));
1797               printwhat (count, opt.ntry);
1798               continue;
1799             }
1800           else                  /* hstat.res == -1 and contlen is given */
1801             {
1802               logprintf (LOG_VERBOSE,
1803                          _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1804                          tms, tmrate, hstat.len, hstat.contlen,
1805                          strerror (errno));
1806               printwhat (count, opt.ntry);
1807               continue;
1808             }
1809         }
1810       /* not reached */
1811       break;
1812     }
1813   while (!opt.ntry || (count < opt.ntry));
1814   xfree (filename_plus_orig_suffix); /* must precede every return! */
1815   return TRYLIMEXC;
1816 }
1817 \f
1818 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1819    than local timezone (mktime assumes the latter).
1820
1821    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1822    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.  */
1823 static time_t
1824 mktime_from_utc (struct tm *t)
1825 {
1826   time_t tl, tb;
1827
1828   tl = mktime (t);
1829   if (tl == -1)
1830     return -1;
1831   tb = mktime (gmtime (&tl));
1832   return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1833 }
1834
1835 /* Check whether the result of strptime() indicates success.
1836    strptime() returns the pointer to how far it got to in the string.
1837    The processing has been successful if the string is at `GMT' or
1838    `+X', or at the end of the string.
1839
1840    In extended regexp parlance, the function returns 1 if P matches
1841    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (a valid result of
1842    strptime()) is considered a failure and 0 is returned.  */
1843 static int
1844 check_end (const char *p)
1845 {
1846   if (!p)
1847     return 0;
1848   while (ISSPACE (*p))
1849     ++p;
1850   if (!*p
1851       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1852       || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
1853     return 1;
1854   else
1855     return 0;
1856 }
1857
1858 /* Convert TIME_STRING time to time_t.  TIME_STRING can be in any of
1859    the three formats RFC2068 allows the HTTP servers to emit --
1860    RFC1123-date, RFC850-date or asctime-date.  Timezones are ignored,
1861    and should be GMT.
1862
1863    We use strptime() to recognize various dates, which makes it a
1864    little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1865    allows shortened dates and months, one-digit days, etc.).  It also
1866    allows more than one space anywhere where the specs require one SP.
1867    The routine should probably be even more forgiving (as recommended
1868    by RFC2068), but I do not have the time to write one.
1869
1870    Return the computed time_t representation, or -1 if all the
1871    schemes fail.
1872
1873    Needless to say, what we *really* need here is something like
1874    Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1875    and does not use strptime().  atotm() is to be found in the sources
1876    of `phttpd', a little-known HTTP server written by Peter Erikson.  */
1877 time_t
1878 http_atotm (char *time_string)
1879 {
1880   struct tm t;
1881
1882   /* Roger Beeman says: "This function dynamically allocates struct tm
1883      t, but does no initialization.  The only field that actually
1884      needs initialization is tm_isdst, since the others will be set by
1885      strptime.  Since strptime does not set tm_isdst, it will return
1886      the data structure with whatever data was in tm_isdst to begin
1887      with.  For those of us in timezones where DST can occur, there
1888      can be a one hour shift depending on the previous contents of the
1889      data area where the data structure is allocated."  */
1890   t.tm_isdst = -1;
1891
1892   /* Note that under foreign locales Solaris strptime() fails to
1893      recognize English dates, which renders this function useless.  I
1894      assume that other non-GNU strptime's are plagued by the same
1895      disease.  We solve this by setting only LC_MESSAGES in
1896      i18n_initialize(), instead of LC_ALL.
1897
1898      Another solution could be to temporarily set locale to C, invoke
1899      strptime(), and restore it back.  This is slow and dirty,
1900      however, and locale support other than LC_MESSAGES can mess other
1901      things, so I rather chose to stick with just setting LC_MESSAGES.
1902
1903      Also note that none of this is necessary under GNU strptime(),
1904      because it recognizes both international and local dates.  */
1905
1906   /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1907      it to eat all white space up to (and including) a newline, and
1908      the function fails if there is no newline (!).
1909
1910      Let's hope all strptime() implementations use ` ' to skip *all*
1911      whitespace instead of just one (it works that way on all the
1912      systems I've tested it on).  */
1913
1914   /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1915   if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1916     return mktime_from_utc (&t);
1917   /* RFC850:  Thursday, 29-Jan-98 22:12:57 */
1918   if (check_end (strptime (time_string, "%A, %d-%b-%y %T", &t)))
1919     return mktime_from_utc (&t);
1920   /* pseudo-RFC850:  Thu, 29-Jan-1998 22:12:57
1921      (google.com uses this for their cookies.)*/
1922   if (check_end (strptime (time_string, "%a, %d-%b-%Y %T", &t)))
1923     return mktime_from_utc (&t);
1924   /* asctime: Thu Jan 29 22:12:57 1998 */
1925   if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1926     return mktime_from_utc (&t);
1927   /* Failure.  */
1928   return -1;
1929 }
1930 \f
1931 /* Authorization support: We support two authorization schemes:
1932
1933    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1934
1935    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1936    consisting of answering to the server's challenge with the proper
1937    MD5 digests.  */
1938
1939 /* How many bytes it will take to store LEN bytes in base64.  */
1940 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1941
1942 /* Encode the string S of length LENGTH to base64 format and place it
1943    to STORE.  STORE will be 0-terminated, and must point to a writable
1944    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
1945 static void
1946 base64_encode (const char *s, char *store, int length)
1947 {
1948   /* Conversion table.  */
1949   static char tbl[64] = {
1950     'A','B','C','D','E','F','G','H',
1951     'I','J','K','L','M','N','O','P',
1952     'Q','R','S','T','U','V','W','X',
1953     'Y','Z','a','b','c','d','e','f',
1954     'g','h','i','j','k','l','m','n',
1955     'o','p','q','r','s','t','u','v',
1956     'w','x','y','z','0','1','2','3',
1957     '4','5','6','7','8','9','+','/'
1958   };
1959   int i;
1960   unsigned char *p = (unsigned char *)store;
1961
1962   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
1963   for (i = 0; i < length; i += 3)
1964     {
1965       *p++ = tbl[s[0] >> 2];
1966       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1967       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1968       *p++ = tbl[s[2] & 0x3f];
1969       s += 3;
1970     }
1971   /* Pad the result if necessary...  */
1972   if (i == length + 1)
1973     *(p - 1) = '=';
1974   else if (i == length + 2)
1975     *(p - 1) = *(p - 2) = '=';
1976   /* ...and zero-terminate it.  */
1977   *p = '\0';
1978 }
1979
1980 /* Create the authentication header contents for the `Basic' scheme.
1981    This is done by encoding the string `USER:PASS' in base64 and
1982    prepending `HEADER: Basic ' to it.  */
1983 static char *
1984 basic_authentication_encode (const char *user, const char *passwd,
1985                              const char *header)
1986 {
1987   char *t1, *t2, *res;
1988   int len1 = strlen (user) + 1 + strlen (passwd);
1989   int len2 = BASE64_LENGTH (len1);
1990
1991   t1 = (char *)alloca (len1 + 1);
1992   sprintf (t1, "%s:%s", user, passwd);
1993   t2 = (char *)alloca (1 + len2);
1994   base64_encode (t1, t2, len1);
1995   res = (char *)xmalloc (len2 + 11 + strlen (header));
1996   sprintf (res, "%s: Basic %s\r\n", header, t2);
1997
1998   return res;
1999 }
2000
2001 #ifdef USE_DIGEST
2002 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
2003    of a field in such a header.  If the field is the one specified by
2004    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2005    digest authorization code), extract its value in the (char*)
2006    variable pointed by RET.  Returns negative on a malformed header,
2007    or number of bytes that have been parsed by this call.  */
2008 static int
2009 extract_header_attr (const char *au, const char *attr_name, char **ret)
2010 {
2011   const char *cp, *ep;
2012
2013   ep = cp = au;
2014
2015   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2016     {
2017       cp += strlen (attr_name);
2018       if (!*cp)
2019         return -1;
2020       cp += skip_lws (cp);
2021       if (*cp != '=')
2022         return -1;
2023       if (!*++cp)
2024         return -1;
2025       cp += skip_lws (cp);
2026       if (*cp != '\"')
2027         return -1;
2028       if (!*++cp)
2029         return -1;
2030       for (ep = cp; *ep && *ep != '\"'; ep++)
2031         ;
2032       if (!*ep)
2033         return -1;
2034       FREE_MAYBE (*ret);
2035       *ret = strdupdelim (cp, ep);
2036       return ep - au + 1;
2037     }
2038   else
2039     return 0;
2040 }
2041
2042 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
2043    from url.h.  See RFC 2069 2.1.2 for the syntax of response-digest.  */
2044 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
2045
2046 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
2047    an array of 16 bytes containing the hash keys, and BUF should be a
2048    buffer of 33 writable characters (32 for hex digits plus one for
2049    zero termination).  */
2050 static void
2051 dump_hash (unsigned char *buf, const unsigned char *hash)
2052 {
2053   int i;
2054
2055   for (i = 0; i < MD5_HASHLEN; i++, hash++)
2056     {
2057       *buf++ = HEXD2asc (*hash >> 4);
2058       *buf++ = HEXD2asc (*hash & 0xf);
2059     }
2060   *buf = '\0';
2061 }
2062
2063 /* Take the line apart to find the challenge, and compose a digest
2064    authorization header.  See RFC2069 section 2.1.2.  */
2065 char *
2066 digest_authentication_encode (const char *au, const char *user,
2067                               const char *passwd, const char *method,
2068                               const char *path)
2069 {
2070   static char *realm, *opaque, *nonce;
2071   static struct {
2072     const char *name;
2073     char **variable;
2074   } options[] = {
2075     { "realm", &realm },
2076     { "opaque", &opaque },
2077     { "nonce", &nonce }
2078   };
2079   char *res;
2080
2081   realm = opaque = nonce = NULL;
2082
2083   au += 6;                      /* skip over `Digest' */
2084   while (*au)
2085     {
2086       int i;
2087
2088       au += skip_lws (au);
2089       for (i = 0; i < ARRAY_SIZE (options); i++)
2090         {
2091           int skip = extract_header_attr (au, options[i].name,
2092                                           options[i].variable);
2093           if (skip < 0)
2094             {
2095               FREE_MAYBE (realm);
2096               FREE_MAYBE (opaque);
2097               FREE_MAYBE (nonce);
2098               return NULL;
2099             }
2100           else if (skip)
2101             {
2102               au += skip;
2103               break;
2104             }
2105         }
2106       if (i == ARRAY_SIZE (options))
2107         {
2108           while (*au && *au != '=')
2109             au++;
2110           if (*au && *++au)
2111             {
2112               au += skip_lws (au);
2113               if (*au == '\"')
2114                 {
2115                   au++;
2116                   while (*au && *au != '\"')
2117                     au++;
2118                   if (*au)
2119                     au++;
2120                 }
2121             }
2122         }
2123       while (*au && *au != ',')
2124         au++;
2125       if (*au)
2126         au++;
2127     }
2128   if (!realm || !nonce || !user || !passwd || !path || !method)
2129     {
2130       FREE_MAYBE (realm);
2131       FREE_MAYBE (opaque);
2132       FREE_MAYBE (nonce);
2133       return NULL;
2134     }
2135
2136   /* Calculate the digest value.  */
2137   {
2138     struct md5_ctx ctx;
2139     unsigned char hash[MD5_HASHLEN];
2140     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2141     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2142
2143     /* A1BUF = H(user ":" realm ":" password) */
2144     md5_init_ctx (&ctx);
2145     md5_process_bytes (user, strlen (user), &ctx);
2146     md5_process_bytes (":", 1, &ctx);
2147     md5_process_bytes (realm, strlen (realm), &ctx);
2148     md5_process_bytes (":", 1, &ctx);
2149     md5_process_bytes (passwd, strlen (passwd), &ctx);
2150     md5_finish_ctx (&ctx, hash);
2151     dump_hash (a1buf, hash);
2152
2153     /* A2BUF = H(method ":" path) */
2154     md5_init_ctx (&ctx);
2155     md5_process_bytes (method, strlen (method), &ctx);
2156     md5_process_bytes (":", 1, &ctx);
2157     md5_process_bytes (path, strlen (path), &ctx);
2158     md5_finish_ctx (&ctx, hash);
2159     dump_hash (a2buf, hash);
2160
2161     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2162     md5_init_ctx (&ctx);
2163     md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2164     md5_process_bytes (":", 1, &ctx);
2165     md5_process_bytes (nonce, strlen (nonce), &ctx);
2166     md5_process_bytes (":", 1, &ctx);
2167     md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2168     md5_finish_ctx (&ctx, hash);
2169     dump_hash (response_digest, hash);
2170
2171     res = (char*) xmalloc (strlen (user)
2172                            + strlen (user)
2173                            + strlen (realm)
2174                            + strlen (nonce)
2175                            + strlen (path)
2176                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2177                            + (opaque ? strlen (opaque) : 0)
2178                            + 128);
2179     sprintf (res, "Authorization: Digest \
2180 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2181              user, realm, nonce, path, response_digest);
2182     if (opaque)
2183       {
2184         char *p = res + strlen (res);
2185         strcat (p, ", opaque=\"");
2186         strcat (p, opaque);
2187         strcat (p, "\"");
2188       }
2189     strcat (res, "\r\n");
2190   }
2191   return res;
2192 }
2193 #endif /* USE_DIGEST */
2194
2195
2196 #define BEGINS_WITH(line, string_constant)                              \
2197   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
2198    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
2199        || !line[sizeof (string_constant) - 1]))
2200
2201 static int
2202 known_authentication_scheme_p (const char *au)
2203 {
2204   return BEGINS_WITH (au, "Basic")
2205     || BEGINS_WITH (au, "Digest")
2206     || BEGINS_WITH (au, "NTLM");
2207 }
2208
2209 #undef BEGINS_WITH
2210
2211 /* Create the HTTP authorization request header.  When the
2212    `WWW-Authenticate' response header is seen, according to the
2213    authorization scheme specified in that header (`Basic' and `Digest'
2214    are supported by the current implementation), produce an
2215    appropriate HTTP authorization request header.  */
2216 static char *
2217 create_authorization_line (const char *au, const char *user,
2218                            const char *passwd, const char *method,
2219                            const char *path)
2220 {
2221   char *wwwauth = NULL;
2222
2223   if (!strncasecmp (au, "Basic", 5))
2224     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2225   if (!strncasecmp (au, "NTLM", 4))
2226     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2227 #ifdef USE_DIGEST
2228   else if (!strncasecmp (au, "Digest", 6))
2229     wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2230 #endif /* USE_DIGEST */
2231   return wwwauth;
2232 }