3 # Copyright (c) 1995-8 Graham Barr <gbarr@pobox.com>. All rights reserved.
4 # This program is free software; you can redistribute it and/or
5 # modify it under the same terms as Perl itself.
7 # Documentation (at end) improved 1996 by Nathan Torkington <gnat@frii.com>.
14 use vars qw(@ISA $VERSION);
22 use Fcntl qw(O_WRONLY O_RDONLY O_APPEND O_CREAT O_TRUNC);
23 # use AutoLoader qw(AUTOLOAD);
25 $VERSION = "2.71"; # $Id: //depot/libnet/Net/FTP.pm#78 $
26 @ISA = qw(Exporter Net::Cmd IO::Socket::INET);
28 # Someday I will "use constant", when I am not bothered to much about
29 # compatability with older releases of perl
31 use vars qw($TELNET_IAC $TELNET_IP $TELNET_DM);
32 ($TELNET_IAC,$TELNET_IP,$TELNET_DM) = (255,244,242);
34 # Name is too long for AutoLoad, it clashes with pasv_xfer
35 sub pasv_xfer_unique {
36 my($sftp,$sfile,$dftp,$dfile) = @_;
37 $sftp->pasv_xfer($sfile,$dftp,$dfile,1);
41 # make a constant so code is fast'ish
42 my $is_os390 = $^O eq 'os390';
43 *trEBCDIC = sub () { $is_os390 }
47 # Having problems with AutoLoader
58 my $fire_type = undef;
60 if(exists($arg{Firewall}) || Net::Config->requires_firewall($peer))
62 $fire = $arg{Firewall}
64 || $NetConfig{ftp_firewall}
71 $fire_type = $arg{FirewallType}
72 || $ENV{FTP_FIREWALL_TYPE}
73 || $NetConfig{firewall_type}
78 my $ftp = $pkg->SUPER::new(PeerAddr => $peer,
79 PeerPort => $arg{Port} || 'ftp(21)',
80 LocalAddr => $arg{'LocalAddr'},
82 Timeout => defined $arg{Timeout}
87 ${*$ftp}{'net_ftp_host'} = $host; # Remote hostname
88 ${*$ftp}{'net_ftp_type'} = 'A'; # ASCII/binary/etc mode
89 ${*$ftp}{'net_ftp_blksize'} = abs($arg{'BlockSize'} || 10240);
91 ${*$ftp}{'net_ftp_localaddr'} = $arg{'LocalAddr'};
93 ${*$ftp}{'net_ftp_firewall'} = $fire
95 ${*$ftp}{'net_ftp_firewall_type'} = $fire_type
96 if(defined $fire_type);
98 ${*$ftp}{'net_ftp_passive'} = int
101 : exists $ENV{FTP_PASSIVE}
104 ? $NetConfig{ftp_ext_passive}
105 : $NetConfig{ftp_int_passive}; # Whew! :-)
107 $ftp->hash(exists $arg{Hash} ? $arg{Hash} : 0, 1024);
111 $ftp->debug(exists $arg{Debug} ? $arg{Debug} : undef);
113 unless ($ftp->response() == CMD_OK)
124 ## User interface methods
128 my $ftp = shift; # self
132 delete ${*$ftp}{'net_ftp_hash'};
135 ($h,$b) = (ref($h)? $h : \*STDERR, $b || 1024);
136 select((select($h), $|=1)[0]);
137 $b = 512 if $b < 512;
138 ${*$ftp}{'net_ftp_hash'} = [$h, $b];
151 sub ascii { shift->type('A',@_); }
152 sub binary { shift->type('I',@_); }
156 carp "TYPE E is unsupported, shall default to I";
162 carp "TYPE L is unsupported, shall default to I";
166 # Allow the user to send a command directly, BE CAREFUL !!
173 $ftp->command( uc $cmd, @_);
181 $ftp->command("SITE", @_);
190 # Server Y2K bug workaround
192 # sigh; some idiotic FTP servers use ("19%d",tm.tm_year) instead of
193 # ("%d",tm.tm_year+1900). This results in an extra digit in the
194 # string returned. To account for this we allow an optional extra
195 # digit in the year. Then if the first two digits are 19 we use the
196 # remainder, otherwise we subtract 1900 from the whole year.
198 $ftp->_MDTM($file) && $ftp->message =~ /((\d\d)(\d\d\d?))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/
199 ? timegm($8,$7,$6,$5,$4-1,$2 eq '19' ? $3 : ($1-1900))
207 if($ftp->supported("SIZE")) {
208 return $ftp->_SIZE($file)
209 ? ($ftp->message =~ /(\d+)$/)[0]
212 elsif($ftp->supported("STAT")) {
215 unless $ftp->_STAT($file) && (@msg = $ftp->message) == 3;
217 foreach $line (@msg) {
218 return (split(/\s+/,$line))[4]
219 if $line =~ /^[-rwx]{10}/
223 my @files = $ftp->dir($file);
225 return (split(/\s+/,$1))[4]
226 if $files[0] =~ /^([-rwx]{10}.*)$/;
233 my($ftp,$user,$pass,$acct) = @_;
234 my($ok,$ruser,$fwtype);
236 unless (defined $user) {
239 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'});
241 ($user,$pass,$acct) = $rc->lpa()
245 $user ||= "anonymous";
248 $fwtype = ${*$ftp}{'net_ftp_firewall_type'}
249 || $NetConfig{'ftp_firewall_type'}
252 if ($fwtype && defined ${*$ftp}{'net_ftp_firewall'}) {
253 if ($fwtype == 1 || $fwtype == 7) {
254 $user .= '@' . ${*$ftp}{'net_ftp_host'};
259 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
261 my($fwuser,$fwpass,$fwacct) = $rc ? $rc->lpa() : ();
264 $user = join('@',$user,$fwuser,${*$ftp}{'net_ftp_host'});
265 $pass = $pass . '@' . $fwpass;
269 $user .= '@' . ${*$ftp}{'net_ftp_host'};
271 elsif ($fwtype == 6) {
272 $fwuser .= '@' . ${*$ftp}{'net_ftp_host'};
275 $ok = $ftp->_USER($fwuser);
277 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
279 $ok = $ftp->_PASS($fwpass || "");
281 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
283 $ok = $ftp->_ACCT($fwacct)
287 $ok = $ftp->command("SITE",${*$ftp}{'net_ftp_host'})->response;
289 elsif ($fwtype == 4) {
290 $ok = $ftp->command("OPEN",${*$ftp}{'net_ftp_host'})->response;
293 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
298 $ok = $ftp->_USER($user);
300 # Some dumb firewalls don't prefix the connection messages
301 $ok = $ftp->response()
302 if ($ok == CMD_OK && $ftp->code == 220 && $user =~ /\@/);
304 if ($ok == CMD_MORE) {
305 unless(defined $pass) {
308 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'}, $ruser);
310 ($ruser,$pass,$acct) = $rc->lpa()
313 $pass = '-anonymous@'
314 if (!defined $pass && (!defined($ruser) || $ruser =~ /^anonymous/o));
317 $ok = $ftp->_PASS($pass || "");
320 $ok = $ftp->_ACCT($acct)
321 if (defined($acct) && ($ok == CMD_MORE || $ok == CMD_OK));
323 if ($fwtype == 7 && $ok == CMD_OK && defined ${*$ftp}{'net_ftp_firewall'}) {
324 my($f,$auth,$resp) = _auth_id($ftp);
325 $ftp->authorize($auth,$resp) if defined($resp);
333 @_ == 2 or croak 'usage: $ftp->account( ACCT )';
336 $ftp->_ACCT($acct) == CMD_OK;
340 my($ftp,$auth,$resp) = @_;
342 unless(defined $resp)
346 $auth ||= eval { (getpwuid($>))[0] } || $ENV{NAME};
348 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'}, $auth)
349 || Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
351 ($auth,$resp) = $rc->lpa()
359 @_ >= 1 || @_ <= 3 or croak 'usage: $ftp->authorize( [AUTH [, RESP]])';
361 my($ftp,$auth,$resp) = &_auth_id;
363 my $ok = $ftp->_AUTH($auth || "");
365 $ok = $ftp->_RESP($resp || "")
366 if ($ok == CMD_MORE);
373 @_ == 3 or croak 'usage: $ftp->rename(FROM, TO)';
375 my($ftp,$from,$to) = @_;
385 my $oldval = ${*$ftp}{'net_ftp_type'};
388 unless (defined $type);
391 unless ($ftp->_TYPE($type,@_));
393 ${*$ftp}{'net_ftp_type'} = join(" ",$type,@_);
402 my $oldval = ${*$ftp}{'net_ftp_allo'};
405 unless (defined $size);
408 unless ($ftp->_ALLO($size,@_));
410 ${*$ftp}{'net_ftp_allo'} = join(" ",$size,@_);
419 send($ftp,pack("CCC", $TELNET_IAC, $TELNET_IP, $TELNET_IAC),MSG_OOB);
421 $ftp->command(pack("C",$TELNET_DM) . "ABOR");
423 ${*$ftp}{'net_ftp_dataconn'}->close()
424 if defined ${*$ftp}{'net_ftp_dataconn'};
428 $ftp->status == CMD_OK;
433 my($ftp,$remote,$local,$where) = @_;
435 my($loc,$len,$buf,$resp,$data);
438 my $localfd = ref($local) || ref(\$local) eq "GLOB";
440 ($local = $remote) =~ s#^.*/##
441 unless(defined $local);
443 croak("Bad remote filename '$remote'\n")
444 if $remote =~ /[\r\n]/s;
446 ${*$ftp}{'net_ftp_rest'} = $where
449 delete ${*$ftp}{'net_ftp_port'};
450 delete ${*$ftp}{'net_ftp_pasv'};
452 $data = $ftp->retr($remote) or
463 unless(sysopen($loc, $local, O_CREAT | O_WRONLY | ($where ? O_APPEND : O_TRUNC)))
465 carp "Cannot open Local file $local: $!\n";
471 if($ftp->type eq 'I' && !binmode($loc))
473 carp "Cannot binmode Local file $local: $!\n";
475 close($loc) unless $localfd;
480 my($count,$hashh,$hashb,$ref) = (0);
482 ($hashh,$hashb) = @$ref
483 if($ref = ${*$ftp}{'net_ftp_hash'});
485 my $blksize = ${*$ftp}{'net_ftp_blksize'};
486 local $\; # Just in case
490 last unless $len = $data->read($buf,$blksize);
492 if (trEBCDIC && $ftp->type ne 'I')
494 $buf = $ftp->toebcdic($buf);
500 print $hashh "#" x (int($count / $hashb));
503 unless(print $loc $buf)
505 carp "Cannot write to Local file $local: $!\n";
513 print $hashh "\n" if $hashh;
519 carp "Cannot close file $local (perhaps disk space) $!\n";
524 unless ($data->close()) # implied $ftp->response
526 carp "Unable to close datastream";
535 @_ == 1 || @_ == 2 or croak 'usage: $ftp->cwd( [ DIR ] )';
539 $dir = "/" unless defined($dir) && $dir =~ /\S/;
548 @_ == 1 or croak 'usage: $ftp->cdup()';
554 @_ == 1 || croak 'usage: $ftp->pwd()';
561 # rmdir( $ftp, $dir, [ $recurse ] )
563 # Removes $dir on remote host via FTP.
564 # $ftp is handle for remote host
566 # If $recurse is TRUE, the directory and deleted recursively.
567 # This means all of its contents and subdirectories.
569 # Initial version contributed by Dinkum Software
573 @_ == 2 || @_ == 3 or croak('usage: $ftp->rmdir( DIR [, RECURSE ] )');
576 my ($ftp, $dir, $recurse) = @_ ;
580 if $ok = $ftp->_RMD( $dir ) or !$recurse;
582 # Try to delete the contents
583 # Get a list of all the files in the directory
584 my $filelist = $ftp->ls($dir);
587 unless $filelist && @$filelist; # failed, it is probably not a directory
589 # Go thru and delete each file or the directory
591 foreach $file (map { m,/, ? $_ : "$dir/$_" } @$filelist)
593 next # successfully deleted the file
594 if $ftp->delete($file);
596 # Failed to delete it, assume its a directory
597 # Recurse and ignore errors, the final rmdir() will
598 # fail on any errors here
600 unless $ok = $ftp->rmdir($file, 1) ;
603 # Directory should be empty
604 # Try to remove the directory again
605 # Pass results directly to caller
606 # If any of the prior deletes failed, this
607 # rmdir() will fail because directory is not empty
608 return $ftp->_RMD($dir) ;
613 @_ == 2 || croak 'usage: $ftp->restart( BYTE_OFFSET )';
615 my($ftp,$where) = @_;
617 ${*$ftp}{'net_ftp_rest'} = $where;
625 @_ == 2 || @_ == 3 or croak 'usage: $ftp->mkdir( DIR [, RECURSE ] )';
627 my($ftp,$dir,$recurse) = @_;
629 $ftp->_MKD($dir) || $recurse or
636 my @path = split(m#(?=/+)#, $dir);
642 $path .= shift @path;
646 $path = $ftp->_extract_path($path);
649 # If the creation of the last element was not successful, see if we
650 # can cd to it, if so then return path
654 my($status,$message) = ($ftp->status,$ftp->message);
657 if($pwd && $ftp->cwd($dir))
666 $ftp->set_status($status,$message);
675 @_ == 2 || croak 'usage: $ftp->delete( FILENAME )';
680 sub put { shift->_store_cmd("stor",@_) }
681 sub put_unique { shift->_store_cmd("stou",@_) }
682 sub append { shift->_store_cmd("appe",@_) }
684 sub nlst { shift->_data_cmd("NLST",@_) }
685 sub list { shift->_data_cmd("LIST",@_) }
686 sub retr { shift->_data_cmd("RETR",@_) }
687 sub stor { shift->_data_cmd("STOR",@_) }
688 sub stou { shift->_data_cmd("STOU",@_) }
689 sub appe { shift->_data_cmd("APPE",@_) }
693 my($ftp,$cmd,$local,$remote) = @_;
694 my($loc,$sock,$len,$buf);
697 my $localfd = ref($local) || ref(\$local) eq "GLOB";
699 unless(defined $remote)
701 croak 'Must specify remote filename with stream input'
704 require File::Basename;
705 $remote = File::Basename::basename($local);
707 if( defined ${*$ftp}{'net_ftp_allo'} )
709 delete ${*$ftp}{'net_ftp_allo'};
712 # if the user hasn't already invoked the alloc method since the last
713 # _store_cmd call, figure out if the local file is a regular file(not
714 # a pipe, or device) and if so get the file size from stat, and send
715 # an ALLO command before sending the STOR, STOU, or APPE command.
716 my $size = -f $local && -s _; # no ALLO if sending data from a pipe
717 $ftp->_ALLO($size) if $size;
719 croak("Bad remote filename '$remote'\n")
720 if $remote =~ /[\r\n]/s;
730 unless(sysopen($loc, $local, O_RDONLY))
732 carp "Cannot open Local file $local: $!\n";
737 if($ftp->type eq 'I' && !binmode($loc))
739 carp "Cannot binmode Local file $local: $!\n";
743 delete ${*$ftp}{'net_ftp_port'};
744 delete ${*$ftp}{'net_ftp_pasv'};
746 $sock = $ftp->_data_cmd($cmd, $remote) or
749 $remote = ($ftp->message =~ /FILE:\s*(.*)/)[0]
750 if 'STOU' eq uc $cmd;
752 my $blksize = ${*$ftp}{'net_ftp_blksize'};
754 my($count,$hashh,$hashb,$ref) = (0);
756 ($hashh,$hashb) = @$ref
757 if($ref = ${*$ftp}{'net_ftp_hash'});
761 last unless $len = read($loc,$buf="",$blksize);
763 if (trEBCDIC && $ftp->type ne 'I')
765 $buf = $ftp->toascii($buf);
771 print $hashh "#" x (int($count / $hashb));
776 unless(defined($wlen = $sock->write($buf,$len)) && $wlen == $len)
781 print $hashh "\n" if $hashh;
786 print $hashh "\n" if $hashh;
794 if ('STOU' eq uc $cmd and $ftp->message =~ m/unique\s+file\s*name\s*:\s*(.*)\)|"(.*)"/)
796 require File::Basename;
797 $remote = File::Basename::basename($+)
805 @_ == 1 || @_ == 2 or croak 'usage: $ftp->port([PORT])';
810 delete ${*$ftp}{'net_ftp_intern_port'};
812 unless(defined $port)
814 # create a Listen socket at same address as the command socket
816 ${*$ftp}{'net_ftp_listen'} ||= IO::Socket::INET->new(Listen => 5,
818 Timeout => $ftp->timeout,
819 LocalAddr => $ftp->sockhost,
822 my $listen = ${*$ftp}{'net_ftp_listen'};
824 my($myport, @myaddr) = ($listen->sockport, split(/\./,$listen->sockhost));
826 $port = join(',', @myaddr, $myport >> 8, $myport & 0xff);
828 ${*$ftp}{'net_ftp_intern_port'} = 1;
831 $ok = $ftp->_PORT($port);
833 ${*$ftp}{'net_ftp_port'} = $port;
838 sub ls { shift->_list_cmd("NLST",@_); }
839 sub dir { shift->_list_cmd("LIST",@_); }
843 @_ == 1 or croak 'usage: $ftp->pasv()';
847 delete ${*$ftp}{'net_ftp_intern_port'};
849 $ftp->_PASV && $ftp->message =~ /(\d+(,\d+)+)/
850 ? ${*$ftp}{'net_ftp_pasv'} = $1
857 ${*$ftp}{'net_ftp_unique'} || undef;
861 @_ == 2 or croak 'usage: $ftp->supported( CMD )';
864 my $hash = ${*$ftp}{'net_ftp_supported'} ||= {};
867 if exists $hash->{$cmd};
869 return $hash->{$cmd} = 0
870 unless $ftp->_HELP($cmd);
872 my $text = $ftp->message;
873 if($text =~ /following\s+commands/i) {
875 while($text =~ /(\*?)(\w+)(\*?)/sg) {
876 $hash->{"\U$2"} = !length("$1$3");
880 $hash->{$cmd} = $text !~ /unimplemented/i;
887 ## Deprecated methods
892 carp "Use of Net::FTP::lsl deprecated, use 'dir'"
899 carp "Use of Net::FTP::authorise deprecated, use 'authorize'"
911 my($ftp, $path) = @_;
913 # This tries to work both with and without the quote doubling
914 # convention (RFC 959 requires it, but the first 3 servers I checked
915 # didn't implement it). It will fail on a server which uses a quote in
916 # the message which isn't a part of or surrounding the path.
918 $ftp->message =~ /(?:^|\s)\"(.*)\"(?:$|\s)/ &&
919 ($path = $1) =~ s/\"\"/\"/g;
925 ## Communication methods
932 my $pkg = "Net::FTP::" . $ftp->type;
934 eval "require " . $pkg;
938 delete ${*$ftp}{'net_ftp_dataconn'};
940 if(defined ${*$ftp}{'net_ftp_pasv'})
942 my @port = split(/,/,${*$ftp}{'net_ftp_pasv'});
944 $data = $pkg->new(PeerAddr => join(".",@port[0..3]),
945 PeerPort => $port[4] * 256 + $port[5],
946 LocalAddr => ${*$ftp}{'net_ftp_localaddr'},
950 elsif(defined ${*$ftp}{'net_ftp_listen'})
952 $data = ${*$ftp}{'net_ftp_listen'}->accept($pkg);
953 close(delete ${*$ftp}{'net_ftp_listen'});
959 $data->timeout($ftp->timeout);
960 ${*$ftp}{'net_ftp_dataconn'} = $data;
961 ${*$data}{'net_ftp_cmd'} = $ftp;
962 ${*$data}{'net_ftp_blksize'} = ${*$ftp}{'net_ftp_blksize'};
973 delete ${*$ftp}{'net_ftp_port'};
974 delete ${*$ftp}{'net_ftp_pasv'};
976 my $data = $ftp->_data_cmd($cmd,@_);
979 unless(defined $data);
982 bless $data, "Net::FTP::A"; # Force ASCII mode
986 my $blksize = ${*$ftp}{'net_ftp_blksize'};
988 while($data->read($databuf,$blksize)) {
992 my $list = [ split(/\n/,$buf) ];
998 for (@$list) { $_ = $ftp->toebcdic($_) }
1001 wantarray ? @{$list}
1010 my $where = delete ${*$ftp}{'net_ftp_rest'} || 0;
1014 croak("Bad argument '$arg'\n")
1015 if $arg =~ /[\r\n]/s;
1018 if(${*$ftp}{'net_ftp_passive'} &&
1019 !defined ${*$ftp}{'net_ftp_pasv'} &&
1020 !defined ${*$ftp}{'net_ftp_port'})
1024 $ok = defined $ftp->pasv;
1025 $ok = $ftp->_REST($where)
1030 $ftp->command($cmd,@_);
1031 $data = $ftp->_dataconn();
1032 $ok = CMD_INFO == $ftp->response();
1036 if $data && $cmd =~ /RETR|LIST|NLST/;
1046 unless (defined ${*$ftp}{'net_ftp_port'} ||
1047 defined ${*$ftp}{'net_ftp_pasv'});
1049 $ok = $ftp->_REST($where)
1055 $ftp->command($cmd,@_);
1058 if(defined ${*$ftp}{'net_ftp_pasv'});
1060 $ok = CMD_INFO == $ftp->response();
1063 unless exists ${*$ftp}{'net_ftp_intern_port'};
1066 my $data = $ftp->_dataconn();
1069 if $data && $cmd =~ /RETR|LIST|NLST/;
1075 close(delete ${*$ftp}{'net_ftp_listen'});
1081 ## Over-ride methods (Net::Cmd)
1084 sub debug_text { $_[2] =~ /^(pass|resp|acct)/i ? "$1 ....\n" : $_[2]; }
1090 delete ${*$ftp}{'net_ftp_port'};
1091 $ftp->SUPER::command(@_);
1097 my $code = $ftp->SUPER::response();
1099 delete ${*$ftp}{'net_ftp_pasv'}
1100 if ($code != CMD_MORE && $code != CMD_INFO);
1107 return ($1, $2 eq "-")
1108 if $_[1] =~ s/^(\d\d\d)(.?)//o;
1112 # Darn MS FTP server is a load of CRAP !!!!
1114 unless ${*$ftp}{'net_cmd_code'} + 0;
1116 (${*$ftp}{'net_cmd_code'},1);
1120 ## Allow 2 servers to talk directly
1124 my($sftp,$sfile,$dftp,$dfile,$unique) = @_;
1126 ($dfile = $sfile) =~ s#.*/##
1127 unless(defined $dfile);
1129 my $port = $sftp->pasv or
1132 $dftp->port($port) or
1136 unless($unique ? $dftp->stou($dfile) : $dftp->stor($dfile));
1138 unless($sftp->retr($sfile) && $sftp->response == CMD_INFO) {
1139 $sftp->retr($sfile);
1145 $dftp->pasv_wait($sftp);
1150 @_ == 2 or croak 'usage: $ftp->pasv_wait(NON_PASV_FTP)';
1152 my($ftp, $non_pasv) = @_;
1153 my($file,$rin,$rout);
1155 vec($rin='',fileno($ftp),1) = 1;
1156 select($rout=$rin, undef, undef, undef);
1159 $non_pasv->response();
1162 unless $ftp->ok() && $non_pasv->ok();
1165 if $ftp->message =~ /unique file name:\s*(\S*)\s*\)/;
1168 if $non_pasv->message =~ /unique file name:\s*(\S*)\s*\)/;
1173 sub cmd { shift->command(@_)->response() }
1175 ########################################
1180 sub _ABOR { shift->command("ABOR")->response() == CMD_OK }
1181 sub _ALLO { shift->command("ALLO",@_)->response() == CMD_OK}
1182 sub _CDUP { shift->command("CDUP")->response() == CMD_OK }
1183 sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
1184 sub _PASV { shift->command("PASV")->response() == CMD_OK }
1185 sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
1186 sub _DELE { shift->command("DELE",@_)->response() == CMD_OK }
1187 sub _CWD { shift->command("CWD", @_)->response() == CMD_OK }
1188 sub _PORT { shift->command("PORT",@_)->response() == CMD_OK }
1189 sub _RMD { shift->command("RMD", @_)->response() == CMD_OK }
1190 sub _MKD { shift->command("MKD", @_)->response() == CMD_OK }
1191 sub _PWD { shift->command("PWD", @_)->response() == CMD_OK }
1192 sub _TYPE { shift->command("TYPE",@_)->response() == CMD_OK }
1193 sub _RNTO { shift->command("RNTO",@_)->response() == CMD_OK }
1194 sub _RESP { shift->command("RESP",@_)->response() == CMD_OK }
1195 sub _MDTM { shift->command("MDTM",@_)->response() == CMD_OK }
1196 sub _SIZE { shift->command("SIZE",@_)->response() == CMD_OK }
1197 sub _HELP { shift->command("HELP",@_)->response() == CMD_OK }
1198 sub _STAT { shift->command("STAT",@_)->response() == CMD_OK }
1199 sub _APPE { shift->command("APPE",@_)->response() == CMD_INFO }
1200 sub _LIST { shift->command("LIST",@_)->response() == CMD_INFO }
1201 sub _NLST { shift->command("NLST",@_)->response() == CMD_INFO }
1202 sub _RETR { shift->command("RETR",@_)->response() == CMD_INFO }
1203 sub _STOR { shift->command("STOR",@_)->response() == CMD_INFO }
1204 sub _STOU { shift->command("STOU",@_)->response() == CMD_INFO }
1205 sub _RNFR { shift->command("RNFR",@_)->response() == CMD_MORE }
1206 sub _REST { shift->command("REST",@_)->response() == CMD_MORE }
1207 sub _USER { shift->command("user",@_)->response() } # A certain brain dead firewall :-)
1208 sub _PASS { shift->command("PASS",@_)->response() }
1209 sub _ACCT { shift->command("ACCT",@_)->response() }
1210 sub _AUTH { shift->command("AUTH",@_)->response() }
1212 sub _SMNT { shift->unsupported(@_) }
1213 sub _MODE { shift->unsupported(@_) }
1214 sub _SYST { shift->unsupported(@_) }
1215 sub _STRU { shift->unsupported(@_) }
1216 sub _REIN { shift->unsupported(@_) }
1224 Net::FTP - FTP Client class
1230 $ftp = Net::FTP->new("some.host.name", Debug => 0)
1231 or die "Cannot connect to some.host.name: $@";
1233 $ftp->login("anonymous",'-anonymous@')
1234 or die "Cannot login ", $ftp->message;
1237 or die "Cannot change working directory ", $ftp->message;
1239 $ftp->get("that.file")
1240 or die "get failed ", $ftp->message;
1246 C<Net::FTP> is a class implementing a simple FTP client in Perl as
1247 described in RFC959. It provides wrappers for a subset of the RFC959
1252 FTP stands for File Transfer Protocol. It is a way of transferring
1253 files between networked machines. The protocol defines a client
1254 (whose commands are provided by this module) and a server (not
1255 implemented in this module). Communication is always initiated by the
1256 client, and the server responds with a message and a status code (and
1257 sometimes with data).
1259 The FTP protocol allows files to be sent to or fetched from the
1260 server. Each transfer involves a B<local file> (on the client) and a
1261 B<remote file> (on the server). In this module, the same file name
1262 will be used for both local and remote if only one is specified. This
1263 means that transferring remote file C</path/to/file> will try to put
1264 that file in C</path/to/file> locally, unless you specify a local file
1267 The protocol also defines several standard B<translations> which the
1268 file can undergo during transfer. These are ASCII, EBCDIC, binary,
1269 and byte. ASCII is the default type, and indicates that the sender of
1270 files will translate the ends of lines to a standard representation
1271 which the receiver will then translate back into their local
1272 representation. EBCDIC indicates the file being transferred is in
1273 EBCDIC format. Binary (also known as image) format sends the data as
1274 a contiguous bit stream. Byte format transfers the data as bytes, the
1275 values of which remain the same regardless of differences in byte size
1276 between the two machines (in theory - in practice you should only use
1277 this if you really know what you're doing).
1283 =item new (HOST [,OPTIONS])
1285 This is the constructor for a new Net::FTP object. C<HOST> is the
1286 name of the remote host to which an FTP connection is required.
1288 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
1289 Possible options are:
1291 B<Firewall> - The name of a machine which acts as an FTP firewall. This can be
1292 overridden by an environment variable C<FTP_FIREWALL>. If specified, and the
1293 given host cannot be directly connected to, then the
1294 connection is made to the firewall machine and the string C<@hostname> is
1295 appended to the login identifier. This kind of setup is also refered to
1298 B<FirewallType> - The type of firewall running on the machine indicated by
1299 B<Firewall>. This can be overridden by an environment variable
1300 C<FTP_FIREWALL_TYPE>. For a list of permissible types, see the description of
1301 ftp_firewall_type in L<Net::Config>.
1303 B<BlockSize> - This is the block size that Net::FTP will use when doing
1304 transfers. (defaults to 10240)
1306 B<Port> - The port number to connect to on the remote machine for the
1309 B<Timeout> - Set a timeout value (defaults to 120)
1311 B<Debug> - debug level (see the debug method in L<Net::Cmd>)
1313 B<Passive> - If set to a non-zero value then all data transfers will be done
1314 using passive mode. This is not usually required except for some I<dumb>
1315 servers, and some firewall configurations. This can also be set by the
1316 environment variable C<FTP_PASSIVE>.
1318 B<Hash> - If given a reference to a file handle (e.g., C<\*STDERR>),
1319 print hash marks (#) on that filehandle every 1024 bytes. This
1320 simply invokes the C<hash()> method for you, so that hash marks
1321 are displayed for all transfers. You can, of course, call C<hash()>
1322 explicitly whenever you'd like.
1324 B<LocalAddr> - Local address to use for all socket connections, this
1325 argument will be passed to L<IO::Socket::INET>
1327 If the constructor fails undef will be returned and an error message will
1334 Unless otherwise stated all methods return either a I<true> or I<false>
1335 value, with I<true> meaning that the operation was a success. When a method
1336 states that it returns a value, failure will be returned as I<undef> or an
1341 =item login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
1343 Log into the remote FTP server with the given login information. If
1344 no arguments are given then the C<Net::FTP> uses the C<Net::Netrc>
1345 package to lookup the login information for the connected host.
1346 If no information is found then a login of I<anonymous> is used.
1347 If no password is given and the login is I<anonymous> then I<anonymous@>
1348 will be used for password.
1350 If the connection is via a firewall then the C<authorize> method will
1351 be called with no arguments.
1353 =item authorize ( [AUTH [, RESP]])
1355 This is a protocol used by some firewall ftp proxies. It is used
1356 to authorise the user to send data out. If both arguments are not specified
1357 then C<authorize> uses C<Net::Netrc> to do a lookup.
1361 Send a SITE command to the remote server and wait for a response.
1363 Returns most significant digit of the response code.
1365 =item type (TYPE [, ARGS])
1367 This method will send the TYPE command to the remote FTP server
1368 to change the type of data transfer. The return value is the previous
1371 =item ascii ([ARGS]) binary([ARGS]) ebcdic([ARGS]) byte([ARGS])
1373 Synonyms for C<type> with the first arguments set correctly
1375 B<NOTE> ebcdic and byte are not fully supported.
1377 =item rename ( OLDNAME, NEWNAME )
1379 Rename a file on the remote FTP server from C<OLDNAME> to C<NEWNAME>. This
1380 is done by sending the RNFR and RNTO commands.
1382 =item delete ( FILENAME )
1384 Send a request to the server to delete C<FILENAME>.
1386 =item cwd ( [ DIR ] )
1388 Attempt to change directory to the directory given in C<$dir>. If
1389 C<$dir> is C<"..">, the FTP C<CDUP> command is used to attempt to
1390 move up one directory. If no directory is given then an attempt is made
1391 to change the directory to the root directory.
1395 Change directory to the parent of the current directory.
1399 Returns the full pathname of the current directory.
1401 =item restart ( WHERE )
1403 Set the byte offset at which to begin the next data transfer. Net::FTP simply
1404 records this value and uses it when during the next data transfer. For this
1405 reason this method will not return an error, but setting it may cause
1406 a subsequent data transfer to fail.
1410 Remove the directory with the name C<DIR>.
1412 =item mkdir ( DIR [, RECURSE ])
1414 Create a new directory with the name C<DIR>. If C<RECURSE> is I<true> then
1415 C<mkdir> will attempt to create all the directories in the given path.
1417 Returns the full pathname to the new directory.
1419 =item ls ( [ DIR ] )
1421 =item alloc ( SIZE [, RECORD_SIZE] )
1423 The alloc command allows you to give the ftp server a hint about the size
1424 of the file about to be transfered using the ALLO ftp command. Some storage
1425 systems use this to make intelligent decisions about how to store the file.
1426 The C<SIZE> argument represents the size of the file in bytes. The
1427 C<RECORD_SIZE> argument indicates a mazimum record or page size for files
1428 sent with a record or page structure.
1430 The size of the file will be determined, and sent to the server
1431 automatically for normal files so that this method need only be called if
1432 you are transfering data from a socket, named pipe, or other stream not
1433 associated with a normal file.
1435 Get a directory listing of C<DIR>, or the current directory.
1437 In an array context, returns a list of lines returned from the server. In
1438 a scalar context, returns a reference to a list.
1440 =item dir ( [ DIR ] )
1442 Get a directory listing of C<DIR>, or the current directory in long format.
1444 In an array context, returns a list of lines returned from the server. In
1445 a scalar context, returns a reference to a list.
1447 =item get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )
1449 Get C<REMOTE_FILE> from the server and store locally. C<LOCAL_FILE> may be
1450 a filename or a filehandle. If not specified, the file will be stored in
1451 the current directory with the same leafname as the remote file.
1453 If C<WHERE> is given then the first C<WHERE> bytes of the file will
1454 not be transfered, and the remaining bytes will be appended to
1455 the local file if it already exists.
1457 Returns C<LOCAL_FILE>, or the generated local file name if C<LOCAL_FILE>
1458 is not given. If an error was encountered undef is returned.
1460 =item put ( LOCAL_FILE [, REMOTE_FILE ] )
1462 Put a file on the remote server. C<LOCAL_FILE> may be a name or a filehandle.
1463 If C<LOCAL_FILE> is a filehandle then C<REMOTE_FILE> must be specified. If
1464 C<REMOTE_FILE> is not specified then the file will be stored in the current
1465 directory with the same leafname as C<LOCAL_FILE>.
1467 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1470 B<NOTE>: If for some reason the transfer does not complete and an error is
1471 returned then the contents that had been transfered will not be remove
1474 =item put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
1476 Same as put but uses the C<STOU> command.
1478 Returns the name of the file on the server.
1480 =item append ( LOCAL_FILE [, REMOTE_FILE ] )
1482 Same as put but appends to the file on the remote server.
1484 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1487 =item unique_name ()
1489 Returns the name of the last file stored on the server using the
1494 Returns the I<modification time> of the given file
1498 Returns the size in bytes for the given file as stored on the remote server.
1500 B<NOTE>: The size reported is the size of the stored file on the remote server.
1501 If the file is subsequently transfered from the server in ASCII mode
1502 and the remote server and local machine have different ideas about
1503 "End Of Line" then the size of file on the local machine after transfer
1506 =item supported ( CMD )
1508 Returns TRUE if the remote server supports the given command.
1510 =item hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] )
1512 Called without parameters, or with the first argument false, hash marks
1513 are suppressed. If the first argument is true but not a reference to a
1514 file handle glob, then \*STDERR is used. The second argument is the number
1515 of bytes per hash mark printed, and defaults to 1024. In all cases the
1516 return value is a reference to an array of two: the filehandle glob reference
1517 and the bytes per hash mark.
1521 The following methods can return different results depending on
1522 how they are called. If the user explicitly calls either
1523 of the C<pasv> or C<port> methods then these methods will
1524 return a I<true> or I<false> value. If the user does not
1525 call either of these methods then the result will be a
1526 reference to a C<Net::FTP::dataconn> based object.
1530 =item nlst ( [ DIR ] )
1532 Send an C<NLST> command to the server, with an optional parameter.
1534 =item list ( [ DIR ] )
1536 Same as C<nlst> but using the C<LIST> command
1540 Begin the retrieval of a file called C<FILE> from the remote server.
1544 Tell the server that you wish to store a file. C<FILE> is the
1545 name of the new file that should be created.
1549 Same as C<stor> but using the C<STOU> command. The name of the unique
1550 file which was created on the server will be available via the C<unique_name>
1551 method after the data connection has been closed.
1555 Tell the server that we want to append some data to the end of a file
1556 called C<FILE>. If this file does not exist then create it.
1560 If for some reason you want to have complete control over the data connection,
1561 this includes generating it and calling the C<response> method when required,
1562 then the user can use these methods to do so.
1564 However calling these methods only affects the use of the methods above that
1565 can return a data connection. They have no effect on methods C<get>, C<put>,
1566 C<put_unique> and those that do not require data connections.
1570 =item port ( [ PORT ] )
1572 Send a C<PORT> command to the server. If C<PORT> is specified then it is sent
1573 to the server. If not, then a listen socket is created and the correct information
1578 Tell the server to go into passive mode. Returns the text that represents the
1579 port on which the server is listening, this text is in a suitable form to
1580 sent to another ftp server using the C<port> method.
1584 The following methods can be used to transfer files between two remote
1585 servers, providing that these two servers can connect directly to each other.
1589 =item pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1591 This method will do a file transfer between two remote ftp servers. If
1592 C<DEST_FILE> is omitted then the leaf name of C<SRC_FILE> will be used.
1594 =item pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1596 Like C<pasv_xfer> but the file is stored on the remote server using
1599 =item pasv_wait ( NON_PASV_SERVER )
1601 This method can be used to wait for a transfer to complete between a passive
1602 server and a non-passive server. The method should be called on the passive
1603 server with the C<Net::FTP> object for the non-passive server passed as an
1608 Abort the current data transfer.
1612 Send the QUIT command to the remote FTP server and close the socket connection.
1616 =head2 Methods for the adventurous
1618 C<Net::FTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
1619 be used to send commands to the remote FTP server.
1623 =item quot (CMD [,ARGS])
1625 Send a command, that Net::FTP does not directly support, to the remote
1626 server and wait for a response.
1628 Returns most significant digit of the response code.
1630 B<WARNING> This call should only be used on commands that do not require
1631 data connections. Misuse of this method can hang the connection.
1635 =head1 THE dataconn CLASS
1637 Some of the methods defined in C<Net::FTP> return an object which will
1638 be derived from this class.The dataconn class itself is derived from
1639 the C<IO::Socket::INET> class, so any normal IO operations can be performed.
1640 However the following methods are defined in the dataconn class and IO should
1641 be performed using these.
1645 =item read ( BUFFER, SIZE [, TIMEOUT ] )
1647 Read C<SIZE> bytes of data from the server and place it into C<BUFFER>, also
1648 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1649 given, the timeout value from the command connection will be used.
1651 Returns the number of bytes read before any <CRLF> translation.
1653 =item write ( BUFFER, SIZE [, TIMEOUT ] )
1655 Write C<SIZE> bytes of data from C<BUFFER> to the server, also
1656 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1657 given, the timeout value from the command connection will be used.
1659 Returns the number of bytes written before any <CRLF> translation.
1663 Returns the number of bytes read so far.
1667 Abort the current data transfer.
1671 Close the data connection and get a response from the FTP server. Returns
1672 I<true> if the connection was closed successfully and the first digit of
1673 the response from the server was a '2'.
1677 =head1 UNIMPLEMENTED
1679 The following RFC959 commands have not been implemented:
1685 Mount a different file system structure without changing login or
1686 accounting information.
1690 Ask the server for "helpful information" (that's what the RFC says) on
1691 the commands it accepts.
1695 Specifies transfer mode (stream, block or compressed) for file to be
1700 Request remote server system identification.
1704 Request remote server status.
1708 Specifies file structure for file to be transferred.
1712 Reinitialize the connection, flushing all I/O and account information.
1716 =head1 REPORTING BUGS
1718 When reporting bugs/problems please include as much information as possible.
1719 It may be difficult for me to reproduce the problem as almost every setup
1722 A small script which yields the problem will probably be of help. It would
1723 also be useful if this script was run with the extra options C<Debug => 1>
1724 passed to the constructor, and the output sent with the bug report. If you
1725 cannot include a small script then please include a Debug trace from a
1726 run of your program which does yield the problem.
1730 Graham Barr <gbarr@pobox.com>
1737 ftp(1), ftpd(8), RFC 959
1738 http://www.cis.ohio-state.edu/htbin/rfc/rfc959.html
1742 For an example of the use of Net::FTP see
1746 =item http://www.csh.rit.edu/~adam/Progs/autoftp-2.0.tar.gz
1748 C<autoftp> is a program that can retrieve, send, or list files via
1749 the FTP protocol in a non-interactive manner.
1755 Henry Gabryjelski <henryg@WPI.EDU> - for the suggestion of creating directories
1758 Nathan Torkington <gnat@frii.com> - for some input on the documentation.
1760 Roderick Schertler <roderick@gate.net> - for various inputs
1764 Copyright (c) 1995-1998 Graham Barr. All rights reserved.
1765 This program is free software; you can redistribute it and/or modify it
1766 under the same terms as Perl itself.
1770 I<$Id: //depot/libnet/Net/FTP.pm#78 $>