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", aprintf ("bytes=%ld-", hs->restval),
227 request_set_header (struct request *req, char *name, char *value,
228 enum rp release_policy)
230 struct request_header *hdr;
234 for (i = 0; i < req->hcount; i++)
236 hdr = &req->headers[i];
237 if (0 == strcasecmp (name, hdr->name))
239 /* Replace existing header. */
240 release_header (hdr);
243 hdr->release_policy = release_policy;
248 /* Install new header. */
250 if (req->hcount >= req->hcount)
252 req->hcapacity <<= 1;
253 req->headers = xrealloc (req->headers,
254 req->hcapacity * sizeof (struct request_header));
256 hdr = &req->headers[req->hcount++];
259 hdr->release_policy = release_policy;
262 /* Like request_set_header, but sets the whole header line, as
263 provided by the user using the `--header' option. For example,
264 request_set_user_header (req, "Foo: bar") works just like
265 request_set_header (req, "Foo", "bar"). */
268 request_set_user_header (struct request *req, const char *header)
271 const char *p = strchr (header, ':');
274 BOUNDED_TO_ALLOCA (header, p, name);
278 request_set_header (req, xstrdup (name), (char *) p, rel_name);
281 #define APPEND(p, str) do { \
282 int A_len = strlen (str); \
283 memcpy (p, str, A_len); \
287 /* Construct the request and write it to FD using fd_write. */
290 request_send (const struct request *req, int fd)
292 char *request_string, *p;
293 int i, size, write_error;
295 /* Count the request size. */
298 /* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
299 size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
301 for (i = 0; i < req->hcount; i++)
303 struct request_header *hdr = &req->headers[i];
304 /* NAME ": " VALUE "\r\n" */
305 size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
311 p = request_string = alloca_array (char, size);
313 /* Generate the request. */
315 APPEND (p, req->method); *p++ = ' ';
316 APPEND (p, req->arg); *p++ = ' ';
317 memcpy (p, "HTTP/1.0\r\n", 10); p += 10;
319 for (i = 0; i < req->hcount; i++)
321 struct request_header *hdr = &req->headers[i];
322 APPEND (p, hdr->name);
323 *p++ = ':', *p++ = ' ';
324 APPEND (p, hdr->value);
325 *p++ = '\r', *p++ = '\n';
328 *p++ = '\r', *p++ = '\n', *p++ = '\0';
329 assert (p - request_string == size);
333 DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
335 /* Send the request to the server. */
337 write_error = fd_write (fd, request_string, size - 1, -1);
339 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
344 /* Release the resources used by REQ. */
347 request_free (struct request *req)
350 xfree_null (req->arg);
351 for (i = 0; i < req->hcount; i++)
352 release_header (&req->headers[i]);
353 xfree_null (req->headers);
357 /* Send the contents of FILE_NAME to SOCK/SSL. Make sure that exactly
358 PROMISED_SIZE bytes are sent over the wire -- if the file is
359 longer, read only that much; if the file is shorter, report an error. */
362 post_file (int sock, const char *file_name, long promised_size)
364 static char chunk[8192];
369 DEBUGP (("[writing POST file %s ... ", file_name));
371 fp = fopen (file_name, "rb");
374 while (!feof (fp) && written < promised_size)
377 int length = fread (chunk, 1, sizeof (chunk), fp);
380 towrite = MIN (promised_size - written, length);
381 write_error = fd_write (sock, chunk, towrite, -1);
391 /* If we've written less than was promised, report a (probably
392 nonsensical) error rather than break the promise. */
393 if (written < promised_size)
399 assert (written == promised_size);
400 DEBUGP (("done]\n"));
405 head_terminator (const char *hunk, int oldlen, int peeklen)
407 const char *start, *end;
409 /* If at first peek, verify whether HUNK starts with "HTTP". If
410 not, this is a HTTP/0.9 request and we must bail out without
412 if (oldlen == 0 && 0 != memcmp (hunk, "HTTP", MIN (peeklen, 4)))
418 start = hunk + oldlen - 4;
419 end = hunk + oldlen + peeklen;
421 for (; start < end - 1; start++)
428 if (start[1] == '\n')
434 /* Read the HTTP request head from FD and return it. The error
435 conditions are the same as with fd_read_hunk.
437 To support HTTP/0.9 responses, this function tries to make sure
438 that the data begins with "HTTP". If this is not the case, no data
439 is read and an empty request is returned, so that the remaining
440 data can be treated as body. */
443 fd_read_http_head (int fd)
445 return fd_read_hunk (fd, head_terminator, 512);
449 /* The response data. */
452 /* The array of pointers that indicate where each header starts.
453 For example, given this HTTP response:
460 The headers are located like this:
462 "HTTP/1.0 200 Ok\r\nDescription: some\r\n text\r\nEtag: x\r\n\r\n"
464 headers[0] headers[1] headers[2] headers[3]
466 I.e. headers[0] points to the beginning of the request,
467 headers[1] points to the end of the first header and the
468 beginning of the second one, etc. */
470 const char **headers;
473 /* Create a new response object from the text of the HTTP response,
474 available in HEAD. That text is automatically split into
475 constituent header lines for fast retrieval using
476 response_header_*. */
478 static struct response *
479 response_new (const char *head)
484 struct response *resp = xnew0 (struct response);
489 /* Empty head means that we're dealing with a headerless
490 (HTTP/0.9) response. In that case, don't set HEADERS at
495 /* Split HEAD into header lines, so that response_header_* functions
496 don't need to do this over and over again. */
502 DO_REALLOC (resp->headers, size, count + 1, const char *);
503 resp->headers[count++] = hdr;
505 /* Break upon encountering an empty line. */
506 if (!hdr[0] || (hdr[0] == '\r' && hdr[1] == '\n') || hdr[0] == '\n')
509 /* Find the end of HDR, including continuations. */
512 const char *end = strchr (hdr, '\n');
518 while (*hdr == ' ' || *hdr == '\t');
520 DO_REALLOC (resp->headers, size, count + 1, const char *);
521 resp->headers[count++] = NULL;
526 /* Locate the header named NAME in the request data. If found, set
527 *BEGPTR to its starting, and *ENDPTR to its ending position, and
528 return 1. Otherwise return 0.
530 This function is used as a building block for response_header_copy
531 and response_header_strdup. */
534 response_header_bounds (const struct response *resp, const char *name,
535 const char **begptr, const char **endptr)
538 const char **headers = resp->headers;
541 if (!headers || !headers[1])
544 name_len = strlen (name);
546 for (i = 1; headers[i + 1]; i++)
548 const char *b = headers[i];
549 const char *e = headers[i + 1];
551 && b[name_len] == ':'
552 && 0 == strncasecmp (b, name, name_len))
555 while (b < e && ISSPACE (*b))
557 while (b < e && ISSPACE (e[-1]))
567 /* Copy the response header named NAME to buffer BUF, no longer than
568 BUFSIZE (BUFSIZE includes the terminating 0). If the header
569 exists, 1 is returned, otherwise 0. If there should be no limit on
570 the size of the header, use response_header_strdup instead.
572 If BUFSIZE is 0, no data is copied, but the boolean indication of
573 whether the header is present is still returned. */
576 response_header_copy (const struct response *resp, const char *name,
577 char *buf, int bufsize)
580 if (!response_header_bounds (resp, name, &b, &e))
584 int len = MIN (e - b, bufsize - 1);
585 memcpy (buf, b, len);
591 /* Return the value of header named NAME in RESP, allocated with
592 malloc. If such a header does not exist in RESP, return NULL. */
595 response_header_strdup (const struct response *resp, const char *name)
598 if (!response_header_bounds (resp, name, &b, &e))
600 return strdupdelim (b, e);
603 /* Parse the HTTP status line, which is of format:
605 HTTP-Version SP Status-Code SP Reason-Phrase
607 The function returns the status-code, or -1 if the status line
608 appears malformed. The pointer to "reason-phrase" message is
609 returned in *MESSAGE. */
612 response_status (const struct response *resp, char **message)
619 /* For a HTTP/0.9 response, assume status 200. */
621 *message = xstrdup (_("No headers, assuming HTTP/0.9"));
625 p = resp->headers[0];
626 end = resp->headers[1];
632 if (end - p < 4 || 0 != strncmp (p, "HTTP", 4))
636 /* Match the HTTP version. This is optional because Gnutella
637 servers have been reported to not specify HTTP version. */
638 if (p < end && *p == '/')
641 while (p < end && ISDIGIT (*p))
643 if (p < end && *p == '.')
645 while (p < end && ISDIGIT (*p))
649 while (p < end && ISSPACE (*p))
651 if (end - p < 3 || !ISDIGIT (p[0]) || !ISDIGIT (p[1]) || !ISDIGIT (p[2]))
654 status = 100 * (p[0] - '0') + 10 * (p[1] - '0') + (p[2] - '0');
659 while (p < end && ISSPACE (*p))
661 while (p < end && ISSPACE (end[-1]))
663 *message = strdupdelim (p, end);
669 /* Release the resources used by RESP. */
672 response_free (struct response *resp)
674 xfree_null (resp->headers);
678 /* Print [b, e) to the log, omitting the trailing CRLF. */
681 print_server_response_1 (const char *prefix, const char *b, const char *e)
684 if (b < e && e[-1] == '\n')
686 if (b < e && e[-1] == '\r')
688 BOUNDED_TO_ALLOCA (b, e, ln);
689 logprintf (LOG_VERBOSE, "%s%s\n", prefix, ln);
692 /* Print the server response, line by line, omitting the trailing CR
693 characters, prefixed with PREFIX. */
696 print_server_response (const struct response *resp, const char *prefix)
701 for (i = 0; resp->headers[i + 1]; i++)
702 print_server_response_1 (prefix, resp->headers[i], resp->headers[i + 1]);
705 /* Parse the `Content-Range' header and extract the information it
706 contains. Returns 1 if successful, -1 otherwise. */
708 parse_content_range (const char *hdr, long *first_byte_ptr,
709 long *last_byte_ptr, long *entity_length_ptr)
713 /* Ancient versions of Netscape proxy server, presumably predating
714 rfc2068, sent out `Content-Range' without the "bytes"
716 if (!strncasecmp (hdr, "bytes", 5))
719 /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
723 while (ISSPACE (*hdr))
730 for (num = 0; ISDIGIT (*hdr); hdr++)
731 num = 10 * num + (*hdr - '0');
732 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
734 *first_byte_ptr = num;
736 for (num = 0; ISDIGIT (*hdr); hdr++)
737 num = 10 * num + (*hdr - '0');
738 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
740 *last_byte_ptr = num;
742 for (num = 0; ISDIGIT (*hdr); hdr++)
743 num = 10 * num + (*hdr - '0');
744 *entity_length_ptr = num;
748 /* Read the body of the request, but don't store it anywhere and don't
749 display a progress gauge. This is useful for reading the error
750 responses whose bodies don't need to be displayed or logged, but
751 which need to be read anyway. */
754 skip_short_body (int fd, long contlen)
756 /* Skipping the body doesn't make sense if the content length is
757 unknown because, in that case, persistent connections cannot be
758 used. (#### This is not the case with HTTP/1.1 where they can
759 still be used with the magic of the "chunked" transfer!) */
762 DEBUGP (("Skipping %ld bytes of body data... ", contlen));
767 int ret = fd_read (fd, dlbuf, MIN (contlen, sizeof (dlbuf)), -1);
772 DEBUGP (("done.\n"));
775 /* Persistent connections. Currently, we cache the most recently used
776 connection as persistent, provided that the HTTP server agrees to
777 make it such. The persistence data is stored in the variables
778 below. Ideally, it should be possible to cache an arbitrary fixed
779 number of these connections. */
781 /* Whether a persistent connection is active. */
782 static int pconn_active;
785 /* The socket of the connection. */
788 /* Host and port of the currently active persistent connection. */
792 /* Whether a ssl handshake has occoured on this connection. */
796 /* Mark the persistent connection as invalid and free the resources it
797 uses. This is used by the CLOSE_* macros after they forcefully
798 close a registered persistent connection. */
801 invalidate_persistent (void)
803 DEBUGP (("Disabling further reuse of socket %d.\n", pconn.socket));
805 fd_close (pconn.socket);
810 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
811 persistent. This will enable someone to use the same connection
812 later. In the context of HTTP, this must be called only AFTER the
813 response has been received and the server has promised that the
814 connection will remain alive.
816 If a previous connection was persistent, it is closed. */
819 register_persistent (const char *host, int port, int fd, int ssl)
823 if (pconn.socket == fd)
825 /* The connection FD is already registered. */
830 /* The old persistent connection is still active; close it
831 first. This situation arises whenever a persistent
832 connection exists, but we then connect to a different
833 host, and try to register a persistent connection to that
835 invalidate_persistent ();
841 pconn.host = xstrdup (host);
845 DEBUGP (("Registered socket %d for persistent reuse.\n", fd));
848 /* Return non-zero if a persistent connection is available for
849 connecting to HOST:PORT. */
852 persistent_available_p (const char *host, int port, int ssl,
853 int *host_lookup_failed)
855 /* First, check whether a persistent connection is active at all. */
859 /* If we want SSL and the last connection wasn't or vice versa,
860 don't use it. Checking for host and port is not enough because
861 HTTP and HTTPS can apparently coexist on the same port. */
862 if (ssl != pconn.ssl)
865 /* If we're not connecting to the same port, we're not interested. */
866 if (port != pconn.port)
869 /* If the host is the same, we're in business. If not, there is
870 still hope -- read below. */
871 if (0 != strcasecmp (host, pconn.host))
873 /* If pconn.socket is already talking to HOST, we needn't
874 reconnect. This happens often when both sites are virtual
875 hosts distinguished only by name and served by the same
876 network interface, and hence the same web server (possibly
877 set up by the ISP and serving many different web sites).
878 This admittedly non-standard optimization does not contradict
879 HTTP and works well with popular server software. */
883 struct address_list *al;
886 /* Don't try to talk to two different SSL sites over the same
887 secure connection! (Besides, it's not clear if name-based
888 virtual hosting is even possible with SSL.) */
891 /* If pconn.socket's peer is one of the IP addresses HOST
892 resolves to, pconn.socket is for all intents and purposes
893 already talking to HOST. */
895 if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER))
897 /* Can't get the peer's address -- something must be very
898 wrong with the connection. */
899 invalidate_persistent ();
902 al = lookup_host (host, 0);
905 *host_lookup_failed = 1;
909 found = address_list_contains (al, &ip);
910 address_list_release (al);
915 /* The persistent connection's peer address was found among the
916 addresses HOST resolved to; therefore, pconn.sock is in fact
917 already talking to HOST -- no need to reconnect. */
920 /* Finally, check whether the connection is still open. This is
921 important because most server implement a liberal (short) timeout
922 on persistent connections. Wget can of course always reconnect
923 if the connection doesn't work out, but it's nicer to know in
924 advance. This test is a logical followup of the first test, but
925 is "expensive" and therefore placed at the end of the list. */
927 if (!test_socket_open (pconn.socket))
929 /* Oops, the socket is no longer open. Now that we know that,
930 let's invalidate the persistent connection before returning
932 invalidate_persistent ();
939 /* The idea behind these two CLOSE macros is to distinguish between
940 two cases: one when the job we've been doing is finished, and we
941 want to close the connection and leave, and two when something is
942 seriously wrong and we're closing the connection as part of
945 In case of keep_alive, CLOSE_FINISH should leave the connection
946 open, while CLOSE_INVALIDATE should still close it.
948 Note that the semantics of the flag `keep_alive' is "this
949 connection *will* be reused (the server has promised not to close
950 the connection once we're done)", while the semantics of
951 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
952 active, registered connection". */
954 #define CLOSE_FINISH(fd) do { \
957 if (pconn_active && (fd) == pconn.socket) \
958 invalidate_persistent (); \
967 #define CLOSE_INVALIDATE(fd) do { \
968 if (pconn_active && (fd) == pconn.socket) \
969 invalidate_persistent (); \
977 long len; /* received length */
978 long contlen; /* expected length */
979 long restval; /* the restart value */
980 int res; /* the result of last read */
981 char *newloc; /* new location (redirection) */
982 char *remote_time; /* remote time-stamp string */
983 char *error; /* textual HTTP error */
984 int statcode; /* status code */
985 long rd_size; /* amount of data read from socket */
986 double dltime; /* time it took to download the data */
987 const char *referer; /* value of the referer header. */
988 char **local_file; /* local file. */
992 free_hstat (struct http_stat *hs)
994 xfree_null (hs->newloc);
995 xfree_null (hs->remote_time);
996 xfree_null (hs->error);
998 /* Guard against being called twice. */
1000 hs->remote_time = NULL;
1004 static char *create_authorization_line PARAMS ((const char *, const char *,
1005 const char *, const char *,
1007 static char *basic_authentication_encode PARAMS ((const char *, const char *));
1008 static int known_authentication_scheme_p PARAMS ((const char *));
1010 time_t http_atotm PARAMS ((const char *));
1012 #define BEGINS_WITH(line, string_constant) \
1013 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
1014 && (ISSPACE (line[sizeof (string_constant) - 1]) \
1015 || !line[sizeof (string_constant) - 1]))
1017 /* Retrieve a document through HTTP protocol. It recognizes status
1018 code, and correctly handles redirections. It closes the network
1019 socket. If it receives an error from the functions below it, it
1020 will print it if there is enough information to do so (almost
1021 always), returning the error to the caller (i.e. http_loop).
1023 Various HTTP parameters are stored to hs.
1025 If PROXY is non-NULL, the connection will be made to the proxy
1026 server, and u->url will be requested. */
1028 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
1030 struct request *req;
1033 char *user, *passwd;
1037 long contlen, contrange;
1044 /* Whether authorization has been already tried. */
1045 int auth_tried_already = 0;
1047 /* Whether our connection to the remote host is through SSL. */
1051 struct response *resp;
1055 /* Whether this connection will be kept alive after the HTTP request
1059 /* Whether keep-alive should be inhibited. */
1060 int inhibit_keep_alive = !opt.http_keep_alive || opt.ignore_length;
1062 /* Headers sent when using POST. */
1063 long post_data_size = 0;
1065 int host_lookup_failed = 0;
1068 if (u->scheme == SCHEME_HTTPS)
1070 /* Initialize the SSL context. After this has once been done,
1071 it becomes a no-op. */
1072 switch (ssl_init ())
1074 case SSLERRCTXCREATE:
1076 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
1077 return SSLERRCTXCREATE;
1078 case SSLERRCERTFILE:
1079 /* try without certfile */
1080 logprintf (LOG_NOTQUIET,
1081 _("Failed to load certificates from %s\n"),
1083 logprintf (LOG_NOTQUIET,
1084 _("Trying without the specified certificate\n"));
1087 logprintf (LOG_NOTQUIET,
1088 _("Failed to get certificate key from %s\n"),
1090 logprintf (LOG_NOTQUIET,
1091 _("Trying without the specified certificate\n"));
1097 #endif /* HAVE_SSL */
1099 if (!(*dt & HEAD_ONLY))
1100 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
1101 know the local filename so we can save to it. */
1102 assert (*hs->local_file != NULL);
1104 auth_tried_already = 0;
1106 /* Initialize certain elements of struct http_stat. */
1111 hs->remote_time = NULL;
1116 /* Prepare the request to send. */
1118 req = request_new ();
1120 const char *meth = "GET";
1121 if (*dt & HEAD_ONLY)
1123 else if (opt.post_file_name || opt.post_data)
1125 /* Use the full path, i.e. one that includes the leading slash and
1126 the query string. E.g. if u->path is "foo/bar" and u->query is
1127 "param=value", full_path will be "/foo/bar?param=value". */
1128 request_set_method (req, meth,
1129 proxy ? xstrdup (u->url) : url_full_path (u));
1132 request_set_header (req, "Referer", (char *) hs->referer, rel_none);
1133 if (*dt & SEND_NOCACHE)
1134 request_set_header (req, "Pragma", "no-cache", rel_none);
1136 request_set_header (req, "Range",
1137 aprintf ("bytes=%ld-", hs->restval), rel_value);
1139 request_set_header (req, "User-Agent", opt.useragent, rel_none);
1141 request_set_header (req, "User-Agent",
1142 aprintf ("Wget/%s", version_string), rel_value);
1143 request_set_header (req, "Accept", "*/*", rel_none);
1145 /* Find the username and password for authentication. */
1148 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
1149 user = user ? user : opt.http_user;
1150 passwd = passwd ? passwd : opt.http_passwd;
1154 /* We have the username and the password, but haven't tried
1155 any authorization yet. Let's see if the "Basic" method
1156 works. If not, we'll come back here and construct a
1157 proper authorization method with the right challenges.
1159 If we didn't employ this kind of logic, every URL that
1160 requires authorization would have to be processed twice,
1161 which is very suboptimal and generates a bunch of false
1162 "unauthorized" errors in the server log.
1164 #### But this logic also has a serious problem when used
1165 with stronger authentications: we *first* transmit the
1166 username and the password in clear text, and *then* attempt a
1167 stronger authentication scheme. That cannot be right! We
1168 are only fortunate that almost everyone still uses the
1169 `Basic' scheme anyway.
1171 There should be an option to prevent this from happening, for
1172 those who use strong authentication schemes and value their
1174 request_set_header (req, "Authorization",
1175 basic_authentication_encode (user, passwd),
1182 char *proxy_user, *proxy_passwd;
1183 /* For normal username and password, URL components override
1184 command-line/wgetrc parameters. With proxy
1185 authentication, it's the reverse, because proxy URLs are
1186 normally the "permanent" ones, so command-line args
1187 should take precedence. */
1188 if (opt.proxy_user && opt.proxy_passwd)
1190 proxy_user = opt.proxy_user;
1191 proxy_passwd = opt.proxy_passwd;
1195 proxy_user = proxy->user;
1196 proxy_passwd = proxy->passwd;
1198 /* #### This does not appear right. Can't the proxy request,
1199 say, `Digest' authentication? */
1200 if (proxy_user && proxy_passwd)
1201 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd);
1203 /* If we're using a proxy, we will be connecting to the proxy
1207 /* Proxy authorization over SSL is handled below. */
1209 if (u->scheme != SCHEME_HTTPS)
1211 request_set_header (req, "Proxy-Authorization", proxyauth, rel_value);
1215 /* Whether we need to print the host header with braces around
1216 host, e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the
1217 usual "Host: symbolic-name:1234". */
1218 int squares = strchr (u->host, ':') != NULL;
1219 if (u->port == scheme_default_port (u->scheme))
1220 request_set_header (req, "Host",
1221 aprintf (squares ? "[%s]" : "%s", u->host),
1224 request_set_header (req, "Host",
1225 aprintf (squares ? "[%s]:%d" : "%s:%d",
1230 if (!inhibit_keep_alive)
1231 request_set_header (req, "Connection", "Keep-Alive", rel_none);
1234 request_set_header (req, "Cookie",
1235 cookie_header (wget_cookie_jar,
1236 u->host, u->port, u->path,
1238 u->scheme == SCHEME_HTTPS
1245 if (opt.post_data || opt.post_file_name)
1247 request_set_header (req, "Content-Type",
1248 "application/x-www-form-urlencoded", rel_none);
1250 post_data_size = strlen (opt.post_data);
1253 post_data_size = file_size (opt.post_file_name);
1254 if (post_data_size == -1)
1256 logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
1257 opt.post_file_name);
1261 request_set_header (req, "Content-Length",
1262 aprintf ("%ld", post_data_size), rel_value);
1265 /* Add the user headers. */
1266 if (opt.user_headers)
1269 for (i = 0; opt.user_headers[i]; i++)
1270 request_set_user_header (req, opt.user_headers[i]);
1274 /* We need to come back here when the initial attempt to retrieve
1275 without authorization header fails. (Expected to happen at least
1276 for the Digest authorization scheme.) */
1280 /* Establish the connection. */
1282 if (!inhibit_keep_alive)
1284 /* Look for a persistent connection to target host, unless a
1285 proxy is used. The exception is when SSL is in use, in which
1286 case the proxy is nothing but a passthrough to the target
1287 host, registered as a connection to the latter. */
1288 struct url *relevant = conn;
1290 if (u->scheme == SCHEME_HTTPS)
1294 if (persistent_available_p (relevant->host, relevant->port,
1296 relevant->scheme == SCHEME_HTTPS,
1300 &host_lookup_failed))
1302 sock = pconn.socket;
1303 using_ssl = pconn.ssl;
1304 logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
1305 pconn.host, pconn.port);
1306 DEBUGP (("Reusing fd %d.\n", sock));
1312 /* In its current implementation, persistent_available_p will
1313 look up conn->host in some cases. If that lookup failed, we
1314 don't need to bother with connect_to_host. */
1315 if (host_lookup_failed)
1318 sock = connect_to_host (conn->host, conn->port);
1322 return (retryable_socket_connect_error (errno)
1323 ? CONERROR : CONIMPOSSIBLE);
1326 if (proxy && u->scheme == SCHEME_HTTPS)
1328 /* When requesting SSL URLs through proxies, use the
1329 CONNECT method to request passthrough. */
1330 struct request *connreq = request_new ();
1331 request_set_method (connreq, "CONNECT",
1332 aprintf ("%s:%d", u->host, u->port));
1335 request_set_header (connreq, "Proxy-Authorization",
1336 proxyauth, rel_value);
1337 /* Now that PROXYAUTH is part of the CONNECT request,
1338 zero it out so we don't send proxy authorization with
1339 the regular request below. */
1343 write_error = request_send (connreq, sock);
1344 request_free (connreq);
1345 if (write_error < 0)
1347 logprintf (LOG_VERBOSE, _("Failed writing to proxy: %s.\n"),
1349 CLOSE_INVALIDATE (sock);
1353 head = fd_read_http_head (sock);
1356 logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
1358 CLOSE_INVALIDATE (sock);
1367 DEBUGP (("proxy responded with: [%s]\n", head));
1369 resp = response_new (head);
1370 statcode = response_status (resp, &message);
1371 response_free (resp);
1372 if (statcode != 200)
1375 logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
1376 message ? message : "?");
1377 xfree_null (message);
1382 /* SOCK is now *really* connected to u->host, so update CONN
1383 to reflect this. That way register_persistent will
1384 register SOCK as being connected to u->host:u->port. */
1388 if (conn->scheme == SCHEME_HTTPS)
1390 if (!ssl_connect (sock))
1397 #endif /* HAVE_SSL */
1400 /* Send the request to server. */
1401 write_error = request_send (req, sock);
1403 if (write_error >= 0)
1407 DEBUGP (("[POST data: %s]\n", opt.post_data));
1408 write_error = fd_write (sock, opt.post_data, post_data_size, -1);
1410 else if (opt.post_file_name && post_data_size != 0)
1411 write_error = post_file (sock, opt.post_file_name, post_data_size);
1414 if (write_error < 0)
1416 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1418 CLOSE_INVALIDATE (sock);
1422 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1423 proxy ? "Proxy" : "HTTP");
1430 head = fd_read_http_head (sock);
1435 logputs (LOG_NOTQUIET, _("No data received.\n"));
1436 CLOSE_INVALIDATE (sock);
1442 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1444 CLOSE_INVALIDATE (sock);
1449 DEBUGP (("\n---response begin---\n%s---response end---\n", head));
1451 resp = response_new (head);
1453 /* Check for status line. */
1455 statcode = response_status (resp, &message);
1456 if (!opt.server_response)
1457 logprintf (LOG_VERBOSE, "%2d %s\n", statcode, message ? message : "");
1460 logprintf (LOG_VERBOSE, "\n");
1461 print_server_response (resp, " ");
1464 if (!opt.ignore_length
1465 && response_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
1466 contlen = strtol (hdrval, NULL, 10);
1468 /* Check for keep-alive related responses. */
1469 if (!inhibit_keep_alive && contlen != -1)
1471 if (response_header_copy (resp, "Keep-Alive", NULL, 0))
1473 else if (response_header_copy (resp, "Connection", hdrval,
1476 if (0 == strcasecmp (hdrval, "Keep-Alive"))
1481 /* The server has promised that it will not close the connection
1482 when we're done. This means that we can register it. */
1483 register_persistent (conn->host, conn->port, sock, using_ssl);
1485 if (statcode == HTTP_STATUS_UNAUTHORIZED)
1487 /* Authorization is required. */
1488 skip_short_body (sock, contlen);
1489 CLOSE_FINISH (sock);
1490 if (auth_tried_already || !(user && passwd))
1492 /* If we have tried it already, then there is not point
1494 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1498 char *www_authenticate = response_header_strdup (resp,
1499 "WWW-Authenticate");
1500 /* If the authentication scheme is unknown or if it's the
1501 "Basic" authentication (which we try by default), there's
1502 no sense in retrying. */
1503 if (!www_authenticate
1504 || !known_authentication_scheme_p (www_authenticate)
1505 || BEGINS_WITH (www_authenticate, "Basic"))
1507 xfree_null (www_authenticate);
1508 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1513 auth_tried_already = 1;
1514 pth = url_full_path (u);
1515 request_set_header (req, "Authorization",
1516 create_authorization_line (www_authenticate,
1518 request_method (req),
1522 xfree (www_authenticate);
1523 goto retry_with_auth;
1531 hs->statcode = statcode;
1533 hs->error = xstrdup (_("Malformed status line"));
1535 hs->error = xstrdup (_("(no description)"));
1537 hs->error = xstrdup (message);
1539 type = response_header_strdup (resp, "Content-Type");
1542 char *tmp = strchr (type, ';');
1545 while (tmp > type && ISSPACE (tmp[-1]))
1550 hs->newloc = response_header_strdup (resp, "Location");
1551 hs->remote_time = response_header_strdup (resp, "Last-Modified");
1553 char *set_cookie = response_header_strdup (resp, "Set-Cookie");
1556 /* The jar should have been created by now. */
1557 assert (wget_cookie_jar != NULL);
1558 cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port, u->path,
1563 if (response_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
1565 long first_byte_pos, last_byte_pos, entity_length;
1566 if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
1568 contrange = first_byte_pos;
1570 response_free (resp);
1572 /* 20x responses are counted among successful by default. */
1573 if (H_20X (statcode))
1576 /* Return if redirected. */
1577 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1579 /* RFC2068 says that in case of the 300 (multiple choices)
1580 response, the server can output a preferred URL through
1581 `Location' header; otherwise, the request should be treated
1582 like GET. So, if the location is set, it will be a
1583 redirection; otherwise, just proceed normally. */
1584 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1588 logprintf (LOG_VERBOSE,
1589 _("Location: %s%s\n"),
1590 hs->newloc ? hs->newloc : _("unspecified"),
1591 hs->newloc ? _(" [following]") : "");
1593 skip_short_body (sock, contlen);
1594 CLOSE_FINISH (sock);
1600 /* If content-type is not given, assume text/html. This is because
1601 of the multitude of broken CGI's that "forget" to generate the
1604 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)) ||
1605 0 == strncasecmp (type, TEXTXHTML_S, strlen (TEXTXHTML_S)))
1610 if (opt.html_extension && (*dt & TEXTHTML))
1611 /* -E / --html-extension / html_extension = on was specified, and this is a
1612 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1613 already the file's suffix, tack on ".html". */
1615 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1617 if (last_period_in_local_filename == NULL
1618 || !(0 == strcasecmp (last_period_in_local_filename, ".htm")
1619 || 0 == strcasecmp (last_period_in_local_filename, ".html")))
1621 size_t local_filename_len = strlen(*hs->local_file);
1623 *hs->local_file = xrealloc(*hs->local_file,
1624 local_filename_len + sizeof(".html"));
1625 strcpy(*hs->local_file + local_filename_len, ".html");
1627 *dt |= ADDED_HTML_EXTENSION;
1631 if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE)
1633 /* If `-c' is in use and the file has been fully downloaded (or
1634 the remote file has shrunk), Wget effectively requests bytes
1635 after the end of file and the server response with 416. */
1636 logputs (LOG_VERBOSE, _("\
1637 \n The file is already fully retrieved; nothing to do.\n\n"));
1638 /* In case the caller inspects. */
1641 /* Mark as successfully retrieved. */
1644 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1645 might be more bytes in the body. */
1646 return RETRUNNEEDED;
1648 if ((contrange != 0 && contrange != hs->restval)
1649 || (H_PARTIAL (statcode) && !contrange))
1651 /* The Range request was somehow misunderstood by the server.
1654 CLOSE_INVALIDATE (sock);
1657 hs->contlen = contlen + contrange;
1663 /* No need to print this output if the body won't be
1664 downloaded at all, or if the original server response is
1666 logputs (LOG_VERBOSE, _("Length: "));
1669 logputs (LOG_VERBOSE, legible (contlen + contrange));
1671 logprintf (LOG_VERBOSE, _(" (%s to go)"), legible (contlen));
1674 logputs (LOG_VERBOSE,
1675 opt.ignore_length ? _("ignored") : _("unspecified"));
1677 logprintf (LOG_VERBOSE, " [%s]\n", type);
1679 logputs (LOG_VERBOSE, "\n");
1683 type = NULL; /* We don't need it any more. */
1685 /* Return if we have no intention of further downloading. */
1686 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1688 /* In case the caller cares to look... */
1692 /* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the
1693 servers not to send body in response to a HEAD request. If
1694 you encounter such a server (more likely a broken CGI), use
1695 `--no-http-keep-alive'. */
1696 CLOSE_FINISH (sock);
1697 return RETRFINISHED;
1700 /* Open the local file. */
1703 mkalldirs (*hs->local_file);
1705 rotate_backups (*hs->local_file);
1706 fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1709 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1710 CLOSE_INVALIDATE (sock);
1717 /* #### This confuses the timestamping code that checks for file
1718 size. Maybe we should save some additional information? */
1719 if (opt.save_headers)
1720 fwrite (head, 1, strlen (head), fp);
1722 /* Download the request body. */
1725 flags |= rb_read_exactly;
1726 if (hs->restval > 0 && contrange == 0)
1727 /* If the server ignored our range request, instruct fd_read_body
1728 to skip the first RESTVAL bytes of body. */
1729 flags |= rb_skip_startpos;
1730 hs->len = hs->restval;
1732 hs->res = fd_read_body (sock, fp, contlen != -1 ? contlen : 0,
1733 hs->restval, &hs->rd_size, &hs->len, &hs->dltime,
1737 CLOSE_FINISH (sock);
1739 CLOSE_INVALIDATE (sock);
1742 /* Close or flush the file. We have to be careful to check for
1743 error here. Checking the result of fwrite() is not enough --
1744 errors could go unnoticed! */
1747 flush_res = fclose (fp);
1749 flush_res = fflush (fp);
1750 if (flush_res == EOF)
1755 return RETRFINISHED;
1758 /* The genuine HTTP loop! This is the part where the retrieval is
1759 retried, and retried, and retried, and... */
1761 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1762 int *dt, struct url *proxy)
1765 int use_ts, got_head = 0; /* time-stamping info */
1766 char *filename_plus_orig_suffix;
1767 char *local_filename = NULL;
1768 char *tms, *locf, *tmrate;
1770 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1771 long local_size = 0; /* the size of the local file */
1772 size_t filename_len;
1773 struct http_stat hstat; /* HTTP status */
1777 /* This used to be done in main(), but it's a better idea to do it
1778 here so that we don't go through the hoops if we're just using
1782 if (!wget_cookie_jar)
1783 wget_cookie_jar = cookie_jar_new ();
1784 if (opt.cookies_input && !cookies_loaded_p)
1786 cookie_jar_load (wget_cookie_jar, opt.cookies_input);
1787 cookies_loaded_p = 1;
1793 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1794 has_wildcards_p because it would also warn on `?', and we know that
1795 shows up in CGI paths a *lot*. */
1796 if (strchr (u->url, '*'))
1797 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1801 /* Determine the local filename. */
1802 if (local_file && *local_file)
1803 hstat.local_file = local_file;
1804 else if (local_file)
1806 *local_file = url_file_name (u);
1807 hstat.local_file = local_file;
1811 dummy = url_file_name (u);
1812 hstat.local_file = &dummy;
1815 if (!opt.output_document)
1816 locf = *hstat.local_file;
1818 locf = opt.output_document;
1820 hstat.referer = referer;
1822 filename_len = strlen (*hstat.local_file);
1823 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1825 if (opt.noclobber && file_exists_p (*hstat.local_file))
1827 /* If opt.noclobber is turned on and file already exists, do not
1828 retrieve the file */
1829 logprintf (LOG_VERBOSE, _("\
1830 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1831 /* If the file is there, we suppose it's retrieved OK. */
1834 /* #### Bogusness alert. */
1835 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1836 if (has_html_suffix_p (*hstat.local_file))
1844 if (opt.timestamping)
1846 int local_dot_orig_file_exists = 0;
1848 if (opt.backup_converted)
1849 /* If -K is specified, we'll act on the assumption that it was specified
1850 last time these files were downloaded as well, and instead of just
1851 comparing local file X against server file X, we'll compare local
1852 file X.orig (if extant, else X) against server file X. If -K
1853 _wasn't_ specified last time, or the server contains files called
1854 *.orig, -N will be back to not operating correctly with -k. */
1856 /* Would a single s[n]printf() call be faster? --dan
1858 Definitely not. sprintf() is horribly slow. It's a
1859 different question whether the difference between the two
1860 affects a program. Usually I'd say "no", but at one
1861 point I profiled Wget, and found that a measurable and
1862 non-negligible amount of time was lost calling sprintf()
1863 in url.c. Replacing sprintf with inline calls to
1864 strcpy() and long_to_string() made a difference.
1866 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1867 memcpy (filename_plus_orig_suffix + filename_len,
1868 ".orig", sizeof (".orig"));
1870 /* Try to stat() the .orig file. */
1871 if (stat (filename_plus_orig_suffix, &st) == 0)
1873 local_dot_orig_file_exists = 1;
1874 local_filename = filename_plus_orig_suffix;
1878 if (!local_dot_orig_file_exists)
1879 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1880 if (stat (*hstat.local_file, &st) == 0)
1881 local_filename = *hstat.local_file;
1883 if (local_filename != NULL)
1884 /* There was a local file, so we'll check later to see if the version
1885 the server has is the same version we already have, allowing us to
1891 /* Modification time granularity is 2 seconds for Windows, so
1892 increase local time by 1 second for later comparison. */
1895 local_size = st.st_size;
1899 /* Reset the counter. */
1905 /* Increment the pass counter. */
1907 sleep_between_retrievals (count);
1908 /* Get the current time string. */
1909 tms = time_str (NULL);
1910 /* Print fetch message, if opt.verbose. */
1913 char *hurl = url_string (u, 1);
1917 sprintf (tmp, _("(try:%2d)"), count);
1918 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1919 tms, hurl, tmp, locf);
1921 ws_changetitle (hurl);
1926 /* Default document type is empty. However, if spider mode is
1927 on or time-stamping is employed, HEAD_ONLY commands is
1928 encoded within *dt. */
1929 if (opt.spider || (use_ts && !got_head))
1934 /* Decide whether or not to restart. */
1937 hstat.restval = hstat.len; /* continue where we left off */
1938 else if (opt.always_rest
1939 && stat (locf, &st) == 0
1940 && S_ISREG (st.st_mode))
1941 hstat.restval = st.st_size;
1943 /* Decide whether to send the no-cache directive. We send it in
1945 a) we're using a proxy, and we're past our first retrieval.
1946 Some proxies are notorious for caching incomplete data, so
1947 we require a fresh get.
1948 b) caching is explicitly inhibited. */
1949 if ((proxy && count > 1) /* a */
1950 || !opt.allow_cache /* b */
1952 *dt |= SEND_NOCACHE;
1954 *dt &= ~SEND_NOCACHE;
1956 /* Try fetching the document, or at least its head. */
1957 err = gethttp (u, &hstat, dt, proxy);
1959 /* It's unfortunate that wget determines the local filename before finding
1960 out the Content-Type of the file. Barring a major restructuring of the
1961 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1962 *hstat.local_file to tack on ".html". */
1963 if (!opt.output_document)
1964 locf = *hstat.local_file;
1966 locf = opt.output_document;
1969 tms = time_str (NULL);
1970 /* Get the new location (with or without the redirection). */
1972 *newloc = xstrdup (hstat.newloc);
1975 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1976 case CONERROR: case READERR: case WRITEFAILED:
1978 /* Non-fatal errors continue executing the loop, which will
1979 bring them to "while" statement at the end, to judge
1980 whether the number of tries was exceeded. */
1981 free_hstat (&hstat);
1982 printwhat (count, opt.ntry);
1985 case HOSTERR: case CONIMPOSSIBLE: case PROXERR: case AUTHFAILED:
1986 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1987 /* Fatal errors just return from the function. */
1988 free_hstat (&hstat);
1992 case FWRITEERR: case FOPENERR:
1993 /* Another fatal error. */
1994 logputs (LOG_VERBOSE, "\n");
1995 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1996 *hstat.local_file, strerror (errno));
1997 free_hstat (&hstat);
2002 /* Another fatal error. */
2003 logputs (LOG_VERBOSE, "\n");
2004 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
2005 free_hstat (&hstat);
2010 /* Return the new location to the caller. */
2013 logprintf (LOG_NOTQUIET,
2014 _("ERROR: Redirection (%d) without location.\n"),
2016 free_hstat (&hstat);
2020 free_hstat (&hstat);
2025 /* The file was already fully retrieved. */
2026 free_hstat (&hstat);
2031 /* Deal with you later. */
2034 /* All possibilities should have been exhausted. */
2037 if (!(*dt & RETROKF))
2041 /* #### Ugly ugly ugly! */
2042 char *hurl = url_string (u, 1);
2043 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
2046 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
2047 tms, hstat.statcode, hstat.error);
2048 logputs (LOG_VERBOSE, "\n");
2049 free_hstat (&hstat);
2054 /* Did we get the time-stamp? */
2057 if (opt.timestamping && !hstat.remote_time)
2059 logputs (LOG_NOTQUIET, _("\
2060 Last-modified header missing -- time-stamps turned off.\n"));
2062 else if (hstat.remote_time)
2064 /* Convert the date-string into struct tm. */
2065 tmr = http_atotm (hstat.remote_time);
2066 if (tmr == (time_t) (-1))
2067 logputs (LOG_VERBOSE, _("\
2068 Last-modified header invalid -- time-stamp ignored.\n"));
2072 /* The time-stamping section. */
2077 use_ts = 0; /* no more time-stamping */
2078 count = 0; /* the retrieve count for HEAD is
2080 if (hstat.remote_time && tmr != (time_t) (-1))
2082 /* Now time-stamping can be used validly. Time-stamping
2083 means that if the sizes of the local and remote file
2084 match, and local file is newer than the remote file,
2085 it will not be retrieved. Otherwise, the normal
2086 download procedure is resumed. */
2088 (hstat.contlen == -1 || local_size == hstat.contlen))
2090 logprintf (LOG_VERBOSE, _("\
2091 Server file no newer than local file `%s' -- not retrieving.\n\n"),
2093 free_hstat (&hstat);
2097 else if (tml >= tmr)
2098 logprintf (LOG_VERBOSE, _("\
2099 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
2101 logputs (LOG_VERBOSE,
2102 _("Remote file is newer, retrieving.\n"));
2104 free_hstat (&hstat);
2107 if ((tmr != (time_t) (-1))
2109 && ((hstat.len == hstat.contlen) ||
2110 ((hstat.res == 0) &&
2111 ((hstat.contlen == -1) ||
2112 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
2114 /* #### This code repeats in http.c and ftp.c. Move it to a
2116 const char *fl = NULL;
2117 if (opt.output_document)
2119 if (output_stream_regular)
2120 fl = opt.output_document;
2123 fl = *hstat.local_file;
2127 /* End of time-stamping section. */
2131 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
2136 tmrate = retr_rate (hstat.rd_size, hstat.dltime, 0);
2138 if (hstat.len == hstat.contlen)
2142 logprintf (LOG_VERBOSE,
2143 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
2144 tms, tmrate, locf, hstat.len, hstat.contlen);
2145 logprintf (LOG_NONVERBOSE,
2146 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
2147 tms, u->url, hstat.len, hstat.contlen, locf, count);
2150 total_downloaded_bytes += hstat.len;
2152 /* Remember that we downloaded the file for later ".orig" code. */
2153 if (*dt & ADDED_HTML_EXTENSION)
2154 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2156 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2158 free_hstat (&hstat);
2162 else if (hstat.res == 0) /* No read error */
2164 if (hstat.contlen == -1) /* We don't know how much we were supposed
2165 to get, so assume we succeeded. */
2169 logprintf (LOG_VERBOSE,
2170 _("%s (%s) - `%s' saved [%ld]\n\n"),
2171 tms, tmrate, locf, hstat.len);
2172 logprintf (LOG_NONVERBOSE,
2173 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
2174 tms, u->url, hstat.len, locf, count);
2177 total_downloaded_bytes += hstat.len;
2179 /* Remember that we downloaded the file for later ".orig" code. */
2180 if (*dt & ADDED_HTML_EXTENSION)
2181 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2183 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2185 free_hstat (&hstat);
2189 else if (hstat.len < hstat.contlen) /* meaning we lost the
2190 connection too soon */
2192 logprintf (LOG_VERBOSE,
2193 _("%s (%s) - Connection closed at byte %ld. "),
2194 tms, tmrate, hstat.len);
2195 printwhat (count, opt.ntry);
2196 free_hstat (&hstat);
2199 else if (!opt.kill_longer) /* meaning we got more than expected */
2201 logprintf (LOG_VERBOSE,
2202 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
2203 tms, tmrate, locf, hstat.len, hstat.contlen);
2204 logprintf (LOG_NONVERBOSE,
2205 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
2206 tms, u->url, hstat.len, hstat.contlen, locf, count);
2208 total_downloaded_bytes += hstat.len;
2210 /* Remember that we downloaded the file for later ".orig" code. */
2211 if (*dt & ADDED_HTML_EXTENSION)
2212 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2214 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2216 free_hstat (&hstat);
2220 else /* the same, but not accepted */
2222 logprintf (LOG_VERBOSE,
2223 _("%s (%s) - Connection closed at byte %ld/%ld. "),
2224 tms, tmrate, hstat.len, hstat.contlen);
2225 printwhat (count, opt.ntry);
2226 free_hstat (&hstat);
2230 else /* now hstat.res can only be -1 */
2232 if (hstat.contlen == -1)
2234 logprintf (LOG_VERBOSE,
2235 _("%s (%s) - Read error at byte %ld (%s)."),
2236 tms, tmrate, hstat.len, strerror (errno));
2237 printwhat (count, opt.ntry);
2238 free_hstat (&hstat);
2241 else /* hstat.res == -1 and contlen is given */
2243 logprintf (LOG_VERBOSE,
2244 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2245 tms, tmrate, hstat.len, hstat.contlen,
2247 printwhat (count, opt.ntry);
2248 free_hstat (&hstat);
2255 while (!opt.ntry || (count < opt.ntry));
2259 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2260 than local timezone.
2262 mktime is similar but assumes struct tm, also known as the
2263 "broken-down" form of time, is in local time zone. mktime_from_utc
2264 uses mktime to make the conversion understanding that an offset
2265 will be introduced by the local time assumption.
2267 mktime_from_utc then measures the introduced offset by applying
2268 gmtime to the initial result and applying mktime to the resulting
2269 "broken-down" form. The difference between the two mktime results
2270 is the measured offset which is then subtracted from the initial
2271 mktime result to yield a calendar time which is the value returned.
2273 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2274 consistent offset (the non DST offset) since tm and tm+o might be
2275 on opposite sides of a DST change.
2277 Some implementations of mktime return -1 for the nonexistent
2278 localtime hour at the beginning of DST. In this event, use
2279 mktime(tm - 1hr) + 3600.
2283 gmtime(t+o) --> tm+o
2284 mktime(tm+o) --> t+2o
2285 t+o - (t+2o - t+o) = t
2287 Note that glibc contains a function of the same purpose named
2288 `timegm' (reverse of gmtime). But obviously, it is not universally
2289 available, and unfortunately it is not straightforwardly
2290 extractable for use here. Perhaps configure should detect timegm
2291 and use it where available.
2293 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2294 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2295 Further improved by Roger with assistance from Edward J. Sabol
2296 based on input by Jamie Zawinski. */
2299 mktime_from_utc (struct tm *t)
2310 return -1; /* can't deal with output from strptime */
2321 return -1; /* can't deal with output from gmtime */
2324 return (tl - (tb - tl));
2327 /* Check whether the result of strptime() indicates success.
2328 strptime() returns the pointer to how far it got to in the string.
2329 The processing has been successful if the string is at `GMT' or
2330 `+X', or at the end of the string.
2332 In extended regexp parlance, the function returns 1 if P matches
2333 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2334 can return) is considered a failure and 0 is returned. */
2336 check_end (const char *p)
2340 while (ISSPACE (*p))
2343 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2344 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2350 /* Convert the textual specification of time in TIME_STRING to the
2351 number of seconds since the Epoch.
2353 TIME_STRING can be in any of the three formats RFC2068 allows the
2354 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2355 Timezones are ignored, and should be GMT.
2357 Return the computed time_t representation, or -1 if the conversion
2360 This function uses strptime with various string formats for parsing
2361 TIME_STRING. This results in a parser that is not as lenient in
2362 interpreting TIME_STRING as I would like it to be. Being based on
2363 strptime, it always allows shortened months, one-digit days, etc.,
2364 but due to the multitude of formats in which time can be
2365 represented, an ideal HTTP time parser would be even more
2366 forgiving. It should completely ignore things like week days and
2367 concentrate only on the various forms of representing years,
2368 months, days, hours, minutes, and seconds. For example, it would
2369 be nice if it accepted ISO 8601 out of the box.
2371 I've investigated free and PD code for this purpose, but none was
2372 usable. getdate was big and unwieldy, and had potential copyright
2373 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2374 distributed with phttpd, is excellent, but we cannot use it because
2375 it is not assigned to the FSF. So I stuck it with strptime. */
2378 http_atotm (const char *time_string)
2380 /* NOTE: Solaris strptime man page claims that %n and %t match white
2381 space, but that's not universally available. Instead, we simply
2382 use ` ' to mean "skip all WS", which works under all strptime
2383 implementations I've tested. */
2385 static const char *time_formats[] = {
2386 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2387 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2388 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2389 (google.com uses this for their cookies.) */
2390 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2396 /* According to Roger Beeman, we need to initialize tm_isdst, since
2397 strptime won't do it. */
2400 /* Note that under foreign locales Solaris strptime() fails to
2401 recognize English dates, which renders this function useless. We
2402 solve this by being careful not to affect LC_TIME when
2403 initializing locale.
2405 Another solution would be to temporarily set locale to C, invoke
2406 strptime(), and restore it back. This is slow and dirty,
2407 however, and locale support other than LC_MESSAGES can mess other
2408 things, so I rather chose to stick with just setting LC_MESSAGES.
2410 GNU strptime does not have this problem because it recognizes
2411 both international and local dates. */
2413 for (i = 0; i < countof (time_formats); i++)
2414 if (check_end (strptime (time_string, time_formats[i], &t)))
2415 return mktime_from_utc (&t);
2417 /* All formats have failed. */
2421 /* Authorization support: We support two authorization schemes:
2423 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2425 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2426 consisting of answering to the server's challenge with the proper
2429 /* How many bytes it will take to store LEN bytes in base64. */
2430 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2432 /* Encode the string S of length LENGTH to base64 format and place it
2433 to STORE. STORE will be 0-terminated, and must point to a writable
2434 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2436 base64_encode (const char *s, char *store, int length)
2438 /* Conversion table. */
2439 static char tbl[64] = {
2440 'A','B','C','D','E','F','G','H',
2441 'I','J','K','L','M','N','O','P',
2442 'Q','R','S','T','U','V','W','X',
2443 'Y','Z','a','b','c','d','e','f',
2444 'g','h','i','j','k','l','m','n',
2445 'o','p','q','r','s','t','u','v',
2446 'w','x','y','z','0','1','2','3',
2447 '4','5','6','7','8','9','+','/'
2450 unsigned char *p = (unsigned char *)store;
2452 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2453 for (i = 0; i < length; i += 3)
2455 *p++ = tbl[s[0] >> 2];
2456 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2457 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2458 *p++ = tbl[s[2] & 0x3f];
2461 /* Pad the result if necessary... */
2462 if (i == length + 1)
2464 else if (i == length + 2)
2465 *(p - 1) = *(p - 2) = '=';
2466 /* ...and zero-terminate it. */
2470 /* Create the authentication header contents for the `Basic' scheme.
2471 This is done by encoding the string `USER:PASS' in base64 and
2472 prepending `HEADER: Basic ' to it. */
2474 basic_authentication_encode (const char *user, const char *passwd)
2476 char *t1, *t2, *res;
2477 int len1 = strlen (user) + 1 + strlen (passwd);
2478 int len2 = BASE64_LENGTH (len1);
2480 t1 = (char *)alloca (len1 + 1);
2481 sprintf (t1, "%s:%s", user, passwd);
2483 t2 = (char *)alloca (len2 + 1);
2484 base64_encode (t1, t2, len1);
2486 res = (char *)xmalloc (6 + len2 + 1);
2487 sprintf (res, "Basic %s", t2);
2492 #define SKIP_WS(x) do { \
2493 while (ISSPACE (*(x))) \
2498 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2499 of a field in such a header. If the field is the one specified by
2500 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2501 digest authorization code), extract its value in the (char*)
2502 variable pointed by RET. Returns negative on a malformed header,
2503 or number of bytes that have been parsed by this call. */
2505 extract_header_attr (const char *au, const char *attr_name, char **ret)
2507 const char *cp, *ep;
2511 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2513 cp += strlen (attr_name);
2526 for (ep = cp; *ep && *ep != '\"'; ep++)
2531 *ret = strdupdelim (cp, ep);
2538 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2539 an array of 16 bytes containing the hash keys, and BUF should be a
2540 buffer of 33 writable characters (32 for hex digits plus one for
2541 zero termination). */
2543 dump_hash (unsigned char *buf, const unsigned char *hash)
2547 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2549 *buf++ = XNUM_TO_digit (*hash >> 4);
2550 *buf++ = XNUM_TO_digit (*hash & 0xf);
2555 /* Take the line apart to find the challenge, and compose a digest
2556 authorization header. See RFC2069 section 2.1.2. */
2558 digest_authentication_encode (const char *au, const char *user,
2559 const char *passwd, const char *method,
2562 static char *realm, *opaque, *nonce;
2567 { "realm", &realm },
2568 { "opaque", &opaque },
2573 realm = opaque = nonce = NULL;
2575 au += 6; /* skip over `Digest' */
2581 for (i = 0; i < countof (options); i++)
2583 int skip = extract_header_attr (au, options[i].name,
2584 options[i].variable);
2588 xfree_null (opaque);
2598 if (i == countof (options))
2600 while (*au && *au != '=')
2608 while (*au && *au != '\"')
2615 while (*au && *au != ',')
2620 if (!realm || !nonce || !user || !passwd || !path || !method)
2623 xfree_null (opaque);
2628 /* Calculate the digest value. */
2630 ALLOCA_MD5_CONTEXT (ctx);
2631 unsigned char hash[MD5_HASHLEN];
2632 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2633 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2635 /* A1BUF = H(user ":" realm ":" password) */
2637 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2638 gen_md5_update ((unsigned char *)":", 1, ctx);
2639 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2640 gen_md5_update ((unsigned char *)":", 1, ctx);
2641 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2642 gen_md5_finish (ctx, hash);
2643 dump_hash (a1buf, hash);
2645 /* A2BUF = H(method ":" path) */
2647 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2648 gen_md5_update ((unsigned char *)":", 1, ctx);
2649 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2650 gen_md5_finish (ctx, hash);
2651 dump_hash (a2buf, hash);
2653 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2655 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2656 gen_md5_update ((unsigned char *)":", 1, ctx);
2657 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2658 gen_md5_update ((unsigned char *)":", 1, ctx);
2659 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2660 gen_md5_finish (ctx, hash);
2661 dump_hash (response_digest, hash);
2663 res = (char*) xmalloc (strlen (user)
2668 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2669 + (opaque ? strlen (opaque) : 0)
2671 sprintf (res, "Digest \
2672 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2673 user, realm, nonce, path, response_digest);
2676 char *p = res + strlen (res);
2677 strcat (p, ", opaque=\"");
2684 #endif /* USE_DIGEST */
2687 #define BEGINS_WITH(line, string_constant) \
2688 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2689 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2690 || !line[sizeof (string_constant) - 1]))
2693 known_authentication_scheme_p (const char *au)
2695 return BEGINS_WITH (au, "Basic")
2696 || BEGINS_WITH (au, "Digest")
2697 || BEGINS_WITH (au, "NTLM");
2702 /* Create the HTTP authorization request header. When the
2703 `WWW-Authenticate' response header is seen, according to the
2704 authorization scheme specified in that header (`Basic' and `Digest'
2705 are supported by the current implementation), produce an
2706 appropriate HTTP authorization request header. */
2708 create_authorization_line (const char *au, const char *user,
2709 const char *passwd, const char *method,
2712 if (0 == strncasecmp (au, "Basic", 5))
2713 return basic_authentication_encode (user, passwd);
2715 if (0 == strncasecmp (au, "Digest", 6))
2716 return digest_authentication_encode (au, user, passwd, method, path);
2717 #endif /* USE_DIGEST */