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