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>
65 # include "gen_sslfunc.h"
68 extern char *version_string;
78 #define TEXTHTML_S "text/html"
79 #define HTTP_ACCEPT "*/*"
81 /* Some status code validation macros: */
82 #define H_20X(x) (((x) >= 200) && ((x) < 300))
83 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
84 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
85 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
87 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
89 #define HTTP_STATUS_OK 200
90 #define HTTP_STATUS_CREATED 201
91 #define HTTP_STATUS_ACCEPTED 202
92 #define HTTP_STATUS_NO_CONTENT 204
93 #define HTTP_STATUS_PARTIAL_CONTENTS 206
95 /* Redirection 3xx. */
96 #define HTTP_STATUS_MULTIPLE_CHOICES 300
97 #define HTTP_STATUS_MOVED_PERMANENTLY 301
98 #define HTTP_STATUS_MOVED_TEMPORARILY 302
99 #define HTTP_STATUS_NOT_MODIFIED 304
101 /* Client error 4xx. */
102 #define HTTP_STATUS_BAD_REQUEST 400
103 #define HTTP_STATUS_UNAUTHORIZED 401
104 #define HTTP_STATUS_FORBIDDEN 403
105 #define HTTP_STATUS_NOT_FOUND 404
107 /* Server errors 5xx. */
108 #define HTTP_STATUS_INTERNAL 500
109 #define HTTP_STATUS_NOT_IMPLEMENTED 501
110 #define HTTP_STATUS_BAD_GATEWAY 502
111 #define HTTP_STATUS_UNAVAILABLE 503
114 /* Parse the HTTP status line, which is of format:
116 HTTP-Version SP Status-Code SP Reason-Phrase
118 The function returns the status-code, or -1 if the status line is
119 malformed. The pointer to reason-phrase is returned in RP. */
121 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
123 /* (the variables must not be named `major' and `minor', because
124 that breaks compilation with SunOS4 cc.) */
125 int mjr, mnr, statcode;
128 *reason_phrase_ptr = NULL;
130 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
131 major version, and Y is minor version. */
132 if (strncmp (line, "HTTP/", 5) != 0)
136 /* Calculate major HTTP version. */
138 for (mjr = 0; ISDIGIT (*line); line++)
139 mjr = 10 * mjr + (*line - '0');
140 if (*line != '.' || p == line)
144 /* Calculate minor HTTP version. */
146 for (mnr = 0; ISDIGIT (*line); line++)
147 mnr = 10 * mnr + (*line - '0');
148 if (*line != ' ' || p == line)
150 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
151 minor version can be safely ignored. */
156 /* Calculate status code. */
157 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
159 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
161 /* Set up the reason phrase pointer. */
163 /* RFC2068 requires SPC here, but we allow the string to finish
164 here, in case no reason-phrase is present. */
168 *reason_phrase_ptr = line;
173 *reason_phrase_ptr = line + 1;
178 /* Functions to be used as arguments to header_process(): */
180 struct http_process_range_closure {
186 /* Parse the `Content-Range' header and extract the information it
187 contains. Returns 1 if successful, -1 otherwise. */
189 http_process_range (const char *hdr, void *arg)
191 struct http_process_range_closure *closure
192 = (struct http_process_range_closure *)arg;
195 /* Certain versions of Nutscape proxy server send out
196 `Content-Length' without "bytes" specifier, which is a breach of
197 RFC2068 (as well as the HTTP/1.1 draft which was current at the
198 time). But hell, I must support it... */
199 if (!strncasecmp (hdr, "bytes", 5))
202 hdr += skip_lws (hdr);
208 for (num = 0; ISDIGIT (*hdr); hdr++)
209 num = 10 * num + (*hdr - '0');
210 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
212 closure->first_byte_pos = num;
214 for (num = 0; ISDIGIT (*hdr); hdr++)
215 num = 10 * num + (*hdr - '0');
216 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
218 closure->last_byte_pos = num;
220 for (num = 0; ISDIGIT (*hdr); hdr++)
221 num = 10 * num + (*hdr - '0');
222 closure->entity_length = num;
226 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
227 Used for `Accept-Ranges'. */
229 http_process_none (const char *hdr, void *arg)
231 int *where = (int *)arg;
233 if (strstr (hdr, "none"))
240 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
242 http_process_type (const char *hdr, void *arg)
244 char **result = (char **)arg;
245 /* Locate P on `;' or the terminating zero, whichever comes first. */
246 const char *p = strchr (hdr, ';');
248 p = hdr + strlen (hdr);
249 while (p > hdr && ISSPACE (*(p - 1)))
251 *result = strdupdelim (hdr, p);
255 /* Check whether the `Connection' header is set to "keep-alive". */
257 http_process_connection (const char *hdr, void *arg)
259 int *flag = (int *)arg;
260 if (!strcasecmp (hdr, "Keep-Alive"))
265 /* Persistent connections. Currently, we cache the most recently used
266 connection as persistent, provided that the HTTP server agrees to
267 make it such. The persistence data is stored in the variables
268 below. Ideally, it would be in a structure, and it should be
269 possible to cache an arbitrary fixed number of these connections.
271 I think the code is quite easy to extend in that direction. */
273 /* Whether a persistent connection is active. */
274 static int pc_active_p;
275 /* Host and port of currently active persistent connection. */
276 static unsigned char pc_last_host[4];
277 static unsigned short pc_last_port;
279 /* File descriptor of the currently active persistent connection. */
280 static int pc_last_fd;
283 /* Whether a ssl handshake has occoured on this connection */
284 static int pc_active_ssl;
285 /* SSL connection of the currently active persistent connection. */
286 static SSL *pc_last_ssl;
287 #endif /* HAVE_SSL */
289 /* Mark the persistent connection as invalid. This is used by the
290 CLOSE_* macros after they forcefully close a registered persistent
291 connection. This does not close the file descriptor -- it is left
292 to the caller to do that. (Maybe it should, though.) */
295 invalidate_persistent (void)
300 #endif /* HAVE_SSL */
301 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
304 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
305 persistent. This will enable someone to use the same connection
306 later. In the context of HTTP, this must be called only AFTER the
307 response has been received and the server has promised that the
308 connection will remain alive.
310 If a previous connection was persistent, it is closed. */
313 register_persistent (const char *host, unsigned short port, int fd
323 if (pc_last_fd == fd)
325 /* The connection FD is already registered. Nothing to
331 /* The old persistent connection is still active; let's
332 close it first. This situation arises whenever a
333 persistent connection exists, but we then connect to a
334 different host, and try to register a persistent
335 connection to that one. */
337 /* The ssl disconnect has to take place before the closing
340 shutdown_ssl(pc_last_ssl);
343 invalidate_persistent ();
347 /* This store_hostaddress may not fail, because it has the results
349 success = store_hostaddress (pc_last_host, host);
356 pc_active_ssl = ssl ? 1 : 0;
358 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
361 /* Return non-zero if a persistent connection is available for
362 connecting to HOST:PORT. */
365 persistent_available_p (const char *host, unsigned short port
371 unsigned char this_host[4];
372 /* First, check whether a persistent connection is active at all. */
375 /* Second, check if the active connection pertains to the correct
376 (HOST, PORT) ordered pair. */
377 if (port != pc_last_port)
380 /* Second, a): check if current connection is (not) ssl, too. This
381 test is unlikely to fail because HTTP and HTTPS typicaly use
382 different ports. Yet it is possible, or so I [Christian
383 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
385 if (ssl != pc_active_ssl)
387 #endif /* HAVE_SSL */
388 if (!store_hostaddress (this_host, host))
390 if (memcmp (pc_last_host, this_host, 4))
392 /* Third: check whether the connection is still open. This is
393 important because most server implement a liberal (short) timeout
394 on persistent connections. Wget can of course always reconnect
395 if the connection doesn't work out, but it's nicer to know in
396 advance. This test is a logical followup of the first test, but
397 is "expensive" and therefore placed at the end of the list. */
398 if (!test_socket_open (pc_last_fd))
400 /* Oops, the socket is no longer open. Now that we know that,
401 let's invalidate the persistent connection before returning
404 invalidate_persistent ();
411 # define SHUTDOWN_SSL(ssl) do { \
413 shutdown_ssl (ssl); \
416 # define SHUTDOWN_SSL(ssl)
419 /* The idea behind these two CLOSE macros is to distinguish between
420 two cases: one when the job we've been doing is finished, and we
421 want to close the connection and leave, and two when something is
422 seriously wrong and we're closing the connection as part of
425 In case of keep_alive, CLOSE_FINISH should leave the connection
426 open, while CLOSE_INVALIDATE should still close it.
428 Note that the semantics of the flag `keep_alive' is "this
429 connection *will* be reused (the server has promised not to close
430 the connection once we're done)", while the semantics of
431 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
432 active, registered connection". */
434 #define CLOSE_FINISH(fd) do { \
437 SHUTDOWN_SSL (ssl); \
439 if (pc_active_p && (fd) == pc_last_fd) \
440 invalidate_persistent (); \
444 #define CLOSE_INVALIDATE(fd) do { \
445 SHUTDOWN_SSL (ssl); \
447 if (pc_active_p && (fd) == pc_last_fd) \
448 invalidate_persistent (); \
453 long len; /* received length */
454 long contlen; /* expected length */
455 long restval; /* the restart value */
456 int res; /* the result of last read */
457 char *newloc; /* new location (redirection) */
458 char *remote_time; /* remote time-stamp string */
459 char *error; /* textual HTTP error */
460 int statcode; /* status code */
461 long dltime; /* time of the download */
464 /* Free the elements of hstat X. */
465 #define FREEHSTAT(x) do \
467 FREE_MAYBE ((x).newloc); \
468 FREE_MAYBE ((x).remote_time); \
469 FREE_MAYBE ((x).error); \
470 (x).newloc = (x).remote_time = (x).error = NULL; \
473 static char *create_authorization_line PARAMS ((const char *, const char *,
474 const char *, const char *,
476 static char *basic_authentication_encode PARAMS ((const char *, const char *,
478 static int known_authentication_scheme_p PARAMS ((const char *));
480 static time_t http_atotm PARAMS ((char *));
482 #define BEGINS_WITH(line, string_constant) \
483 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
484 && (ISSPACE (line[sizeof (string_constant) - 1]) \
485 || !line[sizeof (string_constant) - 1]))
487 /* Retrieve a document through HTTP protocol. It recognizes status
488 code, and correctly handles redirections. It closes the network
489 socket. If it receives an error from the functions below it, it
490 will print it if there is enough information to do so (almost
491 always), returning the error to the caller (i.e. http_loop).
493 Various HTTP parameters are stored to hs. Although it parses the
494 response code correctly, it is not used in a sane way. The caller
497 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
498 and u->proxy->url will be given to the proxy server (bad naming,
501 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
503 char *request, *type, *command, *path;
505 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
506 char *authenticate_h;
510 char *request_keep_alive;
511 int sock, hcount, num_written, all_length, remport, statcode;
512 long contlen, contrange;
516 int auth_tried_already;
519 static SSL_CTX *ssl_ctx = NULL;
521 #endif /* HAVE_SSL */
523 /* Whether this connection will be kept alive after the HTTP request
527 /* Flags that detect the two ways of specifying HTTP keep-alive
529 int http_keep_alive_1, http_keep_alive_2;
531 /* Whether keep-alive should be inhibited. */
532 int inhibit_keep_alive;
535 /* initialize ssl_ctx on first run */
538 #endif /* HAVE_SSL */
540 if (!(*dt & HEAD_ONLY))
541 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
542 know the local filename so we can save to it. */
543 assert (u->local != NULL);
546 auth_tried_already = 0;
548 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
551 /* We need to come back here when the initial attempt to retrieve
552 without authorization header fails. (Expected to happen at least
553 for the Digest authorization scheme.) */
556 http_keep_alive_1 = http_keep_alive_2 = 0;
558 /* Initialize certain elements of struct http_stat. */
563 hs->remote_time = NULL;
566 /* Which structure to use to retrieve the original URL data. */
572 /* First: establish the connection. */
573 if (inhibit_keep_alive
576 !persistent_available_p (u->host, u->port)
578 !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
579 #endif /* HAVE_SSL */
582 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
583 err = make_connection (&sock, u->host, u->port);
587 logputs (LOG_VERBOSE, "\n");
588 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
592 logputs (LOG_VERBOSE, "\n");
593 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
597 logputs (LOG_VERBOSE, "\n");
598 logprintf (LOG_NOTQUIET,
599 _("Connection to %s:%hu refused.\n"), u->host, u->port);
603 logputs (LOG_VERBOSE, "\n");
604 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
609 /* Everything is fine! */
610 logputs (LOG_VERBOSE, _("connected!\n"));
617 if (u->proto == URLHTTPS)
618 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
620 logputs (LOG_VERBOSE, "\n");
621 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
625 #endif /* HAVE_SSL */
629 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
630 /* #### pc_last_fd should be accessed through an accessor
635 #endif /* HAVE_SSL */
636 DEBUGP (("Reusing fd %d.\n", sock));
640 path = u->proxy->url;
644 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
648 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
649 sprintf (referer, "Referer: %s\r\n", ou->referer);
651 if (*dt & SEND_NOCACHE)
652 pragma_h = "Pragma: no-cache\r\n";
657 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
658 /* Gag me! Some servers (e.g. WebSitePro) have been known to
659 respond to the following `Range' format by generating a
660 multipart/x-byte-ranges MIME document! This MIME type was
661 present in an old draft of the byteranges specification.
662 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
663 only if multiple non-overlapping ranges are requested --
664 which Wget never does. */
665 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
670 STRDUP_ALLOCA (useragent, opt.useragent);
673 useragent = (char *)alloca (10 + strlen (version_string));
674 sprintf (useragent, "Wget/%s", version_string);
676 /* Construct the authentication, if userid is present. */
679 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
680 user = user ? user : opt.http_user;
681 passwd = passwd ? passwd : opt.http_passwd;
688 /* We have the username and the password, but haven't tried
689 any authorization yet. Let's see if the "Basic" method
690 works. If not, we'll come back here and construct a
691 proper authorization method with the right challenges.
693 If we didn't employ this kind of logic, every URL that
694 requires authorization would have to be processed twice,
695 which is very suboptimal and generates a bunch of false
696 "unauthorized" errors in the server log.
698 #### But this logic also has a serious problem when used
699 with stronger authentications: we *first* transmit the
700 username and the password in clear text, and *then*
701 attempt a stronger authentication scheme. That cannot be
702 right! We are only fortunate that almost everyone still
703 uses the `Basic' scheme anyway.
705 There should be an option to prevent this from happening,
706 for those who use strong authentication schemes and value
708 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
712 wwwauth = create_authorization_line (authenticate_h, user, passwd,
720 char *proxy_user, *proxy_passwd;
721 /* For normal username and password, URL components override
722 command-line/wgetrc parameters. With proxy authentication,
723 it's the reverse, because proxy URLs are normally the
724 "permanent" ones, so command-line args should take
726 if (opt.proxy_user && opt.proxy_passwd)
728 proxy_user = opt.proxy_user;
729 proxy_passwd = opt.proxy_passwd;
733 proxy_user = u->user;
734 proxy_passwd = u->passwd;
736 /* #### This is junky. Can't the proxy request, say, `Digest'
738 if (proxy_user && proxy_passwd)
739 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
740 "Proxy-Authorization");
745 /* String of the form :PORT. Used only for non-standard ports. */
749 port_maybe = (char *)alloca (numdigit (remport) + 2);
750 sprintf (port_maybe, ":%d", remport);
753 if (!inhibit_keep_alive)
754 request_keep_alive = "Connection: Keep-Alive\r\n";
756 request_keep_alive = NULL;
758 /* Allocate the memory for the request. */
759 request = (char *)alloca (strlen (command) + strlen (path)
762 + (port_maybe ? strlen (port_maybe) : 0)
763 + strlen (HTTP_ACCEPT)
764 + (request_keep_alive
765 ? strlen (request_keep_alive) : 0)
766 + (referer ? strlen (referer) : 0)
767 + (wwwauth ? strlen (wwwauth) : 0)
768 + (proxyauth ? strlen (proxyauth) : 0)
769 + (range ? strlen (range) : 0)
771 + (opt.user_header ? strlen (opt.user_header) : 0)
773 /* Construct the request. */
780 command, path, useragent, remhost,
781 port_maybe ? port_maybe : "",
783 request_keep_alive ? request_keep_alive : "",
784 referer ? referer : "",
785 wwwauth ? wwwauth : "",
786 proxyauth ? proxyauth : "",
789 opt.user_header ? opt.user_header : "");
790 DEBUGP (("---request begin---\n%s---request end---\n", request));
791 /* Free the temporary memory. */
792 FREE_MAYBE (wwwauth);
793 FREE_MAYBE (proxyauth);
795 /* Send the request to server. */
797 if (u->proto == URLHTTPS)
798 num_written = ssl_iwrite (ssl, request, strlen (request));
800 #endif /* HAVE_SSL */
801 num_written = iwrite (sock, request, strlen (request));
805 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
807 CLOSE_INVALIDATE (sock);
810 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
811 u->proxy ? "Proxy" : "HTTP");
812 contlen = contrange = -1;
817 /* Before reading anything, initialize the rbuf. */
818 rbuf_initialize (&rbuf, sock);
820 if (u->proto == URLHTTPS)
824 #endif /* HAVE_SSL */
827 /* Header-fetching loop. */
835 /* Get the header. */
836 status = header_get (&rbuf, &hdr,
837 /* Disallow continuations for status line. */
838 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
840 /* Check for errors. */
841 if (status == HG_EOF && *hdr)
843 /* This used to be an unconditional error, but that was
844 somewhat controversial, because of a large number of
845 broken CGI's that happily "forget" to send the second EOL
846 before closing the connection of a HEAD request.
848 So, the deal is to check whether the header is empty
849 (*hdr is zero if it is); if yes, it means that the
850 previous header was fully retrieved, and that -- most
851 probably -- the request is complete. "...be liberal in
852 what you accept." Oh boy. */
853 logputs (LOG_VERBOSE, "\n");
854 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
857 FREE_MAYBE (hs->newloc);
858 FREE_MAYBE (all_headers);
859 CLOSE_INVALIDATE (sock);
862 else if (status == HG_ERROR)
864 logputs (LOG_VERBOSE, "\n");
865 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
869 FREE_MAYBE (hs->newloc);
870 FREE_MAYBE (all_headers);
871 CLOSE_INVALIDATE (sock);
875 /* If the headers are to be saved to a file later, save them to
877 if (opt.save_headers)
879 int lh = strlen (hdr);
880 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
881 memcpy (all_headers + all_length, hdr, lh);
883 all_headers[all_length++] = '\n';
884 all_headers[all_length] = '\0';
887 /* Print the header if requested. */
888 if (opt.server_response && hcount != 1)
889 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
891 /* Check for status line. */
895 /* Parse the first line of server response. */
896 statcode = parse_http_status_line (hdr, &error);
897 hs->statcode = statcode;
898 /* Store the descriptive response. */
899 if (statcode == -1) /* malformed response */
901 /* A common reason for "malformed response" error is the
902 case when no data was actually received. Handle this
905 hs->error = xstrdup (_("No data received"));
907 hs->error = xstrdup (_("Malformed status line"));
912 hs->error = xstrdup (_("(no description)"));
914 hs->error = xstrdup (error);
921 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
926 /* Exit on empty header. */
933 /* Try getting content-length. */
934 if (contlen == -1 && !opt.ignore_length)
935 if (header_process (hdr, "Content-Length", header_extract_number,
938 /* Try getting content-type. */
940 if (header_process (hdr, "Content-Type", http_process_type, &type))
942 /* Try getting location. */
944 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
946 /* Try getting last-modified. */
947 if (!hs->remote_time)
948 if (header_process (hdr, "Last-Modified", header_strdup,
951 /* Try getting www-authentication. */
953 if (header_process (hdr, "WWW-Authenticate", header_strdup,
956 /* Check for accept-ranges header. If it contains the word
957 `none', disable the ranges. */
958 if (*dt & ACCEPTRANGES)
961 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
964 *dt &= ~ACCEPTRANGES;
968 /* Try getting content-range. */
971 struct http_process_range_closure closure;
972 if (header_process (hdr, "Content-Range", http_process_range, &closure))
974 contrange = closure.first_byte_pos;
978 /* Check for keep-alive related responses. */
979 if (!inhibit_keep_alive)
981 /* Check for the `Keep-Alive' header. */
982 if (!http_keep_alive_1)
984 if (header_process (hdr, "Keep-Alive", header_exists,
988 /* Check for `Connection: Keep-Alive'. */
989 if (!http_keep_alive_2)
991 if (header_process (hdr, "Connection", http_process_connection,
1000 logputs (LOG_VERBOSE, "\n");
1003 && (http_keep_alive_1 || http_keep_alive_2))
1005 assert (inhibit_keep_alive == 0);
1009 /* The server has promised that it will not close the connection
1010 when we're done. This means that we can register it. */
1012 register_persistent (u->host, u->port, sock);
1014 register_persistent (u->host, u->port, sock, ssl);
1015 #endif /* HAVE_SSL */
1017 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1020 /* Authorization is required. */
1024 CLOSE_FINISH (sock);
1025 if (auth_tried_already)
1027 /* If we have tried it already, then there is not point
1030 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1031 xfree (authenticate_h);
1034 else if (!known_authentication_scheme_p (authenticate_h))
1036 xfree (authenticate_h);
1037 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1040 else if (BEGINS_WITH (authenticate_h, "Basic"))
1042 /* The authentication scheme is basic, the one we try by
1043 default, and it failed. There's no sense in trying
1049 auth_tried_already = 1;
1053 /* We do not need this anymore. */
1056 xfree (authenticate_h);
1057 authenticate_h = NULL;
1060 /* 20x responses are counted among successful by default. */
1061 if (H_20X (statcode))
1064 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1067 /* We don't assume text/html by default. */
1070 if (opt.html_extension && (*dt & TEXTHTML))
1071 /* -E / --html-extension / html_extension = on was specified, and this is a
1072 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1073 already the file's suffix, tack on ".html". */
1075 char* last_period_in_local_filename = strrchr(u->local, '.');
1077 if (last_period_in_local_filename == NULL ||
1078 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1079 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1081 size_t local_filename_len = strlen(u->local);
1083 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1084 strcpy(u->local + local_filename_len, ".html");
1086 *dt |= ADDED_HTML_EXTENSION;
1090 if (contrange == -1)
1092 else if (contrange != hs->restval ||
1093 (H_PARTIAL (statcode) && contrange == -1))
1095 /* This means the whole request was somehow misunderstood by the
1096 server. Bail out. */
1098 FREE_MAYBE (hs->newloc);
1099 FREE_MAYBE (all_headers);
1100 CLOSE_INVALIDATE (sock);
1107 contlen += contrange;
1109 contrange = -1; /* If conent-length was not sent,
1110 content-range will be ignored. */
1112 hs->contlen = contlen;
1114 /* Return if redirected. */
1115 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1117 /* RFC2068 says that in case of the 300 (multiple choices)
1118 response, the server can output a preferred URL through
1119 `Location' header; otherwise, the request should be treated
1120 like GET. So, if the location is set, it will be a
1121 redirection; otherwise, just proceed normally. */
1122 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1126 logprintf (LOG_VERBOSE,
1127 _("Location: %s%s\n"),
1128 hs->newloc ? hs->newloc : _("unspecified"),
1129 hs->newloc ? _(" [following]") : "");
1130 CLOSE_FINISH (sock);
1132 FREE_MAYBE (all_headers);
1138 if ((*dt & RETROKF) && !opt.server_response)
1140 /* No need to print this output if the body won't be
1141 downloaded at all, or if the original server response is
1143 logputs (LOG_VERBOSE, _("Length: "));
1146 logputs (LOG_VERBOSE, legible (contlen));
1147 if (contrange != -1)
1148 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1149 legible (contlen - contrange));
1152 logputs (LOG_VERBOSE,
1153 opt.ignore_length ? _("ignored") : _("unspecified"));
1155 logprintf (LOG_VERBOSE, " [%s]\n", type);
1157 logputs (LOG_VERBOSE, "\n");
1161 type = NULL; /* We don't need it any more. */
1163 /* Return if we have no intention of further downloading. */
1164 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1166 /* In case someone cares to look... */
1170 FREE_MAYBE (all_headers);
1171 CLOSE_FINISH (sock);
1172 return RETRFINISHED;
1175 /* Open the local file. */
1178 mkalldirs (u->local);
1180 rotate_backups (u->local);
1181 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1184 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1185 CLOSE_FINISH (sock);
1186 FREE_MAYBE (all_headers);
1195 /* This will silently fail for streams that don't correspond
1196 to regular files, but that's OK. */
1202 /* #### This confuses the code that checks for file size. There
1203 should be some overhead information. */
1204 if (opt.save_headers)
1205 fwrite (all_headers, 1, all_length, fp);
1207 /* Get the contents of the document. */
1208 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1209 (contlen != -1 ? contlen : 0),
1211 hs->dltime = elapsed_time ();
1213 /* Close or flush the file. We have to be careful to check for
1214 error here. Checking the result of fwrite() is not enough --
1215 errors could go unnoticed! */
1218 flush_res = fclose (fp);
1220 flush_res = fflush (fp);
1221 if (flush_res == EOF)
1224 FREE_MAYBE (all_headers);
1225 CLOSE_FINISH (sock);
1228 return RETRFINISHED;
1231 /* The genuine HTTP loop! This is the part where the retrieval is
1232 retried, and retried, and retried, and... */
1234 http_loop (struct urlinfo *u, char **newloc, int *dt)
1237 int use_ts, got_head = 0; /* time-stamping info */
1238 char *filename_plus_orig_suffix;
1239 char *local_filename = NULL;
1240 char *tms, *suf, *locf, *tmrate;
1242 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1243 long local_size = 0; /* the size of the local file */
1244 size_t filename_len;
1245 struct http_stat hstat; /* HTTP status */
1250 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1251 has_wildcards_p because it would also warn on `?', and we know that
1252 shows up in CGI paths a *lot*. */
1253 if (strchr (u->url, '*'))
1254 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1256 /* Determine the local filename. */
1258 u->local = url_filename (u->proxy ? u->proxy : u);
1260 if (!opt.output_document)
1263 locf = opt.output_document;
1265 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1266 xmalloc() here before EACH return. This is one reason it's better to set
1267 flags that influence flow control and then return once at the end. */
1268 filename_len = strlen(u->local);
1269 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1271 if (opt.noclobber && file_exists_p (u->local))
1273 /* If opt.noclobber is turned on and file already exists, do not
1274 retrieve the file */
1275 logprintf (LOG_VERBOSE, _("\
1276 File `%s' already there, will not retrieve.\n"), u->local);
1277 /* If the file is there, we suppose it's retrieved OK. */
1280 /* #### Bogusness alert. */
1281 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1282 text/html, a harmless lie. */
1283 if (((suf = suffix (u->local)) != NULL)
1284 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1287 xfree (filename_plus_orig_suffix); /* must precede every return! */
1288 /* Another harmless lie: */
1293 if (opt.timestamping)
1295 boolean local_dot_orig_file_exists = FALSE;
1297 if (opt.backup_converted)
1298 /* If -K is specified, we'll act on the assumption that it was specified
1299 last time these files were downloaded as well, and instead of just
1300 comparing local file X against server file X, we'll compare local
1301 file X.orig (if extant, else X) against server file X. If -K
1302 _wasn't_ specified last time, or the server contains files called
1303 *.orig, -N will be back to not operating correctly with -k. */
1305 /* Would a single s[n]printf() call be faster? --dan
1307 It wouldn't. sprintf() is horribly slow. At one point I
1308 profiled Wget, and found that a measurable and
1309 non-negligible amount of time was lost calling sprintf()
1310 in url.c. Replacing sprintf with inline calls to
1311 strcpy() and long_to_string() made a difference.
1313 strcpy(filename_plus_orig_suffix, u->local);
1314 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1316 /* Try to stat() the .orig file. */
1317 if (stat(filename_plus_orig_suffix, &st) == 0)
1319 local_dot_orig_file_exists = TRUE;
1320 local_filename = filename_plus_orig_suffix;
1324 if (!local_dot_orig_file_exists)
1325 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1326 if (stat (u->local, &st) == 0)
1327 local_filename = u->local;
1329 if (local_filename != NULL)
1330 /* There was a local file, so we'll check later to see if the version
1331 the server has is the same version we already have, allowing us to
1336 local_size = st.st_size;
1340 /* Reset the counter. */
1342 *dt = 0 | ACCEPTRANGES;
1346 /* Increment the pass counter. */
1348 sleep_between_retrievals (count);
1349 /* Get the current time string. */
1350 tms = time_str (NULL);
1351 /* Print fetch message, if opt.verbose. */
1354 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1358 sprintf (tmp, _("(try:%2d)"), count);
1359 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1360 tms, hurl, tmp, locf);
1362 ws_changetitle (hurl, 1);
1367 /* Default document type is empty. However, if spider mode is
1368 on or time-stamping is employed, HEAD_ONLY commands is
1369 encoded within *dt. */
1370 if (opt.spider || (use_ts && !got_head))
1374 /* Assume no restarting. */
1376 /* Decide whether or not to restart. */
1377 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1378 && file_exists_p (u->local))
1379 if (stat (u->local, &st) == 0)
1380 hstat.restval = st.st_size;
1381 /* Decide whether to send the no-cache directive. */
1382 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1383 *dt |= SEND_NOCACHE;
1385 *dt &= ~SEND_NOCACHE;
1387 /* Try fetching the document, or at least its head. :-) */
1388 err = gethttp (u, &hstat, dt);
1390 /* It's unfortunate that wget determines the local filename before finding
1391 out the Content-Type of the file. Barring a major restructuring of the
1392 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1393 u->local to tack on ".html". */
1394 if (!opt.output_document)
1397 locf = opt.output_document;
1400 tms = time_str (NULL);
1401 /* Get the new location (with or without the redirection). */
1403 *newloc = xstrdup (hstat.newloc);
1406 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1407 case CONERROR: case READERR: case WRITEFAILED:
1409 /* Non-fatal errors continue executing the loop, which will
1410 bring them to "while" statement at the end, to judge
1411 whether the number of tries was exceeded. */
1413 printwhat (count, opt.ntry);
1416 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1417 /* Fatal errors just return from the function. */
1419 xfree (filename_plus_orig_suffix); /* must precede every return! */
1422 case FWRITEERR: case FOPENERR:
1423 /* Another fatal error. */
1424 logputs (LOG_VERBOSE, "\n");
1425 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1426 u->local, strerror (errno));
1431 /* Another fatal error. */
1432 logputs (LOG_VERBOSE, "\n");
1433 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1435 xfree (filename_plus_orig_suffix); /* must precede every return! */
1439 /* Return the new location to the caller. */
1442 logprintf (LOG_NOTQUIET,
1443 _("ERROR: Redirection (%d) without location.\n"),
1445 xfree (filename_plus_orig_suffix); /* must precede every return! */
1449 xfree (filename_plus_orig_suffix); /* must precede every return! */
1453 /* Deal with you later. */
1456 /* All possibilities should have been exhausted. */
1459 if (!(*dt & RETROKF))
1463 /* #### Ugly ugly ugly! */
1464 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1465 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1468 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1469 tms, hstat.statcode, hstat.error);
1470 logputs (LOG_VERBOSE, "\n");
1472 xfree (filename_plus_orig_suffix); /* must precede every return! */
1476 /* Did we get the time-stamp? */
1479 if (opt.timestamping && !hstat.remote_time)
1481 logputs (LOG_NOTQUIET, _("\
1482 Last-modified header missing -- time-stamps turned off.\n"));
1484 else if (hstat.remote_time)
1486 /* Convert the date-string into struct tm. */
1487 tmr = http_atotm (hstat.remote_time);
1488 if (tmr == (time_t) (-1))
1489 logputs (LOG_VERBOSE, _("\
1490 Last-modified header invalid -- time-stamp ignored.\n"));
1494 /* The time-stamping section. */
1499 use_ts = 0; /* no more time-stamping */
1500 count = 0; /* the retrieve count for HEAD is
1502 if (hstat.remote_time && tmr != (time_t) (-1))
1504 /* Now time-stamping can be used validly. Time-stamping
1505 means that if the sizes of the local and remote file
1506 match, and local file is newer than the remote file,
1507 it will not be retrieved. Otherwise, the normal
1508 download procedure is resumed. */
1510 (hstat.contlen == -1 || local_size == hstat.contlen))
1512 logprintf (LOG_VERBOSE, _("\
1513 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1516 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1519 else if (tml >= tmr)
1520 logprintf (LOG_VERBOSE, _("\
1521 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1523 logputs (LOG_VERBOSE,
1524 _("Remote file is newer, retrieving.\n"));
1529 if ((tmr != (time_t) (-1))
1531 && ((hstat.len == hstat.contlen) ||
1532 ((hstat.res == 0) &&
1533 ((hstat.contlen == -1) ||
1534 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1536 /* #### This code repeats in http.c and ftp.c. Move it to a
1538 const char *fl = NULL;
1539 if (opt.output_document)
1541 if (opt.od_known_regular)
1542 fl = opt.output_document;
1549 /* End of time-stamping section. */
1553 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1554 xfree (filename_plus_orig_suffix); /* must precede every return! */
1558 /* It is now safe to free the remainder of hstat, since the
1559 strings within it will no longer be used. */
1562 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1564 if (hstat.len == hstat.contlen)
1568 logprintf (LOG_VERBOSE,
1569 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1570 tms, tmrate, locf, hstat.len, hstat.contlen);
1571 logprintf (LOG_NONVERBOSE,
1572 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1573 tms, u->url, hstat.len, hstat.contlen, locf, count);
1576 downloaded_increase (hstat.len);
1578 /* Remember that we downloaded the file for later ".orig" code. */
1579 if (*dt & ADDED_HTML_EXTENSION)
1580 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1582 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1584 xfree(filename_plus_orig_suffix); /* must precede every return! */
1587 else if (hstat.res == 0) /* No read error */
1589 if (hstat.contlen == -1) /* We don't know how much we were supposed
1590 to get, so assume we succeeded. */
1594 logprintf (LOG_VERBOSE,
1595 _("%s (%s) - `%s' saved [%ld]\n\n"),
1596 tms, tmrate, locf, hstat.len);
1597 logprintf (LOG_NONVERBOSE,
1598 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1599 tms, u->url, hstat.len, locf, count);
1602 downloaded_increase (hstat.len);
1604 /* Remember that we downloaded the file for later ".orig" code. */
1605 if (*dt & ADDED_HTML_EXTENSION)
1606 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1608 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1610 xfree (filename_plus_orig_suffix); /* must precede every return! */
1613 else if (hstat.len < hstat.contlen) /* meaning we lost the
1614 connection too soon */
1616 logprintf (LOG_VERBOSE,
1617 _("%s (%s) - Connection closed at byte %ld. "),
1618 tms, tmrate, hstat.len);
1619 printwhat (count, opt.ntry);
1622 else if (!opt.kill_longer) /* meaning we got more than expected */
1624 logprintf (LOG_VERBOSE,
1625 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1626 tms, tmrate, locf, hstat.len, hstat.contlen);
1627 logprintf (LOG_NONVERBOSE,
1628 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1629 tms, u->url, hstat.len, hstat.contlen, locf, count);
1631 downloaded_increase (hstat.len);
1633 /* Remember that we downloaded the file for later ".orig" code. */
1634 if (*dt & ADDED_HTML_EXTENSION)
1635 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1637 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1639 xfree (filename_plus_orig_suffix); /* must precede every return! */
1642 else /* the same, but not accepted */
1644 logprintf (LOG_VERBOSE,
1645 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1646 tms, tmrate, hstat.len, hstat.contlen);
1647 printwhat (count, opt.ntry);
1651 else /* now hstat.res can only be -1 */
1653 if (hstat.contlen == -1)
1655 logprintf (LOG_VERBOSE,
1656 _("%s (%s) - Read error at byte %ld (%s)."),
1657 tms, tmrate, hstat.len, strerror (errno));
1658 printwhat (count, opt.ntry);
1661 else /* hstat.res == -1 and contlen is given */
1663 logprintf (LOG_VERBOSE,
1664 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1665 tms, tmrate, hstat.len, hstat.contlen,
1667 printwhat (count, opt.ntry);
1674 while (!opt.ntry || (count < opt.ntry));
1675 xfree (filename_plus_orig_suffix); /* must precede every return! */
1679 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1680 than local timezone (mktime assumes the latter).
1682 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1683 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1685 mktime_from_utc (struct tm *t)
1692 tb = mktime (gmtime (&tl));
1693 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1696 /* Check whether the result of strptime() indicates success.
1697 strptime() returns the pointer to how far it got to in the string.
1698 The processing has been successful if the string is at `GMT' or
1699 `+X', or at the end of the string.
1701 In extended regexp parlance, the function returns 1 if P matches
1702 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1703 strptime()) is considered a failure and 0 is returned. */
1705 check_end (const char *p)
1709 while (ISSPACE (*p))
1712 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1713 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1719 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1720 the three formats RFC2068 allows the HTTP servers to emit --
1721 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1724 We use strptime() to recognize various dates, which makes it a
1725 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1726 allows shortened dates and months, one-digit days, etc.). It also
1727 allows more than one space anywhere where the specs require one SP.
1728 The routine should probably be even more forgiving (as recommended
1729 by RFC2068), but I do not have the time to write one.
1731 Return the computed time_t representation, or -1 if all the
1734 Needless to say, what we *really* need here is something like
1735 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1736 and does not use strptime(). atotm() is to be found in the sources
1737 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1739 http_atotm (char *time_string)
1743 /* Roger Beeman says: "This function dynamically allocates struct tm
1744 t, but does no initialization. The only field that actually
1745 needs initialization is tm_isdst, since the others will be set by
1746 strptime. Since strptime does not set tm_isdst, it will return
1747 the data structure with whatever data was in tm_isdst to begin
1748 with. For those of us in timezones where DST can occur, there
1749 can be a one hour shift depending on the previous contents of the
1750 data area where the data structure is allocated." */
1753 /* Note that under foreign locales Solaris strptime() fails to
1754 recognize English dates, which renders this function useless. I
1755 assume that other non-GNU strptime's are plagued by the same
1756 disease. We solve this by setting only LC_MESSAGES in
1757 i18n_initialize(), instead of LC_ALL.
1759 Another solution could be to temporarily set locale to C, invoke
1760 strptime(), and restore it back. This is slow and dirty,
1761 however, and locale support other than LC_MESSAGES can mess other
1762 things, so I rather chose to stick with just setting LC_MESSAGES.
1764 Also note that none of this is necessary under GNU strptime(),
1765 because it recognizes both international and local dates. */
1767 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1768 it to eat all white space up to (and including) a newline, and
1769 the function fails if there is no newline (!).
1771 Let's hope all strptime() implementations use ` ' to skip *all*
1772 whitespace instead of just one (it works that way on all the
1773 systems I've tested it on). */
1775 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1776 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1777 return mktime_from_utc (&t);
1778 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1779 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1780 return mktime_from_utc (&t);
1781 /* asctime: Thu Jan 29 22:12:57 1998 */
1782 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1783 return mktime_from_utc (&t);
1788 /* Authorization support: We support two authorization schemes:
1790 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1792 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1793 consisting of answering to the server's challenge with the proper
1796 /* How many bytes it will take to store LEN bytes in base64. */
1797 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1799 /* Encode the string S of length LENGTH to base64 format and place it
1800 to STORE. STORE will be 0-terminated, and must point to a writable
1801 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1803 base64_encode (const char *s, char *store, int length)
1805 /* Conversion table. */
1806 static char tbl[64] = {
1807 'A','B','C','D','E','F','G','H',
1808 'I','J','K','L','M','N','O','P',
1809 'Q','R','S','T','U','V','W','X',
1810 'Y','Z','a','b','c','d','e','f',
1811 'g','h','i','j','k','l','m','n',
1812 'o','p','q','r','s','t','u','v',
1813 'w','x','y','z','0','1','2','3',
1814 '4','5','6','7','8','9','+','/'
1817 unsigned char *p = (unsigned char *)store;
1819 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1820 for (i = 0; i < length; i += 3)
1822 *p++ = tbl[s[0] >> 2];
1823 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1824 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1825 *p++ = tbl[s[2] & 0x3f];
1828 /* Pad the result if necessary... */
1829 if (i == length + 1)
1831 else if (i == length + 2)
1832 *(p - 1) = *(p - 2) = '=';
1833 /* ...and zero-terminate it. */
1837 /* Create the authentication header contents for the `Basic' scheme.
1838 This is done by encoding the string `USER:PASS' in base64 and
1839 prepending `HEADER: Basic ' to it. */
1841 basic_authentication_encode (const char *user, const char *passwd,
1844 char *t1, *t2, *res;
1845 int len1 = strlen (user) + 1 + strlen (passwd);
1846 int len2 = BASE64_LENGTH (len1);
1848 t1 = (char *)alloca (len1 + 1);
1849 sprintf (t1, "%s:%s", user, passwd);
1850 t2 = (char *)alloca (1 + len2);
1851 base64_encode (t1, t2, len1);
1852 res = (char *)malloc (len2 + 11 + strlen (header));
1853 sprintf (res, "%s: Basic %s\r\n", header, t2);
1859 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1860 of a field in such a header. If the field is the one specified by
1861 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1862 digest authorization code), extract its value in the (char*)
1863 variable pointed by RET. Returns negative on a malformed header,
1864 or number of bytes that have been parsed by this call. */
1866 extract_header_attr (const char *au, const char *attr_name, char **ret)
1868 const char *cp, *ep;
1872 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1874 cp += strlen (attr_name);
1877 cp += skip_lws (cp);
1882 cp += skip_lws (cp);
1887 for (ep = cp; *ep && *ep != '\"'; ep++)
1892 *ret = strdupdelim (cp, ep);
1899 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1900 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1901 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1903 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1904 an array of 16 bytes containing the hash keys, and BUF should be a
1905 buffer of 33 writable characters (32 for hex digits plus one for
1906 zero termination). */
1908 dump_hash (unsigned char *buf, const unsigned char *hash)
1912 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1914 *buf++ = HEXD2asc (*hash >> 4);
1915 *buf++ = HEXD2asc (*hash & 0xf);
1920 /* Take the line apart to find the challenge, and compose a digest
1921 authorization header. See RFC2069 section 2.1.2. */
1923 digest_authentication_encode (const char *au, const char *user,
1924 const char *passwd, const char *method,
1927 static char *realm, *opaque, *nonce;
1932 { "realm", &realm },
1933 { "opaque", &opaque },
1938 realm = opaque = nonce = NULL;
1940 au += 6; /* skip over `Digest' */
1945 au += skip_lws (au);
1946 for (i = 0; i < ARRAY_SIZE (options); i++)
1948 int skip = extract_header_attr (au, options[i].name,
1949 options[i].variable);
1953 FREE_MAYBE (opaque);
1963 if (i == ARRAY_SIZE (options))
1965 while (*au && *au != '=')
1969 au += skip_lws (au);
1973 while (*au && *au != '\"')
1980 while (*au && *au != ',')
1985 if (!realm || !nonce || !user || !passwd || !path || !method)
1988 FREE_MAYBE (opaque);
1993 /* Calculate the digest value. */
1996 unsigned char hash[MD5_HASHLEN];
1997 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
1998 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2000 /* A1BUF = H(user ":" realm ":" password) */
2001 md5_init_ctx (&ctx);
2002 md5_process_bytes (user, strlen (user), &ctx);
2003 md5_process_bytes (":", 1, &ctx);
2004 md5_process_bytes (realm, strlen (realm), &ctx);
2005 md5_process_bytes (":", 1, &ctx);
2006 md5_process_bytes (passwd, strlen (passwd), &ctx);
2007 md5_finish_ctx (&ctx, hash);
2008 dump_hash (a1buf, hash);
2010 /* A2BUF = H(method ":" path) */
2011 md5_init_ctx (&ctx);
2012 md5_process_bytes (method, strlen (method), &ctx);
2013 md5_process_bytes (":", 1, &ctx);
2014 md5_process_bytes (path, strlen (path), &ctx);
2015 md5_finish_ctx (&ctx, hash);
2016 dump_hash (a2buf, hash);
2018 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2019 md5_init_ctx (&ctx);
2020 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2021 md5_process_bytes (":", 1, &ctx);
2022 md5_process_bytes (nonce, strlen (nonce), &ctx);
2023 md5_process_bytes (":", 1, &ctx);
2024 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2025 md5_finish_ctx (&ctx, hash);
2026 dump_hash (response_digest, hash);
2028 res = (char*) xmalloc (strlen (user)
2033 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2034 + (opaque ? strlen (opaque) : 0)
2036 sprintf (res, "Authorization: Digest \
2037 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2038 user, realm, nonce, path, response_digest);
2041 char *p = res + strlen (res);
2042 strcat (p, ", opaque=\"");
2046 strcat (res, "\r\n");
2050 #endif /* USE_DIGEST */
2053 #define BEGINS_WITH(line, string_constant) \
2054 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2055 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2056 || !line[sizeof (string_constant) - 1]))
2059 known_authentication_scheme_p (const char *au)
2061 return BEGINS_WITH (au, "Basic")
2062 || BEGINS_WITH (au, "Digest")
2063 || BEGINS_WITH (au, "NTLM");
2068 /* Create the HTTP authorization request header. When the
2069 `WWW-Authenticate' response header is seen, according to the
2070 authorization scheme specified in that header (`Basic' and `Digest'
2071 are supported by the current implementation), produce an
2072 appropriate HTTP authorization request header. */
2074 create_authorization_line (const char *au, const char *user,
2075 const char *passwd, const char *method,
2078 char *wwwauth = NULL;
2080 if (!strncasecmp (au, "Basic", 5))
2081 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2082 if (!strncasecmp (au, "NTLM", 4))
2083 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2085 else if (!strncasecmp (au, "Digest", 6))
2086 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2087 #endif /* USE_DIGEST */