8 use File::Basename qw[dirname];
12 use IPC::Cmd qw[can_run run];
13 use File::Path qw[mkpath];
14 use Params::Check qw[check];
15 use Module::Load::Conditional qw[can_load];
16 use Locale::Maketext::Simple Style => 'gettext';
18 use vars qw[ $VERBOSE $PREFER_BIN $FROM_EMAIL $USER_AGENT
19 $BLACKLIST $METHOD_FAIL $VERSION $METHODS
20 $FTP_PASSIVE $TIMEOUT $DEBUG $WARN
23 use constant QUOTE => do { $^O eq 'MSWin32' ? q["] : q['] };
27 $PREFER_BIN = 0; # XXX TODO implement
28 $FROM_EMAIL = 'File-Fetch@example.com';
29 $USER_AGENT = 'File::Fetch/$VERSION';
30 $BLACKLIST = [qw|ftp|];
37 ### methods available to fetch the file depending on the scheme
39 http => [ qw|lwp wget curl lynx| ],
40 ftp => [ qw|lwp netftp wget curl ncftp ftp| ],
41 file => [ qw|lwp file| ],
42 rsync => [ qw|rsync| ]
45 ### silly warnings ###
46 local $Params::Check::VERBOSE = 1;
47 local $Params::Check::VERBOSE = 1;
48 local $Module::Load::Conditional::VERBOSE = 0;
49 local $Module::Load::Conditional::VERBOSE = 0;
51 ### see what OS we are on, important for file:// uris ###
52 use constant ON_UNIX => ($^O ne 'MSWin32' and
60 File::Fetch - A generic file fetching mechanism
66 ### build a File::Fetch object ###
67 my $ff = File::Fetch->new(uri => 'http://some.where.com/dir/a.txt');
69 ### fetch the uri to cwd() ###
70 my $where = $ff->fetch() or die $ff->error;
72 ### fetch the uri to /tmp ###
73 my $where = $ff->fetch( to => '/tmp' );
75 ### parsed bits from the uri ###
84 File::Fetch is a generic file fetching mechanism.
86 It allows you to fetch any file pointed to by a C<ftp>, C<http>,
87 C<file>, or C<rsync> uri by a number of different means.
89 See the C<HOW IT WORKS> section further down for details.
93 A C<File::Fetch> object has the following accessors
99 The uri you passed to the constructor
103 The scheme from the uri (like 'file', 'http', etc)
107 The hostname in the uri, will be empty for a 'file' scheme.
111 The path from the uri, will be at least a single '/'.
115 The name of the remote file. For the local file name, the
116 result of $ff->output_file will be used.
121 ##########################
122 ### Object & Accessors ###
123 ##########################
126 ### template for new() and autogenerated accessors ###
128 scheme => { default => 'http' },
129 host => { default => 'localhost' },
130 path => { default => '/' },
131 file => { required => 1 },
132 uri => { required => 1 },
133 _error_msg => { no_override => 1 },
134 _error_msg_long => { no_override => 1 },
137 for my $method ( keys %$Tmpl ) {
141 $self->{$method} = $_[0] if @_;
142 return $self->{$method};
150 my $args = check( $Tmpl, \%hash ) or return;
154 if( lc($args->scheme) ne 'file' and not $args->host ) {
155 return File::Fetch->_error(loc(
156 "Hostname required when fetching from '%1'",$args->scheme));
159 for (qw[path file]) {
160 unless( $args->$_ ) {
161 return File::Fetch->_error(loc("No '%1' specified",$_));
169 =item $ff->output_file
171 The name of the output file. This is the same as $ff->file,
172 but any query parameters are stripped off. For example:
174 http://example.com/index.html?x=y
176 would make the output file be C<index.html> rather than
185 my $file = $self->file;
192 ### XXX do this or just point to URI::Escape?
193 # =head2 $esc_uri = $ff->escaped_uri
197 # ### most of this is stolen straight from URI::escape
198 # { ### Build a char->hex map
199 # my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255;
203 # my $uri = $self->uri;
205 # ### Default unsafe characters. RFC 2732 ^(uric - reserved)
206 # $uri =~ s/([^A-Za-z0-9\-_.!~*'()])/
207 # $escapes{$1} || $self->_fail_hi($1)/ge;
217 # "Can't escape '%1', try using the '%2' module instead",
218 # sprintf("\\x{%04X}", ord($char)), 'URI::Escape'
231 =head2 $ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' );
233 Parses the uri and creates a corresponding File::Fetch::Item object,
234 that is ready to be C<fetch>ed and returns it.
236 Returns false on failure.
246 uri => { required => 1, store => \$uri },
249 check( $tmpl, \%hash ) or return;
251 ### parse the uri to usable parts ###
252 my $href = __PACKAGE__->_parse_uri( $uri ) or return;
254 ### make it into a FFI object ###
255 my $ff = File::Fetch->_create( %$href ) or return;
258 ### return the object ###
262 ### parses an uri to a hash structure:
264 ### $class->_parse_uri( 'ftp://ftp.cpan.org/pub/mirror/index.txt' )
270 ### host => 'ftp.cpan.org',
271 ### path => '/pub/mirror',
272 ### file => 'index.html'
277 my $uri = shift or return;
279 my $href = { uri => $uri };
281 ### find the scheme ###
282 $uri =~ s|^(\w+)://||;
283 $href->{scheme} = $1;
285 ### file:// paths have no host ###
286 if( $href->{scheme} eq 'file' ) {
287 $href->{path} = $uri;
291 @{$href}{qw|host path|} = $uri =~ m|([^/]*)(/.*)$|s;
294 ### split the path into file + dir ###
295 { my @parts = File::Spec::Unix->splitpath( delete $href->{path} );
296 $href->{path} = $parts[1];
297 $href->{file} = $parts[2];
304 =head2 $ff->fetch( [to => /my/output/dir/] )
306 Fetches the file you requested. By default it writes to C<cwd()>,
307 but you can override that by specifying the C<to> argument.
309 Returns the full path to the downloaded file on success, and false
315 my $self = shift or return;
320 to => { default => cwd(), store => \$to },
323 check( $tmpl, \%hash ) or return;
325 ### create the path if it doesn't exist yet ###
327 eval { mkpath( $to ) };
329 return $self->_error(loc("Could not create path '%1'",$to)) if $@;
332 ### set passive ftp if required ###
333 local $ENV{FTP_PASSIVE} = $FTP_PASSIVE;
336 for my $method ( @{ $METHODS->{$self->scheme} } ) {
337 my $sub = '_'.$method.'_fetch';
339 unless( __PACKAGE__->can($sub) ) {
340 $self->_error(loc("Cannot call method for '%1' -- WEIRD!",
345 ### method is blacklisted ###
346 next if grep { lc $_ eq $method } @$BLACKLIST;
348 ### method is known to fail ###
349 next if $METHOD_FAIL->{$method};
351 ### there's serious issues with IPC::Run and quoting of command
352 ### line arguments. using quotes in the wrong place breaks things,
353 ### and in the case of say,
354 ### C:\cygwin\bin\wget.EXE --quiet --passive-ftp --output-document
355 ### "index.html" "http://www.cpan.org/index.html?q=1&y=2"
356 ### it doesn't matter how you quote, it always fails.
357 local $IPC::Cmd::USE_IPC_RUN = 0;
359 if( my $file = $self->$sub(
360 to => File::Spec->catfile( $to, $self->output_file )
363 unless( -e $file && -s _ ) {
364 $self->_error(loc("'%1' said it fetched '%2', ".
365 "but it was not created",$method,$file));
367 ### mark the failure ###
368 $METHOD_FAIL->{$method} = 1;
374 my $abs = File::Spec->rel2abs( $file );
381 ### if we got here, we looped over all methods, but we weren't able
386 ########################
387 ### _*_fetch methods ###
388 ########################
397 to => { required => 1, store => \$to }
399 check( $tmpl, \%hash ) or return;
401 ### modules required to download with lwp ###
404 'LWP::UserAgent' => '0.0',
405 'HTTP::Request' => '0.0',
406 'HTTP::Status' => '0.0',
411 if( can_load(modules => $use_list) ) {
413 ### setup the uri object
414 my $uri = URI->new( File::Spec::Unix->catfile(
415 $self->path, $self->file
418 ### special rules apply for file:// uris ###
419 $uri->scheme( $self->scheme );
420 $uri->host( $self->scheme eq 'file' ? '' : $self->host );
421 $uri->userinfo("anonymous:$FROM_EMAIL") if $self->scheme ne 'file';
423 ### set up the useragent object
424 my $ua = LWP::UserAgent->new();
425 $ua->timeout( $TIMEOUT ) if $TIMEOUT;
426 $ua->agent( $USER_AGENT );
427 $ua->from( $FROM_EMAIL );
430 my $res = $ua->mirror($uri, $to) or return;
432 ### uptodate or fetched ok ###
433 if ( $res->code == 304 or $res->code == 200 ) {
437 return $self->_error(loc("Fetch failed! HTTP response: %1 %2 [%3]",
438 $res->code, HTTP::Status::status_message($res->code),
443 $METHOD_FAIL->{'lwp'} = 1;
448 ### Net::FTP fetching
455 to => { required => 1, store => \$to }
457 check( $tmpl, \%hash ) or return;
459 ### required modules ###
460 my $use_list = { 'Net::FTP' => 0 };
462 if( can_load( modules => $use_list ) ) {
464 ### make connection ###
466 my @options = ($self->host);
467 push(@options, Timeout => $TIMEOUT) if $TIMEOUT;
468 unless( $ftp = Net::FTP->new( @options ) ) {
469 return $self->_error(loc("Ftp creation failed: %1",$@));
473 unless( $ftp->login( anonymous => $FROM_EMAIL ) ) {
474 return $self->_error(loc("Could not login to '%1'",$self->host));
477 ### set binary mode, just in case ###
480 ### create the remote path
481 ### remember remote paths are unix paths! [#11483]
482 my $remote = File::Spec::Unix->catfile( $self->path, $self->file );
484 ### fetch the file ###
486 unless( $target = $ftp->get( $remote, $to ) ) {
487 return $self->_error(loc("Could not fetch '%1' from '%2'",
488 $remote, $self->host));
497 $METHOD_FAIL->{'netftp'} = 1;
502 ### /bin/wget fetch ###
509 to => { required => 1, store => \$to }
511 check( $tmpl, \%hash ) or return;
513 ### see if we have a wget binary ###
514 if( my $wget = can_run('wget') ) {
516 ### no verboseness, thanks ###
517 my $cmd = [ $wget, '--quiet' ];
519 ### if a timeout is set, add it ###
520 push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT;
522 ### run passive if specified ###
523 push @$cmd, '--passive-ftp' if $FTP_PASSIVE;
525 ### set the output document, add the uri ###
526 push @$cmd, '--output-document',
527 ### DO NOT quote things for IPC::Run, it breaks stuff.
528 $IPC::Cmd::USE_IPC_RUN
530 : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE);
534 unless(run( command => $cmd,
535 buffer => \$captured,
538 ### wget creates the output document always, even if the fetch
539 ### fails.. so unlink it in that case
542 return $self->_error(loc( "Command failed: %1", $captured || '' ));
548 $METHOD_FAIL->{'wget'} = 1;
554 ### /bin/ftp fetch ###
561 to => { required => 1, store => \$to }
563 check( $tmpl, \%hash ) or return;
565 ### see if we have a ftp binary ###
566 if( my $ftp = can_run('ftp') ) {
568 my $fh = FileHandle->new;
570 local $SIG{CHLD} = 'IGNORE';
572 unless ($fh->open("|$ftp -n")) {
573 return $self->_error(loc("%1 creation failed: %2", $ftp, $!));
577 "lcd " . dirname($to),
578 "open " . $self->host,
579 "user anonymous $FROM_EMAIL",
583 "get " . $self->file . " " . $self->output_file,
587 foreach (@dialog) { $fh->print($_, "\n") }
588 $fh->close or return;
594 ### lynx is stupid - it decompresses any .gz file it finds to be text
595 ### use /bin/lynx to fetch files
602 to => { required => 1, store => \$to }
604 check( $tmpl, \%hash ) or return;
606 ### see if we have a lynx binary ###
607 if( my $lynx = can_run('lynx') ) {
609 unless( IPC::Cmd->can_capture_buffer ) {
610 $METHOD_FAIL->{'lynx'} = 1;
612 return $self->_error(loc(
613 "Can not capture buffers. Can not use '%1' to fetch files",
617 ### write to the output file ourselves, since lynx ass_u_mes to much
618 my $local = FileHandle->new(">$to")
619 or return $self->_error(loc(
620 "Could not open '%1' for writing: %2",$to,$!));
622 ### dump to stdout ###
626 "-auth=anonymous:$FROM_EMAIL",
629 push @$cmd, "-connect_timeout=$TIMEOUT" if $TIMEOUT;
631 ### DO NOT quote things for IPC::Run, it breaks stuff.
632 push @$cmd, $IPC::Cmd::USE_IPC_RUN
634 : QUOTE. $self->uri .QUOTE;
639 unless(run( command => $cmd,
640 buffer => \$captured,
643 return $self->_error(loc("Command failed: %1", $captured || ''));
646 ### print to local file ###
647 ### XXX on a 404 with a special error page, $captured will actually
648 ### hold the contents of that page, and make it *appear* like the
649 ### request was a success, when really it wasn't :(
650 ### there doesn't seem to be an option for lynx to change the exit
651 ### code based on a 4XX status or so.
652 ### the closest we can come is using --error_file and parsing that,
653 ### which is very unreliable ;(
654 $local->print( $captured );
655 $local->close or return;
660 $METHOD_FAIL->{'lynx'} = 1;
665 ### use /bin/ncftp to fetch files
672 to => { required => 1, store => \$to }
674 check( $tmpl, \%hash ) or return;
676 ### we can only set passive mode in interactive sesssions, so bail out
677 ### if $FTP_PASSIVE is set
678 return if $FTP_PASSIVE;
680 ### see if we have a ncftp binary ###
681 if( my $ncftp = can_run('ncftp') ) {
685 '-V', # do not be verbose
686 '-p', $FROM_EMAIL, # email as password
687 $self->host, # hostname
688 dirname($to), # local dir for the file
689 # remote path to the file
690 ### DO NOT quote things for IPC::Run, it breaks stuff.
691 $IPC::Cmd::USE_IPC_RUN
692 ? File::Spec::Unix->catdir( $self->path, $self->file )
693 : QUOTE. File::Spec::Unix->catdir(
694 $self->path, $self->file ) .QUOTE
700 unless(run( command => $cmd,
701 buffer => \$captured,
704 return $self->_error(loc("Command failed: %1", $captured || ''));
710 $METHOD_FAIL->{'ncftp'} = 1;
715 ### use /bin/curl to fetch files
722 to => { required => 1, store => \$to }
724 check( $tmpl, \%hash ) or return;
726 if (my $curl = can_run('curl')) {
728 ### these long opts are self explanatory - I like that -jmb
731 push(@$cmd, '--connect-timeout', $TIMEOUT) if $TIMEOUT;
733 push(@$cmd, '--silent') unless $DEBUG;
735 ### curl does the right thing with passive, regardless ###
736 if ($self->scheme eq 'ftp') {
737 push(@$cmd, '--user', "anonymous:$FROM_EMAIL");
740 ### curl doesn't follow 302 (temporarily moved) etc automatically
741 ### so we add --location to enable that.
742 push @$cmd, '--fail', '--location', '--output',
743 ### DO NOT quote things for IPC::Run, it breaks stuff.
744 $IPC::Cmd::USE_IPC_RUN
746 : (QUOTE. $to .QUOTE, QUOTE. $self->uri .QUOTE);
749 unless(run( command => $cmd,
750 buffer => \$captured,
754 return $self->_error(loc("Command failed: %1", $captured || ''));
760 $METHOD_FAIL->{'curl'} = 1;
766 ### use File::Copy for fetching file:// urls ###
767 ### XXX file:// uri to local path conversion is just too weird...
768 ### depend on LWP to do it for us
775 to => { required => 1, store => \$to }
777 check( $tmpl, \%hash ) or return;
779 ### prefix a / on unix systems with a file uri, since it would
780 ### look somewhat like this:
781 ### file://home/kane/file
782 ### wheras windows file uris might look like:
783 ### file://C:/home/kane/file
784 my $path = ON_UNIX ? '/'. $self->path : $self->path;
786 my $remote = File::Spec->catfile( $path, $self->file );
788 ### File::Copy is littered with 'die' statements :( ###
789 my $rv = eval { File::Copy::copy( $remote, $to ) };
791 ### something went wrong ###
793 return $self->_error(loc("Could not copy '%1' to '%2': %3 %4",
794 $remote, $to, $!, $@));
800 ### use /usr/bin/rsync to fetch files
807 to => { required => 1, store => \$to }
809 check( $tmpl, \%hash ) or return;
811 if (my $rsync = can_run('rsync')) {
813 my $cmd = [ $rsync ];
815 ### XXX: rsync has no I/O timeouts at all, by default
816 push(@$cmd, '--timeout=' . $TIMEOUT) if $TIMEOUT;
818 push(@$cmd, '--quiet') unless $DEBUG;
820 ### DO NOT quote things for IPC::Run, it breaks stuff.
821 push @$cmd, $IPC::Cmd::USE_IPC_RUN
823 : (QUOTE. $self->uri .QUOTE, QUOTE. $to .QUOTE);
826 unless(run( command => $cmd,
827 buffer => \$captured,
831 return $self->_error(loc("Command failed: %1", $captured || ''));
837 $METHOD_FAIL->{'rsync'} = 1;
842 #################################
846 #################################
850 =head2 $ff->error([BOOL])
852 Returns the last encountered error as string.
853 Pass it a true value to get the C<Carp::longmess()> output instead.
857 ### error handling the way Archive::Extract does it
862 $self->_error_msg( $error );
863 $self->_error_msg_long( Carp::longmess($error) );
866 carp $DEBUG ? $self->_error_msg_long : $self->_error_msg;
874 return shift() ? $self->_error_msg_long : $self->_error_msg;
884 File::Fetch is able to fetch a variety of uris, by using several
885 external programs and modules.
887 Below is a mapping of what utilities will be used in what order
888 for what schemes, if available:
891 http => LWP, wget, curl, lynx
892 ftp => LWP, Net::FTP, wget, curl, ncftp, ftp
895 If you'd like to disable the use of one or more of these utilities
896 and/or modules, see the C<$BLACKLIST> variable further down.
898 If a utility or module isn't available, it will be marked in a cache
899 (see the C<$METHOD_FAIL> variable further down), so it will not be
900 tried again. The C<fetch> method will only fail when all options are
901 exhausted, and it was not able to retrieve the file.
903 A special note about fetching files from an ftp uri:
905 By default, all ftp connections are done in passive mode. To change
906 that, see the C<$FTP_PASSIVE> variable further down.
908 Furthermore, ftp uris only support anonymous connections, so no
909 named user/password pair can be passed along.
911 C</bin/ftp> is blacklisted by default; see the C<$BLACKLIST> variable
914 =head1 GLOBAL VARIABLES
916 The behaviour of File::Fetch can be altered by changing the following
919 =head2 $File::Fetch::FROM_EMAIL
921 This is the email address that will be sent as your anonymous ftp
924 Default is C<File-Fetch@example.com>.
926 =head2 $File::Fetch::USER_AGENT
928 This is the useragent as C<LWP> will report it.
930 Default is C<File::Fetch/$VERSION>.
932 =head2 $File::Fetch::FTP_PASSIVE
934 This variable controls whether the environment variable C<FTP_PASSIVE>
935 and any passive switches to commandline tools will be set to true.
939 Note: When $FTP_PASSIVE is true, C<ncftp> will not be used to fetch
940 files, since passive mode can only be set interactively for this binary
942 =head2 $File::Fetch::TIMEOUT
944 When set, controls the network timeout (counted in seconds).
948 =head2 $File::Fetch::WARN
950 This variable controls whether errors encountered internally by
951 C<File::Fetch> should be C<carp>'d or not.
953 Set to false to silence warnings. Inspect the output of the C<error()>
954 method manually to see what went wrong.
958 =head2 $File::Fetch::DEBUG
960 This enables debugging output when calling commandline utilities to
962 This also enables C<Carp::longmess> errors, instead of the regular
965 Good for tracking down why things don't work with your particular
970 =head2 $File::Fetch::BLACKLIST
972 This is an array ref holding blacklisted modules/utilities for fetching
975 To disallow the use of, for example, C<LWP> and C<Net::FTP>, you could
976 set $File::Fetch::BLACKLIST to:
978 $File::Fetch::BLACKLIST = [qw|lwp netftp|]
980 The default blacklist is [qw|ftp|], as C</bin/ftp> is rather unreliable.
982 See the note on C<MAPPING> below.
984 =head2 $File::Fetch::METHOD_FAIL
986 This is a hashref registering what modules/utilities were known to fail
987 for fetching files (mostly because they weren't installed).
989 You can reset this cache by assigning an empty hashref to it, or
990 individually remove keys.
992 See the note on C<MAPPING> below.
997 Here's a quick mapping for the utilities/modules, and their names for
998 the $BLACKLIST, $METHOD_FAIL and other internal functions.
1009 =head1 FREQUENTLY ASKED QUESTIONS
1011 =head2 So how do I use a proxy with File::Fetch?
1013 C<File::Fetch> currently only supports proxies with LWP::UserAgent.
1014 You will need to set your environment variables accordingly. For
1015 example, to use an ftp proxy:
1017 $ENV{ftp_proxy} = 'foo.com';
1019 Refer to the LWP::UserAgent manpage for more details.
1021 =head2 I used 'lynx' to fetch a file, but its contents is all wrong!
1023 C<lynx> can only fetch remote files by dumping its contents to C<STDOUT>,
1024 which we in turn capture. If that content is a 'custom' error file
1025 (like, say, a C<404 handler>), you will get that contents instead.
1027 Sadly, C<lynx> doesn't support any options to return a different exit
1028 code on non-C<200 OK> status, giving us no way to tell the difference
1029 between a 'successfull' fetch and a custom error page.
1031 Therefor, we recommend to only use C<lynx> as a last resort. This is
1032 why it is at the back of our list of methods to try as well.
1034 =head2 Files I'm trying to fetch have reserved characters or non-ASCII characters in them. What do I do?
1036 C<File::Fetch> is relatively smart about things. When trying to write
1037 a file to disk, it removes the C<query parameters> (see the
1038 C<output_file> method for details) from the file name before creating
1039 it. In most cases this suffices.
1041 If you have any other characters you need to escape, please install
1042 the C<URI::Escape> module from CPAN, and pre-encode your URI before
1043 passing it to C<File::Fetch>. You can read about the details of URIs
1044 and URI encoding here:
1046 http://www.faqs.org/rfcs/rfc2396.html
1052 =item Implement $PREFER_BIN
1054 To indicate to rather use commandline tools than modules
1058 This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
1062 This module is copyright (c) 2003-2007 Jos Boumans
1063 E<lt>kane@cpan.orgE<gt>. All rights reserved.
1065 This library is free software;
1066 you may redistribute and/or modify it under the same
1067 terms as Perl itself.
1072 # c-indentation-style: bsd
1074 # indent-tabs-mode: nil
1076 # vim: expandtab shiftwidth=4: