2 Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
25 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
58 # include "gen_sslfunc.h"
65 extern char *version_string;
71 static int cookies_loaded_p;
73 #define TEXTHTML_S "text/html"
74 #define HTTP_ACCEPT "*/*"
76 /* Some status code validation macros: */
77 #define H_20X(x) (((x) >= 200) && ((x) < 300))
78 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
79 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
80 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
82 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
84 #define HTTP_STATUS_OK 200
85 #define HTTP_STATUS_CREATED 201
86 #define HTTP_STATUS_ACCEPTED 202
87 #define HTTP_STATUS_NO_CONTENT 204
88 #define HTTP_STATUS_PARTIAL_CONTENTS 206
90 /* Redirection 3xx. */
91 #define HTTP_STATUS_MULTIPLE_CHOICES 300
92 #define HTTP_STATUS_MOVED_PERMANENTLY 301
93 #define HTTP_STATUS_MOVED_TEMPORARILY 302
94 #define HTTP_STATUS_NOT_MODIFIED 304
96 /* Client error 4xx. */
97 #define HTTP_STATUS_BAD_REQUEST 400
98 #define HTTP_STATUS_UNAUTHORIZED 401
99 #define HTTP_STATUS_FORBIDDEN 403
100 #define HTTP_STATUS_NOT_FOUND 404
102 /* Server errors 5xx. */
103 #define HTTP_STATUS_INTERNAL 500
104 #define HTTP_STATUS_NOT_IMPLEMENTED 501
105 #define HTTP_STATUS_BAD_GATEWAY 502
106 #define HTTP_STATUS_UNAVAILABLE 503
109 /* Parse the HTTP status line, which is of format:
111 HTTP-Version SP Status-Code SP Reason-Phrase
113 The function returns the status-code, or -1 if the status line is
114 malformed. The pointer to reason-phrase is returned in RP. */
116 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
118 /* (the variables must not be named `major' and `minor', because
119 that breaks compilation with SunOS4 cc.) */
120 int mjr, mnr, statcode;
123 *reason_phrase_ptr = NULL;
125 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
126 major version, and Y is minor version. */
127 if (strncmp (line, "HTTP/", 5) != 0)
131 /* Calculate major HTTP version. */
133 for (mjr = 0; ISDIGIT (*line); line++)
134 mjr = 10 * mjr + (*line - '0');
135 if (*line != '.' || p == line)
139 /* Calculate minor HTTP version. */
141 for (mnr = 0; ISDIGIT (*line); line++)
142 mnr = 10 * mnr + (*line - '0');
143 if (*line != ' ' || p == line)
145 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
146 minor version can be safely ignored. */
151 /* Calculate status code. */
152 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
154 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
156 /* Set up the reason phrase pointer. */
158 /* RFC2068 requires SPC here, but we allow the string to finish
159 here, in case no reason-phrase is present. */
163 *reason_phrase_ptr = line;
168 *reason_phrase_ptr = line + 1;
173 #define WMIN(x, y) ((x) > (y) ? (y) : (x))
175 /* Send the contents of FILE_NAME to SOCK/SSL. Make sure that exactly
176 PROMISED_SIZE bytes are sent over the wire -- if the file is
177 longer, read only that much; if the file is shorter, pad it with
181 post_file (int sock, void *ssl, const char *file_name, long promised_size)
183 static char chunk[8192];
188 /* Only one of SOCK and SSL may be active at the same time. */
189 assert (sock > -1 || ssl != NULL);
190 assert (sock == -1 || ssl == NULL);
192 DEBUGP (("[writing POST file %s ... ", file_name));
194 fp = fopen (file_name, "rb");
197 while (written < promised_size)
200 int length = fread (chunk, 1, sizeof (chunk), fp);
203 towrite = WMIN (promised_size - written, length);
206 write_error = ssl_iwrite (ssl, chunk, towrite);
209 write_error = iwrite (sock, chunk, towrite);
220 if (written < promised_size)
222 /* This highly unlikely case can happen only if the file has
223 shrunk under us. To uphold the promise that exactly
224 promised_size bytes would be delivered, pad the remaining
225 data with zeros. #### Should we abort instead? */
226 DEBUGP (("padding %ld bytes ... ", promised_size - written));
227 memset (chunk, '\0', sizeof (chunk));
228 while (written < promised_size)
230 int towrite = WMIN (promised_size - written, sizeof (chunk));
233 write_error = ssl_iwrite (ssl, chunk, towrite);
236 write_error = iwrite (sock, chunk, towrite);
242 assert (written == promised_size);
243 DEBUGP (("done]\n"));
247 /* Functions to be used as arguments to header_process(): */
249 struct http_process_range_closure {
255 /* Parse the `Content-Range' header and extract the information it
256 contains. Returns 1 if successful, -1 otherwise. */
258 http_process_range (const char *hdr, void *arg)
260 struct http_process_range_closure *closure
261 = (struct http_process_range_closure *)arg;
264 /* Certain versions of Nutscape proxy server send out
265 `Content-Length' without "bytes" specifier, which is a breach of
266 RFC2068 (as well as the HTTP/1.1 draft which was current at the
267 time). But hell, I must support it... */
268 if (!strncasecmp (hdr, "bytes", 5))
271 /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
275 hdr += skip_lws (hdr);
281 for (num = 0; ISDIGIT (*hdr); hdr++)
282 num = 10 * num + (*hdr - '0');
283 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
285 closure->first_byte_pos = num;
287 for (num = 0; ISDIGIT (*hdr); hdr++)
288 num = 10 * num + (*hdr - '0');
289 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
291 closure->last_byte_pos = num;
293 for (num = 0; ISDIGIT (*hdr); hdr++)
294 num = 10 * num + (*hdr - '0');
295 closure->entity_length = num;
299 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
300 Used for `Accept-Ranges'. */
302 http_process_none (const char *hdr, void *arg)
304 int *where = (int *)arg;
306 if (strstr (hdr, "none"))
313 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
315 http_process_type (const char *hdr, void *arg)
317 char **result = (char **)arg;
318 /* Locate P on `;' or the terminating zero, whichever comes first. */
319 const char *p = strchr (hdr, ';');
321 p = hdr + strlen (hdr);
322 while (p > hdr && ISSPACE (*(p - 1)))
324 *result = strdupdelim (hdr, p);
328 /* Check whether the `Connection' header is set to "keep-alive". */
330 http_process_connection (const char *hdr, void *arg)
332 int *flag = (int *)arg;
333 if (!strcasecmp (hdr, "Keep-Alive"))
338 /* Persistent connections. Currently, we cache the most recently used
339 connection as persistent, provided that the HTTP server agrees to
340 make it such. The persistence data is stored in the variables
341 below. Ideally, it would be in a structure, and it should be
342 possible to cache an arbitrary fixed number of these connections.
344 I think the code is quite easy to extend in that direction. */
346 /* Whether a persistent connection is active. */
347 static int pc_active_p;
348 /* Host and port of currently active persistent connection. */
349 static struct address_list *pc_last_host_ip;
350 static unsigned short pc_last_port;
352 /* File descriptor of the currently active persistent connection. */
353 static int pc_last_fd;
356 /* Whether a ssl handshake has occoured on this connection */
357 static int pc_active_ssl;
358 /* SSL connection of the currently active persistent connection. */
359 static SSL *pc_last_ssl;
360 #endif /* HAVE_SSL */
362 /* Mark the persistent connection as invalid. This is used by the
363 CLOSE_* macros after they forcefully close a registered persistent
364 connection. This does not close the file descriptor -- it is left
365 to the caller to do that. (Maybe it should, though.) */
368 invalidate_persistent (void)
373 #endif /* HAVE_SSL */
374 if (pc_last_host_ip != NULL)
376 address_list_release (pc_last_host_ip);
377 pc_last_host_ip = NULL;
379 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
382 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
383 persistent. This will enable someone to use the same connection
384 later. In the context of HTTP, this must be called only AFTER the
385 response has been received and the server has promised that the
386 connection will remain alive.
388 If a previous connection was persistent, it is closed. */
392 register_persistent (const char *host, unsigned short port, int fd, SSL *ssl)
396 register_persistent (const char *host, unsigned short port, int fd)
401 if (pc_last_fd == fd)
403 /* The connection FD is already registered. Nothing to
409 /* The old persistent connection is still active; let's
410 close it first. This situation arises whenever a
411 persistent connection exists, but we then connect to a
412 different host, and try to register a persistent
413 connection to that one. */
415 /* The ssl disconnect has to take place before the closing
418 shutdown_ssl(pc_last_ssl);
421 invalidate_persistent ();
425 assert (pc_last_host_ip == NULL);
427 /* This lookup_host cannot fail, because it has the results in the
429 pc_last_host_ip = lookup_host (host, 1);
430 assert (pc_last_host_ip != NULL);
437 pc_active_ssl = ssl ? 1 : 0;
439 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
443 # define SHUTDOWN_SSL(ssl) do { \
445 shutdown_ssl (ssl); \
448 # define SHUTDOWN_SSL(ssl)
451 /* Return non-zero if a persistent connection is available for
452 connecting to HOST:PORT. */
456 persistent_available_p (const char *host, unsigned short port, int ssl)
460 persistent_available_p (const char *host, unsigned short port)
464 struct address_list *this_host_ip;
466 /* First, check whether a persistent connection is active at all. */
469 /* Second, check if the active connection pertains to the correct
470 (HOST, PORT) ordered pair. */
471 if (port != pc_last_port)
475 /* Second, a): check if current connection is (not) ssl, too. This
476 test is unlikely to fail because HTTP and HTTPS typicaly use
477 different ports. Yet it is possible, or so I [Christian
478 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
480 if (ssl != pc_active_ssl)
482 #endif /* HAVE_SSL */
484 this_host_ip = lookup_host (host, 1);
488 /* To equate the two host names for the purposes of persistent
489 connections, they need to share all the IP addresses in the
491 success = address_list_match_all (pc_last_host_ip, this_host_ip);
492 address_list_release (this_host_ip);
496 /* Third: check whether the connection is still open. This is
497 important because most server implement a liberal (short) timeout
498 on persistent connections. Wget can of course always reconnect
499 if the connection doesn't work out, but it's nicer to know in
500 advance. This test is a logical followup of the first test, but
501 is "expensive" and therefore placed at the end of the list. */
502 if (!test_socket_open (pc_last_fd))
504 /* Oops, the socket is no longer open. Now that we know that,
505 let's invalidate the persistent connection before returning
509 SHUTDOWN_SSL (pc_last_ssl);
512 invalidate_persistent ();
518 /* The idea behind these two CLOSE macros is to distinguish between
519 two cases: one when the job we've been doing is finished, and we
520 want to close the connection and leave, and two when something is
521 seriously wrong and we're closing the connection as part of
524 In case of keep_alive, CLOSE_FINISH should leave the connection
525 open, while CLOSE_INVALIDATE should still close it.
527 Note that the semantics of the flag `keep_alive' is "this
528 connection *will* be reused (the server has promised not to close
529 the connection once we're done)", while the semantics of
530 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
531 active, registered connection". */
533 #define CLOSE_FINISH(fd) do { \
536 SHUTDOWN_SSL (ssl); \
538 if (pc_active_p && (fd) == pc_last_fd) \
539 invalidate_persistent (); \
543 #define CLOSE_INVALIDATE(fd) do { \
544 SHUTDOWN_SSL (ssl); \
546 if (pc_active_p && (fd) == pc_last_fd) \
547 invalidate_persistent (); \
552 long len; /* received length */
553 long contlen; /* expected length */
554 long restval; /* the restart value */
555 int res; /* the result of last read */
556 char *newloc; /* new location (redirection) */
557 char *remote_time; /* remote time-stamp string */
558 char *error; /* textual HTTP error */
559 int statcode; /* status code */
560 long dltime; /* time of the download */
561 int no_truncate; /* whether truncating the file is
563 const char *referer; /* value of the referer header. */
564 char **local_file; /* local file. */
568 free_hstat (struct http_stat *hs)
570 FREE_MAYBE (hs->newloc);
571 FREE_MAYBE (hs->remote_time);
572 FREE_MAYBE (hs->error);
574 /* Guard against being called twice. */
576 hs->remote_time = NULL;
580 static char *create_authorization_line PARAMS ((const char *, const char *,
581 const char *, const char *,
583 static char *basic_authentication_encode PARAMS ((const char *, const char *,
585 static int known_authentication_scheme_p PARAMS ((const char *));
587 time_t http_atotm PARAMS ((char *));
589 #define BEGINS_WITH(line, string_constant) \
590 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
591 && (ISSPACE (line[sizeof (string_constant) - 1]) \
592 || !line[sizeof (string_constant) - 1]))
594 /* Retrieve a document through HTTP protocol. It recognizes status
595 code, and correctly handles redirections. It closes the network
596 socket. If it receives an error from the functions below it, it
597 will print it if there is enough information to do so (almost
598 always), returning the error to the caller (i.e. http_loop).
600 Various HTTP parameters are stored to hs. Although it parses the
601 response code correctly, it is not used in a sane way. The caller
604 If PROXY is non-NULL, the connection will be made to the proxy
605 server, and u->url will be requested. */
607 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
609 char *request, *type, *command, *full_path;
611 char *pragma_h, *referer, *useragent, *range, *wwwauth;
612 char *authenticate_h;
616 char *request_keep_alive;
617 int sock, hcount, all_length, statcode;
619 long contlen, contrange;
622 int auth_tried_already;
625 static SSL_CTX *ssl_ctx = NULL;
628 char *cookies = NULL;
630 /* Whether this connection will be kept alive after the HTTP request
634 /* Flags that detect the two ways of specifying HTTP keep-alive
636 int http_keep_alive_1, http_keep_alive_2;
638 /* Whether keep-alive should be inhibited. */
639 int inhibit_keep_alive;
641 /* Whether we need to print the host header with braces around host,
642 e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the usual
643 "Host: symbolic-name:1234". */
644 int squares_around_host = 0;
646 /* Headers sent when using POST. */
647 char *post_content_type, *post_content_length;
648 long post_data_size = 0;
651 /* initialize ssl_ctx on first run */
654 uerr_t err = init_ssl (&ssl_ctx);
659 case SSLERRCTXCREATE:
661 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
665 /* try without certfile */
666 logprintf (LOG_NOTQUIET,
667 _("Failed to load certificates from %s\n"),
670 logprintf (LOG_NOTQUIET,
671 _("Trying without the specified certificate\n"));
674 logprintf (LOG_NOTQUIET,
675 _("Failed to get certificate key from %s\n"),
678 logprintf (LOG_NOTQUIET,
679 _("Trying without the specified certificate\n"));
686 #endif /* HAVE_SSL */
688 if (!(*dt & HEAD_ONLY))
689 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
690 know the local filename so we can save to it. */
691 assert (*hs->local_file != NULL);
694 auth_tried_already = 0;
696 inhibit_keep_alive = !opt.http_keep_alive || proxy != NULL;
699 /* We need to come back here when the initial attempt to retrieve
700 without authorization header fails. (Expected to happen at least
701 for the Digest authorization scheme.) */
704 http_keep_alive_1 = http_keep_alive_2 = 0;
706 post_content_type = NULL;
707 post_content_length = NULL;
709 /* Initialize certain elements of struct http_stat. */
714 hs->remote_time = NULL;
717 /* If we're using a proxy, we will be connecting to the proxy
719 conn = proxy ? proxy : u;
721 /* First: establish the connection. */
722 if (inhibit_keep_alive
725 !persistent_available_p (conn->host, conn->port)
727 !persistent_available_p (conn->host, conn->port,
728 u->scheme == SCHEME_HTTPS)
729 #endif /* HAVE_SSL */
732 struct address_list *al = lookup_host (conn->host, 0);
735 set_connection_host_name (conn->host);
736 sock = connect_to_many (al, conn->port, 0);
737 set_connection_host_name (NULL);
738 address_list_release (al);
741 return errno == ECONNREFUSED ? CONREFUSED : CONERROR;
744 if (conn->scheme == SCHEME_HTTPS)
745 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
747 logputs (LOG_VERBOSE, "\n");
748 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
753 #endif /* HAVE_SSL */
757 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"),
758 conn->host, conn->port);
759 /* #### pc_last_fd should be accessed through an accessor
764 #endif /* HAVE_SSL */
765 DEBUGP (("Reusing fd %d.\n", sock));
770 else if (opt.post_file_name || opt.post_data)
778 referer = (char *)alloca (9 + strlen (hs->referer) + 3);
779 sprintf (referer, "Referer: %s\r\n", hs->referer);
782 if (*dt & SEND_NOCACHE)
783 pragma_h = "Pragma: no-cache\r\n";
789 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
790 /* Gag me! Some servers (e.g. WebSitePro) have been known to
791 respond to the following `Range' format by generating a
792 multipart/x-byte-ranges MIME document! This MIME type was
793 present in an old draft of the byteranges specification.
794 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
795 only if multiple non-overlapping ranges are requested --
796 which Wget never does. */
797 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
802 STRDUP_ALLOCA (useragent, opt.useragent);
805 useragent = (char *)alloca (10 + strlen (version_string));
806 sprintf (useragent, "Wget/%s", version_string);
808 /* Construct the authentication, if userid is present. */
811 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
812 user = user ? user : opt.http_user;
813 passwd = passwd ? passwd : opt.http_passwd;
820 /* We have the username and the password, but haven't tried
821 any authorization yet. Let's see if the "Basic" method
822 works. If not, we'll come back here and construct a
823 proper authorization method with the right challenges.
825 If we didn't employ this kind of logic, every URL that
826 requires authorization would have to be processed twice,
827 which is very suboptimal and generates a bunch of false
828 "unauthorized" errors in the server log.
830 #### But this logic also has a serious problem when used
831 with stronger authentications: we *first* transmit the
832 username and the password in clear text, and *then*
833 attempt a stronger authentication scheme. That cannot be
834 right! We are only fortunate that almost everyone still
835 uses the `Basic' scheme anyway.
837 There should be an option to prevent this from happening,
838 for those who use strong authentication schemes and value
840 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
844 /* Use the full path, i.e. one that includes the leading
845 slash and the query string, but is independent of proxy
847 char *pth = url_full_path (u);
848 wwwauth = create_authorization_line (authenticate_h, user, passwd,
857 char *proxy_user, *proxy_passwd;
858 /* For normal username and password, URL components override
859 command-line/wgetrc parameters. With proxy authentication,
860 it's the reverse, because proxy URLs are normally the
861 "permanent" ones, so command-line args should take
863 if (opt.proxy_user && opt.proxy_passwd)
865 proxy_user = opt.proxy_user;
866 proxy_passwd = opt.proxy_passwd;
870 proxy_user = proxy->user;
871 proxy_passwd = proxy->passwd;
873 /* #### This does not appear right. Can't the proxy request,
874 say, `Digest' authentication? */
875 if (proxy_user && proxy_passwd)
876 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
877 "Proxy-Authorization");
880 /* String of the form :PORT. Used only for non-standard ports. */
882 if (u->port != scheme_default_port (u->scheme))
884 port_maybe = (char *)alloca (numdigit (u->port) + 2);
885 sprintf (port_maybe, ":%d", u->port);
888 if (!inhibit_keep_alive)
889 request_keep_alive = "Connection: Keep-Alive\r\n";
891 request_keep_alive = NULL;
894 cookies = build_cookies_request (u->host, u->port, u->path,
896 u->scheme == SCHEME_HTTPS
902 if (opt.post_data || opt.post_file_name)
904 post_content_type = "Content-Type: application/x-www-form-urlencoded\r\n";
906 post_data_size = strlen (opt.post_data);
909 post_data_size = file_size (opt.post_file_name);
910 if (post_data_size == -1)
912 logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
917 post_content_length = xmalloc (16 + numdigit (post_data_size) + 2 + 1);
918 sprintf (post_content_length,
919 "Content-Length: %ld\r\n", post_data_size);
923 full_path = xstrdup (u->url);
925 /* Use the full path, i.e. one that includes the leading slash and
926 the query string. E.g. if u->path is "foo/bar" and u->query is
927 "param=value", full_path will be "/foo/bar?param=value". */
928 full_path = url_full_path (u);
930 if (strchr (u->host, ':'))
931 squares_around_host = 1;
933 /* Allocate the memory for the request. */
934 request = (char *)alloca (strlen (command)
938 + (port_maybe ? strlen (port_maybe) : 0)
939 + strlen (HTTP_ACCEPT)
940 + (request_keep_alive
941 ? strlen (request_keep_alive) : 0)
942 + (referer ? strlen (referer) : 0)
943 + (cookies ? strlen (cookies) : 0)
944 + (wwwauth ? strlen (wwwauth) : 0)
945 + (proxyauth ? strlen (proxyauth) : 0)
946 + (range ? strlen (range) : 0)
949 ? strlen (post_content_type) : 0)
950 + (post_content_length
951 ? strlen (post_content_length) : 0)
952 + (opt.user_header ? strlen (opt.user_header) : 0)
954 /* Construct the request. */
960 %s%s%s%s%s%s%s%s%s%s\r\n",
963 squares_around_host ? "[" : "", u->host, squares_around_host ? "]" : "",
964 port_maybe ? port_maybe : "",
966 request_keep_alive ? request_keep_alive : "",
967 referer ? referer : "",
968 cookies ? cookies : "",
969 wwwauth ? wwwauth : "",
970 proxyauth ? proxyauth : "",
973 post_content_type ? post_content_type : "",
974 post_content_length ? post_content_length : "",
975 opt.user_header ? opt.user_header : "");
976 DEBUGP (("---request begin---\n%s", request));
978 /* Free the temporary memory. */
979 FREE_MAYBE (wwwauth);
980 FREE_MAYBE (proxyauth);
981 FREE_MAYBE (cookies);
984 /* Send the request to server. */
986 if (conn->scheme == SCHEME_HTTPS)
987 write_error = ssl_iwrite (ssl, request, strlen (request));
990 write_error = iwrite (sock, request, strlen (request));
992 if (write_error >= 0)
996 DEBUGP (("[POST data: %s]\n", opt.post_data));
998 if (conn->scheme == SCHEME_HTTPS)
999 write_error = ssl_iwrite (ssl, opt.post_data, post_data_size);
1002 write_error = iwrite (sock, opt.post_data, post_data_size);
1004 else if (opt.post_file_name)
1007 if (conn->scheme == SCHEME_HTTPS)
1008 write_error = post_file (-1, ssl, opt.post_file_name,
1012 write_error = post_file (sock, NULL, opt.post_file_name,
1016 DEBUGP (("---request end---\n"));
1018 if (write_error < 0)
1020 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1022 CLOSE_INVALIDATE (sock);
1025 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1026 proxy ? "Proxy" : "HTTP");
1027 contlen = contrange = -1;
1032 /* Before reading anything, initialize the rbuf. */
1033 rbuf_initialize (&rbuf, sock);
1035 if (conn->scheme == SCHEME_HTTPS)
1039 #endif /* HAVE_SSL */
1042 /* Header-fetching loop. */
1050 /* Get the header. */
1051 status = header_get (&rbuf, &hdr,
1052 /* Disallow continuations for status line. */
1053 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
1055 /* Check for errors. */
1056 if (status == HG_EOF && *hdr)
1058 /* This used to be an unconditional error, but that was
1059 somewhat controversial, because of a large number of
1060 broken CGI's that happily "forget" to send the second EOL
1061 before closing the connection of a HEAD request.
1063 So, the deal is to check whether the header is empty
1064 (*hdr is zero if it is); if yes, it means that the
1065 previous header was fully retrieved, and that -- most
1066 probably -- the request is complete. "...be liberal in
1067 what you accept." Oh boy. */
1068 logputs (LOG_VERBOSE, "\n");
1069 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
1072 FREE_MAYBE (all_headers);
1073 CLOSE_INVALIDATE (sock);
1076 else if (status == HG_ERROR)
1078 logputs (LOG_VERBOSE, "\n");
1079 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1083 FREE_MAYBE (all_headers);
1084 CLOSE_INVALIDATE (sock);
1088 /* If the headers are to be saved to a file later, save them to
1090 if (opt.save_headers)
1092 int lh = strlen (hdr);
1093 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
1094 memcpy (all_headers + all_length, hdr, lh);
1096 all_headers[all_length++] = '\n';
1097 all_headers[all_length] = '\0';
1100 /* Check for status line. */
1104 /* Parse the first line of server response. */
1105 statcode = parse_http_status_line (hdr, &error);
1106 hs->statcode = statcode;
1107 /* Store the descriptive response. */
1108 if (statcode == -1) /* malformed response */
1110 /* A common reason for "malformed response" error is the
1111 case when no data was actually received. Handle this
1114 hs->error = xstrdup (_("No data received"));
1116 hs->error = xstrdup (_("Malformed status line"));
1121 hs->error = xstrdup (_("(no description)"));
1123 hs->error = xstrdup (error);
1125 if ((statcode != -1)
1131 if (opt.server_response)
1132 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1134 logprintf (LOG_VERBOSE, "%2d %s", statcode, error);
1140 /* Exit on empty header. */
1147 /* Print the header if requested. */
1148 if (opt.server_response && hcount != 1)
1149 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1151 /* Try getting content-length. */
1152 if (contlen == -1 && !opt.ignore_length)
1153 if (header_process (hdr, "Content-Length", header_extract_number,
1156 /* Try getting content-type. */
1158 if (header_process (hdr, "Content-Type", http_process_type, &type))
1160 /* Try getting location. */
1162 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
1164 /* Try getting last-modified. */
1165 if (!hs->remote_time)
1166 if (header_process (hdr, "Last-Modified", header_strdup,
1169 /* Try getting cookies. */
1171 if (header_process (hdr, "Set-Cookie", set_cookie_header_cb, u))
1173 /* Try getting www-authentication. */
1174 if (!authenticate_h)
1175 if (header_process (hdr, "WWW-Authenticate", header_strdup,
1178 /* Check for accept-ranges header. If it contains the word
1179 `none', disable the ranges. */
1180 if (*dt & ACCEPTRANGES)
1183 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1186 *dt &= ~ACCEPTRANGES;
1190 /* Try getting content-range. */
1191 if (contrange == -1)
1193 struct http_process_range_closure closure;
1194 if (header_process (hdr, "Content-Range", http_process_range, &closure))
1196 contrange = closure.first_byte_pos;
1200 /* Check for keep-alive related responses. */
1201 if (!inhibit_keep_alive)
1203 /* Check for the `Keep-Alive' header. */
1204 if (!http_keep_alive_1)
1206 if (header_process (hdr, "Keep-Alive", header_exists,
1207 &http_keep_alive_1))
1210 /* Check for `Connection: Keep-Alive'. */
1211 if (!http_keep_alive_2)
1213 if (header_process (hdr, "Connection", http_process_connection,
1214 &http_keep_alive_2))
1222 logputs (LOG_VERBOSE, "\n");
1225 && (http_keep_alive_1 || http_keep_alive_2))
1227 assert (inhibit_keep_alive == 0);
1231 /* The server has promised that it will not close the connection
1232 when we're done. This means that we can register it. */
1234 register_persistent (conn->host, conn->port, sock);
1236 register_persistent (conn->host, conn->port, sock, ssl);
1237 #endif /* HAVE_SSL */
1239 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1242 /* Authorization is required. */
1246 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1247 might be more bytes in the body. */
1248 if (auth_tried_already)
1250 /* If we have tried it already, then there is not point
1253 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1254 xfree (authenticate_h);
1257 else if (!known_authentication_scheme_p (authenticate_h))
1259 xfree (authenticate_h);
1260 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1263 else if (BEGINS_WITH (authenticate_h, "Basic"))
1265 /* The authentication scheme is basic, the one we try by
1266 default, and it failed. There's no sense in trying
1272 auth_tried_already = 1;
1276 /* We do not need this anymore. */
1279 xfree (authenticate_h);
1280 authenticate_h = NULL;
1283 /* 20x responses are counted among successful by default. */
1284 if (H_20X (statcode))
1287 /* Return if redirected. */
1288 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1290 /* RFC2068 says that in case of the 300 (multiple choices)
1291 response, the server can output a preferred URL through
1292 `Location' header; otherwise, the request should be treated
1293 like GET. So, if the location is set, it will be a
1294 redirection; otherwise, just proceed normally. */
1295 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1299 logprintf (LOG_VERBOSE,
1300 _("Location: %s%s\n"),
1301 hs->newloc ? hs->newloc : _("unspecified"),
1302 hs->newloc ? _(" [following]") : "");
1303 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1304 might be more bytes in the body. */
1306 FREE_MAYBE (all_headers);
1311 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1314 /* We don't assume text/html by default. */
1317 if (opt.html_extension && (*dt & TEXTHTML))
1318 /* -E / --html-extension / html_extension = on was specified, and this is a
1319 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1320 already the file's suffix, tack on ".html". */
1322 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1324 if (last_period_in_local_filename == NULL ||
1325 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1326 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1328 size_t local_filename_len = strlen(*hs->local_file);
1330 *hs->local_file = xrealloc(*hs->local_file,
1331 local_filename_len + sizeof(".html"));
1332 strcpy(*hs->local_file + local_filename_len, ".html");
1334 *dt |= ADDED_HTML_EXTENSION;
1338 if (contrange == -1)
1340 /* We did not get a content-range header. This means that the
1341 server did not honor our `Range' request. Normally, this
1342 means we should reset hs->restval and continue normally. */
1344 /* However, if `-c' is used, we need to be a bit more careful:
1346 1. If `-c' is specified and the file already existed when
1347 Wget was started, it would be a bad idea for us to start
1348 downloading it from scratch, effectively truncating it. I
1349 believe this cannot happen unless `-c' was specified.
1351 2. If `-c' is used on a file that is already fully
1352 downloaded, we're requesting bytes after the end of file,
1353 which can result in server not honoring `Range'. If this is
1354 the case, `Content-Length' will be equal to the length of the
1356 if (opt.always_rest)
1358 /* Check for condition #2. */
1359 if (hs->restval > 0 /* restart was requested. */
1360 && contlen != -1 /* we got content-length. */
1361 && hs->restval >= contlen /* file fully downloaded
1365 logputs (LOG_VERBOSE, _("\
1366 \n The file is already fully retrieved; nothing to do.\n\n"));
1367 /* In case the caller inspects. */
1370 /* Mark as successfully retrieved. */
1373 FREE_MAYBE (all_headers);
1374 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1375 might be more bytes in the body. */
1376 return RETRUNNEEDED;
1379 /* Check for condition #1. */
1380 if (hs->no_truncate)
1382 logprintf (LOG_NOTQUIET,
1385 Continued download failed on this file, which conflicts with `-c'.\n\
1386 Refusing to truncate existing file `%s'.\n\n"), *hs->local_file);
1388 FREE_MAYBE (all_headers);
1389 CLOSE_INVALIDATE (sock);
1390 return CONTNOTSUPPORTED;
1398 else if (contrange != hs->restval ||
1399 (H_PARTIAL (statcode) && contrange == -1))
1401 /* This means the whole request was somehow misunderstood by the
1402 server. Bail out. */
1404 FREE_MAYBE (all_headers);
1405 CLOSE_INVALIDATE (sock);
1412 contlen += contrange;
1414 contrange = -1; /* If conent-length was not sent,
1415 content-range will be ignored. */
1417 hs->contlen = contlen;
1421 if ((*dt & RETROKF) && !opt.server_response)
1423 /* No need to print this output if the body won't be
1424 downloaded at all, or if the original server response is
1426 logputs (LOG_VERBOSE, _("Length: "));
1429 logputs (LOG_VERBOSE, legible (contlen));
1430 if (contrange != -1)
1431 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1432 legible (contlen - contrange));
1435 logputs (LOG_VERBOSE,
1436 opt.ignore_length ? _("ignored") : _("unspecified"));
1438 logprintf (LOG_VERBOSE, " [%s]\n", type);
1440 logputs (LOG_VERBOSE, "\n");
1444 type = NULL; /* We don't need it any more. */
1446 /* Return if we have no intention of further downloading. */
1447 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1449 /* In case the caller cares to look... */
1453 FREE_MAYBE (all_headers);
1454 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1455 might be more bytes in the body. */
1456 return RETRFINISHED;
1459 /* Open the local file. */
1462 mkalldirs (*hs->local_file);
1464 rotate_backups (*hs->local_file);
1465 fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1468 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1469 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1470 might be more bytes in the body. */
1471 FREE_MAYBE (all_headers);
1477 extern int global_download_count;
1479 /* To ensure that repeated "from scratch" downloads work for -O
1480 files, we rewind the file pointer, unless restval is
1481 non-zero. (This works only when -O is used on regular files,
1482 but it's still a valuable feature.)
1484 However, this loses when more than one URL is specified on
1485 the command line the second rewinds eradicates the contents
1486 of the first download. Thus we disable the above trick for
1487 all the downloads except the very first one.
1489 #### A possible solution to this would be to remember the
1490 file position in the output document and to seek to that
1491 position, instead of rewinding. */
1492 if (!hs->restval && global_download_count == 0)
1494 /* This will silently fail for streams that don't correspond
1495 to regular files, but that's OK. */
1497 /* ftruncate is needed because opt.dfp is opened in append
1498 mode if opt.always_rest is set. */
1499 ftruncate (fileno (fp), 0);
1504 /* #### This confuses the code that checks for file size. There
1505 should be some overhead information. */
1506 if (opt.save_headers)
1507 fwrite (all_headers, 1, all_length, fp);
1509 /* Get the contents of the document. */
1510 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1511 (contlen != -1 ? contlen : 0),
1512 &rbuf, keep_alive, &hs->dltime);
1515 CLOSE_FINISH (sock);
1517 CLOSE_INVALIDATE (sock);
1520 /* Close or flush the file. We have to be careful to check for
1521 error here. Checking the result of fwrite() is not enough --
1522 errors could go unnoticed! */
1525 flush_res = fclose (fp);
1527 flush_res = fflush (fp);
1528 if (flush_res == EOF)
1531 FREE_MAYBE (all_headers);
1534 return RETRFINISHED;
1537 /* The genuine HTTP loop! This is the part where the retrieval is
1538 retried, and retried, and retried, and... */
1540 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1541 int *dt, struct url *proxy)
1544 int use_ts, got_head = 0; /* time-stamping info */
1545 char *filename_plus_orig_suffix;
1546 char *local_filename = NULL;
1547 char *tms, *locf, *tmrate;
1549 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1550 long local_size = 0; /* the size of the local file */
1551 size_t filename_len;
1552 struct http_stat hstat; /* HTTP status */
1556 /* This used to be done in main(), but it's a better idea to do it
1557 here so that we don't go through the hoops if we're just using
1559 if (opt.cookies && opt.cookies_input && !cookies_loaded_p)
1561 load_cookies (opt.cookies_input);
1562 cookies_loaded_p = 1;
1567 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1568 has_wildcards_p because it would also warn on `?', and we know that
1569 shows up in CGI paths a *lot*. */
1570 if (strchr (u->url, '*'))
1571 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1573 /* Determine the local filename. */
1574 if (local_file && *local_file)
1575 hstat.local_file = local_file;
1576 else if (local_file)
1578 *local_file = url_filename (u);
1579 hstat.local_file = local_file;
1583 dummy = url_filename (u);
1584 hstat.local_file = &dummy;
1587 if (!opt.output_document)
1588 locf = *hstat.local_file;
1590 locf = opt.output_document;
1592 hstat.referer = referer;
1594 filename_len = strlen (*hstat.local_file);
1595 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1597 if (opt.noclobber && file_exists_p (*hstat.local_file))
1599 /* If opt.noclobber is turned on and file already exists, do not
1600 retrieve the file */
1601 logprintf (LOG_VERBOSE, _("\
1602 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1603 /* If the file is there, we suppose it's retrieved OK. */
1606 /* #### Bogusness alert. */
1607 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1608 if (has_html_suffix_p (*hstat.local_file))
1616 if (opt.timestamping)
1618 boolean local_dot_orig_file_exists = FALSE;
1620 if (opt.backup_converted)
1621 /* If -K is specified, we'll act on the assumption that it was specified
1622 last time these files were downloaded as well, and instead of just
1623 comparing local file X against server file X, we'll compare local
1624 file X.orig (if extant, else X) against server file X. If -K
1625 _wasn't_ specified last time, or the server contains files called
1626 *.orig, -N will be back to not operating correctly with -k. */
1628 /* Would a single s[n]printf() call be faster? --dan
1630 Definitely not. sprintf() is horribly slow. It's a
1631 different question whether the difference between the two
1632 affects a program. Usually I'd say "no", but at one
1633 point I profiled Wget, and found that a measurable and
1634 non-negligible amount of time was lost calling sprintf()
1635 in url.c. Replacing sprintf with inline calls to
1636 strcpy() and long_to_string() made a difference.
1638 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1639 memcpy (filename_plus_orig_suffix + filename_len,
1640 ".orig", sizeof (".orig"));
1642 /* Try to stat() the .orig file. */
1643 if (stat (filename_plus_orig_suffix, &st) == 0)
1645 local_dot_orig_file_exists = TRUE;
1646 local_filename = filename_plus_orig_suffix;
1650 if (!local_dot_orig_file_exists)
1651 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1652 if (stat (*hstat.local_file, &st) == 0)
1653 local_filename = *hstat.local_file;
1655 if (local_filename != NULL)
1656 /* There was a local file, so we'll check later to see if the version
1657 the server has is the same version we already have, allowing us to
1663 /* Modification time granularity is 2 seconds for Windows, so
1664 increase local time by 1 second for later comparison. */
1667 local_size = st.st_size;
1671 /* Reset the counter. */
1673 *dt = 0 | ACCEPTRANGES;
1677 /* Increment the pass counter. */
1679 sleep_between_retrievals (count);
1680 /* Get the current time string. */
1681 tms = time_str (NULL);
1682 /* Print fetch message, if opt.verbose. */
1685 char *hurl = url_string (u, 1);
1689 sprintf (tmp, _("(try:%2d)"), count);
1690 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1691 tms, hurl, tmp, locf);
1693 ws_changetitle (hurl, 1);
1698 /* Default document type is empty. However, if spider mode is
1699 on or time-stamping is employed, HEAD_ONLY commands is
1700 encoded within *dt. */
1701 if (opt.spider || (use_ts && !got_head))
1705 /* Assume no restarting. */
1707 /* Decide whether or not to restart. */
1708 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1709 /* #### this calls access() and then stat(); could be optimized. */
1710 && file_exists_p (locf))
1711 if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1712 hstat.restval = st.st_size;
1714 /* In `-c' is used and the file is existing and non-empty,
1715 refuse to truncate it if the server doesn't support continued
1717 hstat.no_truncate = 0;
1718 if (opt.always_rest && hstat.restval)
1719 hstat.no_truncate = 1;
1721 /* Decide whether to send the no-cache directive. We send it in
1723 a) we're using a proxy, and we're past our first retrieval.
1724 Some proxies are notorious for caching incomplete data, so
1725 we require a fresh get.
1726 b) caching is explicitly inhibited. */
1727 if ((proxy && count > 1) /* a */
1728 || !opt.allow_cache /* b */
1730 *dt |= SEND_NOCACHE;
1732 *dt &= ~SEND_NOCACHE;
1734 /* Try fetching the document, or at least its head. */
1735 err = gethttp (u, &hstat, dt, proxy);
1737 /* It's unfortunate that wget determines the local filename before finding
1738 out the Content-Type of the file. Barring a major restructuring of the
1739 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1740 *hstat.local_file to tack on ".html". */
1741 if (!opt.output_document)
1742 locf = *hstat.local_file;
1744 locf = opt.output_document;
1747 tms = time_str (NULL);
1748 /* Get the new location (with or without the redirection). */
1750 *newloc = xstrdup (hstat.newloc);
1753 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1754 case CONERROR: case READERR: case WRITEFAILED:
1756 /* Non-fatal errors continue executing the loop, which will
1757 bring them to "while" statement at the end, to judge
1758 whether the number of tries was exceeded. */
1759 free_hstat (&hstat);
1760 printwhat (count, opt.ntry);
1763 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1764 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1765 /* Fatal errors just return from the function. */
1766 free_hstat (&hstat);
1770 case FWRITEERR: case FOPENERR:
1771 /* Another fatal error. */
1772 logputs (LOG_VERBOSE, "\n");
1773 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1774 *hstat.local_file, strerror (errno));
1775 free_hstat (&hstat);
1780 /* Another fatal error. */
1781 logputs (LOG_VERBOSE, "\n");
1782 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1783 free_hstat (&hstat);
1788 /* Return the new location to the caller. */
1791 logprintf (LOG_NOTQUIET,
1792 _("ERROR: Redirection (%d) without location.\n"),
1794 free_hstat (&hstat);
1798 free_hstat (&hstat);
1803 /* The file was already fully retrieved. */
1804 free_hstat (&hstat);
1809 /* Deal with you later. */
1812 /* All possibilities should have been exhausted. */
1815 if (!(*dt & RETROKF))
1819 /* #### Ugly ugly ugly! */
1820 char *hurl = url_string (u, 1);
1821 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1824 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1825 tms, hstat.statcode, hstat.error);
1826 logputs (LOG_VERBOSE, "\n");
1827 free_hstat (&hstat);
1832 /* Did we get the time-stamp? */
1835 if (opt.timestamping && !hstat.remote_time)
1837 logputs (LOG_NOTQUIET, _("\
1838 Last-modified header missing -- time-stamps turned off.\n"));
1840 else if (hstat.remote_time)
1842 /* Convert the date-string into struct tm. */
1843 tmr = http_atotm (hstat.remote_time);
1844 if (tmr == (time_t) (-1))
1845 logputs (LOG_VERBOSE, _("\
1846 Last-modified header invalid -- time-stamp ignored.\n"));
1850 /* The time-stamping section. */
1855 use_ts = 0; /* no more time-stamping */
1856 count = 0; /* the retrieve count for HEAD is
1858 if (hstat.remote_time && tmr != (time_t) (-1))
1860 /* Now time-stamping can be used validly. Time-stamping
1861 means that if the sizes of the local and remote file
1862 match, and local file is newer than the remote file,
1863 it will not be retrieved. Otherwise, the normal
1864 download procedure is resumed. */
1866 (hstat.contlen == -1 || local_size == hstat.contlen))
1868 logprintf (LOG_VERBOSE, _("\
1869 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1871 free_hstat (&hstat);
1875 else if (tml >= tmr)
1876 logprintf (LOG_VERBOSE, _("\
1877 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1879 logputs (LOG_VERBOSE,
1880 _("Remote file is newer, retrieving.\n"));
1882 free_hstat (&hstat);
1885 if ((tmr != (time_t) (-1))
1887 && ((hstat.len == hstat.contlen) ||
1888 ((hstat.res == 0) &&
1889 ((hstat.contlen == -1) ||
1890 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1892 /* #### This code repeats in http.c and ftp.c. Move it to a
1894 const char *fl = NULL;
1895 if (opt.output_document)
1897 if (opt.od_known_regular)
1898 fl = opt.output_document;
1901 fl = *hstat.local_file;
1905 /* End of time-stamping section. */
1909 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1914 tmrate = retr_rate (hstat.len - hstat.restval, hstat.dltime, 0);
1916 if (hstat.len == hstat.contlen)
1920 logprintf (LOG_VERBOSE,
1921 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1922 tms, tmrate, locf, hstat.len, hstat.contlen);
1923 logprintf (LOG_NONVERBOSE,
1924 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1925 tms, u->url, hstat.len, hstat.contlen, locf, count);
1928 downloaded_increase (hstat.len);
1930 /* Remember that we downloaded the file for later ".orig" code. */
1931 if (*dt & ADDED_HTML_EXTENSION)
1932 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1934 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1936 free_hstat (&hstat);
1940 else if (hstat.res == 0) /* No read error */
1942 if (hstat.contlen == -1) /* We don't know how much we were supposed
1943 to get, so assume we succeeded. */
1947 logprintf (LOG_VERBOSE,
1948 _("%s (%s) - `%s' saved [%ld]\n\n"),
1949 tms, tmrate, locf, hstat.len);
1950 logprintf (LOG_NONVERBOSE,
1951 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1952 tms, u->url, hstat.len, locf, count);
1955 downloaded_increase (hstat.len);
1957 /* Remember that we downloaded the file for later ".orig" code. */
1958 if (*dt & ADDED_HTML_EXTENSION)
1959 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1961 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1963 free_hstat (&hstat);
1967 else if (hstat.len < hstat.contlen) /* meaning we lost the
1968 connection too soon */
1970 logprintf (LOG_VERBOSE,
1971 _("%s (%s) - Connection closed at byte %ld. "),
1972 tms, tmrate, hstat.len);
1973 printwhat (count, opt.ntry);
1974 free_hstat (&hstat);
1977 else if (!opt.kill_longer) /* meaning we got more than expected */
1979 logprintf (LOG_VERBOSE,
1980 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1981 tms, tmrate, locf, hstat.len, hstat.contlen);
1982 logprintf (LOG_NONVERBOSE,
1983 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1984 tms, u->url, hstat.len, hstat.contlen, locf, count);
1986 downloaded_increase (hstat.len);
1988 /* Remember that we downloaded the file for later ".orig" code. */
1989 if (*dt & ADDED_HTML_EXTENSION)
1990 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1992 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1994 free_hstat (&hstat);
1998 else /* the same, but not accepted */
2000 logprintf (LOG_VERBOSE,
2001 _("%s (%s) - Connection closed at byte %ld/%ld. "),
2002 tms, tmrate, hstat.len, hstat.contlen);
2003 printwhat (count, opt.ntry);
2004 free_hstat (&hstat);
2008 else /* now hstat.res can only be -1 */
2010 if (hstat.contlen == -1)
2012 logprintf (LOG_VERBOSE,
2013 _("%s (%s) - Read error at byte %ld (%s)."),
2014 tms, tmrate, hstat.len, strerror (errno));
2015 printwhat (count, opt.ntry);
2016 free_hstat (&hstat);
2019 else /* hstat.res == -1 and contlen is given */
2021 logprintf (LOG_VERBOSE,
2022 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2023 tms, tmrate, hstat.len, hstat.contlen,
2025 printwhat (count, opt.ntry);
2026 free_hstat (&hstat);
2033 while (!opt.ntry || (count < opt.ntry));
2037 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2038 than local timezone.
2040 mktime is similar but assumes struct tm, also known as the
2041 "broken-down" form of time, is in local time zone. mktime_from_utc
2042 uses mktime to make the conversion understanding that an offset
2043 will be introduced by the local time assumption.
2045 mktime_from_utc then measures the introduced offset by applying
2046 gmtime to the initial result and applying mktime to the resulting
2047 "broken-down" form. The difference between the two mktime results
2048 is the measured offset which is then subtracted from the initial
2049 mktime result to yield a calendar time which is the value returned.
2051 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2052 consistent offset (the non DST offset) since tm and tm+o might be
2053 on opposite sides of a DST change.
2055 Some implementations of mktime return -1 for the nonexistent
2056 localtime hour at the beginning of DST. In this event, use
2057 mktime(tm - 1hr) + 3600.
2061 gmtime(t+o) --> tm+o
2062 mktime(tm+o) --> t+2o
2063 t+o - (t+2o - t+o) = t
2065 Note that glibc contains a function of the same purpose named
2066 `timegm' (reverse of gmtime). But obviously, it is not universally
2067 available, and unfortunately it is not straightforwardly
2068 extractable for use here. Perhaps configure should detect timegm
2069 and use it where available.
2071 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2072 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2073 Further improved by Roger with assistance from Edward J. Sabol
2074 based on input by Jamie Zawinski. */
2077 mktime_from_utc (struct tm *t)
2088 return -1; /* can't deal with output from strptime */
2099 return -1; /* can't deal with output from gmtime */
2102 return (tl - (tb - tl));
2105 /* Check whether the result of strptime() indicates success.
2106 strptime() returns the pointer to how far it got to in the string.
2107 The processing has been successful if the string is at `GMT' or
2108 `+X', or at the end of the string.
2110 In extended regexp parlance, the function returns 1 if P matches
2111 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2112 can return) is considered a failure and 0 is returned. */
2114 check_end (const char *p)
2118 while (ISSPACE (*p))
2121 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2122 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2128 /* Convert the textual specification of time in TIME_STRING to the
2129 number of seconds since the Epoch.
2131 TIME_STRING can be in any of the three formats RFC2068 allows the
2132 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2133 Timezones are ignored, and should be GMT.
2135 Return the computed time_t representation, or -1 if the conversion
2138 This function uses strptime with various string formats for parsing
2139 TIME_STRING. This results in a parser that is not as lenient in
2140 interpreting TIME_STRING as I would like it to be. Being based on
2141 strptime, it always allows shortened months, one-digit days, etc.,
2142 but due to the multitude of formats in which time can be
2143 represented, an ideal HTTP time parser would be even more
2144 forgiving. It should completely ignore things like week days and
2145 concentrate only on the various forms of representing years,
2146 months, days, hours, minutes, and seconds. For example, it would
2147 be nice if it accepted ISO 8601 out of the box.
2149 I've investigated free and PD code for this purpose, but none was
2150 usable. getdate was big and unwieldy, and had potential copyright
2151 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2152 distributed with phttpd, is excellent, but we cannot use it because
2153 it is not assigned to the FSF. So I stuck it with strptime. */
2156 http_atotm (char *time_string)
2158 /* NOTE: Solaris strptime man page claims that %n and %t match white
2159 space, but that's not universally available. Instead, we simply
2160 use ` ' to mean "skip all WS", which works under all strptime
2161 implementations I've tested. */
2163 static const char *time_formats[] = {
2164 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2165 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2166 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2167 (google.com uses this for their cookies.) */
2168 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2174 /* According to Roger Beeman, we need to initialize tm_isdst, since
2175 strptime won't do it. */
2178 /* Note that under foreign locales Solaris strptime() fails to
2179 recognize English dates, which renders this function useless. We
2180 solve this by being careful not to affect LC_TIME when
2181 initializing locale.
2183 Another solution would be to temporarily set locale to C, invoke
2184 strptime(), and restore it back. This is slow and dirty,
2185 however, and locale support other than LC_MESSAGES can mess other
2186 things, so I rather chose to stick with just setting LC_MESSAGES.
2188 GNU strptime does not have this problem because it recognizes
2189 both international and local dates. */
2191 for (i = 0; i < ARRAY_SIZE (time_formats); i++)
2192 if (check_end (strptime (time_string, time_formats[i], &t)))
2193 return mktime_from_utc (&t);
2195 /* All formats have failed. */
2199 /* Authorization support: We support two authorization schemes:
2201 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2203 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2204 consisting of answering to the server's challenge with the proper
2207 /* How many bytes it will take to store LEN bytes in base64. */
2208 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2210 /* Encode the string S of length LENGTH to base64 format and place it
2211 to STORE. STORE will be 0-terminated, and must point to a writable
2212 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2214 base64_encode (const char *s, char *store, int length)
2216 /* Conversion table. */
2217 static char tbl[64] = {
2218 'A','B','C','D','E','F','G','H',
2219 'I','J','K','L','M','N','O','P',
2220 'Q','R','S','T','U','V','W','X',
2221 'Y','Z','a','b','c','d','e','f',
2222 'g','h','i','j','k','l','m','n',
2223 'o','p','q','r','s','t','u','v',
2224 'w','x','y','z','0','1','2','3',
2225 '4','5','6','7','8','9','+','/'
2228 unsigned char *p = (unsigned char *)store;
2230 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2231 for (i = 0; i < length; i += 3)
2233 *p++ = tbl[s[0] >> 2];
2234 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2235 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2236 *p++ = tbl[s[2] & 0x3f];
2239 /* Pad the result if necessary... */
2240 if (i == length + 1)
2242 else if (i == length + 2)
2243 *(p - 1) = *(p - 2) = '=';
2244 /* ...and zero-terminate it. */
2248 /* Create the authentication header contents for the `Basic' scheme.
2249 This is done by encoding the string `USER:PASS' in base64 and
2250 prepending `HEADER: Basic ' to it. */
2252 basic_authentication_encode (const char *user, const char *passwd,
2255 char *t1, *t2, *res;
2256 int len1 = strlen (user) + 1 + strlen (passwd);
2257 int len2 = BASE64_LENGTH (len1);
2259 t1 = (char *)alloca (len1 + 1);
2260 sprintf (t1, "%s:%s", user, passwd);
2261 t2 = (char *)alloca (1 + len2);
2262 base64_encode (t1, t2, len1);
2263 res = (char *)xmalloc (len2 + 11 + strlen (header));
2264 sprintf (res, "%s: Basic %s\r\n", header, t2);
2270 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2271 of a field in such a header. If the field is the one specified by
2272 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2273 digest authorization code), extract its value in the (char*)
2274 variable pointed by RET. Returns negative on a malformed header,
2275 or number of bytes that have been parsed by this call. */
2277 extract_header_attr (const char *au, const char *attr_name, char **ret)
2279 const char *cp, *ep;
2283 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2285 cp += strlen (attr_name);
2288 cp += skip_lws (cp);
2293 cp += skip_lws (cp);
2298 for (ep = cp; *ep && *ep != '\"'; ep++)
2303 *ret = strdupdelim (cp, ep);
2310 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2311 an array of 16 bytes containing the hash keys, and BUF should be a
2312 buffer of 33 writable characters (32 for hex digits plus one for
2313 zero termination). */
2315 dump_hash (unsigned char *buf, const unsigned char *hash)
2319 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2321 *buf++ = XDIGIT_TO_xchar (*hash >> 4);
2322 *buf++ = XDIGIT_TO_xchar (*hash & 0xf);
2327 /* Take the line apart to find the challenge, and compose a digest
2328 authorization header. See RFC2069 section 2.1.2. */
2330 digest_authentication_encode (const char *au, const char *user,
2331 const char *passwd, const char *method,
2334 static char *realm, *opaque, *nonce;
2339 { "realm", &realm },
2340 { "opaque", &opaque },
2345 realm = opaque = nonce = NULL;
2347 au += 6; /* skip over `Digest' */
2352 au += skip_lws (au);
2353 for (i = 0; i < ARRAY_SIZE (options); i++)
2355 int skip = extract_header_attr (au, options[i].name,
2356 options[i].variable);
2360 FREE_MAYBE (opaque);
2370 if (i == ARRAY_SIZE (options))
2372 while (*au && *au != '=')
2376 au += skip_lws (au);
2380 while (*au && *au != '\"')
2387 while (*au && *au != ',')
2392 if (!realm || !nonce || !user || !passwd || !path || !method)
2395 FREE_MAYBE (opaque);
2400 /* Calculate the digest value. */
2402 ALLOCA_MD5_CONTEXT (ctx);
2403 unsigned char hash[MD5_HASHLEN];
2404 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2405 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2407 /* A1BUF = H(user ":" realm ":" password) */
2409 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2410 gen_md5_update ((unsigned char *)":", 1, ctx);
2411 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2412 gen_md5_update ((unsigned char *)":", 1, ctx);
2413 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2414 gen_md5_finish (ctx, hash);
2415 dump_hash (a1buf, hash);
2417 /* A2BUF = H(method ":" path) */
2419 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2420 gen_md5_update ((unsigned char *)":", 1, ctx);
2421 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2422 gen_md5_finish (ctx, hash);
2423 dump_hash (a2buf, hash);
2425 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2427 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2428 gen_md5_update ((unsigned char *)":", 1, ctx);
2429 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2430 gen_md5_update ((unsigned char *)":", 1, ctx);
2431 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2432 gen_md5_finish (ctx, hash);
2433 dump_hash (response_digest, hash);
2435 res = (char*) xmalloc (strlen (user)
2440 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2441 + (opaque ? strlen (opaque) : 0)
2443 sprintf (res, "Authorization: Digest \
2444 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2445 user, realm, nonce, path, response_digest);
2448 char *p = res + strlen (res);
2449 strcat (p, ", opaque=\"");
2453 strcat (res, "\r\n");
2457 #endif /* USE_DIGEST */
2460 #define BEGINS_WITH(line, string_constant) \
2461 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2462 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2463 || !line[sizeof (string_constant) - 1]))
2466 known_authentication_scheme_p (const char *au)
2468 return BEGINS_WITH (au, "Basic")
2469 || BEGINS_WITH (au, "Digest")
2470 || BEGINS_WITH (au, "NTLM");
2475 /* Create the HTTP authorization request header. When the
2476 `WWW-Authenticate' response header is seen, according to the
2477 authorization scheme specified in that header (`Basic' and `Digest'
2478 are supported by the current implementation), produce an
2479 appropriate HTTP authorization request header. */
2481 create_authorization_line (const char *au, const char *user,
2482 const char *passwd, const char *method,
2485 char *wwwauth = NULL;
2487 if (!strncasecmp (au, "Basic", 5))
2488 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2489 if (!strncasecmp (au, "NTLM", 4))
2490 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2492 else if (!strncasecmp (au, "Digest", 6))
2493 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2494 #endif /* USE_DIGEST */
2501 if (pc_last_host_ip)
2502 address_list_release (pc_last_host_ip);