home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / lwp-rget < prev    next >
Encoding:
Text File  |  2002-01-02  |  14.9 KB  |  596 lines

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