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.62"; # $Id: //depot/libnet/Net/FTP.pm#64 $
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}
77 my $ftp = $pkg->SUPER::new(PeerAddr => $peer,
78 PeerPort => $arg{Port} || 'ftp(21)',
80 Timeout => defined $arg{Timeout}
85 ${*$ftp}{'net_ftp_host'} = $host; # Remote hostname
86 ${*$ftp}{'net_ftp_type'} = 'A'; # ASCII/binary/etc mode
87 ${*$ftp}{'net_ftp_blksize'} = abs($arg{'BlockSize'} || 10240);
89 ${*$ftp}{'net_ftp_firewall'} = $fire
91 ${*$ftp}{'net_ftp_firewall_type'} = $fire_type
92 if(defined $fire_type);
94 ${*$ftp}{'net_ftp_passive'} = int
97 : exists $ENV{FTP_PASSIVE}
100 ? $NetConfig{ftp_ext_passive}
101 : $NetConfig{ftp_int_passive}; # Whew! :-)
103 $ftp->hash(exists $arg{Hash} ? $arg{Hash} : 0, 1024);
107 $ftp->debug(exists $arg{Debug} ? $arg{Debug} : undef);
109 unless ($ftp->response() == CMD_OK)
120 ## User interface methods
124 my $ftp = shift; # self
128 delete ${*$ftp}{'net_ftp_hash'};
131 ($h,$b) = (ref($h)? $h : \*STDERR, $b || 1024);
132 select((select($h), $|=1)[0]);
133 $b = 512 if $b < 512;
134 ${*$ftp}{'net_ftp_hash'} = [$h, $b];
147 sub ascii { shift->type('A',@_); }
148 sub binary { shift->type('I',@_); }
152 carp "TYPE E is unsupported, shall default to I";
158 carp "TYPE L is unsupported, shall default to I";
162 # Allow the user to send a command directly, BE CAREFUL !!
169 $ftp->command( uc $cmd, @_);
177 $ftp->command("SITE", @_);
186 # Server Y2K bug workaround
188 # sigh; some idiotic FTP servers use ("19%d",tm.tm_year) instead of
189 # ("%d",tm.tm_year+1900). This results in an extra digit in the
190 # string returned. To account for this we allow an optional extra
191 # digit in the year. Then if the first two digits are 19 we use the
192 # remainder, otherwise we subtract 1900 from the whole year.
194 $ftp->_MDTM($file) && $ftp->message =~ /((\d\d)(\d\d\d?))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/
195 ? timegm($8,$7,$6,$5,$4-1,$2 eq '19' ? $3 : ($1-1900))
203 if($ftp->supported("SIZE")) {
204 return $ftp->_SIZE($file)
205 ? ($ftp->message =~ /(\d+)$/)[0]
208 elsif($ftp->supported("STAT")) {
211 unless $ftp->_STAT($file) && (@msg = $ftp->message) == 3;
213 foreach $line (@msg) {
214 return (split(/\s+/,$line))[4]
215 if $line =~ /^[-rwx]{10}/
219 my @files = $ftp->dir($file);
221 return (split(/\s+/,$1))[4]
222 if $files[0] =~ /^([-rwx]{10}.*)$/;
229 my($ftp,$user,$pass,$acct) = @_;
230 my($ok,$ruser,$fwtype);
232 unless (defined $user) {
235 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'});
237 ($user,$pass,$acct) = $rc->lpa()
241 $user ||= "anonymous";
244 $fwtype = ${*$ftp}{'net_ftp_firewall_type'}
245 || $NetConfig{'ftp_firewall_type'}
248 if ($fwtype && defined ${*$ftp}{'net_ftp_firewall'}) {
249 if ($fwtype == 1 || $fwtype == 7) {
250 $user .= '@' . ${*$ftp}{'net_ftp_host'};
255 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
257 my($fwuser,$fwpass,$fwacct) = $rc ? $rc->lpa() : ();
260 $user = join('@',$user,$fwuser,${*$ftp}{'net_ftp_host'});
261 $pass = $pass . '@' . $fwpass;
265 $user .= '@' . ${*$ftp}{'net_ftp_host'};
267 elsif ($fwtype == 6) {
268 $fwuser .= '@' . ${*$ftp}{'net_ftp_host'};
271 $ok = $ftp->_USER($fwuser);
273 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
275 $ok = $ftp->_PASS($fwpass || "");
277 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
279 $ok = $ftp->_ACCT($fwacct)
283 $ok = $ftp->command("SITE",${*$ftp}{'net_ftp_host'})->response;
285 elsif ($fwtype == 4) {
286 $ok = $ftp->command("OPEN",${*$ftp}{'net_ftp_host'})->response;
289 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
294 $ok = $ftp->_USER($user);
296 # Some dumb firewalls don't prefix the connection messages
297 $ok = $ftp->response()
298 if ($ok == CMD_OK && $ftp->code == 220 && $user =~ /\@/);
300 if ($ok == CMD_MORE) {
301 unless(defined $pass) {
304 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'}, $ruser);
306 ($ruser,$pass,$acct) = $rc->lpa()
309 $pass = '-anonymous@'
310 if (!defined $pass && (!defined($ruser) || $ruser =~ /^anonymous/o));
313 $ok = $ftp->_PASS($pass || "");
316 $ok = $ftp->_ACCT($acct)
317 if (defined($acct) && ($ok == CMD_MORE || $ok == CMD_OK));
319 if ($fwtype == 7 && $ok == CMD_OK && defined ${*$ftp}{'net_ftp_firewall'}) {
320 my($f,$auth,$resp) = _auth_id($ftp);
321 $ftp->authorize($auth,$resp) if defined($resp);
329 @_ == 2 or croak 'usage: $ftp->account( ACCT )';
332 $ftp->_ACCT($acct) == CMD_OK;
336 my($ftp,$auth,$resp) = @_;
338 unless(defined $resp)
342 $auth ||= eval { (getpwuid($>))[0] } || $ENV{NAME};
344 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'}, $auth)
345 || Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
347 ($auth,$resp) = $rc->lpa()
355 @_ >= 1 || @_ <= 3 or croak 'usage: $ftp->authorize( [AUTH [, RESP]])';
357 my($ftp,$auth,$resp) = &_auth_id;
359 my $ok = $ftp->_AUTH($auth || "");
361 $ok = $ftp->_RESP($resp || "")
362 if ($ok == CMD_MORE);
369 @_ == 3 or croak 'usage: $ftp->rename(FROM, TO)';
371 my($ftp,$from,$to) = @_;
381 my $oldval = ${*$ftp}{'net_ftp_type'};
384 unless (defined $type);
387 unless ($ftp->_TYPE($type,@_));
389 ${*$ftp}{'net_ftp_type'} = join(" ",$type,@_);
398 send($ftp,pack("CCC", $TELNET_IAC, $TELNET_IP, $TELNET_IAC),MSG_OOB);
400 $ftp->command(pack("C",$TELNET_DM) . "ABOR");
402 ${*$ftp}{'net_ftp_dataconn'}->close()
403 if defined ${*$ftp}{'net_ftp_dataconn'};
407 $ftp->status == CMD_OK;
412 my($ftp,$remote,$local,$where) = @_;
414 my($loc,$len,$buf,$resp,$localfd,$data);
417 $localfd = ref($local) || ref(\$local) eq "GLOB"
421 ($local = $remote) =~ s#^.*/##
422 unless(defined $local);
424 croak("Bad remote filename '$remote'\n")
425 if $remote =~ /[\r\n]/s;
427 ${*$ftp}{'net_ftp_rest'} = $where
430 delete ${*$ftp}{'net_ftp_port'};
431 delete ${*$ftp}{'net_ftp_pasv'};
433 $data = $ftp->retr($remote) or
444 unless(sysopen($loc, $local, O_CREAT | O_WRONLY | ($where ? O_APPEND : O_TRUNC)))
446 carp "Cannot open Local file $local: $!\n";
452 if($ftp->type eq 'I' && !binmode($loc))
454 carp "Cannot binmode Local file $local: $!\n";
456 close($loc) unless $localfd;
461 my($count,$hashh,$hashb,$ref) = (0);
463 ($hashh,$hashb) = @$ref
464 if($ref = ${*$ftp}{'net_ftp_hash'});
466 my $blksize = ${*$ftp}{'net_ftp_blksize'};
470 last unless $len = $data->read($buf,$blksize);
472 if (trEBCDIC && $ftp->type ne 'I')
474 $buf = $ftp->toebcdic($buf);
480 print $hashh "#" x (int($count / $hashb));
483 my $written = syswrite($loc,$buf,$len);
484 unless(defined($written) && $written == $len)
486 carp "Cannot write to Local file $local: $!\n";
489 unless defined $localfd;
494 print $hashh "\n" if $hashh;
496 unless (defined $localfd)
500 carp "Cannot close file $local (perhaps disk space) $!\n";
505 unless ($data->close()) # implied $ftp->response
507 carp "Unable to close datastream";
516 @_ == 1 || @_ == 2 or croak 'usage: $ftp->cwd( [ DIR ] )';
520 $dir = "/" unless defined($dir) && $dir =~ /\S/;
529 @_ == 1 or croak 'usage: $ftp->cdup()';
535 @_ == 1 || croak 'usage: $ftp->pwd()';
542 # rmdir( $ftp, $dir, [ $recurse ] )
544 # Removes $dir on remote host via FTP.
545 # $ftp is handle for remote host
547 # If $recurse is TRUE, the directory and deleted recursively.
548 # This means all of its contents and subdirectories.
550 # Initial version contributed by Dinkum Software
554 @_ == 2 || @_ == 3 or croak('usage: $ftp->rmdir( DIR [, RECURSE ] )');
557 my ($ftp, $dir, $recurse) = @_ ;
561 if $ok = $ftp->_RMD( $dir ) or !$recurse;
563 # Try to delete the contents
564 # Get a list of all the files in the directory
565 my $filelist = $ftp->ls($dir);
568 unless $filelist && @$filelist; # failed, it is probably not a directory
570 # Go thru and delete each file or the directory
572 foreach $file (map { m,/, ? $_ : "$dir/$_" } @$filelist)
574 next # successfully deleted the file
575 if $ftp->delete($file);
577 # Failed to delete it, assume its a directory
578 # Recurse and ignore errors, the final rmdir() will
579 # fail on any errors here
581 unless $ok = $ftp->rmdir($file, 1) ;
584 # Directory should be empty
585 # Try to remove the directory again
586 # Pass results directly to caller
587 # If any of the prior deletes failed, this
588 # rmdir() will fail because directory is not empty
589 return $ftp->_RMD($dir) ;
594 @_ == 2 || croak 'usage: $ftp->restart( BYTE_OFFSET )';
596 my($ftp,$where) = @_;
598 ${*$ftp}{'net_ftp_rest'} = $where;
606 @_ == 2 || @_ == 3 or croak 'usage: $ftp->mkdir( DIR [, RECURSE ] )';
608 my($ftp,$dir,$recurse) = @_;
610 $ftp->_MKD($dir) || $recurse or
617 my @path = split(m#(?=/+)#, $dir);
623 $path .= shift @path;
627 $path = $ftp->_extract_path($path);
630 # If the creation of the last element was not sucessful, see if we
631 # can cd to it, if so then return path
635 my($status,$message) = ($ftp->status,$ftp->message);
638 if($pwd && $ftp->cwd($dir))
647 $ftp->set_status($status,$message);
656 @_ == 2 || croak 'usage: $ftp->delete( FILENAME )';
661 sub put { shift->_store_cmd("stor",@_) }
662 sub put_unique { shift->_store_cmd("stou",@_) }
663 sub append { shift->_store_cmd("appe",@_) }
665 sub nlst { shift->_data_cmd("NLST",@_) }
666 sub list { shift->_data_cmd("LIST",@_) }
667 sub retr { shift->_data_cmd("RETR",@_) }
668 sub stor { shift->_data_cmd("STOR",@_) }
669 sub stou { shift->_data_cmd("STOU",@_) }
670 sub appe { shift->_data_cmd("APPE",@_) }
674 my($ftp,$cmd,$local,$remote) = @_;
675 my($loc,$sock,$len,$buf,$localfd);
678 $localfd = ref($local) || ref(\$local) eq "GLOB"
682 unless(defined $remote)
684 croak 'Must specify remote filename with stream input'
687 require File::Basename;
688 $remote = File::Basename::basename($local);
691 croak("Bad remote filename '$remote'\n")
692 if $remote =~ /[\r\n]/s;
702 unless(sysopen($loc, $local, O_RDONLY))
704 carp "Cannot open Local file $local: $!\n";
709 if($ftp->type eq 'I' && !binmode($loc))
711 carp "Cannot binmode Local file $local: $!\n";
715 delete ${*$ftp}{'net_ftp_port'};
716 delete ${*$ftp}{'net_ftp_pasv'};
718 $sock = $ftp->_data_cmd($cmd, $remote) or
721 my $blksize = ${*$ftp}{'net_ftp_blksize'};
723 my($count,$hashh,$hashb,$ref) = (0);
725 ($hashh,$hashb) = @$ref
726 if($ref = ${*$ftp}{'net_ftp_hash'});
730 last unless $len = sysread($loc,$buf="",$blksize);
734 $buf = $ftp->toascii($buf);
740 print $hashh "#" x (int($count / $hashb));
745 unless(defined($wlen = $sock->write($buf,$len)) && $wlen == $len)
749 unless defined $localfd;
750 print $hashh "\n" if $hashh;
755 print $hashh "\n" if $hashh;
758 unless defined $localfd;
763 if ('STOU' eq uc $cmd and $ftp->message =~ m/unique\ file\ name:(.*)\)|"(.*)"/)
765 require File::Basename;
766 $remote = File::Basename::basename($+)
774 @_ == 1 || @_ == 2 or croak 'usage: $ftp->port([PORT])';
779 delete ${*$ftp}{'net_ftp_intern_port'};
781 unless(defined $port)
783 # create a Listen socket at same address as the command socket
785 ${*$ftp}{'net_ftp_listen'} ||= IO::Socket::INET->new(Listen => 5,
787 Timeout => $ftp->timeout,
788 LocalAddr => $ftp->sockhost,
791 my $listen = ${*$ftp}{'net_ftp_listen'};
793 my($myport, @myaddr) = ($listen->sockport, split(/\./,$listen->sockhost));
795 $port = join(',', @myaddr, $myport >> 8, $myport & 0xff);
797 ${*$ftp}{'net_ftp_intern_port'} = 1;
800 $ok = $ftp->_PORT($port);
802 ${*$ftp}{'net_ftp_port'} = $port;
807 sub ls { shift->_list_cmd("NLST",@_); }
808 sub dir { shift->_list_cmd("LIST",@_); }
812 @_ == 1 or croak 'usage: $ftp->pasv()';
816 delete ${*$ftp}{'net_ftp_intern_port'};
818 $ftp->_PASV && $ftp->message =~ /(\d+(,\d+)+)/
819 ? ${*$ftp}{'net_ftp_pasv'} = $1
826 ${*$ftp}{'net_ftp_unique'} || undef;
830 @_ == 2 or croak 'usage: $ftp->supported( CMD )';
833 my $hash = ${*$ftp}{'net_ftp_supported'} ||= {};
836 if exists $hash->{$cmd};
838 return $hash->{$cmd} = 0
839 unless $ftp->_HELP($cmd);
841 my $text = $ftp->message;
842 if($text =~ /following\s+commands/i) {
844 while($text =~ /(\*?)(\w+)(\*?)/sg) {
845 $hash->{"\U$2"} = !length("$1$3");
849 $hash->{$cmd} = $text !~ /unimplemented/i;
856 ## Deprecated methods
861 carp "Use of Net::FTP::lsl deprecated, use 'dir'"
868 carp "Use of Net::FTP::authorise deprecated, use 'authorize'"
880 my($ftp, $path) = @_;
882 # This tries to work both with and without the quote doubling
883 # convention (RFC 959 requires it, but the first 3 servers I checked
884 # didn't implement it). It will fail on a server which uses a quote in
885 # the message which isn't a part of or surrounding the path.
887 $ftp->message =~ /(?:^|\s)\"(.*)\"(?:$|\s)/ &&
888 ($path = $1) =~ s/\"\"/\"/g;
894 ## Communication methods
901 my $pkg = "Net::FTP::" . $ftp->type;
903 eval "require " . $pkg;
907 delete ${*$ftp}{'net_ftp_dataconn'};
909 if(defined ${*$ftp}{'net_ftp_pasv'})
911 my @port = split(/,/,${*$ftp}{'net_ftp_pasv'});
913 $data = $pkg->new(PeerAddr => join(".",@port[0..3]),
914 PeerPort => $port[4] * 256 + $port[5],
918 elsif(defined ${*$ftp}{'net_ftp_listen'})
920 $data = ${*$ftp}{'net_ftp_listen'}->accept($pkg);
921 close(delete ${*$ftp}{'net_ftp_listen'});
927 $data->timeout($ftp->timeout);
928 ${*$ftp}{'net_ftp_dataconn'} = $data;
929 ${*$data}{'net_ftp_cmd'} = $ftp;
930 ${*$data}{'net_ftp_blksize'} = ${*$ftp}{'net_ftp_blksize'};
941 delete ${*$ftp}{'net_ftp_port'};
942 delete ${*$ftp}{'net_ftp_pasv'};
944 my $data = $ftp->_data_cmd($cmd,@_);
947 unless(defined $data);
950 bless $data, "Net::FTP::A"; # Force ASCII mode
954 my $blksize = ${*$ftp}{'net_ftp_blksize'};
956 while($data->read($databuf,$blksize)) {
960 my $list = [ split(/\n/,$buf) ];
966 for (@$list) { $_ = $ftp->toebcdic($_) }
978 my $where = delete ${*$ftp}{'net_ftp_rest'} || 0;
982 croak("Bad argument '$arg'\n")
983 if $arg =~ /[\r\n]/s;
986 if(${*$ftp}{'net_ftp_passive'} &&
987 !defined ${*$ftp}{'net_ftp_pasv'} &&
988 !defined ${*$ftp}{'net_ftp_port'})
992 $ok = defined $ftp->pasv;
993 $ok = $ftp->_REST($where)
998 $ftp->command($cmd,@_);
999 $data = $ftp->_dataconn();
1000 $ok = CMD_INFO == $ftp->response();
1004 if $data && $cmd =~ /RETR|LIST|NLST/;
1014 unless (defined ${*$ftp}{'net_ftp_port'} ||
1015 defined ${*$ftp}{'net_ftp_pasv'});
1017 $ok = $ftp->_REST($where)
1023 $ftp->command($cmd,@_);
1026 if(defined ${*$ftp}{'net_ftp_pasv'});
1028 $ok = CMD_INFO == $ftp->response();
1031 unless exists ${*$ftp}{'net_ftp_intern_port'};
1034 my $data = $ftp->_dataconn();
1037 if $data && $cmd =~ /RETR|LIST|NLST/;
1043 close(delete ${*$ftp}{'net_ftp_listen'});
1049 ## Over-ride methods (Net::Cmd)
1052 sub debug_text { $_[2] =~ /^(pass|resp|acct)/i ? "$1 ....\n" : $_[2]; }
1058 delete ${*$ftp}{'net_ftp_port'};
1059 $ftp->SUPER::command(@_);
1065 my $code = $ftp->SUPER::response();
1067 delete ${*$ftp}{'net_ftp_pasv'}
1068 if ($code != CMD_MORE && $code != CMD_INFO);
1075 return ($1, $2 eq "-")
1076 if $_[1] =~ s/^(\d\d\d)(.?)//o;
1080 # Darn MS FTP server is a load of CRAP !!!!
1082 unless ${*$ftp}{'net_cmd_code'} + 0;
1084 (${*$ftp}{'net_cmd_code'},1);
1088 ## Allow 2 servers to talk directly
1092 my($sftp,$sfile,$dftp,$dfile,$unique) = @_;
1094 ($dfile = $sfile) =~ s#.*/##
1095 unless(defined $dfile);
1097 my $port = $sftp->pasv or
1100 $dftp->port($port) or
1104 unless($unique ? $dftp->stou($dfile) : $dftp->stor($dfile));
1106 unless($sftp->retr($sfile) && $sftp->response == CMD_INFO) {
1107 $sftp->retr($sfile);
1113 $dftp->pasv_wait($sftp);
1118 @_ == 2 or croak 'usage: $ftp->pasv_wait(NON_PASV_FTP)';
1120 my($ftp, $non_pasv) = @_;
1121 my($file,$rin,$rout);
1123 vec($rin='',fileno($ftp),1) = 1;
1124 select($rout=$rin, undef, undef, undef);
1127 $non_pasv->response();
1130 unless $ftp->ok() && $non_pasv->ok();
1133 if $ftp->message =~ /unique file name:\s*(\S*)\s*\)/;
1136 if $non_pasv->message =~ /unique file name:\s*(\S*)\s*\)/;
1141 sub cmd { shift->command(@_)->response() }
1143 ########################################
1148 sub _ABOR { shift->command("ABOR")->response() == CMD_OK }
1149 sub _CDUP { shift->command("CDUP")->response() == CMD_OK }
1150 sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
1151 sub _PASV { shift->command("PASV")->response() == CMD_OK }
1152 sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
1153 sub _DELE { shift->command("DELE",@_)->response() == CMD_OK }
1154 sub _CWD { shift->command("CWD", @_)->response() == CMD_OK }
1155 sub _PORT { shift->command("PORT",@_)->response() == CMD_OK }
1156 sub _RMD { shift->command("RMD", @_)->response() == CMD_OK }
1157 sub _MKD { shift->command("MKD", @_)->response() == CMD_OK }
1158 sub _PWD { shift->command("PWD", @_)->response() == CMD_OK }
1159 sub _TYPE { shift->command("TYPE",@_)->response() == CMD_OK }
1160 sub _RNTO { shift->command("RNTO",@_)->response() == CMD_OK }
1161 sub _RESP { shift->command("RESP",@_)->response() == CMD_OK }
1162 sub _MDTM { shift->command("MDTM",@_)->response() == CMD_OK }
1163 sub _SIZE { shift->command("SIZE",@_)->response() == CMD_OK }
1164 sub _HELP { shift->command("HELP",@_)->response() == CMD_OK }
1165 sub _STAT { shift->command("STAT",@_)->response() == CMD_OK }
1166 sub _APPE { shift->command("APPE",@_)->response() == CMD_INFO }
1167 sub _LIST { shift->command("LIST",@_)->response() == CMD_INFO }
1168 sub _NLST { shift->command("NLST",@_)->response() == CMD_INFO }
1169 sub _RETR { shift->command("RETR",@_)->response() == CMD_INFO }
1170 sub _STOR { shift->command("STOR",@_)->response() == CMD_INFO }
1171 sub _STOU { shift->command("STOU",@_)->response() == CMD_INFO }
1172 sub _RNFR { shift->command("RNFR",@_)->response() == CMD_MORE }
1173 sub _REST { shift->command("REST",@_)->response() == CMD_MORE }
1174 sub _USER { shift->command("user",@_)->response() } # A certain brain dead firewall :-)
1175 sub _PASS { shift->command("PASS",@_)->response() }
1176 sub _ACCT { shift->command("ACCT",@_)->response() }
1177 sub _AUTH { shift->command("AUTH",@_)->response() }
1179 sub _ALLO { shift->unsupported(@_) }
1180 sub _SMNT { shift->unsupported(@_) }
1181 sub _MODE { shift->unsupported(@_) }
1182 sub _SYST { shift->unsupported(@_) }
1183 sub _STRU { shift->unsupported(@_) }
1184 sub _REIN { shift->unsupported(@_) }
1192 Net::FTP - FTP Client class
1198 $ftp = Net::FTP->new("some.host.name", Debug => 0);
1199 $ftp->login("anonymous",'-anonymous@');
1201 $ftp->get("that.file");
1206 C<Net::FTP> is a class implementing a simple FTP client in Perl as
1207 described in RFC959. It provides wrappers for a subset of the RFC959
1212 FTP stands for File Transfer Protocol. It is a way of transferring
1213 files between networked machines. The protocol defines a client
1214 (whose commands are provided by this module) and a server (not
1215 implemented in this module). Communication is always initiated by the
1216 client, and the server responds with a message and a status code (and
1217 sometimes with data).
1219 The FTP protocol allows files to be sent to or fetched from the
1220 server. Each transfer involves a B<local file> (on the client) and a
1221 B<remote file> (on the server). In this module, the same file name
1222 will be used for both local and remote if only one is specified. This
1223 means that transferring remote file C</path/to/file> will try to put
1224 that file in C</path/to/file> locally, unless you specify a local file
1227 The protocol also defines several standard B<translations> which the
1228 file can undergo during transfer. These are ASCII, EBCDIC, binary,
1229 and byte. ASCII is the default type, and indicates that the sender of
1230 files will translate the ends of lines to a standard representation
1231 which the receiver will then translate back into their local
1232 representation. EBCDIC indicates the file being transferred is in
1233 EBCDIC format. Binary (also known as image) format sends the data as
1234 a contiguous bit stream. Byte format transfers the data as bytes, the
1235 values of which remain the same regardless of differences in byte size
1236 between the two machines (in theory - in practice you should only use
1237 this if you really know what you're doing).
1243 =item new (HOST [,OPTIONS])
1245 This is the constructor for a new Net::FTP object. C<HOST> is the
1246 name of the remote host to which an FTP connection is required.
1248 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
1249 Possible options are:
1251 B<Firewall> - The name of a machine which acts as an FTP firewall. This can be
1252 overridden by an environment variable C<FTP_FIREWALL>. If specified, and the
1253 given host cannot be directly connected to, then the
1254 connection is made to the firewall machine and the string C<@hostname> is
1255 appended to the login identifier. This kind of setup is also refered to
1258 B<FirewallType> - The type of firewall running on the machine indicated by
1259 B<Firewall>. This can be overridden by an environment variable
1260 C<FTP_FIREWALL_TYPE>. For a list of permissible types, see the description of
1261 ftp_firewall_type in L<Net::Config>.
1263 B<BlockSize> - This is the block size that Net::FTP will use when doing
1264 transfers. (defaults to 10240)
1266 B<Port> - The port number to connect to on the remote machine for the
1269 B<Timeout> - Set a timeout value (defaults to 120)
1271 B<Debug> - debug level (see the debug method in L<Net::Cmd>)
1273 B<Passive> - If set to a non-zero value then all data transfers will be done
1274 using passive mode. This is not usually required except for some I<dumb>
1275 servers, and some firewall configurations. This can also be set by the
1276 environment variable C<FTP_PASSIVE>.
1278 B<Hash> - If given a reference to a file handle (e.g., C<\*STDERR>),
1279 print hash marks (#) on that filehandle every 1024 bytes. This
1280 simply invokes the C<hash()> method for you, so that hash marks
1281 are displayed for all transfers. You can, of course, call C<hash()>
1282 explicitly whenever you'd like.
1284 If the constructor fails undef will be returned and an error message will
1291 Unless otherwise stated all methods return either a I<true> or I<false>
1292 value, with I<true> meaning that the operation was a success. When a method
1293 states that it returns a value, failure will be returned as I<undef> or an
1298 =item login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
1300 Log into the remote FTP server with the given login information. If
1301 no arguments are given then the C<Net::FTP> uses the C<Net::Netrc>
1302 package to lookup the login information for the connected host.
1303 If no information is found then a login of I<anonymous> is used.
1304 If no password is given and the login is I<anonymous> then the users
1305 Email address will be used for a password.
1307 If the connection is via a firewall then the C<authorize> method will
1308 be called with no arguments.
1310 =item authorize ( [AUTH [, RESP]])
1312 This is a protocol used by some firewall ftp proxies. It is used
1313 to authorise the user to send data out. If both arguments are not specified
1314 then C<authorize> uses C<Net::Netrc> to do a lookup.
1318 Send a SITE command to the remote server and wait for a response.
1320 Returns most significant digit of the response code.
1322 =item type (TYPE [, ARGS])
1324 This method will send the TYPE command to the remote FTP server
1325 to change the type of data transfer. The return value is the previous
1328 =item ascii ([ARGS]) binary([ARGS]) ebcdic([ARGS]) byte([ARGS])
1330 Synonyms for C<type> with the first arguments set correctly
1332 B<NOTE> ebcdic and byte are not fully supported.
1334 =item rename ( OLDNAME, NEWNAME )
1336 Rename a file on the remote FTP server from C<OLDNAME> to C<NEWNAME>. This
1337 is done by sending the RNFR and RNTO commands.
1339 =item delete ( FILENAME )
1341 Send a request to the server to delete C<FILENAME>.
1343 =item cwd ( [ DIR ] )
1345 Attempt to change directory to the directory given in C<$dir>. If
1346 C<$dir> is C<"..">, the FTP C<CDUP> command is used to attempt to
1347 move up one directory. If no directory is given then an attempt is made
1348 to change the directory to the root directory.
1352 Change directory to the parent of the current directory.
1356 Returns the full pathname of the current directory.
1358 =item restart ( WHERE )
1360 Set the byte offset at which to begin the next data transfer. Net::FTP simply
1361 records this value and uses it when during the next data transfer. For this
1362 reason this method will not return an error, but setting it may cause
1363 a subsequent data transfer to fail.
1367 Remove the directory with the name C<DIR>.
1369 =item mkdir ( DIR [, RECURSE ])
1371 Create a new directory with the name C<DIR>. If C<RECURSE> is I<true> then
1372 C<mkdir> will attempt to create all the directories in the given path.
1374 Returns the full pathname to the new directory.
1376 =item ls ( [ DIR ] )
1378 Get a directory listing of C<DIR>, or the current directory.
1380 In an array context, returns a list of lines returned from the server. In
1381 a scalar context, returns a reference to a list.
1383 =item dir ( [ DIR ] )
1385 Get a directory listing of C<DIR>, or the current directory in long format.
1387 In an array context, returns a list of lines returned from the server. In
1388 a scalar context, returns a reference to a list.
1390 =item get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )
1392 Get C<REMOTE_FILE> from the server and store locally. C<LOCAL_FILE> may be
1393 a filename or a filehandle. If not specified, the file will be stored in
1394 the current directory with the same leafname as the remote file.
1396 If C<WHERE> is given then the first C<WHERE> bytes of the file will
1397 not be transfered, and the remaining bytes will be appended to
1398 the local file if it already exists.
1400 Returns C<LOCAL_FILE>, or the generated local file name if C<LOCAL_FILE>
1401 is not given. If an error was encountered undef is returned.
1403 =item put ( LOCAL_FILE [, REMOTE_FILE ] )
1405 Put a file on the remote server. C<LOCAL_FILE> may be a name or a filehandle.
1406 If C<LOCAL_FILE> is a filehandle then C<REMOTE_FILE> must be specified. If
1407 C<REMOTE_FILE> is not specified then the file will be stored in the current
1408 directory with the same leafname as C<LOCAL_FILE>.
1410 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1413 B<NOTE>: If for some reason the transfer does not complete and an error is
1414 returned then the contents that had been transfered will not be remove
1417 =item put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
1419 Same as put but uses the C<STOU> command.
1421 Returns the name of the file on the server.
1423 =item append ( LOCAL_FILE [, REMOTE_FILE ] )
1425 Same as put but appends to the file on the remote server.
1427 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1430 =item unique_name ()
1432 Returns the name of the last file stored on the server using the
1437 Returns the I<modification time> of the given file
1441 Returns the size in bytes for the given file as stored on the remote server.
1443 B<NOTE>: The size reported is the size of the stored file on the remote server.
1444 If the file is subsequently transfered from the server in ASCII mode
1445 and the remote server and local machine have different ideas about
1446 "End Of Line" then the size of file on the local machine after transfer
1449 =item supported ( CMD )
1451 Returns TRUE if the remote server supports the given command.
1453 =item hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] )
1455 Called without parameters, or with the first argument false, hash marks
1456 are suppressed. If the first argument is true but not a reference to a
1457 file handle glob, then \*STDERR is used. The second argument is the number
1458 of bytes per hash mark printed, and defaults to 1024. In all cases the
1459 return value is a reference to an array of two: the filehandle glob reference
1460 and the bytes per hash mark.
1464 The following methods can return different results depending on
1465 how they are called. If the user explicitly calls either
1466 of the C<pasv> or C<port> methods then these methods will
1467 return a I<true> or I<false> value. If the user does not
1468 call either of these methods then the result will be a
1469 reference to a C<Net::FTP::dataconn> based object.
1473 =item nlst ( [ DIR ] )
1475 Send an C<NLST> command to the server, with an optional parameter.
1477 =item list ( [ DIR ] )
1479 Same as C<nlst> but using the C<LIST> command
1483 Begin the retrieval of a file called C<FILE> from the remote server.
1487 Tell the server that you wish to store a file. C<FILE> is the
1488 name of the new file that should be created.
1492 Same as C<stor> but using the C<STOU> command. The name of the unique
1493 file which was created on the server will be available via the C<unique_name>
1494 method after the data connection has been closed.
1498 Tell the server that we want to append some data to the end of a file
1499 called C<FILE>. If this file does not exist then create it.
1503 If for some reason you want to have complete control over the data connection,
1504 this includes generating it and calling the C<response> method when required,
1505 then the user can use these methods to do so.
1507 However calling these methods only affects the use of the methods above that
1508 can return a data connection. They have no effect on methods C<get>, C<put>,
1509 C<put_unique> and those that do not require data connections.
1513 =item port ( [ PORT ] )
1515 Send a C<PORT> command to the server. If C<PORT> is specified then it is sent
1516 to the server. If not, then a listen socket is created and the correct information
1521 Tell the server to go into passive mode. Returns the text that represents the
1522 port on which the server is listening, this text is in a suitable form to
1523 sent to another ftp server using the C<port> method.
1527 The following methods can be used to transfer files between two remote
1528 servers, providing that these two servers can connect directly to each other.
1532 =item pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1534 This method will do a file transfer between two remote ftp servers. If
1535 C<DEST_FILE> is omitted then the leaf name of C<SRC_FILE> will be used.
1537 =item pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1539 Like C<pasv_xfer> but the file is stored on the remote server using
1542 =item pasv_wait ( NON_PASV_SERVER )
1544 This method can be used to wait for a transfer to complete between a passive
1545 server and a non-passive server. The method should be called on the passive
1546 server with the C<Net::FTP> object for the non-passive server passed as an
1551 Abort the current data transfer.
1555 Send the QUIT command to the remote FTP server and close the socket connection.
1559 =head2 Methods for the adventurous
1561 C<Net::FTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
1562 be used to send commands to the remote FTP server.
1566 =item quot (CMD [,ARGS])
1568 Send a command, that Net::FTP does not directly support, to the remote
1569 server and wait for a response.
1571 Returns most significant digit of the response code.
1573 B<WARNING> This call should only be used on commands that do not require
1574 data connections. Misuse of this method can hang the connection.
1578 =head1 THE dataconn CLASS
1580 Some of the methods defined in C<Net::FTP> return an object which will
1581 be derived from this class.The dataconn class itself is derived from
1582 the C<IO::Socket::INET> class, so any normal IO operations can be performed.
1583 However the following methods are defined in the dataconn class and IO should
1584 be performed using these.
1588 =item read ( BUFFER, SIZE [, TIMEOUT ] )
1590 Read C<SIZE> bytes of data from the server and place it into C<BUFFER>, also
1591 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1592 given, the timeout value from the command connection will be used.
1594 Returns the number of bytes read before any <CRLF> translation.
1596 =item write ( BUFFER, SIZE [, TIMEOUT ] )
1598 Write C<SIZE> bytes of data from C<BUFFER> to the server, also
1599 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1600 given, the timeout value from the command connection will be used.
1602 Returns the number of bytes written before any <CRLF> translation.
1606 Returns the number of bytes read so far.
1610 Abort the current data transfer.
1614 Close the data connection and get a response from the FTP server. Returns
1615 I<true> if the connection was closed successfully and the first digit of
1616 the response from the server was a '2'.
1620 =head1 UNIMPLEMENTED
1622 The following RFC959 commands have not been implemented:
1628 Allocates storage for the file to be transferred.
1632 Mount a different file system structure without changing login or
1633 accounting information.
1637 Ask the server for "helpful information" (that's what the RFC says) on
1638 the commands it accepts.
1642 Specifies transfer mode (stream, block or compressed) for file to be
1647 Request remote server system identification.
1651 Request remote server status.
1655 Specifies file structure for file to be transferred.
1659 Reinitialize the connection, flushing all I/O and account information.
1663 =head1 REPORTING BUGS
1665 When reporting bugs/problems please include as much information as possible.
1666 It may be difficult for me to reproduce the problem as almost every setup
1669 A small script which yields the problem will probably be of help. It would
1670 also be useful if this script was run with the extra options C<Debug => 1>
1671 passed to the constructor, and the output sent with the bug report. If you
1672 cannot include a small script then please include a Debug trace from a
1673 run of your program which does yield the problem.
1677 Graham Barr <gbarr@pobox.com>
1684 ftp(1), ftpd(8), RFC 959
1685 http://www.cis.ohio-state.edu/htbin/rfc/rfc959.html
1689 For an example of the use of Net::FTP see
1693 =item http://www.csh.rit.edu/~adam/Progs/autoftp-2.0.tar.gz
1695 C<autoftp> is a program that can retrieve, send, or list files via
1696 the FTP protocol in a non-interactive manner.
1702 Henry Gabryjelski <henryg@WPI.EDU> - for the suggestion of creating directories
1705 Nathan Torkington <gnat@frii.com> - for some input on the documentation.
1707 Roderick Schertler <roderick@gate.net> - for various inputs
1711 Copyright (c) 1995-1998 Graham Barr. All rights reserved.
1712 This program is free software; you can redistribute it and/or modify it
1713 under the same terms as Perl itself.
1717 I<$Id: //depot/libnet/Net/FTP.pm#64 $>