2 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
4 This file is part of Wget.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
24 #include <sys/types.h>
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
65 extern char *version_string;
75 #define TEXTHTML_S "text/html"
76 #define HTTP_ACCEPT "*/*"
78 /* Some status code validation macros: */
79 #define H_20X(x) (((x) >= 200) && ((x) < 300))
80 #define H_PARTIAL(x) ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
81 #define H_REDIRECTED(x) (((x) == HTTP_STATUS_MOVED_PERMANENTLY) \
82 || ((x) == HTTP_STATUS_MOVED_TEMPORARILY))
84 /* HTTP/1.0 status codes from RFC1945, provided for reference. */
86 #define HTTP_STATUS_OK 200
87 #define HTTP_STATUS_CREATED 201
88 #define HTTP_STATUS_ACCEPTED 202
89 #define HTTP_STATUS_NO_CONTENT 204
90 #define HTTP_STATUS_PARTIAL_CONTENTS 206
92 /* Redirection 3xx. */
93 #define HTTP_STATUS_MULTIPLE_CHOICES 300
94 #define HTTP_STATUS_MOVED_PERMANENTLY 301
95 #define HTTP_STATUS_MOVED_TEMPORARILY 302
96 #define HTTP_STATUS_NOT_MODIFIED 304
98 /* Client error 4xx. */
99 #define HTTP_STATUS_BAD_REQUEST 400
100 #define HTTP_STATUS_UNAUTHORIZED 401
101 #define HTTP_STATUS_FORBIDDEN 403
102 #define HTTP_STATUS_NOT_FOUND 404
104 /* Server errors 5xx. */
105 #define HTTP_STATUS_INTERNAL 500
106 #define HTTP_STATUS_NOT_IMPLEMENTED 501
107 #define HTTP_STATUS_BAD_GATEWAY 502
108 #define HTTP_STATUS_UNAVAILABLE 503
111 /* Parse the HTTP status line, which is of format:
113 HTTP-Version SP Status-Code SP Reason-Phrase
115 The function returns the status-code, or -1 if the status line is
116 malformed. The pointer to reason-phrase is returned in RP. */
118 parse_http_status_line (const char *line, const char **reason_phrase_ptr)
120 /* (the variables must not be named `major' and `minor', because
121 that breaks compilation with SunOS4 cc.) */
122 int mjr, mnr, statcode;
125 *reason_phrase_ptr = NULL;
127 /* The standard format of HTTP-Version is: `HTTP/X.Y', where X is
128 major version, and Y is minor version. */
129 if (strncmp (line, "HTTP/", 5) != 0)
133 /* Calculate major HTTP version. */
135 for (mjr = 0; ISDIGIT (*line); line++)
136 mjr = 10 * mjr + (*line - '0');
137 if (*line != '.' || p == line)
141 /* Calculate minor HTTP version. */
143 for (mnr = 0; ISDIGIT (*line); line++)
144 mnr = 10 * mnr + (*line - '0');
145 if (*line != ' ' || p == line)
147 /* Wget will accept only 1.0 and higher HTTP-versions. The value of
148 minor version can be safely ignored. */
153 /* Calculate status code. */
154 if (!(ISDIGIT (*line) && ISDIGIT (line[1]) && ISDIGIT (line[2])))
156 statcode = 100 * (*line - '0') + 10 * (line[1] - '0') + (line[2] - '0');
158 /* Set up the reason phrase pointer. */
160 /* RFC2068 requires SPC here, but we allow the string to finish
161 here, in case no reason-phrase is present. */
165 *reason_phrase_ptr = line;
170 *reason_phrase_ptr = line + 1;
175 /* Functions to be used as arguments to header_process(): */
177 struct http_process_range_closure {
183 /* Parse the `Content-Range' header and extract the information it
184 contains. Returns 1 if successful, -1 otherwise. */
186 http_process_range (const char *hdr, void *arg)
188 struct http_process_range_closure *closure
189 = (struct http_process_range_closure *)arg;
192 /* Certain versions of Nutscape proxy server send out
193 `Content-Length' without "bytes" specifier, which is a breach of
194 RFC2068 (as well as the HTTP/1.1 draft which was current at the
195 time). But hell, I must support it... */
196 if (!strncasecmp (hdr, "bytes", 5))
199 hdr += skip_lws (hdr);
205 for (num = 0; ISDIGIT (*hdr); hdr++)
206 num = 10 * num + (*hdr - '0');
207 if (*hdr != '-' || !ISDIGIT (*(hdr + 1)))
209 closure->first_byte_pos = num;
211 for (num = 0; ISDIGIT (*hdr); hdr++)
212 num = 10 * num + (*hdr - '0');
213 if (*hdr != '/' || !ISDIGIT (*(hdr + 1)))
215 closure->last_byte_pos = num;
217 for (num = 0; ISDIGIT (*hdr); hdr++)
218 num = 10 * num + (*hdr - '0');
219 closure->entity_length = num;
223 /* Place 1 to ARG if the HDR contains the word "none", 0 otherwise.
224 Used for `Accept-Ranges'. */
226 http_process_none (const char *hdr, void *arg)
228 int *where = (int *)arg;
230 if (strstr (hdr, "none"))
237 /* Place the malloc-ed copy of HDR hdr, to the first `;' to ARG. */
239 http_process_type (const char *hdr, void *arg)
241 char **result = (char **)arg;
244 p = strrchr (hdr, ';');
248 *result = (char *)xmalloc (len + 1);
249 memcpy (*result, hdr, len);
250 (*result)[len] = '\0';
253 *result = xstrdup (hdr);
260 long len; /* received length */
261 long contlen; /* expected length */
262 long restval; /* the restart value */
263 int res; /* the result of last read */
264 char *newloc; /* new location (redirection) */
265 char *remote_time; /* remote time-stamp string */
266 char *error; /* textual HTTP error */
267 int statcode; /* status code */
268 long dltime; /* time of the download */
271 /* Free the elements of hstat X. */
272 #define FREEHSTAT(x) do \
274 FREE_MAYBE ((x).newloc); \
275 FREE_MAYBE ((x).remote_time); \
276 FREE_MAYBE ((x).error); \
277 (x).newloc = (x).remote_time = (x).error = NULL; \
280 static char *create_authorization_line PARAMS ((const char *, const char *,
281 const char *, const char *,
283 static char *basic_authentication_encode PARAMS ((const char *, const char *,
285 static int known_authentication_scheme_p PARAMS ((const char *));
287 static time_t http_atotm PARAMS ((char *));
289 /* Retrieve a document through HTTP protocol. It recognizes status
290 code, and correctly handles redirections. It closes the network
291 socket. If it receives an error from the functions below it, it
292 will print it if there is enough information to do so (almost
293 always), returning the error to the caller (i.e. http_loop).
295 Various HTTP parameters are stored to hs. Although it parses the
296 response code correctly, it is not used in a sane way. The caller
299 If u->proxy is non-NULL, the URL u will be taken as a proxy URL,
300 and u->proxy->url will be given to the proxy server (bad naming,
303 gethttp (struct urlinfo *u, struct http_stat *hs, int *dt)
305 char *request, *type, *command, *path;
307 char *pragma_h, *referer, *useragent, *range, *wwwauth, *remhost;
308 char *authenticate_h;
313 int sock, hcount, num_written, all_length, remport, statcode;
314 long contlen, contrange;
318 int auth_tried_already;
321 if (!(*dt & HEAD_ONLY))
322 /* If we're doing a GET on the URL, as opposed to just a HEAD, we need to
323 know the local filename so we can save to it. */
324 assert (u->local != NULL);
327 auth_tried_already = 0;
330 /* We need to come back here when the initial attempt to retrieve
331 without authorization header fails. */
333 /* Initialize certain elements of struct http_stat. */
338 hs->remote_time = NULL;
341 /* Which structure to use to retrieve the original URL data. */
347 /* First: establish the connection. */
348 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "), u->host, u->port);
349 err = make_connection (&sock, u->host, u->port);
353 logputs (LOG_VERBOSE, "\n");
354 logprintf (LOG_NOTQUIET, "%s: %s.\n", u->host, herrmsg (h_errno));
358 logputs (LOG_VERBOSE, "\n");
359 logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno));
363 logputs (LOG_VERBOSE, "\n");
364 logprintf (LOG_NOTQUIET,
365 _("Connection to %s:%hu refused.\n"), u->host, u->port);
369 logputs (LOG_VERBOSE, "\n");
370 logprintf (LOG_NOTQUIET, "connect: %s\n", strerror (errno));
375 /* Everything is fine! */
376 logputs (LOG_VERBOSE, _("connected!\n"));
384 path = u->proxy->url;
388 command = (*dt & HEAD_ONLY) ? "HEAD" : "GET";
392 referer = (char *)alloca (9 + strlen (ou->referer) + 3);
393 sprintf (referer, "Referer: %s\r\n", ou->referer);
395 if (*dt & SEND_NOCACHE)
396 pragma_h = "Pragma: no-cache\r\n";
401 range = (char *)alloca (13 + numdigit (hs->restval) + 4);
402 /* #### Gag me! Some servers (e.g. WebSitePro) have been known
403 to misinterpret the following `Range' format, and return the
404 document as multipart/x-byte-ranges MIME type!
406 #### TODO: Interpret MIME types, recognize bullshits similar
407 the one described above, and deal with them! */
408 sprintf (range, "Range: bytes=%ld-\r\n", hs->restval);
413 STRDUP_ALLOCA (useragent, opt.useragent);
416 useragent = (char *)alloca (10 + strlen (version_string));
417 sprintf (useragent, "Wget/%s", version_string);
419 /* Construct the authentication, if userid is present. */
422 search_netrc (u->host, (const char **)&user, (const char **)&passwd, 0);
423 user = user ? user : opt.http_user;
424 passwd = passwd ? passwd : opt.http_passwd;
427 if (authenticate_h && user && passwd)
429 wwwauth = create_authorization_line (authenticate_h, user, passwd,
436 char *proxy_user, *proxy_passwd;
437 /* For normal username and password, URL components override
438 command-line/wgetrc parameters. With proxy authentication,
439 it's the reverse, because proxy URLs are normally the
440 "permanent" ones, so command-line args should take
442 if (opt.proxy_user && opt.proxy_passwd)
444 proxy_user = opt.proxy_user;
445 proxy_passwd = opt.proxy_passwd;
449 proxy_user = u->user;
450 proxy_passwd = u->passwd;
452 /* #### This is junky. Can't the proxy request, say, `Digest'
454 if (proxy_user && proxy_passwd)
455 proxyauth = basic_authentication_encode (proxy_user, proxy_passwd,
456 "Proxy-Authorization");
468 host_port = (char *)alloca (numdigit (remport) + 2);
469 host_port_len = sprintf (host_port, ":%d", remport);
472 /* Allocate the memory for the request. */
473 request = (char *)alloca (strlen (command) + strlen (path)
475 + strlen (remhost) + host_port_len
476 + strlen (HTTP_ACCEPT)
477 + (referer ? strlen (referer) : 0)
478 + (wwwauth ? strlen (wwwauth) : 0)
479 + (proxyauth ? strlen (proxyauth) : 0)
480 + (range ? strlen (range) : 0)
482 + (opt.user_header ? strlen (opt.user_header) : 0)
484 /* Construct the request. */
491 command, path, useragent, remhost,
492 host_port ? host_port : "",
493 HTTP_ACCEPT, referer ? referer : "",
494 wwwauth ? wwwauth : "",
495 proxyauth ? proxyauth : "",
498 opt.user_header ? opt.user_header : "");
499 DEBUGP (("---request begin---\n%s---request end---\n", request));
500 /* Free the temporary memory. */
501 FREE_MAYBE (wwwauth);
502 FREE_MAYBE (proxyauth);
504 /* Send the request to server. */
505 num_written = iwrite (sock, request, strlen (request));
508 logputs (LOG_VERBOSE, _("Failed writing HTTP request.\n"));
512 logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
513 u->proxy ? "Proxy" : "HTTP");
514 contlen = contrange = -1;
519 /* Before reading anything, initialize the rbuf. */
520 rbuf_initialize (&rbuf, sock);
524 /* Header-fetching loop. */
532 /* Get the header. */
533 status = header_get (&rbuf, &hdr,
534 /* Disallow continuations for status line. */
535 (hcount == 1 ? HG_NO_CONTINUATIONS : HG_NONE));
537 /* Check for errors. */
538 if (status == HG_EOF && *hdr)
540 /* This used to be an unconditional error, but that was
541 somewhat controversial, because of a large number of
542 broken CGI's that happily "forget" to send the second EOL
543 before closing the connection of a HEAD request.
545 So, the deal is to check whether the header is empty
546 (*hdr is zero if it is); if yes, it means that the
547 previous header was fully retrieved, and that -- most
548 probably -- the request is complete. "...be liberal in
549 what you accept." Oh boy. */
550 logputs (LOG_VERBOSE, "\n");
551 logputs (LOG_NOTQUIET, _("End of file while parsing headers.\n"));
554 FREE_MAYBE (hs->newloc);
555 FREE_MAYBE (all_headers);
559 else if (status == HG_ERROR)
561 logputs (LOG_VERBOSE, "\n");
562 logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
566 FREE_MAYBE (hs->newloc);
567 FREE_MAYBE (all_headers);
572 /* If the headers are to be saved to a file later, save them to
574 if (opt.save_headers)
576 int lh = strlen (hdr);
577 all_headers = (char *)xrealloc (all_headers, all_length + lh + 2);
578 memcpy (all_headers + all_length, hdr, lh);
580 all_headers[all_length++] = '\n';
581 all_headers[all_length] = '\0';
584 /* Print the header if requested. */
585 if (opt.server_response && hcount != 1)
586 logprintf (LOG_VERBOSE, "\n%d %s", hcount, hdr);
588 /* Check for status line. */
592 /* Parse the first line of server response. */
593 statcode = parse_http_status_line (hdr, &error);
594 hs->statcode = statcode;
595 /* Store the descriptive response. */
596 if (statcode == -1) /* malformed response */
598 /* A common reason for "malformed response" error is the
599 case when no data was actually received. Handle this
602 hs->error = xstrdup (_("No data received"));
604 hs->error = xstrdup (_("Malformed status line"));
609 hs->error = xstrdup (_("(no description)"));
611 hs->error = xstrdup (error);
618 logprintf (LOG_VERBOSE, "%d %s", statcode, error);
623 /* Exit on empty header. */
630 /* Try getting content-length. */
631 if (contlen == -1 && !opt.ignore_length)
632 if (header_process (hdr, "Content-Length", header_extract_number,
635 /* Try getting content-type. */
637 if (header_process (hdr, "Content-Type", http_process_type, &type))
639 /* Try getting location. */
641 if (header_process (hdr, "Location", header_strdup, &hs->newloc))
643 /* Try getting last-modified. */
644 if (!hs->remote_time)
645 if (header_process (hdr, "Last-Modified", header_strdup,
648 /* Try getting www-authentication. */
650 if (header_process (hdr, "WWW-Authenticate", header_strdup,
653 /* Check for accept-ranges header. If it contains the word
654 `none', disable the ranges. */
655 if (*dt & ACCEPTRANGES)
658 if (header_process (hdr, "Accept-Ranges", http_process_none, &nonep))
661 *dt &= ~ACCEPTRANGES;
665 /* Try getting content-range. */
668 struct http_process_range_closure closure;
669 if (header_process (hdr, "Content-Range", http_process_range, &closure))
671 contrange = closure.first_byte_pos;
679 logputs (LOG_VERBOSE, "\n");
681 if ((statcode == HTTP_STATUS_UNAUTHORIZED)
684 /* Authorization is required. */
689 if (auth_tried_already)
691 /* If we have tried it already, then there is not point
693 logputs (LOG_NOTQUIET, _("Authorization failed.\n"));
694 free (authenticate_h);
697 else if (!known_authentication_scheme_p (authenticate_h))
699 free (authenticate_h);
700 logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
705 auth_tried_already = 1;
709 /* We do not need this anymore. */
712 free (authenticate_h);
713 authenticate_h = NULL;
716 /* 20x responses are counted among successful by default. */
717 if (H_20X (statcode))
720 if (type && !strncasecmp (type, TEXTHTML_S, strlen (TEXTHTML_S)))
723 /* We don't assume text/html by default. */
726 if (opt.html_extension && (*dt & TEXTHTML))
727 /* -E / --html-extension / html_extension = on was specified, and this is a
728 text/html file. If some case-insensitive variation on ".htm[l]" isn't
729 already the file's suffix, tack on ".html". */
731 char* last_period_in_local_filename = strrchr(u->local, '.');
733 if (last_period_in_local_filename == NULL ||
734 !(strcasecmp(last_period_in_local_filename, ".htm") == EQ ||
735 strcasecmp(last_period_in_local_filename, ".html") == EQ))
737 size_t local_filename_len = strlen(u->local);
739 u->local = xrealloc(u->local, local_filename_len + sizeof(".html"));
740 strcpy(u->local + local_filename_len, ".html");
742 *dt |= ADDED_HTML_EXTENSION;
748 else if (contrange != hs->restval ||
749 (H_PARTIAL (statcode) && contrange == -1))
751 /* This means the whole request was somehow misunderstood by the
754 FREE_MAYBE (hs->newloc);
755 FREE_MAYBE (all_headers);
763 contlen += contrange;
765 contrange = -1; /* If conent-length was not sent,
766 content-range will be ignored. */
768 hs->contlen = contlen;
770 /* Return if redirected. */
771 if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
773 /* RFC2068 says that in case of the 300 (multiple choices)
774 response, the server can output a preferred URL through
775 `Location' header; otherwise, the request should be treated
776 like GET. So, if the location is set, it will be a
777 redirection; otherwise, just proceed normally. */
778 if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
782 logprintf (LOG_VERBOSE,
783 _("Location: %s%s\n"),
784 hs->newloc ? hs->newloc : _("unspecified"),
785 hs->newloc ? _(" [following]") : "");
788 FREE_MAYBE (all_headers);
794 if ((*dt & RETROKF) && !opt.server_response)
796 /* No need to print this output if the body won't be
797 downloaded at all, or if the original server response is
799 logputs (LOG_VERBOSE, _("Length: "));
802 logputs (LOG_VERBOSE, legible (contlen));
804 logprintf (LOG_VERBOSE, _(" (%s to go)"),
805 legible (contlen - contrange));
808 logputs (LOG_VERBOSE,
809 opt.ignore_length ? _("ignored") : _("unspecified"));
811 logprintf (LOG_VERBOSE, " [%s]\n", type);
813 logputs (LOG_VERBOSE, "\n");
817 type = NULL; /* We don't need it any more. */
819 /* Return if we have no intention of further downloading. */
820 if (!(*dt & RETROKF) || (*dt & HEAD_ONLY))
822 /* In case someone cares to look... */
826 FREE_MAYBE (all_headers);
831 /* Open the local file. */
834 mkalldirs (u->local);
836 rotate_backups (u->local);
837 fp = fopen (u->local, hs->restval ? "ab" : "wb");
840 logprintf (LOG_NOTQUIET, "%s: %s\n", u->local, strerror (errno));
842 FREE_MAYBE (all_headers);
849 /* #### This confuses the code that checks for file size. There
850 should be some overhead information. */
851 if (opt.save_headers)
852 fwrite (all_headers, 1, all_length, fp);
854 /* Get the contents of the document. */
855 hs->res = get_contents (sock, fp, &hs->len, hs->restval,
856 (contlen != -1 ? contlen : 0),
858 hs->dltime = elapsed_time ();
860 /* Close or flush the file. We have to be careful to check for
861 error here. Checking the result of fwrite() is not enough --
862 errors could go unnoticed! */
865 flush_res = fclose (fp);
867 flush_res = fflush (fp);
868 if (flush_res == EOF)
871 FREE_MAYBE (all_headers);
878 /* The genuine HTTP loop! This is the part where the retrieval is
879 retried, and retried, and retried, and... */
881 http_loop (struct urlinfo *u, char **newloc, int *dt)
883 static int first_retrieval = 1;
886 int use_ts, got_head = 0; /* time-stamping info */
887 char *filename_plus_orig_suffix;
888 char *local_filename = NULL;
889 char *tms, *suf, *locf, *tmrate;
891 time_t tml = -1, tmr = -1; /* local and remote time-stamps */
892 long local_size = 0; /* the size of the local file */
894 struct http_stat hstat; /* HTTP status */
899 /* Warn on (likely bogus) wildcard usage in HTTP. Don't use
900 has_wildcards_p because it would also warn on `?', and we know that
901 shows up in CGI paths a *lot*. */
902 if (strchr (u->url, '*'))
903 logputs (LOG_VERBOSE, _("Warning: wildcards not supported in HTTP.\n"));
905 /* Determine the local filename. */
907 u->local = url_filename (u->proxy ? u->proxy : u);
909 if (!opt.output_document)
912 locf = opt.output_document;
914 /* Yuck. Multiple returns suck. We need to remember to free() the space we
915 xmalloc() here before EACH return. This is one reason it's better to set
916 flags that influence flow control and then return once at the end. */
917 filename_len = strlen(u->local);
918 filename_plus_orig_suffix = xmalloc(filename_len + sizeof(".orig"));
920 if (opt.noclobber && file_exists_p (u->local))
922 /* If opt.noclobber is turned on and file already exists, do not
924 logprintf (LOG_VERBOSE, _("\
925 File `%s' already there, will not retrieve.\n"), u->local);
926 /* If the file is there, we suppose it's retrieved OK. */
929 /* #### Bogusness alert. */
930 /* If its suffix is "html" or (yuck!) "htm", we suppose it's
931 text/html, a harmless lie. */
932 if (((suf = suffix (u->local)) != NULL)
933 && (!strcmp (suf, "html") || !strcmp (suf, "htm")))
936 free(filename_plus_orig_suffix); /* must precede every return! */
937 /* Another harmless lie: */
942 if (opt.timestamping)
944 boolean local_dot_orig_file_exists = FALSE;
946 if (opt.backup_converted)
947 /* If -K is specified, we'll act on the assumption that it was specified
948 last time these files were downloaded as well, and instead of just
949 comparing local file X against server file X, we'll compare local
950 file X.orig (if extant, else X) against server file X. If -K
951 _wasn't_ specified last time, or the server contains files called
952 *.orig, -N will be back to not operating correctly with -k. */
954 /* Would a single s[n]printf() call be faster? */
955 strcpy(filename_plus_orig_suffix, u->local);
956 strcpy(filename_plus_orig_suffix + filename_len, ".orig");
958 /* Try to stat() the .orig file. */
959 if (stat(filename_plus_orig_suffix, &st) == 0)
961 local_dot_orig_file_exists = TRUE;
962 local_filename = filename_plus_orig_suffix;
966 if (!local_dot_orig_file_exists)
967 /* Couldn't stat() <file>.orig, so try to stat() <file>. */
968 if (stat (u->local, &st) == 0)
969 local_filename = u->local;
971 if (local_filename != NULL)
972 /* There was a local file, so we'll check later to see if the version
973 the server has is the same version we already have, allowing us to
978 local_size = st.st_size;
982 /* Reset the counter. */
984 *dt = 0 | ACCEPTRANGES;
988 /* Increment the pass counter. */
990 /* Wait before the retrieval (unless this is the very first
992 Check if we are retrying or not, wait accordingly - HEH */
993 if (!first_retrieval && (opt.wait || (count && opt.waitretry)))
997 if (count<opt.waitretry)
1000 sleep(opt.waitretry);
1005 if (first_retrieval)
1006 first_retrieval = 0;
1007 /* Get the current time string. */
1008 tms = time_str (NULL);
1009 /* Print fetch message, if opt.verbose. */
1012 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1016 sprintf (tmp, _("(try:%2d)"), count);
1017 logprintf (LOG_VERBOSE, "--%s-- %s\n %s => `%s'\n",
1018 tms, hurl, tmp, locf);
1020 ws_changetitle (hurl, 1);
1025 /* Default document type is empty. However, if spider mode is
1026 on or time-stamping is employed, HEAD_ONLY commands is
1027 encoded within *dt. */
1028 if (opt.spider || (use_ts && !got_head))
1032 /* Assume no restarting. */
1034 /* Decide whether or not to restart. */
1035 if (((count > 1 && (*dt & ACCEPTRANGES)) || opt.always_rest)
1036 && file_exists_p (u->local))
1037 if (stat (u->local, &st) == 0)
1038 hstat.restval = st.st_size;
1039 /* Decide whether to send the no-cache directive. */
1040 if (u->proxy && (count > 1 || (opt.proxy_cache == 0)))
1041 *dt |= SEND_NOCACHE;
1043 *dt &= ~SEND_NOCACHE;
1045 /* Try fetching the document, or at least its head. :-) */
1046 err = gethttp (u, &hstat, dt);
1048 /* It's unfortunate that wget determines the local filename before finding
1049 out the Content-Type of the file. Barring a major restructuring of the
1050 code, we need to re-set locf here, since gethttp() may have xrealloc()d
1051 u->local to tack on ".html". */
1052 if (!opt.output_document)
1055 locf = opt.output_document;
1058 tms = time_str (NULL);
1059 /* Get the new location (with or without the redirection). */
1061 *newloc = xstrdup (hstat.newloc);
1064 case HERR: case HEOF: case CONSOCKERR: case CONCLOSED:
1065 case CONERROR: case READERR: case WRITEFAILED:
1067 /* Non-fatal errors continue executing the loop, which will
1068 bring them to "while" statement at the end, to judge
1069 whether the number of tries was exceeded. */
1071 printwhat (count, opt.ntry);
1074 case HOSTERR: case CONREFUSED: case PROXERR: case AUTHFAILED:
1075 /* Fatal errors just return from the function. */
1077 free(filename_plus_orig_suffix); /* must precede every return! */
1080 case FWRITEERR: case FOPENERR:
1081 /* Another fatal error. */
1082 logputs (LOG_VERBOSE, "\n");
1083 logprintf (LOG_NOTQUIET, _("Cannot write to `%s' (%s).\n"),
1084 u->local, strerror (errno));
1086 free(filename_plus_orig_suffix); /* must precede every return! */
1090 /* Return the new location to the caller. */
1093 logprintf (LOG_NOTQUIET,
1094 _("ERROR: Redirection (%d) without location.\n"),
1096 free(filename_plus_orig_suffix); /* must precede every return! */
1100 free(filename_plus_orig_suffix); /* must precede every return! */
1104 /* Deal with you later. */
1107 /* All possibilities should have been exhausted. */
1110 if (!(*dt & RETROKF))
1114 /* #### Ugly ugly ugly! */
1115 char *hurl = str_url (u->proxy ? u->proxy : u, 1);
1116 logprintf (LOG_NONVERBOSE, "%s:\n", hurl);
1119 logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"),
1120 tms, hstat.statcode, hstat.error);
1121 logputs (LOG_VERBOSE, "\n");
1123 free(filename_plus_orig_suffix); /* must precede every return! */
1127 /* Did we get the time-stamp? */
1130 if (opt.timestamping && !hstat.remote_time)
1132 logputs (LOG_NOTQUIET, _("\
1133 Last-modified header missing -- time-stamps turned off.\n"));
1135 else if (hstat.remote_time)
1137 /* Convert the date-string into struct tm. */
1138 tmr = http_atotm (hstat.remote_time);
1139 if (tmr == (time_t) (-1))
1140 logputs (LOG_VERBOSE, _("\
1141 Last-modified header invalid -- time-stamp ignored.\n"));
1145 /* The time-stamping section. */
1150 use_ts = 0; /* no more time-stamping */
1151 count = 0; /* the retrieve count for HEAD is
1153 if (hstat.remote_time && tmr != (time_t) (-1))
1155 /* Now time-stamping can be used validly. Time-stamping
1156 means that if the sizes of the local and remote file
1157 match, and local file is newer than the remote file,
1158 it will not be retrieved. Otherwise, the normal
1159 download procedure is resumed. */
1161 (hstat.contlen == -1 || local_size == hstat.contlen))
1163 logprintf (LOG_VERBOSE, _("\
1164 Server file no newer than local file `%s' -- not retrieving.\n\n"),
1167 free(filename_plus_orig_suffix);/*must precede every return!*/
1170 else if (tml >= tmr)
1171 logprintf (LOG_VERBOSE, _("\
1172 The sizes do not match (local %ld) -- retrieving.\n"), local_size);
1174 logputs (LOG_VERBOSE,
1175 _("Remote file is newer, retrieving.\n"));
1181 && (tmr != (time_t) (-1))
1183 && ((hstat.len == hstat.contlen) ||
1184 ((hstat.res == 0) &&
1185 ((hstat.contlen == -1) ||
1186 (hstat.len >= hstat.contlen && !opt.kill_longer)))))
1188 touch (u->local, tmr);
1190 /* End of time-stamping section. */
1194 logprintf (LOG_NOTQUIET, "%d %s\n\n", hstat.statcode, hstat.error);
1195 free(filename_plus_orig_suffix); /* must precede every return! */
1199 /* It is now safe to free the remainder of hstat, since the
1200 strings within it will no longer be used. */
1203 tmrate = rate (hstat.len - hstat.restval, hstat.dltime);
1205 if (hstat.len == hstat.contlen)
1209 logprintf (LOG_VERBOSE,
1210 _("%s (%s) - `%s' saved [%ld/%ld]\n\n"),
1211 tms, tmrate, locf, hstat.len, hstat.contlen);
1212 logprintf (LOG_NONVERBOSE,
1213 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1214 tms, u->url, hstat.len, hstat.contlen, locf, count);
1217 opt.downloaded += hstat.len;
1219 /* Remember that we downloaded the file for later ".orig" code. */
1220 if (*dt & ADDED_HTML_EXTENSION)
1221 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1223 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1225 free(filename_plus_orig_suffix); /* must precede every return! */
1228 else if (hstat.res == 0) /* No read error */
1230 if (hstat.contlen == -1) /* We don't know how much we were supposed
1231 to get, so assume we succeeded. */
1235 logprintf (LOG_VERBOSE,
1236 _("%s (%s) - `%s' saved [%ld]\n\n"),
1237 tms, tmrate, locf, hstat.len);
1238 logprintf (LOG_NONVERBOSE,
1239 "%s URL:%s [%ld] -> \"%s\" [%d]\n",
1240 tms, u->url, hstat.len, locf, count);
1243 opt.downloaded += hstat.len;
1245 /* Remember that we downloaded the file for later ".orig" code. */
1246 if (*dt & ADDED_HTML_EXTENSION)
1247 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1249 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1251 free(filename_plus_orig_suffix); /* must precede every return! */
1254 else if (hstat.len < hstat.contlen) /* meaning we lost the
1255 connection too soon */
1257 logprintf (LOG_VERBOSE,
1258 _("%s (%s) - Connection closed at byte %ld. "),
1259 tms, tmrate, hstat.len);
1260 printwhat (count, opt.ntry);
1263 else if (!opt.kill_longer) /* meaning we got more than expected */
1265 logprintf (LOG_VERBOSE,
1266 _("%s (%s) - `%s' saved [%ld/%ld])\n\n"),
1267 tms, tmrate, locf, hstat.len, hstat.contlen);
1268 logprintf (LOG_NONVERBOSE,
1269 "%s URL:%s [%ld/%ld] -> \"%s\" [%d]\n",
1270 tms, u->url, hstat.len, hstat.contlen, locf, count);
1272 opt.downloaded += hstat.len;
1274 /* Remember that we downloaded the file for later ".orig" code. */
1275 if (*dt & ADDED_HTML_EXTENSION)
1276 downloaded_file(FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED, locf);
1278 downloaded_file(FILE_DOWNLOADED_NORMALLY, locf);
1280 free(filename_plus_orig_suffix); /* must precede every return! */
1283 else /* the same, but not accepted */
1285 logprintf (LOG_VERBOSE,
1286 _("%s (%s) - Connection closed at byte %ld/%ld. "),
1287 tms, tmrate, hstat.len, hstat.contlen);
1288 printwhat (count, opt.ntry);
1292 else /* now hstat.res can only be -1 */
1294 if (hstat.contlen == -1)
1296 logprintf (LOG_VERBOSE,
1297 _("%s (%s) - Read error at byte %ld (%s)."),
1298 tms, tmrate, hstat.len, strerror (errno));
1299 printwhat (count, opt.ntry);
1302 else /* hstat.res == -1 and contlen is given */
1304 logprintf (LOG_VERBOSE,
1305 _("%s (%s) - Read error at byte %ld/%ld (%s). "),
1306 tms, tmrate, hstat.len, hstat.contlen,
1308 printwhat (count, opt.ntry);
1315 while (!opt.ntry || (count < opt.ntry));
1316 free(filename_plus_orig_suffix); /* must precede every return! */
1320 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
1321 than local timezone (mktime assumes the latter).
1323 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
1324 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
1326 mktime_from_utc (struct tm *t)
1333 tb = mktime (gmtime (&tl));
1334 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
1337 /* Check whether the result of strptime() indicates success.
1338 strptime() returns the pointer to how far it got to in the string.
1339 The processing has been successful if the string is at `GMT' or
1340 `+X', or at the end of the string.
1342 In extended regexp parlance, the function returns 1 if P matches
1343 "^ *(GMT|[+-][0-9]|$)", 0 otherwise. P being NULL (a valid result of
1344 strptime()) is considered a failure and 0 is returned. */
1350 while (ISSPACE (*p))
1353 || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
1354 || ((p[0] == '+' || p[1] == '-') && ISDIGIT (p[1])))
1360 /* Convert TIME_STRING time to time_t. TIME_STRING can be in any of
1361 the three formats RFC2068 allows the HTTP servers to emit --
1362 RFC1123-date, RFC850-date or asctime-date. Timezones are ignored,
1365 We use strptime() to recognize various dates, which makes it a
1366 little bit slacker than the RFC1123/RFC850/asctime (e.g. it always
1367 allows shortened dates and months, one-digit days, etc.). It also
1368 allows more than one space anywhere where the specs require one SP.
1369 The routine should probably be even more forgiving (as recommended
1370 by RFC2068), but I do not have the time to write one.
1372 Return the computed time_t representation, or -1 if all the
1375 Needless to say, what we *really* need here is something like
1376 Marcus Hennecke's atotm(), which is forgiving, fast, to-the-point,
1377 and does not use strptime(). atotm() is to be found in the sources
1378 of `phttpd', a little-known HTTP server written by Peter Erikson. */
1380 http_atotm (char *time_string)
1384 /* Roger Beeman says: "This function dynamically allocates struct tm
1385 t, but does no initialization. The only field that actually
1386 needs initialization is tm_isdst, since the others will be set by
1387 strptime. Since strptime does not set tm_isdst, it will return
1388 the data structure with whatever data was in tm_isdst to begin
1389 with. For those of us in timezones where DST can occur, there
1390 can be a one hour shift depending on the previous contents of the
1391 data area where the data structure is allocated." */
1394 /* Note that under foreign locales Solaris strptime() fails to
1395 recognize English dates, which renders this function useless. I
1396 assume that other non-GNU strptime's are plagued by the same
1397 disease. We solve this by setting only LC_MESSAGES in
1398 i18n_initialize(), instead of LC_ALL.
1400 Another solution could be to temporarily set locale to C, invoke
1401 strptime(), and restore it back. This is slow and dirty,
1402 however, and locale support other than LC_MESSAGES can mess other
1403 things, so I rather chose to stick with just setting LC_MESSAGES.
1405 Also note that none of this is necessary under GNU strptime(),
1406 because it recognizes both international and local dates. */
1408 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
1409 it to eat all white space up to (and including) a newline, and
1410 the function fails if there is no newline (!).
1412 Let's hope all strptime() implementations use ` ' to skip *all*
1413 whitespace instead of just one (it works that way on all the
1414 systems I've tested it on). */
1416 /* RFC1123: Thu, 29 Jan 1998 22:12:57 */
1417 if (check_end (strptime (time_string, "%a, %d %b %Y %T", &t)))
1418 return mktime_from_utc (&t);
1419 /* RFC850: Thu, 29-Jan-98 22:12:57 */
1420 if (check_end (strptime (time_string, "%a, %d-%b-%y %T", &t)))
1421 return mktime_from_utc (&t);
1422 /* asctime: Thu Jan 29 22:12:57 1998 */
1423 if (check_end (strptime (time_string, "%a %b %d %T %Y", &t)))
1424 return mktime_from_utc (&t);
1429 /* Authorization support: We support two authorization schemes:
1431 * `Basic' scheme, consisting of base64-ing USER:PASSWORD string;
1433 * `Digest' scheme, added by Junio Hamano <junio@twinsun.com>,
1434 consisting of answering to the server's challenge with the proper
1437 /* How many bytes it will take to store LEN bytes in base64. */
1438 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
1440 /* Encode the string S of length LENGTH to base64 format and place it
1441 to STORE. STORE will be 0-terminated, and must point to a writable
1442 buffer of at least 1+BASE64_LENGTH(length) bytes. */
1444 base64_encode (const char *s, char *store, int length)
1446 /* Conversion table. */
1447 static char tbl[64] = {
1448 'A','B','C','D','E','F','G','H',
1449 'I','J','K','L','M','N','O','P',
1450 'Q','R','S','T','U','V','W','X',
1451 'Y','Z','a','b','c','d','e','f',
1452 'g','h','i','j','k','l','m','n',
1453 'o','p','q','r','s','t','u','v',
1454 'w','x','y','z','0','1','2','3',
1455 '4','5','6','7','8','9','+','/'
1458 unsigned char *p = (unsigned char *)store;
1460 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
1461 for (i = 0; i < length; i += 3)
1463 *p++ = tbl[s[0] >> 2];
1464 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1465 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1466 *p++ = tbl[s[2] & 0x3f];
1469 /* Pad the result if necessary... */
1470 if (i == length + 1)
1472 else if (i == length + 2)
1473 *(p - 1) = *(p - 2) = '=';
1474 /* ...and zero-terminate it. */
1478 /* Create the authentication header contents for the `Basic' scheme.
1479 This is done by encoding the string `USER:PASS' in base64 and
1480 prepending `HEADER: Basic ' to it. */
1482 basic_authentication_encode (const char *user, const char *passwd,
1485 char *t1, *t2, *res;
1486 int len1 = strlen (user) + 1 + strlen (passwd);
1487 int len2 = BASE64_LENGTH (len1);
1489 t1 = (char *)alloca (len1 + 1);
1490 sprintf (t1, "%s:%s", user, passwd);
1491 t2 = (char *)alloca (1 + len2);
1492 base64_encode (t1, t2, len1);
1493 res = (char *)malloc (len2 + 11 + strlen (header));
1494 sprintf (res, "%s: Basic %s\r\n", header, t2);
1500 /* Parse HTTP `WWW-Authenticate:' header. AU points to the beginning
1501 of a field in such a header. If the field is the one specified by
1502 ATTR_NAME ("realm", "opaque", and "nonce" are used by the current
1503 digest authorization code), extract its value in the (char*)
1504 variable pointed by RET. Returns negative on a malformed header,
1505 or number of bytes that have been parsed by this call. */
1507 extract_header_attr (const char *au, const char *attr_name, char **ret)
1509 const char *cp, *ep;
1513 if (strncmp (cp, attr_name, strlen (attr_name)) == 0)
1515 cp += strlen (attr_name);
1518 cp += skip_lws (cp);
1523 cp += skip_lws (cp);
1528 for (ep = cp; *ep && *ep != '\"'; ep++)
1533 *ret = strdupdelim (cp, ep);
1540 /* Response value needs to be in lowercase, so we cannot use HEXD2ASC
1541 from url.h. See RFC 2069 2.1.2 for the syntax of response-digest. */
1542 #define HEXD2asc(x) (((x) < 10) ? ((x) + '0') : ((x) - 10 + 'a'))
1544 /* Dump the hexadecimal representation of HASH to BUF. HASH should be
1545 an array of 16 bytes containing the hash keys, and BUF should be a
1546 buffer of 33 writable characters (32 for hex digits plus one for
1547 zero termination). */
1549 dump_hash (unsigned char *buf, const unsigned char *hash)
1553 for (i = 0; i < MD5_HASHLEN; i++, hash++)
1555 *buf++ = HEXD2asc (*hash >> 4);
1556 *buf++ = HEXD2asc (*hash & 0xf);
1561 /* Take the line apart to find the challenge, and compose a digest
1562 authorization header. See RFC2069 section 2.1.2. */
1564 digest_authentication_encode (const char *au, const char *user,
1565 const char *passwd, const char *method,
1568 static char *realm, *opaque, *nonce;
1573 { "realm", &realm },
1574 { "opaque", &opaque },
1579 realm = opaque = nonce = NULL;
1581 au += 6; /* skip over `Digest' */
1586 au += skip_lws (au);
1587 for (i = 0; i < ARRAY_SIZE (options); i++)
1589 int skip = extract_header_attr (au, options[i].name,
1590 options[i].variable);
1594 FREE_MAYBE (opaque);
1604 if (i == ARRAY_SIZE (options))
1606 while (*au && *au != '=')
1610 au += skip_lws (au);
1614 while (*au && *au != '\"')
1621 while (*au && *au != ',')
1626 if (!realm || !nonce || !user || !passwd || !path || !method)
1629 FREE_MAYBE (opaque);
1634 /* Calculate the digest value. */
1637 unsigned char hash[MD5_HASHLEN];
1638 unsigned char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
1639 unsigned char response_digest[MD5_HASHLEN * 2 + 1];
1641 /* A1BUF = H(user ":" realm ":" password) */
1642 md5_init_ctx (&ctx);
1643 md5_process_bytes (user, strlen (user), &ctx);
1644 md5_process_bytes (":", 1, &ctx);
1645 md5_process_bytes (realm, strlen (realm), &ctx);
1646 md5_process_bytes (":", 1, &ctx);
1647 md5_process_bytes (passwd, strlen (passwd), &ctx);
1648 md5_finish_ctx (&ctx, hash);
1649 dump_hash (a1buf, hash);
1651 /* A2BUF = H(method ":" path) */
1652 md5_init_ctx (&ctx);
1653 md5_process_bytes (method, strlen (method), &ctx);
1654 md5_process_bytes (":", 1, &ctx);
1655 md5_process_bytes (path, strlen (path), &ctx);
1656 md5_finish_ctx (&ctx, hash);
1657 dump_hash (a2buf, hash);
1659 /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
1660 md5_init_ctx (&ctx);
1661 md5_process_bytes (a1buf, MD5_HASHLEN * 2, &ctx);
1662 md5_process_bytes (":", 1, &ctx);
1663 md5_process_bytes (nonce, strlen (nonce), &ctx);
1664 md5_process_bytes (":", 1, &ctx);
1665 md5_process_bytes (a2buf, MD5_HASHLEN * 2, &ctx);
1666 md5_finish_ctx (&ctx, hash);
1667 dump_hash (response_digest, hash);
1669 res = (char*) xmalloc (strlen (user)
1674 + 2 * MD5_HASHLEN /*strlen (response_digest)*/
1675 + (opaque ? strlen (opaque) : 0)
1677 sprintf (res, "Authorization: Digest \
1678 username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1679 user, realm, nonce, path, response_digest);
1682 char *p = res + strlen (res);
1683 strcat (p, ", opaque=\"");
1687 strcat (res, "\r\n");
1691 #endif /* USE_DIGEST */
1694 #define HACK_O_MATIC(line, string_constant) \
1695 (!strncasecmp (line, string_constant, sizeof (string_constant) - 1) \
1696 && (ISSPACE (line[sizeof (string_constant) - 1]) \
1697 || !line[sizeof (string_constant) - 1]))
1700 known_authentication_scheme_p (const char *au)
1702 return HACK_O_MATIC (au, "Basic") || HACK_O_MATIC (au, "Digest");
1707 /* Create the HTTP authorization request header. When the
1708 `WWW-Authenticate' response header is seen, according to the
1709 authorization scheme specified in that header (`Basic' and `Digest'
1710 are supported by the current implementation), produce an
1711 appropriate HTTP authorization request header. */
1713 create_authorization_line (const char *au, const char *user,
1714 const char *passwd, const char *method,
1717 char *wwwauth = NULL;
1719 if (!strncasecmp (au, "Basic", 5))
1720 wwwauth = basic_authentication_encode (user, passwd, "Authorization");
1722 else if (!strncasecmp (au, "Digest", 6))
1723 wwwauth = digest_authentication_encode (au, user, passwd, method, path);
1724 #endif /* USE_DIGEST */