2 Copyright (C) 2003 Free Software Foundation, Inc.
4 This file is part of GNU Wget.
6 GNU Wget 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 GNU Wget 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 Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables. You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL". If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so. If you do not wish to do
28 so, delete this exception statement from your version. */
34 #include <sys/types.h>
45 #if TIME_WITH_SYS_TIME
46 # include <sys/time.h>
50 # include <sys/time.h>
67 # include "gen_sslfunc.h"
75 extern char *version_string;
76 extern LARGE_INT total_downloaded_bytes;
78 extern FILE *output_stream;
79 extern int output_stream_regular;
82 # define MIN(x, y) ((x) > (y) ? (y) : (x))
86 static int cookies_loaded_p;
87 struct cookie_jar *wget_cookie_jar;
89 #define TEXTHTML_S "text/html"
90 #define TEXTXHTML_S "application/xhtml+xml"
92 /* Some status code validation macros: */
93 #define H_20X(x) (((x) >= 200) && ((x) < 300))
94 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
95 #define H_REDIRECTED(x) ((x) == HTTP_STATUS_MOVED_PERMANENTLY \
96 || (x) == HTTP_STATUS_MOVED_TEMPORARILY \
97 || (x) == HTTP_STATUS_SEE_OTHER \
98 || (x) == HTTP_STATUS_TEMPORARY_REDIRECT)
100 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
101 /* Successful 2xx. */
102 #define HTTP_STATUS_OK 200
103 #define HTTP_STATUS_CREATED 201
104 #define HTTP_STATUS_ACCEPTED 202
105 #define HTTP_STATUS_NO_CONTENT 204
106 #define HTTP_STATUS_PARTIAL_CONTENTS 206
108 /* Redirection 3xx. */
109 #define HTTP_STATUS_MULTIPLE_CHOICES 300
110 #define HTTP_STATUS_MOVED_PERMANENTLY 301
111 #define HTTP_STATUS_MOVED_TEMPORARILY 302
112 #define HTTP_STATUS_SEE_OTHER 303 /* from HTTP/1.1 */
113 #define HTTP_STATUS_NOT_MODIFIED 304
114 #define HTTP_STATUS_TEMPORARY_REDIRECT 307 /* from HTTP/1.1 */
116 /* Client error 4xx. */
117 #define HTTP_STATUS_BAD_REQUEST 400
118 #define HTTP_STATUS_UNAUTHORIZED 401
119 #define HTTP_STATUS_FORBIDDEN 403
120 #define HTTP_STATUS_NOT_FOUND 404
121 #define HTTP_STATUS_RANGE_NOT_SATISFIABLE 416
123 /* Server errors 5xx. */
124 #define HTTP_STATUS_INTERNAL 500
125 #define HTTP_STATUS_NOT_IMPLEMENTED 501
126 #define HTTP_STATUS_BAD_GATEWAY 502
127 #define HTTP_STATUS_UNAVAILABLE 503
130 rel_none, rel_name, rel_value, rel_both
137 struct request_header {
139 enum rp release_policy;
141 int hcount, hcapacity;
144 /* Create a new, empty request. At least request_set_method must be
145 called before the request can be used. */
147 static struct request *
150 struct request *req = xnew0 (struct request);
152 req->headers = xnew_array (struct request_header, req->hcapacity);
156 /* Set the request's method and its arguments. METH should be a
157 literal string (or it should outlive the request) because it will
158 not be freed. ARG will be freed by request_free. */
161 request_set_method (struct request *req, const char *meth, char *arg)
167 /* Return the method string passed with the last call to
168 request_set_method. */
171 request_method (const struct request *req)
176 /* Free one header according to the release policy specified with
177 request_set_header. */
180 release_header (struct request_header *hdr)
182 switch (hdr->release_policy)
199 /* Set the request named NAME to VALUE. Specifically, this means that
200 a "NAME: VALUE\r\n" header line will be used in the request. If a
201 header with the same name previously existed in the request, its
202 value will be replaced by this one.
204 RELEASE_POLICY determines whether NAME and VALUE should be released
205 (freed) with request_free. Allowed values are:
207 - rel_none - don't free NAME or VALUE
208 - rel_name - free NAME when done
209 - rel_value - free VALUE when done
210 - rel_both - free both NAME and VALUE when done
212 Setting release policy is useful when arguments come from different
213 sources. For example:
215 // Don't free literal strings!
216 request_set_header (req, "Pragma", "no-cache", rel_none);
218 // Don't free a global variable, we'll need it later.
219 request_set_header (req, "Referer", opt.referer, rel_none);
221 // Value freshly allocated, free it when done.
222 request_set_header (req, "Range",
223 aprintf ("bytes=%s-", number_to_static_string (hs->restval)),
228 request_set_header (struct request *req, char *name, char *value,
229 enum rp release_policy)
231 struct request_header *hdr;
235 for (i = 0; i < req->hcount; i++)
237 hdr = &req->headers[i];
238 if (0 == strcasecmp (name, hdr->name))
240 /* Replace existing header. */
241 release_header (hdr);
244 hdr->release_policy = release_policy;
249 /* Install new header. */
251 if (req->hcount >= req->hcount)
253 req->hcapacity <<= 1;
254 req->headers = xrealloc (req->headers,
255 req->hcapacity * sizeof (struct request_header));
257 hdr = &req->headers[req->hcount++];
260 hdr->release_policy = release_policy;
263 /* Like request_set_header, but sets the whole header line, as
264 provided by the user using the `--header' option. For example,
265 request_set_user_header (req, "Foo: bar") works just like
266 request_set_header (req, "Foo", "bar"). */
269 request_set_user_header (struct request *req, const char *header)
272 const char *p = strchr (header, ':');
275 BOUNDED_TO_ALLOCA (header, p, name);
279 request_set_header (req, xstrdup (name), (char *) p, rel_name);
282 #define APPEND(p, str) do { \
283 int A_len = strlen (str); \
284 memcpy (p, str, A_len); \
288 /* Construct the request and write it to FD using fd_write. */
291 request_send (const struct request *req, int fd)
293 char *request_string, *p;
294 int i, size, write_error;
296 /* Count the request size. */
299 /* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
300 size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
302 for (i = 0; i < req->hcount; i++)
304 struct request_header *hdr = &req->headers[i];
305 /* NAME ": " VALUE "\r\n" */
306 size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
312 p = request_string = alloca_array (char, size);
314 /* Generate the request. */
316 APPEND (p, req->method); *p++ = ' ';
317 APPEND (p, req->arg); *p++ = ' ';
318 memcpy (p, "HTTP/1.0\r\n", 10); p += 10;
320 for (i = 0; i < req->hcount; i++)
322 struct request_header *hdr = &req->headers[i];
323 APPEND (p, hdr->name);
324 *p++ = ':', *p++ = ' ';
325 APPEND (p, hdr->value);
326 *p++ = '\r', *p++ = '\n';
329 *p++ = '\r', *p++ = '\n', *p++ = '\0';
330 assert (p - request_string == size);
334 DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
336 /* Send the request to the server. */
338 write_error = fd_write (fd, request_string, size - 1, -1);
340 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
345 /* Release the resources used by REQ. */
348 request_free (struct request *req)
351 xfree_null (req->arg);
352 for (i = 0; i < req->hcount; i++)
353 release_header (&req->headers[i]);
354 xfree_null (req->headers);
358 /* Send the contents of FILE_NAME to SOCK/SSL. Make sure that exactly
359 PROMISED_SIZE bytes are sent over the wire -- if the file is
360 longer, read only that much; if the file is shorter, report an error. */
363 post_file (int sock, const char *file_name, wgint promised_size)
365 static char chunk[8192];
370 DEBUGP (("[writing POST file %s ... ", file_name));
372 fp = fopen (file_name, "rb");
375 while (!feof (fp) && written < promised_size)
378 int length = fread (chunk, 1, sizeof (chunk), fp);
381 towrite = MIN (promised_size - written, length);
382 write_error = fd_write (sock, chunk, towrite, -1);
392 /* If we've written less than was promised, report a (probably
393 nonsensical) error rather than break the promise. */
394 if (written < promised_size)
400 assert (written == promised_size);
401 DEBUGP (("done]\n"));
406 head_terminator (const char *hunk, int oldlen, int peeklen)
408 const char *start, *end;
410 /* If at first peek, verify whether HUNK starts with "HTTP". If
411 not, this is a HTTP/0.9 request and we must bail out without
413 if (oldlen == 0 && 0 != memcmp (hunk, "HTTP", MIN (peeklen, 4)))
419 start = hunk + oldlen - 4;
420 end = hunk + oldlen + peeklen;
422 for (; start < end - 1; start++)
429 if (start[1] == '\n')
435 /* Read the HTTP request head from FD and return it. The error
436 conditions are the same as with fd_read_hunk.
438 To support HTTP/0.9 responses, this function tries to make sure
439 that the data begins with "HTTP". If this is not the case, no data
440 is read and an empty request is returned, so that the remaining
441 data can be treated as body. */
444 fd_read_http_head (int fd)
446 return fd_read_hunk (fd, head_terminator, 512);
450 /* The response data. */
453 /* The array of pointers that indicate where each header starts.
454 For example, given this HTTP response:
461 The headers are located like this:
463 "HTTP/1.0 200 Ok\r\nDescription: some\r\n text\r\nEtag: x\r\n\r\n"
465 headers[0] headers[1] headers[2] headers[3]
467 I.e. headers[0] points to the beginning of the request,
468 headers[1] points to the end of the first header and the
469 beginning of the second one, etc. */
471 const char **headers;
474 /* Create a new response object from the text of the HTTP response,
475 available in HEAD. That text is automatically split into
476 constituent header lines for fast retrieval using
477 response_header_*. */
479 static struct response *
480 response_new (const char *head)
485 struct response *resp = xnew0 (struct response);
490 /* Empty head means that we're dealing with a headerless
491 (HTTP/0.9) response. In that case, don't set HEADERS at
496 /* Split HEAD into header lines, so that response_header_* functions
497 don't need to do this over and over again. */
503 DO_REALLOC (resp->headers, size, count + 1, const char *);
504 resp->headers[count++] = hdr;
506 /* Break upon encountering an empty line. */
507 if (!hdr[0] || (hdr[0] == '\r' && hdr[1] == '\n') || hdr[0] == '\n')
510 /* Find the end of HDR, including continuations. */
513 const char *end = strchr (hdr, '\n');
519 while (*hdr == ' ' || *hdr == '\t');
521 DO_REALLOC (resp->headers, size, count + 1, const char *);
522 resp->headers[count] = NULL;
527 /* Locate the header named NAME in the request data. If found, set
528 *BEGPTR to its starting, and *ENDPTR to its ending position, and
529 return 1. Otherwise return 0.
531 This function is used as a building block for response_header_copy
532 and response_header_strdup. */
535 response_header_bounds (const struct response *resp, const char *name,
536 const char **begptr, const char **endptr)
539 const char **headers = resp->headers;
542 if (!headers || !headers[1])
545 name_len = strlen (name);
547 for (i = 1; headers[i + 1]; i++)
549 const char *b = headers[i];
550 const char *e = headers[i + 1];
552 && b[name_len] == ':'
553 && 0 == strncasecmp (b, name, name_len))
556 while (b < e && ISSPACE (*b))
558 while (b < e && ISSPACE (e[-1]))
568 /* Copy the response header named NAME to buffer BUF, no longer than
569 BUFSIZE (BUFSIZE includes the terminating 0). If the header
570 exists, 1 is returned, otherwise 0. If there should be no limit on
571 the size of the header, use response_header_strdup instead.
573 If BUFSIZE is 0, no data is copied, but the boolean indication of
574 whether the header is present is still returned. */
577 response_header_copy (const struct response *resp, const char *name,
578 char *buf, int bufsize)
581 if (!response_header_bounds (resp, name, &b, &e))
585 int len = MIN (e - b, bufsize - 1);
586 memcpy (buf, b, len);
592 /* Return the value of header named NAME in RESP, allocated with
593 malloc. If such a header does not exist in RESP, return NULL. */
596 response_header_strdup (const struct response *resp, const char *name)
599 if (!response_header_bounds (resp, name, &b, &e))
601 return strdupdelim (b, e);
604 /* Parse the HTTP status line, which is of format:
606 HTTP-Version SP Status-Code SP Reason-Phrase
608 The function returns the status-code, or -1 if the status line
609 appears malformed. The pointer to "reason-phrase" message is
610 returned in *MESSAGE. */
613 response_status (const struct response *resp, char **message)
620 /* For a HTTP/0.9 response, assume status 200. */
622 *message = xstrdup (_("No headers, assuming HTTP/0.9"));
626 p = resp->headers[0];
627 end = resp->headers[1];
633 if (end - p < 4 || 0 != strncmp (p, "HTTP", 4))
637 /* Match the HTTP version. This is optional because Gnutella
638 servers have been reported to not specify HTTP version. */
639 if (p < end && *p == '/')
642 while (p < end && ISDIGIT (*p))
644 if (p < end && *p == '.')
646 while (p < end && ISDIGIT (*p))
650 while (p < end && ISSPACE (*p))
652 if (end - p < 3 || !ISDIGIT (p[0]) || !ISDIGIT (p[1]) || !ISDIGIT (p[2]))
655 status = 100 * (p[0] - '0') + 10 * (p[1] - '0') + (p[2] - '0');
660 while (p < end && ISSPACE (*p))
662 while (p < end && ISSPACE (end[-1]))
664 *message = strdupdelim (p, end);
670 /* Release the resources used by RESP. */
673 response_free (struct response *resp)
675 xfree_null (resp->headers);
679 /* Print [b, e) to the log, omitting the trailing CRLF. */
682 print_server_response_1 (const char *prefix, const char *b, const char *e)
685 if (b < e && e[-1] == '\n')
687 if (b < e && e[-1] == '\r')
689 BOUNDED_TO_ALLOCA (b, e, ln);
690 logprintf (LOG_VERBOSE, "%s%s\n", prefix, escnonprint (ln));
693 /* Print the server response, line by line, omitting the trailing CR
694 characters, prefixed with PREFIX. */
697 print_server_response (const struct response *resp, const char *prefix)
702 for (i = 0; resp->headers[i + 1]; i++)
703 print_server_response_1 (prefix, resp->headers[i], resp->headers[i + 1]);
706 /* Parse the `Content-Range' header and extract the information it
707 contains. Returns 1 if successful, -1 otherwise. */
709 parse_content_range (const char *hdr, wgint *first_byte_ptr,
710 wgint *last_byte_ptr, wgint *entity_length_ptr)
714 /* Ancient versions of Netscape proxy server, presumably predating
715 rfc2068, sent out `Content-Range' without the "bytes"
717 if (!strncasecmp (hdr, "bytes", 5))
720 /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
724 while (ISSPACE (*hdr))
731 for (num = 0; ISDIGIT (*hdr); hdr++)
732 num = 10 * num + (*hdr - '0');
733 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
735 *first_byte_ptr = num;
737 for (num = 0; ISDIGIT (*hdr); hdr++)
738 num = 10 * num + (*hdr - '0');
739 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
741 *last_byte_ptr = num;
743 for (num = 0; ISDIGIT (*hdr); hdr++)
744 num = 10 * num + (*hdr - '0');
745 *entity_length_ptr = num;
749 /* Read the body of the request, but don't store it anywhere and don't
750 display a progress gauge. This is useful for reading the error
751 responses whose bodies don't need to be displayed or logged, but
752 which need to be read anyway. */
755 skip_short_body (int fd, wgint contlen)
757 /* Skipping the body doesn't make sense if the content length is
758 unknown because, in that case, persistent connections cannot be
759 used. (#### This is not the case with HTTP/1.1 where they can
760 still be used with the magic of the "chunked" transfer!) */
763 DEBUGP (("Skipping %s bytes of body data... ", number_to_static_string (contlen)));
768 int ret = fd_read (fd, dlbuf, MIN (contlen, sizeof (dlbuf)), -1);
773 DEBUGP (("done.\n"));
776 /* Persistent connections. Currently, we cache the most recently used
777 connection as persistent, provided that the HTTP server agrees to
778 make it such. The persistence data is stored in the variables
779 below. Ideally, it should be possible to cache an arbitrary fixed
780 number of these connections. */
782 /* Whether a persistent connection is active. */
783 static int pconn_active;
786 /* The socket of the connection. */
789 /* Host and port of the currently active persistent connection. */
793 /* Whether a ssl handshake has occoured on this connection. */
797 /* Mark the persistent connection as invalid and free the resources it
798 uses. This is used by the CLOSE_* macros after they forcefully
799 close a registered persistent connection. */
802 invalidate_persistent (void)
804 DEBUGP (("Disabling further reuse of socket %d.\n", pconn.socket));
806 fd_close (pconn.socket);
811 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
812 persistent. This will enable someone to use the same connection
813 later. In the context of HTTP, this must be called only AFTER the
814 response has been received and the server has promised that the
815 connection will remain alive.
817 If a previous connection was persistent, it is closed. */
820 register_persistent (const char *host, int port, int fd, int ssl)
824 if (pconn.socket == fd)
826 /* The connection FD is already registered. */
831 /* The old persistent connection is still active; close it
832 first. This situation arises whenever a persistent
833 connection exists, but we then connect to a different
834 host, and try to register a persistent connection to that
836 invalidate_persistent ();
842 pconn.host = xstrdup (host);
846 DEBUGP (("Registered socket %d for persistent reuse.\n", fd));
849 /* Return non-zero if a persistent connection is available for
850 connecting to HOST:PORT. */
853 persistent_available_p (const char *host, int port, int ssl,
854 int *host_lookup_failed)
856 /* First, check whether a persistent connection is active at all. */
860 /* If we want SSL and the last connection wasn't or vice versa,
861 don't use it. Checking for host and port is not enough because
862 HTTP and HTTPS can apparently coexist on the same port. */
863 if (ssl != pconn.ssl)
866 /* If we're not connecting to the same port, we're not interested. */
867 if (port != pconn.port)
870 /* If the host is the same, we're in business. If not, there is
871 still hope -- read below. */
872 if (0 != strcasecmp (host, pconn.host))
874 /* If pconn.socket is already talking to HOST, we needn't
875 reconnect. This happens often when both sites are virtual
876 hosts distinguished only by name and served by the same
877 network interface, and hence the same web server (possibly
878 set up by the ISP and serving many different web sites).
879 This admittedly non-standard optimization does not contradict
880 HTTP and works well with popular server software. */
884 struct address_list *al;
887 /* Don't try to talk to two different SSL sites over the same
888 secure connection! (Besides, it's not clear if name-based
889 virtual hosting is even possible with SSL.) */
892 /* If pconn.socket's peer is one of the IP addresses HOST
893 resolves to, pconn.socket is for all intents and purposes
894 already talking to HOST. */
896 if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER))
898 /* Can't get the peer's address -- something must be very
899 wrong with the connection. */
900 invalidate_persistent ();
903 al = lookup_host (host, 0);
906 *host_lookup_failed = 1;
910 found = address_list_contains (al, &ip);
911 address_list_release (al);
916 /* The persistent connection's peer address was found among the
917 addresses HOST resolved to; therefore, pconn.sock is in fact
918 already talking to HOST -- no need to reconnect. */
921 /* Finally, check whether the connection is still open. This is
922 important because most server implement a liberal (short) timeout
923 on persistent connections. Wget can of course always reconnect
924 if the connection doesn't work out, but it's nicer to know in
925 advance. This test is a logical followup of the first test, but
926 is "expensive" and therefore placed at the end of the list. */
928 if (!test_socket_open (pconn.socket))
930 /* Oops, the socket is no longer open. Now that we know that,
931 let's invalidate the persistent connection before returning
933 invalidate_persistent ();
940 /* The idea behind these two CLOSE macros is to distinguish between
941 two cases: one when the job we've been doing is finished, and we
942 want to close the connection and leave, and two when something is
943 seriously wrong and we're closing the connection as part of
946 In case of keep_alive, CLOSE_FINISH should leave the connection
947 open, while CLOSE_INVALIDATE should still close it.
949 Note that the semantics of the flag `keep_alive' is "this
950 connection *will* be reused (the server has promised not to close
951 the connection once we're done)", while the semantics of
952 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
953 active, registered connection". */
955 #define CLOSE_FINISH(fd) do { \
958 if (pconn_active && (fd) == pconn.socket) \
959 invalidate_persistent (); \
968 #define CLOSE_INVALIDATE(fd) do { \
969 if (pconn_active && (fd) == pconn.socket) \
970 invalidate_persistent (); \
978 wgint len; /* received length */
979 wgint contlen; /* expected length */
980 wgint restval; /* the restart value */
981 int res; /* the result of last read */
982 char *newloc; /* new location (redirection) */
983 char *remote_time; /* remote time-stamp string */
984 char *error; /* textual HTTP error */
985 int statcode; /* status code */
986 wgint rd_size; /* amount of data read from socket */
987 double dltime; /* time it took to download the data */
988 const char *referer; /* value of the referer header. */
989 char **local_file; /* local file. */
993 free_hstat (struct http_stat *hs)
995 xfree_null (hs->newloc);
996 xfree_null (hs->remote_time);
997 xfree_null (hs->error);
999 /* Guard against being called twice. */
1001 hs->remote_time = NULL;
1005 static char *create_authorization_line PARAMS ((const char *, const char *,
1006 const char *, const char *,
1008 static char *basic_authentication_encode PARAMS ((const char *, const char *));
1009 static int known_authentication_scheme_p PARAMS ((const char *));
1011 time_t http_atotm PARAMS ((const char *));
1013 #define BEGINS_WITH(line, string_constant) \
1014 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
1015 && (ISSPACE (line[sizeof (string_constant) - 1]) \
1016 || !line[sizeof (string_constant) - 1]))
1018 /* Retrieve a document through HTTP protocol. It recognizes status
1019 code, and correctly handles redirections. It closes the network
1020 socket. If it receives an error from the functions below it, it
1021 will print it if there is enough information to do so (almost
1022 always), returning the error to the caller (i.e. http_loop).
1024 Various HTTP parameters are stored to hs.
1026 If PROXY is non-NULL, the connection will be made to the proxy
1027 server, and u->url will be requested. */
1029 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
1031 struct request *req;
1034 char *user, *passwd;
1038 wgint contlen, contrange;
1045 /* Whether authorization has been already tried. */
1046 int auth_tried_already;
1048 /* Whether our connection to the remote host is through SSL. */
1052 struct response *resp;
1056 /* Whether this connection will be kept alive after the HTTP request
1060 /* Whether keep-alive should be inhibited. */
1061 int inhibit_keep_alive = !opt.http_keep_alive || opt.ignore_length;
1063 /* Headers sent when using POST. */
1064 wgint post_data_size = 0;
1066 int host_lookup_failed = 0;
1069 if (u->scheme == SCHEME_HTTPS)
1071 /* Initialize the SSL context. After this has once been done,
1072 it becomes a no-op. */
1073 switch (ssl_init ())
1075 case SSLERRCTXCREATE:
1077 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
1078 return SSLERRCTXCREATE;
1079 case SSLERRCERTFILE:
1080 /* try without certfile */
1081 logprintf (LOG_NOTQUIET,
1082 _("Failed to load certificates from %s\n"),
1084 logprintf (LOG_NOTQUIET,
1085 _("Trying without the specified certificate\n"));
1088 logprintf (LOG_NOTQUIET,
1089 _("Failed to get certificate key from %s\n"),
1091 logprintf (LOG_NOTQUIET,
1092 _("Trying without the specified certificate\n"));
1098 #endif /* HAVE_SSL */
1100 if (!(*dt & HEAD_ONLY))
1101 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
1102 know the local filename so we can save to it. */
1103 assert (*hs->local_file != NULL);
1105 auth_tried_already = 0;
1107 /* Initialize certain elements of struct http_stat. */
1112 hs->remote_time = NULL;
1117 /* Prepare the request to send. */
1119 req = request_new ();
1121 const char *meth = "GET";
1122 if (*dt & HEAD_ONLY)
1124 else if (opt.post_file_name || opt.post_data)
1126 /* Use the full path, i.e. one that includes the leading slash and
1127 the query string. E.g. if u->path is "foo/bar" and u->query is
1128 "param=value", full_path will be "/foo/bar?param=value". */
1129 request_set_method (req, meth,
1130 proxy ? xstrdup (u->url) : url_full_path (u));
1133 request_set_header (req, "Referer", (char *) hs->referer, rel_none);
1134 if (*dt & SEND_NOCACHE)
1135 request_set_header (req, "Pragma", "no-cache", rel_none);
1137 request_set_header (req, "Range",
1138 aprintf ("bytes=%s-",
1139 number_to_static_string (hs->restval)),
1142 request_set_header (req, "User-Agent", opt.useragent, rel_none);
1144 request_set_header (req, "User-Agent",
1145 aprintf ("Wget/%s", version_string), rel_value);
1146 request_set_header (req, "Accept", "*/*", rel_none);
1148 /* Find the username and password for authentication. */
1151 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
1152 user = user ? user : opt.http_user;
1153 passwd = passwd ? passwd : opt.http_passwd;
1157 /* We have the username and the password, but haven't tried
1158 any authorization yet. Let's see if the "Basic" method
1159 works. If not, we'll come back here and construct a
1160 proper authorization method with the right challenges.
1162 If we didn't employ this kind of logic, every URL that
1163 requires authorization would have to be processed twice,
1164 which is very suboptimal and generates a bunch of false
1165 "unauthorized" errors in the server log.
1167 #### But this logic also has a serious problem when used
1168 with stronger authentications: we *first* transmit the
1169 username and the password in clear text, and *then* attempt a
1170 stronger authentication scheme. That cannot be right! We
1171 are only fortunate that almost everyone still uses the
1172 `Basic' scheme anyway.
1174 There should be an option to prevent this from happening, for
1175 those who use strong authentication schemes and value their
1177 request_set_header (req, "Authorization",
1178 basic_authentication_encode (user, passwd),
1185 char *proxy_user, *proxy_passwd;
1186 /* For normal username and password, URL components override
1187 command-line/wgetrc parameters. With proxy
1188 authentication, it's the reverse, because proxy URLs are
1189 normally the "permanent" ones, so command-line args
1190 should take precedence. */
1191 if (opt.proxy_user && opt.proxy_passwd)
1193 proxy_user = opt.proxy_user;
1194 proxy_passwd = opt.proxy_passwd;
1198 proxy_user = proxy->user;
1199 proxy_passwd = proxy->passwd;
1201 /* #### This does not appear right. Can't the proxy request,
1202 say, `Digest' authentication? */
1203 if (proxy_user && proxy_passwd)
1204 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd);
1206 /* If we're using a proxy, we will be connecting to the proxy
1210 /* Proxy authorization over SSL is handled below. */
1212 if (u->scheme != SCHEME_HTTPS)
1214 request_set_header (req, "Proxy-Authorization", proxyauth, rel_value);
1218 /* Whether we need to print the host header with braces around
1219 host, e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the
1220 usual "Host: symbolic-name:1234". */
1221 int squares = strchr (u->host, ':') != NULL;
1222 if (u->port == scheme_default_port (u->scheme))
1223 request_set_header (req, "Host",
1224 aprintf (squares ? "[%s]" : "%s", u->host),
1227 request_set_header (req, "Host",
1228 aprintf (squares ? "[%s]:%d" : "%s:%d",
1233 if (!inhibit_keep_alive)
1234 request_set_header (req, "Connection", "Keep-Alive", rel_none);
1237 request_set_header (req, "Cookie",
1238 cookie_header (wget_cookie_jar,
1239 u->host, u->port, u->path,
1241 u->scheme == SCHEME_HTTPS
1248 if (opt.post_data || opt.post_file_name)
1250 request_set_header (req, "Content-Type",
1251 "application/x-www-form-urlencoded", rel_none);
1253 post_data_size = strlen (opt.post_data);
1256 post_data_size = file_size (opt.post_file_name);
1257 if (post_data_size == -1)
1259 logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
1260 opt.post_file_name);
1264 request_set_header (req, "Content-Length",
1265 xstrdup (number_to_static_string (post_data_size)),
1269 /* Add the user headers. */
1270 if (opt.user_headers)
1273 for (i = 0; opt.user_headers[i]; i++)
1274 request_set_user_header (req, opt.user_headers[i]);
1278 /* We need to come back here when the initial attempt to retrieve
1279 without authorization header fails. (Expected to happen at least
1280 for the Digest authorization scheme.) */
1284 /* Establish the connection. */
1286 if (!inhibit_keep_alive)
1288 /* Look for a persistent connection to target host, unless a
1289 proxy is used. The exception is when SSL is in use, in which
1290 case the proxy is nothing but a passthrough to the target
1291 host, registered as a connection to the latter. */
1292 struct url *relevant = conn;
1294 if (u->scheme == SCHEME_HTTPS)
1298 if (persistent_available_p (relevant->host, relevant->port,
1300 relevant->scheme == SCHEME_HTTPS,
1304 &host_lookup_failed))
1306 sock = pconn.socket;
1307 using_ssl = pconn.ssl;
1308 logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
1309 escnonprint (pconn.host), pconn.port);
1310 DEBUGP (("Reusing fd %d.\n", sock));
1316 /* In its current implementation, persistent_available_p will
1317 look up conn->host in some cases. If that lookup failed, we
1318 don't need to bother with connect_to_host. */
1319 if (host_lookup_failed)
1322 sock = connect_to_host (conn->host, conn->port);
1326 return (retryable_socket_connect_error (errno)
1327 ? CONERROR : CONIMPOSSIBLE);
1330 if (proxy && u->scheme == SCHEME_HTTPS)
1332 /* When requesting SSL URLs through proxies, use the
1333 CONNECT method to request passthrough. */
1334 struct request *connreq = request_new ();
1335 request_set_method (connreq, "CONNECT",
1336 aprintf ("%s:%d", u->host, u->port));
1339 request_set_header (connreq, "Proxy-Authorization",
1340 proxyauth, rel_value);
1341 /* Now that PROXYAUTH is part of the CONNECT request,
1342 zero it out so we don't send proxy authorization with
1343 the regular request below. */
1347 write_error = request_send (connreq, sock);
1348 request_free (connreq);
1349 if (write_error < 0)
1351 logprintf (LOG_VERBOSE, _("Failed writing to proxy: %s.\n"),
1353 CLOSE_INVALIDATE (sock);
1357 head = fd_read_http_head (sock);
1360 logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
1362 CLOSE_INVALIDATE (sock);
1371 DEBUGP (("proxy responded with: [%s]\n", head));
1373 resp = response_new (head);
1374 statcode = response_status (resp, &message);
1375 response_free (resp);
1376 if (statcode != 200)
1379 logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
1380 message ? escnonprint (message) : "?");
1381 xfree_null (message);
1384 xfree_null (message);
1386 /* SOCK is now *really* connected to u->host, so update CONN
1387 to reflect this. That way register_persistent will
1388 register SOCK as being connected to u->host:u->port. */
1392 if (conn->scheme == SCHEME_HTTPS)
1394 if (!ssl_connect (sock))
1401 #endif /* HAVE_SSL */
1404 /* Send the request to server. */
1405 write_error = request_send (req, sock);
1407 if (write_error >= 0)
1411 DEBUGP (("[POST data: %s]\n", opt.post_data));
1412 write_error = fd_write (sock, opt.post_data, post_data_size, -1);
1414 else if (opt.post_file_name && post_data_size != 0)
1415 write_error = post_file (sock, opt.post_file_name, post_data_size);
1418 if (write_error < 0)
1420 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1422 CLOSE_INVALIDATE (sock);
1426 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1427 proxy ? "Proxy" : "HTTP");
1432 head = fd_read_http_head (sock);
1437 logputs (LOG_NOTQUIET, _("No data received.\n"));
1438 CLOSE_INVALIDATE (sock);
1444 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1446 CLOSE_INVALIDATE (sock);
1451 DEBUGP (("\n---response begin---\n%s---response end---\n", head));
1453 resp = response_new (head);
1455 /* Check for status line. */
1457 statcode = response_status (resp, &message);
1458 if (!opt.server_response)
1459 logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
1460 message ? escnonprint (message) : "");
1463 logprintf (LOG_VERBOSE, "\n");
1464 print_server_response (resp, " ");
1467 if (!opt.ignore_length
1468 && response_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
1472 parsed = str_to_wgint (hdrval, NULL, 10);
1473 if (parsed == WGINT_MAX && errno == ERANGE)
1475 #### If Content-Length is out of range, it most likely
1476 means that the file is larger than 2G and that we're
1477 compiled without LFS. In that case we should probably
1478 refuse to even attempt to download the file. */
1484 /* Check for keep-alive related responses. */
1485 if (!inhibit_keep_alive && contlen != -1)
1487 if (response_header_copy (resp, "Keep-Alive", NULL, 0))
1489 else if (response_header_copy (resp, "Connection", hdrval,
1492 if (0 == strcasecmp (hdrval, "Keep-Alive"))
1497 /* The server has promised that it will not close the connection
1498 when we're done. This means that we can register it. */
1499 register_persistent (conn->host, conn->port, sock, using_ssl);
1501 if (statcode == HTTP_STATUS_UNAUTHORIZED)
1503 /* Authorization is required. */
1504 skip_short_body (sock, contlen);
1505 CLOSE_FINISH (sock);
1506 if (auth_tried_already || !(user && passwd))
1508 /* If we have tried it already, then there is not point
1510 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1514 char *www_authenticate = response_header_strdup (resp,
1515 "WWW-Authenticate");
1516 /* If the authentication scheme is unknown or if it's the
1517 "Basic" authentication (which we try by default), there's
1518 no sense in retrying. */
1519 if (!www_authenticate
1520 || !known_authentication_scheme_p (www_authenticate)
1521 || BEGINS_WITH (www_authenticate, "Basic"))
1523 xfree_null (www_authenticate);
1524 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1529 auth_tried_already = 1;
1530 pth = url_full_path (u);
1531 request_set_header (req, "Authorization",
1532 create_authorization_line (www_authenticate,
1534 request_method (req),
1538 xfree (www_authenticate);
1539 goto retry_with_auth;
1547 hs->statcode = statcode;
1549 hs->error = xstrdup (_("Malformed status line"));
1551 hs->error = xstrdup (_("(no description)"));
1553 hs->error = xstrdup (message);
1555 type = response_header_strdup (resp, "Content-Type");
1558 char *tmp = strchr (type, ';');
1561 while (tmp > type && ISSPACE (tmp[-1]))
1566 hs->newloc = response_header_strdup (resp, "Location");
1567 hs->remote_time = response_header_strdup (resp, "Last-Modified");
1569 char *set_cookie = response_header_strdup (resp, "Set-Cookie");
1572 /* The jar should have been created by now. */
1573 assert (wget_cookie_jar != NULL);
1574 cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port, u->path,
1579 if (response_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
1581 wgint first_byte_pos, last_byte_pos, entity_length;
1582 if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
1584 contrange = first_byte_pos;
1586 response_free (resp);
1588 /* 20x responses are counted among successful by default. */
1589 if (H_20X (statcode))
1592 /* Return if redirected. */
1593 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1595 /* RFC2068 says that in case of the 300 (multiple choices)
1596 response, the server can output a preferred URL through
1597 `Location' header; otherwise, the request should be treated
1598 like GET. So, if the location is set, it will be a
1599 redirection; otherwise, just proceed normally. */
1600 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1604 logprintf (LOG_VERBOSE,
1605 _("Location: %s%s\n"),
1606 hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
1607 hs->newloc ? _(" [following]") : "");
1609 skip_short_body (sock, contlen);
1610 CLOSE_FINISH (sock);
1616 /* If content-type is not given, assume text/html. This is because
1617 of the multitude of broken CGI's that "forget" to generate the
1620 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)) ||
1621 0 == strncasecmp (type, TEXTXHTML_S, strlen (TEXTXHTML_S)))
1626 if (opt.html_extension && (*dt & TEXTHTML))
1627 /* -E / --html-extension / html_extension = on was specified, and this is a
1628 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1629 already the file's suffix, tack on ".html". */
1631 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1633 if (last_period_in_local_filename == NULL
1634 || !(0 == strcasecmp (last_period_in_local_filename, ".htm")
1635 || 0 == strcasecmp (last_period_in_local_filename, ".html")))
1637 size_t local_filename_len = strlen(*hs->local_file);
1639 *hs->local_file = xrealloc(*hs->local_file,
1640 local_filename_len + sizeof(".html"));
1641 strcpy(*hs->local_file + local_filename_len, ".html");
1643 *dt |= ADDED_HTML_EXTENSION;
1647 if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE)
1649 /* If `-c' is in use and the file has been fully downloaded (or
1650 the remote file has shrunk), Wget effectively requests bytes
1651 after the end of file and the server response with 416. */
1652 logputs (LOG_VERBOSE, _("\
1653 \n The file is already fully retrieved; nothing to do.\n\n"));
1654 /* In case the caller inspects. */
1657 /* Mark as successfully retrieved. */
1660 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1661 might be more bytes in the body. */
1662 return RETRUNNEEDED;
1664 if ((contrange != 0 && contrange != hs->restval)
1665 || (H_PARTIAL (statcode) && !contrange))
1667 /* The Range request was somehow misunderstood by the server.
1670 CLOSE_INVALIDATE (sock);
1673 hs->contlen = contlen + contrange;
1679 /* No need to print this output if the body won't be
1680 downloaded at all, or if the original server response is
1682 logputs (LOG_VERBOSE, _("Length: "));
1685 logputs (LOG_VERBOSE, legible (contlen + contrange));
1687 logprintf (LOG_VERBOSE, _(" (%s to go)"), legible (contlen));
1690 logputs (LOG_VERBOSE,
1691 opt.ignore_length ? _("ignored") : _("unspecified"));
1693 logprintf (LOG_VERBOSE, " [%s]\n", escnonprint (type));
1695 logputs (LOG_VERBOSE, "\n");
1699 type = NULL; /* We don't need it any more. */
1701 /* Return if we have no intention of further downloading. */
1702 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1704 /* In case the caller cares to look... */
1708 /* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the
1709 servers not to send body in response to a HEAD request. If
1710 you encounter such a server (more likely a broken CGI), use
1711 `--no-http-keep-alive'. */
1712 CLOSE_FINISH (sock);
1713 return RETRFINISHED;
1716 /* Open the local file. */
1719 mkalldirs (*hs->local_file);
1721 rotate_backups (*hs->local_file);
1723 fp = fopen (*hs->local_file, "ab");
1724 else if (opt.noclobber || opt.always_rest || opt.timestamping || opt.dirstruct
1725 || opt.output_document)
1726 fp = fopen (*hs->local_file, "wb");
1729 fp = fopen_excl (*hs->local_file, 0);
1730 if (!fp && errno == EEXIST)
1732 /* We cannot just invent a new name and use it (which is
1733 what functions like unique_create typically do)
1734 because we told the user we'd use this name.
1735 Instead, return and retry the download. */
1736 logprintf (LOG_NOTQUIET,
1737 _("%s has sprung into existence.\n"),
1739 CLOSE_INVALIDATE (sock);
1740 return FOPEN_EXCL_ERR;
1745 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1746 CLOSE_INVALIDATE (sock);
1753 /* #### This confuses the timestamping code that checks for file
1754 size. Maybe we should save some additional information? */
1755 if (opt.save_headers)
1756 fwrite (head, 1, strlen (head), fp);
1758 /* Download the request body. */
1761 flags |= rb_read_exactly;
1762 if (hs->restval > 0 && contrange == 0)
1763 /* If the server ignored our range request, instruct fd_read_body
1764 to skip the first RESTVAL bytes of body. */
1765 flags |= rb_skip_startpos;
1766 hs->len = hs->restval;
1768 hs->res = fd_read_body (sock, fp, contlen != -1 ? contlen : 0,
1769 hs->restval, &hs->rd_size, &hs->len, &hs->dltime,
1773 CLOSE_FINISH (sock);
1775 CLOSE_INVALIDATE (sock);
1778 /* Close or flush the file. We have to be careful to check for
1779 error here. Checking the result of fwrite() is not enough --
1780 errors could go unnoticed! */
1783 flush_res = fclose (fp);
1785 flush_res = fflush (fp);
1786 if (flush_res == EOF)
1791 return RETRFINISHED;
1794 /* The genuine HTTP loop! This is the part where the retrieval is
1795 retried, and retried, and retried, and... */
1797 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1798 int *dt, struct url *proxy)
1801 int use_ts, got_head = 0; /* time-stamping info */
1802 char *filename_plus_orig_suffix;
1803 char *local_filename = NULL;
1804 char *tms, *locf, *tmrate;
1806 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1807 wgint local_size = 0; /* the size of the local file */
1808 size_t filename_len;
1809 struct http_stat hstat; /* HTTP status */
1813 /* This used to be done in main(), but it's a better idea to do it
1814 here so that we don't go through the hoops if we're just using
1818 if (!wget_cookie_jar)
1819 wget_cookie_jar = cookie_jar_new ();
1820 if (opt.cookies_input && !cookies_loaded_p)
1822 cookie_jar_load (wget_cookie_jar, opt.cookies_input);
1823 cookies_loaded_p = 1;
1829 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1830 has_wildcards_p because it would also warn on `?', and we know that
1831 shows up in CGI paths a *lot*. */
1832 if (strchr (u->url, '*'))
1833 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1837 /* Determine the local filename. */
1838 if (local_file && *local_file)
1839 hstat.local_file = local_file;
1840 else if (local_file && !opt.output_document)
1842 *local_file = url_file_name (u);
1843 hstat.local_file = local_file;
1847 dummy = url_file_name (u);
1848 hstat.local_file = &dummy;
1849 /* be honest about where we will save the file */
1850 if (local_file && opt.output_document)
1851 *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);
1854 if (!opt.output_document)
1855 locf = *hstat.local_file;
1857 locf = opt.output_document;
1859 hstat.referer = referer;
1861 filename_len = strlen (*hstat.local_file);
1862 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1864 if (opt.noclobber && file_exists_p (*hstat.local_file))
1866 /* If opt.noclobber is turned on and file already exists, do not
1867 retrieve the file */
1868 logprintf (LOG_VERBOSE, _("\
1869 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1870 /* If the file is there, we suppose it's retrieved OK. */
1873 /* #### Bogusness alert. */
1874 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1875 if (has_html_suffix_p (*hstat.local_file))
1883 if (opt.timestamping)
1885 int local_dot_orig_file_exists = 0;
1887 if (opt.backup_converted)
1888 /* If -K is specified, we'll act on the assumption that it was specified
1889 last time these files were downloaded as well, and instead of just
1890 comparing local file X against server file X, we'll compare local
1891 file X.orig (if extant, else X) against server file X. If -K
1892 _wasn't_ specified last time, or the server contains files called
1893 *.orig, -N will be back to not operating correctly with -k. */
1895 /* Would a single s[n]printf() call be faster? --dan
1897 Definitely not. sprintf() is horribly slow. It's a
1898 different question whether the difference between the two
1899 affects a program. Usually I'd say "no", but at one
1900 point I profiled Wget, and found that a measurable and
1901 non-negligible amount of time was lost calling sprintf()
1902 in url.c. Replacing sprintf with inline calls to
1903 strcpy() and number_to_string() made a difference.
1905 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1906 memcpy (filename_plus_orig_suffix + filename_len,
1907 ".orig", sizeof (".orig"));
1909 /* Try to stat() the .orig file. */
1910 if (stat (filename_plus_orig_suffix, &st) == 0)
1912 local_dot_orig_file_exists = 1;
1913 local_filename = filename_plus_orig_suffix;
1917 if (!local_dot_orig_file_exists)
1918 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1919 if (stat (*hstat.local_file, &st) == 0)
1920 local_filename = *hstat.local_file;
1922 if (local_filename != NULL)
1923 /* There was a local file, so we'll check later to see if the version
1924 the server has is the same version we already have, allowing us to
1930 /* Modification time granularity is 2 seconds for Windows, so
1931 increase local time by 1 second for later comparison. */
1934 local_size = st.st_size;
1938 /* Reset the counter. */
1944 /* Increment the pass counter. */
1946 sleep_between_retrievals (count);
1947 /* Get the current time string. */
1948 tms = time_str (NULL);
1949 /* Print fetch message, if opt.verbose. */
1952 char *hurl = url_string (u, 1);
1956 sprintf (tmp, _("(try:%2d)"), count);
1957 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1958 tms, hurl, tmp, locf);
1960 ws_changetitle (hurl);
1965 /* Default document type is empty. However, if spider mode is
1966 on or time-stamping is employed, HEAD_ONLY commands is
1967 encoded within *dt. */
1968 if (opt.spider || (use_ts && !got_head))
1973 /* Decide whether or not to restart. */
1976 hstat.restval = hstat.len; /* continue where we left off */
1977 else if (opt.always_rest
1978 && stat (locf, &st) == 0
1979 && S_ISREG (st.st_mode))
1980 hstat.restval = st.st_size;
1982 /* Decide whether to send the no-cache directive. We send it in
1984 a) we're using a proxy, and we're past our first retrieval.
1985 Some proxies are notorious for caching incomplete data, so
1986 we require a fresh get.
1987 b) caching is explicitly inhibited. */
1988 if ((proxy && count > 1) /* a */
1989 || !opt.allow_cache /* b */
1991 *dt |= SEND_NOCACHE;
1993 *dt &= ~SEND_NOCACHE;
1995 /* Try fetching the document, or at least its head. */
1996 err = gethttp (u, &hstat, dt, proxy);
1998 /* It's unfortunate that wget determines the local filename before finding
1999 out the Content-Type of the file. Barring a major restructuring of the
2000 code, we need to re-set locf here, since gethttp() may have xrealloc()d
2001 *hstat.local_file to tack on ".html". */
2002 if (!opt.output_document)
2003 locf = *hstat.local_file;
2006 tms = time_str (NULL);
2007 /* Get the new location (with or without the redirection). */
2009 *newloc = xstrdup (hstat.newloc);
2012 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
2013 case CONERROR: case READERR: case WRITEFAILED:
2014 case RANGEERR: case FOPEN_EXCL_ERR:
2015 /* Non-fatal errors continue executing the loop, which will
2016 bring them to "while" statement at the end, to judge
2017 whether the number of tries was exceeded. */
2018 free_hstat (&hstat);
2019 printwhat (count, opt.ntry);
2020 if (err == FOPEN_EXCL_ERR)
2022 /* Re-determine the file name. */
2023 if (local_file && *local_file)
2025 xfree (*local_file);
2026 *local_file = url_file_name (u);
2027 hstat.local_file = local_file;
2032 dummy = url_file_name (u);
2033 hstat.local_file = &dummy;
2035 /* be honest about where we will save the file */
2036 if (local_file && opt.output_document)
2037 *local_file = HYPHENP (opt.output_document) ? NULL : xstrdup (opt.output_document);
2038 if (!opt.output_document)
2039 locf = *hstat.local_file;
2041 locf = opt.output_document;
2045 case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case AUTHFAILED:
2046 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
2047 /* Fatal errors just return from the function. */
2048 free_hstat (&hstat);
2052 case FWRITEERR: case FOPENERR:
2053 /* Another fatal error. */
2054 logputs (LOG_VERBOSE, "\n");
2055 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
2056 *hstat.local_file, strerror (errno));
2057 free_hstat (&hstat);
2062 /* Another fatal error. */
2063 logputs (LOG_VERBOSE, "\n");
2064 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
2065 free_hstat (&hstat);
2070 /* Return the new location to the caller. */
2073 logprintf (LOG_NOTQUIET,
2074 _("ERROR: Redirection (%d) without location.\n"),
2076 free_hstat (&hstat);
2080 free_hstat (&hstat);
2085 /* The file was already fully retrieved. */
2086 free_hstat (&hstat);
2091 /* Deal with you later. */
2094 /* All possibilities should have been exhausted. */
2097 if (!(*dt & RETROKF))
2101 /* #### Ugly ugly ugly! */
2102 char *hurl = url_string (u, 1);
2103 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
2106 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
2107 tms, hstat.statcode, escnonprint (hstat.error));
2108 logputs (LOG_VERBOSE, "\n");
2109 free_hstat (&hstat);
2114 /* Did we get the time-stamp? */
2117 if (opt.timestamping && !hstat.remote_time)
2119 logputs (LOG_NOTQUIET, _("\
2120 Last-modified header missing -- time-stamps turned off.\n"));
2122 else if (hstat.remote_time)
2124 /* Convert the date-string into struct tm. */
2125 tmr = http_atotm (hstat.remote_time);
2126 if (tmr == (time_t) (-1))
2127 logputs (LOG_VERBOSE, _("\
2128 Last-modified header invalid -- time-stamp ignored.\n"));
2132 /* The time-stamping section. */
2137 use_ts = 0; /* no more time-stamping */
2138 count = 0; /* the retrieve count for HEAD is
2140 if (hstat.remote_time && tmr != (time_t) (-1))
2142 /* Now time-stamping can be used validly. Time-stamping
2143 means that if the sizes of the local and remote file
2144 match, and local file is newer than the remote file,
2145 it will not be retrieved. Otherwise, the normal
2146 download procedure is resumed. */
2148 (hstat.contlen == -1 || local_size == hstat.contlen))
2150 logprintf (LOG_VERBOSE, _("\
2151 Server file no newer than local file `%s' -- not retrieving.\n\n"),
2153 free_hstat (&hstat);
2157 else if (tml >= tmr)
2158 logprintf (LOG_VERBOSE, _("\
2159 The sizes do not match (local %s) -- retrieving.\n"),
2160 number_to_static_string (local_size));
2162 logputs (LOG_VERBOSE,
2163 _("Remote file is newer, retrieving.\n"));
2165 free_hstat (&hstat);
2168 if ((tmr != (time_t) (-1))
2170 && ((hstat.len == hstat.contlen) ||
2171 ((hstat.res == 0) &&
2172 ((hstat.contlen == -1) ||
2173 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
2175 /* #### This code repeats in http.c and ftp.c. Move it to a
2177 const char *fl = NULL;
2178 if (opt.output_document)
2180 if (output_stream_regular)
2181 fl = opt.output_document;
2184 fl = *hstat.local_file;
2188 /* End of time-stamping section. */
2192 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode,
2193 escnonprint (hstat.error));
2198 tmrate = retr_rate (hstat.rd_size, hstat.dltime, 0);
2200 if (hstat.len == hstat.contlen)
2204 logprintf (LOG_VERBOSE,
2205 _("%s (%s) - `%s' saved [%s/%s]\n\n"),
2207 number_to_static_string (hstat.len),
2208 number_to_static_string (hstat.contlen));
2209 logprintf (LOG_NONVERBOSE,
2210 "%s URL:%s [%s/%s] -> \"%s\" [%d]\n",
2212 number_to_static_string (hstat.len),
2213 number_to_static_string (hstat.contlen),
2217 total_downloaded_bytes += hstat.len;
2219 /* Remember that we downloaded the file for later ".orig" code. */
2220 if (*dt & ADDED_HTML_EXTENSION)
2221 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2223 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2225 free_hstat (&hstat);
2229 else if (hstat.res == 0) /* No read error */
2231 if (hstat.contlen == -1) /* We don't know how much we were supposed
2232 to get, so assume we succeeded. */
2236 logprintf (LOG_VERBOSE,
2237 _("%s (%s) - `%s' saved [%s]\n\n"),
2239 number_to_static_string (hstat.len));
2240 logprintf (LOG_NONVERBOSE,
2241 "%s URL:%s [%s] -> \"%s\" [%d]\n",
2242 tms, u->url, number_to_static_string (hstat.len),
2246 total_downloaded_bytes += hstat.len;
2248 /* Remember that we downloaded the file for later ".orig" code. */
2249 if (*dt & ADDED_HTML_EXTENSION)
2250 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2252 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2254 free_hstat (&hstat);
2258 else if (hstat.len < hstat.contlen) /* meaning we lost the
2259 connection too soon */
2261 logprintf (LOG_VERBOSE,
2262 _("%s (%s) - Connection closed at byte %s. "),
2263 tms, tmrate, number_to_static_string (hstat.len));
2264 printwhat (count, opt.ntry);
2265 free_hstat (&hstat);
2268 else if (!opt.kill_longer) /* meaning we got more than expected */
2270 logprintf (LOG_VERBOSE,
2271 _("%s (%s) - `%s' saved [%s/%s])\n\n"),
2273 number_to_static_string (hstat.len),
2274 number_to_static_string (hstat.contlen));
2275 logprintf (LOG_NONVERBOSE,
2276 "%s URL:%s [%s/%s] -> \"%s\" [%d]\n",
2278 number_to_static_string (hstat.len),
2279 number_to_static_string (hstat.contlen),
2282 total_downloaded_bytes += hstat.len;
2284 /* Remember that we downloaded the file for later ".orig" code. */
2285 if (*dt & ADDED_HTML_EXTENSION)
2286 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2288 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2290 free_hstat (&hstat);
2294 else /* the same, but not accepted */
2296 logprintf (LOG_VERBOSE,
2297 _("%s (%s) - Connection closed at byte %s/%s. "),
2299 number_to_static_string (hstat.len),
2300 number_to_static_string (hstat.contlen));
2301 printwhat (count, opt.ntry);
2302 free_hstat (&hstat);
2306 else /* now hstat.res can only be -1 */
2308 if (hstat.contlen == -1)
2310 logprintf (LOG_VERBOSE,
2311 _("%s (%s) - Read error at byte %s (%s)."),
2312 tms, tmrate, number_to_static_string (hstat.len),
2314 printwhat (count, opt.ntry);
2315 free_hstat (&hstat);
2318 else /* hstat.res == -1 and contlen is given */
2320 logprintf (LOG_VERBOSE,
2321 _("%s (%s) - Read error at byte %s/%s (%s). "),
2323 number_to_static_string (hstat.len),
2324 number_to_static_string (hstat.contlen),
2326 printwhat (count, opt.ntry);
2327 free_hstat (&hstat);
2334 while (!opt.ntry || (count < opt.ntry));
2338 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2339 than local timezone.
2341 mktime is similar but assumes struct tm, also known as the
2342 "broken-down" form of time, is in local time zone. mktime_from_utc
2343 uses mktime to make the conversion understanding that an offset
2344 will be introduced by the local time assumption.
2346 mktime_from_utc then measures the introduced offset by applying
2347 gmtime to the initial result and applying mktime to the resulting
2348 "broken-down" form. The difference between the two mktime results
2349 is the measured offset which is then subtracted from the initial
2350 mktime result to yield a calendar time which is the value returned.
2352 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2353 consistent offset (the non DST offset) since tm and tm+o might be
2354 on opposite sides of a DST change.
2356 Some implementations of mktime return -1 for the nonexistent
2357 localtime hour at the beginning of DST. In this event, use
2358 mktime(tm - 1hr) + 3600.
2362 gmtime(t+o) --> tm+o
2363 mktime(tm+o) --> t+2o
2364 t+o - (t+2o - t+o) = t
2366 Note that glibc contains a function of the same purpose named
2367 `timegm' (reverse of gmtime). But obviously, it is not universally
2368 available, and unfortunately it is not straightforwardly
2369 extractable for use here. Perhaps configure should detect timegm
2370 and use it where available.
2372 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2373 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2374 Further improved by Roger with assistance from Edward J. Sabol
2375 based on input by Jamie Zawinski. */
2378 mktime_from_utc (struct tm *t)
2389 return -1; /* can't deal with output from strptime */
2400 return -1; /* can't deal with output from gmtime */
2403 return (tl - (tb - tl));
2406 /* Check whether the result of strptime() indicates success.
2407 strptime() returns the pointer to how far it got to in the string.
2408 The processing has been successful if the string is at `GMT' or
2409 `+X', or at the end of the string.
2411 In extended regexp parlance, the function returns 1 if P matches
2412 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2413 can return) is considered a failure and 0 is returned. */
2415 check_end (const char *p)
2419 while (ISSPACE (*p))
2422 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2423 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2429 /* Convert the textual specification of time in TIME_STRING to the
2430 number of seconds since the Epoch.
2432 TIME_STRING can be in any of the three formats RFC2068 allows the
2433 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2434 Timezones are ignored, and should be GMT.
2436 Return the computed time_t representation, or -1 if the conversion
2439 This function uses strptime with various string formats for parsing
2440 TIME_STRING. This results in a parser that is not as lenient in
2441 interpreting TIME_STRING as I would like it to be. Being based on
2442 strptime, it always allows shortened months, one-digit days, etc.,
2443 but due to the multitude of formats in which time can be
2444 represented, an ideal HTTP time parser would be even more
2445 forgiving. It should completely ignore things like week days and
2446 concentrate only on the various forms of representing years,
2447 months, days, hours, minutes, and seconds. For example, it would
2448 be nice if it accepted ISO 8601 out of the box.
2450 I've investigated free and PD code for this purpose, but none was
2451 usable. getdate was big and unwieldy, and had potential copyright
2452 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2453 distributed with phttpd, is excellent, but we cannot use it because
2454 it is not assigned to the FSF. So I stuck it with strptime. */
2457 http_atotm (const char *time_string)
2459 /* NOTE: Solaris strptime man page claims that %n and %t match white
2460 space, but that's not universally available. Instead, we simply
2461 use ` ' to mean "skip all WS", which works under all strptime
2462 implementations I've tested. */
2464 static const char *time_formats[] = {
2465 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2466 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2467 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2468 (google.com uses this for their cookies.) */
2469 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2475 /* According to Roger Beeman, we need to initialize tm_isdst, since
2476 strptime won't do it. */
2479 /* Note that under foreign locales Solaris strptime() fails to
2480 recognize English dates, which renders this function useless. We
2481 solve this by being careful not to affect LC_TIME when
2482 initializing locale.
2484 Another solution would be to temporarily set locale to C, invoke
2485 strptime(), and restore it back. This is slow and dirty,
2486 however, and locale support other than LC_MESSAGES can mess other
2487 things, so I rather chose to stick with just setting LC_MESSAGES.
2489 GNU strptime does not have this problem because it recognizes
2490 both international and local dates. */
2492 for (i = 0; i < countof (time_formats); i++)
2493 if (check_end (strptime (time_string, time_formats[i], &t)))
2494 return mktime_from_utc (&t);
2496 /* All formats have failed. */
2500 /* Authorization support: We support two authorization schemes:
2502 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2504 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2505 consisting of answering to the server's challenge with the proper
2508 /* How many bytes it will take to store LEN bytes in base64. */
2509 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2511 /* Encode the string S of length LENGTH to base64 format and place it
2512 to STORE. STORE will be 0-terminated, and must point to a writable
2513 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2515 base64_encode (const char *s, char *store, int length)
2517 /* Conversion table. */
2518 static char tbl[64] = {
2519 'A','B','C','D','E','F','G','H',
2520 'I','J','K','L','M','N','O','P',
2521 'Q','R','S','T','U','V','W','X',
2522 'Y','Z','a','b','c','d','e','f',
2523 'g','h','i','j','k','l','m','n',
2524 'o','p','q','r','s','t','u','v',
2525 'w','x','y','z','0','1','2','3',
2526 '4','5','6','7','8','9','+','/'
2529 unsigned char *p = (unsigned char *)store;
2531 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2532 for (i = 0; i < length; i += 3)
2534 *p++ = tbl[s[0] >> 2];
2535 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2536 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2537 *p++ = tbl[s[2] & 0x3f];
2540 /* Pad the result if necessary... */
2541 if (i == length + 1)
2543 else if (i == length + 2)
2544 *(p - 1) = *(p - 2) = '=';
2545 /* ...and zero-terminate it. */
2549 /* Create the authentication header contents for the `Basic' scheme.
2550 This is done by encoding the string `USER:PASS' in base64 and
2551 prepending `HEADER: Basic ' to it. */
2553 basic_authentication_encode (const char *user, const char *passwd)
2555 char *t1, *t2, *res;
2556 int len1 = strlen (user) + 1 + strlen (passwd);
2557 int len2 = BASE64_LENGTH (len1);
2559 t1 = (char *)alloca (len1 + 1);
2560 sprintf (t1, "%s:%s", user, passwd);
2562 t2 = (char *)alloca (len2 + 1);
2563 base64_encode (t1, t2, len1);
2565 res = (char *)xmalloc (6 + len2 + 1);
2566 sprintf (res, "Basic %s", t2);
2571 #define SKIP_WS(x) do { \
2572 while (ISSPACE (*(x))) \
2577 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2578 of a field in such a header. If the field is the one specified by
2579 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2580 digest authorization code), extract its value in the (char*)
2581 variable pointed by RET. Returns negative on a malformed header,
2582 or number of bytes that have been parsed by this call. */
2584 extract_header_attr (const char *au, const char *attr_name, char **ret)
2587 const char *cp = au;
2589 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2591 cp += strlen (attr_name);
2604 for (ep = cp; *ep && *ep != '\"'; ep++)
2609 *ret = strdupdelim (cp, ep);
2616 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2617 an array of 16 bytes containing the hash keys, and BUF should be a
2618 buffer of 33 writable characters (32 for hex digits plus one for
2619 zero termination). */
2621 dump_hash (unsigned char *buf, const unsigned char *hash)
2625 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2627 *buf++ = XNUM_TO_digit (*hash >> 4);
2628 *buf++ = XNUM_TO_digit (*hash & 0xf);
2633 /* Take the line apart to find the challenge, and compose a digest
2634 authorization header. See RFC2069 section 2.1.2. */
2636 digest_authentication_encode (const char *au, const char *user,
2637 const char *passwd, const char *method,
2640 static char *realm, *opaque, *nonce;
2645 { "realm", &realm },
2646 { "opaque", &opaque },
2651 realm = opaque = nonce = NULL;
2653 au += 6; /* skip over `Digest' */
2659 for (i = 0; i < countof (options); i++)
2661 int skip = extract_header_attr (au, options[i].name,
2662 options[i].variable);
2666 xfree_null (opaque);
2676 if (i == countof (options))
2678 while (*au && *au != '=')
2686 while (*au && *au != '\"')
2693 while (*au && *au != ',')
2698 if (!realm || !nonce || !user || !passwd || !path || !method)
2701 xfree_null (opaque);
2706 /* Calculate the digest value. */
2708 ALLOCA_MD5_CONTEXT (ctx);
2709 unsigned char hash[MD5_HASHLEN];
2710 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2711 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2713 /* A1BUF = H(user ":" realm ":" password) */
2715 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2716 gen_md5_update ((unsigned char *)":", 1, ctx);
2717 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2718 gen_md5_update ((unsigned char *)":", 1, ctx);
2719 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2720 gen_md5_finish (ctx, hash);
2721 dump_hash (a1buf, hash);
2723 /* A2BUF = H(method ":" path) */
2725 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2726 gen_md5_update ((unsigned char *)":", 1, ctx);
2727 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2728 gen_md5_finish (ctx, hash);
2729 dump_hash (a2buf, hash);
2731 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2733 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2734 gen_md5_update ((unsigned char *)":", 1, ctx);
2735 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2736 gen_md5_update ((unsigned char *)":", 1, ctx);
2737 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2738 gen_md5_finish (ctx, hash);
2739 dump_hash (response_digest, hash);
2741 res = (char*) xmalloc (strlen (user)
2746 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2747 + (opaque ? strlen (opaque) : 0)
2749 sprintf (res, "Digest \
2750 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2751 user, realm, nonce, path, response_digest);
2754 char *p = res + strlen (res);
2755 strcat (p, ", opaque=\"");
2762 #endif /* USE_DIGEST */
2765 #define BEGINS_WITH(line, string_constant) \
2766 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2767 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2768 || !line[sizeof (string_constant) - 1]))
2771 known_authentication_scheme_p (const char *au)
2773 return BEGINS_WITH (au, "Basic")
2774 || BEGINS_WITH (au, "Digest")
2775 || BEGINS_WITH (au, "NTLM");
2780 /* Create the HTTP authorization request header. When the
2781 `WWW-Authenticate' response header is seen, according to the
2782 authorization scheme specified in that header (`Basic' and `Digest'
2783 are supported by the current implementation), produce an
2784 appropriate HTTP authorization request header. */
2786 create_authorization_line (const char *au, const char *user,
2787 const char *passwd, const char *method,
2790 if (0 == strncasecmp (au, "Basic", 5))
2791 return basic_authentication_encode (user, passwd);
2793 if (0 == strncasecmp (au, "Digest", 6))
2794 return digest_authentication_encode (au, user, passwd, method, path);
2795 #endif /* USE_DIGEST */