home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / lwp-rget.bat < prev    next >
Encoding:
DOS Batch File  |  2002-12-01  |  15.3 KB  |  612 lines

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