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