2 Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
4 This file is part of Wget.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
24 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
48 #include "gen_sslfunc.h"
69 extern char *version_string;
79 #define TEXTHTML_S "text/html"
80 #define HTTP_ACCEPT "*/*"
82 /* Some status code validation macros: */
83 #define H_20X(x) (((x) >= 200) && ((x) < 300))
84 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
85 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
86 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
88 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
90 #define HTTP_STATUS_OK 200
91 #define HTTP_STATUS_CREATED 201
92 #define HTTP_STATUS_ACCEPTED 202
93 #define HTTP_STATUS_NO_CONTENT 204
94 #define HTTP_STATUS_PARTIAL_CONTENTS 206
96 /* Redirection 3xx. */
97 #define HTTP_STATUS_MULTIPLE_CHOICES 300
98 #define HTTP_STATUS_MOVED_PERMANENTLY 301
99 #define HTTP_STATUS_MOVED_TEMPORARILY 302
100 #define HTTP_STATUS_NOT_MODIFIED 304
102 /* Client error 4xx. */
103 #define HTTP_STATUS_BAD_REQUEST 400
104 #define HTTP_STATUS_UNAUTHORIZED 401
105 #define HTTP_STATUS_FORBIDDEN 403
106 #define HTTP_STATUS_NOT_FOUND 404
108 /* Server errors 5xx. */
109 #define HTTP_STATUS_INTERNAL 500
110 #define HTTP_STATUS_NOT_IMPLEMENTED 501
111 #define HTTP_STATUS_BAD_GATEWAY 502
112 #define HTTP_STATUS_UNAVAILABLE 503
115 /* Parse the HTTP status line, which is of format:
117 HTTP-Version SP Status-Code SP Reason-Phrase
119 The function returns the status-code, or -1 if the status line is
120 malformed. The pointer to reason-phrase is returned in RP. */
122 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
124 /* (the variables must not be named `major' and `minor', because
125 that breaks compilation with SunOS4 cc.) */
126 int mjr, mnr, statcode;
129 *reason_phrase_ptr = NULL;
131 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
132 major version, and Y is minor version. */
133 if (strncmp (line, "HTTP/", 5) != 0)
137 /* Calculate major HTTP version. */
139 for (mjr = 0; ISDIGIT (*line); line++)
140 mjr = 10 * mjr + (*line - '0');
141 if (*line != '.' || p == line)
145 /* Calculate minor HTTP version. */
147 for (mnr = 0; ISDIGIT (*line); line++)
148 mnr = 10 * mnr + (*line - '0');
149 if (*line != ' ' || p == line)
151 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
152 minor version can be safely ignored. */
157 /* Calculate status code. */
158 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
160 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
162 /* Set up the reason phrase pointer. */
164 /* RFC2068 requires SPC here, but we allow the string to finish
165 here, in case no reason-phrase is present. */
169 *reason_phrase_ptr = line;
174 *reason_phrase_ptr = line + 1;
179 /* Functions to be used as arguments to header_process(): */
181 struct http_process_range_closure {
187 /* Parse the `Content-Range' header and extract the information it
188 contains. Returns 1 if successful, -1 otherwise. */
190 http_process_range (const char *hdr, void *arg)
192 struct http_process_range_closure *closure
193 = (struct http_process_range_closure *)arg;
196 /* Certain versions of Nutscape proxy server send out
197 `Content-Length' without "bytes" specifier, which is a breach of
198 RFC2068 (as well as the HTTP/1.1 draft which was current at the
199 time). But hell, I must support it... */
200 if (!strncasecmp (hdr, "bytes", 5))
203 hdr += skip_lws (hdr);
209 for (num = 0; ISDIGIT (*hdr); hdr++)
210 num = 10 * num + (*hdr - '0');
211 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
213 closure->first_byte_pos = num;
215 for (num = 0; ISDIGIT (*hdr); hdr++)
216 num = 10 * num + (*hdr - '0');
217 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
219 closure->last_byte_pos = num;
221 for (num = 0; ISDIGIT (*hdr); hdr++)
222 num = 10 * num + (*hdr - '0');
223 closure->entity_length = num;
227 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
228 Used for `Accept-Ranges'. */
230 http_process_none (const char *hdr, void *arg)
232 int *where = (int *)arg;
234 if (strstr (hdr, "none"))
241 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
243 http_process_type (const char *hdr, void *arg)
245 char **result = (char **)arg;
246 /* Locate P on `;' or the terminating zero, whichever comes first. */
247 const char *p = strchr (hdr, ';');
249 p = hdr + strlen (hdr);
250 while (p > hdr && ISSPACE (*(p - 1)))
252 *result = strdupdelim (hdr, p);
256 /* Check whether the `Connection' header is set to "keep-alive". */
258 http_process_connection (const char *hdr, void *arg)
260 int *flag = (int *)arg;
261 if (!strcasecmp (hdr, "Keep-Alive"))
266 /* Persistent connections. Currently, we cache the most recently used
267 connection as persistent, provided that the HTTP server agrees to
268 make it such. The persistence data is stored in the variables
269 below. Ideally, it would be in a structure, and it should be
270 possible to cache an arbitrary fixed number of these connections.
272 I think the code is quite easy to extend in that direction. */
274 /* Whether a persistent connection is active. */
275 static int pc_active_p;
276 /* Host and port of currently active persistent connection. */
277 static unsigned char pc_last_host[4];
278 static unsigned short pc_last_port;
280 /* File descriptor of the currently active persistent connection. */
281 static int pc_last_fd;
284 /* Whether a ssl handshake has occoured on this connection */
285 static int pc_active_ssl;
286 /* SSL connection of the currently active persistent connection. */
287 static SSL *pc_last_ssl;
288 #endif /* HAVE_SSL */
290 /* Mark the persistent connection as invalid. This is used by the
291 CLOSE_* macros after they forcefully close a registered persistent
292 connection. This does not close the file descriptor -- it is left
293 to the caller to do that. (Maybe it should, though.) */
296 invalidate_persistent (void)
301 #endif /* HAVE_SSL */
302 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
305 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
306 persistent. This will enable someone to use the same connection
307 later. In the context of HTTP, this must be called only AFTER the
308 response has been received and the server has promised that the
309 connection will remain alive.
311 If a previous connection was persistent, it is closed. */
315 register_persistent (const char *host, unsigned short port, int fd)
317 register_persistent (const char *host, unsigned short port, int fd, SSL* ssl)
318 #endif /* HAVE_SSL */
324 if (pc_last_fd == fd)
326 /* The connection FD is already registered. Nothing to
332 /* The old persistent connection is still active; let's
333 close it first. This situation arises whenever a
334 persistent connection exists, but we then connect to a
335 different host, and try to register a persistent
336 connection to that one. */
338 /* the ssl disconnect has to take place before the closing of pc_last_fd */
339 if (pc_last_ssl) shutdown_ssl(pc_last_ssl);
340 #endif /* HAVE_SSL */
342 invalidate_persistent ();
346 /* This store_hostaddress may not fail, because it has the results
348 success = store_hostaddress (pc_last_host, host);
355 pc_active_ssl= ssl ? 1 : 0;
356 #endif /* HAVE_SSL */
357 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
360 /* Return non-zero if a persistent connection is available for
361 connecting to HOST:PORT. */
365 persistent_available_p (const char *host, unsigned short port)
367 persistent_available_p (const char *host, unsigned short port,int ssl)
368 #endif /* HAVE_SSL */
370 unsigned char this_host[4];
371 /* First, check whether a persistent connection is active at all. */
374 /* Second, check if the active connection pertains to the correct
375 (HOST, PORT) ordered pair. */
376 if (port != pc_last_port)
378 if (!store_hostaddress (this_host, host))
380 if (memcmp (pc_last_host, this_host, 4))
382 /* Third: check whether the connection is still open. This is
383 important because most server implement a liberal (short) timeout
384 on persistent connections. Wget can of course always reconnect
385 if the connection doesn't work out, but it's nicer to know in
386 advance. This test is a logical followup of the first test, but
387 is "expensive" and therefore placed at the end of the list. */
388 if (!test_socket_open (pc_last_fd))
390 /* Oops, the socket is no longer open. Now that we know that,
391 let's invalidate the persistent connection before returning
394 invalidate_persistent ();
398 /* Fourth: check if current connection is (not) ssl, too.
399 This test is unlikely to fail because HTTP and HTTPS
400 typicaly use different ports. Yet it is possible (or so
401 I have been told) to run HTTPS and HTTP simultaneus on
403 if (ssl!=pc_active_ssl)
405 #endif /* HAVE_SSL */
409 /* The idea behind these two CLOSE macros is to distinguish between
410 two cases: one when the job we've been doing is finished, and we
411 want to close the connection and leave, and two when something is
412 seriously wrong and we're closing the connection as part of
415 In case of keep_alive, CLOSE_FINISH should leave the connection
416 open, while CLOSE_INVALIDATE should still close it.
418 Note that the semantics of the flag `keep_alive' is "this
419 connection *will* be reused (the server has promised not to close
420 the connection once we're done)", while the semantics of
421 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
422 active, registered connection". */
425 #define CLOSE_FINISH(fd) do { \
429 if (pc_active_p && (fd) == pc_last_fd) \
430 invalidate_persistent (); \
434 #define CLOSE_INVALIDATE(fd) do { \
436 if (pc_active_p && (fd) == pc_last_fd) \
437 invalidate_persistent (); \
442 #define CLOSE_FINISH(fd,ssl) do { \
445 if (ssl) shutdown_ssl(ssl); \
447 if (pc_active_p && (fd) == pc_last_fd) \
448 invalidate_persistent (); \
452 #define CLOSE_INVALIDATE(fd,ssl) do { \
453 if (ssl) shutdown_ssl(ssl); \
455 if (pc_active_p && (fd) == pc_last_fd) \
456 invalidate_persistent (); \
458 #endif /* HAVE_SSL */
462 long len; /* received length */
463 long contlen; /* expected length */
464 long restval; /* the restart value */
465 int res; /* the result of last read */
466 char *newloc; /* new location (redirection) */
467 char *remote_time; /* remote time-stamp string */
468 char *error; /* textual HTTP error */
469 int statcode; /* status code */
470 long dltime; /* time of the download */
473 /* Free the elements of hstat X. */
474 #define FREEHSTAT(x) do \
476 FREE_MAYBE ((x).newloc); \
477 FREE_MAYBE ((x).remote_time); \
478 FREE_MAYBE ((x).error); \
479 (x).newloc = (x).remote_time = (x).error = NULL; \
482 static char *create_authorization_line PARAMS ((const char *, const char *,
483 const char *, const char *,
485 static char *basic_authentication_encode PARAMS ((const char *, const char *,
487 static int known_authentication_scheme_p PARAMS ((const char *));
489 static time_t http_atotm PARAMS ((char *));
491 #define BEGINS_WITH(line, string_constant) \
492 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
493 && (ISSPACE (line[sizeof (string_constant) - 1]) \
494 || !line[sizeof (string_constant) - 1]))
496 /* Retrieve a document through HTTP protocol. It recognizes status
497 code, and correctly handles redirections. It closes the network
498 socket. If it receives an error from the functions below it, it
499 will print it if there is enough information to do so (almost
500 always), returning the error to the caller (i.e. http_loop).
502 Various HTTP parameters are stored to hs. Although it parses the
503 response code correctly, it is not used in a sane way. The caller
506 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
507 and u->proxy->url will be given to the proxy server (bad naming,
510 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
512 char *request, *type, *command, *path;
514 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
515 char *authenticate_h;
519 char *request_keep_alive;
520 int sock, hcount, num_written, all_length, remport, statcode;
521 long contlen, contrange;
525 int auth_tried_already;
528 static SSL_CTX *ssl_ctx=NULL;
530 #endif /* HAVE_SSL */
532 /* Whether this connection will be kept alive after the HTTP request
536 /* Flags that detect the two ways of specifying HTTP keep-alive
538 int http_keep_alive_1, http_keep_alive_2;
540 /* Whether keep-alive should be inhibited. */
541 int inhibit_keep_alive;
544 /* initialize ssl_ctx on first run */
545 if (!ssl_ctx) init_ssl(&ssl_ctx);
546 #endif /* HAVE_SSL */
548 if (!(*dt & HEAD_ONLY))
549 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
550 know the local filename so we can save to it. */
551 assert (u->local != NULL);
554 auth_tried_already = 0;
556 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
559 /* We need to come back here when the initial attempt to retrieve
560 without authorization header fails. (Expected to happen at least
561 for the Digest authorization scheme.) */
564 http_keep_alive_1 = http_keep_alive_2 = 0;
566 /* Initialize certain elements of struct http_stat. */
571 hs->remote_time = NULL;
574 /* Which structure to use to retrieve the original URL data. */
580 /* First: establish the connection. */
581 if (inhibit_keep_alive
583 || !persistent_available_p (u->host, u->port))
585 || !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0)))
586 #endif /* HAVE_SSL */
588 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
589 err = make_connection (&sock, u->host, u->port);
593 logputs (LOG_VERBOSE, "\n");
594 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
598 logputs (LOG_VERBOSE, "\n");
599 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
603 logputs (LOG_VERBOSE, "\n");
604 logprintf (LOG_NOTQUIET,
605 _("Connection to %s:%hu refused.\n"), u->host, u->port);
609 logputs (LOG_VERBOSE, "\n");
610 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
615 /* Everything is fine! */
616 logputs (LOG_VERBOSE, _("connected!\n"));
623 if (u->proto==URLHTTPS) if (connect_ssl(&ssl,ssl_ctx,sock)!=0) {
624 logputs (LOG_VERBOSE, "\n");
625 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
629 #endif /* HAVE_SSL */
633 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
634 /* #### pc_last_fd should be accessed through an accessor
639 #endif /* HAVE_SSL */
640 DEBUGP (("Reusing fd %d.\n", sock));
644 path = u->proxy->url;
648 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
652 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
653 sprintf (referer, "Referer: %s\r\n", ou->referer);
655 if (*dt & SEND_NOCACHE)
656 pragma_h = "Pragma: no-cache\r\n";
661 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
662 /* Gag me! Some servers (e.g. WebSitePro) have been known to
663 respond to the following `Range' format by generating a
664 multipart/x-byte-ranges MIME document! This MIME type was
665 present in an old draft of the byteranges specification.
666 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
667 only if multiple non-overlapping ranges are requested --
668 which Wget never does. */
669 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
674 STRDUP_ALLOCA (useragent, opt.useragent);
677 useragent = (char *)alloca (10 + strlen (version_string));
678 sprintf (useragent, "Wget/%s", version_string);
680 /* Construct the authentication, if userid is present. */
683 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
684 user = user ? user : opt.http_user;
685 passwd = passwd ? passwd : opt.http_passwd;
692 /* We have the username and the password, but haven't tried
693 any authorization yet. Let's see if the "Basic" method
694 works. If not, we'll come back here and construct a
695 proper authorization method with the right challenges.
697 If we didn't employ this kind of logic, every URL that
698 requires authorization would have to be processed twice,
699 which is very suboptimal and generates a bunch of false
700 "unauthorized" errors in the server log.
702 #### But this logic also has a serious problem when used
703 with stronger authentications: we *first* transmit the
704 username and the password in clear text, and *then*
705 attempt a stronger authentication scheme. That cannot be
706 right! We are only fortunate that almost everyone still
707 uses the `Basic' scheme anyway.
709 There should be an option to prevent this from happening,
710 for those who use strong authentication schemes and value
712 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
716 wwwauth = create_authorization_line (authenticate_h, user, passwd,
724 char *proxy_user, *proxy_passwd;
725 /* For normal username and password, URL components override
726 command-line/wgetrc parameters. With proxy authentication,
727 it's the reverse, because proxy URLs are normally the
728 "permanent" ones, so command-line args should take
730 if (opt.proxy_user && opt.proxy_passwd)
732 proxy_user = opt.proxy_user;
733 proxy_passwd = opt.proxy_passwd;
737 proxy_user = u->user;
738 proxy_passwd = u->passwd;
740 /* #### This is junky. Can't the proxy request, say, `Digest'
742 if (proxy_user && proxy_passwd)
743 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
744 "Proxy-Authorization");
749 /* String of the form :PORT. Used only for non-standard ports. */
753 port_maybe = (char *)alloca (numdigit (remport) + 2);
754 sprintf (port_maybe, ":%d", remport);
757 if (!inhibit_keep_alive)
758 request_keep_alive = "Connection: Keep-Alive\r\n";
760 request_keep_alive = NULL;
762 /* Allocate the memory for the request. */
763 request = (char *)alloca (strlen (command) + strlen (path)
766 + (port_maybe ? strlen (port_maybe) : 0)
767 + strlen (HTTP_ACCEPT)
768 + (request_keep_alive
769 ? strlen (request_keep_alive) : 0)
770 + (referer ? strlen (referer) : 0)
771 + (wwwauth ? strlen (wwwauth) : 0)
772 + (proxyauth ? strlen (proxyauth) : 0)
773 + (range ? strlen (range) : 0)
775 + (opt.user_header ? strlen (opt.user_header) : 0)
777 /* Construct the request. */
784 command, path, useragent, remhost,
785 port_maybe ? port_maybe : "",
787 request_keep_alive ? request_keep_alive : "",
788 referer ? referer : "",
789 wwwauth ? wwwauth : "",
790 proxyauth ? proxyauth : "",
793 opt.user_header ? opt.user_header : "");
794 DEBUGP (("---request begin---\n%s---request end---\n", request));
795 /* Free the temporary memory. */
796 FREE_MAYBE (wwwauth);
797 FREE_MAYBE (proxyauth);
799 /* Send the request to server. */
801 if (u->proto==URLHTTPS) {
802 num_written = ssl_iwrite (ssl, request, strlen (request));
804 #endif /* HAVE_SSL */
805 num_written = iwrite (sock, request, strlen (request));
808 #endif /* HAVE_SSL */
811 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
814 CLOSE_INVALIDATE (sock);
816 CLOSE_INVALIDATE (sock,ssl);
817 #endif /* HAVE_SSL */
820 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
821 u->proxy ? "Proxy" : "HTTP");
822 contlen = contrange = -1;
827 /* Before reading anything, initialize the rbuf. */
828 rbuf_initialize (&rbuf, sock);
830 if (u->proto == URLHTTPS) {
832 } else { rbuf.ssl=NULL; }
833 #endif /* HAVE_SSL */
836 /* Header-fetching loop. */
844 /* Get the header. */
845 status = header_get (&rbuf, &hdr,
846 /* Disallow continuations for status line. */
847 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
849 /* Check for errors. */
850 if (status == HG_EOF && *hdr)
852 /* This used to be an unconditional error, but that was
853 somewhat controversial, because of a large number of
854 broken CGI's that happily "forget" to send the second EOL
855 before closing the connection of a HEAD request.
857 So, the deal is to check whether the header is empty
858 (*hdr is zero if it is); if yes, it means that the
859 previous header was fully retrieved, and that -- most
860 probably -- the request is complete. "...be liberal in
861 what you accept." Oh boy. */
862 logputs (LOG_VERBOSE, "\n");
863 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
866 FREE_MAYBE (hs->newloc);
867 FREE_MAYBE (all_headers);
869 CLOSE_INVALIDATE (sock);
871 CLOSE_INVALIDATE (sock,ssl);
872 #endif /* HAVE_SSL */
875 else if (status == HG_ERROR)
877 logputs (LOG_VERBOSE, "\n");
878 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
882 FREE_MAYBE (hs->newloc);
883 FREE_MAYBE (all_headers);
885 CLOSE_INVALIDATE (sock);
887 CLOSE_INVALIDATE (sock,ssl);
888 #endif /* HAVE_SSL */
892 /* If the headers are to be saved to a file later, save them to
894 if (opt.save_headers)
896 int lh = strlen (hdr);
897 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
898 memcpy (all_headers + all_length, hdr, lh);
900 all_headers[all_length++] = '\n';
901 all_headers[all_length] = '\0';
904 /* Print the header if requested. */
905 if (opt.server_response && hcount != 1)
906 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
908 /* Check for status line. */
912 /* Parse the first line of server response. */
913 statcode = parse_http_status_line (hdr, &error);
914 hs->statcode = statcode;
915 /* Store the descriptive response. */
916 if (statcode == -1) /* malformed response */
918 /* A common reason for "malformed response" error is the
919 case when no data was actually received. Handle this
922 hs->error = xstrdup (_("No data received"));
924 hs->error = xstrdup (_("Malformed status line"));
929 hs->error = xstrdup (_("(no description)"));
931 hs->error = xstrdup (error);
938 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
943 /* Exit on empty header. */
950 /* Try getting content-length. */
951 if (contlen == -1 && !opt.ignore_length)
952 if (header_process (hdr, "Content-Length", header_extract_number,
955 /* Try getting content-type. */
957 if (header_process (hdr, "Content-Type", http_process_type, &type))
959 /* Try getting location. */
961 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
963 /* Try getting last-modified. */
964 if (!hs->remote_time)
965 if (header_process (hdr, "Last-Modified", header_strdup,
968 /* Try getting www-authentication. */
970 if (header_process (hdr, "WWW-Authenticate", header_strdup,
973 /* Check for accept-ranges header. If it contains the word
974 `none', disable the ranges. */
975 if (*dt & ACCEPTRANGES)
978 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
981 *dt &= ~ACCEPTRANGES;
985 /* Try getting content-range. */
988 struct http_process_range_closure closure;
989 if (header_process (hdr, "Content-Range", http_process_range, &closure))
991 contrange = closure.first_byte_pos;
995 /* Check for keep-alive related responses. */
996 if (!inhibit_keep_alive)
998 /* Check for the `Keep-Alive' header. */
999 if (!http_keep_alive_1)
1001 if (header_process (hdr, "Keep-Alive", header_exists,
1002 &http_keep_alive_1))
1005 /* Check for `Connection: Keep-Alive'. */
1006 if (!http_keep_alive_2)
1008 if (header_process (hdr, "Connection", http_process_connection,
1009 &http_keep_alive_2))
1017 logputs (LOG_VERBOSE, "\n");
1020 && (http_keep_alive_1 || http_keep_alive_2))
1022 assert (inhibit_keep_alive == 0);
1026 /* The server has promised that it will not close the connection
1027 when we're done. This means that we can register it. */
1029 register_persistent (u->host, u->port, sock);
1031 register_persistent (u->host, u->port, sock, ssl);
1032 #endif /* HAVE_SSL */
1034 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1037 /* Authorization is required. */
1042 CLOSE_FINISH (sock);
1044 CLOSE_FINISH (sock,ssl);
1045 #endif /* HAVE_SSL */
1046 if (auth_tried_already)
1048 /* If we have tried it already, then there is not point
1051 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1052 xfree (authenticate_h);
1055 else if (!known_authentication_scheme_p (authenticate_h))
1057 xfree (authenticate_h);
1058 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1061 else if (BEGINS_WITH (authenticate_h, "Basic"))
1063 /* The authentication scheme is basic, the one we try by
1064 default, and it failed. There's no sense in trying
1070 auth_tried_already = 1;
1074 /* We do not need this anymore. */
1077 xfree (authenticate_h);
1078 authenticate_h = NULL;
1081 /* 20x responses are counted among successful by default. */
1082 if (H_20X (statcode))
1085 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1088 /* We don't assume text/html by default. */
1091 if (opt.html_extension && (*dt & TEXTHTML))
1092 /* -E / --html-extension / html_extension = on was specified, and this is a
1093 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1094 already the file's suffix, tack on ".html". */
1096 char* last_period_in_local_filename = strrchr(u->local, '.');
1098 if (last_period_in_local_filename == NULL ||
1099 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1100 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1102 size_t local_filename_len = strlen(u->local);
1104 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1105 strcpy(u->local + local_filename_len, ".html");
1107 *dt |= ADDED_HTML_EXTENSION;
1111 if (contrange == -1)
1113 else if (contrange != hs->restval ||
1114 (H_PARTIAL (statcode) && contrange == -1))
1116 /* This means the whole request was somehow misunderstood by the
1117 server. Bail out. */
1119 FREE_MAYBE (hs->newloc);
1120 FREE_MAYBE (all_headers);
1122 CLOSE_INVALIDATE (sock);
1124 CLOSE_INVALIDATE (sock,ssl);
1125 #endif /* HAVE_SSL */
1132 contlen += contrange;
1134 contrange = -1; /* If conent-length was not sent,
1135 content-range will be ignored. */
1137 hs->contlen = contlen;
1139 /* Return if redirected. */
1140 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1142 /* RFC2068 says that in case of the 300 (multiple choices)
1143 response, the server can output a preferred URL through
1144 `Location' header; otherwise, the request should be treated
1145 like GET. So, if the location is set, it will be a
1146 redirection; otherwise, just proceed normally. */
1147 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1151 logprintf (LOG_VERBOSE,
1152 _("Location: %s%s\n"),
1153 hs->newloc ? hs->newloc : _("unspecified"),
1154 hs->newloc ? _(" [following]") : "");
1156 CLOSE_FINISH (sock);
1158 CLOSE_FINISH (sock,ssl);
1159 #endif /* HAVE_SSL */
1161 FREE_MAYBE (all_headers);
1167 if ((*dt & RETROKF) && !opt.server_response)
1169 /* No need to print this output if the body won't be
1170 downloaded at all, or if the original server response is
1172 logputs (LOG_VERBOSE, _("Length: "));
1175 logputs (LOG_VERBOSE, legible (contlen));
1176 if (contrange != -1)
1177 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1178 legible (contlen - contrange));
1181 logputs (LOG_VERBOSE,
1182 opt.ignore_length ? _("ignored") : _("unspecified"));
1184 logprintf (LOG_VERBOSE, " [%s]\n", type);
1186 logputs (LOG_VERBOSE, "\n");
1190 type = NULL; /* We don't need it any more. */
1192 /* Return if we have no intention of further downloading. */
1193 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1195 /* In case someone cares to look... */
1199 FREE_MAYBE (all_headers);
1201 CLOSE_FINISH (sock);
1203 CLOSE_FINISH (sock,ssl);
1204 #endif /* HAVE_SSL */
1205 return RETRFINISHED;
1208 /* Open the local file. */
1211 mkalldirs (u->local);
1213 rotate_backups (u->local);
1214 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1217 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1219 CLOSE_FINISH (sock);
1221 CLOSE_FINISH (sock,ssl);
1222 #endif /* HAVE_SSL */
1223 FREE_MAYBE (all_headers);
1232 /* This will silently fail for streams that don't correspond
1233 to regular files, but that's OK. */
1239 /* #### This confuses the code that checks for file size. There
1240 should be some overhead information. */
1241 if (opt.save_headers)
1242 fwrite (all_headers, 1, all_length, fp);
1244 /* Get the contents of the document. */
1245 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1246 (contlen != -1 ? contlen : 0),
1248 hs->dltime = elapsed_time ();
1250 /* Close or flush the file. We have to be careful to check for
1251 error here. Checking the result of fwrite() is not enough --
1252 errors could go unnoticed! */
1255 flush_res = fclose (fp);
1257 flush_res = fflush (fp);
1258 if (flush_res == EOF)
1261 FREE_MAYBE (all_headers);
1263 CLOSE_FINISH (sock);
1265 CLOSE_FINISH (sock,ssl);
1266 #endif /* HAVE_SSL */
1269 return RETRFINISHED;
1272 /* The genuine HTTP loop! This is the part where the retrieval is
1273 retried, and retried, and retried, and... */
1275 http_loop (struct urlinfo *u, char **newloc, int *dt)
1277 static int first_retrieval = 1;
1280 int use_ts, got_head = 0; /* time-stamping info */
1281 char *filename_plus_orig_suffix;
1282 char *local_filename = NULL;
1283 char *tms, *suf, *locf, *tmrate;
1285 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1286 long local_size = 0; /* the size of the local file */
1287 size_t filename_len;
1288 struct http_stat hstat; /* HTTP status */
1293 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1294 has_wildcards_p because it would also warn on `?', and we know that
1295 shows up in CGI paths a *lot*. */
1296 if (strchr (u->url, '*'))
1297 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1299 /* Determine the local filename. */
1301 u->local = url_filename (u->proxy ? u->proxy : u);
1303 if (!opt.output_document)
1306 locf = opt.output_document;
1308 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1309 xmalloc() here before EACH return. This is one reason it's better to set
1310 flags that influence flow control and then return once at the end. */
1311 filename_len = strlen(u->local);
1312 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1314 if (opt.noclobber && file_exists_p (u->local))
1316 /* If opt.noclobber is turned on and file already exists, do not
1317 retrieve the file */
1318 logprintf (LOG_VERBOSE, _("\
1319 File `%s' already there, will not retrieve.\n"), u->local);
1320 /* If the file is there, we suppose it's retrieved OK. */
1323 /* #### Bogusness alert. */
1324 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1325 text/html, a harmless lie. */
1326 if (((suf = suffix (u->local)) != NULL)
1327 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1330 xfree (filename_plus_orig_suffix); /* must precede every return! */
1331 /* Another harmless lie: */
1336 if (opt.timestamping)
1338 boolean local_dot_orig_file_exists = FALSE;
1340 if (opt.backup_converted)
1341 /* If -K is specified, we'll act on the assumption that it was specified
1342 last time these files were downloaded as well, and instead of just
1343 comparing local file X against server file X, we'll compare local
1344 file X.orig (if extant, else X) against server file X. If -K
1345 _wasn't_ specified last time, or the server contains files called
1346 *.orig, -N will be back to not operating correctly with -k. */
1348 /* Would a single s[n]printf() call be faster? --dan
1350 It wouldn't. sprintf() is horribly slow. At one point I
1351 profiled Wget, and found that a measurable and
1352 non-negligible amount of time was lost calling sprintf()
1353 in url.c. Replacing sprintf with inline calls to
1354 strcpy() and long_to_string() made a difference.
1356 strcpy(filename_plus_orig_suffix, u->local);
1357 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1359 /* Try to stat() the .orig file. */
1360 if (stat(filename_plus_orig_suffix, &st) == 0)
1362 local_dot_orig_file_exists = TRUE;
1363 local_filename = filename_plus_orig_suffix;
1367 if (!local_dot_orig_file_exists)
1368 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1369 if (stat (u->local, &st) == 0)
1370 local_filename = u->local;
1372 if (local_filename != NULL)
1373 /* There was a local file, so we'll check later to see if the version
1374 the server has is the same version we already have, allowing us to
1379 local_size = st.st_size;
1383 /* Reset the counter. */
1385 *dt = 0 | ACCEPTRANGES;
1389 /* Increment the pass counter. */
1391 /* Wait before the retrieval (unless this is the very first
1393 Check if we are retrying or not, wait accordingly - HEH */
1394 if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
1398 if (count<opt.waitretry)
1401 sleep(opt.waitretry);
1406 if (first_retrieval)
1407 first_retrieval = 0;
1408 /* Get the current time string. */
1409 tms = time_str (NULL);
1410 /* Print fetch message, if opt.verbose. */
1413 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1417 sprintf (tmp, _("(try:%2d)"), count);
1418 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1419 tms, hurl, tmp, locf);
1421 ws_changetitle (hurl, 1);
1426 /* Default document type is empty. However, if spider mode is
1427 on or time-stamping is employed, HEAD_ONLY commands is
1428 encoded within *dt. */
1429 if (opt.spider || (use_ts && !got_head))
1433 /* Assume no restarting. */
1435 /* Decide whether or not to restart. */
1436 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1437 && file_exists_p (u->local))
1438 if (stat (u->local, &st) == 0)
1439 hstat.restval = st.st_size;
1440 /* Decide whether to send the no-cache directive. */
1441 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1442 *dt |= SEND_NOCACHE;
1444 *dt &= ~SEND_NOCACHE;
1446 /* Try fetching the document, or at least its head. :-) */
1447 err = gethttp (u, &hstat, dt);
1449 /* It's unfortunate that wget determines the local filename before finding
1450 out the Content-Type of the file. Barring a major restructuring of the
1451 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1452 u->local to tack on ".html". */
1453 if (!opt.output_document)
1456 locf = opt.output_document;
1459 tms = time_str (NULL);
1460 /* Get the new location (with or without the redirection). */
1462 *newloc = xstrdup (hstat.newloc);
1465 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1466 case CONERROR: case READERR: case WRITEFAILED:
1468 /* Non-fatal errors continue executing the loop, which will
1469 bring them to "while" statement at the end, to judge
1470 whether the number of tries was exceeded. */
1472 printwhat (count, opt.ntry);
1475 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1476 /* Fatal errors just return from the function. */
1478 xfree (filename_plus_orig_suffix); /* must precede every return! */
1481 case FWRITEERR: case FOPENERR:
1482 /* Another fatal error. */
1483 logputs (LOG_VERBOSE, "\n");
1484 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1485 u->local, strerror (errno));
1490 /* Another fatal error. */
1491 logputs (LOG_VERBOSE, "\n");
1492 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1494 xfree (filename_plus_orig_suffix); /* must precede every return! */
1498 /* Return the new location to the caller. */
1501 logprintf (LOG_NOTQUIET,
1502 _("ERROR: Redirection (%d) without location.\n"),
1504 xfree (filename_plus_orig_suffix); /* must precede every return! */
1508 xfree (filename_plus_orig_suffix); /* must precede every return! */
1512 /* Deal with you later. */
1515 /* All possibilities should have been exhausted. */
1518 if (!(*dt & RETROKF))
1522 /* #### Ugly ugly ugly! */
1523 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1524 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1527 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1528 tms, hstat.statcode, hstat.error);
1529 logputs (LOG_VERBOSE, "\n");
1531 xfree (filename_plus_orig_suffix); /* must precede every return! */
1535 /* Did we get the time-stamp? */
1538 if (opt.timestamping && !hstat.remote_time)
1540 logputs (LOG_NOTQUIET, _("\
1541 Last-modified header missing -- time-stamps turned off.\n"));
1543 else if (hstat.remote_time)
1545 /* Convert the date-string into struct tm. */
1546 tmr = http_atotm (hstat.remote_time);
1547 if (tmr == (time_t) (-1))
1548 logputs (LOG_VERBOSE, _("\
1549 Last-modified header invalid -- time-stamp ignored.\n"));
1553 /* The time-stamping section. */
1558 use_ts = 0; /* no more time-stamping */
1559 count = 0; /* the retrieve count for HEAD is
1561 if (hstat.remote_time && tmr != (time_t) (-1))
1563 /* Now time-stamping can be used validly. Time-stamping
1564 means that if the sizes of the local and remote file
1565 match, and local file is newer than the remote file,
1566 it will not be retrieved. Otherwise, the normal
1567 download procedure is resumed. */
1569 (hstat.contlen == -1 || local_size == hstat.contlen))
1571 logprintf (LOG_VERBOSE, _("\
1572 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1575 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1578 else if (tml >= tmr)
1579 logprintf (LOG_VERBOSE, _("\
1580 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1582 logputs (LOG_VERBOSE,
1583 _("Remote file is newer, retrieving.\n"));
1589 && (tmr != (time_t) (-1))
1591 && ((hstat.len == hstat.contlen) ||
1592 ((hstat.res == 0) &&
1593 ((hstat.contlen == -1) ||
1594 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1596 touch (u->local, tmr);
1598 /* End of time-stamping section. */
1602 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1603 xfree (filename_plus_orig_suffix); /* must precede every return! */
1607 /* It is now safe to free the remainder of hstat, since the
1608 strings within it will no longer be used. */
1611 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1613 if (hstat.len == hstat.contlen)
1617 logprintf (LOG_VERBOSE,
1618 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1619 tms, tmrate, locf, hstat.len, hstat.contlen);
1620 logprintf (LOG_NONVERBOSE,
1621 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1622 tms, u->url, hstat.len, hstat.contlen, locf, count);
1625 downloaded_increase (hstat.len);
1627 /* Remember that we downloaded the file for later ".orig" code. */
1628 if (*dt & ADDED_HTML_EXTENSION)
1629 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1631 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1633 xfree(filename_plus_orig_suffix); /* must precede every return! */
1636 else if (hstat.res == 0) /* No read error */
1638 if (hstat.contlen == -1) /* We don't know how much we were supposed
1639 to get, so assume we succeeded. */
1643 logprintf (LOG_VERBOSE,
1644 _("%s (%s) - `%s' saved [%ld]\n\n"),
1645 tms, tmrate, locf, hstat.len);
1646 logprintf (LOG_NONVERBOSE,
1647 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1648 tms, u->url, hstat.len, locf, count);
1651 downloaded_increase (hstat.len);
1653 /* Remember that we downloaded the file for later ".orig" code. */
1654 if (*dt & ADDED_HTML_EXTENSION)
1655 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1657 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1659 xfree (filename_plus_orig_suffix); /* must precede every return! */
1662 else if (hstat.len < hstat.contlen) /* meaning we lost the
1663 connection too soon */
1665 logprintf (LOG_VERBOSE,
1666 _("%s (%s) - Connection closed at byte %ld. "),
1667 tms, tmrate, hstat.len);
1668 printwhat (count, opt.ntry);
1671 else if (!opt.kill_longer) /* meaning we got more than expected */
1673 logprintf (LOG_VERBOSE,
1674 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1675 tms, tmrate, locf, hstat.len, hstat.contlen);
1676 logprintf (LOG_NONVERBOSE,
1677 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1678 tms, u->url, hstat.len, hstat.contlen, locf, count);
1680 downloaded_increase (hstat.len);
1682 /* Remember that we downloaded the file for later ".orig" code. */
1683 if (*dt & ADDED_HTML_EXTENSION)
1684 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1686 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1688 xfree (filename_plus_orig_suffix); /* must precede every return! */
1691 else /* the same, but not accepted */
1693 logprintf (LOG_VERBOSE,
1694 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1695 tms, tmrate, hstat.len, hstat.contlen);
1696 printwhat (count, opt.ntry);
1700 else /* now hstat.res can only be -1 */
1702 if (hstat.contlen == -1)
1704 logprintf (LOG_VERBOSE,
1705 _("%s (%s) - Read error at byte %ld (%s)."),
1706 tms, tmrate, hstat.len, strerror (errno));
1707 printwhat (count, opt.ntry);
1710 else /* hstat.res == -1 and contlen is given */
1712 logprintf (LOG_VERBOSE,
1713 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1714 tms, tmrate, hstat.len, hstat.contlen,
1716 printwhat (count, opt.ntry);
1723 while (!opt.ntry || (count < opt.ntry));
1724 xfree (filename_plus_orig_suffix); /* must precede every return! */
1728 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1729 than local timezone (mktime assumes the latter).
1731 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1732 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1734 mktime_from_utc (struct tm *t)
1741 tb = mktime (gmtime (&tl));
1742 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1745 /* Check whether the result of strptime() indicates success.
1746 strptime() returns the pointer to how far it got to in the string.
1747 The processing has been successful if the string is at `GMT' or
1748 `+X', or at the end of the string.
1750 In extended regexp parlance, the function returns 1 if P matches
1751 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1752 strptime()) is considered a failure and 0 is returned. */
1754 check_end (const char *p)
1758 while (ISSPACE (*p))
1761 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1762 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1768 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1769 the three formats RFC2068 allows the HTTP servers to emit --
1770 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1773 We use strptime() to recognize various dates, which makes it a
1774 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1775 allows shortened dates and months, one-digit days, etc.). It also
1776 allows more than one space anywhere where the specs require one SP.
1777 The routine should probably be even more forgiving (as recommended
1778 by RFC2068), but I do not have the time to write one.
1780 Return the computed time_t representation, or -1 if all the
1783 Needless to say, what we *really* need here is something like
1784 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1785 and does not use strptime(). atotm() is to be found in the sources
1786 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1788 http_atotm (char *time_string)
1792 /* Roger Beeman says: "This function dynamically allocates struct tm
1793 t, but does no initialization. The only field that actually
1794 needs initialization is tm_isdst, since the others will be set by
1795 strptime. Since strptime does not set tm_isdst, it will return
1796 the data structure with whatever data was in tm_isdst to begin
1797 with. For those of us in timezones where DST can occur, there
1798 can be a one hour shift depending on the previous contents of the
1799 data area where the data structure is allocated." */
1802 /* Note that under foreign locales Solaris strptime() fails to
1803 recognize English dates, which renders this function useless. I
1804 assume that other non-GNU strptime's are plagued by the same
1805 disease. We solve this by setting only LC_MESSAGES in
1806 i18n_initialize(), instead of LC_ALL.
1808 Another solution could be to temporarily set locale to C, invoke
1809 strptime(), and restore it back. This is slow and dirty,
1810 however, and locale support other than LC_MESSAGES can mess other
1811 things, so I rather chose to stick with just setting LC_MESSAGES.
1813 Also note that none of this is necessary under GNU strptime(),
1814 because it recognizes both international and local dates. */
1816 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1817 it to eat all white space up to (and including) a newline, and
1818 the function fails if there is no newline (!).
1820 Let's hope all strptime() implementations use ` ' to skip *all*
1821 whitespace instead of just one (it works that way on all the
1822 systems I've tested it on). */
1824 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1825 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1826 return mktime_from_utc (&t);
1827 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1828 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1829 return mktime_from_utc (&t);
1830 /* asctime: Thu Jan 29 22:12:57 1998 */
1831 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1832 return mktime_from_utc (&t);
1837 /* Authorization support: We support two authorization schemes:
1839 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1841 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1842 consisting of answering to the server's challenge with the proper
1845 /* How many bytes it will take to store LEN bytes in base64. */
1846 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1848 /* Encode the string S of length LENGTH to base64 format and place it
1849 to STORE. STORE will be 0-terminated, and must point to a writable
1850 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1852 base64_encode (const char *s, char *store, int length)
1854 /* Conversion table. */
1855 static char tbl[64] = {
1856 'A','B','C','D','E','F','G','H',
1857 'I','J','K','L','M','N','O','P',
1858 'Q','R','S','T','U','V','W','X',
1859 'Y','Z','a','b','c','d','e','f',
1860 'g','h','i','j','k','l','m','n',
1861 'o','p','q','r','s','t','u','v',
1862 'w','x','y','z','0','1','2','3',
1863 '4','5','6','7','8','9','+','/'
1866 unsigned char *p = (unsigned char *)store;
1868 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1869 for (i = 0; i < length; i += 3)
1871 *p++ = tbl[s[0] >> 2];
1872 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1873 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1874 *p++ = tbl[s[2] & 0x3f];
1877 /* Pad the result if necessary... */
1878 if (i == length + 1)
1880 else if (i == length + 2)
1881 *(p - 1) = *(p - 2) = '=';
1882 /* ...and zero-terminate it. */
1886 /* Create the authentication header contents for the `Basic' scheme.
1887 This is done by encoding the string `USER:PASS' in base64 and
1888 prepending `HEADER: Basic ' to it. */
1890 basic_authentication_encode (const char *user, const char *passwd,
1893 char *t1, *t2, *res;
1894 int len1 = strlen (user) + 1 + strlen (passwd);
1895 int len2 = BASE64_LENGTH (len1);
1897 t1 = (char *)alloca (len1 + 1);
1898 sprintf (t1, "%s:%s", user, passwd);
1899 t2 = (char *)alloca (1 + len2);
1900 base64_encode (t1, t2, len1);
1901 res = (char *)malloc (len2 + 11 + strlen (header));
1902 sprintf (res, "%s: Basic %s\r\n", header, t2);
1908 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1909 of a field in such a header. If the field is the one specified by
1910 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1911 digest authorization code), extract its value in the (char*)
1912 variable pointed by RET. Returns negative on a malformed header,
1913 or number of bytes that have been parsed by this call. */
1915 extract_header_attr (const char *au, const char *attr_name, char **ret)
1917 const char *cp, *ep;
1921 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1923 cp += strlen (attr_name);
1926 cp += skip_lws (cp);
1931 cp += skip_lws (cp);
1936 for (ep = cp; *ep && *ep != '\"'; ep++)
1941 *ret = strdupdelim (cp, ep);
1948 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1949 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1950 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1952 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1953 an array of 16 bytes containing the hash keys, and BUF should be a
1954 buffer of 33 writable characters (32 for hex digits plus one for
1955 zero termination). */
1957 dump_hash (unsigned char *buf, const unsigned char *hash)
1961 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1963 *buf++ = HEXD2asc (*hash >> 4);
1964 *buf++ = HEXD2asc (*hash & 0xf);
1969 /* Take the line apart to find the challenge, and compose a digest
1970 authorization header. See RFC2069 section 2.1.2. */
1972 digest_authentication_encode (const char *au, const char *user,
1973 const char *passwd, const char *method,
1976 static char *realm, *opaque, *nonce;
1981 { "realm", &realm },
1982 { "opaque", &opaque },
1987 realm = opaque = nonce = NULL;
1989 au += 6; /* skip over `Digest' */
1994 au += skip_lws (au);
1995 for (i = 0; i < ARRAY_SIZE (options); i++)
1997 int skip = extract_header_attr (au, options[i].name,
1998 options[i].variable);
2002 FREE_MAYBE (opaque);
2012 if (i == ARRAY_SIZE (options))
2014 while (*au && *au != '=')
2018 au += skip_lws (au);
2022 while (*au && *au != '\"')
2029 while (*au && *au != ',')
2034 if (!realm || !nonce || !user || !passwd || !path || !method)
2037 FREE_MAYBE (opaque);
2042 /* Calculate the digest value. */
2045 unsigned char hash[MD5_HASHLEN];
2046 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2047 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2049 /* A1BUF = H(user ":" realm ":" password) */
2050 md5_init_ctx (&ctx);
2051 md5_process_bytes (user, strlen (user), &ctx);
2052 md5_process_bytes (":", 1, &ctx);
2053 md5_process_bytes (realm, strlen (realm), &ctx);
2054 md5_process_bytes (":", 1, &ctx);
2055 md5_process_bytes (passwd, strlen (passwd), &ctx);
2056 md5_finish_ctx (&ctx, hash);
2057 dump_hash (a1buf, hash);
2059 /* A2BUF = H(method ":" path) */
2060 md5_init_ctx (&ctx);
2061 md5_process_bytes (method, strlen (method), &ctx);
2062 md5_process_bytes (":", 1, &ctx);
2063 md5_process_bytes (path, strlen (path), &ctx);
2064 md5_finish_ctx (&ctx, hash);
2065 dump_hash (a2buf, hash);
2067 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2068 md5_init_ctx (&ctx);
2069 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2070 md5_process_bytes (":", 1, &ctx);
2071 md5_process_bytes (nonce, strlen (nonce), &ctx);
2072 md5_process_bytes (":", 1, &ctx);
2073 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2074 md5_finish_ctx (&ctx, hash);
2075 dump_hash (response_digest, hash);
2077 res = (char*) xmalloc (strlen (user)
2082 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2083 + (opaque ? strlen (opaque) : 0)
2085 sprintf (res, "Authorization: Digest \
2086 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2087 user, realm, nonce, path, response_digest);
2090 char *p = res + strlen (res);
2091 strcat (p, ", opaque=\"");
2095 strcat (res, "\r\n");
2099 #endif /* USE_DIGEST */
2102 #define BEGINS_WITH(line, string_constant) \
2103 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2104 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2105 || !line[sizeof (string_constant) - 1]))
2108 known_authentication_scheme_p (const char *au)
2110 return BEGINS_WITH (au, "Basic")
2111 || BEGINS_WITH (au, "Digest")
2112 || BEGINS_WITH (au, "NTLM");
2117 /* Create the HTTP authorization request header. When the
2118 `WWW-Authenticate' response header is seen, according to the
2119 authorization scheme specified in that header (`Basic' and `Digest'
2120 are supported by the current implementation), produce an
2121 appropriate HTTP authorization request header. */
2123 create_authorization_line (const char *au, const char *user,
2124 const char *passwd, const char *method,
2127 char *wwwauth = NULL;
2129 if (!strncasecmp (au, "Basic", 5))
2130 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2131 if (!strncasecmp (au, "NTLM", 4))
2132 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2134 else if (!strncasecmp (au, "Digest", 6))
2135 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2136 #endif /* USE_DIGEST */