2 Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
4 This file is part of Wget.
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.
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.
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. */
24 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
65 extern char *version_string;
75 #define TEXTHTML_S "text/html"
76 #define HTTP_ACCEPT "*/*"
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))
84 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
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
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
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
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
111 /* Parse the HTTP status line, which is of format:
113 HTTP-Version SP Status-Code SP Reason-Phrase
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. */
118 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
120 /* (the variables must not be named `major' and `minor', because
121 that breaks compilation with SunOS4 cc.) */
122 int mjr, mnr, statcode;
125 *reason_phrase_ptr = NULL;
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)
133 /* Calculate major HTTP version. */
135 for (mjr = 0; ISDIGIT (*line); line++)
136 mjr = 10 * mjr + (*line - '0');
137 if (*line != '.' || p == line)
141 /* Calculate minor HTTP version. */
143 for (mnr = 0; ISDIGIT (*line); line++)
144 mnr = 10 * mnr + (*line - '0');
145 if (*line != ' ' || p == line)
147 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
148 minor version can be safely ignored. */
153 /* Calculate status code. */
154 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
156 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
158 /* Set up the reason phrase pointer. */
160 /* RFC2068 requires SPC here, but we allow the string to finish
161 here, in case no reason-phrase is present. */
165 *reason_phrase_ptr = line;
170 *reason_phrase_ptr = line + 1;
175 /* Functions to be used as arguments to header_process(): */
177 struct http_process_range_closure {
183 /* Parse the `Content-Range' header and extract the information it
184 contains. Returns 1 if successful, -1 otherwise. */
186 http_process_range (const char *hdr, void *arg)
188 struct http_process_range_closure *closure
189 = (struct http_process_range_closure *)arg;
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))
199 hdr += skip_lws (hdr);
205 for (num = 0; ISDIGIT (*hdr); hdr++)
206 num = 10 * num + (*hdr - '0');
207 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
209 closure->first_byte_pos = num;
211 for (num = 0; ISDIGIT (*hdr); hdr++)
212 num = 10 * num + (*hdr - '0');
213 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
215 closure->last_byte_pos = num;
217 for (num = 0; ISDIGIT (*hdr); hdr++)
218 num = 10 * num + (*hdr - '0');
219 closure->entity_length = num;
223 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
224 Used for `Accept-Ranges'. */
226 http_process_none (const char *hdr, void *arg)
228 int *where = (int *)arg;
230 if (strstr (hdr, "none"))
237 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
239 http_process_type (const char *hdr, void *arg)
241 char **result = (char **)arg;
244 p = strrchr (hdr, ';');
248 *result = (char *)xmalloc (len + 1);
249 memcpy (*result, hdr, len);
250 (*result)[len] = '\0';
253 *result = xstrdup (hdr);
257 /* Check whether the `Connection' header is set to "keep-alive". */
259 http_process_connection (const char *hdr, void *arg)
261 int *flag = (int *)arg;
262 if (!strcasecmp (hdr, "Keep-Alive"))
267 /* Persistent connections (pc). Currently, we cache the most recently
268 used connection as persistent, provided that the HTTP server agrees
269 to make it such. The persistence data is stored in the variables
270 below. Ideally, it would be in a structure, and it should be
271 possible to cache an arbitrary fixed number of these connections.
273 I think the code is quite easy to extend in that direction. */
275 /* Whether the persistent connection is active. */
276 static int pc_active_p;
278 /* Host and port of the last persistent connection. */
279 static unsigned char pc_last_host[4];
280 static unsigned short pc_last_port;
282 /* File descriptor of the last persistent connection. */
283 static int pc_last_fd;
285 /* Mark the persistent connection as invalid. This is used by the
286 CLOSE_* macros after they forcefully close a registered persistent
290 invalidate_persistent (void)
293 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
296 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
297 persistent. This will enable someone to use the same connection
298 later. In the context of HTTP, this must be called only AFTER the
299 response has been received and the server has promised that the
300 connection will remain alive.
302 If a previous connection was persistent, it is closed. */
305 register_persistent (const char *host, unsigned short port, int fd)
311 if (pc_last_fd == fd)
313 /* The connection FD is already registered. Nothing to
319 /* The old persistent connection is still active; let's
320 close it first. This situation arises whenever a
321 persistent connection exists, but we then connect to a
322 different host, and try to register a persistent
323 connection to that one. */
325 invalidate_persistent ();
329 /* This store_hostaddress may not fail, because it has the results
331 success = store_hostaddress (pc_last_host, host);
336 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
339 /* Return non-zero if a persistent connection is available for
340 connecting to HOST:PORT. */
343 persistent_available_p (const char *host, unsigned short port)
345 unsigned char this_host[4];
348 if (port != pc_last_port)
350 if (!store_hostaddress (this_host, host))
352 if (memcmp (pc_last_host, this_host, 4))
354 if (!test_socket_open (pc_last_fd))
357 invalidate_persistent ();
363 /* The idea behind these two CLOSE macros is to distinguish between
364 two cases: one when the job we've been doing is finished, and we
365 want to close the connection and leave, and two when something is
366 seriously wrong and we're closing the connection as part of
369 In case of keep_alive, CLOSE_FINISH should leave the connection
370 open, while CLOSE_INVALIDATE should still close it.
372 Note that the semantics of the flag `keep_alive' is "this
373 connection *will* be reused (the server has promised not to close
374 the connection once we're done)", while the semantics of
375 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
376 active, registered connection". */
378 #define CLOSE_FINISH(fd) do { \
382 if (pc_active_p && (fd) == pc_last_fd) \
383 invalidate_persistent (); \
387 #define CLOSE_INVALIDATE(fd) do { \
389 if (pc_active_p && (fd) == pc_last_fd) \
390 invalidate_persistent (); \
396 long len; /* received length */
397 long contlen; /* expected length */
398 long restval; /* the restart value */
399 int res; /* the result of last read */
400 char *newloc; /* new location (redirection) */
401 char *remote_time; /* remote time-stamp string */
402 char *error; /* textual HTTP error */
403 int statcode; /* status code */
404 long dltime; /* time of the download */
407 /* Free the elements of hstat X. */
408 #define FREEHSTAT(x) do \
410 FREE_MAYBE ((x).newloc); \
411 FREE_MAYBE ((x).remote_time); \
412 FREE_MAYBE ((x).error); \
413 (x).newloc = (x).remote_time = (x).error = NULL; \
416 static char *create_authorization_line PARAMS ((const char *, const char *,
417 const char *, const char *,
419 static char *basic_authentication_encode PARAMS ((const char *, const char *,
421 static int known_authentication_scheme_p PARAMS ((const char *));
423 static time_t http_atotm PARAMS ((char *));
425 /* Retrieve a document through HTTP protocol. It recognizes status
426 code, and correctly handles redirections. It closes the network
427 socket. If it receives an error from the functions below it, it
428 will print it if there is enough information to do so (almost
429 always), returning the error to the caller (i.e. http_loop).
431 Various HTTP parameters are stored to hs. Although it parses the
432 response code correctly, it is not used in a sane way. The caller
435 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
436 and u->proxy->url will be given to the proxy server (bad naming,
439 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
441 char *request, *type, *command, *path;
443 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
444 char *authenticate_h;
448 char *request_keep_alive;
449 int sock, hcount, num_written, all_length, remport, statcode;
450 long contlen, contrange;
454 int auth_tried_already;
457 /* Whether this connection will be kept alive after the HTTP request
461 /* Flags that detect the two ways of specifying HTTP keep-alive
463 int http_keep_alive_1, http_keep_alive_2;
465 /* Whether keep-alive should be inhibited. */
466 int inhibit_keep_alive;
468 if (!(*dt & HEAD_ONLY))
469 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
470 know the local filename so we can save to it. */
471 assert (u->local != NULL);
474 auth_tried_already = 0;
476 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
479 /* We need to come back here when the initial attempt to retrieve
480 without authorization header fails. */
482 http_keep_alive_1 = http_keep_alive_2 = 0;
484 /* Initialize certain elements of struct http_stat. */
489 hs->remote_time = NULL;
492 /* Which structure to use to retrieve the original URL data. */
498 /* First: establish the connection. */
499 if (inhibit_keep_alive
500 || !persistent_available_p (u->host, u->port))
502 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
503 err = make_connection (&sock, u->host, u->port);
507 logputs (LOG_VERBOSE, "\n");
508 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
512 logputs (LOG_VERBOSE, "\n");
513 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
517 logputs (LOG_VERBOSE, "\n");
518 logprintf (LOG_NOTQUIET,
519 _("Connection to %s:%hu refused.\n"), u->host, u->port);
523 logputs (LOG_VERBOSE, "\n");
524 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
529 /* Everything is fine! */
530 logputs (LOG_VERBOSE, _("connected!\n"));
539 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
540 /* #### pc_last_fd should be accessed through an accessor
543 DEBUGP (("Reusing fd %d.\n", sock));
547 path = u->proxy->url;
551 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
555 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
556 sprintf (referer, "Referer: %s\r\n", ou->referer);
558 if (*dt & SEND_NOCACHE)
559 pragma_h = "Pragma: no-cache\r\n";
564 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
565 /* Gag me! Some servers (e.g. WebSitePro) have been known to
566 respond to the following `Range' format by generating a
567 multipart/x-byte-ranges MIME document! This MIME type was
568 present in an old draft of the byteranges specification.
569 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
570 only if multiple non-overlapping ranges are requested --
571 which Wget never does. */
572 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
577 STRDUP_ALLOCA (useragent, opt.useragent);
580 useragent = (char *)alloca (10 + strlen (version_string));
581 sprintf (useragent, "Wget/%s", version_string);
583 /* Construct the authentication, if userid is present. */
586 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
587 user = user ? user : opt.http_user;
588 passwd = passwd ? passwd : opt.http_passwd;
591 if (authenticate_h && user && passwd)
593 wwwauth = create_authorization_line (authenticate_h, user, passwd,
600 char *proxy_user, *proxy_passwd;
601 /* For normal username and password, URL components override
602 command-line/wgetrc parameters. With proxy authentication,
603 it's the reverse, because proxy URLs are normally the
604 "permanent" ones, so command-line args should take
606 if (opt.proxy_user && opt.proxy_passwd)
608 proxy_user = opt.proxy_user;
609 proxy_passwd = opt.proxy_passwd;
613 proxy_user = u->user;
614 proxy_passwd = u->passwd;
616 /* #### This is junky. Can't the proxy request, say, `Digest'
618 if (proxy_user && proxy_passwd)
619 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
620 "Proxy-Authorization");
625 /* String of the form :PORT. Used only for non-standard ports. */
629 port_maybe = (char *)alloca (numdigit (remport) + 2);
630 sprintf (port_maybe, ":%d", remport);
633 if (!inhibit_keep_alive)
634 request_keep_alive = "Connection: Keep-Alive\r\n";
636 request_keep_alive = NULL;
638 /* Allocate the memory for the request. */
639 request = (char *)alloca (strlen (command) + strlen (path)
642 + (port_maybe ? strlen (port_maybe) : 0)
643 + strlen (HTTP_ACCEPT)
644 + (request_keep_alive
645 ? strlen (request_keep_alive) : 0)
646 + (referer ? strlen (referer) : 0)
647 + (wwwauth ? strlen (wwwauth) : 0)
648 + (proxyauth ? strlen (proxyauth) : 0)
649 + (range ? strlen (range) : 0)
651 + (opt.user_header ? strlen (opt.user_header) : 0)
653 /* Construct the request. */
660 command, path, useragent, remhost,
661 port_maybe ? port_maybe : "",
663 request_keep_alive ? request_keep_alive : "",
664 referer ? referer : "",
665 wwwauth ? wwwauth : "",
666 proxyauth ? proxyauth : "",
669 opt.user_header ? opt.user_header : "");
670 DEBUGP (("---request begin---\n%s---request end---\n", request));
671 /* Free the temporary memory. */
672 FREE_MAYBE (wwwauth);
673 FREE_MAYBE (proxyauth);
675 /* Send the request to server. */
676 num_written = iwrite (sock, request, strlen (request));
679 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
681 CLOSE_INVALIDATE (sock);
684 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
685 u->proxy ? "Proxy" : "HTTP");
686 contlen = contrange = -1;
691 /* Before reading anything, initialize the rbuf. */
692 rbuf_initialize (&rbuf, sock);
696 /* Header-fetching loop. */
704 /* Get the header. */
705 status = header_get (&rbuf, &hdr,
706 /* Disallow continuations for status line. */
707 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
709 /* Check for errors. */
710 if (status == HG_EOF && *hdr)
712 /* This used to be an unconditional error, but that was
713 somewhat controversial, because of a large number of
714 broken CGI's that happily "forget" to send the second EOL
715 before closing the connection of a HEAD request.
717 So, the deal is to check whether the header is empty
718 (*hdr is zero if it is); if yes, it means that the
719 previous header was fully retrieved, and that -- most
720 probably -- the request is complete. "...be liberal in
721 what you accept." Oh boy. */
722 logputs (LOG_VERBOSE, "\n");
723 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
726 FREE_MAYBE (hs->newloc);
727 FREE_MAYBE (all_headers);
728 CLOSE_INVALIDATE (sock);
731 else if (status == HG_ERROR)
733 logputs (LOG_VERBOSE, "\n");
734 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
738 FREE_MAYBE (hs->newloc);
739 FREE_MAYBE (all_headers);
740 CLOSE_INVALIDATE (sock);
744 /* If the headers are to be saved to a file later, save them to
746 if (opt.save_headers)
748 int lh = strlen (hdr);
749 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
750 memcpy (all_headers + all_length, hdr, lh);
752 all_headers[all_length++] = '\n';
753 all_headers[all_length] = '\0';
756 /* Print the header if requested. */
757 if (opt.server_response && hcount != 1)
758 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
760 /* Check for status line. */
764 /* Parse the first line of server response. */
765 statcode = parse_http_status_line (hdr, &error);
766 hs->statcode = statcode;
767 /* Store the descriptive response. */
768 if (statcode == -1) /* malformed response */
770 /* A common reason for "malformed response" error is the
771 case when no data was actually received. Handle this
774 hs->error = xstrdup (_("No data received"));
776 hs->error = xstrdup (_("Malformed status line"));
781 hs->error = xstrdup (_("(no description)"));
783 hs->error = xstrdup (error);
790 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
795 /* Exit on empty header. */
802 /* Try getting content-length. */
803 if (contlen == -1 && !opt.ignore_length)
804 if (header_process (hdr, "Content-Length", header_extract_number,
807 /* Try getting content-type. */
809 if (header_process (hdr, "Content-Type", http_process_type, &type))
811 /* Try getting location. */
813 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
815 /* Try getting last-modified. */
816 if (!hs->remote_time)
817 if (header_process (hdr, "Last-Modified", header_strdup,
820 /* Try getting www-authentication. */
822 if (header_process (hdr, "WWW-Authenticate", header_strdup,
825 /* Check for accept-ranges header. If it contains the word
826 `none', disable the ranges. */
827 if (*dt & ACCEPTRANGES)
830 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
833 *dt &= ~ACCEPTRANGES;
837 /* Try getting content-range. */
840 struct http_process_range_closure closure;
841 if (header_process (hdr, "Content-Range", http_process_range, &closure))
843 contrange = closure.first_byte_pos;
847 /* Check for keep-alive related responses. */
848 if (!inhibit_keep_alive)
850 /* Check for the `Keep-Alive' header. */
851 if (!http_keep_alive_1)
853 if (header_process (hdr, "Keep-Alive", header_exists,
857 /* Check for `Connection: Keep-Alive'. */
858 if (!http_keep_alive_2)
860 if (header_process (hdr, "Connection", http_process_connection,
869 logputs (LOG_VERBOSE, "\n");
872 && (http_keep_alive_1 || http_keep_alive_2))
874 assert (inhibit_keep_alive == 0);
878 /* The server has promised that it will not close the connection
879 when we're done. This means that we can register it. */
880 register_persistent (u->host, u->port, sock);
882 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
885 /* Authorization is required. */
890 if (auth_tried_already)
892 /* If we have tried it already, then there is not point
894 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
895 free (authenticate_h);
898 else if (!known_authentication_scheme_p (authenticate_h))
900 free (authenticate_h);
901 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
906 auth_tried_already = 1;
910 /* We do not need this anymore. */
913 free (authenticate_h);
914 authenticate_h = NULL;
917 /* 20x responses are counted among successful by default. */
918 if (H_20X (statcode))
921 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
924 /* We don't assume text/html by default. */
927 if (opt.html_extension && (*dt & TEXTHTML))
928 /* -E / --html-extension / html_extension = on was specified, and this is a
929 text/html file. If some case-insensitive variation on ".htm[l]" isn't
930 already the file's suffix, tack on ".html". */
932 char* last_period_in_local_filename = strrchr(u->local, '.');
934 if (last_period_in_local_filename == NULL ||
935 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
936 strcasecmp(last_period_in_local_filename, ".html") == EQ))
938 size_t local_filename_len = strlen(u->local);
940 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
941 strcpy(u->local + local_filename_len, ".html");
943 *dt |= ADDED_HTML_EXTENSION;
949 else if (contrange != hs->restval ||
950 (H_PARTIAL (statcode) && contrange == -1))
952 /* This means the whole request was somehow misunderstood by the
955 FREE_MAYBE (hs->newloc);
956 FREE_MAYBE (all_headers);
957 CLOSE_INVALIDATE (sock);
964 contlen += contrange;
966 contrange = -1; /* If conent-length was not sent,
967 content-range will be ignored. */
969 hs->contlen = contlen;
971 /* Return if redirected. */
972 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
974 /* RFC2068 says that in case of the 300 (multiple choices)
975 response, the server can output a preferred URL through
976 `Location' header; otherwise, the request should be treated
977 like GET. So, if the location is set, it will be a
978 redirection; otherwise, just proceed normally. */
979 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
983 logprintf (LOG_VERBOSE,
984 _("Location: %s%s\n"),
985 hs->newloc ? hs->newloc : _("unspecified"),
986 hs->newloc ? _(" [following]") : "");
989 FREE_MAYBE (all_headers);
995 if ((*dt & RETROKF) && !opt.server_response)
997 /* No need to print this output if the body won't be
998 downloaded at all, or if the original server response is
1000 logputs (LOG_VERBOSE, _("Length: "));
1003 logputs (LOG_VERBOSE, legible (contlen));
1004 if (contrange != -1)
1005 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1006 legible (contlen - contrange));
1009 logputs (LOG_VERBOSE,
1010 opt.ignore_length ? _("ignored") : _("unspecified"));
1012 logprintf (LOG_VERBOSE, " [%s]\n", type);
1014 logputs (LOG_VERBOSE, "\n");
1018 type = NULL; /* We don't need it any more. */
1020 /* Return if we have no intention of further downloading. */
1021 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1023 /* In case someone cares to look... */
1027 FREE_MAYBE (all_headers);
1028 CLOSE_FINISH (sock);
1029 return RETRFINISHED;
1032 /* Open the local file. */
1035 mkalldirs (u->local);
1037 rotate_backups (u->local);
1038 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1041 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1042 CLOSE_FINISH (sock);
1043 FREE_MAYBE (all_headers);
1052 /* This will silently fail for streams that don't correspond
1053 to regular files, but that's OK. */
1059 /* #### This confuses the code that checks for file size. There
1060 should be some overhead information. */
1061 if (opt.save_headers)
1062 fwrite (all_headers, 1, all_length, fp);
1064 /* Get the contents of the document. */
1065 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1066 (contlen != -1 ? contlen : 0),
1068 hs->dltime = elapsed_time ();
1070 /* Close or flush the file. We have to be careful to check for
1071 error here. Checking the result of fwrite() is not enough --
1072 errors could go unnoticed! */
1075 flush_res = fclose (fp);
1077 flush_res = fflush (fp);
1078 if (flush_res == EOF)
1081 FREE_MAYBE (all_headers);
1082 CLOSE_FINISH (sock);
1085 return RETRFINISHED;
1088 /* The genuine HTTP loop! This is the part where the retrieval is
1089 retried, and retried, and retried, and... */
1091 http_loop (struct urlinfo *u, char **newloc, int *dt)
1093 static int first_retrieval = 1;
1096 int use_ts, got_head = 0; /* time-stamping info */
1097 char *filename_plus_orig_suffix;
1098 char *local_filename = NULL;
1099 char *tms, *suf, *locf, *tmrate;
1101 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1102 long local_size = 0; /* the size of the local file */
1103 size_t filename_len;
1104 struct http_stat hstat; /* HTTP status */
1109 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1110 has_wildcards_p because it would also warn on `?', and we know that
1111 shows up in CGI paths a *lot*. */
1112 if (strchr (u->url, '*'))
1113 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1115 /* Determine the local filename. */
1117 u->local = url_filename (u->proxy ? u->proxy : u);
1119 if (!opt.output_document)
1122 locf = opt.output_document;
1124 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1125 xmalloc() here before EACH return. This is one reason it's better to set
1126 flags that influence flow control and then return once at the end. */
1127 filename_len = strlen(u->local);
1128 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1130 if (opt.noclobber && file_exists_p (u->local))
1132 /* If opt.noclobber is turned on and file already exists, do not
1133 retrieve the file */
1134 logprintf (LOG_VERBOSE, _("\
1135 File `%s' already there, will not retrieve.\n"), u->local);
1136 /* If the file is there, we suppose it's retrieved OK. */
1139 /* #### Bogusness alert. */
1140 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1141 text/html, a harmless lie. */
1142 if (((suf = suffix (u->local)) != NULL)
1143 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1146 free(filename_plus_orig_suffix); /* must precede every return! */
1147 /* Another harmless lie: */
1152 if (opt.timestamping)
1154 boolean local_dot_orig_file_exists = FALSE;
1156 if (opt.backup_converted)
1157 /* If -K is specified, we'll act on the assumption that it was specified
1158 last time these files were downloaded as well, and instead of just
1159 comparing local file X against server file X, we'll compare local
1160 file X.orig (if extant, else X) against server file X. If -K
1161 _wasn't_ specified last time, or the server contains files called
1162 *.orig, -N will be back to not operating correctly with -k. */
1164 /* Would a single s[n]printf() call be faster? --dan
1166 It wouldn't. sprintf() is horribly slow. At one point I
1167 profiled Wget, and found that a measurable and
1168 non-negligible amount of time was lost calling sprintf()
1169 in url.c. Replacing sprintf with inline calls to
1170 strcpy() and long_to_string() made a difference.
1172 strcpy(filename_plus_orig_suffix, u->local);
1173 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1175 /* Try to stat() the .orig file. */
1176 if (stat(filename_plus_orig_suffix, &st) == 0)
1178 local_dot_orig_file_exists = TRUE;
1179 local_filename = filename_plus_orig_suffix;
1183 if (!local_dot_orig_file_exists)
1184 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1185 if (stat (u->local, &st) == 0)
1186 local_filename = u->local;
1188 if (local_filename != NULL)
1189 /* There was a local file, so we'll check later to see if the version
1190 the server has is the same version we already have, allowing us to
1195 local_size = st.st_size;
1199 /* Reset the counter. */
1201 *dt = 0 | ACCEPTRANGES;
1205 /* Increment the pass counter. */
1207 /* Wait before the retrieval (unless this is the very first
1209 Check if we are retrying or not, wait accordingly - HEH */
1210 if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
1214 if (count<opt.waitretry)
1217 sleep(opt.waitretry);
1222 if (first_retrieval)
1223 first_retrieval = 0;
1224 /* Get the current time string. */
1225 tms = time_str (NULL);
1226 /* Print fetch message, if opt.verbose. */
1229 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1233 sprintf (tmp, _("(try:%2d)"), count);
1234 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1235 tms, hurl, tmp, locf);
1237 ws_changetitle (hurl, 1);
1242 /* Default document type is empty. However, if spider mode is
1243 on or time-stamping is employed, HEAD_ONLY commands is
1244 encoded within *dt. */
1245 if (opt.spider || (use_ts && !got_head))
1249 /* Assume no restarting. */
1251 /* Decide whether or not to restart. */
1252 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1253 && file_exists_p (u->local))
1254 if (stat (u->local, &st) == 0)
1255 hstat.restval = st.st_size;
1256 /* Decide whether to send the no-cache directive. */
1257 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1258 *dt |= SEND_NOCACHE;
1260 *dt &= ~SEND_NOCACHE;
1262 /* Try fetching the document, or at least its head. :-) */
1263 err = gethttp (u, &hstat, dt);
1265 /* It's unfortunate that wget determines the local filename before finding
1266 out the Content-Type of the file. Barring a major restructuring of the
1267 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1268 u->local to tack on ".html". */
1269 if (!opt.output_document)
1272 locf = opt.output_document;
1275 tms = time_str (NULL);
1276 /* Get the new location (with or without the redirection). */
1278 *newloc = xstrdup (hstat.newloc);
1281 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1282 case CONERROR: case READERR: case WRITEFAILED:
1284 /* Non-fatal errors continue executing the loop, which will
1285 bring them to "while" statement at the end, to judge
1286 whether the number of tries was exceeded. */
1288 printwhat (count, opt.ntry);
1291 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1292 /* Fatal errors just return from the function. */
1294 free(filename_plus_orig_suffix); /* must precede every return! */
1297 case FWRITEERR: case FOPENERR:
1298 /* Another fatal error. */
1299 logputs (LOG_VERBOSE, "\n");
1300 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1301 u->local, strerror (errno));
1303 free(filename_plus_orig_suffix); /* must precede every return! */
1307 /* Return the new location to the caller. */
1310 logprintf (LOG_NOTQUIET,
1311 _("ERROR: Redirection (%d) without location.\n"),
1313 free(filename_plus_orig_suffix); /* must precede every return! */
1317 free(filename_plus_orig_suffix); /* must precede every return! */
1321 /* Deal with you later. */
1324 /* All possibilities should have been exhausted. */
1327 if (!(*dt & RETROKF))
1331 /* #### Ugly ugly ugly! */
1332 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1333 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1336 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1337 tms, hstat.statcode, hstat.error);
1338 logputs (LOG_VERBOSE, "\n");
1340 free(filename_plus_orig_suffix); /* must precede every return! */
1344 /* Did we get the time-stamp? */
1347 if (opt.timestamping && !hstat.remote_time)
1349 logputs (LOG_NOTQUIET, _("\
1350 Last-modified header missing -- time-stamps turned off.\n"));
1352 else if (hstat.remote_time)
1354 /* Convert the date-string into struct tm. */
1355 tmr = http_atotm (hstat.remote_time);
1356 if (tmr == (time_t) (-1))
1357 logputs (LOG_VERBOSE, _("\
1358 Last-modified header invalid -- time-stamp ignored.\n"));
1362 /* The time-stamping section. */
1367 use_ts = 0; /* no more time-stamping */
1368 count = 0; /* the retrieve count for HEAD is
1370 if (hstat.remote_time && tmr != (time_t) (-1))
1372 /* Now time-stamping can be used validly. Time-stamping
1373 means that if the sizes of the local and remote file
1374 match, and local file is newer than the remote file,
1375 it will not be retrieved. Otherwise, the normal
1376 download procedure is resumed. */
1378 (hstat.contlen == -1 || local_size == hstat.contlen))
1380 logprintf (LOG_VERBOSE, _("\
1381 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1384 free(filename_plus_orig_suffix);/*must precede every return!*/
1387 else if (tml >= tmr)
1388 logprintf (LOG_VERBOSE, _("\
1389 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1391 logputs (LOG_VERBOSE,
1392 _("Remote file is newer, retrieving.\n"));
1398 && (tmr != (time_t) (-1))
1400 && ((hstat.len == hstat.contlen) ||
1401 ((hstat.res == 0) &&
1402 ((hstat.contlen == -1) ||
1403 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1405 touch (u->local, tmr);
1407 /* End of time-stamping section. */
1411 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1412 free(filename_plus_orig_suffix); /* must precede every return! */
1416 /* It is now safe to free the remainder of hstat, since the
1417 strings within it will no longer be used. */
1420 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1422 if (hstat.len == hstat.contlen)
1426 logprintf (LOG_VERBOSE,
1427 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1428 tms, tmrate, locf, hstat.len, hstat.contlen);
1429 logprintf (LOG_NONVERBOSE,
1430 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1431 tms, u->url, hstat.len, hstat.contlen, locf, count);
1434 downloaded_increase (hstat.len);
1436 /* Remember that we downloaded the file for later ".orig" code. */
1437 if (*dt & ADDED_HTML_EXTENSION)
1438 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1440 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1442 free(filename_plus_orig_suffix); /* must precede every return! */
1445 else if (hstat.res == 0) /* No read error */
1447 if (hstat.contlen == -1) /* We don't know how much we were supposed
1448 to get, so assume we succeeded. */
1452 logprintf (LOG_VERBOSE,
1453 _("%s (%s) - `%s' saved [%ld]\n\n"),
1454 tms, tmrate, locf, hstat.len);
1455 logprintf (LOG_NONVERBOSE,
1456 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1457 tms, u->url, hstat.len, locf, count);
1460 downloaded_increase (hstat.len);
1462 /* Remember that we downloaded the file for later ".orig" code. */
1463 if (*dt & ADDED_HTML_EXTENSION)
1464 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1466 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1468 free(filename_plus_orig_suffix); /* must precede every return! */
1471 else if (hstat.len < hstat.contlen) /* meaning we lost the
1472 connection too soon */
1474 logprintf (LOG_VERBOSE,
1475 _("%s (%s) - Connection closed at byte %ld. "),
1476 tms, tmrate, hstat.len);
1477 printwhat (count, opt.ntry);
1480 else if (!opt.kill_longer) /* meaning we got more than expected */
1482 logprintf (LOG_VERBOSE,
1483 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1484 tms, tmrate, locf, hstat.len, hstat.contlen);
1485 logprintf (LOG_NONVERBOSE,
1486 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1487 tms, u->url, hstat.len, hstat.contlen, locf, count);
1489 downloaded_increase (hstat.len);
1491 /* Remember that we downloaded the file for later ".orig" code. */
1492 if (*dt & ADDED_HTML_EXTENSION)
1493 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1495 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1497 free(filename_plus_orig_suffix); /* must precede every return! */
1500 else /* the same, but not accepted */
1502 logprintf (LOG_VERBOSE,
1503 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1504 tms, tmrate, hstat.len, hstat.contlen);
1505 printwhat (count, opt.ntry);
1509 else /* now hstat.res can only be -1 */
1511 if (hstat.contlen == -1)
1513 logprintf (LOG_VERBOSE,
1514 _("%s (%s) - Read error at byte %ld (%s)."),
1515 tms, tmrate, hstat.len, strerror (errno));
1516 printwhat (count, opt.ntry);
1519 else /* hstat.res == -1 and contlen is given */
1521 logprintf (LOG_VERBOSE,
1522 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1523 tms, tmrate, hstat.len, hstat.contlen,
1525 printwhat (count, opt.ntry);
1532 while (!opt.ntry || (count < opt.ntry));
1533 free(filename_plus_orig_suffix); /* must precede every return! */
1537 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1538 than local timezone (mktime assumes the latter).
1540 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1541 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1543 mktime_from_utc (struct tm *t)
1550 tb = mktime (gmtime (&tl));
1551 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1554 /* Check whether the result of strptime() indicates success.
1555 strptime() returns the pointer to how far it got to in the string.
1556 The processing has been successful if the string is at `GMT' or
1557 `+X', or at the end of the string.
1559 In extended regexp parlance, the function returns 1 if P matches
1560 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1561 strptime()) is considered a failure and 0 is returned. */
1567 while (ISSPACE (*p))
1570 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1571 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1577 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1578 the three formats RFC2068 allows the HTTP servers to emit --
1579 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1582 We use strptime() to recognize various dates, which makes it a
1583 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1584 allows shortened dates and months, one-digit days, etc.). It also
1585 allows more than one space anywhere where the specs require one SP.
1586 The routine should probably be even more forgiving (as recommended
1587 by RFC2068), but I do not have the time to write one.
1589 Return the computed time_t representation, or -1 if all the
1592 Needless to say, what we *really* need here is something like
1593 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1594 and does not use strptime(). atotm() is to be found in the sources
1595 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1597 http_atotm (char *time_string)
1601 /* Roger Beeman says: "This function dynamically allocates struct tm
1602 t, but does no initialization. The only field that actually
1603 needs initialization is tm_isdst, since the others will be set by
1604 strptime. Since strptime does not set tm_isdst, it will return
1605 the data structure with whatever data was in tm_isdst to begin
1606 with. For those of us in timezones where DST can occur, there
1607 can be a one hour shift depending on the previous contents of the
1608 data area where the data structure is allocated." */
1611 /* Note that under foreign locales Solaris strptime() fails to
1612 recognize English dates, which renders this function useless. I
1613 assume that other non-GNU strptime's are plagued by the same
1614 disease. We solve this by setting only LC_MESSAGES in
1615 i18n_initialize(), instead of LC_ALL.
1617 Another solution could be to temporarily set locale to C, invoke
1618 strptime(), and restore it back. This is slow and dirty,
1619 however, and locale support other than LC_MESSAGES can mess other
1620 things, so I rather chose to stick with just setting LC_MESSAGES.
1622 Also note that none of this is necessary under GNU strptime(),
1623 because it recognizes both international and local dates. */
1625 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1626 it to eat all white space up to (and including) a newline, and
1627 the function fails if there is no newline (!).
1629 Let's hope all strptime() implementations use ` ' to skip *all*
1630 whitespace instead of just one (it works that way on all the
1631 systems I've tested it on). */
1633 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1634 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1635 return mktime_from_utc (&t);
1636 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1637 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1638 return mktime_from_utc (&t);
1639 /* asctime: Thu Jan 29 22:12:57 1998 */
1640 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1641 return mktime_from_utc (&t);
1646 /* Authorization support: We support two authorization schemes:
1648 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1650 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1651 consisting of answering to the server's challenge with the proper
1654 /* How many bytes it will take to store LEN bytes in base64. */
1655 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1657 /* Encode the string S of length LENGTH to base64 format and place it
1658 to STORE. STORE will be 0-terminated, and must point to a writable
1659 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1661 base64_encode (const char *s, char *store, int length)
1663 /* Conversion table. */
1664 static char tbl[64] = {
1665 'A','B','C','D','E','F','G','H',
1666 'I','J','K','L','M','N','O','P',
1667 'Q','R','S','T','U','V','W','X',
1668 'Y','Z','a','b','c','d','e','f',
1669 'g','h','i','j','k','l','m','n',
1670 'o','p','q','r','s','t','u','v',
1671 'w','x','y','z','0','1','2','3',
1672 '4','5','6','7','8','9','+','/'
1675 unsigned char *p = (unsigned char *)store;
1677 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1678 for (i = 0; i < length; i += 3)
1680 *p++ = tbl[s[0] >> 2];
1681 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1682 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1683 *p++ = tbl[s[2] & 0x3f];
1686 /* Pad the result if necessary... */
1687 if (i == length + 1)
1689 else if (i == length + 2)
1690 *(p - 1) = *(p - 2) = '=';
1691 /* ...and zero-terminate it. */
1695 /* Create the authentication header contents for the `Basic' scheme.
1696 This is done by encoding the string `USER:PASS' in base64 and
1697 prepending `HEADER: Basic ' to it. */
1699 basic_authentication_encode (const char *user, const char *passwd,
1702 char *t1, *t2, *res;
1703 int len1 = strlen (user) + 1 + strlen (passwd);
1704 int len2 = BASE64_LENGTH (len1);
1706 t1 = (char *)alloca (len1 + 1);
1707 sprintf (t1, "%s:%s", user, passwd);
1708 t2 = (char *)alloca (1 + len2);
1709 base64_encode (t1, t2, len1);
1710 res = (char *)malloc (len2 + 11 + strlen (header));
1711 sprintf (res, "%s: Basic %s\r\n", header, t2);
1717 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1718 of a field in such a header. If the field is the one specified by
1719 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1720 digest authorization code), extract its value in the (char*)
1721 variable pointed by RET. Returns negative on a malformed header,
1722 or number of bytes that have been parsed by this call. */
1724 extract_header_attr (const char *au, const char *attr_name, char **ret)
1726 const char *cp, *ep;
1730 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1732 cp += strlen (attr_name);
1735 cp += skip_lws (cp);
1740 cp += skip_lws (cp);
1745 for (ep = cp; *ep && *ep != '\"'; ep++)
1750 *ret = strdupdelim (cp, ep);
1757 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1758 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1759 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1761 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1762 an array of 16 bytes containing the hash keys, and BUF should be a
1763 buffer of 33 writable characters (32 for hex digits plus one for
1764 zero termination). */
1766 dump_hash (unsigned char *buf, const unsigned char *hash)
1770 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1772 *buf++ = HEXD2asc (*hash >> 4);
1773 *buf++ = HEXD2asc (*hash & 0xf);
1778 /* Take the line apart to find the challenge, and compose a digest
1779 authorization header. See RFC2069 section 2.1.2. */
1781 digest_authentication_encode (const char *au, const char *user,
1782 const char *passwd, const char *method,
1785 static char *realm, *opaque, *nonce;
1790 { "realm", &realm },
1791 { "opaque", &opaque },
1796 realm = opaque = nonce = NULL;
1798 au += 6; /* skip over `Digest' */
1803 au += skip_lws (au);
1804 for (i = 0; i < ARRAY_SIZE (options); i++)
1806 int skip = extract_header_attr (au, options[i].name,
1807 options[i].variable);
1811 FREE_MAYBE (opaque);
1821 if (i == ARRAY_SIZE (options))
1823 while (*au && *au != '=')
1827 au += skip_lws (au);
1831 while (*au && *au != '\"')
1838 while (*au && *au != ',')
1843 if (!realm || !nonce || !user || !passwd || !path || !method)
1846 FREE_MAYBE (opaque);
1851 /* Calculate the digest value. */
1854 unsigned char hash[MD5_HASHLEN];
1855 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
1856 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
1858 /* A1BUF = H(user ":" realm ":" password) */
1859 md5_init_ctx (&ctx);
1860 md5_process_bytes (user, strlen (user), &ctx);
1861 md5_process_bytes (":", 1, &ctx);
1862 md5_process_bytes (realm, strlen (realm), &ctx);
1863 md5_process_bytes (":", 1, &ctx);
1864 md5_process_bytes (passwd, strlen (passwd), &ctx);
1865 md5_finish_ctx (&ctx, hash);
1866 dump_hash (a1buf, hash);
1868 /* A2BUF = H(method ":" path) */
1869 md5_init_ctx (&ctx);
1870 md5_process_bytes (method, strlen (method), &ctx);
1871 md5_process_bytes (":", 1, &ctx);
1872 md5_process_bytes (path, strlen (path), &ctx);
1873 md5_finish_ctx (&ctx, hash);
1874 dump_hash (a2buf, hash);
1876 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
1877 md5_init_ctx (&ctx);
1878 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
1879 md5_process_bytes (":", 1, &ctx);
1880 md5_process_bytes (nonce, strlen (nonce), &ctx);
1881 md5_process_bytes (":", 1, &ctx);
1882 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
1883 md5_finish_ctx (&ctx, hash);
1884 dump_hash (response_digest, hash);
1886 res = (char*) xmalloc (strlen (user)
1891 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
1892 + (opaque ? strlen (opaque) : 0)
1894 sprintf (res, "Authorization: Digest \
1895 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1896 user, realm, nonce, path, response_digest);
1899 char *p = res + strlen (res);
1900 strcat (p, ", opaque=\"");
1904 strcat (res, "\r\n");
1908 #endif /* USE_DIGEST */
1911 #define HACK_O_MATIC(line, string_constant) \
1912 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
1913 && (ISSPACE (line[sizeof (string_constant) - 1]) \
1914 || !line[sizeof (string_constant) - 1]))
1917 known_authentication_scheme_p (const char *au)
1919 return HACK_O_MATIC (au, "Basic")
1920 || HACK_O_MATIC (au, "Digest")
1921 || HACK_O_MATIC (au, "NTLM");
1926 /* Create the HTTP authorization request header. When the
1927 `WWW-Authenticate' response header is seen, according to the
1928 authorization scheme specified in that header (`Basic' and `Digest'
1929 are supported by the current implementation), produce an
1930 appropriate HTTP authorization request header. */
1932 create_authorization_line (const char *au, const char *user,
1933 const char *passwd, const char *method,
1936 char *wwwauth = NULL;
1938 if (!strncasecmp (au, "Basic", 5))
1939 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
1940 if (!strncasecmp (au, "NTLM", 4))
1941 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
1943 else if (!strncasecmp (au, "Digest", 6))
1944 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
1945 #endif /* USE_DIGEST */