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>
50 # include <netdb.h> /* for h_errno */
67 # include "gen_sslfunc.h"
70 extern char *version_string;
80 #define TEXTHTML_S "text/html"
81 #define HTTP_ACCEPT "*/*"
83 /* Some status code validation macros: */
84 #define H_20X(x) (((x) >= 200) && ((x) < 300))
85 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
86 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
87 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
89 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
91 #define HTTP_STATUS_OK 200
92 #define HTTP_STATUS_CREATED 201
93 #define HTTP_STATUS_ACCEPTED 202
94 #define HTTP_STATUS_NO_CONTENT 204
95 #define HTTP_STATUS_PARTIAL_CONTENTS 206
97 /* Redirection 3xx. */
98 #define HTTP_STATUS_MULTIPLE_CHOICES 300
99 #define HTTP_STATUS_MOVED_PERMANENTLY 301
100 #define HTTP_STATUS_MOVED_TEMPORARILY 302
101 #define HTTP_STATUS_NOT_MODIFIED 304
103 /* Client error 4xx. */
104 #define HTTP_STATUS_BAD_REQUEST 400
105 #define HTTP_STATUS_UNAUTHORIZED 401
106 #define HTTP_STATUS_FORBIDDEN 403
107 #define HTTP_STATUS_NOT_FOUND 404
109 /* Server errors 5xx. */
110 #define HTTP_STATUS_INTERNAL 500
111 #define HTTP_STATUS_NOT_IMPLEMENTED 501
112 #define HTTP_STATUS_BAD_GATEWAY 502
113 #define HTTP_STATUS_UNAVAILABLE 503
116 /* Parse the HTTP status line, which is of format:
118 HTTP-Version SP Status-Code SP Reason-Phrase
120 The function returns the status-code, or -1 if the status line is
121 malformed. The pointer to reason-phrase is returned in RP. */
123 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
125 /* (the variables must not be named `major' and `minor', because
126 that breaks compilation with SunOS4 cc.) */
127 int mjr, mnr, statcode;
130 *reason_phrase_ptr = NULL;
132 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
133 major version, and Y is minor version. */
134 if (strncmp (line, "HTTP/", 5) != 0)
138 /* Calculate major HTTP version. */
140 for (mjr = 0; ISDIGIT (*line); line++)
141 mjr = 10 * mjr + (*line - '0');
142 if (*line != '.' || p == line)
146 /* Calculate minor HTTP version. */
148 for (mnr = 0; ISDIGIT (*line); line++)
149 mnr = 10 * mnr + (*line - '0');
150 if (*line != ' ' || p == line)
152 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
153 minor version can be safely ignored. */
158 /* Calculate status code. */
159 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
161 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
163 /* Set up the reason phrase pointer. */
165 /* RFC2068 requires SPC here, but we allow the string to finish
166 here, in case no reason-phrase is present. */
170 *reason_phrase_ptr = line;
175 *reason_phrase_ptr = line + 1;
180 /* Functions to be used as arguments to header_process(): */
182 struct http_process_range_closure {
188 /* Parse the `Content-Range' header and extract the information it
189 contains. Returns 1 if successful, -1 otherwise. */
191 http_process_range (const char *hdr, void *arg)
193 struct http_process_range_closure *closure
194 = (struct http_process_range_closure *)arg;
197 /* Certain versions of Nutscape proxy server send out
198 `Content-Length' without "bytes" specifier, which is a breach of
199 RFC2068 (as well as the HTTP/1.1 draft which was current at the
200 time). But hell, I must support it... */
201 if (!strncasecmp (hdr, "bytes", 5))
204 hdr += skip_lws (hdr);
210 for (num = 0; ISDIGIT (*hdr); hdr++)
211 num = 10 * num + (*hdr - '0');
212 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
214 closure->first_byte_pos = num;
216 for (num = 0; ISDIGIT (*hdr); hdr++)
217 num = 10 * num + (*hdr - '0');
218 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
220 closure->last_byte_pos = num;
222 for (num = 0; ISDIGIT (*hdr); hdr++)
223 num = 10 * num + (*hdr - '0');
224 closure->entity_length = num;
228 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
229 Used for `Accept-Ranges'. */
231 http_process_none (const char *hdr, void *arg)
233 int *where = (int *)arg;
235 if (strstr (hdr, "none"))
242 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
244 http_process_type (const char *hdr, void *arg)
246 char **result = (char **)arg;
247 /* Locate P on `;' or the terminating zero, whichever comes first. */
248 const char *p = strchr (hdr, ';');
250 p = hdr + strlen (hdr);
251 while (p > hdr && ISSPACE (*(p - 1)))
253 *result = strdupdelim (hdr, p);
257 /* Check whether the `Connection' header is set to "keep-alive". */
259 http_process_connection (const char *hdr, void *arg)
261 int *flag = (int *)arg;
262 if (!strcasecmp (hdr, "Keep-Alive"))
267 /* Persistent connections. Currently, we cache the most recently used
268 connection as persistent, provided that the HTTP server agrees to
269 make it such. The persistence data is stored in the variables
270 below. Ideally, it would be in a structure, and it should be
271 possible to cache an arbitrary fixed number of these connections.
273 I think the code is quite easy to extend in that direction. */
275 /* Whether a persistent connection is active. */
276 static int pc_active_p;
277 /* Host and port of currently active persistent connection. */
278 static unsigned char pc_last_host[4];
279 static unsigned short pc_last_port;
281 /* File descriptor of the currently active persistent connection. */
282 static int pc_last_fd;
285 /* Whether a ssl handshake has occoured on this connection */
286 static int pc_active_ssl;
287 /* SSL connection of the currently active persistent connection. */
288 static SSL *pc_last_ssl;
289 #endif /* HAVE_SSL */
291 /* Mark the persistent connection as invalid. This is used by the
292 CLOSE_* macros after they forcefully close a registered persistent
293 connection. This does not close the file descriptor -- it is left
294 to the caller to do that. (Maybe it should, though.) */
297 invalidate_persistent (void)
302 #endif /* HAVE_SSL */
303 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
306 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
307 persistent. This will enable someone to use the same connection
308 later. In the context of HTTP, this must be called only AFTER the
309 response has been received and the server has promised that the
310 connection will remain alive.
312 If a previous connection was persistent, it is closed. */
315 register_persistent (const char *host, unsigned short port, int fd
325 if (pc_last_fd == fd)
327 /* The connection FD is already registered. Nothing to
333 /* The old persistent connection is still active; let's
334 close it first. This situation arises whenever a
335 persistent connection exists, but we then connect to a
336 different host, and try to register a persistent
337 connection to that one. */
339 /* The ssl disconnect has to take place before the closing
342 shutdown_ssl(pc_last_ssl);
345 invalidate_persistent ();
349 /* This store_hostaddress may not fail, because it has the results
351 success = store_hostaddress (pc_last_host, host);
358 pc_active_ssl = ssl ? 1 : 0;
360 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
363 /* Return non-zero if a persistent connection is available for
364 connecting to HOST:PORT. */
367 persistent_available_p (const char *host, unsigned short port
373 unsigned char this_host[4];
374 /* First, check whether a persistent connection is active at all. */
377 /* Second, check if the active connection pertains to the correct
378 (HOST, PORT) ordered pair. */
379 if (port != pc_last_port)
382 /* Second, a): check if current connection is (not) ssl, too. This
383 test is unlikely to fail because HTTP and HTTPS typicaly use
384 different ports. Yet it is possible, or so I [Christian
385 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
387 if (ssl != pc_active_ssl)
389 #endif /* HAVE_SSL */
390 if (!store_hostaddress (this_host, host))
392 if (memcmp (pc_last_host, this_host, 4))
394 /* Third: check whether the connection is still open. This is
395 important because most server implement a liberal (short) timeout
396 on persistent connections. Wget can of course always reconnect
397 if the connection doesn't work out, but it's nicer to know in
398 advance. This test is a logical followup of the first test, but
399 is "expensive" and therefore placed at the end of the list. */
400 if (!test_socket_open (pc_last_fd))
402 /* Oops, the socket is no longer open. Now that we know that,
403 let's invalidate the persistent connection before returning
406 invalidate_persistent ();
413 # define SHUTDOWN_SSL(ssl) do { \
415 shutdown_ssl (ssl); \
418 # define SHUTDOWN_SSL(ssl)
421 /* The idea behind these two CLOSE macros is to distinguish between
422 two cases: one when the job we've been doing is finished, and we
423 want to close the connection and leave, and two when something is
424 seriously wrong and we're closing the connection as part of
427 In case of keep_alive, CLOSE_FINISH should leave the connection
428 open, while CLOSE_INVALIDATE should still close it.
430 Note that the semantics of the flag `keep_alive' is "this
431 connection *will* be reused (the server has promised not to close
432 the connection once we're done)", while the semantics of
433 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
434 active, registered connection". */
436 #define CLOSE_FINISH(fd) do { \
439 SHUTDOWN_SSL (ssl); \
441 if (pc_active_p && (fd) == pc_last_fd) \
442 invalidate_persistent (); \
446 #define CLOSE_INVALIDATE(fd) do { \
447 SHUTDOWN_SSL (ssl); \
449 if (pc_active_p && (fd) == pc_last_fd) \
450 invalidate_persistent (); \
455 long len; /* received length */
456 long contlen; /* expected length */
457 long restval; /* the restart value */
458 int res; /* the result of last read */
459 char *newloc; /* new location (redirection) */
460 char *remote_time; /* remote time-stamp string */
461 char *error; /* textual HTTP error */
462 int statcode; /* status code */
463 long dltime; /* time of the download */
466 /* Free the elements of hstat X. */
467 #define FREEHSTAT(x) do \
469 FREE_MAYBE ((x).newloc); \
470 FREE_MAYBE ((x).remote_time); \
471 FREE_MAYBE ((x).error); \
472 (x).newloc = (x).remote_time = (x).error = NULL; \
475 static char *create_authorization_line PARAMS ((const char *, const char *,
476 const char *, const char *,
478 static char *basic_authentication_encode PARAMS ((const char *, const char *,
480 static int known_authentication_scheme_p PARAMS ((const char *));
482 static time_t http_atotm PARAMS ((char *));
484 #define BEGINS_WITH(line, string_constant) \
485 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
486 && (ISSPACE (line[sizeof (string_constant) - 1]) \
487 || !line[sizeof (string_constant) - 1]))
489 /* Retrieve a document through HTTP protocol. It recognizes status
490 code, and correctly handles redirections. It closes the network
491 socket. If it receives an error from the functions below it, it
492 will print it if there is enough information to do so (almost
493 always), returning the error to the caller (i.e. http_loop).
495 Various HTTP parameters are stored to hs. Although it parses the
496 response code correctly, it is not used in a sane way. The caller
499 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
500 and u->proxy->url will be given to the proxy server (bad naming,
503 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
505 char *request, *type, *command, *path;
507 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
508 char *authenticate_h;
512 char *request_keep_alive;
513 int sock, hcount, num_written, all_length, remport, statcode;
514 long contlen, contrange;
518 int auth_tried_already;
521 static SSL_CTX *ssl_ctx = NULL;
523 #endif /* HAVE_SSL */
525 /* Whether this connection will be kept alive after the HTTP request
529 /* Flags that detect the two ways of specifying HTTP keep-alive
531 int http_keep_alive_1, http_keep_alive_2;
533 /* Whether keep-alive should be inhibited. */
534 int inhibit_keep_alive;
537 /* initialize ssl_ctx on first run */
540 #endif /* HAVE_SSL */
542 if (!(*dt & HEAD_ONLY))
543 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
544 know the local filename so we can save to it. */
545 assert (u->local != NULL);
548 auth_tried_already = 0;
550 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
553 /* We need to come back here when the initial attempt to retrieve
554 without authorization header fails. (Expected to happen at least
555 for the Digest authorization scheme.) */
558 http_keep_alive_1 = http_keep_alive_2 = 0;
560 /* Initialize certain elements of struct http_stat. */
565 hs->remote_time = NULL;
568 /* Which structure to use to retrieve the original URL data. */
574 /* First: establish the connection. */
575 if (inhibit_keep_alive
578 !persistent_available_p (u->host, u->port)
580 !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
581 #endif /* HAVE_SSL */
584 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
585 err = make_connection (&sock, u->host, u->port);
589 logputs (LOG_VERBOSE, "\n");
590 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
594 logputs (LOG_VERBOSE, "\n");
595 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
599 logputs (LOG_VERBOSE, "\n");
600 logprintf (LOG_NOTQUIET,
601 _("Connection to %s:%hu refused.\n"), u->host, u->port);
605 logputs (LOG_VERBOSE, "\n");
606 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
611 /* Everything is fine! */
612 logputs (LOG_VERBOSE, _("connected!\n"));
619 if (u->proto == URLHTTPS)
620 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
622 logputs (LOG_VERBOSE, "\n");
623 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
627 #endif /* HAVE_SSL */
631 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
632 /* #### pc_last_fd should be accessed through an accessor
637 #endif /* HAVE_SSL */
638 DEBUGP (("Reusing fd %d.\n", sock));
642 path = u->proxy->url;
646 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
650 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
651 sprintf (referer, "Referer: %s\r\n", ou->referer);
653 if (*dt & SEND_NOCACHE)
654 pragma_h = "Pragma: no-cache\r\n";
659 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
660 /* Gag me! Some servers (e.g. WebSitePro) have been known to
661 respond to the following `Range' format by generating a
662 multipart/x-byte-ranges MIME document! This MIME type was
663 present in an old draft of the byteranges specification.
664 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
665 only if multiple non-overlapping ranges are requested --
666 which Wget never does. */
667 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
672 STRDUP_ALLOCA (useragent, opt.useragent);
675 useragent = (char *)alloca (10 + strlen (version_string));
676 sprintf (useragent, "Wget/%s", version_string);
678 /* Construct the authentication, if userid is present. */
681 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
682 user = user ? user : opt.http_user;
683 passwd = passwd ? passwd : opt.http_passwd;
690 /* We have the username and the password, but haven't tried
691 any authorization yet. Let's see if the "Basic" method
692 works. If not, we'll come back here and construct a
693 proper authorization method with the right challenges.
695 If we didn't employ this kind of logic, every URL that
696 requires authorization would have to be processed twice,
697 which is very suboptimal and generates a bunch of false
698 "unauthorized" errors in the server log.
700 #### But this logic also has a serious problem when used
701 with stronger authentications: we *first* transmit the
702 username and the password in clear text, and *then*
703 attempt a stronger authentication scheme. That cannot be
704 right! We are only fortunate that almost everyone still
705 uses the `Basic' scheme anyway.
707 There should be an option to prevent this from happening,
708 for those who use strong authentication schemes and value
710 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
714 wwwauth = create_authorization_line (authenticate_h, user, passwd,
722 char *proxy_user, *proxy_passwd;
723 /* For normal username and password, URL components override
724 command-line/wgetrc parameters. With proxy authentication,
725 it's the reverse, because proxy URLs are normally the
726 "permanent" ones, so command-line args should take
728 if (opt.proxy_user && opt.proxy_passwd)
730 proxy_user = opt.proxy_user;
731 proxy_passwd = opt.proxy_passwd;
735 proxy_user = u->user;
736 proxy_passwd = u->passwd;
738 /* #### This is junky. Can't the proxy request, say, `Digest'
740 if (proxy_user && proxy_passwd)
741 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
742 "Proxy-Authorization");
747 /* String of the form :PORT. Used only for non-standard ports. */
751 port_maybe = (char *)alloca (numdigit (remport) + 2);
752 sprintf (port_maybe, ":%d", remport);
755 if (!inhibit_keep_alive)
756 request_keep_alive = "Connection: Keep-Alive\r\n";
758 request_keep_alive = NULL;
760 /* Allocate the memory for the request. */
761 request = (char *)alloca (strlen (command) + strlen (path)
764 + (port_maybe ? strlen (port_maybe) : 0)
765 + strlen (HTTP_ACCEPT)
766 + (request_keep_alive
767 ? strlen (request_keep_alive) : 0)
768 + (referer ? strlen (referer) : 0)
769 + (wwwauth ? strlen (wwwauth) : 0)
770 + (proxyauth ? strlen (proxyauth) : 0)
771 + (range ? strlen (range) : 0)
773 + (opt.user_header ? strlen (opt.user_header) : 0)
775 /* Construct the request. */
782 command, path, useragent, remhost,
783 port_maybe ? port_maybe : "",
785 request_keep_alive ? request_keep_alive : "",
786 referer ? referer : "",
787 wwwauth ? wwwauth : "",
788 proxyauth ? proxyauth : "",
791 opt.user_header ? opt.user_header : "");
792 DEBUGP (("---request begin---\n%s---request end---\n", request));
793 /* Free the temporary memory. */
794 FREE_MAYBE (wwwauth);
795 FREE_MAYBE (proxyauth);
797 /* Send the request to server. */
799 if (u->proto == URLHTTPS)
800 num_written = ssl_iwrite (ssl, request, strlen (request));
802 #endif /* HAVE_SSL */
803 num_written = iwrite (sock, request, strlen (request));
807 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
809 CLOSE_INVALIDATE (sock);
812 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
813 u->proxy ? "Proxy" : "HTTP");
814 contlen = contrange = -1;
819 /* Before reading anything, initialize the rbuf. */
820 rbuf_initialize (&rbuf, sock);
822 if (u->proto == URLHTTPS)
826 #endif /* HAVE_SSL */
829 /* Header-fetching loop. */
837 /* Get the header. */
838 status = header_get (&rbuf, &hdr,
839 /* Disallow continuations for status line. */
840 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
842 /* Check for errors. */
843 if (status == HG_EOF && *hdr)
845 /* This used to be an unconditional error, but that was
846 somewhat controversial, because of a large number of
847 broken CGI's that happily "forget" to send the second EOL
848 before closing the connection of a HEAD request.
850 So, the deal is to check whether the header is empty
851 (*hdr is zero if it is); if yes, it means that the
852 previous header was fully retrieved, and that -- most
853 probably -- the request is complete. "...be liberal in
854 what you accept." Oh boy. */
855 logputs (LOG_VERBOSE, "\n");
856 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
859 FREE_MAYBE (hs->newloc);
860 FREE_MAYBE (all_headers);
861 CLOSE_INVALIDATE (sock);
864 else if (status == HG_ERROR)
866 logputs (LOG_VERBOSE, "\n");
867 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
871 FREE_MAYBE (hs->newloc);
872 FREE_MAYBE (all_headers);
873 CLOSE_INVALIDATE (sock);
877 /* If the headers are to be saved to a file later, save them to
879 if (opt.save_headers)
881 int lh = strlen (hdr);
882 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
883 memcpy (all_headers + all_length, hdr, lh);
885 all_headers[all_length++] = '\n';
886 all_headers[all_length] = '\0';
889 /* Print the header if requested. */
890 if (opt.server_response && hcount != 1)
891 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
893 /* Check for status line. */
897 /* Parse the first line of server response. */
898 statcode = parse_http_status_line (hdr, &error);
899 hs->statcode = statcode;
900 /* Store the descriptive response. */
901 if (statcode == -1) /* malformed response */
903 /* A common reason for "malformed response" error is the
904 case when no data was actually received. Handle this
907 hs->error = xstrdup (_("No data received"));
909 hs->error = xstrdup (_("Malformed status line"));
914 hs->error = xstrdup (_("(no description)"));
916 hs->error = xstrdup (error);
923 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
928 /* Exit on empty header. */
935 /* Try getting content-length. */
936 if (contlen == -1 && !opt.ignore_length)
937 if (header_process (hdr, "Content-Length", header_extract_number,
940 /* Try getting content-type. */
942 if (header_process (hdr, "Content-Type", http_process_type, &type))
944 /* Try getting location. */
946 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
948 /* Try getting last-modified. */
949 if (!hs->remote_time)
950 if (header_process (hdr, "Last-Modified", header_strdup,
953 /* Try getting www-authentication. */
955 if (header_process (hdr, "WWW-Authenticate", header_strdup,
958 /* Check for accept-ranges header. If it contains the word
959 `none', disable the ranges. */
960 if (*dt & ACCEPTRANGES)
963 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
966 *dt &= ~ACCEPTRANGES;
970 /* Try getting content-range. */
973 struct http_process_range_closure closure;
974 if (header_process (hdr, "Content-Range", http_process_range, &closure))
976 contrange = closure.first_byte_pos;
980 /* Check for keep-alive related responses. */
981 if (!inhibit_keep_alive)
983 /* Check for the `Keep-Alive' header. */
984 if (!http_keep_alive_1)
986 if (header_process (hdr, "Keep-Alive", header_exists,
990 /* Check for `Connection: Keep-Alive'. */
991 if (!http_keep_alive_2)
993 if (header_process (hdr, "Connection", http_process_connection,
1002 logputs (LOG_VERBOSE, "\n");
1005 && (http_keep_alive_1 || http_keep_alive_2))
1007 assert (inhibit_keep_alive == 0);
1011 /* The server has promised that it will not close the connection
1012 when we're done. This means that we can register it. */
1014 register_persistent (u->host, u->port, sock);
1016 register_persistent (u->host, u->port, sock, ssl);
1017 #endif /* HAVE_SSL */
1019 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1022 /* Authorization is required. */
1026 CLOSE_FINISH (sock);
1027 if (auth_tried_already)
1029 /* If we have tried it already, then there is not point
1032 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1033 xfree (authenticate_h);
1036 else if (!known_authentication_scheme_p (authenticate_h))
1038 xfree (authenticate_h);
1039 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1042 else if (BEGINS_WITH (authenticate_h, "Basic"))
1044 /* The authentication scheme is basic, the one we try by
1045 default, and it failed. There's no sense in trying
1051 auth_tried_already = 1;
1055 /* We do not need this anymore. */
1058 xfree (authenticate_h);
1059 authenticate_h = NULL;
1062 /* 20x responses are counted among successful by default. */
1063 if (H_20X (statcode))
1066 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1069 /* We don't assume text/html by default. */
1072 if (opt.html_extension && (*dt & TEXTHTML))
1073 /* -E / --html-extension / html_extension = on was specified, and this is a
1074 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1075 already the file's suffix, tack on ".html". */
1077 char* last_period_in_local_filename = strrchr(u->local, '.');
1079 if (last_period_in_local_filename == NULL ||
1080 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1081 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1083 size_t local_filename_len = strlen(u->local);
1085 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1086 strcpy(u->local + local_filename_len, ".html");
1088 *dt |= ADDED_HTML_EXTENSION;
1092 if (contrange == -1)
1094 else if (contrange != hs->restval ||
1095 (H_PARTIAL (statcode) && contrange == -1))
1097 /* This means the whole request was somehow misunderstood by the
1098 server. Bail out. */
1100 FREE_MAYBE (hs->newloc);
1101 FREE_MAYBE (all_headers);
1102 CLOSE_INVALIDATE (sock);
1109 contlen += contrange;
1111 contrange = -1; /* If conent-length was not sent,
1112 content-range will be ignored. */
1114 hs->contlen = contlen;
1116 /* Return if redirected. */
1117 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1119 /* RFC2068 says that in case of the 300 (multiple choices)
1120 response, the server can output a preferred URL through
1121 `Location' header; otherwise, the request should be treated
1122 like GET. So, if the location is set, it will be a
1123 redirection; otherwise, just proceed normally. */
1124 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1128 logprintf (LOG_VERBOSE,
1129 _("Location: %s%s\n"),
1130 hs->newloc ? hs->newloc : _("unspecified"),
1131 hs->newloc ? _(" [following]") : "");
1132 CLOSE_FINISH (sock);
1134 FREE_MAYBE (all_headers);
1140 if ((*dt & RETROKF) && !opt.server_response)
1142 /* No need to print this output if the body won't be
1143 downloaded at all, or if the original server response is
1145 logputs (LOG_VERBOSE, _("Length: "));
1148 logputs (LOG_VERBOSE, legible (contlen));
1149 if (contrange != -1)
1150 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1151 legible (contlen - contrange));
1154 logputs (LOG_VERBOSE,
1155 opt.ignore_length ? _("ignored") : _("unspecified"));
1157 logprintf (LOG_VERBOSE, " [%s]\n", type);
1159 logputs (LOG_VERBOSE, "\n");
1163 type = NULL; /* We don't need it any more. */
1165 /* Return if we have no intention of further downloading. */
1166 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1168 /* In case someone cares to look... */
1172 FREE_MAYBE (all_headers);
1173 CLOSE_FINISH (sock);
1174 return RETRFINISHED;
1177 /* Open the local file. */
1180 mkalldirs (u->local);
1182 rotate_backups (u->local);
1183 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1186 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1187 CLOSE_FINISH (sock);
1188 FREE_MAYBE (all_headers);
1197 /* This will silently fail for streams that don't correspond
1198 to regular files, but that's OK. */
1204 /* #### This confuses the code that checks for file size. There
1205 should be some overhead information. */
1206 if (opt.save_headers)
1207 fwrite (all_headers, 1, all_length, fp);
1209 /* Get the contents of the document. */
1210 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1211 (contlen != -1 ? contlen : 0),
1213 hs->dltime = elapsed_time ();
1215 /* Close or flush the file. We have to be careful to check for
1216 error here. Checking the result of fwrite() is not enough --
1217 errors could go unnoticed! */
1220 flush_res = fclose (fp);
1222 flush_res = fflush (fp);
1223 if (flush_res == EOF)
1226 FREE_MAYBE (all_headers);
1227 CLOSE_FINISH (sock);
1230 return RETRFINISHED;
1233 /* The genuine HTTP loop! This is the part where the retrieval is
1234 retried, and retried, and retried, and... */
1236 http_loop (struct urlinfo *u, char **newloc, int *dt)
1239 int use_ts, got_head = 0; /* time-stamping info */
1240 char *filename_plus_orig_suffix;
1241 char *local_filename = NULL;
1242 char *tms, *suf, *locf, *tmrate;
1244 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1245 long local_size = 0; /* the size of the local file */
1246 size_t filename_len;
1247 struct http_stat hstat; /* HTTP status */
1252 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1253 has_wildcards_p because it would also warn on `?', and we know that
1254 shows up in CGI paths a *lot*. */
1255 if (strchr (u->url, '*'))
1256 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1258 /* Determine the local filename. */
1260 u->local = url_filename (u->proxy ? u->proxy : u);
1262 if (!opt.output_document)
1265 locf = opt.output_document;
1267 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1268 xmalloc() here before EACH return. This is one reason it's better to set
1269 flags that influence flow control and then return once at the end. */
1270 filename_len = strlen(u->local);
1271 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1273 if (opt.noclobber && file_exists_p (u->local))
1275 /* If opt.noclobber is turned on and file already exists, do not
1276 retrieve the file */
1277 logprintf (LOG_VERBOSE, _("\
1278 File `%s' already there, will not retrieve.\n"), u->local);
1279 /* If the file is there, we suppose it's retrieved OK. */
1282 /* #### Bogusness alert. */
1283 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1284 text/html, a harmless lie. */
1285 if (((suf = suffix (u->local)) != NULL)
1286 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1289 xfree (filename_plus_orig_suffix); /* must precede every return! */
1290 /* Another harmless lie: */
1295 if (opt.timestamping)
1297 boolean local_dot_orig_file_exists = FALSE;
1299 if (opt.backup_converted)
1300 /* If -K is specified, we'll act on the assumption that it was specified
1301 last time these files were downloaded as well, and instead of just
1302 comparing local file X against server file X, we'll compare local
1303 file X.orig (if extant, else X) against server file X. If -K
1304 _wasn't_ specified last time, or the server contains files called
1305 *.orig, -N will be back to not operating correctly with -k. */
1307 /* Would a single s[n]printf() call be faster? --dan
1309 It wouldn't. sprintf() is horribly slow. At one point I
1310 profiled Wget, and found that a measurable and
1311 non-negligible amount of time was lost calling sprintf()
1312 in url.c. Replacing sprintf with inline calls to
1313 strcpy() and long_to_string() made a difference.
1315 strcpy(filename_plus_orig_suffix, u->local);
1316 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1318 /* Try to stat() the .orig file. */
1319 if (stat(filename_plus_orig_suffix, &st) == 0)
1321 local_dot_orig_file_exists = TRUE;
1322 local_filename = filename_plus_orig_suffix;
1326 if (!local_dot_orig_file_exists)
1327 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1328 if (stat (u->local, &st) == 0)
1329 local_filename = u->local;
1331 if (local_filename != NULL)
1332 /* There was a local file, so we'll check later to see if the version
1333 the server has is the same version we already have, allowing us to
1338 local_size = st.st_size;
1342 /* Reset the counter. */
1344 *dt = 0 | ACCEPTRANGES;
1348 /* Increment the pass counter. */
1350 sleep_between_retrievals (count);
1351 /* Get the current time string. */
1352 tms = time_str (NULL);
1353 /* Print fetch message, if opt.verbose. */
1356 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1360 sprintf (tmp, _("(try:%2d)"), count);
1361 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1362 tms, hurl, tmp, locf);
1364 ws_changetitle (hurl, 1);
1369 /* Default document type is empty. However, if spider mode is
1370 on or time-stamping is employed, HEAD_ONLY commands is
1371 encoded within *dt. */
1372 if (opt.spider || (use_ts && !got_head))
1376 /* Assume no restarting. */
1378 /* Decide whether or not to restart. */
1379 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1380 && file_exists_p (u->local))
1381 if (stat (u->local, &st) == 0)
1382 hstat.restval = st.st_size;
1383 /* Decide whether to send the no-cache directive. */
1384 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1385 *dt |= SEND_NOCACHE;
1387 *dt &= ~SEND_NOCACHE;
1389 /* Try fetching the document, or at least its head. :-) */
1390 err = gethttp (u, &hstat, dt);
1392 /* It's unfortunate that wget determines the local filename before finding
1393 out the Content-Type of the file. Barring a major restructuring of the
1394 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1395 u->local to tack on ".html". */
1396 if (!opt.output_document)
1399 locf = opt.output_document;
1402 tms = time_str (NULL);
1403 /* Get the new location (with or without the redirection). */
1405 *newloc = xstrdup (hstat.newloc);
1408 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1409 case CONERROR: case READERR: case WRITEFAILED:
1411 /* Non-fatal errors continue executing the loop, which will
1412 bring them to "while" statement at the end, to judge
1413 whether the number of tries was exceeded. */
1415 printwhat (count, opt.ntry);
1418 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1419 /* Fatal errors just return from the function. */
1421 xfree (filename_plus_orig_suffix); /* must precede every return! */
1424 case FWRITEERR: case FOPENERR:
1425 /* Another fatal error. */
1426 logputs (LOG_VERBOSE, "\n");
1427 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1428 u->local, strerror (errno));
1433 /* Another fatal error. */
1434 logputs (LOG_VERBOSE, "\n");
1435 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1437 xfree (filename_plus_orig_suffix); /* must precede every return! */
1441 /* Return the new location to the caller. */
1444 logprintf (LOG_NOTQUIET,
1445 _("ERROR: Redirection (%d) without location.\n"),
1447 xfree (filename_plus_orig_suffix); /* must precede every return! */
1451 xfree (filename_plus_orig_suffix); /* must precede every return! */
1455 /* Deal with you later. */
1458 /* All possibilities should have been exhausted. */
1461 if (!(*dt & RETROKF))
1465 /* #### Ugly ugly ugly! */
1466 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1467 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1470 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1471 tms, hstat.statcode, hstat.error);
1472 logputs (LOG_VERBOSE, "\n");
1474 xfree (filename_plus_orig_suffix); /* must precede every return! */
1478 /* Did we get the time-stamp? */
1481 if (opt.timestamping && !hstat.remote_time)
1483 logputs (LOG_NOTQUIET, _("\
1484 Last-modified header missing -- time-stamps turned off.\n"));
1486 else if (hstat.remote_time)
1488 /* Convert the date-string into struct tm. */
1489 tmr = http_atotm (hstat.remote_time);
1490 if (tmr == (time_t) (-1))
1491 logputs (LOG_VERBOSE, _("\
1492 Last-modified header invalid -- time-stamp ignored.\n"));
1496 /* The time-stamping section. */
1501 use_ts = 0; /* no more time-stamping */
1502 count = 0; /* the retrieve count for HEAD is
1504 if (hstat.remote_time && tmr != (time_t) (-1))
1506 /* Now time-stamping can be used validly. Time-stamping
1507 means that if the sizes of the local and remote file
1508 match, and local file is newer than the remote file,
1509 it will not be retrieved. Otherwise, the normal
1510 download procedure is resumed. */
1512 (hstat.contlen == -1 || local_size == hstat.contlen))
1514 logprintf (LOG_VERBOSE, _("\
1515 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1518 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1521 else if (tml >= tmr)
1522 logprintf (LOG_VERBOSE, _("\
1523 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1525 logputs (LOG_VERBOSE,
1526 _("Remote file is newer, retrieving.\n"));
1531 if ((tmr != (time_t) (-1))
1533 && ((hstat.len == hstat.contlen) ||
1534 ((hstat.res == 0) &&
1535 ((hstat.contlen == -1) ||
1536 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1538 /* #### This code repeats in http.c and ftp.c. Move it to a
1540 const char *fl = NULL;
1541 if (opt.output_document)
1543 if (opt.od_known_regular)
1544 fl = opt.output_document;
1551 /* End of time-stamping section. */
1555 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1556 xfree (filename_plus_orig_suffix); /* must precede every return! */
1560 /* It is now safe to free the remainder of hstat, since the
1561 strings within it will no longer be used. */
1564 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1566 if (hstat.len == hstat.contlen)
1570 logprintf (LOG_VERBOSE,
1571 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1572 tms, tmrate, locf, hstat.len, hstat.contlen);
1573 logprintf (LOG_NONVERBOSE,
1574 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1575 tms, u->url, hstat.len, hstat.contlen, locf, count);
1578 downloaded_increase (hstat.len);
1580 /* Remember that we downloaded the file for later ".orig" code. */
1581 if (*dt & ADDED_HTML_EXTENSION)
1582 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1584 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1586 xfree(filename_plus_orig_suffix); /* must precede every return! */
1589 else if (hstat.res == 0) /* No read error */
1591 if (hstat.contlen == -1) /* We don't know how much we were supposed
1592 to get, so assume we succeeded. */
1596 logprintf (LOG_VERBOSE,
1597 _("%s (%s) - `%s' saved [%ld]\n\n"),
1598 tms, tmrate, locf, hstat.len);
1599 logprintf (LOG_NONVERBOSE,
1600 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1601 tms, u->url, hstat.len, locf, count);
1604 downloaded_increase (hstat.len);
1606 /* Remember that we downloaded the file for later ".orig" code. */
1607 if (*dt & ADDED_HTML_EXTENSION)
1608 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1610 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1612 xfree (filename_plus_orig_suffix); /* must precede every return! */
1615 else if (hstat.len < hstat.contlen) /* meaning we lost the
1616 connection too soon */
1618 logprintf (LOG_VERBOSE,
1619 _("%s (%s) - Connection closed at byte %ld. "),
1620 tms, tmrate, hstat.len);
1621 printwhat (count, opt.ntry);
1624 else if (!opt.kill_longer) /* meaning we got more than expected */
1626 logprintf (LOG_VERBOSE,
1627 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1628 tms, tmrate, locf, hstat.len, hstat.contlen);
1629 logprintf (LOG_NONVERBOSE,
1630 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1631 tms, u->url, hstat.len, hstat.contlen, locf, count);
1633 downloaded_increase (hstat.len);
1635 /* Remember that we downloaded the file for later ".orig" code. */
1636 if (*dt & ADDED_HTML_EXTENSION)
1637 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1639 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1641 xfree (filename_plus_orig_suffix); /* must precede every return! */
1644 else /* the same, but not accepted */
1646 logprintf (LOG_VERBOSE,
1647 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1648 tms, tmrate, hstat.len, hstat.contlen);
1649 printwhat (count, opt.ntry);
1653 else /* now hstat.res can only be -1 */
1655 if (hstat.contlen == -1)
1657 logprintf (LOG_VERBOSE,
1658 _("%s (%s) - Read error at byte %ld (%s)."),
1659 tms, tmrate, hstat.len, strerror (errno));
1660 printwhat (count, opt.ntry);
1663 else /* hstat.res == -1 and contlen is given */
1665 logprintf (LOG_VERBOSE,
1666 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1667 tms, tmrate, hstat.len, hstat.contlen,
1669 printwhat (count, opt.ntry);
1676 while (!opt.ntry || (count < opt.ntry));
1677 xfree (filename_plus_orig_suffix); /* must precede every return! */
1681 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1682 than local timezone (mktime assumes the latter).
1684 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1685 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1687 mktime_from_utc (struct tm *t)
1694 tb = mktime (gmtime (&tl));
1695 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1698 /* Check whether the result of strptime() indicates success.
1699 strptime() returns the pointer to how far it got to in the string.
1700 The processing has been successful if the string is at `GMT' or
1701 `+X', or at the end of the string.
1703 In extended regexp parlance, the function returns 1 if P matches
1704 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1705 strptime()) is considered a failure and 0 is returned. */
1707 check_end (const char *p)
1711 while (ISSPACE (*p))
1714 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1715 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1721 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1722 the three formats RFC2068 allows the HTTP servers to emit --
1723 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1726 We use strptime() to recognize various dates, which makes it a
1727 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1728 allows shortened dates and months, one-digit days, etc.). It also
1729 allows more than one space anywhere where the specs require one SP.
1730 The routine should probably be even more forgiving (as recommended
1731 by RFC2068), but I do not have the time to write one.
1733 Return the computed time_t representation, or -1 if all the
1736 Needless to say, what we *really* need here is something like
1737 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1738 and does not use strptime(). atotm() is to be found in the sources
1739 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1741 http_atotm (char *time_string)
1745 /* Roger Beeman says: "This function dynamically allocates struct tm
1746 t, but does no initialization. The only field that actually
1747 needs initialization is tm_isdst, since the others will be set by
1748 strptime. Since strptime does not set tm_isdst, it will return
1749 the data structure with whatever data was in tm_isdst to begin
1750 with. For those of us in timezones where DST can occur, there
1751 can be a one hour shift depending on the previous contents of the
1752 data area where the data structure is allocated." */
1755 /* Note that under foreign locales Solaris strptime() fails to
1756 recognize English dates, which renders this function useless. I
1757 assume that other non-GNU strptime's are plagued by the same
1758 disease. We solve this by setting only LC_MESSAGES in
1759 i18n_initialize(), instead of LC_ALL.
1761 Another solution could be to temporarily set locale to C, invoke
1762 strptime(), and restore it back. This is slow and dirty,
1763 however, and locale support other than LC_MESSAGES can mess other
1764 things, so I rather chose to stick with just setting LC_MESSAGES.
1766 Also note that none of this is necessary under GNU strptime(),
1767 because it recognizes both international and local dates. */
1769 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1770 it to eat all white space up to (and including) a newline, and
1771 the function fails if there is no newline (!).
1773 Let's hope all strptime() implementations use ` ' to skip *all*
1774 whitespace instead of just one (it works that way on all the
1775 systems I've tested it on). */
1777 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1778 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1779 return mktime_from_utc (&t);
1780 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1781 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1782 return mktime_from_utc (&t);
1783 /* asctime: Thu Jan 29 22:12:57 1998 */
1784 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1785 return mktime_from_utc (&t);
1790 /* Authorization support: We support two authorization schemes:
1792 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1794 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1795 consisting of answering to the server's challenge with the proper
1798 /* How many bytes it will take to store LEN bytes in base64. */
1799 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1801 /* Encode the string S of length LENGTH to base64 format and place it
1802 to STORE. STORE will be 0-terminated, and must point to a writable
1803 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1805 base64_encode (const char *s, char *store, int length)
1807 /* Conversion table. */
1808 static char tbl[64] = {
1809 'A','B','C','D','E','F','G','H',
1810 'I','J','K','L','M','N','O','P',
1811 'Q','R','S','T','U','V','W','X',
1812 'Y','Z','a','b','c','d','e','f',
1813 'g','h','i','j','k','l','m','n',
1814 'o','p','q','r','s','t','u','v',
1815 'w','x','y','z','0','1','2','3',
1816 '4','5','6','7','8','9','+','/'
1819 unsigned char *p = (unsigned char *)store;
1821 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1822 for (i = 0; i < length; i += 3)
1824 *p++ = tbl[s[0] >> 2];
1825 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1826 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1827 *p++ = tbl[s[2] & 0x3f];
1830 /* Pad the result if necessary... */
1831 if (i == length + 1)
1833 else if (i == length + 2)
1834 *(p - 1) = *(p - 2) = '=';
1835 /* ...and zero-terminate it. */
1839 /* Create the authentication header contents for the `Basic' scheme.
1840 This is done by encoding the string `USER:PASS' in base64 and
1841 prepending `HEADER: Basic ' to it. */
1843 basic_authentication_encode (const char *user, const char *passwd,
1846 char *t1, *t2, *res;
1847 int len1 = strlen (user) + 1 + strlen (passwd);
1848 int len2 = BASE64_LENGTH (len1);
1850 t1 = (char *)alloca (len1 + 1);
1851 sprintf (t1, "%s:%s", user, passwd);
1852 t2 = (char *)alloca (1 + len2);
1853 base64_encode (t1, t2, len1);
1854 res = (char *)malloc (len2 + 11 + strlen (header));
1855 sprintf (res, "%s: Basic %s\r\n", header, t2);
1861 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1862 of a field in such a header. If the field is the one specified by
1863 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1864 digest authorization code), extract its value in the (char*)
1865 variable pointed by RET. Returns negative on a malformed header,
1866 or number of bytes that have been parsed by this call. */
1868 extract_header_attr (const char *au, const char *attr_name, char **ret)
1870 const char *cp, *ep;
1874 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1876 cp += strlen (attr_name);
1879 cp += skip_lws (cp);
1884 cp += skip_lws (cp);
1889 for (ep = cp; *ep && *ep != '\"'; ep++)
1894 *ret = strdupdelim (cp, ep);
1901 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1902 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1903 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1905 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1906 an array of 16 bytes containing the hash keys, and BUF should be a
1907 buffer of 33 writable characters (32 for hex digits plus one for
1908 zero termination). */
1910 dump_hash (unsigned char *buf, const unsigned char *hash)
1914 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1916 *buf++ = HEXD2asc (*hash >> 4);
1917 *buf++ = HEXD2asc (*hash & 0xf);
1922 /* Take the line apart to find the challenge, and compose a digest
1923 authorization header. See RFC2069 section 2.1.2. */
1925 digest_authentication_encode (const char *au, const char *user,
1926 const char *passwd, const char *method,
1929 static char *realm, *opaque, *nonce;
1934 { "realm", &realm },
1935 { "opaque", &opaque },
1940 realm = opaque = nonce = NULL;
1942 au += 6; /* skip over `Digest' */
1947 au += skip_lws (au);
1948 for (i = 0; i < ARRAY_SIZE (options); i++)
1950 int skip = extract_header_attr (au, options[i].name,
1951 options[i].variable);
1955 FREE_MAYBE (opaque);
1965 if (i == ARRAY_SIZE (options))
1967 while (*au && *au != '=')
1971 au += skip_lws (au);
1975 while (*au && *au != '\"')
1982 while (*au && *au != ',')
1987 if (!realm || !nonce || !user || !passwd || !path || !method)
1990 FREE_MAYBE (opaque);
1995 /* Calculate the digest value. */
1998 unsigned char hash[MD5_HASHLEN];
1999 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2000 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2002 /* A1BUF = H(user ":" realm ":" password) */
2003 md5_init_ctx (&ctx);
2004 md5_process_bytes (user, strlen (user), &ctx);
2005 md5_process_bytes (":", 1, &ctx);
2006 md5_process_bytes (realm, strlen (realm), &ctx);
2007 md5_process_bytes (":", 1, &ctx);
2008 md5_process_bytes (passwd, strlen (passwd), &ctx);
2009 md5_finish_ctx (&ctx, hash);
2010 dump_hash (a1buf, hash);
2012 /* A2BUF = H(method ":" path) */
2013 md5_init_ctx (&ctx);
2014 md5_process_bytes (method, strlen (method), &ctx);
2015 md5_process_bytes (":", 1, &ctx);
2016 md5_process_bytes (path, strlen (path), &ctx);
2017 md5_finish_ctx (&ctx, hash);
2018 dump_hash (a2buf, hash);
2020 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2021 md5_init_ctx (&ctx);
2022 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2023 md5_process_bytes (":", 1, &ctx);
2024 md5_process_bytes (nonce, strlen (nonce), &ctx);
2025 md5_process_bytes (":", 1, &ctx);
2026 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2027 md5_finish_ctx (&ctx, hash);
2028 dump_hash (response_digest, hash);
2030 res = (char*) xmalloc (strlen (user)
2035 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2036 + (opaque ? strlen (opaque) : 0)
2038 sprintf (res, "Authorization: Digest \
2039 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2040 user, realm, nonce, path, response_digest);
2043 char *p = res + strlen (res);
2044 strcat (p, ", opaque=\"");
2048 strcat (res, "\r\n");
2052 #endif /* USE_DIGEST */
2055 #define BEGINS_WITH(line, string_constant) \
2056 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2057 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2058 || !line[sizeof (string_constant) - 1]))
2061 known_authentication_scheme_p (const char *au)
2063 return BEGINS_WITH (au, "Basic")
2064 || BEGINS_WITH (au, "Digest")
2065 || BEGINS_WITH (au, "NTLM");
2070 /* Create the HTTP authorization request header. When the
2071 `WWW-Authenticate' response header is seen, according to the
2072 authorization scheme specified in that header (`Basic' and `Digest'
2073 are supported by the current implementation), produce an
2074 appropriate HTTP authorization request header. */
2076 create_authorization_line (const char *au, const char *user,
2077 const char *passwd, const char *method,
2080 char *wwwauth = NULL;
2082 if (!strncasecmp (au, "Basic", 5))
2083 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2084 if (!strncasecmp (au, "NTLM", 4))
2085 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2087 else if (!strncasecmp (au, "Digest", 6))
2088 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2089 #endif /* USE_DIGEST */