Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

597 lines
14 KiB

  1. #!perl -w
  2. #line 18
  3. =head1 NAME
  4. lwp-rget - Retrieve WWW documents recursively
  5. =head1 SYNOPSIS
  6. lwp-rget [--verbose] [--auth=USER:PASS] [--depth=N] [--hier] [--iis]
  7. [--keepext=mime/type[,mime/type]] [--limit=N] [--nospace]
  8. [--prefix=URL] [--referer=URL] [--sleep=N] [--tolower] <URL>
  9. lwp-rget --version
  10. =head1 DESCRIPTION
  11. This program will retrieve a document and store it in a local file. It
  12. will follow any links found in the document and store these documents
  13. as well, patching links so that they refer to these local copies.
  14. This process continues until there are no more unvisited links or the
  15. process is stopped by the one or more of the limits which can be
  16. controlled by the command line arguments.
  17. This program is useful if you want to make a local copy of a
  18. collection of documents or want to do web reading off-line.
  19. All documents are stored as plain files in the current directory. The
  20. file names chosen are derived from the last component of URL paths.
  21. The options are:
  22. =over 3
  23. =item --auth=USER:PASS<n>
  24. Set the authentication credentials to user "USER" and password "PASS" if
  25. any restricted parts of the web site are hit. If there are restricted
  26. parts of the web site and authentication credentials are not available,
  27. those pages will not be downloaded.
  28. =item --depth=I<n>
  29. Limit the recursive level. Embedded images are always loaded, even if
  30. they fall outside the I<--depth>. This means that one can use
  31. I<--depth=0> in order to fetch a single document together with all
  32. inline graphics.
  33. The default depth is 5.
  34. =item --hier
  35. Download files into a hierarchy that mimics the web site structure.
  36. The default is to put all files in the current directory.
  37. =item --referer=I<URI>
  38. Set the value of the referer header for the initial request. The
  39. special value C<"NONE"> can be used to suppress the referer header in
  40. any of subsequent requests.
  41. =item --iis
  42. Sends an "Accept: */*" on all URL requests as a workaround for a bug in
  43. IIS 2.0. If no Accept MIME header is present, IIS 2.0 returns with a
  44. "406 No acceptable objects were found" error. Also converts any back
  45. slashes (\\) in URLs to forward slashes (/).
  46. =item --keepext=I<mime/type[,mime/type]>
  47. Keeps the current extension for the list MIME types. Useful when
  48. downloading text/plain documents that shouldn't all be translated to
  49. *.txt files.
  50. =item --limit=I<n>
  51. Limit the number of documents to get. The default limit is 50.
  52. =item --nospace
  53. Changes spaces in all URLs to underscore characters (_). Useful when
  54. downloading files from sites serving URLs with spaces in them. Does not
  55. remove spaces from fragments, e.g., "file.html#somewhere in here".
  56. =item --prefix=I<url_prefix>
  57. Limit the links to follow. Only URLs that start the prefix string are
  58. followed.
  59. The default prefix is set as the "directory" of the initial URL to
  60. follow. For instance if we start lwp-rget with the URL
  61. C<http://www.sn.no/foo/bar.html>, then prefix will be set to
  62. C<http://www.sn.no/foo/>.
  63. Use C<--prefix=''> if you don't want the fetching to be limited by any
  64. prefix.
  65. =item --sleep=I<n>
  66. Sleep I<n> seconds before retrieving each document. This options allows
  67. you to go slowly, not loading the server you visiting too much.
  68. =item --tolower
  69. Translates all links to lowercase. Useful when downloading files from
  70. IIS since it does not serve files in a case sensitive manner.
  71. =item --verbose
  72. Make more noise while running.
  73. =item --quiet
  74. Don't make any noise.
  75. =item --version
  76. Print program version number and quit.
  77. =item --help
  78. Print the usage message and quit.
  79. =back
  80. Before the program exits the name of the file, where the initial URL
  81. is stored, is printed on stdout. All used filenames are also printed
  82. on stderr as they are loaded. This printing can be suppressed with
  83. the I<--quiet> option.
  84. =head1 SEE ALSO
  85. L<lwp-request>, L<LWP>
  86. =head1 AUTHOR
  87. Gisle Aas <[email protected]>
  88. =cut
  89. use strict;
  90. use Getopt::Long qw(GetOptions);
  91. use URI::URL qw(url);
  92. use LWP::MediaTypes qw(media_suffix);
  93. use HTML::Entities ();
  94. use vars qw($VERSION);
  95. use vars qw($MAX_DEPTH $MAX_DOCS $PREFIX $REFERER $VERBOSE $QUIET $SLEEP $HIER $AUTH $IIS $TOLOWER $NOSPACE %KEEPEXT);
  96. my $progname = $0;
  97. $progname =~ s|.*/||; # only basename left
  98. $progname =~ s/\.\w*$//; #strip extension if any
  99. $VERSION = sprintf("%d.%02d", q$Revision: 1.19 $ =~ /(\d+)\.(\d+)/);
  100. #$Getopt::Long::debug = 1;
  101. #$Getopt::Long::ignorecase = 0;
  102. # Defaults
  103. $MAX_DEPTH = 5;
  104. $MAX_DOCS = 50;
  105. GetOptions('version' => \&print_version,
  106. 'help' => \&usage,
  107. 'depth=i' => \$MAX_DEPTH,
  108. 'limit=i' => \$MAX_DOCS,
  109. 'verbose!' => \$VERBOSE,
  110. 'quiet!' => \$QUIET,
  111. 'sleep=i' => \$SLEEP,
  112. 'prefix:s' => \$PREFIX,
  113. 'referer:s'=> \$REFERER,
  114. 'hier' => \$HIER,
  115. 'auth=s' => \$AUTH,
  116. 'iis' => \$IIS,
  117. 'tolower' => \$TOLOWER,
  118. 'nospace' => \$NOSPACE,
  119. 'keepext=s' => \$KEEPEXT{'OPT'},
  120. ) || usage();
  121. sub print_version {
  122. require LWP;
  123. my $DISTNAME = 'libwww-perl-' . LWP::Version();
  124. print <<"EOT";
  125. This is lwp-rget version $VERSION ($DISTNAME)
  126. Copyright 1996-1998, Gisle Aas.
  127. This program is free software; you can redistribute it and/or
  128. modify it under the same terms as Perl itself.
  129. EOT
  130. exit 0;
  131. }
  132. my $start_url = shift || usage();
  133. usage() if @ARGV;
  134. require LWP::UserAgent;
  135. my $ua = new LWP::UserAgent;
  136. $ua->agent("$progname/$VERSION " . $ua->agent);
  137. $ua->env_proxy;
  138. unless (defined $PREFIX) {
  139. $PREFIX = url($start_url); # limit to URLs below this one
  140. eval {
  141. $PREFIX->eparams(undef);
  142. $PREFIX->equery(undef);
  143. };
  144. $_ = $PREFIX->epath;
  145. s|[^/]+$||;
  146. $PREFIX->epath($_);
  147. $PREFIX = $PREFIX->as_string;
  148. }
  149. %KEEPEXT = map { lc($_) => 1 } split(/\s*,\s*/, ($KEEPEXT{'OPT'}||0));
  150. my $SUPPRESS_REFERER;
  151. $SUPPRESS_REFERER++ if ($REFERER || "") eq "NONE";
  152. print <<"" if $VERBOSE;
  153. START = $start_url
  154. MAX_DEPTH = $MAX_DEPTH
  155. MAX_DOCS = $MAX_DOCS
  156. PREFIX = $PREFIX
  157. my $no_docs = 0;
  158. my %seen = (); # mapping from URL => local_file
  159. my $filename = fetch($start_url, undef, $REFERER);
  160. print "$filename\n" unless $QUIET;
  161. sub fetch
  162. {
  163. my($url, $type, $referer, $depth) = @_;
  164. # Fix http://sitename.com/../blah/blah.html to
  165. # http://sitename.com/blah/blah.html
  166. $url = $url->as_string if (ref($url));
  167. while ($url =~ s#(https?://[^/]+/)\.\.\/#$1#) {}
  168. # Fix backslashes (\) in URL if $IIS defined
  169. $url = fix_backslashes($url) if (defined $IIS);
  170. $url = url($url) unless ref($url);
  171. $type ||= 'a';
  172. # Might be the background attribute
  173. $type = 'img' if ($type eq 'body' || $type eq 'td');
  174. $depth ||= 0;
  175. # Print the URL before we start checking...
  176. my $out = (" " x $depth) . $url . " ";
  177. $out .= "." x (60 - length($out));
  178. print STDERR $out . " " if $VERBOSE;
  179. # Can't get mailto things
  180. if ($url->scheme eq 'mailto') {
  181. print STDERR "*skipping mailto*\n" if $VERBOSE;
  182. return $url->as_string;
  183. }
  184. # The $plain_url is a URL without the fragment part
  185. my $plain_url = $url->clone;
  186. $plain_url->frag(undef);
  187. # Check PREFIX, but not for <IMG ...> links
  188. if ($type ne 'img' and $url->as_string !~ /^\Q$PREFIX/o) {
  189. print STDERR "*outsider*\n" if $VERBOSE;
  190. return $url->as_string;
  191. }
  192. # Translate URL to lowercase if $TOLOWER defined
  193. $plain_url = to_lower($plain_url) if (defined $TOLOWER);
  194. # If we already have it, then there is nothing to be done
  195. my $seen = $seen{$plain_url->as_string};
  196. if ($seen) {
  197. my $frag = $url->frag;
  198. $seen .= "#$frag" if defined($frag);
  199. $seen = protect_frag_spaces($seen);
  200. print STDERR "$seen (again)\n" if $VERBOSE;
  201. return $seen;
  202. }
  203. # Too much or too deep
  204. if ($depth > $MAX_DEPTH and $type ne 'img') {
  205. print STDERR "*too deep*\n" if $VERBOSE;
  206. return $url;
  207. }
  208. if ($no_docs > $MAX_DOCS) {
  209. print STDERR "*too many*\n" if $VERBOSE;
  210. return $url;
  211. }
  212. # Fetch document
  213. $no_docs++;
  214. sleep($SLEEP) if $SLEEP;
  215. my $req = HTTP::Request->new(GET => $url);
  216. # See: http://ftp.sunet.se/pub/NT/mirror-microsoft/kb/Q163/7/74.TXT
  217. $req->header ('Accept', '*/*') if (defined $IIS); # GIF/JPG from IIS 2.0
  218. $req->authorization_basic(split (/:/, $AUTH)) if (defined $AUTH);
  219. $req->referer($referer) if $referer && !$SUPPRESS_REFERER;
  220. my $res = $ua->request($req);
  221. # Check outcome
  222. if ($res->is_success) {
  223. my $doc = $res->content;
  224. my $ct = $res->content_type;
  225. my $name = find_name($res->request->url, $ct);
  226. print STDERR "$name\n" unless $QUIET;
  227. $seen{$plain_url->as_string} = $name;
  228. # If the file is HTML, then we look for internal links
  229. if ($ct eq "text/html") {
  230. # Save an unprosessed version of the HTML document. This
  231. # both reserves the name used, and it also ensures that we
  232. # don't loose everything if this program is killed before
  233. # we finish.
  234. save($name, $doc);
  235. my $base = $res->base;
  236. # Follow and substitute links...
  237. $doc =~
  238. s/
  239. (
  240. <(img|a|body|area|frame|td)\b # some interesting tag
  241. [^>]+ # still inside tag (not strictly correct)
  242. \b(?:src|href|background) # some link attribute
  243. \s*=\s* # =
  244. )
  245. (?: # scope of OR-ing
  246. (")([^"]*)" | # value in double quotes OR
  247. (')([^']*)' | # value in single quotes OR
  248. ([^\s>]+) # quoteless value
  249. )
  250. /
  251. new_link($1, lc($2), $3||$5, HTML::Entities::decode($4||$6||$7),
  252. $base, $name, "$url", $depth+1)
  253. /giex;
  254. # XXX
  255. # The regular expression above is not strictly correct.
  256. # It is not really possible to parse HTML with a single
  257. # regular expression, but it is faster. Tags that might
  258. # confuse us include:
  259. # <a alt="href" href=link.html>
  260. # <a alt=">" href="link.html">
  261. #
  262. }
  263. save($name, $doc);
  264. return $name;
  265. } else {
  266. print STDERR $res->code . " " . $res->message . "\n" if $VERBOSE;
  267. $seen{$plain_url->as_string} = $url->as_string;
  268. return $url->as_string;
  269. }
  270. }
  271. sub new_link
  272. {
  273. my($pre, $type, $quote, $url, $base, $localbase, $referer, $depth) = @_;
  274. $url = protect_frag_spaces($url);
  275. $url = fetch(url($url, $base)->abs, $type, $referer, $depth);
  276. $url = url("file:$url", "file:$localbase")->rel
  277. unless $url =~ /^[.+\-\w]+:/;
  278. $url = unprotect_frag_spaces($url);
  279. return $pre . $quote . $url . $quote;
  280. }
  281. sub protect_frag_spaces
  282. {
  283. my ($url) = @_;
  284. $url = $url->as_string if (ref($url));
  285. if ($url =~ m/^([^#]*#)(.+)$/)
  286. {
  287. my ($base, $frag) = ($1, $2);
  288. $frag =~ s/ /%20/g;
  289. $url = $base . $frag;
  290. }
  291. return $url;
  292. }
  293. sub unprotect_frag_spaces
  294. {
  295. my ($url) = @_;
  296. $url = $url->as_string if (ref($url));
  297. if ($url =~ m/^([^#]*#)(.+)$/)
  298. {
  299. my ($base, $frag) = ($1, $2);
  300. $frag =~ s/%20/ /g;
  301. $url = $base . $frag;
  302. }
  303. return $url;
  304. }
  305. sub fix_backslashes
  306. {
  307. my ($url) = @_;
  308. my ($base, $frag);
  309. $url = $url->as_string if (ref($url));
  310. if ($url =~ m/([^#]+)(#.*)/)
  311. {
  312. ($base, $frag) = ($1, $2);
  313. }
  314. else
  315. {
  316. $base = $url;
  317. $frag = "";
  318. }
  319. $base =~ tr/\\/\//;
  320. $base =~ s/%5[cC]/\//g; # URL-encoded back slash is %5C
  321. return $base . $frag;
  322. }
  323. sub to_lower
  324. {
  325. my ($url) = @_;
  326. my $was_object = 0;
  327. if (ref($url))
  328. {
  329. $url = $url->as_string;
  330. $was_object = 1;
  331. }
  332. if ($url =~ m/([^#]+)(#.*)/)
  333. {
  334. $url = lc($1) . $2;
  335. }
  336. else
  337. {
  338. $url = lc($url);
  339. }
  340. if ($was_object == 1)
  341. {
  342. return url($url);
  343. }
  344. else
  345. {
  346. return $url;
  347. }
  348. }
  349. sub translate_spaces
  350. {
  351. my ($url) = @_;
  352. my ($base, $frag);
  353. $url = $url->as_string if (ref($url));
  354. if ($url =~ m/([^#]+)(#.*)/)
  355. {
  356. ($base, $frag) = ($1, $2);
  357. }
  358. else
  359. {
  360. $base = $url;
  361. $frag = "";
  362. }
  363. $base =~ s/^ *//; # Remove initial spaces from base
  364. $base =~ s/ *$//; # Remove trailing spaces from base
  365. $base =~ tr/ /_/;
  366. $base =~ s/%20/_/g; # URL-encoded space is %20
  367. return $base . $frag;
  368. }
  369. sub mkdirp
  370. {
  371. my($directory, $mode) = @_;
  372. my @dirs = split(/\//, $directory);
  373. my $path = shift(@dirs); # build it as we go
  374. my $result = 1; # assume it will work
  375. unless (-d $path) {
  376. $result &&= mkdir($path, $mode);
  377. }
  378. foreach (@dirs) {
  379. $path .= "/$_";
  380. if ( ! -d $path) {
  381. $result &&= mkdir($path, $mode);
  382. }
  383. }
  384. return $result;
  385. }
  386. sub find_name
  387. {
  388. my($url, $type) = @_;
  389. #print "find_name($url, $type)\n";
  390. # Translate spaces in URL to underscores (_) if $NOSPACE defined
  391. $url = translate_spaces($url) if (defined $NOSPACE);
  392. # Translate URL to lowercase if $TOLOWER defined
  393. $url = to_lower($url) if (defined $TOLOWER);
  394. $url = url($url) unless ref($url);
  395. my $path = $url->path;
  396. # trim path until only the basename is left
  397. $path =~ s|(.*/)||;
  398. my $dirname = ".$1";
  399. if (!$HIER) {
  400. $dirname = "";
  401. } elsif (! -d $dirname) {
  402. mkdirp($dirname, 0775);
  403. }
  404. my $extra = ""; # something to make the name unique
  405. my $suffix;
  406. if ($KEEPEXT{lc($type)}) {
  407. $suffix = ($path =~ m/\.(.*)/) ? $1 : "";
  408. } else {
  409. $suffix = media_suffix($type);
  410. }
  411. $path =~ s|\..*||; # trim suffix
  412. $path = "index" unless length $path;
  413. while (1) {
  414. # Construct a new file name
  415. my $file = $dirname . $path . $extra;
  416. $file .= ".$suffix" if $suffix;
  417. # Check if it is unique
  418. return $file unless -f $file;
  419. # Try something extra
  420. unless ($extra) {
  421. $extra = "001";
  422. next;
  423. }
  424. $extra++;
  425. }
  426. }
  427. sub save
  428. {
  429. my $name = shift;
  430. #print "save($name,...)\n";
  431. open(FILE, ">$name") || die "Can't save $name: $!";
  432. binmode FILE;
  433. print FILE $_[0];
  434. close(FILE);
  435. }
  436. sub usage
  437. {
  438. die <<"";
  439. Usage: $progname [options] <URL>
  440. Allowed options are:
  441. --auth=USER:PASS Set authentication credentials for web site
  442. --depth=N Maximum depth to traverse (default is $MAX_DEPTH)
  443. --hier Download into hierarchy (not all files into cwd)
  444. --referer=URI Set initial referer header (or "NONE")
  445. --iis Workaround IIS 2.0 bug by sending "Accept: */*" MIME
  446. header; translates backslashes (\\) to forward slashes (/)
  447. --keepext=type Keep file extension for MIME types (comma-separated list)
  448. --limit=N A limit on the number documents to get (default is $MAX_DOCS)
  449. --nospace Translate spaces URLs (not #fragments) to underscores (_)
  450. --version Print version number and quit
  451. --verbose More output
  452. --quiet No output
  453. --sleep=SECS Sleep between gets, ie. go slowly
  454. --prefix=PREFIX Limit URLs to follow to those which begin with PREFIX
  455. --tolower Translate all URLs to lowercase (useful with IIS servers)
  456. }