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 content-type is not given, assume text/html. This is because
1312 of the multitude of broken CGI's that "forget" to generate the
1314 if (!type || 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1319 if (opt.html_extension && (*dt & TEXTHTML))
1320 /* -E / --html-extension / html_extension = on was specified, and this is a
1321 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1322 already the file's suffix, tack on ".html". */
1324 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1326 if (last_period_in_local_filename == NULL ||
1327 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1328 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1330 size_t local_filename_len = strlen(*hs->local_file);
1332 *hs->local_file = xrealloc(*hs->local_file,
1333 local_filename_len + sizeof(".html"));
1334 strcpy(*hs->local_file + local_filename_len, ".html");
1336 *dt |= ADDED_HTML_EXTENSION;
1340 if (contrange == -1)
1342 /* We did not get a content-range header. This means that the
1343 server did not honor our `Range' request. Normally, this
1344 means we should reset hs->restval and continue normally. */
1346 /* However, if `-c' is used, we need to be a bit more careful:
1348 1. If `-c' is specified and the file already existed when
1349 Wget was started, it would be a bad idea for us to start
1350 downloading it from scratch, effectively truncating it. I
1351 believe this cannot happen unless `-c' was specified.
1353 2. If `-c' is used on a file that is already fully
1354 downloaded, we're requesting bytes after the end of file,
1355 which can result in server not honoring `Range'. If this is
1356 the case, `Content-Length' will be equal to the length of the
1358 if (opt.always_rest)
1360 /* Check for condition #2. */
1361 if (hs->restval > 0 /* restart was requested. */
1362 && contlen != -1 /* we got content-length. */
1363 && hs->restval >= contlen /* file fully downloaded
1367 logputs (LOG_VERBOSE, _("\
1368 \n The file is already fully retrieved; nothing to do.\n\n"));
1369 /* In case the caller inspects. */
1372 /* Mark as successfully retrieved. */
1375 FREE_MAYBE (all_headers);
1376 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1377 might be more bytes in the body. */
1378 return RETRUNNEEDED;
1381 /* Check for condition #1. */
1382 if (hs->no_truncate)
1384 logprintf (LOG_NOTQUIET,
1387 Continued download failed on this file, which conflicts with `-c'.\n\
1388 Refusing to truncate existing file `%s'.\n\n"), *hs->local_file);
1390 FREE_MAYBE (all_headers);
1391 CLOSE_INVALIDATE (sock);
1392 return CONTNOTSUPPORTED;
1400 else if (contrange != hs->restval ||
1401 (H_PARTIAL (statcode) && contrange == -1))
1403 /* This means the whole request was somehow misunderstood by the
1404 server. Bail out. */
1406 FREE_MAYBE (all_headers);
1407 CLOSE_INVALIDATE (sock);
1414 contlen += contrange;
1416 contrange = -1; /* If conent-length was not sent,
1417 content-range will be ignored. */
1419 hs->contlen = contlen;
1423 if ((*dt & RETROKF) && !opt.server_response)
1425 /* No need to print this output if the body won't be
1426 downloaded at all, or if the original server response is
1428 logputs (LOG_VERBOSE, _("Length: "));
1431 logputs (LOG_VERBOSE, legible (contlen));
1432 if (contrange != -1)
1433 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1434 legible (contlen - contrange));
1437 logputs (LOG_VERBOSE,
1438 opt.ignore_length ? _("ignored") : _("unspecified"));
1440 logprintf (LOG_VERBOSE, " [%s]\n", type);
1442 logputs (LOG_VERBOSE, "\n");
1446 type = NULL; /* We don't need it any more. */
1448 /* Return if we have no intention of further downloading. */
1449 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1451 /* In case the caller cares to look... */
1455 FREE_MAYBE (all_headers);
1456 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1457 might be more bytes in the body. */
1458 return RETRFINISHED;
1461 /* Open the local file. */
1464 mkalldirs (*hs->local_file);
1466 rotate_backups (*hs->local_file);
1467 fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1470 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1471 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1472 might be more bytes in the body. */
1473 FREE_MAYBE (all_headers);
1479 extern int global_download_count;
1481 /* To ensure that repeated "from scratch" downloads work for -O
1482 files, we rewind the file pointer, unless restval is
1483 non-zero. (This works only when -O is used on regular files,
1484 but it's still a valuable feature.)
1486 However, this loses when more than one URL is specified on
1487 the command line the second rewinds eradicates the contents
1488 of the first download. Thus we disable the above trick for
1489 all the downloads except the very first one.
1491 #### A possible solution to this would be to remember the
1492 file position in the output document and to seek to that
1493 position, instead of rewinding. */
1494 if (!hs->restval && global_download_count == 0)
1496 /* This will silently fail for streams that don't correspond
1497 to regular files, but that's OK. */
1499 /* ftruncate is needed because opt.dfp is opened in append
1500 mode if opt.always_rest is set. */
1501 ftruncate (fileno (fp), 0);
1506 /* #### This confuses the code that checks for file size. There
1507 should be some overhead information. */
1508 if (opt.save_headers)
1509 fwrite (all_headers, 1, all_length, fp);
1511 /* Get the contents of the document. */
1512 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1513 (contlen != -1 ? contlen : 0),
1514 &rbuf, keep_alive, &hs->dltime);
1517 CLOSE_FINISH (sock);
1519 CLOSE_INVALIDATE (sock);
1522 /* Close or flush the file. We have to be careful to check for
1523 error here. Checking the result of fwrite() is not enough --
1524 errors could go unnoticed! */
1527 flush_res = fclose (fp);
1529 flush_res = fflush (fp);
1530 if (flush_res == EOF)
1533 FREE_MAYBE (all_headers);
1536 return RETRFINISHED;
1539 /* The genuine HTTP loop! This is the part where the retrieval is
1540 retried, and retried, and retried, and... */
1542 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1543 int *dt, struct url *proxy)
1546 int use_ts, got_head = 0; /* time-stamping info */
1547 char *filename_plus_orig_suffix;
1548 char *local_filename = NULL;
1549 char *tms, *locf, *tmrate;
1551 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1552 long local_size = 0; /* the size of the local file */
1553 size_t filename_len;
1554 struct http_stat hstat; /* HTTP status */
1558 /* This used to be done in main(), but it's a better idea to do it
1559 here so that we don't go through the hoops if we're just using
1561 if (opt.cookies && opt.cookies_input && !cookies_loaded_p)
1563 load_cookies (opt.cookies_input);
1564 cookies_loaded_p = 1;
1569 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1570 has_wildcards_p because it would also warn on `?', and we know that
1571 shows up in CGI paths a *lot*. */
1572 if (strchr (u->url, '*'))
1573 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1575 /* Determine the local filename. */
1576 if (local_file && *local_file)
1577 hstat.local_file = local_file;
1578 else if (local_file)
1580 *local_file = url_filename (u);
1581 hstat.local_file = local_file;
1585 dummy = url_filename (u);
1586 hstat.local_file = &dummy;
1589 if (!opt.output_document)
1590 locf = *hstat.local_file;
1592 locf = opt.output_document;
1594 hstat.referer = referer;
1596 filename_len = strlen (*hstat.local_file);
1597 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1599 if (opt.noclobber && file_exists_p (*hstat.local_file))
1601 /* If opt.noclobber is turned on and file already exists, do not
1602 retrieve the file */
1603 logprintf (LOG_VERBOSE, _("\
1604 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1605 /* If the file is there, we suppose it's retrieved OK. */
1608 /* #### Bogusness alert. */
1609 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1610 if (has_html_suffix_p (*hstat.local_file))
1618 if (opt.timestamping)
1620 boolean local_dot_orig_file_exists = FALSE;
1622 if (opt.backup_converted)
1623 /* If -K is specified, we'll act on the assumption that it was specified
1624 last time these files were downloaded as well, and instead of just
1625 comparing local file X against server file X, we'll compare local
1626 file X.orig (if extant, else X) against server file X. If -K
1627 _wasn't_ specified last time, or the server contains files called
1628 *.orig, -N will be back to not operating correctly with -k. */
1630 /* Would a single s[n]printf() call be faster? --dan
1632 Definitely not. sprintf() is horribly slow. It's a
1633 different question whether the difference between the two
1634 affects a program. Usually I'd say "no", but at one
1635 point I profiled Wget, and found that a measurable and
1636 non-negligible amount of time was lost calling sprintf()
1637 in url.c. Replacing sprintf with inline calls to
1638 strcpy() and long_to_string() made a difference.
1640 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1641 memcpy (filename_plus_orig_suffix + filename_len,
1642 ".orig", sizeof (".orig"));
1644 /* Try to stat() the .orig file. */
1645 if (stat (filename_plus_orig_suffix, &st) == 0)
1647 local_dot_orig_file_exists = TRUE;
1648 local_filename = filename_plus_orig_suffix;
1652 if (!local_dot_orig_file_exists)
1653 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1654 if (stat (*hstat.local_file, &st) == 0)
1655 local_filename = *hstat.local_file;
1657 if (local_filename != NULL)
1658 /* There was a local file, so we'll check later to see if the version
1659 the server has is the same version we already have, allowing us to
1665 /* Modification time granularity is 2 seconds for Windows, so
1666 increase local time by 1 second for later comparison. */
1669 local_size = st.st_size;
1673 /* Reset the counter. */
1675 *dt = 0 | ACCEPTRANGES;
1679 /* Increment the pass counter. */
1681 sleep_between_retrievals (count);
1682 /* Get the current time string. */
1683 tms = time_str (NULL);
1684 /* Print fetch message, if opt.verbose. */
1687 char *hurl = url_string (u, 1);
1691 sprintf (tmp, _("(try:%2d)"), count);
1692 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1693 tms, hurl, tmp, locf);
1695 ws_changetitle (hurl, 1);
1700 /* Default document type is empty. However, if spider mode is
1701 on or time-stamping is employed, HEAD_ONLY commands is
1702 encoded within *dt. */
1703 if (opt.spider || (use_ts && !got_head))
1707 /* Assume no restarting. */
1709 /* Decide whether or not to restart. */
1710 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1711 /* #### this calls access() and then stat(); could be optimized. */
1712 && file_exists_p (locf))
1713 if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1714 hstat.restval = st.st_size;
1716 /* In `-c' is used and the file is existing and non-empty,
1717 refuse to truncate it if the server doesn't support continued
1719 hstat.no_truncate = 0;
1720 if (opt.always_rest && hstat.restval)
1721 hstat.no_truncate = 1;
1723 /* Decide whether to send the no-cache directive. We send it in
1725 a) we're using a proxy, and we're past our first retrieval.
1726 Some proxies are notorious for caching incomplete data, so
1727 we require a fresh get.
1728 b) caching is explicitly inhibited. */
1729 if ((proxy && count > 1) /* a */
1730 || !opt.allow_cache /* b */
1732 *dt |= SEND_NOCACHE;
1734 *dt &= ~SEND_NOCACHE;
1736 /* Try fetching the document, or at least its head. */
1737 err = gethttp (u, &hstat, dt, proxy);
1739 /* It's unfortunate that wget determines the local filename before finding
1740 out the Content-Type of the file. Barring a major restructuring of the
1741 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1742 *hstat.local_file to tack on ".html". */
1743 if (!opt.output_document)
1744 locf = *hstat.local_file;
1746 locf = opt.output_document;
1749 tms = time_str (NULL);
1750 /* Get the new location (with or without the redirection). */
1752 *newloc = xstrdup (hstat.newloc);
1755 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1756 case CONERROR: case READERR: case WRITEFAILED:
1758 /* Non-fatal errors continue executing the loop, which will
1759 bring them to "while" statement at the end, to judge
1760 whether the number of tries was exceeded. */
1761 free_hstat (&hstat);
1762 printwhat (count, opt.ntry);
1765 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1766 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1767 /* Fatal errors just return from the function. */
1768 free_hstat (&hstat);
1772 case FWRITEERR: case FOPENERR:
1773 /* Another fatal error. */
1774 logputs (LOG_VERBOSE, "\n");
1775 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1776 *hstat.local_file, strerror (errno));
1777 free_hstat (&hstat);
1782 /* Another fatal error. */
1783 logputs (LOG_VERBOSE, "\n");
1784 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1785 free_hstat (&hstat);
1790 /* Return the new location to the caller. */
1793 logprintf (LOG_NOTQUIET,
1794 _("ERROR: Redirection (%d) without location.\n"),
1796 free_hstat (&hstat);
1800 free_hstat (&hstat);
1805 /* The file was already fully retrieved. */
1806 free_hstat (&hstat);
1811 /* Deal with you later. */
1814 /* All possibilities should have been exhausted. */
1817 if (!(*dt & RETROKF))
1821 /* #### Ugly ugly ugly! */
1822 char *hurl = url_string (u, 1);
1823 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1826 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1827 tms, hstat.statcode, hstat.error);
1828 logputs (LOG_VERBOSE, "\n");
1829 free_hstat (&hstat);
1834 /* Did we get the time-stamp? */
1837 if (opt.timestamping && !hstat.remote_time)
1839 logputs (LOG_NOTQUIET, _("\
1840 Last-modified header missing -- time-stamps turned off.\n"));
1842 else if (hstat.remote_time)
1844 /* Convert the date-string into struct tm. */
1845 tmr = http_atotm (hstat.remote_time);
1846 if (tmr == (time_t) (-1))
1847 logputs (LOG_VERBOSE, _("\
1848 Last-modified header invalid -- time-stamp ignored.\n"));
1852 /* The time-stamping section. */
1857 use_ts = 0; /* no more time-stamping */
1858 count = 0; /* the retrieve count for HEAD is
1860 if (hstat.remote_time && tmr != (time_t) (-1))
1862 /* Now time-stamping can be used validly. Time-stamping
1863 means that if the sizes of the local and remote file
1864 match, and local file is newer than the remote file,
1865 it will not be retrieved. Otherwise, the normal
1866 download procedure is resumed. */
1868 (hstat.contlen == -1 || local_size == hstat.contlen))
1870 logprintf (LOG_VERBOSE, _("\
1871 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1873 free_hstat (&hstat);
1877 else if (tml >= tmr)
1878 logprintf (LOG_VERBOSE, _("\
1879 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1881 logputs (LOG_VERBOSE,
1882 _("Remote file is newer, retrieving.\n"));
1884 free_hstat (&hstat);
1887 if ((tmr != (time_t) (-1))
1889 && ((hstat.len == hstat.contlen) ||
1890 ((hstat.res == 0) &&
1891 ((hstat.contlen == -1) ||
1892 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1894 /* #### This code repeats in http.c and ftp.c. Move it to a
1896 const char *fl = NULL;
1897 if (opt.output_document)
1899 if (opt.od_known_regular)
1900 fl = opt.output_document;
1903 fl = *hstat.local_file;
1907 /* End of time-stamping section. */
1911 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1916 tmrate = retr_rate (hstat.len - hstat.restval, hstat.dltime, 0);
1918 if (hstat.len == hstat.contlen)
1922 logprintf (LOG_VERBOSE,
1923 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1924 tms, tmrate, locf, hstat.len, hstat.contlen);
1925 logprintf (LOG_NONVERBOSE,
1926 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1927 tms, u->url, hstat.len, hstat.contlen, locf, count);
1930 downloaded_increase (hstat.len);
1932 /* Remember that we downloaded the file for later ".orig" code. */
1933 if (*dt & ADDED_HTML_EXTENSION)
1934 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1936 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1938 free_hstat (&hstat);
1942 else if (hstat.res == 0) /* No read error */
1944 if (hstat.contlen == -1) /* We don't know how much we were supposed
1945 to get, so assume we succeeded. */
1949 logprintf (LOG_VERBOSE,
1950 _("%s (%s) - `%s' saved [%ld]\n\n"),
1951 tms, tmrate, locf, hstat.len);
1952 logprintf (LOG_NONVERBOSE,
1953 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1954 tms, u->url, hstat.len, locf, count);
1957 downloaded_increase (hstat.len);
1959 /* Remember that we downloaded the file for later ".orig" code. */
1960 if (*dt & ADDED_HTML_EXTENSION)
1961 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1963 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1965 free_hstat (&hstat);
1969 else if (hstat.len < hstat.contlen) /* meaning we lost the
1970 connection too soon */
1972 logprintf (LOG_VERBOSE,
1973 _("%s (%s) - Connection closed at byte %ld. "),
1974 tms, tmrate, hstat.len);
1975 printwhat (count, opt.ntry);
1976 free_hstat (&hstat);
1979 else if (!opt.kill_longer) /* meaning we got more than expected */
1981 logprintf (LOG_VERBOSE,
1982 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1983 tms, tmrate, locf, hstat.len, hstat.contlen);
1984 logprintf (LOG_NONVERBOSE,
1985 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1986 tms, u->url, hstat.len, hstat.contlen, locf, count);
1988 downloaded_increase (hstat.len);
1990 /* Remember that we downloaded the file for later ".orig" code. */
1991 if (*dt & ADDED_HTML_EXTENSION)
1992 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1994 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1996 free_hstat (&hstat);
2000 else /* the same, but not accepted */
2002 logprintf (LOG_VERBOSE,
2003 _("%s (%s) - Connection closed at byte %ld/%ld. "),
2004 tms, tmrate, hstat.len, hstat.contlen);
2005 printwhat (count, opt.ntry);
2006 free_hstat (&hstat);
2010 else /* now hstat.res can only be -1 */
2012 if (hstat.contlen == -1)
2014 logprintf (LOG_VERBOSE,
2015 _("%s (%s) - Read error at byte %ld (%s)."),
2016 tms, tmrate, hstat.len, strerror (errno));
2017 printwhat (count, opt.ntry);
2018 free_hstat (&hstat);
2021 else /* hstat.res == -1 and contlen is given */
2023 logprintf (LOG_VERBOSE,
2024 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2025 tms, tmrate, hstat.len, hstat.contlen,
2027 printwhat (count, opt.ntry);
2028 free_hstat (&hstat);
2035 while (!opt.ntry || (count < opt.ntry));
2039 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2040 than local timezone.
2042 mktime is similar but assumes struct tm, also known as the
2043 "broken-down" form of time, is in local time zone. mktime_from_utc
2044 uses mktime to make the conversion understanding that an offset
2045 will be introduced by the local time assumption.
2047 mktime_from_utc then measures the introduced offset by applying
2048 gmtime to the initial result and applying mktime to the resulting
2049 "broken-down" form. The difference between the two mktime results
2050 is the measured offset which is then subtracted from the initial
2051 mktime result to yield a calendar time which is the value returned.
2053 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2054 consistent offset (the non DST offset) since tm and tm+o might be
2055 on opposite sides of a DST change.
2057 Some implementations of mktime return -1 for the nonexistent
2058 localtime hour at the beginning of DST. In this event, use
2059 mktime(tm - 1hr) + 3600.
2063 gmtime(t+o) --> tm+o
2064 mktime(tm+o) --> t+2o
2065 t+o - (t+2o - t+o) = t
2067 Note that glibc contains a function of the same purpose named
2068 `timegm' (reverse of gmtime). But obviously, it is not universally
2069 available, and unfortunately it is not straightforwardly
2070 extractable for use here. Perhaps configure should detect timegm
2071 and use it where available.
2073 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2074 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2075 Further improved by Roger with assistance from Edward J. Sabol
2076 based on input by Jamie Zawinski. */
2079 mktime_from_utc (struct tm *t)
2090 return -1; /* can't deal with output from strptime */
2101 return -1; /* can't deal with output from gmtime */
2104 return (tl - (tb - tl));
2107 /* Check whether the result of strptime() indicates success.
2108 strptime() returns the pointer to how far it got to in the string.
2109 The processing has been successful if the string is at `GMT' or
2110 `+X', or at the end of the string.
2112 In extended regexp parlance, the function returns 1 if P matches
2113 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2114 can return) is considered a failure and 0 is returned. */
2116 check_end (const char *p)
2120 while (ISSPACE (*p))
2123 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2124 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2130 /* Convert the textual specification of time in TIME_STRING to the
2131 number of seconds since the Epoch.
2133 TIME_STRING can be in any of the three formats RFC2068 allows the
2134 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2135 Timezones are ignored, and should be GMT.
2137 Return the computed time_t representation, or -1 if the conversion
2140 This function uses strptime with various string formats for parsing
2141 TIME_STRING. This results in a parser that is not as lenient in
2142 interpreting TIME_STRING as I would like it to be. Being based on
2143 strptime, it always allows shortened months, one-digit days, etc.,
2144 but due to the multitude of formats in which time can be
2145 represented, an ideal HTTP time parser would be even more
2146 forgiving. It should completely ignore things like week days and
2147 concentrate only on the various forms of representing years,
2148 months, days, hours, minutes, and seconds. For example, it would
2149 be nice if it accepted ISO 8601 out of the box.
2151 I've investigated free and PD code for this purpose, but none was
2152 usable. getdate was big and unwieldy, and had potential copyright
2153 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2154 distributed with phttpd, is excellent, but we cannot use it because
2155 it is not assigned to the FSF. So I stuck it with strptime. */
2158 http_atotm (char *time_string)
2160 /* NOTE: Solaris strptime man page claims that %n and %t match white
2161 space, but that's not universally available. Instead, we simply
2162 use ` ' to mean "skip all WS", which works under all strptime
2163 implementations I've tested. */
2165 static const char *time_formats[] = {
2166 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2167 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2168 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2169 (google.com uses this for their cookies.) */
2170 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2176 /* According to Roger Beeman, we need to initialize tm_isdst, since
2177 strptime won't do it. */
2180 /* Note that under foreign locales Solaris strptime() fails to
2181 recognize English dates, which renders this function useless. We
2182 solve this by being careful not to affect LC_TIME when
2183 initializing locale.
2185 Another solution would be to temporarily set locale to C, invoke
2186 strptime(), and restore it back. This is slow and dirty,
2187 however, and locale support other than LC_MESSAGES can mess other
2188 things, so I rather chose to stick with just setting LC_MESSAGES.
2190 GNU strptime does not have this problem because it recognizes
2191 both international and local dates. */
2193 for (i = 0; i < ARRAY_SIZE (time_formats); i++)
2194 if (check_end (strptime (time_string, time_formats[i], &t)))
2195 return mktime_from_utc (&t);
2197 /* All formats have failed. */
2201 /* Authorization support: We support two authorization schemes:
2203 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2205 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2206 consisting of answering to the server's challenge with the proper
2209 /* How many bytes it will take to store LEN bytes in base64. */
2210 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2212 /* Encode the string S of length LENGTH to base64 format and place it
2213 to STORE. STORE will be 0-terminated, and must point to a writable
2214 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2216 base64_encode (const char *s, char *store, int length)
2218 /* Conversion table. */
2219 static char tbl[64] = {
2220 'A','B','C','D','E','F','G','H',
2221 'I','J','K','L','M','N','O','P',
2222 'Q','R','S','T','U','V','W','X',
2223 'Y','Z','a','b','c','d','e','f',
2224 'g','h','i','j','k','l','m','n',
2225 'o','p','q','r','s','t','u','v',
2226 'w','x','y','z','0','1','2','3',
2227 '4','5','6','7','8','9','+','/'
2230 unsigned char *p = (unsigned char *)store;
2232 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2233 for (i = 0; i < length; i += 3)
2235 *p++ = tbl[s[0] >> 2];
2236 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2237 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2238 *p++ = tbl[s[2] & 0x3f];
2241 /* Pad the result if necessary... */
2242 if (i == length + 1)
2244 else if (i == length + 2)
2245 *(p - 1) = *(p - 2) = '=';
2246 /* ...and zero-terminate it. */
2250 /* Create the authentication header contents for the `Basic' scheme.
2251 This is done by encoding the string `USER:PASS' in base64 and
2252 prepending `HEADER: Basic ' to it. */
2254 basic_authentication_encode (const char *user, const char *passwd,
2257 char *t1, *t2, *res;
2258 int len1 = strlen (user) + 1 + strlen (passwd);
2259 int len2 = BASE64_LENGTH (len1);
2261 t1 = (char *)alloca (len1 + 1);
2262 sprintf (t1, "%s:%s", user, passwd);
2263 t2 = (char *)alloca (1 + len2);
2264 base64_encode (t1, t2, len1);
2265 res = (char *)xmalloc (len2 + 11 + strlen (header));
2266 sprintf (res, "%s: Basic %s\r\n", header, t2);
2272 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2273 of a field in such a header. If the field is the one specified by
2274 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2275 digest authorization code), extract its value in the (char*)
2276 variable pointed by RET. Returns negative on a malformed header,
2277 or number of bytes that have been parsed by this call. */
2279 extract_header_attr (const char *au, const char *attr_name, char **ret)
2281 const char *cp, *ep;
2285 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2287 cp += strlen (attr_name);
2290 cp += skip_lws (cp);
2295 cp += skip_lws (cp);
2300 for (ep = cp; *ep && *ep != '\"'; ep++)
2305 *ret = strdupdelim (cp, ep);
2312 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2313 an array of 16 bytes containing the hash keys, and BUF should be a
2314 buffer of 33 writable characters (32 for hex digits plus one for
2315 zero termination). */
2317 dump_hash (unsigned char *buf, const unsigned char *hash)
2321 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2323 *buf++ = XDIGIT_TO_xchar (*hash >> 4);
2324 *buf++ = XDIGIT_TO_xchar (*hash & 0xf);
2329 /* Take the line apart to find the challenge, and compose a digest
2330 authorization header. See RFC2069 section 2.1.2. */
2332 digest_authentication_encode (const char *au, const char *user,
2333 const char *passwd, const char *method,
2336 static char *realm, *opaque, *nonce;
2341 { "realm", &realm },
2342 { "opaque", &opaque },
2347 realm = opaque = nonce = NULL;
2349 au += 6; /* skip over `Digest' */
2354 au += skip_lws (au);
2355 for (i = 0; i < ARRAY_SIZE (options); i++)
2357 int skip = extract_header_attr (au, options[i].name,
2358 options[i].variable);
2362 FREE_MAYBE (opaque);
2372 if (i == ARRAY_SIZE (options))
2374 while (*au && *au != '=')
2378 au += skip_lws (au);
2382 while (*au && *au != '\"')
2389 while (*au && *au != ',')
2394 if (!realm || !nonce || !user || !passwd || !path || !method)
2397 FREE_MAYBE (opaque);
2402 /* Calculate the digest value. */
2404 ALLOCA_MD5_CONTEXT (ctx);
2405 unsigned char hash[MD5_HASHLEN];
2406 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2407 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2409 /* A1BUF = H(user ":" realm ":" password) */
2411 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2412 gen_md5_update ((unsigned char *)":", 1, ctx);
2413 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2414 gen_md5_update ((unsigned char *)":", 1, ctx);
2415 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2416 gen_md5_finish (ctx, hash);
2417 dump_hash (a1buf, hash);
2419 /* A2BUF = H(method ":" path) */
2421 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2422 gen_md5_update ((unsigned char *)":", 1, ctx);
2423 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2424 gen_md5_finish (ctx, hash);
2425 dump_hash (a2buf, hash);
2427 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2429 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2430 gen_md5_update ((unsigned char *)":", 1, ctx);
2431 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2432 gen_md5_update ((unsigned char *)":", 1, ctx);
2433 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2434 gen_md5_finish (ctx, hash);
2435 dump_hash (response_digest, hash);
2437 res = (char*) xmalloc (strlen (user)
2442 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2443 + (opaque ? strlen (opaque) : 0)
2445 sprintf (res, "Authorization: Digest \
2446 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2447 user, realm, nonce, path, response_digest);
2450 char *p = res + strlen (res);
2451 strcat (p, ", opaque=\"");
2455 strcat (res, "\r\n");
2459 #endif /* USE_DIGEST */
2462 #define BEGINS_WITH(line, string_constant) \
2463 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2464 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2465 || !line[sizeof (string_constant) - 1]))
2468 known_authentication_scheme_p (const char *au)
2470 return BEGINS_WITH (au, "Basic")
2471 || BEGINS_WITH (au, "Digest")
2472 || BEGINS_WITH (au, "NTLM");
2477 /* Create the HTTP authorization request header. When the
2478 `WWW-Authenticate' response header is seen, according to the
2479 authorization scheme specified in that header (`Basic' and `Digest'
2480 are supported by the current implementation), produce an
2481 appropriate HTTP authorization request header. */
2483 create_authorization_line (const char *au, const char *user,
2484 const char *passwd, const char *method,
2487 char *wwwauth = NULL;
2489 if (!strncasecmp (au, "Basic", 5))
2490 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2491 if (!strncasecmp (au, "NTLM", 4))
2492 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2494 else if (!strncasecmp (au, "Digest", 6))
2495 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2496 #endif /* USE_DIGEST */
2503 if (pc_last_host_ip)
2504 address_list_release (pc_last_host_ip);