2 Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables. You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL". If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so. If you do not wish to do
29 so, delete this exception statement from your version. */
35 #include <sys/types.h>
46 #if TIME_WITH_SYS_TIME
47 # include <sys/time.h>
51 # include <sys/time.h>
68 # include "gen_sslfunc.h"
75 extern char *version_string;
81 static int cookies_loaded_p;
82 struct cookie_jar *wget_cookie_jar;
84 #define TEXTHTML_S "text/html"
85 #define HTTP_ACCEPT "*/*"
87 /* Some status code validation macros: */
88 #define H_20X(x) (((x) >= 200) && ((x) < 300))
89 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
90 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
91 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
93 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
95 #define HTTP_STATUS_OK 200
96 #define HTTP_STATUS_CREATED 201
97 #define HTTP_STATUS_ACCEPTED 202
98 #define HTTP_STATUS_NO_CONTENT 204
99 #define HTTP_STATUS_PARTIAL_CONTENTS 206
101 /* Redirection 3xx. */
102 #define HTTP_STATUS_MULTIPLE_CHOICES 300
103 #define HTTP_STATUS_MOVED_PERMANENTLY 301
104 #define HTTP_STATUS_MOVED_TEMPORARILY 302
105 #define HTTP_STATUS_NOT_MODIFIED 304
107 /* Client error 4xx. */
108 #define HTTP_STATUS_BAD_REQUEST 400
109 #define HTTP_STATUS_UNAUTHORIZED 401
110 #define HTTP_STATUS_FORBIDDEN 403
111 #define HTTP_STATUS_NOT_FOUND 404
113 /* Server errors 5xx. */
114 #define HTTP_STATUS_INTERNAL 500
115 #define HTTP_STATUS_NOT_IMPLEMENTED 501
116 #define HTTP_STATUS_BAD_GATEWAY 502
117 #define HTTP_STATUS_UNAVAILABLE 503
120 /* Parse the HTTP status line, which is of format:
122 HTTP-Version SP Status-Code SP Reason-Phrase
124 The function returns the status-code, or -1 if the status line is
125 malformed. The pointer to reason-phrase is returned in RP. */
127 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
129 /* (the variables must not be named `major' and `minor', because
130 that breaks compilation with SunOS4 cc.) */
131 int mjr, mnr, statcode;
134 *reason_phrase_ptr = NULL;
136 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
137 major version, and Y is minor version. */
138 if (strncmp (line, "HTTP/", 5) != 0)
142 /* Calculate major HTTP version. */
144 for (mjr = 0; ISDIGIT (*line); line++)
145 mjr = 10 * mjr + (*line - '0');
146 if (*line != '.' || p == line)
150 /* Calculate minor HTTP version. */
152 for (mnr = 0; ISDIGIT (*line); line++)
153 mnr = 10 * mnr + (*line - '0');
154 if (*line != ' ' || p == line)
156 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
157 minor version can be safely ignored. */
162 /* Calculate status code. */
163 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
165 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
167 /* Set up the reason phrase pointer. */
169 /* RFC2068 requires SPC here, but we allow the string to finish
170 here, in case no reason-phrase is present. */
174 *reason_phrase_ptr = line;
179 *reason_phrase_ptr = line + 1;
184 #define WMIN(x, y) ((x) > (y) ? (y) : (x))
186 /* Send the contents of FILE_NAME to SOCK/SSL. Make sure that exactly
187 PROMISED_SIZE bytes are sent over the wire -- if the file is
188 longer, read only that much; if the file is shorter, report an error. */
191 post_file (int sock, void *ssl, const char *file_name, long promised_size)
193 static char chunk[8192];
198 /* Only one of SOCK and SSL may be active at the same time. */
199 assert (sock > -1 || ssl != NULL);
200 assert (sock == -1 || ssl == NULL);
202 DEBUGP (("[writing POST file %s ... ", file_name));
204 fp = fopen (file_name, "rb");
207 while (!feof (fp) && written < promised_size)
210 int length = fread (chunk, 1, sizeof (chunk), fp);
213 towrite = WMIN (promised_size - written, length);
216 write_error = ssl_iwrite (ssl, chunk, towrite);
219 write_error = iwrite (sock, chunk, towrite);
229 /* If we've written less than was promised, report a (probably
230 nonsensical) error rather than break the promise. */
231 if (written < promised_size)
237 assert (written == promised_size);
238 DEBUGP (("done]\n"));
242 /* Functions to be used as arguments to header_process(): */
244 struct http_process_range_closure {
250 /* Parse the `Content-Range' header and extract the information it
251 contains. Returns 1 if successful, -1 otherwise. */
253 http_process_range (const char *hdr, void *arg)
255 struct http_process_range_closure *closure
256 = (struct http_process_range_closure *)arg;
259 /* Certain versions of Nutscape proxy server send out
260 `Content-Length' without "bytes" specifier, which is a breach of
261 RFC2068 (as well as the HTTP/1.1 draft which was current at the
262 time). But hell, I must support it... */
263 if (!strncasecmp (hdr, "bytes", 5))
266 /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
270 hdr += skip_lws (hdr);
276 for (num = 0; ISDIGIT (*hdr); hdr++)
277 num = 10 * num + (*hdr - '0');
278 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
280 closure->first_byte_pos = num;
282 for (num = 0; ISDIGIT (*hdr); hdr++)
283 num = 10 * num + (*hdr - '0');
284 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
286 closure->last_byte_pos = num;
288 for (num = 0; ISDIGIT (*hdr); hdr++)
289 num = 10 * num + (*hdr - '0');
290 closure->entity_length = num;
294 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
295 Used for `Accept-Ranges'. */
297 http_process_none (const char *hdr, void *arg)
299 int *where = (int *)arg;
301 if (strstr (hdr, "none"))
308 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
310 http_process_type (const char *hdr, void *arg)
312 char **result = (char **)arg;
313 /* Locate P on `;' or the terminating zero, whichever comes first. */
314 const char *p = strchr (hdr, ';');
316 p = hdr + strlen (hdr);
317 while (p > hdr && ISSPACE (*(p - 1)))
319 *result = strdupdelim (hdr, p);
323 /* Check whether the `Connection' header is set to "keep-alive". */
325 http_process_connection (const char *hdr, void *arg)
327 int *flag = (int *)arg;
328 if (!strcasecmp (hdr, "Keep-Alive"))
333 /* Commit the cookie to the cookie jar. */
336 http_process_set_cookie (const char *hdr, void *arg)
338 struct url *u = (struct url *)arg;
340 /* The jar should have been created by now. */
341 assert (wget_cookie_jar != NULL);
343 cookie_jar_process_set_cookie (wget_cookie_jar, u->host, u->port, u->path,
349 /* Persistent connections. Currently, we cache the most recently used
350 connection as persistent, provided that the HTTP server agrees to
351 make it such. The persistence data is stored in the variables
352 below. Ideally, it would be in a structure, and it should be
353 possible to cache an arbitrary fixed number of these connections.
355 I think the code is quite easy to extend in that direction. */
357 /* Whether a persistent connection is active. */
358 static int pc_active_p;
359 /* Host and port of currently active persistent connection. */
360 static struct address_list *pc_last_host_ip;
361 static unsigned short pc_last_port;
363 /* File descriptor of the currently active persistent connection. */
364 static int pc_last_fd;
367 /* Whether a ssl handshake has occoured on this connection */
368 static int pc_active_ssl;
369 /* SSL connection of the currently active persistent connection. */
370 static SSL *pc_last_ssl;
371 #endif /* HAVE_SSL */
373 /* Mark the persistent connection as invalid. This is used by the
374 CLOSE_* macros after they forcefully close a registered persistent
375 connection. This does not close the file descriptor -- it is left
376 to the caller to do that. (Maybe it should, though.) */
379 invalidate_persistent (void)
384 #endif /* HAVE_SSL */
385 if (pc_last_host_ip != NULL)
387 address_list_release (pc_last_host_ip);
388 pc_last_host_ip = NULL;
390 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
393 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
394 persistent. This will enable someone to use the same connection
395 later. In the context of HTTP, this must be called only AFTER the
396 response has been received and the server has promised that the
397 connection will remain alive.
399 If a previous connection was persistent, it is closed. */
403 register_persistent (const char *host, unsigned short port, int fd, SSL *ssl)
407 register_persistent (const char *host, unsigned short port, int fd)
412 if (pc_last_fd == fd)
414 /* The connection FD is already registered. Nothing to
420 /* The old persistent connection is still active; let's
421 close it first. This situation arises whenever a
422 persistent connection exists, but we then connect to a
423 different host, and try to register a persistent
424 connection to that one. */
426 /* The ssl disconnect has to take place before the closing
429 shutdown_ssl(pc_last_ssl);
432 invalidate_persistent ();
436 assert (pc_last_host_ip == NULL);
438 /* This lookup_host cannot fail, because it has the results in the
440 pc_last_host_ip = lookup_host (host, 1);
441 assert (pc_last_host_ip != NULL);
448 pc_active_ssl = ssl ? 1 : 0;
450 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
454 # define SHUTDOWN_SSL(ssl) do { \
456 shutdown_ssl (ssl); \
459 # define SHUTDOWN_SSL(ssl)
462 /* Return non-zero if a persistent connection is available for
463 connecting to HOST:PORT. */
467 persistent_available_p (const char *host, unsigned short port, int ssl)
471 persistent_available_p (const char *host, unsigned short port)
475 struct address_list *this_host_ip;
477 /* First, check whether a persistent connection is active at all. */
480 /* Second, check if the active connection pertains to the correct
481 (HOST, PORT) ordered pair. */
482 if (port != pc_last_port)
486 /* Second, a): check if current connection is (not) ssl, too. This
487 test is unlikely to fail because HTTP and HTTPS typicaly use
488 different ports. Yet it is possible, or so I [Christian
489 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
491 if (ssl != pc_active_ssl)
493 #endif /* HAVE_SSL */
495 this_host_ip = lookup_host (host, 1);
499 /* To equate the two host names for the purposes of persistent
500 connections, they need to share all the IP addresses in the
502 success = address_list_match_all (pc_last_host_ip, this_host_ip);
503 address_list_release (this_host_ip);
507 /* Third: check whether the connection is still open. This is
508 important because most server implement a liberal (short) timeout
509 on persistent connections. Wget can of course always reconnect
510 if the connection doesn't work out, but it's nicer to know in
511 advance. This test is a logical followup of the first test, but
512 is "expensive" and therefore placed at the end of the list. */
513 if (!test_socket_open (pc_last_fd))
515 /* Oops, the socket is no longer open. Now that we know that,
516 let's invalidate the persistent connection before returning
520 SHUTDOWN_SSL (pc_last_ssl);
523 invalidate_persistent ();
529 /* The idea behind these two CLOSE macros is to distinguish between
530 two cases: one when the job we've been doing is finished, and we
531 want to close the connection and leave, and two when something is
532 seriously wrong and we're closing the connection as part of
535 In case of keep_alive, CLOSE_FINISH should leave the connection
536 open, while CLOSE_INVALIDATE should still close it.
538 Note that the semantics of the flag `keep_alive' is "this
539 connection *will* be reused (the server has promised not to close
540 the connection once we're done)", while the semantics of
541 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
542 active, registered connection". */
544 #define CLOSE_FINISH(fd) do { \
547 SHUTDOWN_SSL (ssl); \
549 if (pc_active_p && (fd) == pc_last_fd) \
550 invalidate_persistent (); \
554 #define CLOSE_INVALIDATE(fd) do { \
555 SHUTDOWN_SSL (ssl); \
557 if (pc_active_p && (fd) == pc_last_fd) \
558 invalidate_persistent (); \
563 long len; /* received length */
564 long contlen; /* expected length */
565 long restval; /* the restart value */
566 int res; /* the result of last read */
567 char *newloc; /* new location (redirection) */
568 char *remote_time; /* remote time-stamp string */
569 char *error; /* textual HTTP error */
570 int statcode; /* status code */
571 double dltime; /* time of the download in msecs */
572 int no_truncate; /* whether truncating the file is
574 const char *referer; /* value of the referer header. */
575 char **local_file; /* local file. */
579 free_hstat (struct http_stat *hs)
581 FREE_MAYBE (hs->newloc);
582 FREE_MAYBE (hs->remote_time);
583 FREE_MAYBE (hs->error);
585 /* Guard against being called twice. */
587 hs->remote_time = NULL;
591 static char *create_authorization_line PARAMS ((const char *, const char *,
592 const char *, const char *,
594 static char *basic_authentication_encode PARAMS ((const char *, const char *,
596 static int known_authentication_scheme_p PARAMS ((const char *));
598 time_t http_atotm PARAMS ((const char *));
600 #define BEGINS_WITH(line, string_constant) \
601 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
602 && (ISSPACE (line[sizeof (string_constant) - 1]) \
603 || !line[sizeof (string_constant) - 1]))
605 /* Retrieve a document through HTTP protocol. It recognizes status
606 code, and correctly handles redirections. It closes the network
607 socket. If it receives an error from the functions below it, it
608 will print it if there is enough information to do so (almost
609 always), returning the error to the caller (i.e. http_loop).
611 Various HTTP parameters are stored to hs. Although it parses the
612 response code correctly, it is not used in a sane way. The caller
615 If PROXY is non-NULL, the connection will be made to the proxy
616 server, and u->url will be requested. */
618 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
620 char *request, *type, *command, *full_path;
622 char *pragma_h, *referer, *useragent, *range, *wwwauth;
623 char *authenticate_h;
627 char *request_keep_alive;
628 int sock, hcount, all_length, statcode;
630 long contlen, contrange;
633 int auth_tried_already;
636 static SSL_CTX *ssl_ctx = NULL;
639 char *cookies = NULL;
641 /* Whether this connection will be kept alive after the HTTP request
645 /* Flags that detect the two ways of specifying HTTP keep-alive
647 int http_keep_alive_1, http_keep_alive_2;
649 /* Whether keep-alive should be inhibited. */
650 int inhibit_keep_alive;
652 /* Whether we need to print the host header with braces around host,
653 e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the usual
654 "Host: symbolic-name:1234". */
655 int squares_around_host = 0;
657 /* Headers sent when using POST. */
658 char *post_content_type, *post_content_length;
659 long post_data_size = 0;
662 /* initialize ssl_ctx on first run */
665 uerr_t err = init_ssl (&ssl_ctx);
670 case SSLERRCTXCREATE:
672 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
676 /* try without certfile */
677 logprintf (LOG_NOTQUIET,
678 _("Failed to load certificates from %s\n"),
681 logprintf (LOG_NOTQUIET,
682 _("Trying without the specified certificate\n"));
685 logprintf (LOG_NOTQUIET,
686 _("Failed to get certificate key from %s\n"),
689 logprintf (LOG_NOTQUIET,
690 _("Trying without the specified certificate\n"));
697 #endif /* HAVE_SSL */
699 if (!(*dt & HEAD_ONLY))
700 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
701 know the local filename so we can save to it. */
702 assert (*hs->local_file != NULL);
705 auth_tried_already = 0;
707 inhibit_keep_alive = !opt.http_keep_alive || proxy != NULL;
710 /* We need to come back here when the initial attempt to retrieve
711 without authorization header fails. (Expected to happen at least
712 for the Digest authorization scheme.) */
715 http_keep_alive_1 = http_keep_alive_2 = 0;
717 post_content_type = NULL;
718 post_content_length = NULL;
720 /* Initialize certain elements of struct http_stat. */
725 hs->remote_time = NULL;
728 /* If we're using a proxy, we will be connecting to the proxy
730 conn = proxy ? proxy : u;
732 /* First: establish the connection. */
733 if (inhibit_keep_alive
736 !persistent_available_p (conn->host, conn->port)
738 !persistent_available_p (conn->host, conn->port,
739 u->scheme == SCHEME_HTTPS)
740 #endif /* HAVE_SSL */
743 struct address_list *al = lookup_host (conn->host, 0);
746 set_connection_host_name (conn->host);
747 sock = connect_to_many (al, conn->port, 0);
748 set_connection_host_name (NULL);
749 address_list_release (al);
752 return CONNECT_ERROR (errno);
755 if (conn->scheme == SCHEME_HTTPS)
756 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
758 logputs (LOG_VERBOSE, "\n");
759 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
764 #endif /* HAVE_SSL */
768 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"),
769 conn->host, conn->port);
770 /* #### pc_last_fd should be accessed through an accessor
775 #endif /* HAVE_SSL */
776 DEBUGP (("Reusing fd %d.\n", sock));
781 else if (opt.post_file_name || opt.post_data)
789 referer = (char *)alloca (9 + strlen (hs->referer) + 3);
790 sprintf (referer, "Referer: %s\r\n", hs->referer);
793 if (*dt & SEND_NOCACHE)
794 pragma_h = "Pragma: no-cache\r\n";
800 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
801 /* Gag me! Some servers (e.g. WebSitePro) have been known to
802 respond to the following `Range' format by generating a
803 multipart/x-byte-ranges MIME document! This MIME type was
804 present in an old draft of the byteranges specification.
805 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
806 only if multiple non-overlapping ranges are requested --
807 which Wget never does. */
808 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
813 STRDUP_ALLOCA (useragent, opt.useragent);
816 useragent = (char *)alloca (10 + strlen (version_string));
817 sprintf (useragent, "Wget/%s", version_string);
819 /* Construct the authentication, if userid is present. */
822 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
823 user = user ? user : opt.http_user;
824 passwd = passwd ? passwd : opt.http_passwd;
831 /* We have the username and the password, but haven't tried
832 any authorization yet. Let's see if the "Basic" method
833 works. If not, we'll come back here and construct a
834 proper authorization method with the right challenges.
836 If we didn't employ this kind of logic, every URL that
837 requires authorization would have to be processed twice,
838 which is very suboptimal and generates a bunch of false
839 "unauthorized" errors in the server log.
841 #### But this logic also has a serious problem when used
842 with stronger authentications: we *first* transmit the
843 username and the password in clear text, and *then*
844 attempt a stronger authentication scheme. That cannot be
845 right! We are only fortunate that almost everyone still
846 uses the `Basic' scheme anyway.
848 There should be an option to prevent this from happening,
849 for those who use strong authentication schemes and value
851 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
855 /* Use the full path, i.e. one that includes the leading
856 slash and the query string, but is independent of proxy
858 char *pth = url_full_path (u);
859 wwwauth = create_authorization_line (authenticate_h, user, passwd,
868 char *proxy_user, *proxy_passwd;
869 /* For normal username and password, URL components override
870 command-line/wgetrc parameters. With proxy authentication,
871 it's the reverse, because proxy URLs are normally the
872 "permanent" ones, so command-line args should take
874 if (opt.proxy_user && opt.proxy_passwd)
876 proxy_user = opt.proxy_user;
877 proxy_passwd = opt.proxy_passwd;
881 proxy_user = proxy->user;
882 proxy_passwd = proxy->passwd;
884 /* #### This does not appear right. Can't the proxy request,
885 say, `Digest' authentication? */
886 if (proxy_user && proxy_passwd)
887 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
888 "Proxy-Authorization");
891 /* String of the form :PORT. Used only for non-standard ports. */
893 if (u->port != scheme_default_port (u->scheme))
895 port_maybe = (char *)alloca (numdigit (u->port) + 2);
896 sprintf (port_maybe, ":%d", u->port);
899 if (!inhibit_keep_alive)
900 request_keep_alive = "Connection: Keep-Alive\r\n";
902 request_keep_alive = NULL;
905 cookies = cookie_jar_generate_cookie_header (wget_cookie_jar, u->host,
908 u->scheme == SCHEME_HTTPS
914 if (opt.post_data || opt.post_file_name)
916 post_content_type = "Content-Type: application/x-www-form-urlencoded\r\n";
918 post_data_size = strlen (opt.post_data);
921 post_data_size = file_size (opt.post_file_name);
922 if (post_data_size == -1)
924 logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
929 post_content_length = xmalloc (16 + numdigit (post_data_size) + 2 + 1);
930 sprintf (post_content_length,
931 "Content-Length: %ld\r\n", post_data_size);
935 full_path = xstrdup (u->url);
937 /* Use the full path, i.e. one that includes the leading slash and
938 the query string. E.g. if u->path is "foo/bar" and u->query is
939 "param=value", full_path will be "/foo/bar?param=value". */
940 full_path = url_full_path (u);
942 if (strchr (u->host, ':'))
943 squares_around_host = 1;
945 /* Allocate the memory for the request. */
946 request = (char *)alloca (strlen (command)
950 + (port_maybe ? strlen (port_maybe) : 0)
951 + strlen (HTTP_ACCEPT)
952 + (request_keep_alive
953 ? strlen (request_keep_alive) : 0)
954 + (referer ? strlen (referer) : 0)
955 + (cookies ? strlen (cookies) : 0)
956 + (wwwauth ? strlen (wwwauth) : 0)
957 + (proxyauth ? strlen (proxyauth) : 0)
958 + (range ? strlen (range) : 0)
961 ? strlen (post_content_type) : 0)
962 + (post_content_length
963 ? strlen (post_content_length) : 0)
964 + (opt.user_header ? strlen (opt.user_header) : 0)
966 /* Construct the request. */
972 %s%s%s%s%s%s%s%s%s%s\r\n",
975 squares_around_host ? "[" : "", u->host, squares_around_host ? "]" : "",
976 port_maybe ? port_maybe : "",
978 request_keep_alive ? request_keep_alive : "",
979 referer ? referer : "",
980 cookies ? cookies : "",
981 wwwauth ? wwwauth : "",
982 proxyauth ? proxyauth : "",
985 post_content_type ? post_content_type : "",
986 post_content_length ? post_content_length : "",
987 opt.user_header ? opt.user_header : "");
988 DEBUGP (("---request begin---\n%s", request));
990 /* Free the temporary memory. */
991 FREE_MAYBE (wwwauth);
992 FREE_MAYBE (proxyauth);
993 FREE_MAYBE (cookies);
996 /* Send the request to server. */
998 if (conn->scheme == SCHEME_HTTPS)
999 write_error = ssl_iwrite (ssl, request, strlen (request));
1002 write_error = iwrite (sock, request, strlen (request));
1004 if (write_error >= 0)
1008 DEBUGP (("[POST data: %s]\n", opt.post_data));
1010 if (conn->scheme == SCHEME_HTTPS)
1011 write_error = ssl_iwrite (ssl, opt.post_data, post_data_size);
1014 write_error = iwrite (sock, opt.post_data, post_data_size);
1016 else if (opt.post_file_name)
1019 if (conn->scheme == SCHEME_HTTPS)
1020 write_error = post_file (-1, ssl, opt.post_file_name,
1024 write_error = post_file (sock, NULL, opt.post_file_name,
1028 DEBUGP (("---request end---\n"));
1030 if (write_error < 0)
1032 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1034 CLOSE_INVALIDATE (sock);
1037 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1038 proxy ? "Proxy" : "HTTP");
1039 contlen = contrange = -1;
1044 /* Before reading anything, initialize the rbuf. */
1045 rbuf_initialize (&rbuf, sock);
1047 if (conn->scheme == SCHEME_HTTPS)
1051 #endif /* HAVE_SSL */
1054 /* Header-fetching loop. */
1062 /* Get the header. */
1063 status = header_get (&rbuf, &hdr,
1064 /* Disallow continuations for status line. */
1065 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
1067 /* Check for errors. */
1068 if (status == HG_EOF && *hdr)
1070 /* This used to be an unconditional error, but that was
1071 somewhat controversial, because of a large number of
1072 broken CGI's that happily "forget" to send the second EOL
1073 before closing the connection of a HEAD request.
1075 So, the deal is to check whether the header is empty
1076 (*hdr is zero if it is); if yes, it means that the
1077 previous header was fully retrieved, and that -- most
1078 probably -- the request is complete. "...be liberal in
1079 what you accept." Oh boy. */
1080 logputs (LOG_VERBOSE, "\n");
1081 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
1084 FREE_MAYBE (all_headers);
1085 CLOSE_INVALIDATE (sock);
1088 else if (status == HG_ERROR)
1090 logputs (LOG_VERBOSE, "\n");
1091 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1095 FREE_MAYBE (all_headers);
1096 CLOSE_INVALIDATE (sock);
1100 /* If the headers are to be saved to a file later, save them to
1102 if (opt.save_headers)
1104 int lh = strlen (hdr);
1105 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
1106 memcpy (all_headers + all_length, hdr, lh);
1108 all_headers[all_length++] = '\n';
1109 all_headers[all_length] = '\0';
1112 /* Check for status line. */
1116 /* Parse the first line of server response. */
1117 statcode = parse_http_status_line (hdr, &error);
1118 hs->statcode = statcode;
1119 /* Store the descriptive response. */
1120 if (statcode == -1) /* malformed response */
1122 /* A common reason for "malformed response" error is the
1123 case when no data was actually received. Handle this
1126 hs->error = xstrdup (_("No data received"));
1128 hs->error = xstrdup (_("Malformed status line"));
1133 hs->error = xstrdup (_("(no description)"));
1135 hs->error = xstrdup (error);
1137 if ((statcode != -1)
1143 if (opt.server_response)
1144 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1146 logprintf (LOG_VERBOSE, "%2d %s", statcode, error);
1152 /* Exit on empty header. */
1159 /* Print the header if requested. */
1160 if (opt.server_response && hcount != 1)
1161 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1163 /* Try getting content-length. */
1164 if (contlen == -1 && !opt.ignore_length)
1165 if (header_process (hdr, "Content-Length", header_extract_number,
1168 /* Try getting content-type. */
1170 if (header_process (hdr, "Content-Type", http_process_type, &type))
1172 /* Try getting location. */
1174 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
1176 /* Try getting last-modified. */
1177 if (!hs->remote_time)
1178 if (header_process (hdr, "Last-Modified", header_strdup,
1181 /* Try getting cookies. */
1183 if (header_process (hdr, "Set-Cookie", http_process_set_cookie, u))
1185 /* Try getting www-authentication. */
1186 if (!authenticate_h)
1187 if (header_process (hdr, "WWW-Authenticate", header_strdup,
1190 /* Check for accept-ranges header. If it contains the word
1191 `none', disable the ranges. */
1192 if (*dt & ACCEPTRANGES)
1195 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1198 *dt &= ~ACCEPTRANGES;
1202 /* Try getting content-range. */
1203 if (contrange == -1)
1205 struct http_process_range_closure closure;
1206 if (header_process (hdr, "Content-Range", http_process_range, &closure))
1208 contrange = closure.first_byte_pos;
1212 /* Check for keep-alive related responses. */
1213 if (!inhibit_keep_alive)
1215 /* Check for the `Keep-Alive' header. */
1216 if (!http_keep_alive_1)
1218 if (header_process (hdr, "Keep-Alive", header_exists,
1219 &http_keep_alive_1))
1222 /* Check for `Connection: Keep-Alive'. */
1223 if (!http_keep_alive_2)
1225 if (header_process (hdr, "Connection", http_process_connection,
1226 &http_keep_alive_2))
1234 logputs (LOG_VERBOSE, "\n");
1237 && (http_keep_alive_1 || http_keep_alive_2))
1239 assert (inhibit_keep_alive == 0);
1243 /* The server has promised that it will not close the connection
1244 when we're done. This means that we can register it. */
1246 register_persistent (conn->host, conn->port, sock);
1248 register_persistent (conn->host, conn->port, sock, ssl);
1249 #endif /* HAVE_SSL */
1251 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1254 /* Authorization is required. */
1258 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1259 might be more bytes in the body. */
1260 if (auth_tried_already)
1262 /* If we have tried it already, then there is not point
1265 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1266 xfree (authenticate_h);
1269 else if (!known_authentication_scheme_p (authenticate_h))
1271 xfree (authenticate_h);
1272 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1275 else if (BEGINS_WITH (authenticate_h, "Basic"))
1277 /* The authentication scheme is basic, the one we try by
1278 default, and it failed. There's no sense in trying
1284 auth_tried_already = 1;
1288 /* We do not need this anymore. */
1291 xfree (authenticate_h);
1292 authenticate_h = NULL;
1295 /* 20x responses are counted among successful by default. */
1296 if (H_20X (statcode))
1299 /* Return if redirected. */
1300 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1302 /* RFC2068 says that in case of the 300 (multiple choices)
1303 response, the server can output a preferred URL through
1304 `Location' header; otherwise, the request should be treated
1305 like GET. So, if the location is set, it will be a
1306 redirection; otherwise, just proceed normally. */
1307 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1311 logprintf (LOG_VERBOSE,
1312 _("Location: %s%s\n"),
1313 hs->newloc ? hs->newloc : _("unspecified"),
1314 hs->newloc ? _(" [following]") : "");
1315 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1316 might be more bytes in the body. */
1318 FREE_MAYBE (all_headers);
1323 /* If content-type is not given, assume text/html. This is because
1324 of the multitude of broken CGI's that "forget" to generate the
1326 if (!type || 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1331 if (opt.html_extension && (*dt & TEXTHTML))
1332 /* -E / --html-extension / html_extension = on was specified, and this is a
1333 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1334 already the file's suffix, tack on ".html". */
1336 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1338 if (last_period_in_local_filename == NULL ||
1339 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1340 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1342 size_t local_filename_len = strlen(*hs->local_file);
1344 *hs->local_file = xrealloc(*hs->local_file,
1345 local_filename_len + sizeof(".html"));
1346 strcpy(*hs->local_file + local_filename_len, ".html");
1348 *dt |= ADDED_HTML_EXTENSION;
1352 if (contrange == -1)
1354 /* We did not get a content-range header. This means that the
1355 server did not honor our `Range' request. Normally, this
1356 means we should reset hs->restval and continue normally. */
1358 /* However, if `-c' is used, we need to be a bit more careful:
1360 1. If `-c' is specified and the file already existed when
1361 Wget was started, it would be a bad idea for us to start
1362 downloading it from scratch, effectively truncating it. I
1363 believe this cannot happen unless `-c' was specified.
1365 2. If `-c' is used on a file that is already fully
1366 downloaded, we're requesting bytes after the end of file,
1367 which can result in server not honoring `Range'. If this is
1368 the case, `Content-Length' will be equal to the length of the
1370 if (opt.always_rest)
1372 /* Check for condition #2. */
1373 if (hs->restval > 0 /* restart was requested. */
1374 && contlen != -1 /* we got content-length. */
1375 && hs->restval >= contlen /* file fully downloaded
1379 logputs (LOG_VERBOSE, _("\
1380 \n The file is already fully retrieved; nothing to do.\n\n"));
1381 /* In case the caller inspects. */
1384 /* Mark as successfully retrieved. */
1387 FREE_MAYBE (all_headers);
1388 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1389 might be more bytes in the body. */
1390 return RETRUNNEEDED;
1393 /* Check for condition #1. */
1394 if (hs->no_truncate)
1396 logprintf (LOG_NOTQUIET,
1399 Continued download failed on this file, which conflicts with `-c'.\n\
1400 Refusing to truncate existing file `%s'.\n\n"), *hs->local_file);
1402 FREE_MAYBE (all_headers);
1403 CLOSE_INVALIDATE (sock);
1404 return CONTNOTSUPPORTED;
1412 else if (contrange != hs->restval ||
1413 (H_PARTIAL (statcode) && contrange == -1))
1415 /* This means the whole request was somehow misunderstood by the
1416 server. Bail out. */
1418 FREE_MAYBE (all_headers);
1419 CLOSE_INVALIDATE (sock);
1426 contlen += contrange;
1428 contrange = -1; /* If conent-length was not sent,
1429 content-range will be ignored. */
1431 hs->contlen = contlen;
1435 if ((*dt & RETROKF) && !opt.server_response)
1437 /* No need to print this output if the body won't be
1438 downloaded at all, or if the original server response is
1440 logputs (LOG_VERBOSE, _("Length: "));
1443 logputs (LOG_VERBOSE, legible (contlen));
1444 if (contrange != -1)
1445 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1446 legible (contlen - contrange));
1449 logputs (LOG_VERBOSE,
1450 opt.ignore_length ? _("ignored") : _("unspecified"));
1452 logprintf (LOG_VERBOSE, " [%s]\n", type);
1454 logputs (LOG_VERBOSE, "\n");
1458 type = NULL; /* We don't need it any more. */
1460 /* Return if we have no intention of further downloading. */
1461 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1463 /* In case the caller cares to look... */
1467 FREE_MAYBE (all_headers);
1468 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1469 might be more bytes in the body. */
1470 return RETRFINISHED;
1473 /* Open the local file. */
1476 mkalldirs (*hs->local_file);
1478 rotate_backups (*hs->local_file);
1479 fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1482 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1483 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1484 might be more bytes in the body. */
1485 FREE_MAYBE (all_headers);
1491 extern int global_download_count;
1493 /* To ensure that repeated "from scratch" downloads work for -O
1494 files, we rewind the file pointer, unless restval is
1495 non-zero. (This works only when -O is used on regular files,
1496 but it's still a valuable feature.)
1498 However, this loses when more than one URL is specified on
1499 the command line the second rewinds eradicates the contents
1500 of the first download. Thus we disable the above trick for
1501 all the downloads except the very first one.
1503 #### A possible solution to this would be to remember the
1504 file position in the output document and to seek to that
1505 position, instead of rewinding.
1507 We don't truncate stdout, since that breaks
1508 "wget -O - [...] >> foo".
1510 if (!hs->restval && global_download_count == 0 && opt.dfp != stdout)
1512 /* This will silently fail for streams that don't correspond
1513 to regular files, but that's OK. */
1515 /* ftruncate is needed because opt.dfp is opened in append
1516 mode if opt.always_rest is set. */
1517 ftruncate (fileno (fp), 0);
1522 /* #### This confuses the code that checks for file size. There
1523 should be some overhead information. */
1524 if (opt.save_headers)
1525 fwrite (all_headers, 1, all_length, fp);
1527 /* Get the contents of the document. */
1528 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1529 (contlen != -1 ? contlen : 0),
1530 &rbuf, keep_alive, &hs->dltime);
1533 CLOSE_FINISH (sock);
1535 CLOSE_INVALIDATE (sock);
1538 /* Close or flush the file. We have to be careful to check for
1539 error here. Checking the result of fwrite() is not enough --
1540 errors could go unnoticed! */
1543 flush_res = fclose (fp);
1545 flush_res = fflush (fp);
1546 if (flush_res == EOF)
1549 FREE_MAYBE (all_headers);
1552 return RETRFINISHED;
1555 /* The genuine HTTP loop! This is the part where the retrieval is
1556 retried, and retried, and retried, and... */
1558 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1559 int *dt, struct url *proxy)
1562 int use_ts, got_head = 0; /* time-stamping info */
1563 char *filename_plus_orig_suffix;
1564 char *local_filename = NULL;
1565 char *tms, *locf, *tmrate;
1567 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1568 long local_size = 0; /* the size of the local file */
1569 size_t filename_len;
1570 struct http_stat hstat; /* HTTP status */
1574 /* This used to be done in main(), but it's a better idea to do it
1575 here so that we don't go through the hoops if we're just using
1579 if (!wget_cookie_jar)
1580 wget_cookie_jar = cookie_jar_new ();
1581 if (opt.cookies_input && !cookies_loaded_p)
1583 cookie_jar_load (wget_cookie_jar, opt.cookies_input);
1584 cookies_loaded_p = 1;
1590 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1591 has_wildcards_p because it would also warn on `?', and we know that
1592 shows up in CGI paths a *lot*. */
1593 if (strchr (u->url, '*'))
1594 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1596 /* Determine the local filename. */
1597 if (local_file && *local_file)
1598 hstat.local_file = local_file;
1599 else if (local_file)
1601 *local_file = url_file_name (u);
1602 hstat.local_file = local_file;
1606 dummy = url_file_name (u);
1607 hstat.local_file = &dummy;
1610 if (!opt.output_document)
1611 locf = *hstat.local_file;
1613 locf = opt.output_document;
1615 hstat.referer = referer;
1617 filename_len = strlen (*hstat.local_file);
1618 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1620 if (opt.noclobber && file_exists_p (*hstat.local_file))
1622 /* If opt.noclobber is turned on and file already exists, do not
1623 retrieve the file */
1624 logprintf (LOG_VERBOSE, _("\
1625 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1626 /* If the file is there, we suppose it's retrieved OK. */
1629 /* #### Bogusness alert. */
1630 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1631 if (has_html_suffix_p (*hstat.local_file))
1639 if (opt.timestamping)
1641 boolean local_dot_orig_file_exists = FALSE;
1643 if (opt.backup_converted)
1644 /* If -K is specified, we'll act on the assumption that it was specified
1645 last time these files were downloaded as well, and instead of just
1646 comparing local file X against server file X, we'll compare local
1647 file X.orig (if extant, else X) against server file X. If -K
1648 _wasn't_ specified last time, or the server contains files called
1649 *.orig, -N will be back to not operating correctly with -k. */
1651 /* Would a single s[n]printf() call be faster? --dan
1653 Definitely not. sprintf() is horribly slow. It's a
1654 different question whether the difference between the two
1655 affects a program. Usually I'd say "no", but at one
1656 point I profiled Wget, and found that a measurable and
1657 non-negligible amount of time was lost calling sprintf()
1658 in url.c. Replacing sprintf with inline calls to
1659 strcpy() and long_to_string() made a difference.
1661 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1662 memcpy (filename_plus_orig_suffix + filename_len,
1663 ".orig", sizeof (".orig"));
1665 /* Try to stat() the .orig file. */
1666 if (stat (filename_plus_orig_suffix, &st) == 0)
1668 local_dot_orig_file_exists = TRUE;
1669 local_filename = filename_plus_orig_suffix;
1673 if (!local_dot_orig_file_exists)
1674 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1675 if (stat (*hstat.local_file, &st) == 0)
1676 local_filename = *hstat.local_file;
1678 if (local_filename != NULL)
1679 /* There was a local file, so we'll check later to see if the version
1680 the server has is the same version we already have, allowing us to
1686 /* Modification time granularity is 2 seconds for Windows, so
1687 increase local time by 1 second for later comparison. */
1690 local_size = st.st_size;
1694 /* Reset the counter. */
1696 *dt = 0 | ACCEPTRANGES;
1700 /* Increment the pass counter. */
1702 sleep_between_retrievals (count);
1703 /* Get the current time string. */
1704 tms = time_str (NULL);
1705 /* Print fetch message, if opt.verbose. */
1708 char *hurl = url_string (u, 1);
1712 sprintf (tmp, _("(try:%2d)"), count);
1713 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1714 tms, hurl, tmp, locf);
1716 ws_changetitle (hurl, 1);
1721 /* Default document type is empty. However, if spider mode is
1722 on or time-stamping is employed, HEAD_ONLY commands is
1723 encoded within *dt. */
1724 if (opt.spider || (use_ts && !got_head))
1728 /* Assume no restarting. */
1730 /* Decide whether or not to restart. */
1731 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1732 /* #### this calls access() and then stat(); could be optimized. */
1733 && file_exists_p (locf))
1734 if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1735 hstat.restval = st.st_size;
1737 /* In `-c' is used and the file is existing and non-empty,
1738 refuse to truncate it if the server doesn't support continued
1740 hstat.no_truncate = 0;
1741 if (opt.always_rest && hstat.restval)
1742 hstat.no_truncate = 1;
1744 /* Decide whether to send the no-cache directive. We send it in
1746 a) we're using a proxy, and we're past our first retrieval.
1747 Some proxies are notorious for caching incomplete data, so
1748 we require a fresh get.
1749 b) caching is explicitly inhibited. */
1750 if ((proxy && count > 1) /* a */
1751 || !opt.allow_cache /* b */
1753 *dt |= SEND_NOCACHE;
1755 *dt &= ~SEND_NOCACHE;
1757 /* Try fetching the document, or at least its head. */
1758 err = gethttp (u, &hstat, dt, proxy);
1760 /* It's unfortunate that wget determines the local filename before finding
1761 out the Content-Type of the file. Barring a major restructuring of the
1762 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1763 *hstat.local_file to tack on ".html". */
1764 if (!opt.output_document)
1765 locf = *hstat.local_file;
1767 locf = opt.output_document;
1770 tms = time_str (NULL);
1771 /* Get the new location (with or without the redirection). */
1773 *newloc = xstrdup (hstat.newloc);
1776 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1777 case CONERROR: case READERR: case WRITEFAILED:
1779 /* Non-fatal errors continue executing the loop, which will
1780 bring them to "while" statement at the end, to judge
1781 whether the number of tries was exceeded. */
1782 free_hstat (&hstat);
1783 printwhat (count, opt.ntry);
1786 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1787 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1788 /* Fatal errors just return from the function. */
1789 free_hstat (&hstat);
1793 case FWRITEERR: case FOPENERR:
1794 /* Another fatal error. */
1795 logputs (LOG_VERBOSE, "\n");
1796 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1797 *hstat.local_file, strerror (errno));
1798 free_hstat (&hstat);
1803 /* Another fatal error. */
1804 logputs (LOG_VERBOSE, "\n");
1805 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1806 free_hstat (&hstat);
1811 /* Return the new location to the caller. */
1814 logprintf (LOG_NOTQUIET,
1815 _("ERROR: Redirection (%d) without location.\n"),
1817 free_hstat (&hstat);
1821 free_hstat (&hstat);
1826 /* The file was already fully retrieved. */
1827 free_hstat (&hstat);
1832 /* Deal with you later. */
1835 /* All possibilities should have been exhausted. */
1838 if (!(*dt & RETROKF))
1842 /* #### Ugly ugly ugly! */
1843 char *hurl = url_string (u, 1);
1844 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1847 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1848 tms, hstat.statcode, hstat.error);
1849 logputs (LOG_VERBOSE, "\n");
1850 free_hstat (&hstat);
1855 /* Did we get the time-stamp? */
1858 if (opt.timestamping && !hstat.remote_time)
1860 logputs (LOG_NOTQUIET, _("\
1861 Last-modified header missing -- time-stamps turned off.\n"));
1863 else if (hstat.remote_time)
1865 /* Convert the date-string into struct tm. */
1866 tmr = http_atotm (hstat.remote_time);
1867 if (tmr == (time_t) (-1))
1868 logputs (LOG_VERBOSE, _("\
1869 Last-modified header invalid -- time-stamp ignored.\n"));
1873 /* The time-stamping section. */
1878 use_ts = 0; /* no more time-stamping */
1879 count = 0; /* the retrieve count for HEAD is
1881 if (hstat.remote_time && tmr != (time_t) (-1))
1883 /* Now time-stamping can be used validly. Time-stamping
1884 means that if the sizes of the local and remote file
1885 match, and local file is newer than the remote file,
1886 it will not be retrieved. Otherwise, the normal
1887 download procedure is resumed. */
1889 (hstat.contlen == -1 || local_size == hstat.contlen))
1891 logprintf (LOG_VERBOSE, _("\
1892 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1894 free_hstat (&hstat);
1898 else if (tml >= tmr)
1899 logprintf (LOG_VERBOSE, _("\
1900 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1902 logputs (LOG_VERBOSE,
1903 _("Remote file is newer, retrieving.\n"));
1905 free_hstat (&hstat);
1908 if ((tmr != (time_t) (-1))
1910 && ((hstat.len == hstat.contlen) ||
1911 ((hstat.res == 0) &&
1912 ((hstat.contlen == -1) ||
1913 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1915 /* #### This code repeats in http.c and ftp.c. Move it to a
1917 const char *fl = NULL;
1918 if (opt.output_document)
1920 if (opt.od_known_regular)
1921 fl = opt.output_document;
1924 fl = *hstat.local_file;
1928 /* End of time-stamping section. */
1932 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1937 tmrate = retr_rate (hstat.len - hstat.restval, hstat.dltime, 0);
1939 if (hstat.len == hstat.contlen)
1943 logprintf (LOG_VERBOSE,
1944 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1945 tms, tmrate, locf, hstat.len, hstat.contlen);
1946 logprintf (LOG_NONVERBOSE,
1947 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1948 tms, u->url, hstat.len, hstat.contlen, locf, count);
1951 downloaded_increase (hstat.len);
1953 /* Remember that we downloaded the file for later ".orig" code. */
1954 if (*dt & ADDED_HTML_EXTENSION)
1955 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1957 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1959 free_hstat (&hstat);
1963 else if (hstat.res == 0) /* No read error */
1965 if (hstat.contlen == -1) /* We don't know how much we were supposed
1966 to get, so assume we succeeded. */
1970 logprintf (LOG_VERBOSE,
1971 _("%s (%s) - `%s' saved [%ld]\n\n"),
1972 tms, tmrate, locf, hstat.len);
1973 logprintf (LOG_NONVERBOSE,
1974 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1975 tms, u->url, hstat.len, locf, count);
1978 downloaded_increase (hstat.len);
1980 /* Remember that we downloaded the file for later ".orig" code. */
1981 if (*dt & ADDED_HTML_EXTENSION)
1982 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1984 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1986 free_hstat (&hstat);
1990 else if (hstat.len < hstat.contlen) /* meaning we lost the
1991 connection too soon */
1993 logprintf (LOG_VERBOSE,
1994 _("%s (%s) - Connection closed at byte %ld. "),
1995 tms, tmrate, hstat.len);
1996 printwhat (count, opt.ntry);
1997 free_hstat (&hstat);
2000 else if (!opt.kill_longer) /* meaning we got more than expected */
2002 logprintf (LOG_VERBOSE,
2003 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
2004 tms, tmrate, locf, hstat.len, hstat.contlen);
2005 logprintf (LOG_NONVERBOSE,
2006 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
2007 tms, u->url, hstat.len, hstat.contlen, locf, count);
2009 downloaded_increase (hstat.len);
2011 /* Remember that we downloaded the file for later ".orig" code. */
2012 if (*dt & ADDED_HTML_EXTENSION)
2013 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2015 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2017 free_hstat (&hstat);
2021 else /* the same, but not accepted */
2023 logprintf (LOG_VERBOSE,
2024 _("%s (%s) - Connection closed at byte %ld/%ld. "),
2025 tms, tmrate, hstat.len, hstat.contlen);
2026 printwhat (count, opt.ntry);
2027 free_hstat (&hstat);
2031 else /* now hstat.res can only be -1 */
2033 if (hstat.contlen == -1)
2035 logprintf (LOG_VERBOSE,
2036 _("%s (%s) - Read error at byte %ld (%s)."),
2037 tms, tmrate, hstat.len, strerror (errno));
2038 printwhat (count, opt.ntry);
2039 free_hstat (&hstat);
2042 else /* hstat.res == -1 and contlen is given */
2044 logprintf (LOG_VERBOSE,
2045 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2046 tms, tmrate, hstat.len, hstat.contlen,
2048 printwhat (count, opt.ntry);
2049 free_hstat (&hstat);
2056 while (!opt.ntry || (count < opt.ntry));
2060 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2061 than local timezone.
2063 mktime is similar but assumes struct tm, also known as the
2064 "broken-down" form of time, is in local time zone. mktime_from_utc
2065 uses mktime to make the conversion understanding that an offset
2066 will be introduced by the local time assumption.
2068 mktime_from_utc then measures the introduced offset by applying
2069 gmtime to the initial result and applying mktime to the resulting
2070 "broken-down" form. The difference between the two mktime results
2071 is the measured offset which is then subtracted from the initial
2072 mktime result to yield a calendar time which is the value returned.
2074 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2075 consistent offset (the non DST offset) since tm and tm+o might be
2076 on opposite sides of a DST change.
2078 Some implementations of mktime return -1 for the nonexistent
2079 localtime hour at the beginning of DST. In this event, use
2080 mktime(tm - 1hr) + 3600.
2084 gmtime(t+o) --> tm+o
2085 mktime(tm+o) --> t+2o
2086 t+o - (t+2o - t+o) = t
2088 Note that glibc contains a function of the same purpose named
2089 `timegm' (reverse of gmtime). But obviously, it is not universally
2090 available, and unfortunately it is not straightforwardly
2091 extractable for use here. Perhaps configure should detect timegm
2092 and use it where available.
2094 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2095 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2096 Further improved by Roger with assistance from Edward J. Sabol
2097 based on input by Jamie Zawinski. */
2100 mktime_from_utc (struct tm *t)
2111 return -1; /* can't deal with output from strptime */
2122 return -1; /* can't deal with output from gmtime */
2125 return (tl - (tb - tl));
2128 /* Check whether the result of strptime() indicates success.
2129 strptime() returns the pointer to how far it got to in the string.
2130 The processing has been successful if the string is at `GMT' or
2131 `+X', or at the end of the string.
2133 In extended regexp parlance, the function returns 1 if P matches
2134 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2135 can return) is considered a failure and 0 is returned. */
2137 check_end (const char *p)
2141 while (ISSPACE (*p))
2144 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2145 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2151 /* Convert the textual specification of time in TIME_STRING to the
2152 number of seconds since the Epoch.
2154 TIME_STRING can be in any of the three formats RFC2068 allows the
2155 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2156 Timezones are ignored, and should be GMT.
2158 Return the computed time_t representation, or -1 if the conversion
2161 This function uses strptime with various string formats for parsing
2162 TIME_STRING. This results in a parser that is not as lenient in
2163 interpreting TIME_STRING as I would like it to be. Being based on
2164 strptime, it always allows shortened months, one-digit days, etc.,
2165 but due to the multitude of formats in which time can be
2166 represented, an ideal HTTP time parser would be even more
2167 forgiving. It should completely ignore things like week days and
2168 concentrate only on the various forms of representing years,
2169 months, days, hours, minutes, and seconds. For example, it would
2170 be nice if it accepted ISO 8601 out of the box.
2172 I've investigated free and PD code for this purpose, but none was
2173 usable. getdate was big and unwieldy, and had potential copyright
2174 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2175 distributed with phttpd, is excellent, but we cannot use it because
2176 it is not assigned to the FSF. So I stuck it with strptime. */
2179 http_atotm (const char *time_string)
2181 /* NOTE: Solaris strptime man page claims that %n and %t match white
2182 space, but that's not universally available. Instead, we simply
2183 use ` ' to mean "skip all WS", which works under all strptime
2184 implementations I've tested. */
2186 static const char *time_formats[] = {
2187 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2188 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2189 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2190 (google.com uses this for their cookies.) */
2191 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2197 /* According to Roger Beeman, we need to initialize tm_isdst, since
2198 strptime won't do it. */
2201 /* Note that under foreign locales Solaris strptime() fails to
2202 recognize English dates, which renders this function useless. We
2203 solve this by being careful not to affect LC_TIME when
2204 initializing locale.
2206 Another solution would be to temporarily set locale to C, invoke
2207 strptime(), and restore it back. This is slow and dirty,
2208 however, and locale support other than LC_MESSAGES can mess other
2209 things, so I rather chose to stick with just setting LC_MESSAGES.
2211 GNU strptime does not have this problem because it recognizes
2212 both international and local dates. */
2214 for (i = 0; i < countof (time_formats); i++)
2215 if (check_end (strptime (time_string, time_formats[i], &t)))
2216 return mktime_from_utc (&t);
2218 /* All formats have failed. */
2222 /* Authorization support: We support two authorization schemes:
2224 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2226 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2227 consisting of answering to the server's challenge with the proper
2230 /* How many bytes it will take to store LEN bytes in base64. */
2231 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2233 /* Encode the string S of length LENGTH to base64 format and place it
2234 to STORE. STORE will be 0-terminated, and must point to a writable
2235 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2237 base64_encode (const char *s, char *store, int length)
2239 /* Conversion table. */
2240 static char tbl[64] = {
2241 'A','B','C','D','E','F','G','H',
2242 'I','J','K','L','M','N','O','P',
2243 'Q','R','S','T','U','V','W','X',
2244 'Y','Z','a','b','c','d','e','f',
2245 'g','h','i','j','k','l','m','n',
2246 'o','p','q','r','s','t','u','v',
2247 'w','x','y','z','0','1','2','3',
2248 '4','5','6','7','8','9','+','/'
2251 unsigned char *p = (unsigned char *)store;
2253 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2254 for (i = 0; i < length; i += 3)
2256 *p++ = tbl[s[0] >> 2];
2257 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2258 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2259 *p++ = tbl[s[2] & 0x3f];
2262 /* Pad the result if necessary... */
2263 if (i == length + 1)
2265 else if (i == length + 2)
2266 *(p - 1) = *(p - 2) = '=';
2267 /* ...and zero-terminate it. */
2271 /* Create the authentication header contents for the `Basic' scheme.
2272 This is done by encoding the string `USER:PASS' in base64 and
2273 prepending `HEADER: Basic ' to it. */
2275 basic_authentication_encode (const char *user, const char *passwd,
2278 char *t1, *t2, *res;
2279 int len1 = strlen (user) + 1 + strlen (passwd);
2280 int len2 = BASE64_LENGTH (len1);
2282 t1 = (char *)alloca (len1 + 1);
2283 sprintf (t1, "%s:%s", user, passwd);
2284 t2 = (char *)alloca (1 + len2);
2285 base64_encode (t1, t2, len1);
2286 res = (char *)xmalloc (len2 + 11 + strlen (header));
2287 sprintf (res, "%s: Basic %s\r\n", header, t2);
2293 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2294 of a field in such a header. If the field is the one specified by
2295 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2296 digest authorization code), extract its value in the (char*)
2297 variable pointed by RET. Returns negative on a malformed header,
2298 or number of bytes that have been parsed by this call. */
2300 extract_header_attr (const char *au, const char *attr_name, char **ret)
2302 const char *cp, *ep;
2306 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2308 cp += strlen (attr_name);
2311 cp += skip_lws (cp);
2316 cp += skip_lws (cp);
2321 for (ep = cp; *ep && *ep != '\"'; ep++)
2326 *ret = strdupdelim (cp, ep);
2333 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2334 an array of 16 bytes containing the hash keys, and BUF should be a
2335 buffer of 33 writable characters (32 for hex digits plus one for
2336 zero termination). */
2338 dump_hash (unsigned char *buf, const unsigned char *hash)
2342 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2344 *buf++ = XNUM_TO_digit (*hash >> 4);
2345 *buf++ = XNUM_TO_digit (*hash & 0xf);
2350 /* Take the line apart to find the challenge, and compose a digest
2351 authorization header. See RFC2069 section 2.1.2. */
2353 digest_authentication_encode (const char *au, const char *user,
2354 const char *passwd, const char *method,
2357 static char *realm, *opaque, *nonce;
2362 { "realm", &realm },
2363 { "opaque", &opaque },
2368 realm = opaque = nonce = NULL;
2370 au += 6; /* skip over `Digest' */
2375 au += skip_lws (au);
2376 for (i = 0; i < countof (options); i++)
2378 int skip = extract_header_attr (au, options[i].name,
2379 options[i].variable);
2383 FREE_MAYBE (opaque);
2393 if (i == countof (options))
2395 while (*au && *au != '=')
2399 au += skip_lws (au);
2403 while (*au && *au != '\"')
2410 while (*au && *au != ',')
2415 if (!realm || !nonce || !user || !passwd || !path || !method)
2418 FREE_MAYBE (opaque);
2423 /* Calculate the digest value. */
2425 ALLOCA_MD5_CONTEXT (ctx);
2426 unsigned char hash[MD5_HASHLEN];
2427 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2428 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2430 /* A1BUF = H(user ":" realm ":" password) */
2432 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2433 gen_md5_update ((unsigned char *)":", 1, ctx);
2434 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2435 gen_md5_update ((unsigned char *)":", 1, ctx);
2436 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2437 gen_md5_finish (ctx, hash);
2438 dump_hash (a1buf, hash);
2440 /* A2BUF = H(method ":" path) */
2442 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2443 gen_md5_update ((unsigned char *)":", 1, ctx);
2444 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2445 gen_md5_finish (ctx, hash);
2446 dump_hash (a2buf, hash);
2448 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2450 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2451 gen_md5_update ((unsigned char *)":", 1, ctx);
2452 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2453 gen_md5_update ((unsigned char *)":", 1, ctx);
2454 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2455 gen_md5_finish (ctx, hash);
2456 dump_hash (response_digest, hash);
2458 res = (char*) xmalloc (strlen (user)
2463 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2464 + (opaque ? strlen (opaque) : 0)
2466 sprintf (res, "Authorization: Digest \
2467 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2468 user, realm, nonce, path, response_digest);
2471 char *p = res + strlen (res);
2472 strcat (p, ", opaque=\"");
2476 strcat (res, "\r\n");
2480 #endif /* USE_DIGEST */
2483 #define BEGINS_WITH(line, string_constant) \
2484 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2485 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2486 || !line[sizeof (string_constant) - 1]))
2489 known_authentication_scheme_p (const char *au)
2491 return BEGINS_WITH (au, "Basic")
2492 || BEGINS_WITH (au, "Digest")
2493 || BEGINS_WITH (au, "NTLM");
2498 /* Create the HTTP authorization request header. When the
2499 `WWW-Authenticate' response header is seen, according to the
2500 authorization scheme specified in that header (`Basic' and `Digest'
2501 are supported by the current implementation), produce an
2502 appropriate HTTP authorization request header. */
2504 create_authorization_line (const char *au, const char *user,
2505 const char *passwd, const char *method,
2508 char *wwwauth = NULL;
2510 if (!strncasecmp (au, "Basic", 5))
2511 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2512 if (!strncasecmp (au, "NTLM", 4))
2513 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2515 else if (!strncasecmp (au, "Digest", 6))
2516 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2517 #endif /* USE_DIGEST */
2524 if (pc_last_host_ip)
2525 address_list_release (pc_last_host_ip);