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>
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
40 # include <sys/time.h>
49 # include <netdb.h> /* for h_errno */
66 # 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 */
466 int no_truncate; /* whether truncating the file is
470 /* Free the elements of hstat X. */
471 #define FREEHSTAT(x) do \
473 FREE_MAYBE ((x).newloc); \
474 FREE_MAYBE ((x).remote_time); \
475 FREE_MAYBE ((x).error); \
476 (x).newloc = (x).remote_time = (x).error = NULL; \
479 static char *create_authorization_line PARAMS ((const char *, const char *,
480 const char *, const char *,
482 static char *basic_authentication_encode PARAMS ((const char *, const char *,
484 static int known_authentication_scheme_p PARAMS ((const char *));
486 time_t http_atotm PARAMS ((char *));
488 #define BEGINS_WITH(line, string_constant) \
489 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
490 && (ISSPACE (line[sizeof (string_constant) - 1]) \
491 || !line[sizeof (string_constant) - 1]))
493 /* Retrieve a document through HTTP protocol. It recognizes status
494 code, and correctly handles redirections. It closes the network
495 socket. If it receives an error from the functions below it, it
496 will print it if there is enough information to do so (almost
497 always), returning the error to the caller (i.e. http_loop).
499 Various HTTP parameters are stored to hs. Although it parses the
500 response code correctly, it is not used in a sane way. The caller
503 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
504 and u->proxy->url will be given to the proxy server (bad naming,
507 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
509 char *request, *type, *command, *path;
511 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
512 char *authenticate_h;
516 char *request_keep_alive;
517 int sock, hcount, num_written, all_length, remport, statcode;
518 long contlen, contrange;
522 int auth_tried_already;
525 static SSL_CTX *ssl_ctx = NULL;
527 #endif /* HAVE_SSL */
528 char *cookies = NULL;
530 /* Whether this connection will be kept alive after the HTTP request
534 /* Flags that detect the two ways of specifying HTTP keep-alive
536 int http_keep_alive_1, http_keep_alive_2;
538 /* Whether keep-alive should be inhibited. */
539 int inhibit_keep_alive;
542 /* initialize ssl_ctx on first run */
545 err=init_ssl (&ssl_ctx);
550 case SSLERRCTXCREATE:
552 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
556 /* try without certfile */
557 logprintf (LOG_NOTQUIET,
558 _("Failed to load certificates from %s\n"),
561 logprintf (LOG_NOTQUIET,
562 _("Trying without the specified certificate\n"));
565 logprintf (LOG_NOTQUIET,
566 _("Failed to get certificate key from %s\n"),
569 logprintf (LOG_NOTQUIET,
570 _("Trying without the specified certificate\n"));
577 #endif /* HAVE_SSL */
579 if (!(*dt & HEAD_ONLY))
580 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
581 know the local filename so we can save to it. */
582 assert (u->local != NULL);
585 auth_tried_already = 0;
587 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
590 /* We need to come back here when the initial attempt to retrieve
591 without authorization header fails. (Expected to happen at least
592 for the Digest authorization scheme.) */
595 http_keep_alive_1 = http_keep_alive_2 = 0;
598 cookies = build_cookies_request (u->host, u->port, u->path,
599 u->proto == URLHTTPS);
601 /* Initialize certain elements of struct http_stat. */
606 hs->remote_time = NULL;
609 /* Which structure to use to retrieve the original URL data. */
615 /* First: establish the connection. */
616 if (inhibit_keep_alive
619 !persistent_available_p (u->host, u->port)
621 !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
622 #endif /* HAVE_SSL */
625 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
626 err = make_connection (&sock, u->host, u->port);
630 logputs (LOG_VERBOSE, "\n");
631 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
635 logputs (LOG_VERBOSE, "\n");
636 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
640 logputs (LOG_VERBOSE, "\n");
641 logprintf (LOG_NOTQUIET,
642 _("Connection to %s:%hu refused.\n"), u->host, u->port);
646 logputs (LOG_VERBOSE, "\n");
647 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
652 /* Everything is fine! */
653 logputs (LOG_VERBOSE, _("connected!\n"));
660 if (u->proto == URLHTTPS)
661 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
663 logputs (LOG_VERBOSE, "\n");
664 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
668 #endif /* HAVE_SSL */
672 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
673 /* #### pc_last_fd should be accessed through an accessor
678 #endif /* HAVE_SSL */
679 DEBUGP (("Reusing fd %d.\n", sock));
683 path = u->proxy->url;
687 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
691 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
692 sprintf (referer, "Referer: %s\r\n", ou->referer);
694 if (*dt & SEND_NOCACHE)
695 pragma_h = "Pragma: no-cache\r\n";
700 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
701 /* Gag me! Some servers (e.g. WebSitePro) have been known to
702 respond to the following `Range' format by generating a
703 multipart/x-byte-ranges MIME document! This MIME type was
704 present in an old draft of the byteranges specification.
705 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
706 only if multiple non-overlapping ranges are requested --
707 which Wget never does. */
708 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
713 STRDUP_ALLOCA (useragent, opt.useragent);
716 useragent = (char *)alloca (10 + strlen (version_string));
717 sprintf (useragent, "Wget/%s", version_string);
719 /* Construct the authentication, if userid is present. */
722 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
723 user = user ? user : opt.http_user;
724 passwd = passwd ? passwd : opt.http_passwd;
731 /* We have the username and the password, but haven't tried
732 any authorization yet. Let's see if the "Basic" method
733 works. If not, we'll come back here and construct a
734 proper authorization method with the right challenges.
736 If we didn't employ this kind of logic, every URL that
737 requires authorization would have to be processed twice,
738 which is very suboptimal and generates a bunch of false
739 "unauthorized" errors in the server log.
741 #### But this logic also has a serious problem when used
742 with stronger authentications: we *first* transmit the
743 username and the password in clear text, and *then*
744 attempt a stronger authentication scheme. That cannot be
745 right! We are only fortunate that almost everyone still
746 uses the `Basic' scheme anyway.
748 There should be an option to prevent this from happening,
749 for those who use strong authentication schemes and value
751 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
755 wwwauth = create_authorization_line (authenticate_h, user, passwd,
763 char *proxy_user, *proxy_passwd;
764 /* For normal username and password, URL components override
765 command-line/wgetrc parameters. With proxy authentication,
766 it's the reverse, because proxy URLs are normally the
767 "permanent" ones, so command-line args should take
769 if (opt.proxy_user && opt.proxy_passwd)
771 proxy_user = opt.proxy_user;
772 proxy_passwd = opt.proxy_passwd;
776 proxy_user = u->user;
777 proxy_passwd = u->passwd;
779 /* #### This is junky. Can't the proxy request, say, `Digest'
781 if (proxy_user && proxy_passwd)
782 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
783 "Proxy-Authorization");
788 /* String of the form :PORT. Used only for non-standard ports. */
791 if (remport != (u->proto == URLHTTPS ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT) )
793 if (remport != DEFAULT_HTTP_PORT)
796 port_maybe = (char *)alloca (numdigit (remport) + 2);
797 sprintf (port_maybe, ":%d", remport);
800 if (!inhibit_keep_alive)
801 request_keep_alive = "Connection: Keep-Alive\r\n";
803 request_keep_alive = NULL;
805 /* Allocate the memory for the request. */
806 request = (char *)alloca (strlen (command) + strlen (path)
809 + (port_maybe ? strlen (port_maybe) : 0)
810 + strlen (HTTP_ACCEPT)
811 + (request_keep_alive
812 ? strlen (request_keep_alive) : 0)
813 + (referer ? strlen (referer) : 0)
814 + (cookies ? strlen (cookies) : 0)
815 + (wwwauth ? strlen (wwwauth) : 0)
816 + (proxyauth ? strlen (proxyauth) : 0)
817 + (range ? strlen (range) : 0)
819 + (opt.user_header ? strlen (opt.user_header) : 0)
821 /* Construct the request. */
827 %s%s%s%s%s%s%s%s\r\n",
828 command, path, useragent, remhost,
829 port_maybe ? port_maybe : "",
831 request_keep_alive ? request_keep_alive : "",
832 referer ? referer : "",
833 cookies ? cookies : "",
834 wwwauth ? wwwauth : "",
835 proxyauth ? proxyauth : "",
838 opt.user_header ? opt.user_header : "");
839 DEBUGP (("---request begin---\n%s---request end---\n", request));
840 /* Free the temporary memory. */
841 FREE_MAYBE (wwwauth);
842 FREE_MAYBE (proxyauth);
843 FREE_MAYBE (cookies);
845 /* Send the request to server. */
847 if (u->proto == URLHTTPS)
848 num_written = ssl_iwrite (ssl, request, strlen (request));
850 #endif /* HAVE_SSL */
851 num_written = iwrite (sock, request, strlen (request));
855 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
857 CLOSE_INVALIDATE (sock);
860 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
861 u->proxy ? "Proxy" : "HTTP");
862 contlen = contrange = -1;
867 /* Before reading anything, initialize the rbuf. */
868 rbuf_initialize (&rbuf, sock);
870 if (u->proto == URLHTTPS)
874 #endif /* HAVE_SSL */
877 /* Header-fetching loop. */
885 /* Get the header. */
886 status = header_get (&rbuf, &hdr,
887 /* Disallow continuations for status line. */
888 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
890 /* Check for errors. */
891 if (status == HG_EOF && *hdr)
893 /* This used to be an unconditional error, but that was
894 somewhat controversial, because of a large number of
895 broken CGI's that happily "forget" to send the second EOL
896 before closing the connection of a HEAD request.
898 So, the deal is to check whether the header is empty
899 (*hdr is zero if it is); if yes, it means that the
900 previous header was fully retrieved, and that -- most
901 probably -- the request is complete. "...be liberal in
902 what you accept." Oh boy. */
903 logputs (LOG_VERBOSE, "\n");
904 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
907 FREE_MAYBE (hs->newloc);
908 FREE_MAYBE (all_headers);
909 CLOSE_INVALIDATE (sock);
912 else if (status == HG_ERROR)
914 logputs (LOG_VERBOSE, "\n");
915 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
919 FREE_MAYBE (hs->newloc);
920 FREE_MAYBE (all_headers);
921 CLOSE_INVALIDATE (sock);
925 /* If the headers are to be saved to a file later, save them to
927 if (opt.save_headers)
929 int lh = strlen (hdr);
930 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
931 memcpy (all_headers + all_length, hdr, lh);
933 all_headers[all_length++] = '\n';
934 all_headers[all_length] = '\0';
937 /* Print the header if requested. */
938 if (opt.server_response && hcount != 1)
939 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
941 /* Check for status line. */
945 /* Parse the first line of server response. */
946 statcode = parse_http_status_line (hdr, &error);
947 hs->statcode = statcode;
948 /* Store the descriptive response. */
949 if (statcode == -1) /* malformed response */
951 /* A common reason for "malformed response" error is the
952 case when no data was actually received. Handle this
955 hs->error = xstrdup (_("No data received"));
957 hs->error = xstrdup (_("Malformed status line"));
962 hs->error = xstrdup (_("(no description)"));
964 hs->error = xstrdup (error);
971 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
976 /* Exit on empty header. */
983 /* Try getting content-length. */
984 if (contlen == -1 && !opt.ignore_length)
985 if (header_process (hdr, "Content-Length", header_extract_number,
988 /* Try getting content-type. */
990 if (header_process (hdr, "Content-Type", http_process_type, &type))
992 /* Try getting location. */
994 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
996 /* Try getting last-modified. */
997 if (!hs->remote_time)
998 if (header_process (hdr, "Last-Modified", header_strdup,
1001 /* Try getting cookies. */
1003 if (header_process (hdr, "Set-Cookie", set_cookie_header_cb, u))
1005 /* Try getting www-authentication. */
1006 if (!authenticate_h)
1007 if (header_process (hdr, "WWW-Authenticate", header_strdup,
1010 /* Check for accept-ranges header. If it contains the word
1011 `none', disable the ranges. */
1012 if (*dt & ACCEPTRANGES)
1015 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1018 *dt &= ~ACCEPTRANGES;
1022 /* Try getting content-range. */
1023 if (contrange == -1)
1025 struct http_process_range_closure closure;
1026 if (header_process (hdr, "Content-Range", http_process_range, &closure))
1028 contrange = closure.first_byte_pos;
1032 /* Check for keep-alive related responses. */
1033 if (!inhibit_keep_alive)
1035 /* Check for the `Keep-Alive' header. */
1036 if (!http_keep_alive_1)
1038 if (header_process (hdr, "Keep-Alive", header_exists,
1039 &http_keep_alive_1))
1042 /* Check for `Connection: Keep-Alive'. */
1043 if (!http_keep_alive_2)
1045 if (header_process (hdr, "Connection", http_process_connection,
1046 &http_keep_alive_2))
1054 logputs (LOG_VERBOSE, "\n");
1057 && (http_keep_alive_1 || http_keep_alive_2))
1059 assert (inhibit_keep_alive == 0);
1063 /* The server has promised that it will not close the connection
1064 when we're done. This means that we can register it. */
1066 register_persistent (u->host, u->port, sock);
1068 register_persistent (u->host, u->port, sock, ssl);
1069 #endif /* HAVE_SSL */
1071 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1074 /* Authorization is required. */
1078 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1079 might be more bytes in the body. */
1080 if (auth_tried_already)
1082 /* If we have tried it already, then there is not point
1085 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1086 xfree (authenticate_h);
1089 else if (!known_authentication_scheme_p (authenticate_h))
1091 xfree (authenticate_h);
1092 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1095 else if (BEGINS_WITH (authenticate_h, "Basic"))
1097 /* The authentication scheme is basic, the one we try by
1098 default, and it failed. There's no sense in trying
1104 auth_tried_already = 1;
1108 /* We do not need this anymore. */
1111 xfree (authenticate_h);
1112 authenticate_h = NULL;
1115 /* 20x responses are counted among successful by default. */
1116 if (H_20X (statcode))
1119 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1122 /* We don't assume text/html by default. */
1125 if (opt.html_extension && (*dt & TEXTHTML))
1126 /* -E / --html-extension / html_extension = on was specified, and this is a
1127 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1128 already the file's suffix, tack on ".html". */
1130 char* last_period_in_local_filename = strrchr(u->local, '.');
1132 if (last_period_in_local_filename == NULL ||
1133 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1134 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1136 size_t local_filename_len = strlen(u->local);
1138 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1139 strcpy(u->local + local_filename_len, ".html");
1141 *dt |= ADDED_HTML_EXTENSION;
1145 if (contrange == -1)
1147 /* We did not get a content-range header. This means that the
1148 server did not honor our `Range' request. Normally, this
1149 means we should reset hs->restval and continue normally. */
1151 /* However, if `-c' is used, we need to be a bit more careful:
1153 1. If `-c' is specified and the file already existed when
1154 Wget was started, it would be a bad idea for us to start
1155 downloading it from scratch, effectively truncating it. I
1156 believe this cannot happen unless `-c' was specified.
1158 2. If `-c' is used on a file that is already fully
1159 downloaded, we're requesting bytes after the end of file,
1160 which can result in server not honoring `Range'. If this is
1161 the case, `Content-Length' will be equal to the length of the
1163 if (opt.always_rest)
1165 /* Check for condition #2. */
1166 if (hs->restval == contlen)
1168 logputs (LOG_VERBOSE, _("\
1169 \n The file is already fully retrieved; nothing to do.\n\n"));
1170 /* In case the caller inspects. */
1174 FREE_MAYBE (hs->newloc);
1175 FREE_MAYBE (all_headers);
1176 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1177 might be more bytes in the body. */
1178 return RETRFINISHED;
1181 /* Check for condition #1. */
1182 if (hs->no_truncate)
1184 logprintf (LOG_NOTQUIET,
1187 The server does not support continued download;\n\
1188 refusing to truncate `%s'.\n\n"), u->local);
1189 return CONTNOTSUPPORTED;
1198 else if (contrange != hs->restval ||
1199 (H_PARTIAL (statcode) && contrange == -1))
1201 /* This means the whole request was somehow misunderstood by the
1202 server. Bail out. */
1204 FREE_MAYBE (hs->newloc);
1205 FREE_MAYBE (all_headers);
1206 CLOSE_INVALIDATE (sock);
1213 contlen += contrange;
1215 contrange = -1; /* If conent-length was not sent,
1216 content-range will be ignored. */
1218 hs->contlen = contlen;
1220 /* Return if redirected. */
1221 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1223 /* RFC2068 says that in case of the 300 (multiple choices)
1224 response, the server can output a preferred URL through
1225 `Location' header; otherwise, the request should be treated
1226 like GET. So, if the location is set, it will be a
1227 redirection; otherwise, just proceed normally. */
1228 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1232 logprintf (LOG_VERBOSE,
1233 _("Location: %s%s\n"),
1234 hs->newloc ? hs->newloc : _("unspecified"),
1235 hs->newloc ? _(" [following]") : "");
1236 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1237 might be more bytes in the body. */
1239 FREE_MAYBE (all_headers);
1245 if ((*dt & RETROKF) && !opt.server_response)
1247 /* No need to print this output if the body won't be
1248 downloaded at all, or if the original server response is
1250 logputs (LOG_VERBOSE, _("Length: "));
1253 logputs (LOG_VERBOSE, legible (contlen));
1254 if (contrange != -1)
1255 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1256 legible (contlen - contrange));
1259 logputs (LOG_VERBOSE,
1260 opt.ignore_length ? _("ignored") : _("unspecified"));
1262 logprintf (LOG_VERBOSE, " [%s]\n", type);
1264 logputs (LOG_VERBOSE, "\n");
1268 type = NULL; /* We don't need it any more. */
1270 /* Return if we have no intention of further downloading. */
1271 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1273 /* In case the caller cares to look... */
1277 FREE_MAYBE (all_headers);
1278 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1279 might be more bytes in the body. */
1280 return RETRFINISHED;
1283 /* Open the local file. */
1286 mkalldirs (u->local);
1288 rotate_backups (u->local);
1289 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1292 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1293 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1294 might be more bytes in the body. */
1295 FREE_MAYBE (all_headers);
1301 extern int global_download_count;
1303 /* To ensure that repeated "from scratch" downloads work for -O
1304 files, we rewind the file pointer, unless restval is
1305 non-zero. (This works only when -O is used on regular files,
1306 but it's still a valuable feature.)
1308 However, this loses when more than one URL is specified on
1309 the command line the second rewinds eradicates the contents
1310 of the first download. Thus we disable the above trick for
1311 all the downloads except the very first one.
1313 #### A possible solution to this would be to remember the
1314 file position in the output document and to seek to that
1315 position, instead of rewinding. */
1316 if (!hs->restval && global_download_count == 0)
1318 /* This will silently fail for streams that don't correspond
1319 to regular files, but that's OK. */
1321 /* ftruncate is needed because opt.dfp is opened in append
1322 mode if opt.always_rest is set. */
1323 ftruncate (fileno (fp), 0);
1328 /* #### This confuses the code that checks for file size. There
1329 should be some overhead information. */
1330 if (opt.save_headers)
1331 fwrite (all_headers, 1, all_length, fp);
1333 /* Get the contents of the document. */
1334 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1335 (contlen != -1 ? contlen : 0),
1337 hs->dltime = elapsed_time ();
1339 /* Close or flush the file. We have to be careful to check for
1340 error here. Checking the result of fwrite() is not enough --
1341 errors could go unnoticed! */
1344 flush_res = fclose (fp);
1346 flush_res = fflush (fp);
1347 if (flush_res == EOF)
1350 FREE_MAYBE (all_headers);
1351 CLOSE_FINISH (sock);
1354 return RETRFINISHED;
1357 /* The genuine HTTP loop! This is the part where the retrieval is
1358 retried, and retried, and retried, and... */
1360 http_loop (struct urlinfo *u, char **newloc, int *dt)
1363 int use_ts, got_head = 0; /* time-stamping info */
1364 char *filename_plus_orig_suffix;
1365 char *local_filename = NULL;
1366 char *tms, *suf, *locf, *tmrate;
1368 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1369 long local_size = 0; /* the size of the local file */
1370 size_t filename_len;
1371 struct http_stat hstat; /* HTTP status */
1376 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1377 has_wildcards_p because it would also warn on `?', and we know that
1378 shows up in CGI paths a *lot*. */
1379 if (strchr (u->url, '*'))
1380 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1382 /* Determine the local filename. */
1384 u->local = url_filename (u->proxy ? u->proxy : u);
1386 if (!opt.output_document)
1389 locf = opt.output_document;
1391 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1392 xmalloc() here before EACH return. This is one reason it's better to set
1393 flags that influence flow control and then return once at the end. */
1394 filename_len = strlen(u->local);
1395 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1397 if (opt.noclobber && file_exists_p (u->local))
1399 /* If opt.noclobber is turned on and file already exists, do not
1400 retrieve the file */
1401 logprintf (LOG_VERBOSE, _("\
1402 File `%s' already there, will not retrieve.\n"), u->local);
1403 /* If the file is there, we suppose it's retrieved OK. */
1406 /* #### Bogusness alert. */
1407 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1408 text/html, a harmless lie. */
1409 if (((suf = suffix (u->local)) != NULL)
1410 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1413 xfree (filename_plus_orig_suffix); /* must precede every return! */
1414 /* Another harmless lie: */
1419 if (opt.timestamping)
1421 boolean local_dot_orig_file_exists = FALSE;
1423 if (opt.backup_converted)
1424 /* If -K is specified, we'll act on the assumption that it was specified
1425 last time these files were downloaded as well, and instead of just
1426 comparing local file X against server file X, we'll compare local
1427 file X.orig (if extant, else X) against server file X. If -K
1428 _wasn't_ specified last time, or the server contains files called
1429 *.orig, -N will be back to not operating correctly with -k. */
1431 /* Would a single s[n]printf() call be faster? --dan
1433 Definitely not. sprintf() is horribly slow. It's a
1434 different question whether the difference between the two
1435 affects a program. Usually I'd say "no", but at one
1436 point I profiled Wget, and found that a measurable and
1437 non-negligible amount of time was lost calling sprintf()
1438 in url.c. Replacing sprintf with inline calls to
1439 strcpy() and long_to_string() made a difference.
1441 strcpy(filename_plus_orig_suffix, u->local);
1442 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1444 /* Try to stat() the .orig file. */
1445 if (stat(filename_plus_orig_suffix, &st) == 0)
1447 local_dot_orig_file_exists = TRUE;
1448 local_filename = filename_plus_orig_suffix;
1452 if (!local_dot_orig_file_exists)
1453 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1454 if (stat (u->local, &st) == 0)
1455 local_filename = u->local;
1457 if (local_filename != NULL)
1458 /* There was a local file, so we'll check later to see if the version
1459 the server has is the same version we already have, allowing us to
1464 local_size = st.st_size;
1468 /* Reset the counter. */
1470 *dt = 0 | ACCEPTRANGES;
1474 /* Increment the pass counter. */
1476 sleep_between_retrievals (count);
1477 /* Get the current time string. */
1478 tms = time_str (NULL);
1479 /* Print fetch message, if opt.verbose. */
1482 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1486 sprintf (tmp, _("(try:%2d)"), count);
1487 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1488 tms, hurl, tmp, locf);
1490 ws_changetitle (hurl, 1);
1495 /* Default document type is empty. However, if spider mode is
1496 on or time-stamping is employed, HEAD_ONLY commands is
1497 encoded within *dt. */
1498 if (opt.spider || (use_ts && !got_head))
1502 /* Assume no restarting. */
1504 /* Decide whether or not to restart. */
1505 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1506 && file_exists_p (locf))
1507 if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1508 hstat.restval = st.st_size;
1509 /* Decide whether to send the no-cache directive. */
1510 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1511 *dt |= SEND_NOCACHE;
1513 *dt &= ~SEND_NOCACHE;
1515 /* Try fetching the document, or at least its head. :-) */
1516 err = gethttp (u, &hstat, dt);
1518 /* It's unfortunate that wget determines the local filename before finding
1519 out the Content-Type of the file. Barring a major restructuring of the
1520 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1521 u->local to tack on ".html". */
1522 if (!opt.output_document)
1525 locf = opt.output_document;
1527 /* In `-c' is used, check whether the file we're writing to
1528 exists before we've done anything. If so, we'll refuse to
1529 truncate it if the server doesn't support continued
1531 if (opt.always_rest)
1532 hstat.no_truncate = file_exists_p (locf);
1535 tms = time_str (NULL);
1536 /* Get the new location (with or without the redirection). */
1538 *newloc = xstrdup (hstat.newloc);
1541 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1542 case CONERROR: case READERR: case WRITEFAILED:
1544 /* Non-fatal errors continue executing the loop, which will
1545 bring them to "while" statement at the end, to judge
1546 whether the number of tries was exceeded. */
1548 printwhat (count, opt.ntry);
1551 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1552 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1553 /* Fatal errors just return from the function. */
1555 xfree (filename_plus_orig_suffix); /* must precede every return! */
1558 case FWRITEERR: case FOPENERR:
1559 /* Another fatal error. */
1560 logputs (LOG_VERBOSE, "\n");
1561 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1562 u->local, strerror (errno));
1567 /* Another fatal error. */
1568 logputs (LOG_VERBOSE, "\n");
1569 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1571 xfree (filename_plus_orig_suffix); /* must precede every return! */
1575 /* Return the new location to the caller. */
1578 logprintf (LOG_NOTQUIET,
1579 _("ERROR: Redirection (%d) without location.\n"),
1581 xfree (filename_plus_orig_suffix); /* must precede every return! */
1585 xfree (filename_plus_orig_suffix); /* must precede every return! */
1589 /* Deal with you later. */
1592 /* All possibilities should have been exhausted. */
1595 if (!(*dt & RETROKF))
1599 /* #### Ugly ugly ugly! */
1600 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1601 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1604 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1605 tms, hstat.statcode, hstat.error);
1606 logputs (LOG_VERBOSE, "\n");
1608 xfree (filename_plus_orig_suffix); /* must precede every return! */
1612 /* Did we get the time-stamp? */
1615 if (opt.timestamping && !hstat.remote_time)
1617 logputs (LOG_NOTQUIET, _("\
1618 Last-modified header missing -- time-stamps turned off.\n"));
1620 else if (hstat.remote_time)
1622 /* Convert the date-string into struct tm. */
1623 tmr = http_atotm (hstat.remote_time);
1624 if (tmr == (time_t) (-1))
1625 logputs (LOG_VERBOSE, _("\
1626 Last-modified header invalid -- time-stamp ignored.\n"));
1630 /* The time-stamping section. */
1635 use_ts = 0; /* no more time-stamping */
1636 count = 0; /* the retrieve count for HEAD is
1638 if (hstat.remote_time && tmr != (time_t) (-1))
1640 /* Now time-stamping can be used validly. Time-stamping
1641 means that if the sizes of the local and remote file
1642 match, and local file is newer than the remote file,
1643 it will not be retrieved. Otherwise, the normal
1644 download procedure is resumed. */
1646 (hstat.contlen == -1 || local_size == hstat.contlen))
1648 logprintf (LOG_VERBOSE, _("\
1649 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1652 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1655 else if (tml >= tmr)
1656 logprintf (LOG_VERBOSE, _("\
1657 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1659 logputs (LOG_VERBOSE,
1660 _("Remote file is newer, retrieving.\n"));
1665 if ((tmr != (time_t) (-1))
1667 && ((hstat.len == hstat.contlen) ||
1668 ((hstat.res == 0) &&
1669 ((hstat.contlen == -1) ||
1670 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1672 /* #### This code repeats in http.c and ftp.c. Move it to a
1674 const char *fl = NULL;
1675 if (opt.output_document)
1677 if (opt.od_known_regular)
1678 fl = opt.output_document;
1685 /* End of time-stamping section. */
1689 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1690 xfree (filename_plus_orig_suffix); /* must precede every return! */
1694 /* It is now safe to free the remainder of hstat, since the
1695 strings within it will no longer be used. */
1698 tmrate = rate (hstat.len - hstat.restval, hstat.dltime, 0);
1700 if (hstat.len == hstat.contlen)
1704 logprintf (LOG_VERBOSE,
1705 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1706 tms, tmrate, locf, hstat.len, hstat.contlen);
1707 logprintf (LOG_NONVERBOSE,
1708 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1709 tms, u->url, hstat.len, hstat.contlen, locf, count);
1712 downloaded_increase (hstat.len);
1714 /* Remember that we downloaded the file for later ".orig" code. */
1715 if (*dt & ADDED_HTML_EXTENSION)
1716 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1718 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1720 xfree(filename_plus_orig_suffix); /* must precede every return! */
1723 else if (hstat.res == 0) /* No read error */
1725 if (hstat.contlen == -1) /* We don't know how much we were supposed
1726 to get, so assume we succeeded. */
1730 logprintf (LOG_VERBOSE,
1731 _("%s (%s) - `%s' saved [%ld]\n\n"),
1732 tms, tmrate, locf, hstat.len);
1733 logprintf (LOG_NONVERBOSE,
1734 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1735 tms, u->url, hstat.len, locf, count);
1738 downloaded_increase (hstat.len);
1740 /* Remember that we downloaded the file for later ".orig" code. */
1741 if (*dt & ADDED_HTML_EXTENSION)
1742 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1744 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1746 xfree (filename_plus_orig_suffix); /* must precede every return! */
1749 else if (hstat.len < hstat.contlen) /* meaning we lost the
1750 connection too soon */
1752 logprintf (LOG_VERBOSE,
1753 _("%s (%s) - Connection closed at byte %ld. "),
1754 tms, tmrate, hstat.len);
1755 printwhat (count, opt.ntry);
1758 else if (!opt.kill_longer) /* meaning we got more than expected */
1760 logprintf (LOG_VERBOSE,
1761 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1762 tms, tmrate, locf, hstat.len, hstat.contlen);
1763 logprintf (LOG_NONVERBOSE,
1764 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1765 tms, u->url, hstat.len, hstat.contlen, locf, count);
1767 downloaded_increase (hstat.len);
1769 /* Remember that we downloaded the file for later ".orig" code. */
1770 if (*dt & ADDED_HTML_EXTENSION)
1771 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1773 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1775 xfree (filename_plus_orig_suffix); /* must precede every return! */
1778 else /* the same, but not accepted */
1780 logprintf (LOG_VERBOSE,
1781 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1782 tms, tmrate, hstat.len, hstat.contlen);
1783 printwhat (count, opt.ntry);
1787 else /* now hstat.res can only be -1 */
1789 if (hstat.contlen == -1)
1791 logprintf (LOG_VERBOSE,
1792 _("%s (%s) - Read error at byte %ld (%s)."),
1793 tms, tmrate, hstat.len, strerror (errno));
1794 printwhat (count, opt.ntry);
1797 else /* hstat.res == -1 and contlen is given */
1799 logprintf (LOG_VERBOSE,
1800 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1801 tms, tmrate, hstat.len, hstat.contlen,
1803 printwhat (count, opt.ntry);
1810 while (!opt.ntry || (count < opt.ntry));
1811 xfree (filename_plus_orig_suffix); /* must precede every return! */
1815 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1816 than local timezone (mktime assumes the latter).
1818 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1819 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1821 mktime_from_utc (struct tm *t)
1828 tb = mktime (gmtime (&tl));
1829 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1832 /* Check whether the result of strptime() indicates success.
1833 strptime() returns the pointer to how far it got to in the string.
1834 The processing has been successful if the string is at `GMT' or
1835 `+X', or at the end of the string.
1837 In extended regexp parlance, the function returns 1 if P matches
1838 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1839 strptime()) is considered a failure and 0 is returned. */
1841 check_end (const char *p)
1845 while (ISSPACE (*p))
1848 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1849 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
1855 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1856 the three formats RFC2068 allows the HTTP servers to emit --
1857 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1860 We use strptime() to recognize various dates, which makes it a
1861 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1862 allows shortened dates and months, one-digit days, etc.). It also
1863 allows more than one space anywhere where the specs require one SP.
1864 The routine should probably be even more forgiving (as recommended
1865 by RFC2068), but I do not have the time to write one.
1867 Return the computed time_t representation, or -1 if all the
1870 Needless to say, what we *really* need here is something like
1871 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1872 and does not use strptime(). atotm() is to be found in the sources
1873 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1875 http_atotm (char *time_string)
1879 /* Roger Beeman says: "This function dynamically allocates struct tm
1880 t, but does no initialization. The only field that actually
1881 needs initialization is tm_isdst, since the others will be set by
1882 strptime. Since strptime does not set tm_isdst, it will return
1883 the data structure with whatever data was in tm_isdst to begin
1884 with. For those of us in timezones where DST can occur, there
1885 can be a one hour shift depending on the previous contents of the
1886 data area where the data structure is allocated." */
1889 /* Note that under foreign locales Solaris strptime() fails to
1890 recognize English dates, which renders this function useless. I
1891 assume that other non-GNU strptime's are plagued by the same
1892 disease. We solve this by setting only LC_MESSAGES in
1893 i18n_initialize(), instead of LC_ALL.
1895 Another solution could be to temporarily set locale to C, invoke
1896 strptime(), and restore it back. This is slow and dirty,
1897 however, and locale support other than LC_MESSAGES can mess other
1898 things, so I rather chose to stick with just setting LC_MESSAGES.
1900 Also note that none of this is necessary under GNU strptime(),
1901 because it recognizes both international and local dates. */
1903 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1904 it to eat all white space up to (and including) a newline, and
1905 the function fails if there is no newline (!).
1907 Let's hope all strptime() implementations use ` ' to skip *all*
1908 whitespace instead of just one (it works that way on all the
1909 systems I've tested it on). */
1911 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1912 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1913 return mktime_from_utc (&t);
1914 /* RFC850: Thursday, 29-Jan-98 22:12:57 */
1915 if (check_end (strptime (time_string, "%A, %d-%b-%y %T", &t)))
1916 return mktime_from_utc (&t);
1917 /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
1918 (google.com uses this for their cookies.)*/
1919 if (check_end (strptime (time_string, "%a, %d-%b-%Y %T", &t)))
1920 return mktime_from_utc (&t);
1921 /* asctime: Thu Jan 29 22:12:57 1998 */
1922 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1923 return mktime_from_utc (&t);
1928 /* Authorization support: We support two authorization schemes:
1930 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1932 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1933 consisting of answering to the server's challenge with the proper
1936 /* How many bytes it will take to store LEN bytes in base64. */
1937 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1939 /* Encode the string S of length LENGTH to base64 format and place it
1940 to STORE. STORE will be 0-terminated, and must point to a writable
1941 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1943 base64_encode (const char *s, char *store, int length)
1945 /* Conversion table. */
1946 static char tbl[64] = {
1947 'A','B','C','D','E','F','G','H',
1948 'I','J','K','L','M','N','O','P',
1949 'Q','R','S','T','U','V','W','X',
1950 'Y','Z','a','b','c','d','e','f',
1951 'g','h','i','j','k','l','m','n',
1952 'o','p','q','r','s','t','u','v',
1953 'w','x','y','z','0','1','2','3',
1954 '4','5','6','7','8','9','+','/'
1957 unsigned char *p = (unsigned char *)store;
1959 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1960 for (i = 0; i < length; i += 3)
1962 *p++ = tbl[s[0] >> 2];
1963 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1964 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1965 *p++ = tbl[s[2] & 0x3f];
1968 /* Pad the result if necessary... */
1969 if (i == length + 1)
1971 else if (i == length + 2)
1972 *(p - 1) = *(p - 2) = '=';
1973 /* ...and zero-terminate it. */
1977 /* Create the authentication header contents for the `Basic' scheme.
1978 This is done by encoding the string `USER:PASS' in base64 and
1979 prepending `HEADER: Basic ' to it. */
1981 basic_authentication_encode (const char *user, const char *passwd,
1984 char *t1, *t2, *res;
1985 int len1 = strlen (user) + 1 + strlen (passwd);
1986 int len2 = BASE64_LENGTH (len1);
1988 t1 = (char *)alloca (len1 + 1);
1989 sprintf (t1, "%s:%s", user, passwd);
1990 t2 = (char *)alloca (1 + len2);
1991 base64_encode (t1, t2, len1);
1992 res = (char *)xmalloc (len2 + 11 + strlen (header));
1993 sprintf (res, "%s: Basic %s\r\n", header, t2);
1999 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2000 of a field in such a header. If the field is the one specified by
2001 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2002 digest authorization code), extract its value in the (char*)
2003 variable pointed by RET. Returns negative on a malformed header,
2004 or number of bytes that have been parsed by this call. */
2006 extract_header_attr (const char *au, const char *attr_name, char **ret)
2008 const char *cp, *ep;
2012 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2014 cp += strlen (attr_name);
2017 cp += skip_lws (cp);
2022 cp += skip_lws (cp);
2027 for (ep = cp; *ep && *ep != '\"'; ep++)
2032 *ret = strdupdelim (cp, ep);
2039 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
2040 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
2041 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
2043 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2044 an array of 16 bytes containing the hash keys, and BUF should be a
2045 buffer of 33 writable characters (32 for hex digits plus one for
2046 zero termination). */
2048 dump_hash (unsigned char *buf, const unsigned char *hash)
2052 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2054 *buf++ = HEXD2asc (*hash >> 4);
2055 *buf++ = HEXD2asc (*hash & 0xf);
2060 /* Take the line apart to find the challenge, and compose a digest
2061 authorization header. See RFC2069 section 2.1.2. */
2063 digest_authentication_encode (const char *au, const char *user,
2064 const char *passwd, const char *method,
2067 static char *realm, *opaque, *nonce;
2072 { "realm", &realm },
2073 { "opaque", &opaque },
2078 realm = opaque = nonce = NULL;
2080 au += 6; /* skip over `Digest' */
2085 au += skip_lws (au);
2086 for (i = 0; i < ARRAY_SIZE (options); i++)
2088 int skip = extract_header_attr (au, options[i].name,
2089 options[i].variable);
2093 FREE_MAYBE (opaque);
2103 if (i == ARRAY_SIZE (options))
2105 while (*au && *au != '=')
2109 au += skip_lws (au);
2113 while (*au && *au != '\"')
2120 while (*au && *au != ',')
2125 if (!realm || !nonce || !user || !passwd || !path || !method)
2128 FREE_MAYBE (opaque);
2133 /* Calculate the digest value. */
2136 unsigned char hash[MD5_HASHLEN];
2137 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2138 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2140 /* A1BUF = H(user ":" realm ":" password) */
2141 md5_init_ctx (&ctx);
2142 md5_process_bytes (user, strlen (user), &ctx);
2143 md5_process_bytes (":", 1, &ctx);
2144 md5_process_bytes (realm, strlen (realm), &ctx);
2145 md5_process_bytes (":", 1, &ctx);
2146 md5_process_bytes (passwd, strlen (passwd), &ctx);
2147 md5_finish_ctx (&ctx, hash);
2148 dump_hash (a1buf, hash);
2150 /* A2BUF = H(method ":" path) */
2151 md5_init_ctx (&ctx);
2152 md5_process_bytes (method, strlen (method), &ctx);
2153 md5_process_bytes (":", 1, &ctx);
2154 md5_process_bytes (path, strlen (path), &ctx);
2155 md5_finish_ctx (&ctx, hash);
2156 dump_hash (a2buf, hash);
2158 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2159 md5_init_ctx (&ctx);
2160 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2161 md5_process_bytes (":", 1, &ctx);
2162 md5_process_bytes (nonce, strlen (nonce), &ctx);
2163 md5_process_bytes (":", 1, &ctx);
2164 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2165 md5_finish_ctx (&ctx, hash);
2166 dump_hash (response_digest, hash);
2168 res = (char*) xmalloc (strlen (user)
2173 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2174 + (opaque ? strlen (opaque) : 0)
2176 sprintf (res, "Authorization: Digest \
2177 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2178 user, realm, nonce, path, response_digest);
2181 char *p = res + strlen (res);
2182 strcat (p, ", opaque=\"");
2186 strcat (res, "\r\n");
2190 #endif /* USE_DIGEST */
2193 #define BEGINS_WITH(line, string_constant) \
2194 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2195 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2196 || !line[sizeof (string_constant) - 1]))
2199 known_authentication_scheme_p (const char *au)
2201 return BEGINS_WITH (au, "Basic")
2202 || BEGINS_WITH (au, "Digest")
2203 || BEGINS_WITH (au, "NTLM");
2208 /* Create the HTTP authorization request header. When the
2209 `WWW-Authenticate' response header is seen, according to the
2210 authorization scheme specified in that header (`Basic' and `Digest'
2211 are supported by the current implementation), produce an
2212 appropriate HTTP authorization request header. */
2214 create_authorization_line (const char *au, const char *user,
2215 const char *passwd, const char *method,
2218 char *wwwauth = NULL;
2220 if (!strncasecmp (au, "Basic", 5))
2221 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2222 if (!strncasecmp (au, "NTLM", 4))
2223 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2225 else if (!strncasecmp (au, "Digest", 6))
2226 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2227 #endif /* USE_DIGEST */