2 Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables. You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL". If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so. If you do not wish to do
29 so, delete this exception statement from your version. */
35 #include <sys/types.h>
46 #if TIME_WITH_SYS_TIME
47 # include <sys/time.h>
51 # include <sys/time.h>
67 # include "gen_sslfunc.h"
75 extern char *version_string;
81 static int cookies_loaded_p;
82 struct cookie_jar *wget_cookie_jar;
84 #define TEXTHTML_S "text/html"
85 #define TEXTXHTML_S "application/xhtml+xml"
86 #define HTTP_ACCEPT "*/*"
88 /* Some status code validation macros: */
89 #define H_20X(x) (((x) >= 200) && ((x) < 300))
90 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
91 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
92 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
94 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
96 #define HTTP_STATUS_OK 200
97 #define HTTP_STATUS_CREATED 201
98 #define HTTP_STATUS_ACCEPTED 202
99 #define HTTP_STATUS_NO_CONTENT 204
100 #define HTTP_STATUS_PARTIAL_CONTENTS 206
102 /* Redirection 3xx. */
103 #define HTTP_STATUS_MULTIPLE_CHOICES 300
104 #define HTTP_STATUS_MOVED_PERMANENTLY 301
105 #define HTTP_STATUS_MOVED_TEMPORARILY 302
106 #define HTTP_STATUS_NOT_MODIFIED 304
108 /* Client error 4xx. */
109 #define HTTP_STATUS_BAD_REQUEST 400
110 #define HTTP_STATUS_UNAUTHORIZED 401
111 #define HTTP_STATUS_FORBIDDEN 403
112 #define HTTP_STATUS_NOT_FOUND 404
114 /* Server errors 5xx. */
115 #define HTTP_STATUS_INTERNAL 500
116 #define HTTP_STATUS_NOT_IMPLEMENTED 501
117 #define HTTP_STATUS_BAD_GATEWAY 502
118 #define HTTP_STATUS_UNAVAILABLE 503
121 /* Parse the HTTP status line, which is of format:
123 HTTP-Version SP Status-Code SP Reason-Phrase
125 The function returns the status-code, or -1 if the status line is
126 malformed. The pointer to reason-phrase is returned in RP. */
128 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
130 /* (the variables must not be named `major' and `minor', because
131 that breaks compilation with SunOS4 cc.) */
132 int mjr, mnr, statcode;
135 *reason_phrase_ptr = NULL;
137 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
138 major version, and Y is minor version. */
139 if (strncmp (line, "HTTP/", 5) != 0)
143 /* Calculate major HTTP version. */
145 for (mjr = 0; ISDIGIT (*line); line++)
146 mjr = 10 * mjr + (*line - '0');
147 if (*line != '.' || p == line)
151 /* Calculate minor HTTP version. */
153 for (mnr = 0; ISDIGIT (*line); line++)
154 mnr = 10 * mnr + (*line - '0');
155 if (*line != ' ' || p == line)
157 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
158 minor version can be safely ignored. */
163 /* Calculate status code. */
164 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
166 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
168 /* Set up the reason phrase pointer. */
170 /* RFC2068 requires SPC here, but we allow the string to finish
171 here, in case no reason-phrase is present. */
175 *reason_phrase_ptr = line;
180 *reason_phrase_ptr = line + 1;
185 #define WMIN(x, y) ((x) > (y) ? (y) : (x))
187 /* Send the contents of FILE_NAME to SOCK/SSL. Make sure that exactly
188 PROMISED_SIZE bytes are sent over the wire -- if the file is
189 longer, read only that much; if the file is shorter, report an error. */
192 post_file (int sock, void *ssl, const char *file_name, long promised_size)
194 static char chunk[8192];
199 /* Only one of SOCK and SSL may be active at the same time. */
200 assert (sock > -1 || ssl != NULL);
201 assert (sock == -1 || ssl == NULL);
203 DEBUGP (("[writing POST file %s ... ", file_name));
205 fp = fopen (file_name, "rb");
208 while (!feof (fp) && written < promised_size)
211 int length = fread (chunk, 1, sizeof (chunk), fp);
214 towrite = WMIN (promised_size - written, length);
217 write_error = ssl_iwrite (ssl, chunk, towrite);
220 write_error = iwrite (sock, chunk, towrite);
230 /* If we've written less than was promised, report a (probably
231 nonsensical) error rather than break the promise. */
232 if (written < promised_size)
238 assert (written == promised_size);
239 DEBUGP (("done]\n"));
243 /* Functions to be used as arguments to header_process(): */
245 struct http_process_range_closure {
251 /* Parse the `Content-Range' header and extract the information it
252 contains. Returns 1 if successful, -1 otherwise. */
254 http_process_range (const char *hdr, void *arg)
256 struct http_process_range_closure *closure
257 = (struct http_process_range_closure *)arg;
260 /* Certain versions of Nutscape proxy server send out
261 `Content-Length' without "bytes" specifier, which is a breach of
262 RFC2068 (as well as the HTTP/1.1 draft which was current at the
263 time). But hell, I must support it... */
264 if (!strncasecmp (hdr, "bytes", 5))
267 /* "JavaWebServer/1.1.1" sends "bytes: x-y/z", contrary to the
271 hdr += skip_lws (hdr);
277 for (num = 0; ISDIGIT (*hdr); hdr++)
278 num = 10 * num + (*hdr - '0');
279 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
281 closure->first_byte_pos = num;
283 for (num = 0; ISDIGIT (*hdr); hdr++)
284 num = 10 * num + (*hdr - '0');
285 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
287 closure->last_byte_pos = num;
289 for (num = 0; ISDIGIT (*hdr); hdr++)
290 num = 10 * num + (*hdr - '0');
291 closure->entity_length = num;
295 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
296 Used for `Accept-Ranges'. */
298 http_process_none (const char *hdr, void *arg)
300 int *where = (int *)arg;
302 if (strstr (hdr, "none"))
309 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
311 http_process_type (const char *hdr, void *arg)
313 char **result = (char **)arg;
314 /* Locate P on `;' or the terminating zero, whichever comes first. */
315 const char *p = strchr (hdr, ';');
317 p = hdr + strlen (hdr);
318 while (p > hdr && ISSPACE (*(p - 1)))
320 *result = strdupdelim (hdr, p);
324 /* Check whether the `Connection' header is set to "keep-alive". */
326 http_process_connection (const char *hdr, void *arg)
328 int *flag = (int *)arg;
329 if (!strcasecmp (hdr, "Keep-Alive"))
334 /* Commit the cookie to the cookie jar. */
337 http_process_set_cookie (const char *hdr, void *arg)
339 struct url *u = (struct url *)arg;
341 /* The jar should have been created by now. */
342 assert (wget_cookie_jar != NULL);
344 cookie_jar_process_set_cookie (wget_cookie_jar, u->host, u->port, u->path,
350 /* Persistent connections. Currently, we cache the most recently used
351 connection as persistent, provided that the HTTP server agrees to
352 make it such. The persistence data is stored in the variables
353 below. Ideally, it would be in a structure, and it should be
354 possible to cache an arbitrary fixed number of these connections.
356 I think the code is quite easy to extend in that direction. */
358 /* Whether a persistent connection is active. */
359 static int pc_active_p;
360 /* Host and port of currently active persistent connection. */
361 static struct address_list *pc_last_host_ip;
362 static unsigned short pc_last_port;
364 /* File descriptor of the currently active persistent connection. */
365 static int pc_last_fd;
368 /* Whether a ssl handshake has occoured on this connection */
369 static int pc_active_ssl;
370 /* SSL connection of the currently active persistent connection. */
371 static SSL *pc_last_ssl;
372 #endif /* HAVE_SSL */
374 /* Mark the persistent connection as invalid. This is used by the
375 CLOSE_* macros after they forcefully close a registered persistent
376 connection. This does not close the file descriptor -- it is left
377 to the caller to do that. (Maybe it should, though.) */
380 invalidate_persistent (void)
385 #endif /* HAVE_SSL */
386 if (pc_last_host_ip != NULL)
388 address_list_release (pc_last_host_ip);
389 pc_last_host_ip = NULL;
391 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
394 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
395 persistent. This will enable someone to use the same connection
396 later. In the context of HTTP, this must be called only AFTER the
397 response has been received and the server has promised that the
398 connection will remain alive.
400 If a previous connection was persistent, it is closed. */
404 register_persistent (const char *host, unsigned short port, int fd, SSL *ssl)
408 register_persistent (const char *host, unsigned short port, int fd)
413 if (pc_last_fd == fd)
415 /* The connection FD is already registered. Nothing to
421 /* The old persistent connection is still active; let's
422 close it first. This situation arises whenever a
423 persistent connection exists, but we then connect to a
424 different host, and try to register a persistent
425 connection to that one. */
427 /* The ssl disconnect has to take place before the closing
430 shutdown_ssl(pc_last_ssl);
433 invalidate_persistent ();
437 assert (pc_last_host_ip == NULL);
439 /* This lookup_host cannot fail, because it has the results in the
441 pc_last_host_ip = lookup_host (host, 1);
442 assert (pc_last_host_ip != NULL);
449 pc_active_ssl = ssl ? 1 : 0;
451 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
455 # define SHUTDOWN_SSL(ssl) do { \
457 shutdown_ssl (ssl); \
460 # define SHUTDOWN_SSL(ssl)
463 /* Return non-zero if a persistent connection is available for
464 connecting to HOST:PORT. */
468 persistent_available_p (const char *host, unsigned short port, int ssl)
472 persistent_available_p (const char *host, unsigned short port)
476 struct address_list *this_host_ip;
478 /* First, check whether a persistent connection is active at all. */
481 /* Second, check if the active connection pertains to the correct
482 (HOST, PORT) ordered pair. */
483 if (port != pc_last_port)
487 /* Second, a): check if current connection is (not) ssl, too. This
488 test is unlikely to fail because HTTP and HTTPS typicaly use
489 different ports. Yet it is possible, or so I [Christian
490 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
492 if (ssl != pc_active_ssl)
494 #endif /* HAVE_SSL */
496 this_host_ip = lookup_host (host, 1);
500 /* To equate the two host names for the purposes of persistent
501 connections, they need to share all the IP addresses in the
503 success = address_list_match_all (pc_last_host_ip, this_host_ip);
504 address_list_release (this_host_ip);
508 /* Third: check whether the connection is still open. This is
509 important because most server implement a liberal (short) timeout
510 on persistent connections. Wget can of course always reconnect
511 if the connection doesn't work out, but it's nicer to know in
512 advance. This test is a logical followup of the first test, but
513 is "expensive" and therefore placed at the end of the list. */
514 if (!test_socket_open (pc_last_fd))
516 /* Oops, the socket is no longer open. Now that we know that,
517 let's invalidate the persistent connection before returning
521 SHUTDOWN_SSL (pc_last_ssl);
524 invalidate_persistent ();
530 /* The idea behind these two CLOSE macros is to distinguish between
531 two cases: one when the job we've been doing is finished, and we
532 want to close the connection and leave, and two when something is
533 seriously wrong and we're closing the connection as part of
536 In case of keep_alive, CLOSE_FINISH should leave the connection
537 open, while CLOSE_INVALIDATE should still close it.
539 Note that the semantics of the flag `keep_alive' is "this
540 connection *will* be reused (the server has promised not to close
541 the connection once we're done)", while the semantics of
542 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
543 active, registered connection". */
545 #define CLOSE_FINISH(fd) do { \
548 SHUTDOWN_SSL (ssl); \
550 if (pc_active_p && (fd) == pc_last_fd) \
551 invalidate_persistent (); \
555 #define CLOSE_INVALIDATE(fd) do { \
556 SHUTDOWN_SSL (ssl); \
558 if (pc_active_p && (fd) == pc_last_fd) \
559 invalidate_persistent (); \
564 long len; /* received length */
565 long contlen; /* expected length */
566 long restval; /* the restart value */
567 int res; /* the result of last read */
568 char *newloc; /* new location (redirection) */
569 char *remote_time; /* remote time-stamp string */
570 char *error; /* textual HTTP error */
571 int statcode; /* status code */
572 double dltime; /* time of the download in msecs */
573 int no_truncate; /* whether truncating the file is
575 const char *referer; /* value of the referer header. */
576 char **local_file; /* local file. */
580 free_hstat (struct http_stat *hs)
582 FREE_MAYBE (hs->newloc);
583 FREE_MAYBE (hs->remote_time);
584 FREE_MAYBE (hs->error);
586 /* Guard against being called twice. */
588 hs->remote_time = NULL;
592 static char *create_authorization_line PARAMS ((const char *, const char *,
593 const char *, const char *,
595 static char *basic_authentication_encode PARAMS ((const char *, const char *,
597 static int known_authentication_scheme_p PARAMS ((const char *));
599 time_t http_atotm PARAMS ((const char *));
601 #define BEGINS_WITH(line, string_constant) \
602 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
603 && (ISSPACE (line[sizeof (string_constant) - 1]) \
604 || !line[sizeof (string_constant) - 1]))
606 /* Retrieve a document through HTTP protocol. It recognizes status
607 code, and correctly handles redirections. It closes the network
608 socket. If it receives an error from the functions below it, it
609 will print it if there is enough information to do so (almost
610 always), returning the error to the caller (i.e. http_loop).
612 Various HTTP parameters are stored to hs. Although it parses the
613 response code correctly, it is not used in a sane way. The caller
616 If PROXY is non-NULL, the connection will be made to the proxy
617 server, and u->url will be requested. */
619 gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy)
621 char *request, *type, *command, *full_path;
623 char *pragma_h, *referer, *useragent, *range, *wwwauth;
624 char *authenticate_h;
628 char *request_keep_alive;
629 int sock, hcount, all_length, statcode;
631 long contlen, contrange;
634 int auth_tried_already;
637 static SSL_CTX *ssl_ctx = NULL;
640 char *cookies = NULL;
642 /* Whether this connection will be kept alive after the HTTP request
646 /* Flags that detect the two ways of specifying HTTP keep-alive
648 int http_keep_alive_1, http_keep_alive_2;
650 /* Whether keep-alive should be inhibited. */
651 int inhibit_keep_alive;
653 /* Whether we need to print the host header with braces around host,
654 e.g. "Host: [3ffe:8100:200:2::2]:1234" instead of the usual
655 "Host: symbolic-name:1234". */
656 int squares_around_host = 0;
658 /* Headers sent when using POST. */
659 char *post_content_type, *post_content_length;
660 long post_data_size = 0;
663 /* initialize ssl_ctx on first run */
666 uerr_t err = init_ssl (&ssl_ctx);
671 case SSLERRCTXCREATE:
673 logprintf (LOG_NOTQUIET, _("Failed to set up an SSL context\n"));
677 /* try without certfile */
678 logprintf (LOG_NOTQUIET,
679 _("Failed to load certificates from %s\n"),
682 logprintf (LOG_NOTQUIET,
683 _("Trying without the specified certificate\n"));
686 logprintf (LOG_NOTQUIET,
687 _("Failed to get certificate key from %s\n"),
690 logprintf (LOG_NOTQUIET,
691 _("Trying without the specified certificate\n"));
698 #endif /* HAVE_SSL */
700 if (!(*dt & HEAD_ONLY))
701 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
702 know the local filename so we can save to it. */
703 assert (*hs->local_file != NULL);
706 auth_tried_already = 0;
708 inhibit_keep_alive = !opt.http_keep_alive || proxy != NULL;
711 /* We need to come back here when the initial attempt to retrieve
712 without authorization header fails. (Expected to happen at least
713 for the Digest authorization scheme.) */
716 http_keep_alive_1 = http_keep_alive_2 = 0;
718 post_content_type = NULL;
719 post_content_length = NULL;
721 /* Initialize certain elements of struct http_stat. */
726 hs->remote_time = NULL;
729 /* If we're using a proxy, we will be connecting to the proxy
731 conn = proxy ? proxy : u;
733 /* First: establish the connection. */
734 if (inhibit_keep_alive
737 !persistent_available_p (conn->host, conn->port)
739 !persistent_available_p (conn->host, conn->port,
740 u->scheme == SCHEME_HTTPS)
741 #endif /* HAVE_SSL */
744 struct address_list *al = lookup_host (conn->host, 0);
747 set_connection_host_name (conn->host);
748 sock = connect_to_many (al, conn->port, 0);
749 set_connection_host_name (NULL);
750 address_list_release (al);
753 return CONNECT_ERROR (errno);
756 if (conn->scheme == SCHEME_HTTPS)
757 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
759 logputs (LOG_VERBOSE, "\n");
760 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
765 #endif /* HAVE_SSL */
769 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"),
770 conn->host, conn->port);
771 /* #### pc_last_fd should be accessed through an accessor
776 #endif /* HAVE_SSL */
777 DEBUGP (("Reusing fd %d.\n", sock));
782 else if (opt.post_file_name || opt.post_data)
790 referer = (char *)alloca (9 + strlen (hs->referer) + 3);
791 sprintf (referer, "Referer: %s\r\n", hs->referer);
794 if (*dt & SEND_NOCACHE)
795 pragma_h = "Pragma: no-cache\r\n";
801 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
802 /* Gag me! Some servers (e.g. WebSitePro) have been known to
803 respond to the following `Range' format by generating a
804 multipart/x-byte-ranges MIME document! This MIME type was
805 present in an old draft of the byteranges specification.
806 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
807 only if multiple non-overlapping ranges are requested --
808 which Wget never does. */
809 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
814 STRDUP_ALLOCA (useragent, opt.useragent);
817 useragent = (char *)alloca (10 + strlen (version_string));
818 sprintf (useragent, "Wget/%s", version_string);
820 /* Construct the authentication, if userid is present. */
823 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
824 user = user ? user : opt.http_user;
825 passwd = passwd ? passwd : opt.http_passwd;
832 /* We have the username and the password, but haven't tried
833 any authorization yet. Let's see if the "Basic" method
834 works. If not, we'll come back here and construct a
835 proper authorization method with the right challenges.
837 If we didn't employ this kind of logic, every URL that
838 requires authorization would have to be processed twice,
839 which is very suboptimal and generates a bunch of false
840 "unauthorized" errors in the server log.
842 #### But this logic also has a serious problem when used
843 with stronger authentications: we *first* transmit the
844 username and the password in clear text, and *then*
845 attempt a stronger authentication scheme. That cannot be
846 right! We are only fortunate that almost everyone still
847 uses the `Basic' scheme anyway.
849 There should be an option to prevent this from happening,
850 for those who use strong authentication schemes and value
852 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
856 /* Use the full path, i.e. one that includes the leading
857 slash and the query string, but is independent of proxy
859 char *pth = url_full_path (u);
860 wwwauth = create_authorization_line (authenticate_h, user, passwd,
869 char *proxy_user, *proxy_passwd;
870 /* For normal username and password, URL components override
871 command-line/wgetrc parameters. With proxy authentication,
872 it's the reverse, because proxy URLs are normally the
873 "permanent" ones, so command-line args should take
875 if (opt.proxy_user && opt.proxy_passwd)
877 proxy_user = opt.proxy_user;
878 proxy_passwd = opt.proxy_passwd;
882 proxy_user = proxy->user;
883 proxy_passwd = proxy->passwd;
885 /* #### This does not appear right. Can't the proxy request,
886 say, `Digest' authentication? */
887 if (proxy_user && proxy_passwd)
888 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
889 "Proxy-Authorization");
892 /* String of the form :PORT. Used only for non-standard ports. */
894 if (u->port != scheme_default_port (u->scheme))
896 port_maybe = (char *)alloca (numdigit (u->port) + 2);
897 sprintf (port_maybe, ":%d", u->port);
900 if (!inhibit_keep_alive)
901 request_keep_alive = "Connection: Keep-Alive\r\n";
903 request_keep_alive = NULL;
906 cookies = cookie_jar_generate_cookie_header (wget_cookie_jar, u->host,
909 u->scheme == SCHEME_HTTPS
915 if (opt.post_data || opt.post_file_name)
917 post_content_type = "Content-Type: application/x-www-form-urlencoded\r\n";
919 post_data_size = strlen (opt.post_data);
922 post_data_size = file_size (opt.post_file_name);
923 if (post_data_size == -1)
925 logprintf (LOG_NOTQUIET, "POST data file missing: %s\n",
930 post_content_length = xmalloc (16 + numdigit (post_data_size) + 2 + 1);
931 sprintf (post_content_length,
932 "Content-Length: %ld\r\n", post_data_size);
936 full_path = xstrdup (u->url);
938 /* Use the full path, i.e. one that includes the leading slash and
939 the query string. E.g. if u->path is "foo/bar" and u->query is
940 "param=value", full_path will be "/foo/bar?param=value". */
941 full_path = url_full_path (u);
943 if (strchr (u->host, ':'))
944 squares_around_host = 1;
946 /* Allocate the memory for the request. */
947 request = (char *)alloca (strlen (command)
951 + (port_maybe ? strlen (port_maybe) : 0)
952 + strlen (HTTP_ACCEPT)
953 + (request_keep_alive
954 ? strlen (request_keep_alive) : 0)
955 + (referer ? strlen (referer) : 0)
956 + (cookies ? strlen (cookies) : 0)
957 + (wwwauth ? strlen (wwwauth) : 0)
958 + (proxyauth ? strlen (proxyauth) : 0)
959 + (range ? strlen (range) : 0)
962 ? strlen (post_content_type) : 0)
963 + (post_content_length
964 ? strlen (post_content_length) : 0)
965 + (opt.user_header ? strlen (opt.user_header) : 0)
967 /* Construct the request. */
973 %s%s%s%s%s%s%s%s%s%s\r\n",
976 squares_around_host ? "[" : "", u->host, squares_around_host ? "]" : "",
977 port_maybe ? port_maybe : "",
979 request_keep_alive ? request_keep_alive : "",
980 referer ? referer : "",
981 cookies ? cookies : "",
982 wwwauth ? wwwauth : "",
983 proxyauth ? proxyauth : "",
986 post_content_type ? post_content_type : "",
987 post_content_length ? post_content_length : "",
988 opt.user_header ? opt.user_header : "");
989 DEBUGP (("---request begin---\n%s", request));
991 /* Free the temporary memory. */
992 FREE_MAYBE (wwwauth);
993 FREE_MAYBE (proxyauth);
994 FREE_MAYBE (cookies);
997 /* Send the request to server. */
999 if (conn->scheme == SCHEME_HTTPS)
1000 write_error = ssl_iwrite (ssl, request, strlen (request));
1003 write_error = iwrite (sock, request, strlen (request));
1005 if (write_error >= 0)
1009 DEBUGP (("[POST data: %s]\n", opt.post_data));
1011 if (conn->scheme == SCHEME_HTTPS)
1012 write_error = ssl_iwrite (ssl, opt.post_data, post_data_size);
1015 write_error = iwrite (sock, opt.post_data, post_data_size);
1017 else if (opt.post_file_name && post_data_size != 0)
1020 if (conn->scheme == SCHEME_HTTPS)
1021 write_error = post_file (-1, ssl, opt.post_file_name,
1025 write_error = post_file (sock, NULL, opt.post_file_name,
1029 DEBUGP (("---request end---\n"));
1031 if (write_error < 0)
1033 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
1035 CLOSE_INVALIDATE (sock);
1038 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
1039 proxy ? "Proxy" : "HTTP");
1040 contlen = contrange = -1;
1045 /* Before reading anything, initialize the rbuf. */
1046 rbuf_initialize (&rbuf, sock);
1048 if (conn->scheme == SCHEME_HTTPS)
1052 #endif /* HAVE_SSL */
1055 /* Header-fetching loop. */
1063 /* Get the header. */
1064 status = header_get (&rbuf, &hdr,
1065 /* Disallow continuations for status line. */
1066 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
1068 /* Check for errors. */
1069 if (status == HG_EOF && *hdr)
1071 /* This used to be an unconditional error, but that was
1072 somewhat controversial, because of a large number of
1073 broken CGI's that happily "forget" to send the second EOL
1074 before closing the connection of a HEAD request.
1076 So, the deal is to check whether the header is empty
1077 (*hdr is zero if it is); if yes, it means that the
1078 previous header was fully retrieved, and that -- most
1079 probably -- the request is complete. "...be liberal in
1080 what you accept." Oh boy. */
1081 logputs (LOG_VERBOSE, "\n");
1082 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
1085 FREE_MAYBE (all_headers);
1086 CLOSE_INVALIDATE (sock);
1089 else if (status == HG_ERROR)
1091 logputs (LOG_VERBOSE, "\n");
1092 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
1096 FREE_MAYBE (all_headers);
1097 CLOSE_INVALIDATE (sock);
1101 /* If the headers are to be saved to a file later, save them to
1103 if (opt.save_headers)
1105 int lh = strlen (hdr);
1106 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
1107 memcpy (all_headers + all_length, hdr, lh);
1109 all_headers[all_length++] = '\n';
1110 all_headers[all_length] = '\0';
1113 /* Check for status line. */
1117 /* Parse the first line of server response. */
1118 statcode = parse_http_status_line (hdr, &error);
1119 hs->statcode = statcode;
1120 /* Store the descriptive response. */
1121 if (statcode == -1) /* malformed response */
1123 /* A common reason for "malformed response" error is the
1124 case when no data was actually received. Handle this
1127 hs->error = xstrdup (_("No data received"));
1129 hs->error = xstrdup (_("Malformed status line"));
1134 hs->error = xstrdup (_("(no description)"));
1136 hs->error = xstrdup (error);
1138 if ((statcode != -1)
1144 if (opt.server_response)
1145 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1147 logprintf (LOG_VERBOSE, "%2d %s", statcode, error);
1153 /* Exit on empty header. */
1160 /* Print the header if requested. */
1161 if (opt.server_response && hcount != 1)
1162 logprintf (LOG_VERBOSE, "\n%2d %s", hcount, hdr);
1164 /* Try getting content-length. */
1165 if (contlen == -1 && !opt.ignore_length)
1166 if (header_process (hdr, "Content-Length", header_extract_number,
1169 /* Try getting content-type. */
1171 if (header_process (hdr, "Content-Type", http_process_type, &type))
1173 /* Try getting location. */
1175 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
1177 /* Try getting last-modified. */
1178 if (!hs->remote_time)
1179 if (header_process (hdr, "Last-Modified", header_strdup,
1182 /* Try getting cookies. */
1184 if (header_process (hdr, "Set-Cookie", http_process_set_cookie, u))
1186 /* Try getting www-authentication. */
1187 if (!authenticate_h)
1188 if (header_process (hdr, "WWW-Authenticate", header_strdup,
1191 /* Check for accept-ranges header. If it contains the word
1192 `none', disable the ranges. */
1193 if (*dt & ACCEPTRANGES)
1196 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
1199 *dt &= ~ACCEPTRANGES;
1203 /* Try getting content-range. */
1204 if (contrange == -1)
1206 struct http_process_range_closure closure;
1207 if (header_process (hdr, "Content-Range", http_process_range, &closure))
1209 contrange = closure.first_byte_pos;
1213 /* Check for keep-alive related responses. */
1214 if (!inhibit_keep_alive)
1216 /* Check for the `Keep-Alive' header. */
1217 if (!http_keep_alive_1)
1219 if (header_process (hdr, "Keep-Alive", header_exists,
1220 &http_keep_alive_1))
1223 /* Check for `Connection: Keep-Alive'. */
1224 if (!http_keep_alive_2)
1226 if (header_process (hdr, "Connection", http_process_connection,
1227 &http_keep_alive_2))
1235 logputs (LOG_VERBOSE, "\n");
1238 && (http_keep_alive_1 || http_keep_alive_2))
1240 assert (inhibit_keep_alive == 0);
1244 /* The server has promised that it will not close the connection
1245 when we're done. This means that we can register it. */
1247 register_persistent (conn->host, conn->port, sock);
1249 register_persistent (conn->host, conn->port, sock, ssl);
1250 #endif /* HAVE_SSL */
1252 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1255 /* Authorization is required. */
1259 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1260 might be more bytes in the body. */
1261 if (auth_tried_already)
1263 /* If we have tried it already, then there is not point
1266 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1267 xfree (authenticate_h);
1270 else if (!known_authentication_scheme_p (authenticate_h))
1272 xfree (authenticate_h);
1273 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1276 else if (BEGINS_WITH (authenticate_h, "Basic"))
1278 /* The authentication scheme is basic, the one we try by
1279 default, and it failed. There's no sense in trying
1285 auth_tried_already = 1;
1289 /* We do not need this anymore. */
1292 xfree (authenticate_h);
1293 authenticate_h = NULL;
1296 /* 20x responses are counted among successful by default. */
1297 if (H_20X (statcode))
1300 /* Return if redirected. */
1301 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1303 /* RFC2068 says that in case of the 300 (multiple choices)
1304 response, the server can output a preferred URL through
1305 `Location' header; otherwise, the request should be treated
1306 like GET. So, if the location is set, it will be a
1307 redirection; otherwise, just proceed normally. */
1308 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1312 logprintf (LOG_VERBOSE,
1313 _("Location: %s%s\n"),
1314 hs->newloc ? hs->newloc : _("unspecified"),
1315 hs->newloc ? _(" [following]") : "");
1316 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1317 might be more bytes in the body. */
1319 FREE_MAYBE (all_headers);
1324 /* If content-type is not given, assume text/html. This is because
1325 of the multitude of broken CGI's that "forget" to generate the
1328 0 == strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)) ||
1329 0 == strncasecmp (type, TEXTXHTML_S, strlen (TEXTXHTML_S)))
1334 if (opt.html_extension && (*dt & TEXTHTML))
1335 /* -E / --html-extension / html_extension = on was specified, and this is a
1336 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1337 already the file's suffix, tack on ".html". */
1339 char* last_period_in_local_filename = strrchr(*hs->local_file, '.');
1341 if (last_period_in_local_filename == NULL ||
1342 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1343 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1345 size_t local_filename_len = strlen(*hs->local_file);
1347 *hs->local_file = xrealloc(*hs->local_file,
1348 local_filename_len + sizeof(".html"));
1349 strcpy(*hs->local_file + local_filename_len, ".html");
1351 *dt |= ADDED_HTML_EXTENSION;
1355 if (contrange == -1)
1357 /* We did not get a content-range header. This means that the
1358 server did not honor our `Range' request. Normally, this
1359 means we should reset hs->restval and continue normally. */
1361 /* However, if `-c' is used, we need to be a bit more careful:
1363 1. If `-c' is specified and the file already existed when
1364 Wget was started, it would be a bad idea for us to start
1365 downloading it from scratch, effectively truncating it. I
1366 believe this cannot happen unless `-c' was specified.
1368 2. If `-c' is used on a file that is already fully
1369 downloaded, we're requesting bytes after the end of file,
1370 which can result in server not honoring `Range'. If this is
1371 the case, `Content-Length' will be equal to the length of the
1373 if (opt.always_rest)
1375 /* Check for condition #2. */
1376 if (hs->restval > 0 /* restart was requested. */
1377 && contlen != -1 /* we got content-length. */
1378 && hs->restval >= contlen /* file fully downloaded
1382 logputs (LOG_VERBOSE, _("\
1383 \n The file is already fully retrieved; nothing to do.\n\n"));
1384 /* In case the caller inspects. */
1387 /* Mark as successfully retrieved. */
1390 FREE_MAYBE (all_headers);
1391 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1392 might be more bytes in the body. */
1393 return RETRUNNEEDED;
1396 /* Check for condition #1. */
1397 if (hs->no_truncate)
1399 logprintf (LOG_NOTQUIET,
1402 Continued download failed on this file, which conflicts with `-c'.\n\
1403 Refusing to truncate existing file `%s'.\n\n"), *hs->local_file);
1405 FREE_MAYBE (all_headers);
1406 CLOSE_INVALIDATE (sock);
1407 return CONTNOTSUPPORTED;
1415 else if (contrange != hs->restval ||
1416 (H_PARTIAL (statcode) && contrange == -1))
1418 /* This means the whole request was somehow misunderstood by the
1419 server. Bail out. */
1421 FREE_MAYBE (all_headers);
1422 CLOSE_INVALIDATE (sock);
1429 contlen += contrange;
1431 contrange = -1; /* If conent-length was not sent,
1432 content-range will be ignored. */
1434 hs->contlen = contlen;
1438 if ((*dt & RETROKF) && !opt.server_response)
1440 /* No need to print this output if the body won't be
1441 downloaded at all, or if the original server response is
1443 logputs (LOG_VERBOSE, _("Length: "));
1446 logputs (LOG_VERBOSE, legible (contlen));
1447 if (contrange != -1)
1448 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1449 legible (contlen - contrange));
1452 logputs (LOG_VERBOSE,
1453 opt.ignore_length ? _("ignored") : _("unspecified"));
1455 logprintf (LOG_VERBOSE, " [%s]\n", type);
1457 logputs (LOG_VERBOSE, "\n");
1461 type = NULL; /* We don't need it any more. */
1463 /* Return if we have no intention of further downloading. */
1464 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1466 /* In case the caller cares to look... */
1470 FREE_MAYBE (all_headers);
1471 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1472 might be more bytes in the body. */
1473 return RETRFINISHED;
1476 /* Open the local file. */
1479 mkalldirs (*hs->local_file);
1481 rotate_backups (*hs->local_file);
1482 fp = fopen (*hs->local_file, hs->restval ? "ab" : "wb");
1485 logprintf (LOG_NOTQUIET, "%s: %s\n", *hs->local_file, strerror (errno));
1486 CLOSE_INVALIDATE (sock); /* would be CLOSE_FINISH, but there
1487 might be more bytes in the body. */
1488 FREE_MAYBE (all_headers);
1494 extern int global_download_count;
1496 /* To ensure that repeated "from scratch" downloads work for -O
1497 files, we rewind the file pointer, unless restval is
1498 non-zero. (This works only when -O is used on regular files,
1499 but it's still a valuable feature.)
1501 However, this loses when more than one URL is specified on
1502 the command line the second rewinds eradicates the contents
1503 of the first download. Thus we disable the above trick for
1504 all the downloads except the very first one.
1506 #### A possible solution to this would be to remember the
1507 file position in the output document and to seek to that
1508 position, instead of rewinding.
1510 We don't truncate stdout, since that breaks
1511 "wget -O - [...] >> foo".
1513 if (!hs->restval && global_download_count == 0 && opt.dfp != stdout)
1515 /* This will silently fail for streams that don't correspond
1516 to regular files, but that's OK. */
1518 /* ftruncate is needed because opt.dfp is opened in append
1519 mode if opt.always_rest is set. */
1520 ftruncate (fileno (fp), 0);
1525 /* #### This confuses the code that checks for file size. There
1526 should be some overhead information. */
1527 if (opt.save_headers)
1528 fwrite (all_headers, 1, all_length, fp);
1530 /* Get the contents of the document. */
1531 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1532 (contlen != -1 ? contlen : 0),
1533 &rbuf, keep_alive, &hs->dltime);
1536 CLOSE_FINISH (sock);
1538 CLOSE_INVALIDATE (sock);
1541 /* Close or flush the file. We have to be careful to check for
1542 error here. Checking the result of fwrite() is not enough --
1543 errors could go unnoticed! */
1546 flush_res = fclose (fp);
1548 flush_res = fflush (fp);
1549 if (flush_res == EOF)
1552 FREE_MAYBE (all_headers);
1555 return RETRFINISHED;
1558 /* The genuine HTTP loop! This is the part where the retrieval is
1559 retried, and retried, and retried, and... */
1561 http_loop (struct url *u, char **newloc, char **local_file, const char *referer,
1562 int *dt, struct url *proxy)
1565 int use_ts, got_head = 0; /* time-stamping info */
1566 char *filename_plus_orig_suffix;
1567 char *local_filename = NULL;
1568 char *tms, *locf, *tmrate;
1570 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1571 long local_size = 0; /* the size of the local file */
1572 size_t filename_len;
1573 struct http_stat hstat; /* HTTP status */
1577 /* This used to be done in main(), but it's a better idea to do it
1578 here so that we don't go through the hoops if we're just using
1582 if (!wget_cookie_jar)
1583 wget_cookie_jar = cookie_jar_new ();
1584 if (opt.cookies_input && !cookies_loaded_p)
1586 cookie_jar_load (wget_cookie_jar, opt.cookies_input);
1587 cookies_loaded_p = 1;
1593 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1594 has_wildcards_p because it would also warn on `?', and we know that
1595 shows up in CGI paths a *lot*. */
1596 if (strchr (u->url, '*'))
1597 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1599 /* Determine the local filename. */
1600 if (local_file && *local_file)
1601 hstat.local_file = local_file;
1602 else if (local_file)
1604 *local_file = url_file_name (u);
1605 hstat.local_file = local_file;
1609 dummy = url_file_name (u);
1610 hstat.local_file = &dummy;
1613 if (!opt.output_document)
1614 locf = *hstat.local_file;
1616 locf = opt.output_document;
1618 hstat.referer = referer;
1620 filename_len = strlen (*hstat.local_file);
1621 filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
1623 if (opt.noclobber && file_exists_p (*hstat.local_file))
1625 /* If opt.noclobber is turned on and file already exists, do not
1626 retrieve the file */
1627 logprintf (LOG_VERBOSE, _("\
1628 File `%s' already there, will not retrieve.\n"), *hstat.local_file);
1629 /* If the file is there, we suppose it's retrieved OK. */
1632 /* #### Bogusness alert. */
1633 /* If its suffix is "html" or "htm" or similar, assume text/html. */
1634 if (has_html_suffix_p (*hstat.local_file))
1642 if (opt.timestamping)
1644 boolean local_dot_orig_file_exists = FALSE;
1646 if (opt.backup_converted)
1647 /* If -K is specified, we'll act on the assumption that it was specified
1648 last time these files were downloaded as well, and instead of just
1649 comparing local file X against server file X, we'll compare local
1650 file X.orig (if extant, else X) against server file X. If -K
1651 _wasn't_ specified last time, or the server contains files called
1652 *.orig, -N will be back to not operating correctly with -k. */
1654 /* Would a single s[n]printf() call be faster? --dan
1656 Definitely not. sprintf() is horribly slow. It's a
1657 different question whether the difference between the two
1658 affects a program. Usually I'd say "no", but at one
1659 point I profiled Wget, and found that a measurable and
1660 non-negligible amount of time was lost calling sprintf()
1661 in url.c. Replacing sprintf with inline calls to
1662 strcpy() and long_to_string() made a difference.
1664 memcpy (filename_plus_orig_suffix, *hstat.local_file, filename_len);
1665 memcpy (filename_plus_orig_suffix + filename_len,
1666 ".orig", sizeof (".orig"));
1668 /* Try to stat() the .orig file. */
1669 if (stat (filename_plus_orig_suffix, &st) == 0)
1671 local_dot_orig_file_exists = TRUE;
1672 local_filename = filename_plus_orig_suffix;
1676 if (!local_dot_orig_file_exists)
1677 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1678 if (stat (*hstat.local_file, &st) == 0)
1679 local_filename = *hstat.local_file;
1681 if (local_filename != NULL)
1682 /* There was a local file, so we'll check later to see if the version
1683 the server has is the same version we already have, allowing us to
1689 /* Modification time granularity is 2 seconds for Windows, so
1690 increase local time by 1 second for later comparison. */
1693 local_size = st.st_size;
1697 /* Reset the counter. */
1699 *dt = 0 | ACCEPTRANGES;
1703 /* Increment the pass counter. */
1705 sleep_between_retrievals (count);
1706 /* Get the current time string. */
1707 tms = time_str (NULL);
1708 /* Print fetch message, if opt.verbose. */
1711 char *hurl = url_string (u, 1);
1715 sprintf (tmp, _("(try:%2d)"), count);
1716 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1717 tms, hurl, tmp, locf);
1719 ws_changetitle (hurl, 1);
1724 /* Default document type is empty. However, if spider mode is
1725 on or time-stamping is employed, HEAD_ONLY commands is
1726 encoded within *dt. */
1727 if (opt.spider || (use_ts && !got_head))
1731 /* Assume no restarting. */
1733 /* Decide whether or not to restart. */
1734 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1735 /* #### this calls access() and then stat(); could be optimized. */
1736 && file_exists_p (locf))
1737 if (stat (locf, &st) == 0 && S_ISREG (st.st_mode))
1738 hstat.restval = st.st_size;
1740 /* In `-c' is used and the file is existing and non-empty,
1741 refuse to truncate it if the server doesn't support continued
1743 hstat.no_truncate = 0;
1744 if (opt.always_rest && hstat.restval)
1745 hstat.no_truncate = 1;
1747 /* Decide whether to send the no-cache directive. We send it in
1749 a) we're using a proxy, and we're past our first retrieval.
1750 Some proxies are notorious for caching incomplete data, so
1751 we require a fresh get.
1752 b) caching is explicitly inhibited. */
1753 if ((proxy && count > 1) /* a */
1754 || !opt.allow_cache /* b */
1756 *dt |= SEND_NOCACHE;
1758 *dt &= ~SEND_NOCACHE;
1760 /* Try fetching the document, or at least its head. */
1761 err = gethttp (u, &hstat, dt, proxy);
1763 /* It's unfortunate that wget determines the local filename before finding
1764 out the Content-Type of the file. Barring a major restructuring of the
1765 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1766 *hstat.local_file to tack on ".html". */
1767 if (!opt.output_document)
1768 locf = *hstat.local_file;
1770 locf = opt.output_document;
1773 tms = time_str (NULL);
1774 /* Get the new location (with or without the redirection). */
1776 *newloc = xstrdup (hstat.newloc);
1779 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1780 case CONERROR: case READERR: case WRITEFAILED:
1782 /* Non-fatal errors continue executing the loop, which will
1783 bring them to "while" statement at the end, to judge
1784 whether the number of tries was exceeded. */
1785 free_hstat (&hstat);
1786 printwhat (count, opt.ntry);
1789 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1790 case SSLERRCTXCREATE: case CONTNOTSUPPORTED:
1791 /* Fatal errors just return from the function. */
1792 free_hstat (&hstat);
1796 case FWRITEERR: case FOPENERR:
1797 /* Another fatal error. */
1798 logputs (LOG_VERBOSE, "\n");
1799 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1800 *hstat.local_file, strerror (errno));
1801 free_hstat (&hstat);
1806 /* Another fatal error. */
1807 logputs (LOG_VERBOSE, "\n");
1808 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1809 free_hstat (&hstat);
1814 /* Return the new location to the caller. */
1817 logprintf (LOG_NOTQUIET,
1818 _("ERROR: Redirection (%d) without location.\n"),
1820 free_hstat (&hstat);
1824 free_hstat (&hstat);
1829 /* The file was already fully retrieved. */
1830 free_hstat (&hstat);
1835 /* Deal with you later. */
1838 /* All possibilities should have been exhausted. */
1841 if (!(*dt & RETROKF))
1845 /* #### Ugly ugly ugly! */
1846 char *hurl = url_string (u, 1);
1847 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1850 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1851 tms, hstat.statcode, hstat.error);
1852 logputs (LOG_VERBOSE, "\n");
1853 free_hstat (&hstat);
1858 /* Did we get the time-stamp? */
1861 if (opt.timestamping && !hstat.remote_time)
1863 logputs (LOG_NOTQUIET, _("\
1864 Last-modified header missing -- time-stamps turned off.\n"));
1866 else if (hstat.remote_time)
1868 /* Convert the date-string into struct tm. */
1869 tmr = http_atotm (hstat.remote_time);
1870 if (tmr == (time_t) (-1))
1871 logputs (LOG_VERBOSE, _("\
1872 Last-modified header invalid -- time-stamp ignored.\n"));
1876 /* The time-stamping section. */
1881 use_ts = 0; /* no more time-stamping */
1882 count = 0; /* the retrieve count for HEAD is
1884 if (hstat.remote_time && tmr != (time_t) (-1))
1886 /* Now time-stamping can be used validly. Time-stamping
1887 means that if the sizes of the local and remote file
1888 match, and local file is newer than the remote file,
1889 it will not be retrieved. Otherwise, the normal
1890 download procedure is resumed. */
1892 (hstat.contlen == -1 || local_size == hstat.contlen))
1894 logprintf (LOG_VERBOSE, _("\
1895 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1897 free_hstat (&hstat);
1901 else if (tml >= tmr)
1902 logprintf (LOG_VERBOSE, _("\
1903 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1905 logputs (LOG_VERBOSE,
1906 _("Remote file is newer, retrieving.\n"));
1908 free_hstat (&hstat);
1911 if ((tmr != (time_t) (-1))
1913 && ((hstat.len == hstat.contlen) ||
1914 ((hstat.res == 0) &&
1915 ((hstat.contlen == -1) ||
1916 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1918 /* #### This code repeats in http.c and ftp.c. Move it to a
1920 const char *fl = NULL;
1921 if (opt.output_document)
1923 if (opt.od_known_regular)
1924 fl = opt.output_document;
1927 fl = *hstat.local_file;
1931 /* End of time-stamping section. */
1935 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1940 tmrate = retr_rate (hstat.len - hstat.restval, hstat.dltime, 0);
1942 if (hstat.len == hstat.contlen)
1946 logprintf (LOG_VERBOSE,
1947 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1948 tms, tmrate, locf, hstat.len, hstat.contlen);
1949 logprintf (LOG_NONVERBOSE,
1950 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1951 tms, u->url, hstat.len, hstat.contlen, locf, count);
1954 downloaded_increase (hstat.len);
1956 /* Remember that we downloaded the file for later ".orig" code. */
1957 if (*dt & ADDED_HTML_EXTENSION)
1958 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1960 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1962 free_hstat (&hstat);
1966 else if (hstat.res == 0) /* No read error */
1968 if (hstat.contlen == -1) /* We don't know how much we were supposed
1969 to get, so assume we succeeded. */
1973 logprintf (LOG_VERBOSE,
1974 _("%s (%s) - `%s' saved [%ld]\n\n"),
1975 tms, tmrate, locf, hstat.len);
1976 logprintf (LOG_NONVERBOSE,
1977 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1978 tms, u->url, hstat.len, locf, count);
1981 downloaded_increase (hstat.len);
1983 /* Remember that we downloaded the file for later ".orig" code. */
1984 if (*dt & ADDED_HTML_EXTENSION)
1985 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1987 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1989 free_hstat (&hstat);
1993 else if (hstat.len < hstat.contlen) /* meaning we lost the
1994 connection too soon */
1996 logprintf (LOG_VERBOSE,
1997 _("%s (%s) - Connection closed at byte %ld. "),
1998 tms, tmrate, hstat.len);
1999 printwhat (count, opt.ntry);
2000 free_hstat (&hstat);
2003 else if (!opt.kill_longer) /* meaning we got more than expected */
2005 logprintf (LOG_VERBOSE,
2006 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
2007 tms, tmrate, locf, hstat.len, hstat.contlen);
2008 logprintf (LOG_NONVERBOSE,
2009 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
2010 tms, u->url, hstat.len, hstat.contlen, locf, count);
2012 downloaded_increase (hstat.len);
2014 /* Remember that we downloaded the file for later ".orig" code. */
2015 if (*dt & ADDED_HTML_EXTENSION)
2016 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
2018 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
2020 free_hstat (&hstat);
2024 else /* the same, but not accepted */
2026 logprintf (LOG_VERBOSE,
2027 _("%s (%s) - Connection closed at byte %ld/%ld. "),
2028 tms, tmrate, hstat.len, hstat.contlen);
2029 printwhat (count, opt.ntry);
2030 free_hstat (&hstat);
2034 else /* now hstat.res can only be -1 */
2036 if (hstat.contlen == -1)
2038 logprintf (LOG_VERBOSE,
2039 _("%s (%s) - Read error at byte %ld (%s)."),
2040 tms, tmrate, hstat.len, strerror (errno));
2041 printwhat (count, opt.ntry);
2042 free_hstat (&hstat);
2045 else /* hstat.res == -1 and contlen is given */
2047 logprintf (LOG_VERBOSE,
2048 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
2049 tms, tmrate, hstat.len, hstat.contlen,
2051 printwhat (count, opt.ntry);
2052 free_hstat (&hstat);
2059 while (!opt.ntry || (count < opt.ntry));
2063 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
2064 than local timezone.
2066 mktime is similar but assumes struct tm, also known as the
2067 "broken-down" form of time, is in local time zone. mktime_from_utc
2068 uses mktime to make the conversion understanding that an offset
2069 will be introduced by the local time assumption.
2071 mktime_from_utc then measures the introduced offset by applying
2072 gmtime to the initial result and applying mktime to the resulting
2073 "broken-down" form. The difference between the two mktime results
2074 is the measured offset which is then subtracted from the initial
2075 mktime result to yield a calendar time which is the value returned.
2077 tm_isdst in struct tm is set to 0 to force mktime to introduce a
2078 consistent offset (the non DST offset) since tm and tm+o might be
2079 on opposite sides of a DST change.
2081 Some implementations of mktime return -1 for the nonexistent
2082 localtime hour at the beginning of DST. In this event, use
2083 mktime(tm - 1hr) + 3600.
2087 gmtime(t+o) --> tm+o
2088 mktime(tm+o) --> t+2o
2089 t+o - (t+2o - t+o) = t
2091 Note that glibc contains a function of the same purpose named
2092 `timegm' (reverse of gmtime). But obviously, it is not universally
2093 available, and unfortunately it is not straightforwardly
2094 extractable for use here. Perhaps configure should detect timegm
2095 and use it where available.
2097 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
2098 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO.
2099 Further improved by Roger with assistance from Edward J. Sabol
2100 based on input by Jamie Zawinski. */
2103 mktime_from_utc (struct tm *t)
2114 return -1; /* can't deal with output from strptime */
2125 return -1; /* can't deal with output from gmtime */
2128 return (tl - (tb - tl));
2131 /* Check whether the result of strptime() indicates success.
2132 strptime() returns the pointer to how far it got to in the string.
2133 The processing has been successful if the string is at `GMT' or
2134 `+X', or at the end of the string.
2136 In extended regexp parlance, the function returns 1 if P matches
2137 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (which strptime
2138 can return) is considered a failure and 0 is returned. */
2140 check_end (const char *p)
2144 while (ISSPACE (*p))
2147 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
2148 || ((p[0] == '+' || p[0] == '-') && ISDIGIT (p[1])))
2154 /* Convert the textual specification of time in TIME_STRING to the
2155 number of seconds since the Epoch.
2157 TIME_STRING can be in any of the three formats RFC2068 allows the
2158 HTTP servers to emit -- RFC1123-date, RFC850-date or asctime-date.
2159 Timezones are ignored, and should be GMT.
2161 Return the computed time_t representation, or -1 if the conversion
2164 This function uses strptime with various string formats for parsing
2165 TIME_STRING. This results in a parser that is not as lenient in
2166 interpreting TIME_STRING as I would like it to be. Being based on
2167 strptime, it always allows shortened months, one-digit days, etc.,
2168 but due to the multitude of formats in which time can be
2169 represented, an ideal HTTP time parser would be even more
2170 forgiving. It should completely ignore things like week days and
2171 concentrate only on the various forms of representing years,
2172 months, days, hours, minutes, and seconds. For example, it would
2173 be nice if it accepted ISO 8601 out of the box.
2175 I've investigated free and PD code for this purpose, but none was
2176 usable. getdate was big and unwieldy, and had potential copyright
2177 issues, or so I was informed. Dr. Marcus Hennecke's atotm(),
2178 distributed with phttpd, is excellent, but we cannot use it because
2179 it is not assigned to the FSF. So I stuck it with strptime. */
2182 http_atotm (const char *time_string)
2184 /* NOTE: Solaris strptime man page claims that %n and %t match white
2185 space, but that's not universally available. Instead, we simply
2186 use ` ' to mean "skip all WS", which works under all strptime
2187 implementations I've tested. */
2189 static const char *time_formats[] = {
2190 "%a, %d %b %Y %T", /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
2191 "%A, %d-%b-%y %T", /* RFC850: Thursday, 29-Jan-98 22:12:57 */
2192 "%a, %d-%b-%Y %T", /* pseudo-RFC850: Thu, 29-Jan-1998 22:12:57
2193 (google.com uses this for their cookies.) */
2194 "%a %b %d %T %Y" /* asctime: Thu Jan 29 22:12:57 1998 */
2200 /* According to Roger Beeman, we need to initialize tm_isdst, since
2201 strptime won't do it. */
2204 /* Note that under foreign locales Solaris strptime() fails to
2205 recognize English dates, which renders this function useless. We
2206 solve this by being careful not to affect LC_TIME when
2207 initializing locale.
2209 Another solution would be to temporarily set locale to C, invoke
2210 strptime(), and restore it back. This is slow and dirty,
2211 however, and locale support other than LC_MESSAGES can mess other
2212 things, so I rather chose to stick with just setting LC_MESSAGES.
2214 GNU strptime does not have this problem because it recognizes
2215 both international and local dates. */
2217 for (i = 0; i < countof (time_formats); i++)
2218 if (check_end (strptime (time_string, time_formats[i], &t)))
2219 return mktime_from_utc (&t);
2221 /* All formats have failed. */
2225 /* Authorization support: We support two authorization schemes:
2227 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
2229 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
2230 consisting of answering to the server's challenge with the proper
2233 /* How many bytes it will take to store LEN bytes in base64. */
2234 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
2236 /* Encode the string S of length LENGTH to base64 format and place it
2237 to STORE. STORE will be 0-terminated, and must point to a writable
2238 buffer of at least 1+BASE64_LENGTH(length) bytes. */
2240 base64_encode (const char *s, char *store, int length)
2242 /* Conversion table. */
2243 static char tbl[64] = {
2244 'A','B','C','D','E','F','G','H',
2245 'I','J','K','L','M','N','O','P',
2246 'Q','R','S','T','U','V','W','X',
2247 'Y','Z','a','b','c','d','e','f',
2248 'g','h','i','j','k','l','m','n',
2249 'o','p','q','r','s','t','u','v',
2250 'w','x','y','z','0','1','2','3',
2251 '4','5','6','7','8','9','+','/'
2254 unsigned char *p = (unsigned char *)store;
2256 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
2257 for (i = 0; i < length; i += 3)
2259 *p++ = tbl[s[0] >> 2];
2260 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
2261 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
2262 *p++ = tbl[s[2] & 0x3f];
2265 /* Pad the result if necessary... */
2266 if (i == length + 1)
2268 else if (i == length + 2)
2269 *(p - 1) = *(p - 2) = '=';
2270 /* ...and zero-terminate it. */
2274 /* Create the authentication header contents for the `Basic' scheme.
2275 This is done by encoding the string `USER:PASS' in base64 and
2276 prepending `HEADER: Basic ' to it. */
2278 basic_authentication_encode (const char *user, const char *passwd,
2281 char *t1, *t2, *res;
2282 int len1 = strlen (user) + 1 + strlen (passwd);
2283 int len2 = BASE64_LENGTH (len1);
2285 t1 = (char *)alloca (len1 + 1);
2286 sprintf (t1, "%s:%s", user, passwd);
2287 t2 = (char *)alloca (1 + len2);
2288 base64_encode (t1, t2, len1);
2289 res = (char *)xmalloc (len2 + 11 + strlen (header));
2290 sprintf (res, "%s: Basic %s\r\n", header, t2);
2296 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
2297 of a field in such a header. If the field is the one specified by
2298 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
2299 digest authorization code), extract its value in the (char*)
2300 variable pointed by RET. Returns negative on a malformed header,
2301 or number of bytes that have been parsed by this call. */
2303 extract_header_attr (const char *au, const char *attr_name, char **ret)
2305 const char *cp, *ep;
2309 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
2311 cp += strlen (attr_name);
2314 cp += skip_lws (cp);
2319 cp += skip_lws (cp);
2324 for (ep = cp; *ep && *ep != '\"'; ep++)
2329 *ret = strdupdelim (cp, ep);
2336 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
2337 an array of 16 bytes containing the hash keys, and BUF should be a
2338 buffer of 33 writable characters (32 for hex digits plus one for
2339 zero termination). */
2341 dump_hash (unsigned char *buf, const unsigned char *hash)
2345 for (i = 0; i < MD5_HASHLEN; i++, hash++)
2347 *buf++ = XNUM_TO_digit (*hash >> 4);
2348 *buf++ = XNUM_TO_digit (*hash & 0xf);
2353 /* Take the line apart to find the challenge, and compose a digest
2354 authorization header. See RFC2069 section 2.1.2. */
2356 digest_authentication_encode (const char *au, const char *user,
2357 const char *passwd, const char *method,
2360 static char *realm, *opaque, *nonce;
2365 { "realm", &realm },
2366 { "opaque", &opaque },
2371 realm = opaque = nonce = NULL;
2373 au += 6; /* skip over `Digest' */
2378 au += skip_lws (au);
2379 for (i = 0; i < countof (options); i++)
2381 int skip = extract_header_attr (au, options[i].name,
2382 options[i].variable);
2386 FREE_MAYBE (opaque);
2396 if (i == countof (options))
2398 while (*au && *au != '=')
2402 au += skip_lws (au);
2406 while (*au && *au != '\"')
2413 while (*au && *au != ',')
2418 if (!realm || !nonce || !user || !passwd || !path || !method)
2421 FREE_MAYBE (opaque);
2426 /* Calculate the digest value. */
2428 ALLOCA_MD5_CONTEXT (ctx);
2429 unsigned char hash[MD5_HASHLEN];
2430 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2431 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2433 /* A1BUF = H(user ":" realm ":" password) */
2435 gen_md5_update ((unsigned char *)user, strlen (user), ctx);
2436 gen_md5_update ((unsigned char *)":", 1, ctx);
2437 gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
2438 gen_md5_update ((unsigned char *)":", 1, ctx);
2439 gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
2440 gen_md5_finish (ctx, hash);
2441 dump_hash (a1buf, hash);
2443 /* A2BUF = H(method ":" path) */
2445 gen_md5_update ((unsigned char *)method, strlen (method), ctx);
2446 gen_md5_update ((unsigned char *)":", 1, ctx);
2447 gen_md5_update ((unsigned char *)path, strlen (path), ctx);
2448 gen_md5_finish (ctx, hash);
2449 dump_hash (a2buf, hash);
2451 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2453 gen_md5_update (a1buf, MD5_HASHLEN * 2, ctx);
2454 gen_md5_update ((unsigned char *)":", 1, ctx);
2455 gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
2456 gen_md5_update ((unsigned char *)":", 1, ctx);
2457 gen_md5_update (a2buf, MD5_HASHLEN * 2, ctx);
2458 gen_md5_finish (ctx, hash);
2459 dump_hash (response_digest, hash);
2461 res = (char*) xmalloc (strlen (user)
2466 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2467 + (opaque ? strlen (opaque) : 0)
2469 sprintf (res, "Authorization: Digest \
2470 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2471 user, realm, nonce, path, response_digest);
2474 char *p = res + strlen (res);
2475 strcat (p, ", opaque=\"");
2479 strcat (res, "\r\n");
2483 #endif /* USE_DIGEST */
2486 #define BEGINS_WITH(line, string_constant) \
2487 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2488 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2489 || !line[sizeof (string_constant) - 1]))
2492 known_authentication_scheme_p (const char *au)
2494 return BEGINS_WITH (au, "Basic")
2495 || BEGINS_WITH (au, "Digest")
2496 || BEGINS_WITH (au, "NTLM");
2501 /* Create the HTTP authorization request header. When the
2502 `WWW-Authenticate' response header is seen, according to the
2503 authorization scheme specified in that header (`Basic' and `Digest'
2504 are supported by the current implementation), produce an
2505 appropriate HTTP authorization request header. */
2507 create_authorization_line (const char *au, const char *user,
2508 const char *passwd, const char *method,
2511 char *wwwauth = NULL;
2513 if (!strncasecmp (au, "Basic", 5))
2514 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2515 if (!strncasecmp (au, "NTLM", 4))
2516 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2518 else if (!strncasecmp (au, "Digest", 6))
2519 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2520 #endif /* USE_DIGEST */
2527 if (pc_last_host_ip)
2528 address_list_release (pc_last_host_ip);