2 Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
4 This file is part of Wget.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
24 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
48 #include "gen_sslfunc.h"
69 extern char *version_string;
79 #define TEXTHTML_S "text/html"
80 #define HTTP_ACCEPT "*/*"
82 /* Some status code validation macros: */
83 #define H_20X(x) (((x) >= 200) && ((x) < 300))
84 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
85 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
86 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
88 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
90 #define HTTP_STATUS_OK 200
91 #define HTTP_STATUS_CREATED 201
92 #define HTTP_STATUS_ACCEPTED 202
93 #define HTTP_STATUS_NO_CONTENT 204
94 #define HTTP_STATUS_PARTIAL_CONTENTS 206
96 /* Redirection 3xx. */
97 #define HTTP_STATUS_MULTIPLE_CHOICES 300
98 #define HTTP_STATUS_MOVED_PERMANENTLY 301
99 #define HTTP_STATUS_MOVED_TEMPORARILY 302
100 #define HTTP_STATUS_NOT_MODIFIED 304
102 /* Client error 4xx. */
103 #define HTTP_STATUS_BAD_REQUEST 400
104 #define HTTP_STATUS_UNAUTHORIZED 401
105 #define HTTP_STATUS_FORBIDDEN 403
106 #define HTTP_STATUS_NOT_FOUND 404
108 /* Server errors 5xx. */
109 #define HTTP_STATUS_INTERNAL 500
110 #define HTTP_STATUS_NOT_IMPLEMENTED 501
111 #define HTTP_STATUS_BAD_GATEWAY 502
112 #define HTTP_STATUS_UNAVAILABLE 503
115 /* Parse the HTTP status line, which is of format:
117 HTTP-Version SP Status-Code SP Reason-Phrase
119 The function returns the status-code, or -1 if the status line is
120 malformed. The pointer to reason-phrase is returned in RP. */
122 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
124 /* (the variables must not be named `major' and `minor', because
125 that breaks compilation with SunOS4 cc.) */
126 int mjr, mnr, statcode;
129 *reason_phrase_ptr = NULL;
131 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
132 major version, and Y is minor version. */
133 if (strncmp (line, "HTTP/", 5) != 0)
137 /* Calculate major HTTP version. */
139 for (mjr = 0; ISDIGIT (*line); line++)
140 mjr = 10 * mjr + (*line - '0');
141 if (*line != '.' || p == line)
145 /* Calculate minor HTTP version. */
147 for (mnr = 0; ISDIGIT (*line); line++)
148 mnr = 10 * mnr + (*line - '0');
149 if (*line != ' ' || p == line)
151 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
152 minor version can be safely ignored. */
157 /* Calculate status code. */
158 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
160 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
162 /* Set up the reason phrase pointer. */
164 /* RFC2068 requires SPC here, but we allow the string to finish
165 here, in case no reason-phrase is present. */
169 *reason_phrase_ptr = line;
174 *reason_phrase_ptr = line + 1;
179 /* Functions to be used as arguments to header_process(): */
181 struct http_process_range_closure {
187 /* Parse the `Content-Range' header and extract the information it
188 contains. Returns 1 if successful, -1 otherwise. */
190 http_process_range (const char *hdr, void *arg)
192 struct http_process_range_closure *closure
193 = (struct http_process_range_closure *)arg;
196 /* Certain versions of Nutscape proxy server send out
197 `Content-Length' without "bytes" specifier, which is a breach of
198 RFC2068 (as well as the HTTP/1.1 draft which was current at the
199 time). But hell, I must support it... */
200 if (!strncasecmp (hdr, "bytes", 5))
203 hdr += skip_lws (hdr);
209 for (num = 0; ISDIGIT (*hdr); hdr++)
210 num = 10 * num + (*hdr - '0');
211 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
213 closure->first_byte_pos = num;
215 for (num = 0; ISDIGIT (*hdr); hdr++)
216 num = 10 * num + (*hdr - '0');
217 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
219 closure->last_byte_pos = num;
221 for (num = 0; ISDIGIT (*hdr); hdr++)
222 num = 10 * num + (*hdr - '0');
223 closure->entity_length = num;
227 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
228 Used for `Accept-Ranges'. */
230 http_process_none (const char *hdr, void *arg)
232 int *where = (int *)arg;
234 if (strstr (hdr, "none"))
241 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
243 http_process_type (const char *hdr, void *arg)
245 char **result = (char **)arg;
246 /* Locate P on `;' or the terminating zero, whichever comes first. */
247 const char *p = strchr (hdr, ';');
249 p = hdr + strlen (hdr);
250 while (p > hdr && ISSPACE (*(p - 1)))
252 *result = strdupdelim (hdr, p);
256 /* Check whether the `Connection' header is set to "keep-alive". */
258 http_process_connection (const char *hdr, void *arg)
260 int *flag = (int *)arg;
261 if (!strcasecmp (hdr, "Keep-Alive"))
266 /* Persistent connections. Currently, we cache the most recently used
267 connection as persistent, provided that the HTTP server agrees to
268 make it such. The persistence data is stored in the variables
269 below. Ideally, it would be in a structure, and it should be
270 possible to cache an arbitrary fixed number of these connections.
272 I think the code is quite easy to extend in that direction. */
274 /* Whether a persistent connection is active. */
275 static int pc_active_p;
276 /* Host and port of currently active persistent connection. */
277 static unsigned char pc_last_host[4];
278 static unsigned short pc_last_port;
280 /* File descriptor of the currently active persistent connection. */
281 static int pc_last_fd;
284 /* Whether a ssl handshake has occoured on this connection */
285 static int pc_active_ssl;
286 /* SSL connection of the currently active persistent connection. */
287 static SSL *pc_last_ssl;
288 #endif /* HAVE_SSL */
290 /* Mark the persistent connection as invalid. This is used by the
291 CLOSE_* macros after they forcefully close a registered persistent
292 connection. This does not close the file descriptor -- it is left
293 to the caller to do that. (Maybe it should, though.) */
296 invalidate_persistent (void)
301 #endif /* HAVE_SSL */
302 DEBUGP (("Invalidating fd %d from further reuse.\n", pc_last_fd));
305 /* Register FD, which should be a TCP/IP connection to HOST:PORT, as
306 persistent. This will enable someone to use the same connection
307 later. In the context of HTTP, this must be called only AFTER the
308 response has been received and the server has promised that the
309 connection will remain alive.
311 If a previous connection was persistent, it is closed. */
314 register_persistent (const char *host, unsigned short port, int fd
324 if (pc_last_fd == fd)
326 /* The connection FD is already registered. Nothing to
332 /* The old persistent connection is still active; let's
333 close it first. This situation arises whenever a
334 persistent connection exists, but we then connect to a
335 different host, and try to register a persistent
336 connection to that one. */
338 /* The ssl disconnect has to take place before the closing
341 shutdown_ssl(pc_last_ssl);
344 invalidate_persistent ();
348 /* This store_hostaddress may not fail, because it has the results
350 success = store_hostaddress (pc_last_host, host);
357 pc_active_ssl = ssl ? 1 : 0;
359 DEBUGP (("Registered fd %d for persistent reuse.\n", fd));
362 /* Return non-zero if a persistent connection is available for
363 connecting to HOST:PORT. */
366 persistent_available_p (const char *host, unsigned short port
372 unsigned char this_host[4];
373 /* First, check whether a persistent connection is active at all. */
376 /* Second, check if the active connection pertains to the correct
377 (HOST, PORT) ordered pair. */
378 if (port != pc_last_port)
381 /* Second, a): check if current connection is (not) ssl, too. This
382 test is unlikely to fail because HTTP and HTTPS typicaly use
383 different ports. Yet it is possible, or so I [Christian
384 Fraenkel] have been told, to run HTTPS and HTTP simultaneus on
386 if (ssl != pc_active_ssl)
388 #endif /* HAVE_SSL */
389 if (!store_hostaddress (this_host, host))
391 if (memcmp (pc_last_host, this_host, 4))
393 /* Third: check whether the connection is still open. This is
394 important because most server implement a liberal (short) timeout
395 on persistent connections. Wget can of course always reconnect
396 if the connection doesn't work out, but it's nicer to know in
397 advance. This test is a logical followup of the first test, but
398 is "expensive" and therefore placed at the end of the list. */
399 if (!test_socket_open (pc_last_fd))
401 /* Oops, the socket is no longer open. Now that we know that,
402 let's invalidate the persistent connection before returning
405 invalidate_persistent ();
412 # define SHUTDOWN_SSL(ssl) do { \
414 shutdown_ssl (ssl); \
417 # define SHUTDOWN_SSL(ssl)
420 /* The idea behind these two CLOSE macros is to distinguish between
421 two cases: one when the job we've been doing is finished, and we
422 want to close the connection and leave, and two when something is
423 seriously wrong and we're closing the connection as part of
426 In case of keep_alive, CLOSE_FINISH should leave the connection
427 open, while CLOSE_INVALIDATE should still close it.
429 Note that the semantics of the flag `keep_alive' is "this
430 connection *will* be reused (the server has promised not to close
431 the connection once we're done)", while the semantics of
432 `pc_active_p && (fd) == pc_last_fd' is "we're *now* using an
433 active, registered connection". */
435 #define CLOSE_FINISH(fd) do { \
438 SHUTDOWN_SSL (ssl); \
440 if (pc_active_p && (fd) == pc_last_fd) \
441 invalidate_persistent (); \
445 #define CLOSE_INVALIDATE(fd) do { \
446 SHUTDOWN_SSL (ssl); \
448 if (pc_active_p && (fd) == pc_last_fd) \
449 invalidate_persistent (); \
454 long len; /* received length */
455 long contlen; /* expected length */
456 long restval; /* the restart value */
457 int res; /* the result of last read */
458 char *newloc; /* new location (redirection) */
459 char *remote_time; /* remote time-stamp string */
460 char *error; /* textual HTTP error */
461 int statcode; /* status code */
462 long dltime; /* time of the download */
465 /* Free the elements of hstat X. */
466 #define FREEHSTAT(x) do \
468 FREE_MAYBE ((x).newloc); \
469 FREE_MAYBE ((x).remote_time); \
470 FREE_MAYBE ((x).error); \
471 (x).newloc = (x).remote_time = (x).error = NULL; \
474 static char *create_authorization_line PARAMS ((const char *, const char *,
475 const char *, const char *,
477 static char *basic_authentication_encode PARAMS ((const char *, const char *,
479 static int known_authentication_scheme_p PARAMS ((const char *));
481 static time_t http_atotm PARAMS ((char *));
483 #define BEGINS_WITH(line, string_constant) \
484 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
485 && (ISSPACE (line[sizeof (string_constant) - 1]) \
486 || !line[sizeof (string_constant) - 1]))
488 /* Retrieve a document through HTTP protocol. It recognizes status
489 code, and correctly handles redirections. It closes the network
490 socket. If it receives an error from the functions below it, it
491 will print it if there is enough information to do so (almost
492 always), returning the error to the caller (i.e. http_loop).
494 Various HTTP parameters are stored to hs. Although it parses the
495 response code correctly, it is not used in a sane way. The caller
498 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
499 and u->proxy->url will be given to the proxy server (bad naming,
502 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
504 char *request, *type, *command, *path;
506 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
507 char *authenticate_h;
511 char *request_keep_alive;
512 int sock, hcount, num_written, all_length, remport, statcode;
513 long contlen, contrange;
517 int auth_tried_already;
520 static SSL_CTX *ssl_ctx = NULL;
522 #endif /* HAVE_SSL */
524 /* Whether this connection will be kept alive after the HTTP request
528 /* Flags that detect the two ways of specifying HTTP keep-alive
530 int http_keep_alive_1, http_keep_alive_2;
532 /* Whether keep-alive should be inhibited. */
533 int inhibit_keep_alive;
536 /* initialize ssl_ctx on first run */
539 #endif /* HAVE_SSL */
541 if (!(*dt & HEAD_ONLY))
542 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
543 know the local filename so we can save to it. */
544 assert (u->local != NULL);
547 auth_tried_already = 0;
549 inhibit_keep_alive = (!opt.http_keep_alive || u->proxy != NULL);
552 /* We need to come back here when the initial attempt to retrieve
553 without authorization header fails. (Expected to happen at least
554 for the Digest authorization scheme.) */
557 http_keep_alive_1 = http_keep_alive_2 = 0;
559 /* Initialize certain elements of struct http_stat. */
564 hs->remote_time = NULL;
567 /* Which structure to use to retrieve the original URL data. */
573 /* First: establish the connection. */
574 if (inhibit_keep_alive
577 !persistent_available_p (u->host, u->port)
579 !persistent_available_p (u->host, u->port, (u->proto==URLHTTPS ? 1 : 0))
580 #endif /* HAVE_SSL */
583 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
584 err = make_connection (&sock, u->host, u->port);
588 logputs (LOG_VERBOSE, "\n");
589 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
593 logputs (LOG_VERBOSE, "\n");
594 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
598 logputs (LOG_VERBOSE, "\n");
599 logprintf (LOG_NOTQUIET,
600 _("Connection to %s:%hu refused.\n"), u->host, u->port);
604 logputs (LOG_VERBOSE, "\n");
605 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
610 /* Everything is fine! */
611 logputs (LOG_VERBOSE, _("connected!\n"));
618 if (u->proto == URLHTTPS)
619 if (connect_ssl (&ssl, ssl_ctx,sock) != 0)
621 logputs (LOG_VERBOSE, "\n");
622 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
626 #endif /* HAVE_SSL */
630 logprintf (LOG_VERBOSE, _("Reusing connection to %s:%hu.\n"), u->host, u->port);
631 /* #### pc_last_fd should be accessed through an accessor
636 #endif /* HAVE_SSL */
637 DEBUGP (("Reusing fd %d.\n", sock));
641 path = u->proxy->url;
645 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
649 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
650 sprintf (referer, "Referer: %s\r\n", ou->referer);
652 if (*dt & SEND_NOCACHE)
653 pragma_h = "Pragma: no-cache\r\n";
658 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
659 /* Gag me! Some servers (e.g. WebSitePro) have been known to
660 respond to the following `Range' format by generating a
661 multipart/x-byte-ranges MIME document! This MIME type was
662 present in an old draft of the byteranges specification.
663 HTTP/1.1 specifies a multipart/byte-ranges MIME type, but
664 only if multiple non-overlapping ranges are requested --
665 which Wget never does. */
666 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
671 STRDUP_ALLOCA (useragent, opt.useragent);
674 useragent = (char *)alloca (10 + strlen (version_string));
675 sprintf (useragent, "Wget/%s", version_string);
677 /* Construct the authentication, if userid is present. */
680 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
681 user = user ? user : opt.http_user;
682 passwd = passwd ? passwd : opt.http_passwd;
689 /* We have the username and the password, but haven't tried
690 any authorization yet. Let's see if the "Basic" method
691 works. If not, we'll come back here and construct a
692 proper authorization method with the right challenges.
694 If we didn't employ this kind of logic, every URL that
695 requires authorization would have to be processed twice,
696 which is very suboptimal and generates a bunch of false
697 "unauthorized" errors in the server log.
699 #### But this logic also has a serious problem when used
700 with stronger authentications: we *first* transmit the
701 username and the password in clear text, and *then*
702 attempt a stronger authentication scheme. That cannot be
703 right! We are only fortunate that almost everyone still
704 uses the `Basic' scheme anyway.
706 There should be an option to prevent this from happening,
707 for those who use strong authentication schemes and value
709 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
713 wwwauth = create_authorization_line (authenticate_h, user, passwd,
721 char *proxy_user, *proxy_passwd;
722 /* For normal username and password, URL components override
723 command-line/wgetrc parameters. With proxy authentication,
724 it's the reverse, because proxy URLs are normally the
725 "permanent" ones, so command-line args should take
727 if (opt.proxy_user && opt.proxy_passwd)
729 proxy_user = opt.proxy_user;
730 proxy_passwd = opt.proxy_passwd;
734 proxy_user = u->user;
735 proxy_passwd = u->passwd;
737 /* #### This is junky. Can't the proxy request, say, `Digest'
739 if (proxy_user && proxy_passwd)
740 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
741 "Proxy-Authorization");
746 /* String of the form :PORT. Used only for non-standard ports. */
750 port_maybe = (char *)alloca (numdigit (remport) + 2);
751 sprintf (port_maybe, ":%d", remport);
754 if (!inhibit_keep_alive)
755 request_keep_alive = "Connection: Keep-Alive\r\n";
757 request_keep_alive = NULL;
759 /* Allocate the memory for the request. */
760 request = (char *)alloca (strlen (command) + strlen (path)
763 + (port_maybe ? strlen (port_maybe) : 0)
764 + strlen (HTTP_ACCEPT)
765 + (request_keep_alive
766 ? strlen (request_keep_alive) : 0)
767 + (referer ? strlen (referer) : 0)
768 + (wwwauth ? strlen (wwwauth) : 0)
769 + (proxyauth ? strlen (proxyauth) : 0)
770 + (range ? strlen (range) : 0)
772 + (opt.user_header ? strlen (opt.user_header) : 0)
774 /* Construct the request. */
781 command, path, useragent, remhost,
782 port_maybe ? port_maybe : "",
784 request_keep_alive ? request_keep_alive : "",
785 referer ? referer : "",
786 wwwauth ? wwwauth : "",
787 proxyauth ? proxyauth : "",
790 opt.user_header ? opt.user_header : "");
791 DEBUGP (("---request begin---\n%s---request end---\n", request));
792 /* Free the temporary memory. */
793 FREE_MAYBE (wwwauth);
794 FREE_MAYBE (proxyauth);
796 /* Send the request to server. */
798 if (u->proto == URLHTTPS)
799 num_written = ssl_iwrite (ssl, request, strlen (request));
801 #endif /* HAVE_SSL */
802 num_written = iwrite (sock, request, strlen (request));
806 logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
808 CLOSE_INVALIDATE (sock);
811 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
812 u->proxy ? "Proxy" : "HTTP");
813 contlen = contrange = -1;
818 /* Before reading anything, initialize the rbuf. */
819 rbuf_initialize (&rbuf, sock);
821 if (u->proto == URLHTTPS)
825 #endif /* HAVE_SSL */
828 /* Header-fetching loop. */
836 /* Get the header. */
837 status = header_get (&rbuf, &hdr,
838 /* Disallow continuations for status line. */
839 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
841 /* Check for errors. */
842 if (status == HG_EOF && *hdr)
844 /* This used to be an unconditional error, but that was
845 somewhat controversial, because of a large number of
846 broken CGI's that happily "forget" to send the second EOL
847 before closing the connection of a HEAD request.
849 So, the deal is to check whether the header is empty
850 (*hdr is zero if it is); if yes, it means that the
851 previous header was fully retrieved, and that -- most
852 probably -- the request is complete. "...be liberal in
853 what you accept." Oh boy. */
854 logputs (LOG_VERBOSE, "\n");
855 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
858 FREE_MAYBE (hs->newloc);
859 FREE_MAYBE (all_headers);
860 CLOSE_INVALIDATE (sock);
863 else if (status == HG_ERROR)
865 logputs (LOG_VERBOSE, "\n");
866 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
870 FREE_MAYBE (hs->newloc);
871 FREE_MAYBE (all_headers);
872 CLOSE_INVALIDATE (sock);
876 /* If the headers are to be saved to a file later, save them to
878 if (opt.save_headers)
880 int lh = strlen (hdr);
881 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
882 memcpy (all_headers + all_length, hdr, lh);
884 all_headers[all_length++] = '\n';
885 all_headers[all_length] = '\0';
888 /* Print the header if requested. */
889 if (opt.server_response && hcount != 1)
890 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
892 /* Check for status line. */
896 /* Parse the first line of server response. */
897 statcode = parse_http_status_line (hdr, &error);
898 hs->statcode = statcode;
899 /* Store the descriptive response. */
900 if (statcode == -1) /* malformed response */
902 /* A common reason for "malformed response" error is the
903 case when no data was actually received. Handle this
906 hs->error = xstrdup (_("No data received"));
908 hs->error = xstrdup (_("Malformed status line"));
913 hs->error = xstrdup (_("(no description)"));
915 hs->error = xstrdup (error);
922 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
927 /* Exit on empty header. */
934 /* Try getting content-length. */
935 if (contlen == -1 && !opt.ignore_length)
936 if (header_process (hdr, "Content-Length", header_extract_number,
939 /* Try getting content-type. */
941 if (header_process (hdr, "Content-Type", http_process_type, &type))
943 /* Try getting location. */
945 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
947 /* Try getting last-modified. */
948 if (!hs->remote_time)
949 if (header_process (hdr, "Last-Modified", header_strdup,
952 /* Try getting www-authentication. */
954 if (header_process (hdr, "WWW-Authenticate", header_strdup,
957 /* Check for accept-ranges header. If it contains the word
958 `none', disable the ranges. */
959 if (*dt & ACCEPTRANGES)
962 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
965 *dt &= ~ACCEPTRANGES;
969 /* Try getting content-range. */
972 struct http_process_range_closure closure;
973 if (header_process (hdr, "Content-Range", http_process_range, &closure))
975 contrange = closure.first_byte_pos;
979 /* Check for keep-alive related responses. */
980 if (!inhibit_keep_alive)
982 /* Check for the `Keep-Alive' header. */
983 if (!http_keep_alive_1)
985 if (header_process (hdr, "Keep-Alive", header_exists,
989 /* Check for `Connection: Keep-Alive'. */
990 if (!http_keep_alive_2)
992 if (header_process (hdr, "Connection", http_process_connection,
1001 logputs (LOG_VERBOSE, "\n");
1004 && (http_keep_alive_1 || http_keep_alive_2))
1006 assert (inhibit_keep_alive == 0);
1010 /* The server has promised that it will not close the connection
1011 when we're done. This means that we can register it. */
1013 register_persistent (u->host, u->port, sock);
1015 register_persistent (u->host, u->port, sock, ssl);
1016 #endif /* HAVE_SSL */
1018 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
1021 /* Authorization is required. */
1025 CLOSE_FINISH (sock);
1026 if (auth_tried_already)
1028 /* If we have tried it already, then there is not point
1031 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
1032 xfree (authenticate_h);
1035 else if (!known_authentication_scheme_p (authenticate_h))
1037 xfree (authenticate_h);
1038 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
1041 else if (BEGINS_WITH (authenticate_h, "Basic"))
1043 /* The authentication scheme is basic, the one we try by
1044 default, and it failed. There's no sense in trying
1050 auth_tried_already = 1;
1054 /* We do not need this anymore. */
1057 xfree (authenticate_h);
1058 authenticate_h = NULL;
1061 /* 20x responses are counted among successful by default. */
1062 if (H_20X (statcode))
1065 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
1068 /* We don't assume text/html by default. */
1071 if (opt.html_extension && (*dt & TEXTHTML))
1072 /* -E / --html-extension / html_extension = on was specified, and this is a
1073 text/html file. If some case-insensitive variation on ".htm[l]" isn't
1074 already the file's suffix, tack on ".html". */
1076 char* last_period_in_local_filename = strrchr(u->local, '.');
1078 if (last_period_in_local_filename == NULL ||
1079 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
1080 strcasecmp(last_period_in_local_filename, ".html") == EQ))
1082 size_t local_filename_len = strlen(u->local);
1084 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
1085 strcpy(u->local + local_filename_len, ".html");
1087 *dt |= ADDED_HTML_EXTENSION;
1091 if (contrange == -1)
1093 else if (contrange != hs->restval ||
1094 (H_PARTIAL (statcode) && contrange == -1))
1096 /* This means the whole request was somehow misunderstood by the
1097 server. Bail out. */
1099 FREE_MAYBE (hs->newloc);
1100 FREE_MAYBE (all_headers);
1101 CLOSE_INVALIDATE (sock);
1108 contlen += contrange;
1110 contrange = -1; /* If conent-length was not sent,
1111 content-range will be ignored. */
1113 hs->contlen = contlen;
1115 /* Return if redirected. */
1116 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
1118 /* RFC2068 says that in case of the 300 (multiple choices)
1119 response, the server can output a preferred URL through
1120 `Location' header; otherwise, the request should be treated
1121 like GET. So, if the location is set, it will be a
1122 redirection; otherwise, just proceed normally. */
1123 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
1127 logprintf (LOG_VERBOSE,
1128 _("Location: %s%s\n"),
1129 hs->newloc ? hs->newloc : _("unspecified"),
1130 hs->newloc ? _(" [following]") : "");
1131 CLOSE_FINISH (sock);
1133 FREE_MAYBE (all_headers);
1139 if ((*dt & RETROKF) && !opt.server_response)
1141 /* No need to print this output if the body won't be
1142 downloaded at all, or if the original server response is
1144 logputs (LOG_VERBOSE, _("Length: "));
1147 logputs (LOG_VERBOSE, legible (contlen));
1148 if (contrange != -1)
1149 logprintf (LOG_VERBOSE, _(" (%s to go)"),
1150 legible (contlen - contrange));
1153 logputs (LOG_VERBOSE,
1154 opt.ignore_length ? _("ignored") : _("unspecified"));
1156 logprintf (LOG_VERBOSE, " [%s]\n", type);
1158 logputs (LOG_VERBOSE, "\n");
1162 type = NULL; /* We don't need it any more. */
1164 /* Return if we have no intention of further downloading. */
1165 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
1167 /* In case someone cares to look... */
1171 FREE_MAYBE (all_headers);
1172 CLOSE_FINISH (sock);
1173 return RETRFINISHED;
1176 /* Open the local file. */
1179 mkalldirs (u->local);
1181 rotate_backups (u->local);
1182 fp = fopen (u->local, hs->restval ? "ab" : "wb");
1185 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
1186 CLOSE_FINISH (sock);
1187 FREE_MAYBE (all_headers);
1196 /* This will silently fail for streams that don't correspond
1197 to regular files, but that's OK. */
1203 /* #### This confuses the code that checks for file size. There
1204 should be some overhead information. */
1205 if (opt.save_headers)
1206 fwrite (all_headers, 1, all_length, fp);
1208 /* Get the contents of the document. */
1209 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
1210 (contlen != -1 ? contlen : 0),
1212 hs->dltime = elapsed_time ();
1214 /* Close or flush the file. We have to be careful to check for
1215 error here. Checking the result of fwrite() is not enough --
1216 errors could go unnoticed! */
1219 flush_res = fclose (fp);
1221 flush_res = fflush (fp);
1222 if (flush_res == EOF)
1225 FREE_MAYBE (all_headers);
1226 CLOSE_FINISH (sock);
1229 return RETRFINISHED;
1232 /* The genuine HTTP loop! This is the part where the retrieval is
1233 retried, and retried, and retried, and... */
1235 http_loop (struct urlinfo *u, char **newloc, int *dt)
1237 static int first_retrieval = 1;
1240 int use_ts, got_head = 0; /* time-stamping info */
1241 char *filename_plus_orig_suffix;
1242 char *local_filename = NULL;
1243 char *tms, *suf, *locf, *tmrate;
1245 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
1246 long local_size = 0; /* the size of the local file */
1247 size_t filename_len;
1248 struct http_stat hstat; /* HTTP status */
1253 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
1254 has_wildcards_p because it would also warn on `?', and we know that
1255 shows up in CGI paths a *lot*. */
1256 if (strchr (u->url, '*'))
1257 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
1259 /* Determine the local filename. */
1261 u->local = url_filename (u->proxy ? u->proxy : u);
1263 if (!opt.output_document)
1266 locf = opt.output_document;
1268 /* Yuck. Multiple returns suck. We need to remember to free() the space we
1269 xmalloc() here before EACH return. This is one reason it's better to set
1270 flags that influence flow control and then return once at the end. */
1271 filename_len = strlen(u->local);
1272 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
1274 if (opt.noclobber && file_exists_p (u->local))
1276 /* If opt.noclobber is turned on and file already exists, do not
1277 retrieve the file */
1278 logprintf (LOG_VERBOSE, _("\
1279 File `%s' already there, will not retrieve.\n"), u->local);
1280 /* If the file is there, we suppose it's retrieved OK. */
1283 /* #### Bogusness alert. */
1284 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
1285 text/html, a harmless lie. */
1286 if (((suf = suffix (u->local)) != NULL)
1287 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
1290 xfree (filename_plus_orig_suffix); /* must precede every return! */
1291 /* Another harmless lie: */
1296 if (opt.timestamping)
1298 boolean local_dot_orig_file_exists = FALSE;
1300 if (opt.backup_converted)
1301 /* If -K is specified, we'll act on the assumption that it was specified
1302 last time these files were downloaded as well, and instead of just
1303 comparing local file X against server file X, we'll compare local
1304 file X.orig (if extant, else X) against server file X. If -K
1305 _wasn't_ specified last time, or the server contains files called
1306 *.orig, -N will be back to not operating correctly with -k. */
1308 /* Would a single s[n]printf() call be faster? --dan
1310 It wouldn't. sprintf() is horribly slow. At one point I
1311 profiled Wget, and found that a measurable and
1312 non-negligible amount of time was lost calling sprintf()
1313 in url.c. Replacing sprintf with inline calls to
1314 strcpy() and long_to_string() made a difference.
1316 strcpy(filename_plus_orig_suffix, u->local);
1317 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
1319 /* Try to stat() the .orig file. */
1320 if (stat(filename_plus_orig_suffix, &st) == 0)
1322 local_dot_orig_file_exists = TRUE;
1323 local_filename = filename_plus_orig_suffix;
1327 if (!local_dot_orig_file_exists)
1328 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
1329 if (stat (u->local, &st) == 0)
1330 local_filename = u->local;
1332 if (local_filename != NULL)
1333 /* There was a local file, so we'll check later to see if the version
1334 the server has is the same version we already have, allowing us to
1339 local_size = st.st_size;
1343 /* Reset the counter. */
1345 *dt = 0 | ACCEPTRANGES;
1349 /* Increment the pass counter. */
1351 /* Wait before the retrieval (unless this is the very first
1353 Check if we are retrying or not, wait accordingly - HEH */
1354 if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
1358 if (count<opt.waitretry)
1361 sleep(opt.waitretry);
1366 if (first_retrieval)
1367 first_retrieval = 0;
1368 /* Get the current time string. */
1369 tms = time_str (NULL);
1370 /* Print fetch message, if opt.verbose. */
1373 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1377 sprintf (tmp, _("(try:%2d)"), count);
1378 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1379 tms, hurl, tmp, locf);
1381 ws_changetitle (hurl, 1);
1386 /* Default document type is empty. However, if spider mode is
1387 on or time-stamping is employed, HEAD_ONLY commands is
1388 encoded within *dt. */
1389 if (opt.spider || (use_ts && !got_head))
1393 /* Assume no restarting. */
1395 /* Decide whether or not to restart. */
1396 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1397 && file_exists_p (u->local))
1398 if (stat (u->local, &st) == 0)
1399 hstat.restval = st.st_size;
1400 /* Decide whether to send the no-cache directive. */
1401 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1402 *dt |= SEND_NOCACHE;
1404 *dt &= ~SEND_NOCACHE;
1406 /* Try fetching the document, or at least its head. :-) */
1407 err = gethttp (u, &hstat, dt);
1409 /* It's unfortunate that wget determines the local filename before finding
1410 out the Content-Type of the file. Barring a major restructuring of the
1411 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1412 u->local to tack on ".html". */
1413 if (!opt.output_document)
1416 locf = opt.output_document;
1419 tms = time_str (NULL);
1420 /* Get the new location (with or without the redirection). */
1422 *newloc = xstrdup (hstat.newloc);
1425 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1426 case CONERROR: case READERR: case WRITEFAILED:
1428 /* Non-fatal errors continue executing the loop, which will
1429 bring them to "while" statement at the end, to judge
1430 whether the number of tries was exceeded. */
1432 printwhat (count, opt.ntry);
1435 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1436 /* Fatal errors just return from the function. */
1438 xfree (filename_plus_orig_suffix); /* must precede every return! */
1441 case FWRITEERR: case FOPENERR:
1442 /* Another fatal error. */
1443 logputs (LOG_VERBOSE, "\n");
1444 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1445 u->local, strerror (errno));
1450 /* Another fatal error. */
1451 logputs (LOG_VERBOSE, "\n");
1452 logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
1454 xfree (filename_plus_orig_suffix); /* must precede every return! */
1458 /* Return the new location to the caller. */
1461 logprintf (LOG_NOTQUIET,
1462 _("ERROR: Redirection (%d) without location.\n"),
1464 xfree (filename_plus_orig_suffix); /* must precede every return! */
1468 xfree (filename_plus_orig_suffix); /* must precede every return! */
1472 /* Deal with you later. */
1475 /* All possibilities should have been exhausted. */
1478 if (!(*dt & RETROKF))
1482 /* #### Ugly ugly ugly! */
1483 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1484 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1487 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1488 tms, hstat.statcode, hstat.error);
1489 logputs (LOG_VERBOSE, "\n");
1491 xfree (filename_plus_orig_suffix); /* must precede every return! */
1495 /* Did we get the time-stamp? */
1498 if (opt.timestamping && !hstat.remote_time)
1500 logputs (LOG_NOTQUIET, _("\
1501 Last-modified header missing -- time-stamps turned off.\n"));
1503 else if (hstat.remote_time)
1505 /* Convert the date-string into struct tm. */
1506 tmr = http_atotm (hstat.remote_time);
1507 if (tmr == (time_t) (-1))
1508 logputs (LOG_VERBOSE, _("\
1509 Last-modified header invalid -- time-stamp ignored.\n"));
1513 /* The time-stamping section. */
1518 use_ts = 0; /* no more time-stamping */
1519 count = 0; /* the retrieve count for HEAD is
1521 if (hstat.remote_time && tmr != (time_t) (-1))
1523 /* Now time-stamping can be used validly. Time-stamping
1524 means that if the sizes of the local and remote file
1525 match, and local file is newer than the remote file,
1526 it will not be retrieved. Otherwise, the normal
1527 download procedure is resumed. */
1529 (hstat.contlen == -1 || local_size == hstat.contlen))
1531 logprintf (LOG_VERBOSE, _("\
1532 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1535 xfree (filename_plus_orig_suffix); /*must precede every return!*/
1538 else if (tml >= tmr)
1539 logprintf (LOG_VERBOSE, _("\
1540 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1542 logputs (LOG_VERBOSE,
1543 _("Remote file is newer, retrieving.\n"));
1549 && (tmr != (time_t) (-1))
1551 && ((hstat.len == hstat.contlen) ||
1552 ((hstat.res == 0) &&
1553 ((hstat.contlen == -1) ||
1554 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1556 touch (u->local, tmr);
1558 /* End of time-stamping section. */
1562 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1563 xfree (filename_plus_orig_suffix); /* must precede every return! */
1567 /* It is now safe to free the remainder of hstat, since the
1568 strings within it will no longer be used. */
1571 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1573 if (hstat.len == hstat.contlen)
1577 logprintf (LOG_VERBOSE,
1578 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1579 tms, tmrate, locf, hstat.len, hstat.contlen);
1580 logprintf (LOG_NONVERBOSE,
1581 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1582 tms, u->url, hstat.len, hstat.contlen, locf, count);
1585 downloaded_increase (hstat.len);
1587 /* Remember that we downloaded the file for later ".orig" code. */
1588 if (*dt & ADDED_HTML_EXTENSION)
1589 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1591 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1593 xfree(filename_plus_orig_suffix); /* must precede every return! */
1596 else if (hstat.res == 0) /* No read error */
1598 if (hstat.contlen == -1) /* We don't know how much we were supposed
1599 to get, so assume we succeeded. */
1603 logprintf (LOG_VERBOSE,
1604 _("%s (%s) - `%s' saved [%ld]\n\n"),
1605 tms, tmrate, locf, hstat.len);
1606 logprintf (LOG_NONVERBOSE,
1607 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1608 tms, u->url, hstat.len, locf, count);
1611 downloaded_increase (hstat.len);
1613 /* Remember that we downloaded the file for later ".orig" code. */
1614 if (*dt & ADDED_HTML_EXTENSION)
1615 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1617 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1619 xfree (filename_plus_orig_suffix); /* must precede every return! */
1622 else if (hstat.len < hstat.contlen) /* meaning we lost the
1623 connection too soon */
1625 logprintf (LOG_VERBOSE,
1626 _("%s (%s) - Connection closed at byte %ld. "),
1627 tms, tmrate, hstat.len);
1628 printwhat (count, opt.ntry);
1631 else if (!opt.kill_longer) /* meaning we got more than expected */
1633 logprintf (LOG_VERBOSE,
1634 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1635 tms, tmrate, locf, hstat.len, hstat.contlen);
1636 logprintf (LOG_NONVERBOSE,
1637 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1638 tms, u->url, hstat.len, hstat.contlen, locf, count);
1640 downloaded_increase (hstat.len);
1642 /* Remember that we downloaded the file for later ".orig" code. */
1643 if (*dt & ADDED_HTML_EXTENSION)
1644 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1646 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1648 xfree (filename_plus_orig_suffix); /* must precede every return! */
1651 else /* the same, but not accepted */
1653 logprintf (LOG_VERBOSE,
1654 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1655 tms, tmrate, hstat.len, hstat.contlen);
1656 printwhat (count, opt.ntry);
1660 else /* now hstat.res can only be -1 */
1662 if (hstat.contlen == -1)
1664 logprintf (LOG_VERBOSE,
1665 _("%s (%s) - Read error at byte %ld (%s)."),
1666 tms, tmrate, hstat.len, strerror (errno));
1667 printwhat (count, opt.ntry);
1670 else /* hstat.res == -1 and contlen is given */
1672 logprintf (LOG_VERBOSE,
1673 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1674 tms, tmrate, hstat.len, hstat.contlen,
1676 printwhat (count, opt.ntry);
1683 while (!opt.ntry || (count < opt.ntry));
1684 xfree (filename_plus_orig_suffix); /* must precede every return! */
1688 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1689 than local timezone (mktime assumes the latter).
1691 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1692 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1694 mktime_from_utc (struct tm *t)
1701 tb = mktime (gmtime (&tl));
1702 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1705 /* Check whether the result of strptime() indicates success.
1706 strptime() returns the pointer to how far it got to in the string.
1707 The processing has been successful if the string is at `GMT' or
1708 `+X', or at the end of the string.
1710 In extended regexp parlance, the function returns 1 if P matches
1711 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1712 strptime()) is considered a failure and 0 is returned. */
1714 check_end (const char *p)
1718 while (ISSPACE (*p))
1721 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1722 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1728 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1729 the three formats RFC2068 allows the HTTP servers to emit --
1730 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1733 We use strptime() to recognize various dates, which makes it a
1734 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1735 allows shortened dates and months, one-digit days, etc.). It also
1736 allows more than one space anywhere where the specs require one SP.
1737 The routine should probably be even more forgiving (as recommended
1738 by RFC2068), but I do not have the time to write one.
1740 Return the computed time_t representation, or -1 if all the
1743 Needless to say, what we *really* need here is something like
1744 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1745 and does not use strptime(). atotm() is to be found in the sources
1746 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1748 http_atotm (char *time_string)
1752 /* Roger Beeman says: "This function dynamically allocates struct tm
1753 t, but does no initialization. The only field that actually
1754 needs initialization is tm_isdst, since the others will be set by
1755 strptime. Since strptime does not set tm_isdst, it will return
1756 the data structure with whatever data was in tm_isdst to begin
1757 with. For those of us in timezones where DST can occur, there
1758 can be a one hour shift depending on the previous contents of the
1759 data area where the data structure is allocated." */
1762 /* Note that under foreign locales Solaris strptime() fails to
1763 recognize English dates, which renders this function useless. I
1764 assume that other non-GNU strptime's are plagued by the same
1765 disease. We solve this by setting only LC_MESSAGES in
1766 i18n_initialize(), instead of LC_ALL.
1768 Another solution could be to temporarily set locale to C, invoke
1769 strptime(), and restore it back. This is slow and dirty,
1770 however, and locale support other than LC_MESSAGES can mess other
1771 things, so I rather chose to stick with just setting LC_MESSAGES.
1773 Also note that none of this is necessary under GNU strptime(),
1774 because it recognizes both international and local dates. */
1776 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1777 it to eat all white space up to (and including) a newline, and
1778 the function fails if there is no newline (!).
1780 Let's hope all strptime() implementations use ` ' to skip *all*
1781 whitespace instead of just one (it works that way on all the
1782 systems I've tested it on). */
1784 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1785 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1786 return mktime_from_utc (&t);
1787 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1788 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1789 return mktime_from_utc (&t);
1790 /* asctime: Thu Jan 29 22:12:57 1998 */
1791 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1792 return mktime_from_utc (&t);
1797 /* Authorization support: We support two authorization schemes:
1799 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1801 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1802 consisting of answering to the server's challenge with the proper
1805 /* How many bytes it will take to store LEN bytes in base64. */
1806 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1808 /* Encode the string S of length LENGTH to base64 format and place it
1809 to STORE. STORE will be 0-terminated, and must point to a writable
1810 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1812 base64_encode (const char *s, char *store, int length)
1814 /* Conversion table. */
1815 static char tbl[64] = {
1816 'A','B','C','D','E','F','G','H',
1817 'I','J','K','L','M','N','O','P',
1818 'Q','R','S','T','U','V','W','X',
1819 'Y','Z','a','b','c','d','e','f',
1820 'g','h','i','j','k','l','m','n',
1821 'o','p','q','r','s','t','u','v',
1822 'w','x','y','z','0','1','2','3',
1823 '4','5','6','7','8','9','+','/'
1826 unsigned char *p = (unsigned char *)store;
1828 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1829 for (i = 0; i < length; i += 3)
1831 *p++ = tbl[s[0] >> 2];
1832 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1833 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1834 *p++ = tbl[s[2] & 0x3f];
1837 /* Pad the result if necessary... */
1838 if (i == length + 1)
1840 else if (i == length + 2)
1841 *(p - 1) = *(p - 2) = '=';
1842 /* ...and zero-terminate it. */
1846 /* Create the authentication header contents for the `Basic' scheme.
1847 This is done by encoding the string `USER:PASS' in base64 and
1848 prepending `HEADER: Basic ' to it. */
1850 basic_authentication_encode (const char *user, const char *passwd,
1853 char *t1, *t2, *res;
1854 int len1 = strlen (user) + 1 + strlen (passwd);
1855 int len2 = BASE64_LENGTH (len1);
1857 t1 = (char *)alloca (len1 + 1);
1858 sprintf (t1, "%s:%s", user, passwd);
1859 t2 = (char *)alloca (1 + len2);
1860 base64_encode (t1, t2, len1);
1861 res = (char *)malloc (len2 + 11 + strlen (header));
1862 sprintf (res, "%s: Basic %s\r\n", header, t2);
1868 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1869 of a field in such a header. If the field is the one specified by
1870 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1871 digest authorization code), extract its value in the (char*)
1872 variable pointed by RET. Returns negative on a malformed header,
1873 or number of bytes that have been parsed by this call. */
1875 extract_header_attr (const char *au, const char *attr_name, char **ret)
1877 const char *cp, *ep;
1881 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1883 cp += strlen (attr_name);
1886 cp += skip_lws (cp);
1891 cp += skip_lws (cp);
1896 for (ep = cp; *ep && *ep != '\"'; ep++)
1901 *ret = strdupdelim (cp, ep);
1908 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1909 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1910 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1912 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1913 an array of 16 bytes containing the hash keys, and BUF should be a
1914 buffer of 33 writable characters (32 for hex digits plus one for
1915 zero termination). */
1917 dump_hash (unsigned char *buf, const unsigned char *hash)
1921 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1923 *buf++ = HEXD2asc (*hash >> 4);
1924 *buf++ = HEXD2asc (*hash & 0xf);
1929 /* Take the line apart to find the challenge, and compose a digest
1930 authorization header. See RFC2069 section 2.1.2. */
1932 digest_authentication_encode (const char *au, const char *user,
1933 const char *passwd, const char *method,
1936 static char *realm, *opaque, *nonce;
1941 { "realm", &realm },
1942 { "opaque", &opaque },
1947 realm = opaque = nonce = NULL;
1949 au += 6; /* skip over `Digest' */
1954 au += skip_lws (au);
1955 for (i = 0; i < ARRAY_SIZE (options); i++)
1957 int skip = extract_header_attr (au, options[i].name,
1958 options[i].variable);
1962 FREE_MAYBE (opaque);
1972 if (i == ARRAY_SIZE (options))
1974 while (*au && *au != '=')
1978 au += skip_lws (au);
1982 while (*au && *au != '\"')
1989 while (*au && *au != ',')
1994 if (!realm || !nonce || !user || !passwd || !path || !method)
1997 FREE_MAYBE (opaque);
2002 /* Calculate the digest value. */
2005 unsigned char hash[MD5_HASHLEN];
2006 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
2007 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
2009 /* A1BUF = H(user ":" realm ":" password) */
2010 md5_init_ctx (&ctx);
2011 md5_process_bytes (user, strlen (user), &ctx);
2012 md5_process_bytes (":", 1, &ctx);
2013 md5_process_bytes (realm, strlen (realm), &ctx);
2014 md5_process_bytes (":", 1, &ctx);
2015 md5_process_bytes (passwd, strlen (passwd), &ctx);
2016 md5_finish_ctx (&ctx, hash);
2017 dump_hash (a1buf, hash);
2019 /* A2BUF = H(method ":" path) */
2020 md5_init_ctx (&ctx);
2021 md5_process_bytes (method, strlen (method), &ctx);
2022 md5_process_bytes (":", 1, &ctx);
2023 md5_process_bytes (path, strlen (path), &ctx);
2024 md5_finish_ctx (&ctx, hash);
2025 dump_hash (a2buf, hash);
2027 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
2028 md5_init_ctx (&ctx);
2029 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
2030 md5_process_bytes (":", 1, &ctx);
2031 md5_process_bytes (nonce, strlen (nonce), &ctx);
2032 md5_process_bytes (":", 1, &ctx);
2033 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
2034 md5_finish_ctx (&ctx, hash);
2035 dump_hash (response_digest, hash);
2037 res = (char*) xmalloc (strlen (user)
2042 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
2043 + (opaque ? strlen (opaque) : 0)
2045 sprintf (res, "Authorization: Digest \
2046 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
2047 user, realm, nonce, path, response_digest);
2050 char *p = res + strlen (res);
2051 strcat (p, ", opaque=\"");
2055 strcat (res, "\r\n");
2059 #endif /* USE_DIGEST */
2062 #define BEGINS_WITH(line, string_constant) \
2063 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
2064 && (ISSPACE (line[sizeof (string_constant) - 1]) \
2065 || !line[sizeof (string_constant) - 1]))
2068 known_authentication_scheme_p (const char *au)
2070 return BEGINS_WITH (au, "Basic")
2071 || BEGINS_WITH (au, "Digest")
2072 || BEGINS_WITH (au, "NTLM");
2077 /* Create the HTTP authorization request header. When the
2078 `WWW-Authenticate' response header is seen, according to the
2079 authorization scheme specified in that header (`Basic' and `Digest'
2080 are supported by the current implementation), produce an
2081 appropriate HTTP authorization request header. */
2083 create_authorization_line (const char *au, const char *user,
2084 const char *passwd, const char *method,
2087 char *wwwauth = NULL;
2089 if (!strncasecmp (au, "Basic", 5))
2090 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2091 if (!strncasecmp (au, "NTLM", 4))
2092 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
2094 else if (!strncasecmp (au, "Digest", 6))
2095 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
2096 #endif /* USE_DIGEST */