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