]> sjero.net Git - wget/blob - src/http.c
[svn] Gracefully handle opt.downloaded overflowing.
[wget] / src / http.c
1 /* HTTP support.
2    Copyright (C) 1995, 1996, 1997, 1998 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 \f
258 struct http_stat
259 {
260   long len;                     /* received length */
261   long contlen;                 /* expected length */
262   long restval;                 /* the restart value */
263   int res;                      /* the result of last read */
264   char *newloc;                 /* new location (redirection) */
265   char *remote_time;            /* remote time-stamp string */
266   char *error;                  /* textual HTTP error */
267   int statcode;                 /* status code */
268   long dltime;                  /* time of the download */
269 };
270
271 /* Free the elements of hstat X.  */
272 #define FREEHSTAT(x) do                                 \
273 {                                                       \
274   FREE_MAYBE ((x).newloc);                              \
275   FREE_MAYBE ((x).remote_time);                         \
276   FREE_MAYBE ((x).error);                               \
277   (x).newloc = (x).remote_time = (x).error = NULL;      \
278 } while (0)
279
280 static char *create_authorization_line PARAMS ((const char *, const char *,
281                                                 const char *, const char *,
282                                                 const char *));
283 static char *basic_authentication_encode PARAMS ((const char *, const char *,
284                                                   const char *));
285 static int known_authentication_scheme_p PARAMS ((const char *));
286
287 static time_t http_atotm PARAMS ((char *));
288
289 /* Retrieve a document through HTTP protocol.  It recognizes status
290    code, and correctly handles redirections.  It closes the network
291    socket.  If it receives an error from the functions below it, it
292    will print it if there is enough information to do so (almost
293    always), returning the error to the caller (i.e. http_loop).
294
295    Various HTTP parameters are stored to hs.  Although it parses the
296    response code correctly, it is not used in a sane way.  The caller
297    can do that, though.
298
299    If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
300    and u->proxy->url will be given to the proxy server (bad naming,
301    I'm afraid).  */
302 static uerr_t
303 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
304 {
305   char *request, *type, *command, *path;
306   char *user, *passwd;
307   char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
308   char *authenticate_h;
309   char *proxyauth;
310   char *all_headers;
311   char *host_port;
312   int host_port_len;
313   int sock, hcount, num_written, all_length, remport, statcode;
314   long contlen, contrange;
315   struct urlinfo *ou;
316   uerr_t err;
317   FILE *fp;
318   int auth_tried_already;
319   struct rbuf rbuf;
320
321   if (!(*dt & HEAD_ONLY))
322     /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
323        know the local filename so we can save to it. */
324     assert (u->local != NULL);
325
326   authenticate_h = 0;
327   auth_tried_already = 0;
328
329  again:
330   /* We need to come back here when the initial attempt to retrieve
331      without authorization header fails.  */
332
333   /* Initialize certain elements of struct http_stat.  */
334   hs->len = 0L;
335   hs->contlen = -1;
336   hs->res = -1;
337   hs->newloc = NULL;
338   hs->remote_time = NULL;
339   hs->error = NULL;
340
341   /* Which structure to use to retrieve the original URL data.  */
342   if (u->proxy)
343     ou = u->proxy;
344   else
345     ou = u;
346
347   /* First: establish the connection.  */
348   logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
349   err = make_connection (&sock, u->host, u->port);
350   switch (err)
351     {
352     case HOSTERR:
353       logputs (LOG_VERBOSE, "\n");
354       logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
355       return HOSTERR;
356       break;
357     case CONSOCKERR:
358       logputs (LOG_VERBOSE, "\n");
359       logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
360       return CONSOCKERR;
361       break;
362     case CONREFUSED:
363       logputs (LOG_VERBOSE, "\n");
364       logprintf (LOG_NOTQUIET,
365                  _("Connection to %s:%hu refused.\n"), u->host, u->port);
366       CLOSE (sock);
367       return CONREFUSED;
368     case CONERROR:
369       logputs (LOG_VERBOSE, "\n");
370       logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
371       CLOSE (sock);
372       return CONERROR;
373       break;
374     case NOCONERROR:
375       /* Everything is fine!  */
376       logputs (LOG_VERBOSE, _("connected!\n"));
377       break;
378     default:
379       abort ();
380       break;
381     } /* switch */
382
383   if (u->proxy)
384     path = u->proxy->url;
385   else
386     path = u->path;
387   
388   command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
389   referer = NULL;
390   if (ou->referer)
391     {
392       referer = (char *)alloca (9 + strlen (ou->referer) + 3);
393       sprintf (referer, "Referer: %s\r\n", ou->referer);
394     }
395   if (*dt & SEND_NOCACHE)
396     pragma_h = "Pragma: no-cache\r\n";
397   else
398     pragma_h = "";
399   if (hs->restval)
400     {
401       range = (char *)alloca (13 + numdigit (hs->restval) + 4);
402       /* #### Gag me!  Some servers (e.g. WebSitePro) have been known
403          to misinterpret the following `Range' format, and return the
404          document as multipart/x-byte-ranges MIME type!
405
406          #### TODO: Interpret MIME types, recognize bullshits similar
407          the one described above, and deal with them!  */
408       sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
409     }
410   else
411     range = NULL;
412   if (opt.useragent)
413     STRDUP_ALLOCA (useragent, opt.useragent);
414   else
415     {
416       useragent = (char *)alloca (10 + strlen (version_string));
417       sprintf (useragent, "Wget/%s", version_string);
418     }
419   /* Construct the authentication, if userid is present.  */
420   user = ou->user;
421   passwd = ou->passwd;
422   search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
423   user = user ? user : opt.http_user;
424   passwd = passwd ? passwd : opt.http_passwd;
425
426   wwwauth = NULL;
427   if (authenticate_h && user && passwd)
428     {
429       wwwauth = create_authorization_line (authenticate_h, user, passwd,
430                                            command, ou->path);
431     }
432
433   proxyauth = NULL;
434   if (u->proxy)
435     {
436       char *proxy_user, *proxy_passwd;
437       /* For normal username and password, URL components override
438          command-line/wgetrc parameters.  With proxy authentication,
439          it's the reverse, because proxy URLs are normally the
440          "permanent" ones, so command-line args should take
441          precedence.  */
442       if (opt.proxy_user && opt.proxy_passwd)
443         {
444           proxy_user = opt.proxy_user;
445           proxy_passwd = opt.proxy_passwd;
446         }
447       else
448         {
449           proxy_user = u->user;
450           proxy_passwd = u->passwd;
451         }
452       /* #### This is junky.  Can't the proxy request, say, `Digest'
453          authentication?  */
454       if (proxy_user && proxy_passwd)
455         proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
456                                                  "Proxy-Authorization");
457     }
458   remhost = ou->host;
459   remport = ou->port;
460
461   if (remport == 80)
462     {
463       host_port = NULL;
464       host_port_len = 0;
465     }
466   else
467     {
468       host_port = (char *)alloca (numdigit (remport) + 2);
469       host_port_len = sprintf (host_port, ":%d", remport);
470     }
471
472   /* Allocate the memory for the request.  */
473   request = (char *)alloca (strlen (command) + strlen (path)
474                             + strlen (useragent)
475                             + strlen (remhost) + host_port_len
476                             + strlen (HTTP_ACCEPT)
477                             + (referer ? strlen (referer) : 0)
478                             + (wwwauth ? strlen (wwwauth) : 0)
479                             + (proxyauth ? strlen (proxyauth) : 0)
480                             + (range ? strlen (range) : 0)
481                             + strlen (pragma_h)
482                             + (opt.user_header ? strlen (opt.user_header) : 0)
483                             + 64);
484   /* Construct the request.  */
485   sprintf (request, "\
486 %s %s HTTP/1.0\r\n\
487 User-Agent: %s\r\n\
488 Host: %s%s\r\n\
489 Accept: %s\r\n\
490 %s%s%s%s%s%s\r\n",
491            command, path, useragent, remhost,
492            host_port ? host_port : "",
493            HTTP_ACCEPT, referer ? referer : "",
494            wwwauth ? wwwauth : "", 
495            proxyauth ? proxyauth : "", 
496            range ? range : "",
497            pragma_h, 
498            opt.user_header ? opt.user_header : "");
499   DEBUGP (("---request begin---\n%s---request end---\n", request));
500    /* Free the temporary memory.  */
501   FREE_MAYBE (wwwauth);
502   FREE_MAYBE (proxyauth);
503
504   /* Send the request to server.  */
505   num_written = iwrite (sock, request, strlen (request));
506   if (num_written < 0)
507     {
508       logputs (LOG_VERBOSE, _("Failed writing HTTP request.\n"));
509       CLOSE (sock);
510       return WRITEFAILED;
511     }
512   logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
513              u->proxy ? "Proxy" : "HTTP");
514   contlen = contrange = -1;
515   type = NULL;
516   statcode = -1;
517   *dt &= ~RETROKF;
518
519   /* Before reading anything, initialize the rbuf.  */
520   rbuf_initialize (&rbuf, sock);
521
522   all_headers = NULL;
523   all_length = 0;
524   /* Header-fetching loop.  */
525   hcount = 0;
526   while (1)
527     {
528       char *hdr;
529       int status;
530
531       ++hcount;
532       /* Get the header.  */
533       status = header_get (&rbuf, &hdr,
534                            /* Disallow continuations for status line.  */
535                            (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
536
537       /* Check for errors.  */
538       if (status == HG_EOF && *hdr)
539         {
540           /* This used to be an unconditional error, but that was
541              somewhat controversial, because of a large number of
542              broken CGI's that happily "forget" to send the second EOL
543              before closing the connection of a HEAD request.
544
545              So, the deal is to check whether the header is empty
546              (*hdr is zero if it is); if yes, it means that the
547              previous header was fully retrieved, and that -- most
548              probably -- the request is complete.  "...be liberal in
549              what you accept."  Oh boy.  */
550           logputs (LOG_VERBOSE, "\n");
551           logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
552           free (hdr);
553           FREE_MAYBE (type);
554           FREE_MAYBE (hs->newloc);
555           FREE_MAYBE (all_headers);
556           CLOSE (sock);
557           return HEOF;
558         }
559       else if (status == HG_ERROR)
560         {
561           logputs (LOG_VERBOSE, "\n");
562           logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
563                      strerror (errno));
564           free (hdr);
565           FREE_MAYBE (type);
566           FREE_MAYBE (hs->newloc);
567           FREE_MAYBE (all_headers);
568           CLOSE (sock);
569           return HERR;
570         }
571
572       /* If the headers are to be saved to a file later, save them to
573          memory now.  */
574       if (opt.save_headers)
575         {
576           int lh = strlen (hdr);
577           all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
578           memcpy (all_headers + all_length, hdr, lh);
579           all_length += lh;
580           all_headers[all_length++] = '\n';
581           all_headers[all_length] = '\0';
582         }
583
584       /* Print the header if requested.  */
585       if (opt.server_response && hcount != 1)
586         logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
587
588       /* Check for status line.  */
589       if (hcount == 1)
590         {
591           const char *error;
592           /* Parse the first line of server response.  */
593           statcode = parse_http_status_line (hdr, &error);
594           hs->statcode = statcode;
595           /* Store the descriptive response.  */
596           if (statcode == -1) /* malformed response */
597             {
598               /* A common reason for "malformed response" error is the
599                  case when no data was actually received.  Handle this
600                  special case.  */
601               if (!*hdr)
602                 hs->error = xstrdup (_("No data received"));
603               else
604                 hs->error = xstrdup (_("Malformed status line"));
605               free (hdr);
606               break;
607             }
608           else if (!*error)
609             hs->error = xstrdup (_("(no description)"));
610           else
611             hs->error = xstrdup (error);
612
613           if ((statcode != -1)
614 #ifdef DEBUG
615               && !opt.debug
616 #endif
617               )
618             logprintf (LOG_VERBOSE, "%d %s", statcode, error);
619
620           goto done_header;
621         }
622
623       /* Exit on empty header.  */
624       if (!*hdr)
625         {
626           free (hdr);
627           break;
628         }
629
630       /* Try getting content-length.  */
631       if (contlen == -1 && !opt.ignore_length)
632         if (header_process (hdr, "Content-Length", header_extract_number,
633                             &contlen))
634           goto done_header;
635       /* Try getting content-type.  */
636       if (!type)
637         if (header_process (hdr, "Content-Type", http_process_type, &type))
638           goto done_header;
639       /* Try getting location.  */
640       if (!hs->newloc)
641         if (header_process (hdr, "Location", header_strdup, &hs->newloc))
642           goto done_header;
643       /* Try getting last-modified.  */
644       if (!hs->remote_time)
645         if (header_process (hdr, "Last-Modified", header_strdup,
646                             &hs->remote_time))
647           goto done_header;
648       /* Try getting www-authentication.  */
649       if (!authenticate_h)
650         if (header_process (hdr, "WWW-Authenticate", header_strdup,
651                             &authenticate_h))
652           goto done_header;
653       /* Check for accept-ranges header.  If it contains the word
654          `none', disable the ranges.  */
655       if (*dt & ACCEPTRANGES)
656         {
657           int nonep;
658           if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
659             {
660               if (nonep)
661                 *dt &= ~ACCEPTRANGES;
662               goto done_header;
663             }
664         }
665       /* Try getting content-range.  */
666       if (contrange == -1)
667         {
668           struct http_process_range_closure closure;
669           if (header_process (hdr, "Content-Range", http_process_range, &closure))
670             {
671               contrange = closure.first_byte_pos;
672               goto done_header;
673             }
674         }
675     done_header:
676       free (hdr);
677     }
678
679   logputs (LOG_VERBOSE, "\n");
680
681   if ((statcode == HTTP_STATUS_UNAUTHORIZED)
682       && authenticate_h)
683     {
684       /* Authorization is required.  */
685       FREE_MAYBE (type);
686       type = NULL;
687       FREEHSTAT (*hs);
688       CLOSE (sock);
689       if (auth_tried_already)
690         {
691           /* If we have tried it already, then there is not point
692              retrying it.  */
693           logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
694           free (authenticate_h);
695           return AUTHFAILED;
696         }
697       else if (!known_authentication_scheme_p (authenticate_h))
698         {
699           free (authenticate_h);
700           logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
701           return AUTHFAILED;
702         }
703       else
704         {
705           auth_tried_already = 1;
706           goto again;
707         }
708     }
709   /* We do not need this anymore.  */
710   if (authenticate_h)
711     {
712       free (authenticate_h);
713       authenticate_h = NULL;
714     }
715
716   /* 20x responses are counted among successful by default.  */
717   if (H_20X (statcode))
718     *dt |= RETROKF;
719
720   if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
721     *dt |= TEXTHTML;
722   else
723     /* We don't assume text/html by default.  */
724     *dt &= ~TEXTHTML;
725
726   if (opt.html_extension && (*dt & TEXTHTML))
727     /* -E / --html-extension / html_extension = on was specified, and this is a
728        text/html file.  If some case-insensitive variation on ".htm[l]" isn't
729        already the file's suffix, tack on ".html". */
730     {
731       char*  last_period_in_local_filename = strrchr(u->local, '.');
732
733       if (last_period_in_local_filename == NULL ||
734           !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
735             strcasecmp(last_period_in_local_filename, ".html") == EQ))
736         {
737           size_t  local_filename_len = strlen(u->local);
738           
739           u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
740           strcpy(u->local + local_filename_len, ".html");
741
742           *dt |= ADDED_HTML_EXTENSION;
743         }
744     }
745
746   if (contrange == -1)
747     hs->restval = 0;
748   else if (contrange != hs->restval ||
749            (H_PARTIAL (statcode) && contrange == -1))
750     {
751       /* This means the whole request was somehow misunderstood by the
752          server.  Bail out.  */
753       FREE_MAYBE (type);
754       FREE_MAYBE (hs->newloc);
755       FREE_MAYBE (all_headers);
756       CLOSE (sock);
757       return RANGEERR;
758     }
759
760   if (hs->restval)
761     {
762       if (contlen != -1)
763         contlen += contrange;
764       else
765         contrange = -1;        /* If conent-length was not sent,
766                                   content-range will be ignored.  */
767     }
768   hs->contlen = contlen;
769
770   /* Return if redirected.  */
771   if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
772     {
773       /* RFC2068 says that in case of the 300 (multiple choices)
774          response, the server can output a preferred URL through
775          `Location' header; otherwise, the request should be treated
776          like GET.  So, if the location is set, it will be a
777          redirection; otherwise, just proceed normally.  */
778       if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
779         *dt |= RETROKF;
780       else
781         {
782           logprintf (LOG_VERBOSE,
783                      _("Location: %s%s\n"),
784                      hs->newloc ? hs->newloc : _("unspecified"),
785                      hs->newloc ? _(" [following]") : "");
786           CLOSE (sock);
787           FREE_MAYBE (type);
788           FREE_MAYBE (all_headers);
789           return NEWLOCATION;
790         }
791     }
792   if (opt.verbose)
793     {
794       if ((*dt & RETROKF) && !opt.server_response)
795         {
796           /* No need to print this output if the body won't be
797              downloaded at all, or if the original server response is
798              printed.  */
799           logputs (LOG_VERBOSE, _("Length: "));
800           if (contlen != -1)
801             {
802               logputs (LOG_VERBOSE, legible (contlen));
803               if (contrange != -1)
804                 logprintf (LOG_VERBOSE, _(" (%s to go)"),
805                            legible (contlen - contrange));
806             }
807           else
808             logputs (LOG_VERBOSE,
809                      opt.ignore_length ? _("ignored") : _("unspecified"));
810           if (type)
811             logprintf (LOG_VERBOSE, " [%s]\n", type);
812           else
813             logputs (LOG_VERBOSE, "\n");
814         }
815     }
816   FREE_MAYBE (type);
817   type = NULL;                  /* We don't need it any more.  */
818
819   /* Return if we have no intention of further downloading.  */
820   if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
821     {
822       /* In case someone cares to look...  */
823       hs->len = 0L;
824       hs->res = 0;
825       FREE_MAYBE (type);
826       FREE_MAYBE (all_headers);
827       CLOSE (sock);
828       return RETRFINISHED;
829     }
830
831   /* Open the local file.  */
832   if (!opt.dfp)
833     {
834       mkalldirs (u->local);
835       if (opt.backups)
836         rotate_backups (u->local);
837       fp = fopen (u->local, hs->restval ? "ab" : "wb");
838       if (!fp)
839         {
840           logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
841           CLOSE (sock);
842           FREE_MAYBE (all_headers);
843           return FOPENERR;
844         }
845     }
846   else                          /* opt.dfp */
847     {
848       fp = opt.dfp;
849       if (!hs->restval)
850         {
851           /* This will silently fail for streams that don't correspond
852              to regular files, but that's OK.  */
853           rewind (fp);
854           clearerr (fp);
855         }
856     }
857
858   /* #### This confuses the code that checks for file size.  There
859      should be some overhead information.  */
860   if (opt.save_headers)
861     fwrite (all_headers, 1, all_length, fp);
862   reset_timer ();
863   /* Get the contents of the document.  */
864   hs->res = get_contents (sock, fp, &hs->len, hs->restval,
865                           (contlen != -1 ? contlen : 0),
866                           &rbuf);
867   hs->dltime = elapsed_time ();
868   {
869     /* Close or flush the file.  We have to be careful to check for
870        error here.  Checking the result of fwrite() is not enough --
871        errors could go unnoticed!  */
872     int flush_res;
873     if (!opt.dfp)
874       flush_res = fclose (fp);
875     else
876       flush_res = fflush (fp);
877     if (flush_res == EOF)
878       hs->res = -2;
879   }
880   FREE_MAYBE (all_headers);
881   CLOSE (sock);
882   if (hs->res == -2)
883     return FWRITEERR;
884   return RETRFINISHED;
885 }
886
887 /* The genuine HTTP loop!  This is the part where the retrieval is
888    retried, and retried, and retried, and...  */
889 uerr_t
890 http_loop (struct urlinfo *u, char **newloc, int *dt)
891 {
892   static int first_retrieval = 1;
893
894   int count;
895   int use_ts, got_head = 0;     /* time-stamping info */
896   char *filename_plus_orig_suffix;
897   char *local_filename = NULL;
898   char *tms, *suf, *locf, *tmrate;
899   uerr_t err;
900   time_t tml = -1, tmr = -1;    /* local and remote time-stamps */
901   long local_size = 0;          /* the size of the local file */
902   size_t filename_len;
903   struct http_stat hstat;       /* HTTP status */
904   struct stat st;
905
906   *newloc = NULL;
907
908   /* Warn on (likely bogus) wildcard usage in HTTP.  Don't use
909      has_wildcards_p because it would also warn on `?', and we know that
910      shows up in CGI paths a *lot*.  */
911   if (strchr (u->url, '*'))
912     logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
913
914   /* Determine the local filename.  */
915   if (!u->local)
916     u->local = url_filename (u->proxy ? u->proxy : u);
917
918   if (!opt.output_document)
919     locf = u->local;
920   else
921     locf = opt.output_document;
922
923   /* Yuck.  Multiple returns suck.  We need to remember to free() the space we
924      xmalloc() here before EACH return.  This is one reason it's better to set
925      flags that influence flow control and then return once at the end. */
926   filename_len = strlen(u->local);
927   filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
928
929   if (opt.noclobber && file_exists_p (u->local))
930     {
931       /* If opt.noclobber is turned on and file already exists, do not
932          retrieve the file */
933       logprintf (LOG_VERBOSE, _("\
934 File `%s' already there, will not retrieve.\n"), u->local);
935       /* If the file is there, we suppose it's retrieved OK.  */
936       *dt |= RETROKF;
937
938       /* #### Bogusness alert.  */
939       /* If its suffix is "html" or (yuck!) "htm", we suppose it's
940          text/html, a harmless lie.  */
941       if (((suf = suffix (u->local)) != NULL)
942           && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
943         *dt |= TEXTHTML;
944       free (suf);
945       free(filename_plus_orig_suffix);  /* must precede every return! */
946       /* Another harmless lie: */
947       return RETROK;
948     }
949
950   use_ts = 0;
951   if (opt.timestamping)
952     {
953       boolean  local_dot_orig_file_exists = FALSE;
954
955       if (opt.backup_converted)
956         /* If -K is specified, we'll act on the assumption that it was specified
957            last time these files were downloaded as well, and instead of just
958            comparing local file X against server file X, we'll compare local
959            file X.orig (if extant, else X) against server file X.  If -K
960            _wasn't_ specified last time, or the server contains files called
961            *.orig, -N will be back to not operating correctly with -k. */
962         {
963           /* Would a single s[n]printf() call be faster? */
964           strcpy(filename_plus_orig_suffix, u->local);
965           strcpy(filename_plus_orig_suffix + filename_len, ".orig");
966
967           /* Try to stat() the .orig file. */
968           if (stat(filename_plus_orig_suffix, &st) == 0)
969             {
970               local_dot_orig_file_exists = TRUE;
971               local_filename = filename_plus_orig_suffix;
972             }
973         }      
974
975       if (!local_dot_orig_file_exists)
976         /* Couldn't stat() <file>.orig, so try to stat() <file>. */
977         if (stat (u->local, &st) == 0)
978           local_filename = u->local;
979
980       if (local_filename != NULL)
981         /* There was a local file, so we'll check later to see if the version
982            the server has is the same version we already have, allowing us to
983            skip a download. */
984         {
985           use_ts = 1;
986           tml = st.st_mtime;
987           local_size = st.st_size;
988           got_head = 0;
989         }
990     }
991   /* Reset the counter.  */
992   count = 0;
993   *dt = 0 | ACCEPTRANGES;
994   /* THE loop */
995   do
996     {
997       /* Increment the pass counter.  */
998       ++count;
999       /* Wait before the retrieval (unless this is the very first
1000          retrieval).
1001          Check if we are retrying or not, wait accordingly - HEH */
1002       if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
1003         {
1004           if (count)
1005             {
1006               if (count<opt.waitretry)
1007                 sleep(count);
1008               else
1009                 sleep(opt.waitretry);
1010             }
1011           else
1012             sleep (opt.wait);
1013         }
1014       if (first_retrieval)
1015         first_retrieval = 0;
1016       /* Get the current time string.  */
1017       tms = time_str (NULL);
1018       /* Print fetch message, if opt.verbose.  */
1019       if (opt.verbose)
1020         {
1021           char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1022           char tmp[15];
1023           strcpy (tmp, "        ");
1024           if (count > 1)
1025             sprintf (tmp, _("(try:%2d)"), count);
1026           logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => `%s'\n",
1027                      tms, hurl, tmp, locf);
1028 #ifdef WINDOWS
1029           ws_changetitle (hurl, 1);
1030 #endif
1031           free (hurl);
1032         }
1033
1034       /* Default document type is empty.  However, if spider mode is
1035          on or time-stamping is employed, HEAD_ONLY commands is
1036          encoded within *dt.  */
1037       if (opt.spider || (use_ts && !got_head))
1038         *dt |= HEAD_ONLY;
1039       else
1040         *dt &= ~HEAD_ONLY;
1041       /* Assume no restarting.  */
1042       hstat.restval = 0L;
1043       /* Decide whether or not to restart.  */
1044       if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1045           && file_exists_p (u->local))
1046         if (stat (u->local, &st) == 0)
1047           hstat.restval = st.st_size;
1048       /* Decide whether to send the no-cache directive.  */
1049       if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1050         *dt |= SEND_NOCACHE;
1051       else
1052         *dt &= ~SEND_NOCACHE;
1053
1054       /* Try fetching the document, or at least its head.  :-) */
1055       err = gethttp (u, &hstat, dt);
1056
1057       /* It's unfortunate that wget determines the local filename before finding
1058          out the Content-Type of the file.  Barring a major restructuring of the
1059          code, we need to re-set locf here, since gethttp() may have xrealloc()d
1060          u->local to tack on ".html". */
1061       if (!opt.output_document)
1062         locf = u->local;
1063       else
1064         locf = opt.output_document;
1065
1066       /* Time?  */
1067       tms = time_str (NULL);
1068       /* Get the new location (with or without the redirection).  */
1069       if (hstat.newloc)
1070         *newloc = xstrdup (hstat.newloc);
1071       switch (err)
1072         {
1073         case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1074         case CONERROR: case READERR: case WRITEFAILED:
1075         case RANGEERR:
1076           /* Non-fatal errors continue executing the loop, which will
1077              bring them to "while" statement at the end, to judge
1078              whether the number of tries was exceeded.  */
1079           FREEHSTAT (hstat);
1080           printwhat (count, opt.ntry);
1081           continue;
1082           break;
1083         case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1084           /* Fatal errors just return from the function.  */
1085           FREEHSTAT (hstat);
1086           free(filename_plus_orig_suffix);  /* must precede every return! */
1087           return err;
1088           break;
1089         case FWRITEERR: case FOPENERR:
1090           /* Another fatal error.  */
1091           logputs (LOG_VERBOSE, "\n");
1092           logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1093                      u->local, strerror (errno));
1094           FREEHSTAT (hstat);
1095           free(filename_plus_orig_suffix);  /* must precede every return! */
1096           return err;
1097           break;
1098         case NEWLOCATION:
1099           /* Return the new location to the caller.  */
1100           if (!hstat.newloc)
1101             {
1102               logprintf (LOG_NOTQUIET,
1103                          _("ERROR: Redirection (%d) without location.\n"),
1104                          hstat.statcode);
1105               free(filename_plus_orig_suffix);  /* must precede every return! */
1106               return WRONGCODE;
1107             }
1108           FREEHSTAT (hstat);
1109           free(filename_plus_orig_suffix);  /* must precede every return! */
1110           return NEWLOCATION;
1111           break;
1112         case RETRFINISHED:
1113           /* Deal with you later.  */
1114           break;
1115         default:
1116           /* All possibilities should have been exhausted.  */
1117           abort ();
1118         }
1119       if (!(*dt & RETROKF))
1120         {
1121           if (!opt.verbose)
1122             {
1123               /* #### Ugly ugly ugly! */
1124               char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1125               logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1126               free (hurl);
1127             }
1128           logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1129                      tms, hstat.statcode, hstat.error);
1130           logputs (LOG_VERBOSE, "\n");
1131           FREEHSTAT (hstat);
1132           free(filename_plus_orig_suffix);  /* must precede every return! */
1133           return WRONGCODE;
1134         }
1135
1136       /* Did we get the time-stamp?  */
1137       if (!got_head)
1138         {
1139           if (opt.timestamping && !hstat.remote_time)
1140             {
1141               logputs (LOG_NOTQUIET, _("\
1142 Last-modified header missing -- time-stamps turned off.\n"));
1143             }
1144           else if (hstat.remote_time)
1145             {
1146               /* Convert the date-string into struct tm.  */
1147               tmr = http_atotm (hstat.remote_time);
1148               if (tmr == (time_t) (-1))
1149                 logputs (LOG_VERBOSE, _("\
1150 Last-modified header invalid -- time-stamp ignored.\n"));
1151             }
1152         }
1153
1154       /* The time-stamping section.  */
1155       if (use_ts)
1156         {
1157           got_head = 1;
1158           *dt &= ~HEAD_ONLY;
1159           use_ts = 0;           /* no more time-stamping */
1160           count = 0;            /* the retrieve count for HEAD is
1161                                    reset */
1162           if (hstat.remote_time && tmr != (time_t) (-1))
1163             {
1164               /* Now time-stamping can be used validly.  Time-stamping
1165                  means that if the sizes of the local and remote file
1166                  match, and local file is newer than the remote file,
1167                  it will not be retrieved.  Otherwise, the normal
1168                  download procedure is resumed.  */
1169               if (tml >= tmr &&
1170                   (hstat.contlen == -1 || local_size == hstat.contlen))
1171                 {
1172                   logprintf (LOG_VERBOSE, _("\
1173 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1174                              local_filename);
1175                   FREEHSTAT (hstat);
1176                   free(filename_plus_orig_suffix);/*must precede every return!*/
1177                   return RETROK;
1178                 }
1179               else if (tml >= tmr)
1180                 logprintf (LOG_VERBOSE, _("\
1181 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1182               else
1183                 logputs (LOG_VERBOSE,
1184                          _("Remote file is newer, retrieving.\n"));
1185             }
1186           FREEHSTAT (hstat);
1187           continue;
1188         }
1189       if (!opt.dfp
1190           && (tmr != (time_t) (-1))
1191           && !opt.spider
1192           && ((hstat.len == hstat.contlen) ||
1193               ((hstat.res == 0) &&
1194                ((hstat.contlen == -1) ||
1195                 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1196         {
1197           touch (u->local, tmr);
1198         }
1199       /* End of time-stamping section.  */
1200
1201       if (opt.spider)
1202         {
1203           logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1204           free(filename_plus_orig_suffix);  /* must precede every return! */
1205           return RETROK;
1206         }
1207
1208       /* It is now safe to free the remainder of hstat, since the
1209          strings within it will no longer be used.  */
1210       FREEHSTAT (hstat);
1211
1212       tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1213
1214       if (hstat.len == hstat.contlen)
1215         {
1216           if (*dt & RETROKF)
1217             {
1218               logprintf (LOG_VERBOSE,
1219                          _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1220                          tms, tmrate, locf, hstat.len, hstat.contlen);
1221               logprintf (LOG_NONVERBOSE,
1222                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1223                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1224             }
1225           ++opt.numurls;
1226           downloaded_increase (hstat.len);
1227
1228           /* Remember that we downloaded the file for later ".orig" code. */
1229           if (*dt & ADDED_HTML_EXTENSION)
1230             downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1231           else
1232             downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1233
1234           free(filename_plus_orig_suffix);  /* must precede every return! */
1235           return RETROK;
1236         }
1237       else if (hstat.res == 0) /* No read error */
1238         {
1239           if (hstat.contlen == -1)  /* We don't know how much we were supposed
1240                                        to get, so assume we succeeded. */ 
1241             {
1242               if (*dt & RETROKF)
1243                 {
1244                   logprintf (LOG_VERBOSE,
1245                              _("%s (%s) - `%s' saved [%ld]\n\n"),
1246                              tms, tmrate, locf, hstat.len);
1247                   logprintf (LOG_NONVERBOSE,
1248                              "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1249                              tms, u->url, hstat.len, locf, count);
1250                 }
1251               ++opt.numurls;
1252               downloaded_increase (hstat.len);
1253
1254               /* Remember that we downloaded the file for later ".orig" code. */
1255               if (*dt & ADDED_HTML_EXTENSION)
1256                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1257               else
1258                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1259               
1260               free(filename_plus_orig_suffix);  /* must precede every return! */
1261               return RETROK;
1262             }
1263           else if (hstat.len < hstat.contlen) /* meaning we lost the
1264                                                  connection too soon */
1265             {
1266               logprintf (LOG_VERBOSE,
1267                          _("%s (%s) - Connection closed at byte %ld. "),
1268                          tms, tmrate, hstat.len);
1269               printwhat (count, opt.ntry);
1270               continue;
1271             }
1272           else if (!opt.kill_longer) /* meaning we got more than expected */
1273             {
1274               logprintf (LOG_VERBOSE,
1275                          _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1276                          tms, tmrate, locf, hstat.len, hstat.contlen);
1277               logprintf (LOG_NONVERBOSE,
1278                          "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1279                          tms, u->url, hstat.len, hstat.contlen, locf, count);
1280               ++opt.numurls;
1281               downloaded_increase (hstat.len);
1282
1283               /* Remember that we downloaded the file for later ".orig" code. */
1284               if (*dt & ADDED_HTML_EXTENSION)
1285                 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1286               else
1287                 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1288               
1289               free(filename_plus_orig_suffix);  /* must precede every return! */
1290               return RETROK;
1291             }
1292           else                  /* the same, but not accepted */
1293             {
1294               logprintf (LOG_VERBOSE,
1295                          _("%s (%s) - Connection closed at byte %ld/%ld. "),
1296                          tms, tmrate, hstat.len, hstat.contlen);
1297               printwhat (count, opt.ntry);
1298               continue;
1299             }
1300         }
1301       else                      /* now hstat.res can only be -1 */
1302         {
1303           if (hstat.contlen == -1)
1304             {
1305               logprintf (LOG_VERBOSE,
1306                          _("%s (%s) - Read error at byte %ld (%s)."),
1307                          tms, tmrate, hstat.len, strerror (errno));
1308               printwhat (count, opt.ntry);
1309               continue;
1310             }
1311           else                  /* hstat.res == -1 and contlen is given */
1312             {
1313               logprintf (LOG_VERBOSE,
1314                          _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1315                          tms, tmrate, hstat.len, hstat.contlen,
1316                          strerror (errno));
1317               printwhat (count, opt.ntry);
1318               continue;
1319             }
1320         }
1321       /* not reached */
1322       break;
1323     }
1324   while (!opt.ntry || (count < opt.ntry));
1325   free(filename_plus_orig_suffix);  /* must precede every return! */
1326   return TRYLIMEXC;
1327 }
1328 \f
1329 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1330    than local timezone (mktime assumes the latter).
1331
1332    Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1333    Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.  */
1334 static time_t
1335 mktime_from_utc (struct tm *t)
1336 {
1337   time_t tl, tb;
1338
1339   tl = mktime (t);
1340   if (tl == -1)
1341     return -1;
1342   tb = mktime (gmtime (&tl));
1343   return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1344 }
1345
1346 /* Check whether the result of strptime() indicates success.
1347    strptime() returns the pointer to how far it got to in the string.
1348    The processing has been successful if the string is at `GMT' or
1349    `+X', or at the end of the string.
1350
1351    In extended regexp parlance, the function returns 1 if P matches
1352    "^ *(GMT|[+-][0-9]|$)", 0 otherwise.  P being NULL (a valid result of
1353    strptime()) is considered a failure and 0 is returned.  */
1354 static int
1355 check_end (char *p)
1356 {
1357   if (!p)
1358     return 0;
1359   while (ISSPACE (*p))
1360     ++p;
1361   if (!*p
1362       || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1363       || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1364     return 1;
1365   else
1366     return 0;
1367 }
1368
1369 /* Convert TIME_STRING time to time_t.  TIME_STRING can be in any of
1370    the three formats RFC2068 allows the HTTP servers to emit --
1371    RFC1123-date, RFC850-date or asctime-date.  Timezones are ignored,
1372    and should be GMT.
1373
1374    We use strptime() to recognize various dates, which makes it a
1375    little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1376    allows shortened dates and months, one-digit days, etc.).  It also
1377    allows more than one space anywhere where the specs require one SP.
1378    The routine should probably be even more forgiving (as recommended
1379    by RFC2068), but I do not have the time to write one.
1380
1381    Return the computed time_t representation, or -1 if all the
1382    schemes fail.
1383
1384    Needless to say, what we *really* need here is something like
1385    Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1386    and does not use strptime().  atotm() is to be found in the sources
1387    of `phttpd', a little-known HTTP server written by Peter Erikson.  */
1388 static time_t
1389 http_atotm (char *time_string)
1390 {
1391   struct tm t;
1392
1393   /* Roger Beeman says: "This function dynamically allocates struct tm
1394      t, but does no initialization.  The only field that actually
1395      needs initialization is tm_isdst, since the others will be set by
1396      strptime.  Since strptime does not set tm_isdst, it will return
1397      the data structure with whatever data was in tm_isdst to begin
1398      with.  For those of us in timezones where DST can occur, there
1399      can be a one hour shift depending on the previous contents of the
1400      data area where the data structure is allocated."  */
1401   t.tm_isdst = -1;
1402
1403   /* Note that under foreign locales Solaris strptime() fails to
1404      recognize English dates, which renders this function useless.  I
1405      assume that other non-GNU strptime's are plagued by the same
1406      disease.  We solve this by setting only LC_MESSAGES in
1407      i18n_initialize(), instead of LC_ALL.
1408
1409      Another solution could be to temporarily set locale to C, invoke
1410      strptime(), and restore it back.  This is slow and dirty,
1411      however, and locale support other than LC_MESSAGES can mess other
1412      things, so I rather chose to stick with just setting LC_MESSAGES.
1413
1414      Also note that none of this is necessary under GNU strptime(),
1415      because it recognizes both international and local dates.  */
1416
1417   /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1418      it to eat all white space up to (and including) a newline, and
1419      the function fails if there is no newline (!).
1420
1421      Let's hope all strptime() implementations use ` ' to skip *all*
1422      whitespace instead of just one (it works that way on all the
1423      systems I've tested it on).  */
1424
1425   /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1426   if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1427     return mktime_from_utc (&t);
1428   /* RFC850:  Thu, 29-Jan-98 22:12:57 */
1429   if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1430     return mktime_from_utc (&t);
1431   /* asctime: Thu Jan 29 22:12:57 1998 */
1432   if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1433     return mktime_from_utc (&t);
1434   /* Failure.  */
1435   return -1;
1436 }
1437 \f
1438 /* Authorization support: We support two authorization schemes:
1439
1440    * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1441
1442    * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1443    consisting of answering to the server's challenge with the proper
1444    MD5 digests.  */
1445
1446 /* How many bytes it will take to store LEN bytes in base64.  */
1447 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1448
1449 /* Encode the string S of length LENGTH to base64 format and place it
1450    to STORE.  STORE will be 0-terminated, and must point to a writable
1451    buffer of at least 1+BASE64_LENGTH(length) bytes.  */
1452 static void
1453 base64_encode (const char *s, char *store, int length)
1454 {
1455   /* Conversion table.  */
1456   static char tbl[64] = {
1457     'A','B','C','D','E','F','G','H',
1458     'I','J','K','L','M','N','O','P',
1459     'Q','R','S','T','U','V','W','X',
1460     'Y','Z','a','b','c','d','e','f',
1461     'g','h','i','j','k','l','m','n',
1462     'o','p','q','r','s','t','u','v',
1463     'w','x','y','z','0','1','2','3',
1464     '4','5','6','7','8','9','+','/'
1465   };
1466   int i;
1467   unsigned char *p = (unsigned char *)store;
1468
1469   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
1470   for (i = 0; i < length; i += 3)
1471     {
1472       *p++ = tbl[s[0] >> 2];
1473       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1474       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1475       *p++ = tbl[s[2] & 0x3f];
1476       s += 3;
1477     }
1478   /* Pad the result if necessary...  */
1479   if (i == length + 1)
1480     *(p - 1) = '=';
1481   else if (i == length + 2)
1482     *(p - 1) = *(p - 2) = '=';
1483   /* ...and zero-terminate it.  */
1484   *p = '\0';
1485 }
1486
1487 /* Create the authentication header contents for the `Basic' scheme.
1488    This is done by encoding the string `USER:PASS' in base64 and
1489    prepending `HEADER: Basic ' to it.  */
1490 static char *
1491 basic_authentication_encode (const char *user, const char *passwd,
1492                              const char *header)
1493 {
1494   char *t1, *t2, *res;
1495   int len1 = strlen (user) + 1 + strlen (passwd);
1496   int len2 = BASE64_LENGTH (len1);
1497
1498   t1 = (char *)alloca (len1 + 1);
1499   sprintf (t1, "%s:%s", user, passwd);
1500   t2 = (char *)alloca (1 + len2);
1501   base64_encode (t1, t2, len1);
1502   res = (char *)malloc (len2 + 11 + strlen (header));
1503   sprintf (res, "%s: Basic %s\r\n", header, t2);
1504
1505   return res;
1506 }
1507
1508 #ifdef USE_DIGEST
1509 /* Parse HTTP `WWW-Authenticate:' header.  AU points to the beginning
1510    of a field in such a header.  If the field is the one specified by
1511    ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1512    digest authorization code), extract its value in the (char*)
1513    variable pointed by RET.  Returns negative on a malformed header,
1514    or number of bytes that have been parsed by this call.  */
1515 static int
1516 extract_header_attr (const char *au, const char *attr_name, char **ret)
1517 {
1518   const char *cp, *ep;
1519
1520   ep = cp = au;
1521
1522   if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1523     {
1524       cp += strlen (attr_name);
1525       if (!*cp)
1526         return -1;
1527       cp += skip_lws (cp);
1528       if (*cp != '=')
1529         return -1;
1530       if (!*++cp)
1531         return -1;
1532       cp += skip_lws (cp);
1533       if (*cp != '\"')
1534         return -1;
1535       if (!*++cp)
1536         return -1;
1537       for (ep = cp; *ep && *ep != '\"'; ep++)
1538         ;
1539       if (!*ep)
1540         return -1;
1541       FREE_MAYBE (*ret);
1542       *ret = strdupdelim (cp, ep);
1543       return ep - au + 1;
1544     }
1545   else
1546     return 0;
1547 }
1548
1549 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1550    from url.h.  See RFC 2069 2.1.2 for the syntax of response-digest.  */
1551 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1552
1553 /* Dump the hexadecimal representation of HASH to BUF.  HASH should be
1554    an array of 16 bytes containing the hash keys, and BUF should be a
1555    buffer of 33 writable characters (32 for hex digits plus one for
1556    zero termination).  */
1557 static void
1558 dump_hash (unsigned char *buf, const unsigned char *hash)
1559 {
1560   int i;
1561
1562   for (i = 0; i < MD5_HASHLEN; i++, hash++)
1563     {
1564       *buf++ = HEXD2asc (*hash >> 4);
1565       *buf++ = HEXD2asc (*hash & 0xf);
1566     }
1567   *buf = '\0';
1568 }
1569
1570 /* Take the line apart to find the challenge, and compose a digest
1571    authorization header.  See RFC2069 section 2.1.2.  */
1572 char *
1573 digest_authentication_encode (const char *au, const char *user,
1574                               const char *passwd, const char *method,
1575                               const char *path)
1576 {
1577   static char *realm, *opaque, *nonce;
1578   static struct {
1579     const char *name;
1580     char **variable;
1581   } options[] = {
1582     { "realm", &realm },
1583     { "opaque", &opaque },
1584     { "nonce", &nonce }
1585   };
1586   char *res;
1587
1588   realm = opaque = nonce = NULL;
1589
1590   au += 6;                      /* skip over `Digest' */
1591   while (*au)
1592     {
1593       int i;
1594
1595       au += skip_lws (au);
1596       for (i = 0; i < ARRAY_SIZE (options); i++)
1597         {
1598           int skip = extract_header_attr (au, options[i].name,
1599                                           options[i].variable);
1600           if (skip < 0)
1601             {
1602               FREE_MAYBE (realm);
1603               FREE_MAYBE (opaque);
1604               FREE_MAYBE (nonce);
1605               return NULL;
1606             }
1607           else if (skip)
1608             {
1609               au += skip;
1610               break;
1611             }
1612         }
1613       if (i == ARRAY_SIZE (options))
1614         {
1615           while (*au && *au != '=')
1616             au++;
1617           if (*au && *++au)
1618             {
1619               au += skip_lws (au);
1620               if (*au == '\"')
1621                 {
1622                   au++;
1623                   while (*au && *au != '\"')
1624                     au++;
1625                   if (*au)
1626                     au++;
1627                 }
1628             }
1629         }
1630       while (*au && *au != ',')
1631         au++;
1632       if (*au)
1633         au++;
1634     }
1635   if (!realm || !nonce || !user || !passwd || !path || !method)
1636     {
1637       FREE_MAYBE (realm);
1638       FREE_MAYBE (opaque);
1639       FREE_MAYBE (nonce);
1640       return NULL;
1641     }
1642
1643   /* Calculate the digest value.  */
1644   {
1645     struct md5_ctx ctx;
1646     unsigned char hash[MD5_HASHLEN];
1647     unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
1648     unsigned char response_digest[MD5_HASHLEN * 2 + 1];
1649
1650     /* A1BUF = H(user ":" realm ":" password) */
1651     md5_init_ctx (&ctx);
1652     md5_process_bytes (user, strlen (user), &ctx);
1653     md5_process_bytes (":", 1, &ctx);
1654     md5_process_bytes (realm, strlen (realm), &ctx);
1655     md5_process_bytes (":", 1, &ctx);
1656     md5_process_bytes (passwd, strlen (passwd), &ctx);
1657     md5_finish_ctx (&ctx, hash);
1658     dump_hash (a1buf, hash);
1659
1660     /* A2BUF = H(method ":" path) */
1661     md5_init_ctx (&ctx);
1662     md5_process_bytes (method, strlen (method), &ctx);
1663     md5_process_bytes (":", 1, &ctx);
1664     md5_process_bytes (path, strlen (path), &ctx);
1665     md5_finish_ctx (&ctx, hash);
1666     dump_hash (a2buf, hash);
1667
1668     /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
1669     md5_init_ctx (&ctx);
1670     md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
1671     md5_process_bytes (":", 1, &ctx);
1672     md5_process_bytes (nonce, strlen (nonce), &ctx);
1673     md5_process_bytes (":", 1, &ctx);
1674     md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
1675     md5_finish_ctx (&ctx, hash);
1676     dump_hash (response_digest, hash);
1677
1678     res = (char*) xmalloc (strlen (user)
1679                            + strlen (user)
1680                            + strlen (realm)
1681                            + strlen (nonce)
1682                            + strlen (path)
1683                            + 2 * MD5_HASHLEN /*strlen (response_digest)*/
1684                            + (opaque ? strlen (opaque) : 0)
1685                            + 128);
1686     sprintf (res, "Authorization: Digest \
1687 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1688              user, realm, nonce, path, response_digest);
1689     if (opaque)
1690       {
1691         char *p = res + strlen (res);
1692         strcat (p, ", opaque=\"");
1693         strcat (p, opaque);
1694         strcat (p, "\"");
1695       }
1696     strcat (res, "\r\n");
1697   }
1698   return res;
1699 }
1700 #endif /* USE_DIGEST */
1701
1702
1703 #define HACK_O_MATIC(line, string_constant)                             \
1704   (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)   \
1705    && (ISSPACE (line[sizeof (string_constant) - 1])                     \
1706        || !line[sizeof (string_constant) - 1]))
1707
1708 static int
1709 known_authentication_scheme_p (const char *au)
1710 {
1711   return HACK_O_MATIC (au, "Basic") || HACK_O_MATIC (au, "Digest");
1712 }
1713
1714 #undef HACK_O_MATIC
1715
1716 /* Create the HTTP authorization request header.  When the
1717    `WWW-Authenticate' response header is seen, according to the
1718    authorization scheme specified in that header (`Basic' and `Digest'
1719    are supported by the current implementation), produce an
1720    appropriate HTTP authorization request header.  */
1721 static char *
1722 create_authorization_line (const char *au, const char *user,
1723                            const char *passwd, const char *method,
1724                            const char *path)
1725 {
1726   char *wwwauth = NULL;
1727
1728   if (!strncasecmp (au, "Basic", 5))
1729     wwwauth = basic_authentication_encode (user, passwd, "Authorization");
1730 #ifdef USE_DIGEST
1731   else if (!strncasecmp (au, "Digest", 6))
1732     wwwauth = digest_authentication_encode (au, user, passwd, method, path);
1733 #endif /* USE_DIGEST */
1734   return wwwauth;
1735 }