9 use File::Basename qw[dirname];
13 use IPC::Cmd qw[can_run run];
14 use File::Path qw[mkpath];
15 use Params::Check qw[check];
16 use Module::Load::Conditional qw[can_load];
17 use Locale::Maketext::Simple Style => 'gettext';
19 use vars qw[ $VERBOSE $PREFER_BIN $FROM_EMAIL $USER_AGENT
20 $BLACKLIST $METHOD_FAIL $VERSION $METHODS
21 $FTP_PASSIVE $TIMEOUT $DEBUG $WARN
25 $PREFER_BIN = 0; # XXX TODO implement
26 $FROM_EMAIL = 'File-Fetch@example.com';
27 $USER_AGENT = 'File::Fetch/$VERSION';
28 $BLACKLIST = [qw|ftp|];
35 ### methods available to fetch the file depending on the scheme
37 http => [ qw|lwp wget curl lynx| ],
38 ftp => [ qw|lwp netftp wget curl ncftp ftp| ],
39 file => [ qw|lwp file| ],
40 rsync => [ qw|rsync| ]
43 ### silly warnings ###
44 local $Params::Check::VERBOSE = 1;
45 local $Params::Check::VERBOSE = 1;
46 local $Module::Load::Conditional::VERBOSE = 0;
47 local $Module::Load::Conditional::VERBOSE = 0;
49 ### see what OS we are on, important for file:// uris ###
50 use constant ON_UNIX => ($^O ne 'MSWin32' and
58 File::Fetch - A generic file fetching mechanism
64 ### build a File::Fetch object ###
65 my $ff = File::Fetch->new(uri => 'http://some.where.com/dir/a.txt');
67 ### fetch the uri to cwd() ###
68 my $where = $ff->fetch() or die $ff->error;
70 ### fetch the uri to /tmp ###
71 my $where = $ff->fetch( to => '/tmp' );
73 ### parsed bits from the uri ###
82 File::Fetch is a generic file fetching mechanism.
84 It allows you to fetch any file pointed to by a C<ftp>, C<http>,
85 C<file>, or C<rsync> uri by a number of different means.
87 See the C<HOW IT WORKS> section further down for details.
91 =head2 $ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' );
93 Parses the uri and creates a corresponding File::Fetch::Item object,
94 that is ready to be C<fetch>ed and returns it.
96 Returns false on failure.
106 uri => { required => 1, store => \$uri },
109 check( $tmpl, \%hash ) or return;
111 ### parse the uri to usable parts ###
112 my $href = __PACKAGE__->_parse_uri( $uri ) or return;
114 ### make it into a FFI object ###
115 my $ffi = File::Fetch::Item->new( %$href ) or return;
118 ### return the object ###
122 ### parses an uri to a hash structure:
124 ### $class->_parse_uri( 'ftp://ftp.cpan.org/pub/mirror/index.txt' )
130 ### host => 'ftp.cpan.org',
131 ### path => '/pub/mirror',
132 ### file => 'index.html'
137 my $uri = shift or return;
139 my $href = { uri => $uri };
141 ### find the scheme ###
142 $uri =~ s|^(\w+)://||;
143 $href->{scheme} = $1;
145 ### file:// paths have no host ###
146 if( $href->{scheme} eq 'file' ) {
147 $href->{path} = $uri;
151 @{$href}{qw|host path|} = $uri =~ m|([^/]*)(/.*)$|s;
154 ### split the path into file + dir ###
155 { my @parts = File::Spec::Unix->splitpath( delete $href->{path} );
156 $href->{path} = $parts[1];
157 $href->{file} = $parts[2];
164 =head2 $ff->fetch( [to => /my/output/dir/] )
166 Fetches the file you requested. By default it writes to C<cwd()>,
167 but you can override that by specifying the C<to> argument.
169 Returns the full path to the downloaded file on success, and false
175 my $self = shift or return;
180 to => { default => cwd(), store => \$to },
183 check( $tmpl, \%hash ) or return;
185 ### create the path if it doesn't exist yet ###
187 eval { mkpath( $to ) };
189 return $self->_error(loc("Could not create path '%1'",$to)) if $@;
192 ### set passive ftp if required ###
193 local $ENV{FTP_PASSIVE} = $FTP_PASSIVE;
196 for my $method ( @{ $METHODS->{$self->scheme} } ) {
197 my $sub = '_'.$method.'_fetch';
199 unless( __PACKAGE__->can($sub) ) {
200 $self->_error(loc("Cannot call method for '%1' -- WEIRD!",
205 ### method is blacklisted ###
206 next if grep { lc $_ eq $method } @$BLACKLIST;
208 ### method is known to fail ###
209 next if $METHOD_FAIL->{$method};
211 if(my $file = $self->$sub(to=>File::Spec->catfile($to,$self->file))){
213 unless( -e $file && -s _ ) {
214 $self->_error(loc("'%1' said it fetched '%2', ".
215 "but it was not created",$method,$file));
217 ### mark the failure ###
218 $METHOD_FAIL->{$method} = 1;
224 my $abs = File::Spec->rel2abs( $file );
231 ### if we got here, we looped over all methods, but we weren't able
238 A C<File::Fetch> object has the following accessors
244 The uri you passed to the constructor
248 The scheme from the uri (like 'file', 'http', etc)
252 The hostname in the uri, will be empty for a 'file' scheme.
256 The path from the uri, will be at least a single '/'.
260 The name of the remote file. Will be used as the name for the local
267 ########################
268 ### _*_fetch methods ###
269 ########################
278 to => { required => 1, store => \$to }
280 check( $tmpl, \%hash ) or return;
282 ### modules required to download with lwp ###
285 'LWP::UserAgent' => '0.0',
286 'HTTP::Request' => '0.0',
287 'HTTP::Status' => '0.0',
292 if( can_load(modules => $use_list) ) {
294 ### setup the uri object
295 my $uri = URI->new( File::Spec::Unix->catfile(
296 $self->path, $self->file
299 ### special rules apply for file:// uris ###
300 $uri->scheme( $self->scheme );
301 $uri->host( $self->scheme eq 'file' ? '' : $self->host );
302 $uri->userinfo("anonymous:$FROM_EMAIL") if $self->scheme ne 'file';
304 ### set up the useragent object
305 my $ua = LWP::UserAgent->new();
306 $ua->timeout( $TIMEOUT ) if $TIMEOUT;
307 $ua->agent( $USER_AGENT );
308 $ua->from( $FROM_EMAIL );
311 my $res = $ua->mirror($uri, $to) or return;
313 ### uptodate or fetched ok ###
314 if ( $res->code == 304 or $res->code == 200 ) {
318 return $self->_error(loc("Fetch failed! HTTP response: %1 %2 [%3]",
319 $res->code, HTTP::Status::status_message($res->code),
324 $METHOD_FAIL->{'lwp'} = 1;
329 ### Net::FTP fetching
336 to => { required => 1, store => \$to }
338 check( $tmpl, \%hash ) or return;
340 ### required modules ###
341 my $use_list = { 'Net::FTP' => 0 };
343 if( can_load( modules => $use_list ) ) {
345 ### make connection ###
347 my @options = ($self->host);
348 push(@options, Timeout => $TIMEOUT) if $TIMEOUT;
349 unless( $ftp = Net::FTP->new( @options ) ) {
350 return $self->_error(loc("Ftp creation failed: %1",$@));
354 unless( $ftp->login( anonymous => $FROM_EMAIL ) ) {
355 return $self->_error(loc("Could not login to '%1'",$self->host));
358 ### set binary mode, just in case ###
361 ### create the remote path
362 ### remember remote paths are unix paths! [#11483]
363 my $remote = File::Spec::Unix->catfile( $self->path, $self->file );
365 ### fetch the file ###
367 unless( $target = $ftp->get( $remote, $to ) ) {
368 return $self->_error(loc("Could not fetch '%1' from '%2'",
369 $remote, $self->host));
378 $METHOD_FAIL->{'netftp'} = 1;
383 ### /bin/wget fetch ###
390 to => { required => 1, store => \$to }
392 check( $tmpl, \%hash ) or return;
394 ### see if we have a wget binary ###
395 if( my $wget = can_run('wget') ) {
397 ### no verboseness, thanks ###
398 my $cmd = [ $wget, '--quiet' ];
400 ### if a timeout is set, add it ###
401 push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT;
403 ### run passive if specified ###
404 push @$cmd, '--passive-ftp' if $FTP_PASSIVE;
406 ### set the output document, add the uri ###
407 push @$cmd, '--output-document', $to, $self->uri;
411 unless( run( command => $cmd, buffer => \$captured, verbose => 0 ) ) {
412 ### wget creates the output document always, even if the fetch
413 ### fails.. so unlink it in that case
416 return $self->_error(loc( "Command failed: %1", $captured || '' ));
422 $METHOD_FAIL->{'wget'} = 1;
428 ### /bin/ftp fetch ###
435 to => { required => 1, store => \$to }
437 check( $tmpl, \%hash ) or return;
439 ### see if we have a wget binary ###
440 if( my $ftp = can_run('ftp') ) {
442 my $fh = FileHandle->new;
444 local $SIG{CHLD} = 'IGNORE';
446 unless ($fh->open("|$ftp -n")) {
447 return $self->_error(loc("%1 creation failed: %2", $ftp, $!));
451 "lcd " . dirname($to),
452 "open " . $self->host,
453 "user anonymous $FROM_EMAIL",
457 "get " . $self->file . " " . $self->file,
461 foreach (@dialog) { $fh->print($_, "\n") }
462 $fh->close or return;
468 ### lynx is stupid - it decompresses any .gz file it finds to be text
469 ### use /bin/lynx to fetch files
476 to => { required => 1, store => \$to }
478 check( $tmpl, \%hash ) or return;
480 ### see if we have a wget binary ###
481 if( my $lynx = can_run('lynx') ) {
484 ### write to the output file ourselves, since lynx ass_u_mes to much
485 my $local = FileHandle->new(">$to")
486 or return $self->_error(loc(
487 "Could not open '%1' for writing: %2",$to,$!));
489 ### dump to stdout ###
493 "-auth=anonymous:$FROM_EMAIL",
496 push @$cmd, "-connect_timeout=$TIMEOUT" if $TIMEOUT;
498 push @$cmd, $self->uri;
502 unless(run( command => $cmd,
503 buffer => \$captured,
506 return $self->_error(loc("Command failed: %1", $captured || ''));
509 ### print to local file ###
510 ### XXX on a 404 with a special error page, $captured will actually
511 ### hold the contents of that page, and make it *appear* like the
512 ### request was a success, when really it wasn't :(
513 ### there doesn't seem to be an option for lynx to change the exit
514 ### code based on a 4XX status or so.
515 ### the closest we can come is using --error_file and parsing that,
516 ### which is very unreliable ;(
517 $local->print( $captured );
518 $local->close or return;
523 $METHOD_FAIL->{'lynx'} = 1;
528 ### use /bin/ncftp to fetch files
535 to => { required => 1, store => \$to }
537 check( $tmpl, \%hash ) or return;
539 ### we can only set passive mode in interactive sesssions, so bail out
540 ### if $FTP_PASSIVE is set
541 return if $FTP_PASSIVE;
543 ### see if we have a wget binary ###
544 if( my $ncftp = can_run('ncftp') ) {
548 '-V', # do not be verbose
549 '-p', $FROM_EMAIL, # email as password
550 $self->host, # hostname
551 dirname($to), # local dir for the file
552 # remote path to the file
553 File::Spec::Unix->catdir( $self->path, $self->file ),
558 unless(run( command => $cmd,
559 buffer => \$captured,
562 return $self->_error(loc("Command failed: %1", $captured || ''));
568 $METHOD_FAIL->{'ncftp'} = 1;
573 ### use /bin/curl to fetch files
580 to => { required => 1, store => \$to }
582 check( $tmpl, \%hash ) or return;
584 if (my $curl = can_run('curl')) {
586 ### these long opts are self explanatory - I like that -jmb
589 push(@$cmd, '--connect-timeout', $TIMEOUT) if $TIMEOUT;
591 push(@$cmd, '--silent') unless $DEBUG;
593 ### curl does the right thing with passive, regardless ###
594 if ($self->scheme eq 'ftp') {
595 push(@$cmd, '--user', "anonymous:$FROM_EMAIL");
598 ### curl doesn't follow 302 (temporarily moved) etc automatically
599 ### so we add --location to enable that.
600 push @$cmd, '--fail', '--location', '--output', $to, $self->uri;
603 unless(run( command => $cmd,
604 buffer => \$captured,
608 return $self->_error(loc("Command failed: %1", $captured || ''));
614 $METHOD_FAIL->{'curl'} = 1;
620 ### use File::Copy for fetching file:// urls ###
621 ### XXX file:// uri to local path conversion is just too weird...
622 ### depend on LWP to do it for us
629 to => { required => 1, store => \$to }
631 check( $tmpl, \%hash ) or return;
633 ### prefix a / on unix systems with a file uri, since it would
634 ### look somewhat like this:
635 ### file://home/kane/file
636 ### wheras windows file uris might look like:
637 ### file://C:/home/kane/file
638 my $path = ON_UNIX ? '/'. $self->path : $self->path;
640 my $remote = File::Spec->catfile( $path, $self->file );
642 ### File::Copy is littered with 'die' statements :( ###
643 my $rv = eval { File::Copy::copy( $remote, $to ) };
645 ### something went wrong ###
647 return $self->_error(loc("Could not copy '%1' to '%2': %3 %4",
648 $remote, $to, $!, $@));
654 ### use /usr/bin/rsync to fetch files
661 to => { required => 1, store => \$to }
663 check( $tmpl, \%hash ) or return;
665 if (my $rsync = can_run('rsync')) {
667 my $cmd = [ $rsync ];
669 ### XXX: rsync has no I/O timeouts at all, by default
670 push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT;
672 push(@$cmd, '--quiet') unless $DEBUG;
674 push @$cmd, $self->uri, $to;
677 unless(run( command => $cmd,
678 buffer => \$captured,
682 return $self->_error(loc("Command failed: %1", $captured || ''));
688 $METHOD_FAIL->{'rsync'} = 1;
693 #################################
697 #################################
701 =head2 $ff->error([BOOL])
703 Returns the last encountered error as string.
704 Pass it a true value to get the C<Carp::longmess()> output instead.
708 ### Error handling, the way Archive::Tar does it ###
716 $longmess = Carp::longmess($error);
718 ### set Archive::Tar::WARN to 0 to disable printing
721 carp $DEBUG ? $longmess : $error;
729 return shift() ? $longmess : $error;
741 File::Fetch is able to fetch a variety of uris, by using several
742 external programs and modules.
744 Below is a mapping of what utilities will be used in what order
745 for what schemes, if available:
748 http => LWP, wget, curl, lynx
749 ftp => LWP, Net::FTP, wget, curl, ncftp, ftp
752 If you'd like to disable the use of one or more of these utilities
753 and/or modules, see the C<$BLACKLIST> variable further down.
755 If a utility or module isn't available, it will be marked in a cache
756 (see the C<$METHOD_FAIL> variable further down), so it will not be
757 tried again. The C<fetch> method will only fail when all options are
758 exhausted, and it was not able to retrieve the file.
760 A special note about fetching files from an ftp uri:
762 By default, all ftp connections are done in passive mode. To change
763 that, see the C<$FTP_PASSIVE> variable further down.
765 Furthermore, ftp uris only support anonymous connections, so no
766 named user/password pair can be passed along.
768 C</bin/ftp> is blacklisted by default; see the C<$BLACKLIST> variable
771 =head1 GLOBAL VARIABLES
773 The behaviour of File::Fetch can be altered by changing the following
776 =head2 $File::Fetch::FROM_EMAIL
778 This is the email address that will be sent as your anonymous ftp
781 Default is C<File-Fetch@example.com>.
783 =head2 $File::Fetch::USER_AGENT
785 This is the useragent as C<LWP> will report it.
787 Default is C<File::Fetch/$VERSION>.
789 =head2 $File::Fetch::FTP_PASSIVE
791 This variable controls whether the environment variable C<FTP_PASSIVE>
792 and any passive switches to commandline tools will be set to true.
796 Note: When $FTP_PASSIVE is true, C<ncftp> will not be used to fetch
797 files, since passive mode can only be set interactively for this binary
799 =head2 $File::Fetch::TIMEOUT
801 When set, controls the network timeout (counted in seconds).
805 =head2 $File::Fetch::WARN
807 This variable controls whether errors encountered internally by
808 C<File::Fetch> should be C<carp>'d or not.
810 Set to false to silence warnings. Inspect the output of the C<error()>
811 method manually to see what went wrong.
815 =head2 $File::Fetch::DEBUG
817 This enables debugging output when calling commandline utilities to
819 This also enables C<Carp::longmess> errors, instead of the regular
822 Good for tracking down why things don't work with your particular
827 =head2 $File::Fetch::BLACKLIST
829 This is an array ref holding blacklisted modules/utilities for fetching
832 To disallow the use of, for example, C<LWP> and C<Net::FTP>, you could
833 set $File::Fetch::BLACKLIST to:
835 $File::Fetch::BLACKLIST = [qw|lwp netftp|]
837 The default blacklist is [qw|ftp|], as C</bin/ftp> is rather unreliable.
839 See the note on C<MAPPING> below.
841 =head2 $File::Fetch::METHOD_FAIL
843 This is a hashref registering what modules/utilities were known to fail
844 for fetching files (mostly because they weren't installed).
846 You can reset this cache by assigning an empty hashref to it, or
847 individually remove keys.
849 See the note on C<MAPPING> below.
854 Here's a quick mapping for the utilities/modules, and their names for
855 the $BLACKLIST, $METHOD_FAIL and other internal functions.
866 =head1 FREQUENTLY ASKED QUESTIONS
868 =head2 So how do I use a proxy with File::Fetch?
870 C<File::Fetch> currently only supports proxies with LWP::UserAgent.
871 You will need to set your environment variables accordingly. For
872 example, to use an ftp proxy:
874 $ENV{ftp_proxy} = 'foo.com';
876 Refer to the LWP::UserAgent manpage for more details.
878 =head2 I used 'lynx' to fetch a file, but its contents is all wrong!
880 C<lynx> can only fetch remote files by dumping its contents to C<STDOUT>,
881 which we in turn capture. If that content is a 'custom' error file
882 (like, say, a C<404 handler>), you will get that contents instead.
884 Sadly, C<lynx> doesn't support any options to return a different exit
885 code on non-C<200 OK> status, giving us no way to tell the difference
886 between a 'successfull' fetch and a custom error page.
888 Therefor, we recommend to only use C<lynx> as a last resort. This is
889 why it is at the back of our list of methods to try as well.
895 =item Implement $PREFER_BIN
897 To indicate to rather use commandline tools than modules
902 Jos Boumans E<lt>kane@cpan.orgE<gt>.
907 copyright (c) 2003 Jos Boumans E<lt>kane@cpan.orgE<gt>.
910 This library is free software;
911 you may redistribute and/or modify it under the same
912 terms as Perl itself.
917 # c-indentation-style: bsd
919 # indent-tabs-mode: nil
921 # vim: expandtab shiftwidth=4: