]> sjero.net Git - wget/blob - src/http.c
93b3a12f197c4fe28fc14c29de81f5ca444e90e3
[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 static int cookies_loaded_p;
82
83 #define TEXTHTML_S "text/html"
84 #define HTTP_ACCEPT "*/*"
85
86 /* Some status code validation macros: */
87 #define H_20X(x)        (((x) >= 200) && ((x) < 300))
88 #define H_PARTIAL(x)    ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
89 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
90                          || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
91
92 /* HTTP/1.0 status codes from RFC1945, provided for reference.  */
93 /* Successful 2xx.  */
94 #define HTTP_STATUS_OK                  200
95 #define HTTP_STATUS_CREATED             201
96 #define HTTP_STATUS_ACCEPTED            202
97 #define HTTP_STATUS_NO_CONTENT          204
98 #define HTTP_STATUS_PARTIAL_CONTENTS    206
99
100 /* Redirection 3xx.  */
101 #define HTTP_STATUS_MULTIPLE_CHOICES    300
102 #define HTTP_STATUS_MOVED_PERMANENTLY   301
103 #define HTTP_STATUS_MOVED_TEMPORARILY   302
104 #define HTTP_STATUS_NOT_MODIFIED        304
105
106 /* Client error 4xx.  */
107 #define HTTP_STATUS_BAD_REQUEST         400
108 #define HTTP_STATUS_UNAUTHORIZED        401
109 #define HTTP_STATUS_FORBIDDEN           403
110 #define HTTP_STATUS_NOT_FOUND           404
111
112 /* Server errors 5xx.  */
113 #define HTTP_STATUS_INTERNAL            500
114 #define HTTP_STATUS_NOT_IMPLEMENTED     501
115 #define HTTP_STATUS_BAD_GATEWAY         502
116 #define HTTP_STATUS_UNAVAILABLE         503
117
118 \f
119 /* Parse the HTTP status line, which is of format:
120
121    HTTP-Version SP Status-Code SP Reason-Phrase
122
123    The function returns the status-code, or -1 if the status line is
124    malformed.  The pointer to reason-phrase is returned in RP.  */
125 static int
126 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
127 {
128   /* (the variables must not be named `major' and `minor', because
129      that breaks compilation with SunOS4 cc.)  */
130   int mjr, mnr, statcode;
131   const char *p;
132
133   *reason_phrase_ptr = NULL;
134
135   /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
136      major version, and Y is minor version.  */
137   if (strncmp (line, "HTTP/", 5) != 0)
138     return -1;
139   line += 5;
140
141   /* Calculate major HTTP version.  */
142   p = line;
143   for (mjr = 0; ISDIGIT (*line); line++)
144     mjr = 10 * mjr + (*line - '0');
145   if (*line != '.' || p == line)
146     return -1;
147   ++line;
148
149   /* Calculate minor HTTP version.  */
150   p = line;
151   for (mnr = 0; ISDIGIT (*line); line++)
152     mnr = 10 * mnr + (*line - '0');
153   if (*line != ' ' || p == line)
154     return -1;
155   /* Wget will accept only 1.0 and higher HTTP-versions.  The value of
156      minor version can be safely ignored.  */
157   if (mjr < 1)
158     return -1;
159   ++line;
160
161   /* Calculate status code.  */
162   if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
163     return -1;
164   statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
165
166   /* Set up the reason phrase pointer.  */
167   line += 3;
168   /* RFC2068 requires SPC here, but we allow the string to finish
169      here, in case no reason-phrase is present.  */
170   if (*line != ' ')
171     {
172       if (!*line)
173         *reason_phrase_ptr = line;
174       else
175         return -1;
176     }
177   else
178     *reason_phrase_ptr = line + 1;
179
180   return statcode;
181 }
182 \f
183 /* Functions to be used as arguments to header_process(): */
184
185 struct http_process_range_closure {
186   long first_byte_pos;
187   long last_byte_pos;
188   long entity_length;
189 };
190
191 /* Parse the `Content-Range' header and extract the information it
192    contains.  Returns 1 if successful, -1 otherwise.  */
193 static int
194 http_process_range (const char *hdr, void *arg)
195 {
196   struct http_process_range_closure *closure
197     = (struct http_process_range_closure *)arg;
198   long num;
199
200   /* Certain versions of Nutscape proxy server send out
201      `Content-Length' without "bytes" specifier, which is a breach of
202      RFC2068 (as well as the HTTP/1.1 draft which was current at the
203      time).  But hell, I must support it...  */
204   if (!strncasecmp (hdr, "bytes", 5))
205     {
206       hdr += 5;
207       hdr += skip_lws (hdr);
208       if (!*hdr)
209         return 0;
210     }
211   if (!ISDIGIT (*hdr))
212     return 0;
213   for (num = 0; ISDIGIT (*hdr); hdr++)
214     num = 10 * num + (*hdr - '0');
215   if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
216     return 0;
217   closure->first_byte_pos = num;
218   ++hdr;
219   for (num = 0; ISDIGIT (*hdr); hdr++)
220     num = 10 * num + (*hdr - '0');
221   if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
222     return 0;
223   closure->last_byte_pos = num;
224   ++hdr;
225   for (num = 0; ISDIGIT (*hdr); hdr++)
226     num = 10 * num + (*hdr - '0');
227   closure->entity_length = num;
228   return 1;
229 }
230
231 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
232    Used for `Accept-Ranges'.  */
233 static int
234 http_process_none (const char *hdr, void *arg)
235 {
236   int *where = (int *)arg;
237
238   if (strstr (hdr, "none"))
239     *where = 1;
240   else
241     *where = 0;
242   return 1;
243 }
244
245 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG.  */
246 static int
247 http_process_type (const char *hdr, void *arg)
248 {
249   char **result = (char **)arg;
250   /* Locate P on `;' or the terminating zero, whichever comes first. */
251   const char *p = strchr (hdr, ';');
252   if (!p)
253     p = hdr + strlen (hdr);
254   while (p > hdr && ISSPACE (*(p - 1)))
255     --p;
256   *result = strdupdelim (hdr, p);
257   return 1;
258 }
259
260 /* Check whether the `Connection' header is set to "keep-alive". */
261 static int
262 http_process_connection (const char *hdr, void *arg)
263 {
264   int *flag = (int *)arg;
265   if (!strcasecmp (hdr, "Keep-Alive"))
266     *flag = 1;
267   return 1;
268 }
269 \f
270 /* Persistent connections.  Currently, we cache the most recently used
271    connection as persistent, provided that the HTTP server agrees to
272    make it such.  The persistence data is stored in the variables
273    below.  Ideally, it would be in a structure, and it should be
274    possible to cache an arbitrary fixed number of these connections.
275
276    I think the code is quite easy to extend in that direction.  */
277
278 /* Whether a persistent connection is active. */
279 static int pc_active_p;
280 /* Host and port of currently active persistent connection. */
281 static unsigned char pc_last_host[4];
282 static unsigned short pc_last_port;
283
284 /* File descriptor of the currently active persistent connection. */
285 static int pc_last_fd;
286
287 #ifdef HAVE_SSL
288 /* Whether a ssl handshake has occoured on this connection */
289 static int pc_active_ssl;
290 /* SSL connection of the currently active persistent connection. */
291 static SSL *pc_last_ssl;
292 #endif /* HAVE_SSL */
293
294 /* Mark the persistent connection as invalid.  This is used by the
295    CLOSE_* macros after they forcefully close a registered persistent
296    connection.  This does not close the file descriptor -- it is left
297    to the caller to do that.  (Maybe it should, though.)  */
298
299 static void
300 invalidate_persistent (void)
301 {
302   pc_active_p = 0;
303 #ifdef HAVE_SSL
304   pc_active_ssl = 0;
305 #endif /* HAVE_SSL */
306   DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
307 }
308
309 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
310    persistent.  This will enable someone to use the same connection
311    later.  In the context of HTTP, this must be called only AFTER the
312    response has been received and the server has promised that the
313    connection will remain alive.
314
315    If a previous connection was persistent, it is closed. */
316
317 static void
318 register_persistent (const char *host, unsigned short port, int fd
319 #ifdef HAVE_SSL
320                      , SSL *ssl
321 #endif
322                      )
323 {
324   int success;
325
326   if (pc_active_p)
327     {
328       if (pc_last_fd == fd)
329         {
330           /* The connection FD is already registered.  Nothing to
331              do. */
332           return;
333         }
334       else
335         {
336           /* The old persistent connection is still active; let's
337              close it first.  This situation arises whenever a
338              persistent connection exists, but we then connect to a
339              different host, and try to register a persistent
340              connection to that one.  */
341 #ifdef HAVE_SSL
342           /* The ssl disconnect has to take place before the closing
343              of pc_last_fd.  */
344           if (pc_last_ssl)
345             shutdown_ssl(pc_last_ssl);
346 #endif
347           CLOSE (pc_last_fd);
348           invalidate_persistent ();
349         }
350     }
351
352   /* This store_hostaddress may not fail, because it has the results
353      in the cache.  */
354   success = store_hostaddress (pc_last_host, host);
355   assert (success);
356   pc_last_port = port;
357   pc_last_fd = fd;
358   pc_active_p = 1;
359 #ifdef HAVE_SSL
360   pc_last_ssl = ssl;
361   pc_active_ssl = ssl ? 1 : 0;
362 #endif
363   DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
364 }
365
366 /* Return non-zero if a persistent connection is available for
367    connecting to HOST:PORT.  */
368
369 static int
370 persistent_available_p (const char *host, unsigned short port
371 #ifdef HAVE_SSL
372                         , int ssl
373 #endif
374                         )
375 {
376   unsigned char this_host[4];
377   /* First, check whether a persistent connection is active at all.  */
378   if (!pc_active_p)
379     return 0;
380   /* Second, check if the active connection pertains to the correct
381      (HOST, PORT) ordered pair.  */
382   if (port != pc_last_port)
383     return 0;
384 #ifdef HAVE_SSL
385   /* Second, a): check if current connection is (not) ssl, too.  This
386      test is unlikely to fail because HTTP and HTTPS typicaly use
387      different ports.  Yet it is possible, or so I [Christian
388      Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
389      the same port.  */
390   if (ssl != pc_active_ssl)
391     return 0;
392 #endif /* HAVE_SSL */
393   if (!store_hostaddress (this_host, host))
394     return 0;
395   if (memcmp (pc_last_host, this_host, 4))
396     return 0;
397   /* Third: check whether the connection is still open.  This is
398      important because most server implement a liberal (short) timeout
399      on persistent connections.  Wget can of course always reconnect
400      if the connection doesn't work out, but it's nicer to know in
401      advance.  This test is a logical followup of the first test, but
402      is "expensive" and therefore placed at the end of the list.  */
403   if (!test_socket_open (pc_last_fd))
404     {
405       /* Oops, the socket is no longer open.  Now that we know that,
406          let's invalidate the persistent connection before returning
407          0.  */
408       CLOSE (pc_last_fd);
409       invalidate_persistent ();
410       return 0;
411     }
412   return 1;
413 }
414
415 #ifdef HAVE_SSL
416 # define SHUTDOWN_SSL(ssl) do {         \
417   if (ssl)                              \
418     shutdown_ssl (ssl);                 \
419 } while (0)
420 #else
421 # define SHUTDOWN_SSL(ssl) 
422 #endif
423
424 /* The idea behind these two CLOSE macros is to distinguish between
425    two cases: one when the job we've been doing is finished, and we
426    want to close the connection and leave, and two when something is
427    seriously wrong and we're closing the connection as part of
428    cleanup.
429
430    In case of keep_alive, CLOSE_FINISH should leave the connection
431    open, while CLOSE_INVALIDATE should still close it.
432
433    Note that the semantics of the flag `keep_alive' is "this
434    connection *will* be reused (the server has promised not to close
435    the connection once we're done)", while the semantics of
436    `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
437    active, registered connection".  */
438
439 #define CLOSE_FINISH(fd) do {                   \
440   if (!keep_alive)                              \
441     {                                           \
442       SHUTDOWN_SSL (ssl);                       \
443       CLOSE (fd);                               \
444       if (pc_active_p && (fd) == pc_last_fd)    \
445         invalidate_persistent ();               \
446     }                                           \
447 } while (0)
448
449 #define CLOSE_INVALIDATE(fd) do {               \
450   SHUTDOWN_SSL (ssl);                           \
451   CLOSE (fd);                                   \
452   if (pc_active_p && (fd) == pc_last_fd)        \
453     invalidate_persistent ();                   \
454 } while (0)
455 \f
456 struct http_stat
457 {
458   long len;                     /* received length */
459   long contlen;                 /* expected length */
460   long restval;                 /* the restart value */
461   int res;                      /* the result of last read */
462   char *newloc;                 /* new location (redirection) */
463   char *remote_time;            /* remote time-stamp string */
464   char *error;                  /* textual HTTP error */
465   int statcode;                 /* status code */
466   long dltime;                  /* time of the download */
467   int no_truncate;              /* whether truncating the file is
468                                    forbidden. */
469 };
470
471 /* Free the elements of hstat X.  */
472 #define FREEHSTAT(x) do                                 \
473 {                                                       \
474   FREE_MAYBE ((x).newloc);                              \
475   FREE_MAYBE ((x).remote_time);                         \
476   FREE_MAYBE ((x).error);                               \
477   (x).newloc = (x).remote_time = (x).error = NULL;      \
478 } while (0)
479
480 static char *create_authorization_line PARAMS ((const char *, const char *,
481                                                 const char *, const char *,
482                                                 const char *));
483 static char *basic_authentication_encode PARAMS ((const char *, const char *,
484                                                   const char *));
485 static int known_authentication_scheme_p PARAMS ((const char *));
486
487 time_t http_atotm PARAMS ((char *));
488
489 #define BEGINS_WITH(line, string_constant)                              \
490   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
491    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
492        || !line[sizeof (string_constant) - 1]))
493
494 /* Retrieve a document through HTTP protocol.  It recognizes status
495    code, and correctly handles redirections.  It closes the network
496    socket.  If it receives an error from the functions below it, it
497    will print it if there is enough information to do so (almost
498    always), returning the error to the caller (i.e. http_loop).
499
500    Various HTTP parameters are stored to hs.  Although it parses the
501    response code correctly, it is not used in a sane way.  The caller
502    can do that, though.
503
504    If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
505    and u->proxy->url will be given to the proxy server (bad naming,
506    I'm afraid).  */
507 static uerr_t
508 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
509 {
510   char *request, *type, *command, *path;
511   char *user, *passwd;
512   char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
513   char *authenticate_h;
514   char *proxyauth;
515   char *all_headers;
516   char *port_maybe;
517   char *request_keep_alive;
518   int sock, hcount, num_written, all_length, remport, statcode;
519   long contlen, contrange;
520   struct urlinfo *ou;
521   uerr_t err;
522   FILE *fp;
523   int auth_tried_already;
524   struct rbuf rbuf;
525 #ifdef HAVE_SSL
526   static SSL_CTX *ssl_ctx = NULL;
527   SSL *ssl = NULL;
528 #endif /* HAVE_SSL */
529   struct wget_timer *timer;
530   char *cookies = NULL;
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)
546     {
547       err=init_ssl (&ssl_ctx);
548       if (err != 0)
549         {
550           switch (err)
551             {
552             case SSLERRCTXCREATE:
553               /* this is fatal */
554               logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
555               ssl_printerrors ();
556               return err;
557             case SSLERRCERTFILE:
558               /* try without certfile */
559               logprintf (LOG_NOTQUIET,
560                          _("Failed to load certificates from %s\n"),
561                          opt.sslcertfile);
562               ssl_printerrors ();
563               logprintf (LOG_NOTQUIET,
564                          _("Trying without the specified certificate\n"));
565               break;
566             case SSLERRCERTKEY:
567               logprintf (LOG_NOTQUIET,
568                          _("Failed to get certificate key from %s\n"),
569                          opt.sslcertkey);
570               ssl_printerrors ();
571               logprintf (LOG_NOTQUIET,
572                          _("Trying without the specified certificate\n"));
573               break;
574             default:
575               break;
576             }
577         }
578     }
579 #endif /* HAVE_SSL */
580
581   if (!(*dt & HEAD_ONLY))
582     /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
583        know the local filename so we can save to it. */
584     assert (u->local != NULL);
585
586   authenticate_h = 0;
587   auth_tried_already = 0;
588
589   inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
590
591  again:
592   /* We need to come back here when the initial attempt to retrieve
593      without authorization header fails.  (Expected to happen at least
594      for the Digest authorization scheme.)  */
595
596   keep_alive = 0;
597   http_keep_alive_1 = http_keep_alive_2 = 0;
598
599   /* Initialize certain elements of struct http_stat.  */
600   hs->len = 0L;
601   hs->contlen = -1;
602   hs->res = -1;
603   hs->newloc = NULL;
604   hs->remote_time = NULL;
605   hs->error = NULL;
606
607   /* Which structure to use to retrieve the original URL data.  */
608   if (u->proxy)
609     ou = u->proxy;
610   else
611     ou = u;
612
613   /* First: establish the connection.  */
614   if (inhibit_keep_alive
615       ||
616 #ifndef HAVE_SSL
617       !persistent_available_p (u->host, u->port)
618 #else
619       !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
620 #endif /* HAVE_SSL */
621       )
622     {
623       logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
624       err = make_connection (&sock, u->host, u->port);
625       switch (err)
626         {
627         case HOSTERR:
628           logputs (LOG_VERBOSE, "\n");
629           logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
630           return HOSTERR;
631           break;
632         case CONSOCKERR:
633           logputs (LOG_VERBOSE, "\n");
634           logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
635           return CONSOCKERR;
636           break;
637         case CONREFUSED:
638           logputs (LOG_VERBOSE, "\n");
639           logprintf (LOG_NOTQUIET,
640                      _("Connection to %s:%hu refused.\n"), u->host, u->port);
641           CLOSE (sock);
642           return CONREFUSED;
643         case CONERROR:
644           logputs (LOG_VERBOSE, "\n");
645           logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
646           CLOSE (sock);
647           return CONERROR;
648           break;
649         case NOCONERROR:
650           /* Everything is fine!  */
651           logputs (LOG_VERBOSE, _("connected!\n"));
652           break;
653         default:
654           abort ();
655           break;
656         }
657 #ifdef HAVE_SSL
658      if (u->proto == URLHTTPS)
659        if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
660          {
661            logputs (LOG_VERBOSE, "\n");
662            logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
663            CLOSE (sock);
664            return CONSSLERR;
665          }
666 #endif /* HAVE_SSL */
667     }
668   else
669     {
670       logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
671       /* #### pc_last_fd should be accessed through an accessor
672          function.  */
673       sock = pc_last_fd;
674 #ifdef HAVE_SSL
675       ssl = pc_last_ssl;
676 #endif /* HAVE_SSL */
677       DEBUGP (("Reusing fd %d.\n", sock));
678     }
679
680   if (u->proxy)
681     path = u->proxy->url;
682   else
683     path = u->path;
684   
685   command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
686   referer = NULL;
687   if (ou->referer)
688     {
689       referer = (char *)alloca (9 + strlen (ou->referer) + 3);
690       sprintf (referer, "Referer: %s\r\n", ou->referer);
691     }
692   if (*dt & SEND_NOCACHE)
693     pragma_h = "Pragma: no-cache\r\n";
694   else
695     pragma_h = "";
696   if (hs->restval)
697     {
698       range = (char *)alloca (13 + numdigit (hs->restval) + 4);
699       /* Gag me!  Some servers (e.g. WebSitePro) have been known to
700          respond to the following `Range' format by generating a
701          multipart/x-byte-ranges MIME document!  This MIME type was
702          present in an old draft of the byteranges specification.
703          HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
704          only if multiple non-overlapping ranges are requested --
705          which Wget never does.  */
706       sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
707     }
708   else
709     range = NULL;
710   if (opt.useragent)
711     STRDUP_ALLOCA (useragent, opt.useragent);
712   else
713     {
714       useragent = (char *)alloca (10 + strlen (version_string));
715       sprintf (useragent, "Wget/%s", version_string);
716     }
717   /* Construct the authentication, if userid is present.  */
718   user = ou->user;
719   passwd = ou->passwd;
720   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
721   user = user ? user : opt.http_user;
722   passwd = passwd ? passwd : opt.http_passwd;
723
724   wwwauth = NULL;
725   if (user && passwd)
726     {
727       if (!authenticate_h)
728         {
729           /* We have the username and the password, but haven't tried
730              any authorization yet.  Let's see if the "Basic" method
731              works.  If not, we'll come back here and construct a
732              proper authorization method with the right challenges.
733
734              If we didn't employ this kind of logic, every URL that
735              requires authorization would have to be processed twice,
736              which is very suboptimal and generates a bunch of false
737              "unauthorized" errors in the server log.
738
739              #### But this logic also has a serious problem when used
740              with stronger authentications: we *first* transmit the
741              username and the password in clear text, and *then*
742              attempt a stronger authentication scheme.  That cannot be
743              right!  We are only fortunate that almost everyone still
744              uses the `Basic' scheme anyway.
745
746              There should be an option to prevent this from happening,
747              for those who use strong authentication schemes and value
748              their passwords.  */
749           wwwauth = basic_authentication_encode (user, passwd, "Authorization");
750         }
751       else
752         {
753           wwwauth = create_authorization_line (authenticate_h, user, passwd,
754                                                command, ou->path);
755         }
756     }
757
758   proxyauth = NULL;
759   if (u->proxy)
760     {
761       char *proxy_user, *proxy_passwd;
762       /* For normal username and password, URL components override
763          command-line/wgetrc parameters.  With proxy authentication,
764          it's the reverse, because proxy URLs are normally the
765          "permanent" ones, so command-line args should take
766          precedence.  */
767       if (opt.proxy_user && opt.proxy_passwd)
768         {
769           proxy_user = opt.proxy_user;
770           proxy_passwd = opt.proxy_passwd;
771         }
772       else
773         {
774           proxy_user = u->user;
775           proxy_passwd = u->passwd;
776         }
777       /* #### This is junky.  Can't the proxy request, say, `Digest'
778          authentication?  */
779       if (proxy_user && proxy_passwd)
780         proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
781                                                  "Proxy-Authorization");
782     }
783   remhost = ou->host;
784   remport = ou->port;
785
786   /* String of the form :PORT.  Used only for non-standard ports. */
787   port_maybe = NULL;
788   if (1
789 #ifdef HAVE_SSL
790       && remport != (u->proto == URLHTTPS
791                      ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT)
792 #else
793       && remport != DEFAULT_HTTP_PORT
794 #endif
795       )
796     {
797       port_maybe = (char *)alloca (numdigit (remport) + 2);
798       sprintf (port_maybe, ":%d", remport);
799     }
800
801   if (!inhibit_keep_alive)
802     request_keep_alive = "Connection: Keep-Alive\r\n";
803   else
804     request_keep_alive = NULL;
805
806   if (opt.cookies)
807     cookies = build_cookies_request (ou->host, ou->port, ou->path,
808                                      ou->proto == URLHTTPS);
809
810   /* Allocate the memory for the request.  */
811   request = (char *)alloca (strlen (command) + strlen (path)
812                             + strlen (useragent)
813                             + strlen (remhost)
814                             + (port_maybe ? strlen (port_maybe) : 0)
815                             + strlen (HTTP_ACCEPT)
816                             + (request_keep_alive
817                                ? strlen (request_keep_alive) : 0)
818                             + (referer ? strlen (referer) : 0)
819                             + (cookies ? strlen (cookies) : 0)
820                             + (wwwauth ? strlen (wwwauth) : 0)
821                             + (proxyauth ? strlen (proxyauth) : 0)
822                             + (range ? strlen (range) : 0)
823                             + strlen (pragma_h)
824                             + (opt.user_header ? strlen (opt.user_header) : 0)
825                             + 64);
826   /* Construct the request.  */
827   sprintf (request, "\
828 %s %s HTTP/1.0\r\n\
829 User-Agent: %s\r\n\
830 Host: %s%s\r\n\
831 Accept: %s\r\n\
832 %s%s%s%s%s%s%s%s\r\n",
833            command, path, useragent, remhost,
834            port_maybe ? port_maybe : "",
835            HTTP_ACCEPT,
836            request_keep_alive ? request_keep_alive : "",
837            referer ? referer : "",
838            cookies ? cookies : "", 
839            wwwauth ? wwwauth : "", 
840            proxyauth ? proxyauth : "", 
841            range ? range : "",
842            pragma_h, 
843            opt.user_header ? opt.user_header : "");
844   DEBUGP (("---request begin---\n%s---request end---\n", request));
845    /* Free the temporary memory.  */
846   FREE_MAYBE (wwwauth);
847   FREE_MAYBE (proxyauth);
848   FREE_MAYBE (cookies);
849
850   /* Send the request to server.  */
851 #ifdef HAVE_SSL
852   if (u->proto == URLHTTPS)
853     num_written = ssl_iwrite (ssl, request, strlen (request));
854   else
855 #endif /* HAVE_SSL */
856     num_written = iwrite (sock, request, strlen (request));
857
858   if (num_written < 0)
859     {
860       logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
861                  strerror (errno));
862       CLOSE_INVALIDATE (sock);
863       return WRITEFAILED;
864     }
865   logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
866              u->proxy ? "Proxy" : "HTTP");
867   contlen = contrange = -1;
868   type = NULL;
869   statcode = -1;
870   *dt &= ~RETROKF;
871
872   /* Before reading anything, initialize the rbuf.  */
873   rbuf_initialize (&rbuf, sock);
874 #ifdef HAVE_SSL
875   if (u->proto == URLHTTPS)
876     rbuf.ssl = ssl;
877   else
878     rbuf.ssl = NULL;
879 #endif /* HAVE_SSL */
880   all_headers = NULL;
881   all_length = 0;
882   /* Header-fetching loop.  */
883   hcount = 0;
884   while (1)
885     {
886       char *hdr;
887       int status;
888
889       ++hcount;
890       /* Get the header.  */
891       status = header_get (&rbuf, &hdr,
892                            /* Disallow continuations for status line.  */
893                            (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
894
895       /* Check for errors.  */
896       if (status == HG_EOF && *hdr)
897         {
898           /* This used to be an unconditional error, but that was
899              somewhat controversial, because of a large number of
900              broken CGI's that happily "forget" to send the second EOL
901              before closing the connection of a HEAD request.
902
903              So, the deal is to check whether the header is empty
904              (*hdr is zero if it is); if yes, it means that the
905              previous header was fully retrieved, and that -- most
906              probably -- the request is complete.  "...be liberal in
907              what you accept."  Oh boy.  */
908           logputs (LOG_VERBOSE, "\n");
909           logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
910           xfree (hdr);
911           FREE_MAYBE (type);
912           FREE_MAYBE (all_headers);
913           CLOSE_INVALIDATE (sock);
914           return HEOF;
915         }
916       else if (status == HG_ERROR)
917         {
918           logputs (LOG_VERBOSE, "\n");
919           logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
920                      strerror (errno));
921           xfree (hdr);
922           FREE_MAYBE (type);
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   /* Return if redirected.  */
1123   if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1124     {
1125       /* RFC2068 says that in case of the 300 (multiple choices)
1126          response, the server can output a preferred URL through
1127          `Location' header; otherwise, the request should be treated
1128          like GET.  So, if the location is set, it will be a
1129          redirection; otherwise, just proceed normally.  */
1130       if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1131         *dt |= RETROKF;
1132       else
1133         {
1134           logprintf (LOG_VERBOSE,
1135                      _("Location: %s%s\n"),
1136                      hs->newloc ? hs->newloc : _("unspecified"),
1137                      hs->newloc ? _(" [following]") : "");
1138           CLOSE_INVALIDATE (sock);      /* would be CLOSE_FINISH, but there
1139                                            might be more bytes in the body. */
1140           FREE_MAYBE (type);
1141           FREE_MAYBE (all_headers);
1142           return NEWLOCATION;
1143         }
1144     }
1145
1146   if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1147     *dt |= TEXTHTML;
1148   else
1149     /* We don't assume text/html by default.  */
1150     *dt &= ~TEXTHTML;
1151
1152   if (opt.html_extension && (*dt & TEXTHTML))
1153     /* -E / --html-extension / html_extension = on was specified, and this is a
1154        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
1155        already the file's suffix, tack on ".html". */
1156     {
1157       char*  last_period_in_local_filename = strrchr(u->local, '.');
1158
1159       if (last_period_in_local_filename == NULL ||
1160           !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1161             strcasecmp(last_period_in_local_filename, ".html") == EQ))
1162         {
1163           size_t  local_filename_len = strlen(u->local);
1164           
1165           u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1166           strcpy(u->local + local_filename_len, ".html");
1167
1168           *dt |= ADDED_HTML_EXTENSION;
1169         }
1170     }
1171
1172   if (contrange == -1)
1173     {
1174       /* We did not get a content-range header.  This means that the
1175          server did not honor our `Range' request.  Normally, this
1176          means we should reset hs->restval and continue normally.  */
1177
1178       /* However, if `-c' is used, we need to be a bit more careful:
1179
1180          1. If `-c' is specified and the file already existed when
1181          Wget was started, it would be a bad idea for us to start
1182          downloading it from scratch, effectively truncating it.  I
1183          believe this cannot happen unless `-c' was specified.
1184
1185          2. If `-c' is used on a file that is already fully
1186          downloaded, we're requesting bytes after the end of file,
1187          which can result in server not honoring `Range'.  If this is
1188          the case, `Content-Length' will be equal to the length of the
1189          file.  */
1190       if (opt.always_rest)
1191         {
1192           /* Check for condition #2. */
1193           if (hs->restval > 0               /* restart was requested. */
1194               && contlen != -1              /* we got content-length. */
1195               && hs->restval >= contlen     /* file fully downloaded
1196                                                or has shrunk.  */
1197               )
1198             {
1199               logputs (LOG_VERBOSE, _("\
1200 \n    The file is already fully retrieved; nothing to do.\n\n"));
1201               /* In case the caller inspects. */
1202               hs->len = contlen;
1203               hs->res = 0;
1204               FREE_MAYBE (type);
1205               FREE_MAYBE (all_headers);
1206               CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1207                                            might be more bytes in the body. */
1208               return RETRUNNEEDED;
1209             }
1210
1211           /* Check for condition #1. */
1212           if (hs->no_truncate)
1213             {
1214               logprintf (LOG_NOTQUIET,
1215                          _("\
1216 \n\
1217 The server does not support continued downloads, which conflicts with `-c'.\n\
1218 Refusing to truncate existing file `%s'.\n\n"), u->local);
1219               FREE_MAYBE (type);
1220               FREE_MAYBE (all_headers);
1221               CLOSE_INVALIDATE (sock);
1222               return CONTNOTSUPPORTED;
1223             }
1224
1225           /* Fallthrough */
1226         }
1227
1228       hs->restval = 0;
1229     }
1230   else if (contrange != hs->restval ||
1231            (H_PARTIAL (statcode) && contrange == -1))
1232     {
1233       /* This means the whole request was somehow misunderstood by the
1234          server.  Bail out.  */
1235       FREE_MAYBE (type);
1236       FREE_MAYBE (all_headers);
1237       CLOSE_INVALIDATE (sock);
1238       return RANGEERR;
1239     }
1240
1241   if (hs->restval)
1242     {
1243       if (contlen != -1)
1244         contlen += contrange;
1245       else
1246         contrange = -1;        /* If conent-length was not sent,
1247                                   content-range will be ignored.  */
1248     }
1249   hs->contlen = contlen;
1250
1251   if (opt.verbose)
1252     {
1253       if ((*dt & RETROKF) && !opt.server_response)
1254         {
1255           /* No need to print this output if the body won't be
1256              downloaded at all, or if the original server response is
1257              printed.  */
1258           logputs (LOG_VERBOSE, _("Length: "));
1259           if (contlen != -1)
1260             {
1261               logputs (LOG_VERBOSE, legible (contlen));
1262               if (contrange != -1)
1263                 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1264                            legible (contlen - contrange));
1265             }
1266           else
1267             logputs (LOG_VERBOSE,
1268                      opt.ignore_length ? _("ignored") : _("unspecified"));
1269           if (type)
1270             logprintf (LOG_VERBOSE, " [%s]\n", type);
1271           else
1272             logputs (LOG_VERBOSE, "\n");
1273         }
1274     }
1275   FREE_MAYBE (type);
1276   type = NULL;                  /* We don't need it any more.  */
1277
1278   /* Return if we have no intention of further downloading.  */
1279   if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1280     {
1281       /* In case the caller cares to look...  */
1282       hs->len = 0L;
1283       hs->res = 0;
1284       FREE_MAYBE (type);
1285       FREE_MAYBE (all_headers);
1286       CLOSE_INVALIDATE (sock);  /* would be CLOSE_FINISH, but there
1287                                    might be more bytes in the body. */
1288       return RETRFINISHED;
1289     }
1290
1291   /* Open the local file.  */
1292   if (!opt.dfp)
1293     {
1294       mkalldirs (u->local);
1295       if (opt.backups)
1296         rotate_backups (u->local);
1297       fp = fopen (u->local, hs->restval ? "ab" : "wb");
1298       if (!fp)
1299         {
1300           logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1301           CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1302                                       might be more bytes in the body. */
1303           FREE_MAYBE (all_headers);
1304           return FOPENERR;
1305         }
1306     }
1307   else                          /* opt.dfp */
1308     {
1309       extern int global_download_count;
1310       fp = opt.dfp;
1311       /* To ensure that repeated "from scratch" downloads work for -O
1312          files, we rewind the file pointer, unless restval is
1313          non-zero.  (This works only when -O is used on regular files,
1314          but it's still a valuable feature.)
1315
1316          However, this loses when more than one URL is specified on
1317          the command line the second rewinds eradicates the contents
1318          of the first download.  Thus we disable the above trick for
1319          all the downloads except the very first one.
1320
1321          #### A possible solution to this would be to remember the
1322          file position in the output document and to seek to that
1323          position, instead of rewinding.  */
1324       if (!hs->restval && global_download_count == 0)
1325         {
1326           /* This will silently fail for streams that don't correspond
1327              to regular files, but that's OK.  */
1328           rewind (fp);
1329           /* ftruncate is needed because opt.dfp is opened in append
1330              mode if opt.always_rest is set.  */
1331           ftruncate (fileno (fp), 0);
1332           clearerr (fp);
1333         }
1334     }
1335
1336   /* #### This confuses the code that checks for file size.  There
1337      should be some overhead information.  */
1338   if (opt.save_headers)
1339     fwrite (all_headers, 1, all_length, fp);
1340   timer = wtimer_new ();
1341   /* Get the contents of the document.  */
1342   hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1343                           (contlen != -1 ? contlen : 0),
1344                           &rbuf, keep_alive);
1345   hs->dltime = wtimer_elapsed (timer);
1346   wtimer_delete (timer);
1347   {
1348     /* Close or flush the file.  We have to be careful to check for
1349        error here.  Checking the result of fwrite() is not enough --
1350        errors could go unnoticed!  */
1351     int flush_res;
1352     if (!opt.dfp)
1353       flush_res = fclose (fp);
1354     else
1355       flush_res = fflush (fp);
1356     if (flush_res == EOF)
1357       hs->res = -2;
1358   }
1359   FREE_MAYBE (all_headers);
1360   CLOSE_FINISH (sock);
1361   if (hs->res == -2)
1362     return FWRITEERR;
1363   return RETRFINISHED;
1364 }
1365
1366 /* The genuine HTTP loop!  This is the part where the retrieval is
1367    retried, and retried, and retried, and...  */
1368 uerr_t
1369 http_loop (struct urlinfo *u, char **newloc, int *dt)
1370 {
1371   int count;
1372   int use_ts, got_head = 0;     /* time-stamping info */
1373   char *filename_plus_orig_suffix;
1374   char *local_filename = NULL;
1375   char *tms, *suf, *locf, *tmrate;
1376   uerr_t err;
1377   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
1378   long local_size = 0;          /* the size of the local file */
1379   size_t filename_len;
1380   struct http_stat hstat;       /* HTTP status */
1381   struct stat st;
1382
1383   /* This used to be done in main(), but it's a better idea to do it
1384      here so that we don't go through the hoops if we're just using
1385      FTP or whatever. */
1386   if (opt.cookies && opt.cookies_input && !cookies_loaded_p)
1387     {
1388       load_cookies (opt.cookies_input);
1389       cookies_loaded_p = 1;
1390     }
1391
1392   *newloc = NULL;
1393
1394   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
1395      has_wildcards_p because it would also warn on `?', and we know that
1396      shows up in CGI paths a *lot*.  */
1397   if (strchr (u->url, '*'))
1398     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1399
1400   /* Determine the local filename.  */
1401   if (!u->local)
1402     u->local = url_filename (u->proxy ? u->proxy : u);
1403
1404   if (!opt.output_document)
1405     locf = u->local;
1406   else
1407     locf = opt.output_document;
1408
1409   filename_len = strlen (u->local);
1410   filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1411
1412   if (opt.noclobber && file_exists_p (u->local))
1413     {
1414       /* If opt.noclobber is turned on and file already exists, do not
1415          retrieve the file */
1416       logprintf (LOG_VERBOSE, _("\
1417 File `%s' already there, will not retrieve.\n"), u->local);
1418       /* If the file is there, we suppose it's retrieved OK.  */
1419       *dt |= RETROKF;
1420
1421       /* #### Bogusness alert.  */
1422       /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1423          text/html, a harmless lie.  */
1424       if (((suf = suffix (u->local)) != NULL)
1425           && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1426         *dt |= TEXTHTML;
1427       xfree (suf);
1428       /* Another harmless lie: */
1429       return RETROK;
1430     }
1431
1432   use_ts = 0;
1433   if (opt.timestamping)
1434     {
1435       boolean  local_dot_orig_file_exists = FALSE;
1436
1437       if (opt.backup_converted)
1438         /* If -K is specified, we'll act on the assumption that it was specified
1439            last time these files were downloaded as well, and instead of just
1440            comparing local file X against server file X, we'll compare local
1441            file X.orig (if extant, else X) against server file X.  If -K
1442            _wasn't_ specified last time, or the server contains files called
1443            *.orig, -N will be back to not operating correctly with -k. */
1444         {
1445           /* Would a single s[n]printf() call be faster?  --dan
1446
1447              Definitely not.  sprintf() is horribly slow.  It's a
1448              different question whether the difference between the two
1449              affects a program.  Usually I'd say "no", but at one
1450              point I profiled Wget, and found that a measurable and
1451              non-negligible amount of time was lost calling sprintf()
1452              in url.c.  Replacing sprintf with inline calls to
1453              strcpy() and long_to_string() made a difference.
1454              --hniksic */
1455           memcpy (filename_plus_orig_suffix, u->local, filename_len);
1456           memcpy (filename_plus_orig_suffix + filename_len,
1457                   ".orig", sizeof (".orig"));
1458
1459           /* Try to stat() the .orig file. */
1460           if (stat (filename_plus_orig_suffix, &st) == 0)
1461             {
1462               local_dot_orig_file_exists = TRUE;
1463               local_filename = filename_plus_orig_suffix;
1464             }
1465         }      
1466
1467       if (!local_dot_orig_file_exists)
1468         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1469         if (stat (u->local, &st) == 0)
1470           local_filename = u->local;
1471
1472       if (local_filename != NULL)
1473         /* There was a local file, so we'll check later to see if the version
1474            the server has is the same version we already have, allowing us to
1475            skip a download. */
1476         {
1477           use_ts = 1;
1478           tml = st.st_mtime;
1479           local_size = st.st_size;
1480           got_head = 0;
1481         }
1482     }
1483   /* Reset the counter.  */
1484   count = 0;
1485   *dt = 0 | ACCEPTRANGES;
1486   /* THE loop */
1487   do
1488     {
1489       /* Increment the pass counter.  */
1490       ++count;
1491       sleep_between_retrievals (count);
1492       /* Get the current time string.  */
1493       tms = time_str (NULL);
1494       /* Print fetch message, if opt.verbose.  */
1495       if (opt.verbose)
1496         {
1497           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1498           char tmp[15];
1499           strcpy (tmp, "        ");
1500           if (count > 1)
1501             sprintf (tmp, _("(try:%2d)"), count);
1502           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1503                      tms, hurl, tmp, locf);
1504 #ifdef WINDOWS
1505           ws_changetitle (hurl, 1);
1506 #endif
1507           xfree (hurl);
1508         }
1509
1510       /* Default document type is empty.  However, if spider mode is
1511          on or time-stamping is employed, HEAD_ONLY commands is
1512          encoded within *dt.  */
1513       if (opt.spider || (use_ts && !got_head))
1514         *dt |= HEAD_ONLY;
1515       else
1516         *dt &= ~HEAD_ONLY;
1517       /* Assume no restarting.  */
1518       hstat.restval = 0L;
1519       /* Decide whether or not to restart.  */
1520       if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1521           /* #### this calls access() and then stat(); could be optimized. */
1522           && file_exists_p (locf))
1523         if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1524           hstat.restval = st.st_size;
1525
1526       /* In `-c' is used and the file is existing and non-empty,
1527          refuse to truncate it if the server doesn't support continued
1528          downloads.  */
1529       hstat.no_truncate = 0;
1530       if (opt.always_rest && hstat.restval)
1531         hstat.no_truncate = 1;
1532
1533       /* Decide whether to send the no-cache directive.  We send it in
1534          two cases:
1535            a) we're using a proxy, and we're past our first retrieval.
1536               Some proxies are notorious for caching incomplete data, so
1537               we require a fresh get.
1538            b) caching is explicitly inhibited. */
1539       if ((u->proxy && count > 1) /* a */
1540           || !opt.allow_cache     /* b */
1541           )
1542         *dt |= SEND_NOCACHE;
1543       else
1544         *dt &= ~SEND_NOCACHE;
1545
1546       /* Try fetching the document, or at least its head.  :-) */
1547       err = gethttp (u, &hstat, dt);
1548
1549       /* It's unfortunate that wget determines the local filename before finding
1550          out the Content-Type of the file.  Barring a major restructuring of the
1551          code, we need to re-set locf here, since gethttp() may have xrealloc()d
1552          u->local to tack on ".html". */
1553       if (!opt.output_document)
1554         locf = u->local;
1555       else
1556         locf = opt.output_document;
1557
1558       /* Time?  */
1559       tms = time_str (NULL);
1560       /* Get the new location (with or without the redirection).  */
1561       if (hstat.newloc)
1562         *newloc = xstrdup (hstat.newloc);
1563       switch (err)
1564         {
1565         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1566         case CONERROR: case READERR: case WRITEFAILED:
1567         case RANGEERR:
1568           /* Non-fatal errors continue executing the loop, which will
1569              bring them to "while" statement at the end, to judge
1570              whether the number of tries was exceeded.  */
1571           FREEHSTAT (hstat);
1572           printwhat (count, opt.ntry);
1573           continue;
1574           break;
1575         case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED: 
1576         case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1577           /* Fatal errors just return from the function.  */
1578           FREEHSTAT (hstat);
1579           return err;
1580           break;
1581         case FWRITEERR: case FOPENERR:
1582           /* Another fatal error.  */
1583           logputs (LOG_VERBOSE, "\n");
1584           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1585                      u->local, strerror (errno));
1586           FREEHSTAT (hstat);
1587           return err;
1588           break;
1589         case CONSSLERR:
1590           /* Another fatal error.  */
1591           logputs (LOG_VERBOSE, "\n");
1592           logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1593           FREEHSTAT (hstat);
1594           return err;
1595           break;
1596         case NEWLOCATION:
1597           /* Return the new location to the caller.  */
1598           if (!hstat.newloc)
1599             {
1600               logprintf (LOG_NOTQUIET,
1601                          _("ERROR: Redirection (%d) without location.\n"),
1602                          hstat.statcode);
1603               return WRONGCODE;
1604             }
1605           FREEHSTAT (hstat);
1606           return NEWLOCATION;
1607           break;
1608         case RETRUNNEEDED:
1609           /* The file was already fully retrieved. */
1610           FREEHSTAT (hstat);
1611           return RETROK;
1612           break;
1613         case RETRFINISHED:
1614           /* Deal with you later.  */
1615           break;
1616         default:
1617           /* All possibilities should have been exhausted.  */
1618           abort ();
1619         }
1620       if (!(*dt & RETROKF))
1621         {
1622           if (!opt.verbose)
1623             {
1624               /* #### Ugly ugly ugly! */
1625               char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1626               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1627               xfree (hurl);
1628             }
1629           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1630                      tms, hstat.statcode, hstat.error);
1631           logputs (LOG_VERBOSE, "\n");
1632           FREEHSTAT (hstat);
1633           return WRONGCODE;
1634         }
1635
1636       /* Did we get the time-stamp?  */
1637       if (!got_head)
1638         {
1639           if (opt.timestamping && !hstat.remote_time)
1640             {
1641               logputs (LOG_NOTQUIET, _("\
1642 Last-modified header missing -- time-stamps turned off.\n"));
1643             }
1644           else if (hstat.remote_time)
1645             {
1646               /* Convert the date-string into struct tm.  */
1647               tmr = http_atotm (hstat.remote_time);
1648               if (tmr == (time_t) (-1))
1649                 logputs (LOG_VERBOSE, _("\
1650 Last-modified header invalid -- time-stamp ignored.\n"));
1651             }
1652         }
1653
1654       /* The time-stamping section.  */
1655       if (use_ts)
1656         {
1657           got_head = 1;
1658           *dt &= ~HEAD_ONLY;
1659           use_ts = 0;           /* no more time-stamping */
1660           count = 0;            /* the retrieve count for HEAD is
1661                                    reset */
1662           if (hstat.remote_time && tmr != (time_t) (-1))
1663             {
1664               /* Now time-stamping can be used validly.  Time-stamping
1665                  means that if the sizes of the local and remote file
1666                  match, and local file is newer than the remote file,
1667                  it will not be retrieved.  Otherwise, the normal
1668                  download procedure is resumed.  */
1669               if (tml >= tmr &&
1670                   (hstat.contlen == -1 || local_size == hstat.contlen))
1671                 {
1672                   logprintf (LOG_VERBOSE, _("\
1673 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1674                              local_filename);
1675                   FREEHSTAT (hstat);
1676                   return RETROK;
1677                 }
1678               else if (tml >= tmr)
1679                 logprintf (LOG_VERBOSE, _("\
1680 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1681               else
1682                 logputs (LOG_VERBOSE,
1683                          _("Remote file is newer, retrieving.\n"));
1684             }
1685           FREEHSTAT (hstat);
1686           continue;
1687         }
1688       if ((tmr != (time_t) (-1))
1689           && !opt.spider
1690           && ((hstat.len == hstat.contlen) ||
1691               ((hstat.res == 0) &&
1692                ((hstat.contlen == -1) ||
1693                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1694         {
1695           /* #### This code repeats in http.c and ftp.c.  Move it to a
1696              function!  */
1697           const char *fl = NULL;
1698           if (opt.output_document)
1699             {
1700               if (opt.od_known_regular)
1701                 fl = opt.output_document;
1702             }
1703           else
1704             fl = u->local;
1705           if (fl)
1706             touch (fl, tmr);
1707         }
1708       /* End of time-stamping section.  */
1709
1710       if (opt.spider)
1711         {
1712           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1713           return RETROK;
1714         }
1715
1716       /* It is now safe to free the remainder of hstat, since the
1717          strings within it will no longer be used.  */
1718       FREEHSTAT (hstat);
1719
1720       tmrate = rate (hstat.len - hstat.restval, hstat.dltime, 0);
1721
1722       if (hstat.len == hstat.contlen)
1723         {
1724           if (*dt & RETROKF)
1725             {
1726               logprintf (LOG_VERBOSE,
1727                          _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1728                          tms, tmrate, locf, hstat.len, hstat.contlen);
1729               logprintf (LOG_NONVERBOSE,
1730                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1731                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1732             }
1733           ++opt.numurls;
1734           downloaded_increase (hstat.len);
1735
1736           /* Remember that we downloaded the file for later ".orig" code. */
1737           if (*dt & ADDED_HTML_EXTENSION)
1738             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1739           else
1740             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1741
1742           return RETROK;
1743         }
1744       else if (hstat.res == 0) /* No read error */
1745         {
1746           if (hstat.contlen == -1)  /* We don't know how much we were supposed
1747                                        to get, so assume we succeeded. */ 
1748             {
1749               if (*dt & RETROKF)
1750                 {
1751                   logprintf (LOG_VERBOSE,
1752                              _("%s (%s) - `%s' saved [%ld]\n\n"),
1753                              tms, tmrate, locf, hstat.len);
1754                   logprintf (LOG_NONVERBOSE,
1755                              "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1756                              tms, u->url, hstat.len, locf, count);
1757                 }
1758               ++opt.numurls;
1759               downloaded_increase (hstat.len);
1760
1761               /* Remember that we downloaded the file for later ".orig" code. */
1762               if (*dt & ADDED_HTML_EXTENSION)
1763                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1764               else
1765                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1766               
1767               return RETROK;
1768             }
1769           else if (hstat.len < hstat.contlen) /* meaning we lost the
1770                                                  connection too soon */
1771             {
1772               logprintf (LOG_VERBOSE,
1773                          _("%s (%s) - Connection closed at byte %ld. "),
1774                          tms, tmrate, hstat.len);
1775               printwhat (count, opt.ntry);
1776               continue;
1777             }
1778           else if (!opt.kill_longer) /* meaning we got more than expected */
1779             {
1780               logprintf (LOG_VERBOSE,
1781                          _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1782                          tms, tmrate, locf, hstat.len, hstat.contlen);
1783               logprintf (LOG_NONVERBOSE,
1784                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1785                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1786               ++opt.numurls;
1787               downloaded_increase (hstat.len);
1788
1789               /* Remember that we downloaded the file for later ".orig" code. */
1790               if (*dt & ADDED_HTML_EXTENSION)
1791                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1792               else
1793                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1794               
1795               return RETROK;
1796             }
1797           else                  /* the same, but not accepted */
1798             {
1799               logprintf (LOG_VERBOSE,
1800                          _("%s (%s) - Connection closed at byte %ld/%ld. "),
1801                          tms, tmrate, hstat.len, hstat.contlen);
1802               printwhat (count, opt.ntry);
1803               continue;
1804             }
1805         }
1806       else                      /* now hstat.res can only be -1 */
1807         {
1808           if (hstat.contlen == -1)
1809             {
1810               logprintf (LOG_VERBOSE,
1811                          _("%s (%s) - Read error at byte %ld (%s)."),
1812                          tms, tmrate, hstat.len, strerror (errno));
1813               printwhat (count, opt.ntry);
1814               continue;
1815             }
1816           else                  /* hstat.res == -1 and contlen is given */
1817             {
1818               logprintf (LOG_VERBOSE,
1819                          _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1820                          tms, tmrate, hstat.len, hstat.contlen,
1821                          strerror (errno));
1822               printwhat (count, opt.ntry);
1823               continue;
1824             }
1825         }
1826       /* not reached */
1827       break;
1828     }
1829   while (!opt.ntry || (count < opt.ntry));
1830   return TRYLIMEXC;
1831 }
1832 \f
1833 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1834    than local timezone.
1835
1836    mktime is similar but assumes struct tm, also known as the
1837    "broken-down" form of time, is in local time zone.  mktime_from_utc
1838    uses mktime to make the conversion understanding that an offset
1839    will be introduced by the local time assumption.
1840
1841    mktime_from_utc then measures the introduced offset by applying
1842    gmtime to the initial result and applying mktime to the resulting
1843    "broken-down" form.  The difference between the two mktime results
1844    is the measured offset which is then subtracted from the initial
1845    mktime result to yield a calendar time which is the value returned.
1846
1847    tm_isdst in struct tm is set to 0 to force mktime to introduce a
1848    consistent offset (the non DST offset) since tm and tm+o might be
1849    on opposite sides of a DST change.
1850
1851    Some implementations of mktime return -1 for the nonexistent
1852    localtime hour at the beginning of DST.  In this event, use
1853    mktime(tm - 1hr) + 3600.
1854
1855    Schematically
1856      mktime(tm)   --> t+o
1857      gmtime(t+o)  --> tm+o
1858      mktime(tm+o) --> t+2o
1859      t+o - (t+2o - t+o) = t
1860
1861    Note that glibc contains a function of the same purpose named
1862    `timegm' (reverse of gmtime).  But obviously, it is not universally
1863    available, and unfortunately it is not straightforwardly
1864    extractable for use here.  Perhaps configure should detect timegm
1865    and use it where available.
1866
1867    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1868    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
1869    Further improved by Roger with assistance from Edward J. Sabol
1870    based on input by Jamie Zawinski.  */
1871
1872 static time_t
1873 mktime_from_utc (struct tm *t)
1874 {
1875   time_t tl, tb;
1876   struct tm *tg;
1877
1878   tl = mktime (t);
1879   if (tl == -1)
1880     {
1881       t->tm_hour--;
1882       tl = mktime (t);
1883       if (tl == -1)
1884         return -1; /* can't deal with output from strptime */
1885       tl += 3600;
1886     }
1887   tg = gmtime (&tl);
1888   tg->tm_isdst = 0;
1889   tb = mktime (tg);
1890   if (tb == -1)
1891     {
1892       tg->tm_hour--;
1893       tb = mktime (tg);
1894       if (tb == -1)
1895         return -1; /* can't deal with output from gmtime */
1896       tb += 3600;
1897     }
1898   return (tl - (tb - tl));
1899 }
1900
1901 /* Check whether the result of strptime() indicates success.
1902    strptime() returns the pointer to how far it got to in the string.
1903    The processing has been successful if the string is at `GMT' or
1904    `+X', or at the end of the string.
1905
1906    In extended regexp parlance, the function returns 1 if P matches
1907    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (which strptime
1908    can return) is considered a failure and 0 is returned.  */
1909 static int
1910 check_end (const char *p)
1911 {
1912   if (!p)
1913     return 0;
1914   while (ISSPACE (*p))
1915     ++p;
1916   if (!*p
1917       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1918       || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
1919     return 1;
1920   else
1921     return 0;
1922 }
1923
1924 /* Convert the textual specification of time in TIME_STRING to the
1925    number of seconds since the Epoch.
1926
1927    TIME_STRING can be in any of the three formats RFC2068 allows the
1928    HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
1929    Timezones are ignored, and should be GMT.
1930
1931    Return the computed time_t representation, or -1 if the conversion
1932    fails.
1933
1934    This function uses strptime with various string formats for parsing
1935    TIME_STRING.  This results in a parser that is not as lenient in
1936    interpreting TIME_STRING as I would like it to be.  Being based on
1937    strptime, it always allows shortened months, one-digit days, etc.,
1938    but due to the multitude of formats in which time can be
1939    represented, an ideal HTTP time parser would be even more
1940    forgiving.  It should completely ignore things like week days and
1941    concentrate only on the various forms of representing years,
1942    months, days, hours, minutes, and seconds.  For example, it would
1943    be nice if it accepted ISO 8601 out of the box.
1944
1945    I've investigated free and PD code for this purpose, but none was
1946    usable.  getdate was big and unwieldy, and had potential copyright
1947    issues, or so I was informed.  Dr. Marcus Hennecke's atotm(),
1948    distributed with phttpd, is excellent, but we cannot use it because
1949    it is not assigned to the FSF.  So I stuck it with strptime.  */
1950
1951 time_t
1952 http_atotm (char *time_string)
1953 {
1954   /* NOTE: Solaris strptime man page claims that %n and %t match white
1955      space, but that's not universally available.  Instead, we simply
1956      use ` ' to mean "skip all WS", which works under all strptime
1957      implementations I've tested.  */
1958
1959   static const char *time_formats[] = {
1960     "%a, %d %b %Y %T",          /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1961     "%A, %d-%b-%y %T",          /* RFC850:  Thursday, 29-Jan-98 22:12:57 */
1962     "%a, %d-%b-%Y %T",          /* pseudo-RFC850:  Thu, 29-Jan-1998 22:12:57
1963                                    (google.com uses this for their cookies.) */
1964     "%a %b %d %T %Y"            /* asctime: Thu Jan 29 22:12:57 1998 */
1965   };
1966
1967   int i;
1968   struct tm t;
1969
1970   /* According to Roger Beeman, we need to initialize tm_isdst, since
1971      strptime won't do it.  */
1972   t.tm_isdst = 0;
1973
1974   /* Note that under foreign locales Solaris strptime() fails to
1975      recognize English dates, which renders this function useless.  We
1976      solve this by being careful not to affect LC_TIME when
1977      initializing locale.
1978
1979      Another solution would be to temporarily set locale to C, invoke
1980      strptime(), and restore it back.  This is slow and dirty,
1981      however, and locale support other than LC_MESSAGES can mess other
1982      things, so I rather chose to stick with just setting LC_MESSAGES.
1983
1984      GNU strptime does not have this problem because it recognizes
1985      both international and local dates.  */
1986
1987   for (i = 0; i < ARRAY_SIZE (time_formats); i++)
1988     if (check_end (strptime (time_string, time_formats[i], &t)))
1989       return mktime_from_utc (&t);
1990
1991   /* All formats have failed.  */
1992   return -1;
1993 }
1994 \f
1995 /* Authorization support: We support two authorization schemes:
1996
1997    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1998
1999    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2000    consisting of answering to the server's challenge with the proper
2001    MD5 digests.  */
2002
2003 /* How many bytes it will take to store LEN bytes in base64.  */
2004 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2005
2006 /* Encode the string S of length LENGTH to base64 format and place it
2007    to STORE.  STORE will be 0-terminated, and must point to a writable
2008    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
2009 static void
2010 base64_encode (const char *s, char *store, int length)
2011 {
2012   /* Conversion table.  */
2013   static char tbl[64] = {
2014     'A','B','C','D','E','F','G','H',
2015     'I','J','K','L','M','N','O','P',
2016     'Q','R','S','T','U','V','W','X',
2017     'Y','Z','a','b','c','d','e','f',
2018     'g','h','i','j','k','l','m','n',
2019     'o','p','q','r','s','t','u','v',
2020     'w','x','y','z','0','1','2','3',
2021     '4','5','6','7','8','9','+','/'
2022   };
2023   int i;
2024   unsigned char *p = (unsigned char *)store;
2025
2026   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
2027   for (i = 0; i < length; i += 3)
2028     {
2029       *p++ = tbl[s[0] >> 2];
2030       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2031       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2032       *p++ = tbl[s[2] & 0x3f];
2033       s += 3;
2034     }
2035   /* Pad the result if necessary...  */
2036   if (i == length + 1)
2037     *(p - 1) = '=';
2038   else if (i == length + 2)
2039     *(p - 1) = *(p - 2) = '=';
2040   /* ...and zero-terminate it.  */
2041   *p = '\0';
2042 }
2043
2044 /* Create the authentication header contents for the `Basic' scheme.
2045    This is done by encoding the string `USER:PASS' in base64 and
2046    prepending `HEADER: Basic ' to it.  */
2047 static char *
2048 basic_authentication_encode (const char *user, const char *passwd,
2049                              const char *header)
2050 {
2051   char *t1, *t2, *res;
2052   int len1 = strlen (user) + 1 + strlen (passwd);
2053   int len2 = BASE64_LENGTH (len1);
2054
2055   t1 = (char *)alloca (len1 + 1);
2056   sprintf (t1, "%s:%s", user, passwd);
2057   t2 = (char *)alloca (1 + len2);
2058   base64_encode (t1, t2, len1);
2059   res = (char *)xmalloc (len2 + 11 + strlen (header));
2060   sprintf (res, "%s: Basic %s\r\n", header, t2);
2061
2062   return res;
2063 }
2064
2065 #ifdef USE_DIGEST
2066 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
2067    of a field in such a header.  If the field is the one specified by
2068    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2069    digest authorization code), extract its value in the (char*)
2070    variable pointed by RET.  Returns negative on a malformed header,
2071    or number of bytes that have been parsed by this call.  */
2072 static int
2073 extract_header_attr (const char *au, const char *attr_name, char **ret)
2074 {
2075   const char *cp, *ep;
2076
2077   ep = cp = au;
2078
2079   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2080     {
2081       cp += strlen (attr_name);
2082       if (!*cp)
2083         return -1;
2084       cp += skip_lws (cp);
2085       if (*cp != '=')
2086         return -1;
2087       if (!*++cp)
2088         return -1;
2089       cp += skip_lws (cp);
2090       if (*cp != '\"')
2091         return -1;
2092       if (!*++cp)
2093         return -1;
2094       for (ep = cp; *ep && *ep != '\"'; ep++)
2095         ;
2096       if (!*ep)
2097         return -1;
2098       FREE_MAYBE (*ret);
2099       *ret = strdupdelim (cp, ep);
2100       return ep - au + 1;
2101     }
2102   else
2103     return 0;
2104 }
2105
2106 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
2107    an array of 16 bytes containing the hash keys, and BUF should be a
2108    buffer of 33 writable characters (32 for hex digits plus one for
2109    zero termination).  */
2110 static void
2111 dump_hash (unsigned char *buf, const unsigned char *hash)
2112 {
2113   int i;
2114
2115   for (i = 0; i < MD5_HASHLEN; i++, hash++)
2116     {
2117       *buf++ = XDIGIT_TO_xchar (*hash >> 4);
2118       *buf++ = XDIGIT_TO_xchar (*hash & 0xf);
2119     }
2120   *buf = '\0';
2121 }
2122
2123 /* Take the line apart to find the challenge, and compose a digest
2124    authorization header.  See RFC2069 section 2.1.2.  */
2125 char *
2126 digest_authentication_encode (const char *au, const char *user,
2127                               const char *passwd, const char *method,
2128                               const char *path)
2129 {
2130   static char *realm, *opaque, *nonce;
2131   static struct {
2132     const char *name;
2133     char **variable;
2134   } options[] = {
2135     { "realm", &realm },
2136     { "opaque", &opaque },
2137     { "nonce", &nonce }
2138   };
2139   char *res;
2140
2141   realm = opaque = nonce = NULL;
2142
2143   au += 6;                      /* skip over `Digest' */
2144   while (*au)
2145     {
2146       int i;
2147
2148       au += skip_lws (au);
2149       for (i = 0; i < ARRAY_SIZE (options); i++)
2150         {
2151           int skip = extract_header_attr (au, options[i].name,
2152                                           options[i].variable);
2153           if (skip < 0)
2154             {
2155               FREE_MAYBE (realm);
2156               FREE_MAYBE (opaque);
2157               FREE_MAYBE (nonce);
2158               return NULL;
2159             }
2160           else if (skip)
2161             {
2162               au += skip;
2163               break;
2164             }
2165         }
2166       if (i == ARRAY_SIZE (options))
2167         {
2168           while (*au && *au != '=')
2169             au++;
2170           if (*au && *++au)
2171             {
2172               au += skip_lws (au);
2173               if (*au == '\"')
2174                 {
2175                   au++;
2176                   while (*au && *au != '\"')
2177                     au++;
2178                   if (*au)
2179                     au++;
2180                 }
2181             }
2182         }
2183       while (*au && *au != ',')
2184         au++;
2185       if (*au)
2186         au++;
2187     }
2188   if (!realm || !nonce || !user || !passwd || !path || !method)
2189     {
2190       FREE_MAYBE (realm);
2191       FREE_MAYBE (opaque);
2192       FREE_MAYBE (nonce);
2193       return NULL;
2194     }
2195
2196   /* Calculate the digest value.  */
2197   {
2198     struct md5_ctx ctx;
2199     unsigned char hash[MD5_HASHLEN];
2200     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2201     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2202
2203     /* A1BUF = H(user ":" realm ":" password) */
2204     md5_init_ctx (&ctx);
2205     md5_process_bytes (user, strlen (user), &ctx);
2206     md5_process_bytes (":", 1, &ctx);
2207     md5_process_bytes (realm, strlen (realm), &ctx);
2208     md5_process_bytes (":", 1, &ctx);
2209     md5_process_bytes (passwd, strlen (passwd), &ctx);
2210     md5_finish_ctx (&ctx, hash);
2211     dump_hash (a1buf, hash);
2212
2213     /* A2BUF = H(method ":" path) */
2214     md5_init_ctx (&ctx);
2215     md5_process_bytes (method, strlen (method), &ctx);
2216     md5_process_bytes (":", 1, &ctx);
2217     md5_process_bytes (path, strlen (path), &ctx);
2218     md5_finish_ctx (&ctx, hash);
2219     dump_hash (a2buf, hash);
2220
2221     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2222     md5_init_ctx (&ctx);
2223     md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2224     md5_process_bytes (":", 1, &ctx);
2225     md5_process_bytes (nonce, strlen (nonce), &ctx);
2226     md5_process_bytes (":", 1, &ctx);
2227     md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2228     md5_finish_ctx (&ctx, hash);
2229     dump_hash (response_digest, hash);
2230
2231     res = (char*) xmalloc (strlen (user)
2232                            + strlen (user)
2233                            + strlen (realm)
2234                            + strlen (nonce)
2235                            + strlen (path)
2236                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2237                            + (opaque ? strlen (opaque) : 0)
2238                            + 128);
2239     sprintf (res, "Authorization: Digest \
2240 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2241              user, realm, nonce, path, response_digest);
2242     if (opaque)
2243       {
2244         char *p = res + strlen (res);
2245         strcat (p, ", opaque=\"");
2246         strcat (p, opaque);
2247         strcat (p, "\"");
2248       }
2249     strcat (res, "\r\n");
2250   }
2251   return res;
2252 }
2253 #endif /* USE_DIGEST */
2254
2255
2256 #define BEGINS_WITH(line, string_constant)                              \
2257   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
2258    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
2259        || !line[sizeof (string_constant) - 1]))
2260
2261 static int
2262 known_authentication_scheme_p (const char *au)
2263 {
2264   return BEGINS_WITH (au, "Basic")
2265     || BEGINS_WITH (au, "Digest")
2266     || BEGINS_WITH (au, "NTLM");
2267 }
2268
2269 #undef BEGINS_WITH
2270
2271 /* Create the HTTP authorization request header.  When the
2272    `WWW-Authenticate' response header is seen, according to the
2273    authorization scheme specified in that header (`Basic' and `Digest'
2274    are supported by the current implementation), produce an
2275    appropriate HTTP authorization request header.  */
2276 static char *
2277 create_authorization_line (const char *au, const char *user,
2278                            const char *passwd, const char *method,
2279                            const char *path)
2280 {
2281   char *wwwauth = NULL;
2282
2283   if (!strncasecmp (au, "Basic", 5))
2284     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2285   if (!strncasecmp (au, "NTLM", 4))
2286     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2287 #ifdef USE_DIGEST
2288   else if (!strncasecmp (au, "Digest", 6))
2289     wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2290 #endif /* USE_DIGEST */
2291   return wwwauth;
2292 }