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>
50 # include <netdb.h> /* for h_errno */
67 # include "gen_sslfunc.h"
70 extern char *version_string;
82 #define TEXTHTML_S "text/html"
83 #define HTTP_ACCEPT "*/*"
85 /* Some status code validation macros: */
86 #define H_20X(x) (((x) >= 200) && ((x) < 300))
87 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
88 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
89 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
91 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
93 #define HTTP_STATUS_OK 200
94 #define HTTP_STATUS_CREATED 201
95 #define HTTP_STATUS_ACCEPTED 202
96 #define HTTP_STATUS_NO_CONTENT 204
97 #define HTTP_STATUS_PARTIAL_CONTENTS 206
99 /* Redirection 3xx. */
100 #define HTTP_STATUS_MULTIPLE_CHOICES 300
101 #define HTTP_STATUS_MOVED_PERMANENTLY 301
102 #define HTTP_STATUS_MOVED_TEMPORARILY 302
103 #define HTTP_STATUS_NOT_MODIFIED 304
105 /* Client error 4xx. */
106 #define HTTP_STATUS_BAD_REQUEST 400
107 #define HTTP_STATUS_UNAUTHORIZED 401
108 #define HTTP_STATUS_FORBIDDEN 403
109 #define HTTP_STATUS_NOT_FOUND 404
111 /* Server errors 5xx. */
112 #define HTTP_STATUS_INTERNAL 500
113 #define HTTP_STATUS_NOT_IMPLEMENTED 501
114 #define HTTP_STATUS_BAD_GATEWAY 502
115 #define HTTP_STATUS_UNAVAILABLE 503
118 /* Parse the HTTP status line, which is of format:
120 HTTP-Version SP Status-Code SP Reason-Phrase
122 The function returns the status-code, or -1 if the status line is
123 malformed. The pointer to reason-phrase is returned in RP. */
125 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
127 /* (the variables must not be named `major' and `minor', because
128 that breaks compilation with SunOS4 cc.) */
129 int mjr, mnr, statcode;
132 *reason_phrase_ptr = NULL;
134 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
135 major version, and Y is minor version. */
136 if (strncmp (line, "HTTP/", 5) != 0)
140 /* Calculate major HTTP version. */
142 for (mjr = 0; ISDIGIT (*line); line++)
143 mjr = 10 * mjr + (*line - '0');
144 if (*line != '.' || p == line)
148 /* Calculate minor HTTP version. */
150 for (mnr = 0; ISDIGIT (*line); line++)
151 mnr = 10 * mnr + (*line - '0');
152 if (*line != ' ' || p == line)
154 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
155 minor version can be safely ignored. */
160 /* Calculate status code. */
161 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
163 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
165 /* Set up the reason phrase pointer. */
167 /* RFC2068 requires SPC here, but we allow the string to finish
168 here, in case no reason-phrase is present. */
172 *reason_phrase_ptr = line;
177 *reason_phrase_ptr = line + 1;
182 /* Functions to be used as arguments to header_process(): */
184 struct http_process_range_closure {
190 /* Parse the `Content-Range' header and extract the information it
191 contains. Returns 1 if successful, -1 otherwise. */
193 http_process_range (const char *hdr, void *arg)
195 struct http_process_range_closure *closure
196 = (struct http_process_range_closure *)arg;
199 /* Certain versions of Nutscape proxy server send out
200 `Content-Length' without "bytes" specifier, which is a breach of
201 RFC2068 (as well as the HTTP/1.1 draft which was current at the
202 time). But hell, I must support it... */
203 if (!strncasecmp (hdr, "bytes", 5))
206 hdr += skip_lws (hdr);
212 for (num = 0; ISDIGIT (*hdr); hdr++)
213 num = 10 * num + (*hdr - '0');
214 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
216 closure->first_byte_pos = num;
218 for (num = 0; ISDIGIT (*hdr); hdr++)
219 num = 10 * num + (*hdr - '0');
220 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
222 closure->last_byte_pos = num;
224 for (num = 0; ISDIGIT (*hdr); hdr++)
225 num = 10 * num + (*hdr - '0');
226 closure->entity_length = num;
230 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
231 Used for `Accept-Ranges'. */
233 http_process_none (const char *hdr, void *arg)
235 int *where = (int *)arg;
237 if (strstr (hdr, "none"))
244 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
246 http_process_type (const char *hdr, void *arg)
248 char **result = (char **)arg;
249 /* Locate P on `;' or the terminating zero, whichever comes first. */
250 const char *p = strchr (hdr, ';');
252 p = hdr + strlen (hdr);
253 while (p > hdr && ISSPACE (*(p - 1)))
255 *result = strdupdelim (hdr, p);
259 /* Check whether the `Connection' header is set to "keep-alive". */
261 http_process_connection (const char *hdr, void *arg)
263 int *flag = (int *)arg;
264 if (!strcasecmp (hdr, "Keep-Alive"))
269 /* Persistent connections. Currently, we cache the most recently used
270 connection as persistent, provided that the HTTP server agrees to
271 make it such. The persistence data is stored in the variables
272 below. Ideally, it would be in a structure, and it should be
273 possible to cache an arbitrary fixed number of these connections.
275 I think the code is quite easy to extend in that direction. */
277 /* Whether a persistent connection is active. */
278 static int pc_active_p;
279 /* Host and port of currently active persistent connection. */
280 static unsigned char pc_last_host[4];
281 static unsigned short pc_last_port;
283 /* File descriptor of the currently active persistent connection. */
284 static int pc_last_fd;
287 /* Whether a ssl handshake has occoured on this connection */
288 static int pc_active_ssl;
289 /* SSL connection of the currently active persistent connection. */
290 static SSL *pc_last_ssl;
291 #endif /* HAVE_SSL */
293 /* Mark the persistent connection as invalid. This is used by the
294 CLOSE_* macros after they forcefully close a registered persistent
295 connection. This does not close the file descriptor -- it is left
296 to the caller to do that. (Maybe it should, though.) */
299 invalidate_persistent (void)
304 #endif /* HAVE_SSL */
305 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
308 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
309 persistent. This will enable someone to use the same connection
310 later. In the context of HTTP, this must be called only AFTER the
311 response has been received and the server has promised that the
312 connection will remain alive.
314 If a previous connection was persistent, it is closed. */
317 register_persistent (const char *host, unsigned short port, int fd
327 if (pc_last_fd == fd)
329 /* The connection FD is already registered. Nothing to
335 /* The old persistent connection is still active; let's
336 close it first. This situation arises whenever a
337 persistent connection exists, but we then connect to a
338 different host, and try to register a persistent
339 connection to that one. */
341 /* The ssl disconnect has to take place before the closing
344 shutdown_ssl(pc_last_ssl);
347 invalidate_persistent ();
351 /* This store_hostaddress may not fail, because it has the results
353 success = store_hostaddress (pc_last_host, host);
360 pc_active_ssl = ssl ? 1 : 0;
362 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
365 /* Return non-zero if a persistent connection is available for
366 connecting to HOST:PORT. */
369 persistent_available_p (const char *host, unsigned short port
375 unsigned char this_host[4];
376 /* First, check whether a persistent connection is active at all. */
379 /* Second, check if the active connection pertains to the correct
380 (HOST, PORT) ordered pair. */
381 if (port != pc_last_port)
384 /* Second, a): check if current connection is (not) ssl, too. This
385 test is unlikely to fail because HTTP and HTTPS typicaly use
386 different ports. Yet it is possible, or so I [Christian
387 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
389 if (ssl != pc_active_ssl)
391 #endif /* HAVE_SSL */
392 if (!store_hostaddress (this_host, host))
394 if (memcmp (pc_last_host, this_host, 4))
396 /* Third: check whether the connection is still open. This is
397 important because most server implement a liberal (short) timeout
398 on persistent connections. Wget can of course always reconnect
399 if the connection doesn't work out, but it's nicer to know in
400 advance. This test is a logical followup of the first test, but
401 is "expensive" and therefore placed at the end of the list. */
402 if (!test_socket_open (pc_last_fd))
404 /* Oops, the socket is no longer open. Now that we know that,
405 let's invalidate the persistent connection before returning
408 invalidate_persistent ();
415 # define SHUTDOWN_SSL(ssl) do { \
417 shutdown_ssl (ssl); \
420 # define SHUTDOWN_SSL(ssl)
423 /* The idea behind these two CLOSE macros is to distinguish between
424 two cases: one when the job we've been doing is finished, and we
425 want to close the connection and leave, and two when something is
426 seriously wrong and we're closing the connection as part of
429 In case of keep_alive, CLOSE_FINISH should leave the connection
430 open, while CLOSE_INVALIDATE should still close it.
432 Note that the semantics of the flag `keep_alive' is "this
433 connection *will* be reused (the server has promised not to close
434 the connection once we're done)", while the semantics of
435 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
436 active, registered connection". */
438 #define CLOSE_FINISH(fd) do { \
441 SHUTDOWN_SSL (ssl); \
443 if (pc_active_p && (fd) == pc_last_fd) \
444 invalidate_persistent (); \
448 #define CLOSE_INVALIDATE(fd) do { \
449 SHUTDOWN_SSL (ssl); \
451 if (pc_active_p && (fd) == pc_last_fd) \
452 invalidate_persistent (); \
457 long len; /* received length */
458 long contlen; /* expected length */
459 long restval; /* the restart value */
460 int res; /* the result of last read */
461 char *newloc; /* new location (redirection) */
462 char *remote_time; /* remote time-stamp string */
463 char *error; /* textual HTTP error */
464 int statcode; /* status code */
465 long dltime; /* time of the download */
468 /* Free the elements of hstat X. */
469 #define FREEHSTAT(x) do \
471 FREE_MAYBE ((x).newloc); \
472 FREE_MAYBE ((x).remote_time); \
473 FREE_MAYBE ((x).error); \
474 (x).newloc = (x).remote_time = (x).error = NULL; \
477 static char *create_authorization_line PARAMS ((const char *, const char *,
478 const char *, const char *,
480 static char *basic_authentication_encode PARAMS ((const char *, const char *,
482 static int known_authentication_scheme_p PARAMS ((const char *));
484 static time_t http_atotm PARAMS ((char *));
486 #define BEGINS_WITH(line, string_constant) \
487 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
488 && (ISSPACE (line[sizeof (string_constant) - 1]) \
489 || !line[sizeof (string_constant) - 1]))
491 /* Retrieve a document through HTTP protocol. It recognizes status
492 code, and correctly handles redirections. It closes the network
493 socket. If it receives an error from the functions below it, it
494 will print it if there is enough information to do so (almost
495 always), returning the error to the caller (i.e. http_loop).
497 Various HTTP parameters are stored to hs. Although it parses the
498 response code correctly, it is not used in a sane way. The caller
501 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
502 and u->proxy->url will be given to the proxy server (bad naming,
505 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
507 char *request, *type, *command, *path;
509 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
510 char *authenticate_h;
514 char *request_keep_alive;
515 int sock, hcount, num_written, all_length, remport, statcode;
516 long contlen, contrange;
520 int auth_tried_already;
523 static SSL_CTX *ssl_ctx = NULL;
525 #endif /* HAVE_SSL */
527 /* Whether this connection will be kept alive after the HTTP request
531 /* Flags that detect the two ways of specifying HTTP keep-alive
533 int http_keep_alive_1, http_keep_alive_2;
535 /* Whether keep-alive should be inhibited. */
536 int inhibit_keep_alive;
539 /* initialize ssl_ctx on first run */
542 err=init_ssl (&ssl_ctx);
547 case SSLERRCTXCREATE:
549 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
553 /* try without certfile */
554 logprintf (LOG_NOTQUIET,
555 _("Failed to load certificates from %s\n"),
558 logprintf (LOG_NOTQUIET,
559 _("Trying without the specified certificate\n"));
562 logprintf (LOG_NOTQUIET,
563 _("Failed to get certificate key from %s\n"),
566 logprintf (LOG_NOTQUIET,
567 _("Trying without the specified certificate\n"));
574 #endif /* HAVE_SSL */
576 if (!(*dt & HEAD_ONLY))
577 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
578 know the local filename so we can save to it. */
579 assert (u->local != NULL);
582 auth_tried_already = 0;
584 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
587 /* We need to come back here when the initial attempt to retrieve
588 without authorization header fails. (Expected to happen at least
589 for the Digest authorization scheme.) */
592 http_keep_alive_1 = http_keep_alive_2 = 0;
594 /* Initialize certain elements of struct http_stat. */
599 hs->remote_time = NULL;
602 /* Which structure to use to retrieve the original URL data. */
608 /* First: establish the connection. */
609 if (inhibit_keep_alive
612 !persistent_available_p (u->host, u->port)
614 !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
615 #endif /* HAVE_SSL */
618 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
619 err = make_connection (&sock, u->host, u->port);
623 logputs (LOG_VERBOSE, "\n");
624 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
628 logputs (LOG_VERBOSE, "\n");
629 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
633 logputs (LOG_VERBOSE, "\n");
634 logprintf (LOG_NOTQUIET,
635 _("Connection to %s:%hu refused.\n"), u->host, u->port);
639 logputs (LOG_VERBOSE, "\n");
640 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
645 /* Everything is fine! */
646 logputs (LOG_VERBOSE, _("connected!\n"));
653 if (u->proto == URLHTTPS)
654 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
656 logputs (LOG_VERBOSE, "\n");
657 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
661 #endif /* HAVE_SSL */
665 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
666 /* #### pc_last_fd should be accessed through an accessor
671 #endif /* HAVE_SSL */
672 DEBUGP (("Reusing fd %d.\n", sock));
676 path = u->proxy->url;
680 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
684 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
685 sprintf (referer, "Referer: %s\r\n", ou->referer);
687 if (*dt & SEND_NOCACHE)
688 pragma_h = "Pragma: no-cache\r\n";
693 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
694 /* Gag me! Some servers (e.g. WebSitePro) have been known to
695 respond to the following `Range' format by generating a
696 multipart/x-byte-ranges MIME document! This MIME type was
697 present in an old draft of the byteranges specification.
698 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
699 only if multiple non-overlapping ranges are requested --
700 which Wget never does. */
701 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
706 STRDUP_ALLOCA (useragent, opt.useragent);
709 useragent = (char *)alloca (10 + strlen (version_string));
710 sprintf (useragent, "Wget/%s", version_string);
712 /* Construct the authentication, if userid is present. */
715 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
716 user = user ? user : opt.http_user;
717 passwd = passwd ? passwd : opt.http_passwd;
724 /* We have the username and the password, but haven't tried
725 any authorization yet. Let's see if the "Basic" method
726 works. If not, we'll come back here and construct a
727 proper authorization method with the right challenges.
729 If we didn't employ this kind of logic, every URL that
730 requires authorization would have to be processed twice,
731 which is very suboptimal and generates a bunch of false
732 "unauthorized" errors in the server log.
734 #### But this logic also has a serious problem when used
735 with stronger authentications: we *first* transmit the
736 username and the password in clear text, and *then*
737 attempt a stronger authentication scheme. That cannot be
738 right! We are only fortunate that almost everyone still
739 uses the `Basic' scheme anyway.
741 There should be an option to prevent this from happening,
742 for those who use strong authentication schemes and value
744 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
748 wwwauth = create_authorization_line (authenticate_h, user, passwd,
756 char *proxy_user, *proxy_passwd;
757 /* For normal username and password, URL components override
758 command-line/wgetrc parameters. With proxy authentication,
759 it's the reverse, because proxy URLs are normally the
760 "permanent" ones, so command-line args should take
762 if (opt.proxy_user && opt.proxy_passwd)
764 proxy_user = opt.proxy_user;
765 proxy_passwd = opt.proxy_passwd;
769 proxy_user = u->user;
770 proxy_passwd = u->passwd;
772 /* #### This is junky. Can't the proxy request, say, `Digest'
774 if (proxy_user && proxy_passwd)
775 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
776 "Proxy-Authorization");
781 /* String of the form :PORT. Used only for non-standard ports. */
785 port_maybe = (char *)alloca (numdigit (remport) + 2);
786 sprintf (port_maybe, ":%d", remport);
789 if (!inhibit_keep_alive)
790 request_keep_alive = "Connection: Keep-Alive\r\n";
792 request_keep_alive = NULL;
794 /* Allocate the memory for the request. */
795 request = (char *)alloca (strlen (command) + strlen (path)
798 + (port_maybe ? strlen (port_maybe) : 0)
799 + strlen (HTTP_ACCEPT)
800 + (request_keep_alive
801 ? strlen (request_keep_alive) : 0)
802 + (referer ? strlen (referer) : 0)
803 + (wwwauth ? strlen (wwwauth) : 0)
804 + (proxyauth ? strlen (proxyauth) : 0)
805 + (range ? strlen (range) : 0)
807 + (opt.user_header ? strlen (opt.user_header) : 0)
809 /* Construct the request. */
816 command, path, useragent, remhost,
817 port_maybe ? port_maybe : "",
819 request_keep_alive ? request_keep_alive : "",
820 referer ? referer : "",
821 wwwauth ? wwwauth : "",
822 proxyauth ? proxyauth : "",
825 opt.user_header ? opt.user_header : "");
826 DEBUGP (("---request begin---\n%s---request end---\n", request));
827 /* Free the temporary memory. */
828 FREE_MAYBE (wwwauth);
829 FREE_MAYBE (proxyauth);
831 /* Send the request to server. */
833 if (u->proto == URLHTTPS)
834 num_written = ssl_iwrite (ssl, request, strlen (request));
836 #endif /* HAVE_SSL */
837 num_written = iwrite (sock, request, strlen (request));
841 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
843 CLOSE_INVALIDATE (sock);
846 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
847 u->proxy ? "Proxy" : "HTTP");
848 contlen = contrange = -1;
853 /* Before reading anything, initialize the rbuf. */
854 rbuf_initialize (&rbuf, sock);
856 if (u->proto == URLHTTPS)
860 #endif /* HAVE_SSL */
863 /* Header-fetching loop. */
871 /* Get the header. */
872 status = header_get (&rbuf, &hdr,
873 /* Disallow continuations for status line. */
874 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
876 /* Check for errors. */
877 if (status == HG_EOF && *hdr)
879 /* This used to be an unconditional error, but that was
880 somewhat controversial, because of a large number of
881 broken CGI's that happily "forget" to send the second EOL
882 before closing the connection of a HEAD request.
884 So, the deal is to check whether the header is empty
885 (*hdr is zero if it is); if yes, it means that the
886 previous header was fully retrieved, and that -- most
887 probably -- the request is complete. "...be liberal in
888 what you accept." Oh boy. */
889 logputs (LOG_VERBOSE, "\n");
890 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
893 FREE_MAYBE (hs->newloc);
894 FREE_MAYBE (all_headers);
895 CLOSE_INVALIDATE (sock);
898 else if (status == HG_ERROR)
900 logputs (LOG_VERBOSE, "\n");
901 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
905 FREE_MAYBE (hs->newloc);
906 FREE_MAYBE (all_headers);
907 CLOSE_INVALIDATE (sock);
911 /* If the headers are to be saved to a file later, save them to
913 if (opt.save_headers)
915 int lh = strlen (hdr);
916 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
917 memcpy (all_headers + all_length, hdr, lh);
919 all_headers[all_length++] = '\n';
920 all_headers[all_length] = '\0';
923 /* Print the header if requested. */
924 if (opt.server_response && hcount != 1)
925 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
927 /* Check for status line. */
931 /* Parse the first line of server response. */
932 statcode = parse_http_status_line (hdr, &error);
933 hs->statcode = statcode;
934 /* Store the descriptive response. */
935 if (statcode == -1) /* malformed response */
937 /* A common reason for "malformed response" error is the
938 case when no data was actually received. Handle this
941 hs->error = xstrdup (_("No data received"));
943 hs->error = xstrdup (_("Malformed status line"));
948 hs->error = xstrdup (_("(no description)"));
950 hs->error = xstrdup (error);
957 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
962 /* Exit on empty header. */
969 /* Try getting content-length. */
970 if (contlen == -1 && !opt.ignore_length)
971 if (header_process (hdr, "Content-Length", header_extract_number,
974 /* Try getting content-type. */
976 if (header_process (hdr, "Content-Type", http_process_type, &type))
978 /* Try getting location. */
980 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
982 /* Try getting last-modified. */
983 if (!hs->remote_time)
984 if (header_process (hdr, "Last-Modified", header_strdup,
987 /* Try getting www-authentication. */
989 if (header_process (hdr, "WWW-Authenticate", header_strdup,
992 /* Check for accept-ranges header. If it contains the word
993 `none', disable the ranges. */
994 if (*dt & ACCEPTRANGES)
997 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1000 *dt &= ~ACCEPTRANGES;
1004 /* Try getting content-range. */
1005 if (contrange == -1)
1007 struct http_process_range_closure closure;
1008 if (header_process (hdr, "Content-Range", http_process_range, &closure))
1010 contrange = closure.first_byte_pos;
1014 /* Check for keep-alive related responses. */
1015 if (!inhibit_keep_alive)
1017 /* Check for the `Keep-Alive' header. */
1018 if (!http_keep_alive_1)
1020 if (header_process (hdr, "Keep-Alive", header_exists,
1021 &http_keep_alive_1))
1024 /* Check for `Connection: Keep-Alive'. */
1025 if (!http_keep_alive_2)
1027 if (header_process (hdr, "Connection", http_process_connection,
1028 &http_keep_alive_2))
1036 logputs (LOG_VERBOSE, "\n");
1039 && (http_keep_alive_1 || http_keep_alive_2))
1041 assert (inhibit_keep_alive == 0);
1045 /* The server has promised that it will not close the connection
1046 when we're done. This means that we can register it. */
1048 register_persistent (u->host, u->port, sock);
1050 register_persistent (u->host, u->port, sock, ssl);
1051 #endif /* HAVE_SSL */
1053 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1056 /* Authorization is required. */
1060 CLOSE_FINISH (sock);
1061 if (auth_tried_already)
1063 /* If we have tried it already, then there is not point
1066 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1067 xfree (authenticate_h);
1070 else if (!known_authentication_scheme_p (authenticate_h))
1072 xfree (authenticate_h);
1073 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1076 else if (BEGINS_WITH (authenticate_h, "Basic"))
1078 /* The authentication scheme is basic, the one we try by
1079 default, and it failed. There's no sense in trying
1085 auth_tried_already = 1;
1089 /* We do not need this anymore. */
1092 xfree (authenticate_h);
1093 authenticate_h = NULL;
1096 /* 20x responses are counted among successful by default. */
1097 if (H_20X (statcode))
1100 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1103 /* We don't assume text/html by default. */
1106 if (opt.html_extension && (*dt & TEXTHTML))
1107 /* -E / --html-extension / html_extension = on was specified, and this is a
1108 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1109 already the file's suffix, tack on ".html". */
1111 char* last_period_in_local_filename = strrchr(u->local, '.');
1113 if (last_period_in_local_filename == NULL ||
1114 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1115 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1117 size_t local_filename_len = strlen(u->local);
1119 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1120 strcpy(u->local + local_filename_len, ".html");
1122 *dt |= ADDED_HTML_EXTENSION;
1126 if (contrange == -1)
1128 else if (contrange != hs->restval ||
1129 (H_PARTIAL (statcode) && contrange == -1))
1131 /* This means the whole request was somehow misunderstood by the
1132 server. Bail out. */
1134 FREE_MAYBE (hs->newloc);
1135 FREE_MAYBE (all_headers);
1136 CLOSE_INVALIDATE (sock);
1143 contlen += contrange;
1145 contrange = -1; /* If conent-length was not sent,
1146 content-range will be ignored. */
1148 hs->contlen = contlen;
1150 /* Return if redirected. */
1151 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1153 /* RFC2068 says that in case of the 300 (multiple choices)
1154 response, the server can output a preferred URL through
1155 `Location' header; otherwise, the request should be treated
1156 like GET. So, if the location is set, it will be a
1157 redirection; otherwise, just proceed normally. */
1158 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1162 logprintf (LOG_VERBOSE,
1163 _("Location: %s%s\n"),
1164 hs->newloc ? hs->newloc : _("unspecified"),
1165 hs->newloc ? _(" [following]") : "");
1166 CLOSE_FINISH (sock);
1168 FREE_MAYBE (all_headers);
1174 if ((*dt & RETROKF) && !opt.server_response)
1176 /* No need to print this output if the body won't be
1177 downloaded at all, or if the original server response is
1179 logputs (LOG_VERBOSE, _("Length: "));
1182 logputs (LOG_VERBOSE, legible (contlen));
1183 if (contrange != -1)
1184 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1185 legible (contlen - contrange));
1188 logputs (LOG_VERBOSE,
1189 opt.ignore_length ? _("ignored") : _("unspecified"));
1191 logprintf (LOG_VERBOSE, " [%s]\n", type);
1193 logputs (LOG_VERBOSE, "\n");
1197 type = NULL; /* We don't need it any more. */
1199 /* Return if we have no intention of further downloading. */
1200 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1202 /* In case someone cares to look... */
1206 FREE_MAYBE (all_headers);
1207 CLOSE_FINISH (sock);
1208 return RETRFINISHED;
1211 /* Open the local file. */
1214 mkalldirs (u->local);
1216 rotate_backups (u->local);
1217 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1220 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1221 CLOSE_FINISH (sock);
1222 FREE_MAYBE (all_headers);
1231 /* This will silently fail for streams that don't correspond
1232 to regular files, but that's OK. */
1238 /* #### This confuses the code that checks for file size. There
1239 should be some overhead information. */
1240 if (opt.save_headers)
1241 fwrite (all_headers, 1, all_length, fp);
1243 /* Get the contents of the document. */
1244 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1245 (contlen != -1 ? contlen : 0),
1247 hs->dltime = elapsed_time ();
1249 /* Close or flush the file. We have to be careful to check for
1250 error here. Checking the result of fwrite() is not enough --
1251 errors could go unnoticed! */
1254 flush_res = fclose (fp);
1256 flush_res = fflush (fp);
1257 if (flush_res == EOF)
1260 FREE_MAYBE (all_headers);
1261 CLOSE_FINISH (sock);
1264 return RETRFINISHED;
1267 /* The genuine HTTP loop! This is the part where the retrieval is
1268 retried, and retried, and retried, and... */
1270 http_loop (struct urlinfo *u, char **newloc, int *dt)
1273 int use_ts, got_head = 0; /* time-stamping info */
1274 char *filename_plus_orig_suffix;
1275 char *local_filename = NULL;
1276 char *tms, *suf, *locf, *tmrate;
1278 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1279 long local_size = 0; /* the size of the local file */
1280 size_t filename_len;
1281 struct http_stat hstat; /* HTTP status */
1286 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1287 has_wildcards_p because it would also warn on `?', and we know that
1288 shows up in CGI paths a *lot*. */
1289 if (strchr (u->url, '*'))
1290 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1292 /* Determine the local filename. */
1294 u->local = url_filename (u->proxy ? u->proxy : u);
1296 if (!opt.output_document)
1299 locf = opt.output_document;
1301 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1302 xmalloc() here before EACH return. This is one reason it's better to set
1303 flags that influence flow control and then return once at the end. */
1304 filename_len = strlen(u->local);
1305 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1307 if (opt.noclobber && file_exists_p (u->local))
1309 /* If opt.noclobber is turned on and file already exists, do not
1310 retrieve the file */
1311 logprintf (LOG_VERBOSE, _("\
1312 File `%s' already there, will not retrieve.\n"), u->local);
1313 /* If the file is there, we suppose it's retrieved OK. */
1316 /* #### Bogusness alert. */
1317 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1318 text/html, a harmless lie. */
1319 if (((suf = suffix (u->local)) != NULL)
1320 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1323 xfree (filename_plus_orig_suffix); /* must precede every return! */
1324 /* Another harmless lie: */
1329 if (opt.timestamping)
1331 boolean local_dot_orig_file_exists = FALSE;
1333 if (opt.backup_converted)
1334 /* If -K is specified, we'll act on the assumption that it was specified
1335 last time these files were downloaded as well, and instead of just
1336 comparing local file X against server file X, we'll compare local
1337 file X.orig (if extant, else X) against server file X. If -K
1338 _wasn't_ specified last time, or the server contains files called
1339 *.orig, -N will be back to not operating correctly with -k. */
1341 /* Would a single s[n]printf() call be faster? --dan
1343 It wouldn't. sprintf() is horribly slow. At one point I
1344 profiled Wget, and found that a measurable and
1345 non-negligible amount of time was lost calling sprintf()
1346 in url.c. Replacing sprintf with inline calls to
1347 strcpy() and long_to_string() made a difference.
1349 strcpy(filename_plus_orig_suffix, u->local);
1350 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1352 /* Try to stat() the .orig file. */
1353 if (stat(filename_plus_orig_suffix, &st) == 0)
1355 local_dot_orig_file_exists = TRUE;
1356 local_filename = filename_plus_orig_suffix;
1360 if (!local_dot_orig_file_exists)
1361 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1362 if (stat (u->local, &st) == 0)
1363 local_filename = u->local;
1365 if (local_filename != NULL)
1366 /* There was a local file, so we'll check later to see if the version
1367 the server has is the same version we already have, allowing us to
1372 local_size = st.st_size;
1376 /* Reset the counter. */
1378 *dt = 0 | ACCEPTRANGES;
1382 /* Increment the pass counter. */
1384 sleep_between_retrievals (count);
1385 /* Get the current time string. */
1386 tms = time_str (NULL);
1387 /* Print fetch message, if opt.verbose. */
1390 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1394 sprintf (tmp, _("(try:%2d)"), count);
1395 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1396 tms, hurl, tmp, locf);
1398 ws_changetitle (hurl, 1);
1403 /* Default document type is empty. However, if spider mode is
1404 on or time-stamping is employed, HEAD_ONLY commands is
1405 encoded within *dt. */
1406 if (opt.spider || (use_ts && !got_head))
1410 /* Assume no restarting. */
1412 /* Decide whether or not to restart. */
1413 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1414 && file_exists_p (u->local))
1415 if (stat (u->local, &st) == 0)
1416 hstat.restval = st.st_size;
1417 /* Decide whether to send the no-cache directive. */
1418 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1419 *dt |= SEND_NOCACHE;
1421 *dt &= ~SEND_NOCACHE;
1423 /* Try fetching the document, or at least its head. :-) */
1424 err = gethttp (u, &hstat, dt);
1426 /* It's unfortunate that wget determines the local filename before finding
1427 out the Content-Type of the file. Barring a major restructuring of the
1428 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1429 u->local to tack on ".html". */
1430 if (!opt.output_document)
1433 locf = opt.output_document;
1436 tms = time_str (NULL);
1437 /* Get the new location (with or without the redirection). */
1439 *newloc = xstrdup (hstat.newloc);
1442 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1443 case CONERROR: case READERR: case WRITEFAILED:
1445 /* Non-fatal errors continue executing the loop, which will
1446 bring them to "while" statement at the end, to judge
1447 whether the number of tries was exceeded. */
1449 printwhat (count, opt.ntry);
1452 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1453 case SSLERRCTXCREATE:
1454 /* Fatal errors just return from the function. */
1456 xfree (filename_plus_orig_suffix); /* must precede every return! */
1459 case FWRITEERR: case FOPENERR:
1460 /* Another fatal error. */
1461 logputs (LOG_VERBOSE, "\n");
1462 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1463 u->local, strerror (errno));
1468 /* Another fatal error. */
1469 logputs (LOG_VERBOSE, "\n");
1470 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1472 xfree (filename_plus_orig_suffix); /* must precede every return! */
1476 /* Return the new location to the caller. */
1479 logprintf (LOG_NOTQUIET,
1480 _("ERROR: Redirection (%d) without location.\n"),
1482 xfree (filename_plus_orig_suffix); /* must precede every return! */
1486 xfree (filename_plus_orig_suffix); /* must precede every return! */
1490 /* Deal with you later. */
1493 /* All possibilities should have been exhausted. */
1496 if (!(*dt & RETROKF))
1500 /* #### Ugly ugly ugly! */
1501 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1502 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1505 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1506 tms, hstat.statcode, hstat.error);
1507 logputs (LOG_VERBOSE, "\n");
1509 xfree (filename_plus_orig_suffix); /* must precede every return! */
1513 /* Did we get the time-stamp? */
1516 if (opt.timestamping && !hstat.remote_time)
1518 logputs (LOG_NOTQUIET, _("\
1519 Last-modified header missing -- time-stamps turned off.\n"));
1521 else if (hstat.remote_time)
1523 /* Convert the date-string into struct tm. */
1524 tmr = http_atotm (hstat.remote_time);
1525 if (tmr == (time_t) (-1))
1526 logputs (LOG_VERBOSE, _("\
1527 Last-modified header invalid -- time-stamp ignored.\n"));
1531 /* The time-stamping section. */
1536 use_ts = 0; /* no more time-stamping */
1537 count = 0; /* the retrieve count for HEAD is
1539 if (hstat.remote_time && tmr != (time_t) (-1))
1541 /* Now time-stamping can be used validly. Time-stamping
1542 means that if the sizes of the local and remote file
1543 match, and local file is newer than the remote file,
1544 it will not be retrieved. Otherwise, the normal
1545 download procedure is resumed. */
1547 (hstat.contlen == -1 || local_size == hstat.contlen))
1549 logprintf (LOG_VERBOSE, _("\
1550 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1553 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1556 else if (tml >= tmr)
1557 logprintf (LOG_VERBOSE, _("\
1558 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1560 logputs (LOG_VERBOSE,
1561 _("Remote file is newer, retrieving.\n"));
1566 if ((tmr != (time_t) (-1))
1568 && ((hstat.len == hstat.contlen) ||
1569 ((hstat.res == 0) &&
1570 ((hstat.contlen == -1) ||
1571 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1573 /* #### This code repeats in http.c and ftp.c. Move it to a
1575 const char *fl = NULL;
1576 if (opt.output_document)
1578 if (opt.od_known_regular)
1579 fl = opt.output_document;
1586 /* End of time-stamping section. */
1590 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1591 xfree (filename_plus_orig_suffix); /* must precede every return! */
1595 /* It is now safe to free the remainder of hstat, since the
1596 strings within it will no longer be used. */
1599 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1601 if (hstat.len == hstat.contlen)
1605 logprintf (LOG_VERBOSE,
1606 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1607 tms, tmrate, locf, hstat.len, hstat.contlen);
1608 logprintf (LOG_NONVERBOSE,
1609 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1610 tms, u->url, hstat.len, hstat.contlen, locf, count);
1613 downloaded_increase (hstat.len);
1615 /* Remember that we downloaded the file for later ".orig" code. */
1616 if (*dt & ADDED_HTML_EXTENSION)
1617 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1619 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1621 xfree(filename_plus_orig_suffix); /* must precede every return! */
1624 else if (hstat.res == 0) /* No read error */
1626 if (hstat.contlen == -1) /* We don't know how much we were supposed
1627 to get, so assume we succeeded. */
1631 logprintf (LOG_VERBOSE,
1632 _("%s (%s) - `%s' saved [%ld]\n\n"),
1633 tms, tmrate, locf, hstat.len);
1634 logprintf (LOG_NONVERBOSE,
1635 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1636 tms, u->url, hstat.len, locf, count);
1639 downloaded_increase (hstat.len);
1641 /* Remember that we downloaded the file for later ".orig" code. */
1642 if (*dt & ADDED_HTML_EXTENSION)
1643 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1645 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1647 xfree (filename_plus_orig_suffix); /* must precede every return! */
1650 else if (hstat.len < hstat.contlen) /* meaning we lost the
1651 connection too soon */
1653 logprintf (LOG_VERBOSE,
1654 _("%s (%s) - Connection closed at byte %ld. "),
1655 tms, tmrate, hstat.len);
1656 printwhat (count, opt.ntry);
1659 else if (!opt.kill_longer) /* meaning we got more than expected */
1661 logprintf (LOG_VERBOSE,
1662 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1663 tms, tmrate, locf, hstat.len, hstat.contlen);
1664 logprintf (LOG_NONVERBOSE,
1665 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1666 tms, u->url, hstat.len, hstat.contlen, locf, count);
1668 downloaded_increase (hstat.len);
1670 /* Remember that we downloaded the file for later ".orig" code. */
1671 if (*dt & ADDED_HTML_EXTENSION)
1672 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1674 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1676 xfree (filename_plus_orig_suffix); /* must precede every return! */
1679 else /* the same, but not accepted */
1681 logprintf (LOG_VERBOSE,
1682 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1683 tms, tmrate, hstat.len, hstat.contlen);
1684 printwhat (count, opt.ntry);
1688 else /* now hstat.res can only be -1 */
1690 if (hstat.contlen == -1)
1692 logprintf (LOG_VERBOSE,
1693 _("%s (%s) - Read error at byte %ld (%s)."),
1694 tms, tmrate, hstat.len, strerror (errno));
1695 printwhat (count, opt.ntry);
1698 else /* hstat.res == -1 and contlen is given */
1700 logprintf (LOG_VERBOSE,
1701 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1702 tms, tmrate, hstat.len, hstat.contlen,
1704 printwhat (count, opt.ntry);
1711 while (!opt.ntry || (count < opt.ntry));
1712 xfree (filename_plus_orig_suffix); /* must precede every return! */
1716 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1717 than local timezone (mktime assumes the latter).
1719 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1720 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1722 mktime_from_utc (struct tm *t)
1729 tb = mktime (gmtime (&tl));
1730 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1733 /* Check whether the result of strptime() indicates success.
1734 strptime() returns the pointer to how far it got to in the string.
1735 The processing has been successful if the string is at `GMT' or
1736 `+X', or at the end of the string.
1738 In extended regexp parlance, the function returns 1 if P matches
1739 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1740 strptime()) is considered a failure and 0 is returned. */
1742 check_end (const char *p)
1746 while (ISSPACE (*p))
1749 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1750 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
1756 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1757 the three formats RFC2068 allows the HTTP servers to emit --
1758 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1761 We use strptime() to recognize various dates, which makes it a
1762 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1763 allows shortened dates and months, one-digit days, etc.). It also
1764 allows more than one space anywhere where the specs require one SP.
1765 The routine should probably be even more forgiving (as recommended
1766 by RFC2068), but I do not have the time to write one.
1768 Return the computed time_t representation, or -1 if all the
1771 Needless to say, what we *really* need here is something like
1772 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1773 and does not use strptime(). atotm() is to be found in the sources
1774 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1776 http_atotm (char *time_string)
1780 /* Roger Beeman says: "This function dynamically allocates struct tm
1781 t, but does no initialization. The only field that actually
1782 needs initialization is tm_isdst, since the others will be set by
1783 strptime. Since strptime does not set tm_isdst, it will return
1784 the data structure with whatever data was in tm_isdst to begin
1785 with. For those of us in timezones where DST can occur, there
1786 can be a one hour shift depending on the previous contents of the
1787 data area where the data structure is allocated." */
1790 /* Note that under foreign locales Solaris strptime() fails to
1791 recognize English dates, which renders this function useless. I
1792 assume that other non-GNU strptime's are plagued by the same
1793 disease. We solve this by setting only LC_MESSAGES in
1794 i18n_initialize(), instead of LC_ALL.
1796 Another solution could be to temporarily set locale to C, invoke
1797 strptime(), and restore it back. This is slow and dirty,
1798 however, and locale support other than LC_MESSAGES can mess other
1799 things, so I rather chose to stick with just setting LC_MESSAGES.
1801 Also note that none of this is necessary under GNU strptime(),
1802 because it recognizes both international and local dates. */
1804 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1805 it to eat all white space up to (and including) a newline, and
1806 the function fails if there is no newline (!).
1808 Let's hope all strptime() implementations use ` ' to skip *all*
1809 whitespace instead of just one (it works that way on all the
1810 systems I've tested it on). */
1812 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1813 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1814 return mktime_from_utc (&t);
1815 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1816 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1817 return mktime_from_utc (&t);
1818 /* asctime: Thu Jan 29 22:12:57 1998 */
1819 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1820 return mktime_from_utc (&t);
1825 /* Authorization support: We support two authorization schemes:
1827 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1829 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1830 consisting of answering to the server's challenge with the proper
1833 /* How many bytes it will take to store LEN bytes in base64. */
1834 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1836 /* Encode the string S of length LENGTH to base64 format and place it
1837 to STORE. STORE will be 0-terminated, and must point to a writable
1838 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1840 base64_encode (const char *s, char *store, int length)
1842 /* Conversion table. */
1843 static char tbl[64] = {
1844 'A','B','C','D','E','F','G','H',
1845 'I','J','K','L','M','N','O','P',
1846 'Q','R','S','T','U','V','W','X',
1847 'Y','Z','a','b','c','d','e','f',
1848 'g','h','i','j','k','l','m','n',
1849 'o','p','q','r','s','t','u','v',
1850 'w','x','y','z','0','1','2','3',
1851 '4','5','6','7','8','9','+','/'
1854 unsigned char *p = (unsigned char *)store;
1856 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1857 for (i = 0; i < length; i += 3)
1859 *p++ = tbl[s[0] >> 2];
1860 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1861 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1862 *p++ = tbl[s[2] & 0x3f];
1865 /* Pad the result if necessary... */
1866 if (i == length + 1)
1868 else if (i == length + 2)
1869 *(p - 1) = *(p - 2) = '=';
1870 /* ...and zero-terminate it. */
1874 /* Create the authentication header contents for the `Basic' scheme.
1875 This is done by encoding the string `USER:PASS' in base64 and
1876 prepending `HEADER: Basic ' to it. */
1878 basic_authentication_encode (const char *user, const char *passwd,
1881 char *t1, *t2, *res;
1882 int len1 = strlen (user) + 1 + strlen (passwd);
1883 int len2 = BASE64_LENGTH (len1);
1885 t1 = (char *)alloca (len1 + 1);
1886 sprintf (t1, "%s:%s", user, passwd);
1887 t2 = (char *)alloca (1 + len2);
1888 base64_encode (t1, t2, len1);
1889 res = (char *)xmalloc (len2 + 11 + strlen (header));
1890 sprintf (res, "%s: Basic %s\r\n", header, t2);
1896 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1897 of a field in such a header. If the field is the one specified by
1898 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1899 digest authorization code), extract its value in the (char*)
1900 variable pointed by RET. Returns negative on a malformed header,
1901 or number of bytes that have been parsed by this call. */
1903 extract_header_attr (const char *au, const char *attr_name, char **ret)
1905 const char *cp, *ep;
1909 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1911 cp += strlen (attr_name);
1914 cp += skip_lws (cp);
1919 cp += skip_lws (cp);
1924 for (ep = cp; *ep && *ep != '\"'; ep++)
1929 *ret = strdupdelim (cp, ep);
1936 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1937 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1938 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1940 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1941 an array of 16 bytes containing the hash keys, and BUF should be a
1942 buffer of 33 writable characters (32 for hex digits plus one for
1943 zero termination). */
1945 dump_hash (unsigned char *buf, const unsigned char *hash)
1949 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1951 *buf++ = HEXD2asc (*hash >> 4);
1952 *buf++ = HEXD2asc (*hash & 0xf);
1957 /* Take the line apart to find the challenge, and compose a digest
1958 authorization header. See RFC2069 section 2.1.2. */
1960 digest_authentication_encode (const char *au, const char *user,
1961 const char *passwd, const char *method,
1964 static char *realm, *opaque, *nonce;
1969 { "realm", &realm },
1970 { "opaque", &opaque },
1975 realm = opaque = nonce = NULL;
1977 au += 6; /* skip over `Digest' */
1982 au += skip_lws (au);
1983 for (i = 0; i < ARRAY_SIZE (options); i++)
1985 int skip = extract_header_attr (au, options[i].name,
1986 options[i].variable);
1990 FREE_MAYBE (opaque);
2000 if (i == ARRAY_SIZE (options))
2002 while (*au && *au != '=')
2006 au += skip_lws (au);
2010 while (*au && *au != '\"')
2017 while (*au && *au != ',')
2022 if (!realm || !nonce || !user || !passwd || !path || !method)
2025 FREE_MAYBE (opaque);
2030 /* Calculate the digest value. */
2033 unsigned char hash[MD5_HASHLEN];
2034 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2035 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2037 /* A1BUF = H(user ":" realm ":" password) */
2038 md5_init_ctx (&ctx);
2039 md5_process_bytes (user, strlen (user), &ctx);
2040 md5_process_bytes (":", 1, &ctx);
2041 md5_process_bytes (realm, strlen (realm), &ctx);
2042 md5_process_bytes (":", 1, &ctx);
2043 md5_process_bytes (passwd, strlen (passwd), &ctx);
2044 md5_finish_ctx (&ctx, hash);
2045 dump_hash (a1buf, hash);
2047 /* A2BUF = H(method ":" path) */
2048 md5_init_ctx (&ctx);
2049 md5_process_bytes (method, strlen (method), &ctx);
2050 md5_process_bytes (":", 1, &ctx);
2051 md5_process_bytes (path, strlen (path), &ctx);
2052 md5_finish_ctx (&ctx, hash);
2053 dump_hash (a2buf, hash);
2055 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2056 md5_init_ctx (&ctx);
2057 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2058 md5_process_bytes (":", 1, &ctx);
2059 md5_process_bytes (nonce, strlen (nonce), &ctx);
2060 md5_process_bytes (":", 1, &ctx);
2061 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2062 md5_finish_ctx (&ctx, hash);
2063 dump_hash (response_digest, hash);
2065 res = (char*) xmalloc (strlen (user)
2070 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2071 + (opaque ? strlen (opaque) : 0)
2073 sprintf (res, "Authorization: Digest \
2074 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2075 user, realm, nonce, path, response_digest);
2078 char *p = res + strlen (res);
2079 strcat (p, ", opaque=\"");
2083 strcat (res, "\r\n");
2087 #endif /* USE_DIGEST */
2090 #define BEGINS_WITH(line, string_constant) \
2091 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2092 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2093 || !line[sizeof (string_constant) - 1]))
2096 known_authentication_scheme_p (const char *au)
2098 return BEGINS_WITH (au, "Basic")
2099 || BEGINS_WITH (au, "Digest")
2100 || BEGINS_WITH (au, "NTLM");
2105 /* Create the HTTP authorization request header. When the
2106 `WWW-Authenticate' response header is seen, according to the
2107 authorization scheme specified in that header (`Basic' and `Digest'
2108 are supported by the current implementation), produce an
2109 appropriate HTTP authorization request header. */
2111 create_authorization_line (const char *au, const char *user,
2112 const char *passwd, const char *method,
2115 char *wwwauth = NULL;
2117 if (!strncasecmp (au, "Basic", 5))
2118 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2119 if (!strncasecmp (au, "NTLM", 4))
2120 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2122 else if (!strncasecmp (au, "Digest", 6))
2123 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2124 #endif /* USE_DIGEST */