3 # Copyright (c) 1995-2004 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);
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
59 $peer=delete $arg{Host};
64 my $fire_type = undef;
66 if(exists($arg{Firewall}) || Net::Config->requires_firewall($peer))
68 $fire = $arg{Firewall}
70 || $NetConfig{ftp_firewall}
77 $fire_type = $arg{FirewallType}
78 || $ENV{FTP_FIREWALL_TYPE}
79 || $NetConfig{firewall_type}
84 my $ftp = $pkg->SUPER::new(PeerAddr => $peer,
85 PeerPort => $arg{Port} || 'ftp(21)',
86 LocalAddr => $arg{'LocalAddr'},
88 Timeout => defined $arg{Timeout}
93 ${*$ftp}{'net_ftp_host'} = $host; # Remote hostname
94 ${*$ftp}{'net_ftp_type'} = 'A'; # ASCII/binary/etc mode
95 ${*$ftp}{'net_ftp_blksize'} = abs($arg{'BlockSize'} || 10240);
97 ${*$ftp}{'net_ftp_localaddr'} = $arg{'LocalAddr'};
99 ${*$ftp}{'net_ftp_firewall'} = $fire
101 ${*$ftp}{'net_ftp_firewall_type'} = $fire_type
102 if(defined $fire_type);
104 ${*$ftp}{'net_ftp_passive'} = int
107 : exists $ENV{FTP_PASSIVE}
110 ? $NetConfig{ftp_ext_passive}
111 : $NetConfig{ftp_int_passive}; # Whew! :-)
113 $ftp->hash(exists $arg{Hash} ? $arg{Hash} : 0, 1024);
117 $ftp->debug(exists $arg{Debug} ? $arg{Debug} : undef);
119 unless ($ftp->response() == CMD_OK)
130 ## User interface methods
136 ${*$me}{'net_ftp_host'};
141 my $ftp = shift; # self
145 delete ${*$ftp}{'net_ftp_hash'};
148 ($h,$b) = (ref($h)? $h : \*STDERR, $b || 1024);
149 select((select($h), $|=1)[0]);
150 $b = 512 if $b < 512;
151 ${*$ftp}{'net_ftp_hash'} = [$h, $b];
164 sub ascii { shift->type('A',@_); }
165 sub binary { shift->type('I',@_); }
169 carp "TYPE E is unsupported, shall default to I";
175 carp "TYPE L is unsupported, shall default to I";
179 # Allow the user to send a command directly, BE CAREFUL !!
186 $ftp->command( uc $cmd, @_);
194 $ftp->command("SITE", @_);
203 # Server Y2K bug workaround
205 # sigh; some idiotic FTP servers use ("19%d",tm.tm_year) instead of
206 # ("%d",tm.tm_year+1900). This results in an extra digit in the
207 # string returned. To account for this we allow an optional extra
208 # digit in the year. Then if the first two digits are 19 we use the
209 # remainder, otherwise we subtract 1900 from the whole year.
211 $ftp->_MDTM($file) && $ftp->message =~ /((\d\d)(\d\d\d?))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/
212 ? timegm($8,$7,$6,$5,$4-1,$2 eq '19' ? $3 : ($1-1900))
220 if($ftp->supported("SIZE")) {
221 return $ftp->_SIZE($file)
222 ? ($ftp->message =~ /(\d+)\s*(bytes?\s*)?$/)[0]
225 elsif($ftp->supported("STAT")) {
228 unless $ftp->_STAT($file) && (@msg = $ftp->message) == 3;
230 foreach $line (@msg) {
231 return (split(/\s+/,$line))[4]
232 if $line =~ /^[-rwxSsTt]{10}/
236 my @files = $ftp->dir($file);
238 return (split(/\s+/,$1))[4]
239 if $files[0] =~ /^([-rwxSsTt]{10}.*)$/;
246 my($ftp,$user,$pass,$acct) = @_;
247 my($ok,$ruser,$fwtype);
249 unless (defined $user) {
252 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'});
254 ($user,$pass,$acct) = $rc->lpa()
258 $user ||= "anonymous";
261 $fwtype = ${*$ftp}{'net_ftp_firewall_type'}
262 || $NetConfig{'ftp_firewall_type'}
265 if ($fwtype && defined ${*$ftp}{'net_ftp_firewall'}) {
266 if ($fwtype == 1 || $fwtype == 7) {
267 $user .= '@' . ${*$ftp}{'net_ftp_host'};
272 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
274 my($fwuser,$fwpass,$fwacct) = $rc ? $rc->lpa() : ();
277 $user = join('@',$user,$fwuser,${*$ftp}{'net_ftp_host'});
278 $pass = $pass . '@' . $fwpass;
282 $user .= '@' . ${*$ftp}{'net_ftp_host'};
284 elsif ($fwtype == 6) {
285 $fwuser .= '@' . ${*$ftp}{'net_ftp_host'};
288 $ok = $ftp->_USER($fwuser);
290 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
292 $ok = $ftp->_PASS($fwpass || "");
294 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
296 $ok = $ftp->_ACCT($fwacct)
300 $ok = $ftp->command("SITE",${*$ftp}{'net_ftp_host'})->response;
302 elsif ($fwtype == 4) {
303 $ok = $ftp->command("OPEN",${*$ftp}{'net_ftp_host'})->response;
306 return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
311 $ok = $ftp->_USER($user);
313 # Some dumb firewalls don't prefix the connection messages
314 $ok = $ftp->response()
315 if ($ok == CMD_OK && $ftp->code == 220 && $user =~ /\@/);
317 if ($ok == CMD_MORE) {
318 unless(defined $pass) {
321 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'}, $ruser);
323 ($ruser,$pass,$acct) = $rc->lpa()
326 $pass = '-anonymous@'
327 if (!defined $pass && (!defined($ruser) || $ruser =~ /^anonymous/o));
330 $ok = $ftp->_PASS($pass || "");
333 $ok = $ftp->_ACCT($acct)
334 if (defined($acct) && ($ok == CMD_MORE || $ok == CMD_OK));
336 if ($fwtype == 7 && $ok == CMD_OK && defined ${*$ftp}{'net_ftp_firewall'}) {
337 my($f,$auth,$resp) = _auth_id($ftp);
338 $ftp->authorize($auth,$resp) if defined($resp);
346 @_ == 2 or croak 'usage: $ftp->account( ACCT )';
349 $ftp->_ACCT($acct) == CMD_OK;
353 my($ftp,$auth,$resp) = @_;
355 unless(defined $resp)
359 $auth ||= eval { (getpwuid($>))[0] } || $ENV{NAME};
361 my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'}, $auth)
362 || Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
364 ($auth,$resp) = $rc->lpa()
372 @_ >= 1 || @_ <= 3 or croak 'usage: $ftp->authorize( [AUTH [, RESP]])';
374 my($ftp,$auth,$resp) = &_auth_id;
376 my $ok = $ftp->_AUTH($auth || "");
378 $ok = $ftp->_RESP($resp || "")
379 if ($ok == CMD_MORE);
386 @_ == 3 or croak 'usage: $ftp->rename(FROM, TO)';
388 my($ftp,$from,$to) = @_;
398 my $oldval = ${*$ftp}{'net_ftp_type'};
401 unless (defined $type);
404 unless ($ftp->_TYPE($type,@_));
406 ${*$ftp}{'net_ftp_type'} = join(" ",$type,@_);
415 my $oldval = ${*$ftp}{'net_ftp_allo'};
418 unless (defined $size);
421 unless ($ftp->_ALLO($size,@_));
423 ${*$ftp}{'net_ftp_allo'} = join(" ",$size,@_);
432 send($ftp,pack("CCC", $TELNET_IAC, $TELNET_IP, $TELNET_IAC),MSG_OOB);
434 $ftp->command(pack("C",$TELNET_DM) . "ABOR");
436 ${*$ftp}{'net_ftp_dataconn'}->close()
437 if defined ${*$ftp}{'net_ftp_dataconn'};
441 $ftp->status == CMD_OK;
446 my($ftp,$remote,$local,$where) = @_;
448 my($loc,$len,$buf,$resp,$data);
451 my $localfd = ref($local) || ref(\$local) eq "GLOB";
453 ($local = $remote) =~ s#^.*/##
454 unless(defined $local);
456 croak("Bad remote filename '$remote'\n")
457 if $remote =~ /[\r\n]/s;
459 ${*$ftp}{'net_ftp_rest'} = $where if defined $where;
460 my $rest = ${*$ftp}{'net_ftp_rest'};
462 delete ${*$ftp}{'net_ftp_port'};
463 delete ${*$ftp}{'net_ftp_pasv'};
465 $data = $ftp->retr($remote) or
476 unless(sysopen($loc, $local, O_CREAT | O_WRONLY | ($rest ? O_APPEND : O_TRUNC)))
478 carp "Cannot open Local file $local: $!\n";
484 if($ftp->type eq 'I' && !binmode($loc))
486 carp "Cannot binmode Local file $local: $!\n";
488 close($loc) unless $localfd;
493 my($count,$hashh,$hashb,$ref) = (0);
495 ($hashh,$hashb) = @$ref
496 if($ref = ${*$ftp}{'net_ftp_hash'});
498 my $blksize = ${*$ftp}{'net_ftp_blksize'};
499 local $\; # Just in case
503 last unless $len = $data->read($buf,$blksize);
505 if (trEBCDIC && $ftp->type ne 'I')
507 $buf = $ftp->toebcdic($buf);
513 print $hashh "#" x (int($count / $hashb));
516 unless(print $loc $buf)
518 carp "Cannot write to Local file $local: $!\n";
526 print $hashh "\n" if $hashh;
532 carp "Cannot close file $local (perhaps disk space) $!\n";
537 unless ($data->close()) # implied $ftp->response
539 carp "Unable to close datastream";
548 @_ == 1 || @_ == 2 or croak 'usage: $ftp->cwd( [ DIR ] )';
552 $dir = "/" unless defined($dir) && $dir =~ /\S/;
561 @_ == 1 or croak 'usage: $ftp->cdup()';
567 @_ == 1 || croak 'usage: $ftp->pwd()';
574 # rmdir( $ftp, $dir, [ $recurse ] )
576 # Removes $dir on remote host via FTP.
577 # $ftp is handle for remote host
579 # If $recurse is TRUE, the directory and deleted recursively.
580 # This means all of its contents and subdirectories.
582 # Initial version contributed by Dinkum Software
586 @_ == 2 || @_ == 3 or croak('usage: $ftp->rmdir( DIR [, RECURSE ] )');
589 my ($ftp, $dir, $recurse) = @_ ;
593 if $ok = $ftp->_RMD( $dir ) or !$recurse;
595 # Try to delete the contents
596 # Get a list of all the files in the directory
597 my @filelist = grep { !/^\.{1,2}$/ } $ftp->ls($dir);
600 unless @filelist; # failed, it is probably not a directory
602 # Go thru and delete each file or the directory
604 foreach $file (map { m,/, ? $_ : "$dir/$_" } @filelist)
606 next # successfully deleted the file
607 if $ftp->delete($file);
609 # Failed to delete it, assume its a directory
610 # Recurse and ignore errors, the final rmdir() will
611 # fail on any errors here
613 unless $ok = $ftp->rmdir($file, 1) ;
616 # Directory should be empty
617 # Try to remove the directory again
618 # Pass results directly to caller
619 # If any of the prior deletes failed, this
620 # rmdir() will fail because directory is not empty
621 return $ftp->_RMD($dir) ;
626 @_ == 2 || croak 'usage: $ftp->restart( BYTE_OFFSET )';
628 my($ftp,$where) = @_;
630 ${*$ftp}{'net_ftp_rest'} = $where;
638 @_ == 2 || @_ == 3 or croak 'usage: $ftp->mkdir( DIR [, RECURSE ] )';
640 my($ftp,$dir,$recurse) = @_;
642 $ftp->_MKD($dir) || $recurse or
649 my @path = split(m#(?=/+)#, $dir);
655 $path .= shift @path;
659 $path = $ftp->_extract_path($path);
662 # If the creation of the last element was not successful, see if we
663 # can cd to it, if so then return path
667 my($status,$message) = ($ftp->status,$ftp->message);
670 if($pwd && $ftp->cwd($dir))
679 $ftp->set_status($status,$message);
688 @_ == 2 || croak 'usage: $ftp->delete( FILENAME )';
693 sub put { shift->_store_cmd("stor",@_) }
694 sub put_unique { shift->_store_cmd("stou",@_) }
695 sub append { shift->_store_cmd("appe",@_) }
697 sub nlst { shift->_data_cmd("NLST",@_) }
698 sub list { shift->_data_cmd("LIST",@_) }
699 sub retr { shift->_data_cmd("RETR",@_) }
700 sub stor { shift->_data_cmd("STOR",@_) }
701 sub stou { shift->_data_cmd("STOU",@_) }
702 sub appe { shift->_data_cmd("APPE",@_) }
706 my($ftp,$cmd,$local,$remote) = @_;
707 my($loc,$sock,$len,$buf);
710 my $localfd = ref($local) || ref(\$local) eq "GLOB";
712 unless(defined $remote)
714 croak 'Must specify remote filename with stream input'
717 require File::Basename;
718 $remote = File::Basename::basename($local);
720 if( defined ${*$ftp}{'net_ftp_allo'} )
722 delete ${*$ftp}{'net_ftp_allo'};
725 # if the user hasn't already invoked the alloc method since the last
726 # _store_cmd call, figure out if the local file is a regular file(not
727 # a pipe, or device) and if so get the file size from stat, and send
728 # an ALLO command before sending the STOR, STOU, or APPE command.
729 my $size = do { local $^W; -f $local && -s _ }; # no ALLO if sending data from a pipe
730 $ftp->_ALLO($size) if $size;
732 croak("Bad remote filename '$remote'\n")
733 if $remote =~ /[\r\n]/s;
743 unless(sysopen($loc, $local, O_RDONLY))
745 carp "Cannot open Local file $local: $!\n";
750 if($ftp->type eq 'I' && !binmode($loc))
752 carp "Cannot binmode Local file $local: $!\n";
756 delete ${*$ftp}{'net_ftp_port'};
757 delete ${*$ftp}{'net_ftp_pasv'};
759 $sock = $ftp->_data_cmd($cmd, $remote) or
762 $remote = ($ftp->message =~ /FILE:\s*(.*)/)[0]
763 if 'STOU' eq uc $cmd;
765 my $blksize = ${*$ftp}{'net_ftp_blksize'};
767 my($count,$hashh,$hashb,$ref) = (0);
769 ($hashh,$hashb) = @$ref
770 if($ref = ${*$ftp}{'net_ftp_hash'});
774 last unless $len = read($loc,$buf="",$blksize);
776 if (trEBCDIC && $ftp->type ne 'I')
778 $buf = $ftp->toascii($buf);
784 print $hashh "#" x (int($count / $hashb));
789 unless(defined($wlen = $sock->write($buf,$len)) && $wlen == $len)
794 print $hashh "\n" if $hashh;
799 print $hashh "\n" if $hashh;
807 if ('STOU' eq uc $cmd and $ftp->message =~ m/unique\s+file\s*name\s*:\s*(.*)\)|"(.*)"/)
809 require File::Basename;
810 $remote = File::Basename::basename($+)
818 @_ == 1 || @_ == 2 or croak 'usage: $ftp->port([PORT])';
823 delete ${*$ftp}{'net_ftp_intern_port'};
825 unless(defined $port)
827 # create a Listen socket at same address as the command socket
829 ${*$ftp}{'net_ftp_listen'} ||= IO::Socket::INET->new(Listen => 5,
831 Timeout => $ftp->timeout,
832 LocalAddr => $ftp->sockhost,
835 my $listen = ${*$ftp}{'net_ftp_listen'};
837 my($myport, @myaddr) = ($listen->sockport, split(/\./,$listen->sockhost));
839 $port = join(',', @myaddr, $myport >> 8, $myport & 0xff);
841 ${*$ftp}{'net_ftp_intern_port'} = 1;
844 $ok = $ftp->_PORT($port);
846 ${*$ftp}{'net_ftp_port'} = $port;
851 sub ls { shift->_list_cmd("NLST",@_); }
852 sub dir { shift->_list_cmd("LIST",@_); }
856 @_ == 1 or croak 'usage: $ftp->pasv()';
860 delete ${*$ftp}{'net_ftp_intern_port'};
862 $ftp->_PASV && $ftp->message =~ /(\d+(,\d+)+)/
863 ? ${*$ftp}{'net_ftp_pasv'} = $1
870 ${*$ftp}{'net_ftp_unique'} || undef;
874 @_ == 2 or croak 'usage: $ftp->supported( CMD )';
877 my $hash = ${*$ftp}{'net_ftp_supported'} ||= {};
880 if exists $hash->{$cmd};
882 return $hash->{$cmd} = 0
883 unless $ftp->_HELP($cmd);
885 my $text = $ftp->message;
886 if($text =~ /following\s+commands/i) {
888 while($text =~ /(\*?)(\w+)(\*?)/sg) {
889 $hash->{"\U$2"} = !length("$1$3");
893 $hash->{$cmd} = $text !~ /unimplemented/i;
900 ## Deprecated methods
905 carp "Use of Net::FTP::lsl deprecated, use 'dir'"
912 carp "Use of Net::FTP::authorise deprecated, use 'authorize'"
924 my($ftp, $path) = @_;
926 # This tries to work both with and without the quote doubling
927 # convention (RFC 959 requires it, but the first 3 servers I checked
928 # didn't implement it). It will fail on a server which uses a quote in
929 # the message which isn't a part of or surrounding the path.
931 $ftp->message =~ /(?:^|\s)\"(.*)\"(?:$|\s)/ &&
932 ($path = $1) =~ s/\"\"/\"/g;
938 ## Communication methods
945 my $pkg = "Net::FTP::" . $ftp->type;
947 eval "require " . $pkg;
951 delete ${*$ftp}{'net_ftp_dataconn'};
953 if(defined ${*$ftp}{'net_ftp_pasv'})
955 my @port = map { 0+$_ } split(/,/,${*$ftp}{'net_ftp_pasv'});
957 $data = $pkg->new(PeerAddr => join(".",@port[0..3]),
958 PeerPort => $port[4] * 256 + $port[5],
959 LocalAddr => ${*$ftp}{'net_ftp_localaddr'},
963 elsif(defined ${*$ftp}{'net_ftp_listen'})
965 $data = ${*$ftp}{'net_ftp_listen'}->accept($pkg);
966 close(delete ${*$ftp}{'net_ftp_listen'});
972 $data->timeout($ftp->timeout);
973 ${*$ftp}{'net_ftp_dataconn'} = $data;
974 ${*$data}{'net_ftp_cmd'} = $ftp;
975 ${*$data}{'net_ftp_blksize'} = ${*$ftp}{'net_ftp_blksize'};
986 delete ${*$ftp}{'net_ftp_port'};
987 delete ${*$ftp}{'net_ftp_pasv'};
989 my $data = $ftp->_data_cmd($cmd,@_);
992 unless(defined $data);
995 bless $data, "Net::FTP::A"; # Force ASCII mode
999 my $blksize = ${*$ftp}{'net_ftp_blksize'};
1001 while($data->read($databuf,$blksize)) {
1005 my $list = [ split(/\n/,$buf) ];
1011 for (@$list) { $_ = $ftp->toebcdic($_) }
1014 wantarray ? @{$list}
1023 my $where = delete ${*$ftp}{'net_ftp_rest'} || 0;
1027 croak("Bad argument '$arg'\n")
1028 if $arg =~ /[\r\n]/s;
1031 if(${*$ftp}{'net_ftp_passive'} &&
1032 !defined ${*$ftp}{'net_ftp_pasv'} &&
1033 !defined ${*$ftp}{'net_ftp_port'})
1037 $ok = defined $ftp->pasv;
1038 $ok = $ftp->_REST($where)
1043 $ftp->command($cmd,@_);
1044 $data = $ftp->_dataconn();
1045 $ok = CMD_INFO == $ftp->response();
1049 if $data && $cmd =~ /RETR|LIST|NLST/;
1059 unless (defined ${*$ftp}{'net_ftp_port'} ||
1060 defined ${*$ftp}{'net_ftp_pasv'});
1062 $ok = $ftp->_REST($where)
1068 $ftp->command($cmd,@_);
1071 if(defined ${*$ftp}{'net_ftp_pasv'});
1073 $ok = CMD_INFO == $ftp->response();
1076 unless exists ${*$ftp}{'net_ftp_intern_port'};
1079 my $data = $ftp->_dataconn();
1082 if $data && $cmd =~ /RETR|LIST|NLST/;
1088 close(delete ${*$ftp}{'net_ftp_listen'});
1094 ## Over-ride methods (Net::Cmd)
1097 sub debug_text { $_[2] =~ /^(pass|resp|acct)/i ? "$1 ....\n" : $_[2]; }
1103 delete ${*$ftp}{'net_ftp_port'};
1104 $ftp->SUPER::command(@_);
1110 my $code = $ftp->SUPER::response();
1112 delete ${*$ftp}{'net_ftp_pasv'}
1113 if ($code != CMD_MORE && $code != CMD_INFO);
1120 return ($1, $2 eq "-")
1121 if $_[1] =~ s/^(\d\d\d)([- ]?)//o;
1125 # Darn MS FTP server is a load of CRAP !!!!
1127 unless ${*$ftp}{'net_cmd_code'} + 0;
1129 (${*$ftp}{'net_cmd_code'},1);
1133 ## Allow 2 servers to talk directly
1137 my($sftp,$sfile,$dftp,$dfile,$unique) = @_;
1139 ($dfile = $sfile) =~ s#.*/##
1140 unless(defined $dfile);
1142 my $port = $sftp->pasv or
1145 $dftp->port($port) or
1149 unless($unique ? $dftp->stou($dfile) : $dftp->stor($dfile));
1151 unless($sftp->retr($sfile) && $sftp->response == CMD_INFO) {
1152 $sftp->retr($sfile);
1158 $dftp->pasv_wait($sftp);
1163 @_ == 2 or croak 'usage: $ftp->pasv_wait(NON_PASV_FTP)';
1165 my($ftp, $non_pasv) = @_;
1166 my($file,$rin,$rout);
1168 vec($rin='',fileno($ftp),1) = 1;
1169 select($rout=$rin, undef, undef, undef);
1172 $non_pasv->response();
1175 unless $ftp->ok() && $non_pasv->ok();
1178 if $ftp->message =~ /unique file name:\s*(\S*)\s*\)/;
1181 if $non_pasv->message =~ /unique file name:\s*(\S*)\s*\)/;
1186 sub cmd { shift->command(@_)->response() }
1188 ########################################
1193 sub _ABOR { shift->command("ABOR")->response() == CMD_OK }
1194 sub _ALLO { shift->command("ALLO",@_)->response() == CMD_OK}
1195 sub _CDUP { shift->command("CDUP")->response() == CMD_OK }
1196 sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
1197 sub _PASV { shift->command("PASV")->response() == CMD_OK }
1198 sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
1199 sub _DELE { shift->command("DELE",@_)->response() == CMD_OK }
1200 sub _CWD { shift->command("CWD", @_)->response() == CMD_OK }
1201 sub _PORT { shift->command("PORT",@_)->response() == CMD_OK }
1202 sub _RMD { shift->command("RMD", @_)->response() == CMD_OK }
1203 sub _MKD { shift->command("MKD", @_)->response() == CMD_OK }
1204 sub _PWD { shift->command("PWD", @_)->response() == CMD_OK }
1205 sub _TYPE { shift->command("TYPE",@_)->response() == CMD_OK }
1206 sub _RNTO { shift->command("RNTO",@_)->response() == CMD_OK }
1207 sub _RESP { shift->command("RESP",@_)->response() == CMD_OK }
1208 sub _MDTM { shift->command("MDTM",@_)->response() == CMD_OK }
1209 sub _SIZE { shift->command("SIZE",@_)->response() == CMD_OK }
1210 sub _HELP { shift->command("HELP",@_)->response() == CMD_OK }
1211 sub _STAT { shift->command("STAT",@_)->response() == CMD_OK }
1212 sub _APPE { shift->command("APPE",@_)->response() == CMD_INFO }
1213 sub _LIST { shift->command("LIST",@_)->response() == CMD_INFO }
1214 sub _NLST { shift->command("NLST",@_)->response() == CMD_INFO }
1215 sub _RETR { shift->command("RETR",@_)->response() == CMD_INFO }
1216 sub _STOR { shift->command("STOR",@_)->response() == CMD_INFO }
1217 sub _STOU { shift->command("STOU",@_)->response() == CMD_INFO }
1218 sub _RNFR { shift->command("RNFR",@_)->response() == CMD_MORE }
1219 sub _REST { shift->command("REST",@_)->response() == CMD_MORE }
1220 sub _PASS { shift->command("PASS",@_)->response() }
1221 sub _ACCT { shift->command("ACCT",@_)->response() }
1222 sub _AUTH { shift->command("AUTH",@_)->response() }
1226 my $ok = $ftp->command("USER",@_)->response();
1228 # A certain brain dead firewall :-)
1229 $ok = $ftp->command("user",@_)->response()
1230 unless $ok == CMD_MORE or $ok == CMD_OK;
1235 sub _SMNT { shift->unsupported(@_) }
1236 sub _MODE { shift->unsupported(@_) }
1237 sub _SYST { shift->unsupported(@_) }
1238 sub _STRU { shift->unsupported(@_) }
1239 sub _REIN { shift->unsupported(@_) }
1247 Net::FTP - FTP Client class
1253 $ftp = Net::FTP->new("some.host.name", Debug => 0)
1254 or die "Cannot connect to some.host.name: $@";
1256 $ftp->login("anonymous",'-anonymous@')
1257 or die "Cannot login ", $ftp->message;
1260 or die "Cannot change working directory ", $ftp->message;
1262 $ftp->get("that.file")
1263 or die "get failed ", $ftp->message;
1269 C<Net::FTP> is a class implementing a simple FTP client in Perl as
1270 described in RFC959. It provides wrappers for a subset of the RFC959
1275 FTP stands for File Transfer Protocol. It is a way of transferring
1276 files between networked machines. The protocol defines a client
1277 (whose commands are provided by this module) and a server (not
1278 implemented in this module). Communication is always initiated by the
1279 client, and the server responds with a message and a status code (and
1280 sometimes with data).
1282 The FTP protocol allows files to be sent to or fetched from the
1283 server. Each transfer involves a B<local file> (on the client) and a
1284 B<remote file> (on the server). In this module, the same file name
1285 will be used for both local and remote if only one is specified. This
1286 means that transferring remote file C</path/to/file> will try to put
1287 that file in C</path/to/file> locally, unless you specify a local file
1290 The protocol also defines several standard B<translations> which the
1291 file can undergo during transfer. These are ASCII, EBCDIC, binary,
1292 and byte. ASCII is the default type, and indicates that the sender of
1293 files will translate the ends of lines to a standard representation
1294 which the receiver will then translate back into their local
1295 representation. EBCDIC indicates the file being transferred is in
1296 EBCDIC format. Binary (also known as image) format sends the data as
1297 a contiguous bit stream. Byte format transfers the data as bytes, the
1298 values of which remain the same regardless of differences in byte size
1299 between the two machines (in theory - in practice you should only use
1300 this if you really know what you're doing).
1306 =item new ([ HOST ] [, OPTIONS ])
1308 This is the constructor for a new Net::FTP object. C<HOST> is the
1309 name of the remote host to which an FTP connection is required.
1311 C<HOST> is optional. If C<HOST> is not given then it may instead be
1312 passed as the C<Host> option described below.
1314 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
1315 Possible options are:
1317 B<Host> - FTP host to connect to. It may be a single scalar, as defined for
1318 the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
1319 an array with hosts to try in turn. The L</host> method will return the value
1320 which was used to connect to the host.
1323 B<Firewall> - The name of a machine which acts as an FTP firewall. This can be
1324 overridden by an environment variable C<FTP_FIREWALL>. If specified, and the
1325 given host cannot be directly connected to, then the
1326 connection is made to the firewall machine and the string C<@hostname> is
1327 appended to the login identifier. This kind of setup is also referred to
1330 B<FirewallType> - The type of firewall running on the machine indicated by
1331 B<Firewall>. This can be overridden by an environment variable
1332 C<FTP_FIREWALL_TYPE>. For a list of permissible types, see the description of
1333 ftp_firewall_type in L<Net::Config>.
1335 B<BlockSize> - This is the block size that Net::FTP will use when doing
1336 transfers. (defaults to 10240)
1338 B<Port> - The port number to connect to on the remote machine for the
1341 B<Timeout> - Set a timeout value (defaults to 120)
1343 B<Debug> - debug level (see the debug method in L<Net::Cmd>)
1345 B<Passive> - If set to a non-zero value then all data transfers will
1346 be done using passive mode. If set to zero then data transfers will be
1347 done using active mode. If the machine is connected to the Internet
1348 directly, both passive and active mode should work equally well.
1349 Behind most firewall and NAT configurations passive mode has a better
1350 chance of working. However, in some rare firewall configurations,
1351 active mode actually works when passive mode doesn't. Some really old
1352 FTP servers might not implement passive transfers. If not specified,
1353 then the transfer mode is set by the environment variable
1354 C<FTP_PASSIVE> or if that one is not set by the settings done by the
1355 F<libnetcfg> utility. If none of these apply then passive mode is
1358 B<Hash> - If given a reference to a file handle (e.g., C<\*STDERR>),
1359 print hash marks (#) on that filehandle every 1024 bytes. This
1360 simply invokes the C<hash()> method for you, so that hash marks
1361 are displayed for all transfers. You can, of course, call C<hash()>
1362 explicitly whenever you'd like.
1364 B<LocalAddr> - Local address to use for all socket connections, this
1365 argument will be passed to L<IO::Socket::INET>
1367 If the constructor fails undef will be returned and an error message will
1374 Unless otherwise stated all methods return either a I<true> or I<false>
1375 value, with I<true> meaning that the operation was a success. When a method
1376 states that it returns a value, failure will be returned as I<undef> or an
1381 =item login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
1383 Log into the remote FTP server with the given login information. If
1384 no arguments are given then the C<Net::FTP> uses the C<Net::Netrc>
1385 package to lookup the login information for the connected host.
1386 If no information is found then a login of I<anonymous> is used.
1387 If no password is given and the login is I<anonymous> then I<anonymous@>
1388 will be used for password.
1390 If the connection is via a firewall then the C<authorize> method will
1391 be called with no arguments.
1393 =item authorize ( [AUTH [, RESP]])
1395 This is a protocol used by some firewall ftp proxies. It is used
1396 to authorise the user to send data out. If both arguments are not specified
1397 then C<authorize> uses C<Net::Netrc> to do a lookup.
1401 Send a SITE command to the remote server and wait for a response.
1403 Returns most significant digit of the response code.
1407 Transfer file in ASCII. CRLF translation will be done if required
1411 Transfer file in binary mode. No transformation will be done.
1413 B<Hint>: If both server and client machines use the same line ending for
1414 text files, then it will be faster to transfer all files in binary mode.
1416 =item rename ( OLDNAME, NEWNAME )
1418 Rename a file on the remote FTP server from C<OLDNAME> to C<NEWNAME>. This
1419 is done by sending the RNFR and RNTO commands.
1421 =item delete ( FILENAME )
1423 Send a request to the server to delete C<FILENAME>.
1425 =item cwd ( [ DIR ] )
1427 Attempt to change directory to the directory given in C<$dir>. If
1428 C<$dir> is C<"..">, the FTP C<CDUP> command is used to attempt to
1429 move up one directory. If no directory is given then an attempt is made
1430 to change the directory to the root directory.
1434 Change directory to the parent of the current directory.
1438 Returns the full pathname of the current directory.
1440 =item restart ( WHERE )
1442 Set the byte offset at which to begin the next data transfer. Net::FTP simply
1443 records this value and uses it when during the next data transfer. For this
1444 reason this method will not return an error, but setting it may cause
1445 a subsequent data transfer to fail.
1447 =item rmdir ( DIR [, RECURSE ])
1449 Remove the directory with the name C<DIR>. If C<RECURSE> is I<true> then
1450 C<rmdir> will attempt to delete everything inside the directory.
1452 =item mkdir ( DIR [, RECURSE ])
1454 Create a new directory with the name C<DIR>. If C<RECURSE> is I<true> then
1455 C<mkdir> will attempt to create all the directories in the given path.
1457 Returns the full pathname to the new directory.
1459 =item alloc ( SIZE [, RECORD_SIZE] )
1461 The alloc command allows you to give the ftp server a hint about the size
1462 of the file about to be transferred using the ALLO ftp command. Some storage
1463 systems use this to make intelligent decisions about how to store the file.
1464 The C<SIZE> argument represents the size of the file in bytes. The
1465 C<RECORD_SIZE> argument indicates a mazimum record or page size for files
1466 sent with a record or page structure.
1468 The size of the file will be determined, and sent to the server
1469 automatically for normal files so that this method need only be called if
1470 you are transferring data from a socket, named pipe, or other stream not
1471 associated with a normal file.
1473 =item ls ( [ DIR ] )
1475 Get a directory listing of C<DIR>, or the current directory.
1477 In an array context, returns a list of lines returned from the server. In
1478 a scalar context, returns a reference to a list.
1480 =item dir ( [ DIR ] )
1482 Get a directory listing of C<DIR>, or the current directory in long format.
1484 In an array context, returns a list of lines returned from the server. In
1485 a scalar context, returns a reference to a list.
1487 =item get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )
1489 Get C<REMOTE_FILE> from the server and store locally. C<LOCAL_FILE> may be
1490 a filename or a filehandle. If not specified, the file will be stored in
1491 the current directory with the same leafname as the remote file.
1493 If C<WHERE> is given then the first C<WHERE> bytes of the file will
1494 not be transferred, and the remaining bytes will be appended to
1495 the local file if it already exists.
1497 Returns C<LOCAL_FILE>, or the generated local file name if C<LOCAL_FILE>
1498 is not given. If an error was encountered undef is returned.
1500 =item put ( LOCAL_FILE [, REMOTE_FILE ] )
1502 Put a file on the remote server. C<LOCAL_FILE> may be a name or a filehandle.
1503 If C<LOCAL_FILE> is a filehandle then C<REMOTE_FILE> must be specified. If
1504 C<REMOTE_FILE> is not specified then the file will be stored in the current
1505 directory with the same leafname as C<LOCAL_FILE>.
1507 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1510 B<NOTE>: If for some reason the transfer does not complete and an error is
1511 returned then the contents that had been transferred will not be remove
1514 =item put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
1516 Same as put but uses the C<STOU> command.
1518 Returns the name of the file on the server.
1520 =item append ( LOCAL_FILE [, REMOTE_FILE ] )
1522 Same as put but appends to the file on the remote server.
1524 Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1527 =item unique_name ()
1529 Returns the name of the last file stored on the server using the
1534 Returns the I<modification time> of the given file
1538 Returns the size in bytes for the given file as stored on the remote server.
1540 B<NOTE>: The size reported is the size of the stored file on the remote server.
1541 If the file is subsequently transferred from the server in ASCII mode
1542 and the remote server and local machine have different ideas about
1543 "End Of Line" then the size of file on the local machine after transfer
1546 =item supported ( CMD )
1548 Returns TRUE if the remote server supports the given command.
1550 =item hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] )
1552 Called without parameters, or with the first argument false, hash marks
1553 are suppressed. If the first argument is true but not a reference to a
1554 file handle glob, then \*STDERR is used. The second argument is the number
1555 of bytes per hash mark printed, and defaults to 1024. In all cases the
1556 return value is a reference to an array of two: the filehandle glob reference
1557 and the bytes per hash mark.
1561 The following methods can return different results depending on
1562 how they are called. If the user explicitly calls either
1563 of the C<pasv> or C<port> methods then these methods will
1564 return a I<true> or I<false> value. If the user does not
1565 call either of these methods then the result will be a
1566 reference to a C<Net::FTP::dataconn> based object.
1570 =item nlst ( [ DIR ] )
1572 Send an C<NLST> command to the server, with an optional parameter.
1574 =item list ( [ DIR ] )
1576 Same as C<nlst> but using the C<LIST> command
1580 Begin the retrieval of a file called C<FILE> from the remote server.
1584 Tell the server that you wish to store a file. C<FILE> is the
1585 name of the new file that should be created.
1589 Same as C<stor> but using the C<STOU> command. The name of the unique
1590 file which was created on the server will be available via the C<unique_name>
1591 method after the data connection has been closed.
1595 Tell the server that we want to append some data to the end of a file
1596 called C<FILE>. If this file does not exist then create it.
1600 If for some reason you want to have complete control over the data connection,
1601 this includes generating it and calling the C<response> method when required,
1602 then the user can use these methods to do so.
1604 However calling these methods only affects the use of the methods above that
1605 can return a data connection. They have no effect on methods C<get>, C<put>,
1606 C<put_unique> and those that do not require data connections.
1610 =item port ( [ PORT ] )
1612 Send a C<PORT> command to the server. If C<PORT> is specified then it is sent
1613 to the server. If not, then a listen socket is created and the correct information
1618 Tell the server to go into passive mode. Returns the text that represents the
1619 port on which the server is listening, this text is in a suitable form to
1620 sent to another ftp server using the C<port> method.
1624 The following methods can be used to transfer files between two remote
1625 servers, providing that these two servers can connect directly to each other.
1629 =item pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1631 This method will do a file transfer between two remote ftp servers. If
1632 C<DEST_FILE> is omitted then the leaf name of C<SRC_FILE> will be used.
1634 =item pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1636 Like C<pasv_xfer> but the file is stored on the remote server using
1639 =item pasv_wait ( NON_PASV_SERVER )
1641 This method can be used to wait for a transfer to complete between a passive
1642 server and a non-passive server. The method should be called on the passive
1643 server with the C<Net::FTP> object for the non-passive server passed as an
1648 Abort the current data transfer.
1652 Send the QUIT command to the remote FTP server and close the socket connection.
1656 =head2 Methods for the adventurous
1658 C<Net::FTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
1659 be used to send commands to the remote FTP server.
1663 =item quot (CMD [,ARGS])
1665 Send a command, that Net::FTP does not directly support, to the remote
1666 server and wait for a response.
1668 Returns most significant digit of the response code.
1670 B<WARNING> This call should only be used on commands that do not require
1671 data connections. Misuse of this method can hang the connection.
1675 =head1 THE dataconn CLASS
1677 Some of the methods defined in C<Net::FTP> return an object which will
1678 be derived from this class.The dataconn class itself is derived from
1679 the C<IO::Socket::INET> class, so any normal IO operations can be performed.
1680 However the following methods are defined in the dataconn class and IO should
1681 be performed using these.
1685 =item read ( BUFFER, SIZE [, TIMEOUT ] )
1687 Read C<SIZE> bytes of data from the server and place it into C<BUFFER>, also
1688 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1689 given, the timeout value from the command connection will be used.
1691 Returns the number of bytes read before any <CRLF> translation.
1693 =item write ( BUFFER, SIZE [, TIMEOUT ] )
1695 Write C<SIZE> bytes of data from C<BUFFER> to the server, also
1696 performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1697 given, the timeout value from the command connection will be used.
1699 Returns the number of bytes written before any <CRLF> translation.
1703 Returns the number of bytes read so far.
1707 Abort the current data transfer.
1711 Close the data connection and get a response from the FTP server. Returns
1712 I<true> if the connection was closed successfully and the first digit of
1713 the response from the server was a '2'.
1717 =head1 UNIMPLEMENTED
1719 The following RFC959 commands have not been implemented:
1725 Mount a different file system structure without changing login or
1726 accounting information.
1730 Ask the server for "helpful information" (that's what the RFC says) on
1731 the commands it accepts.
1735 Specifies transfer mode (stream, block or compressed) for file to be
1740 Request remote server system identification.
1744 Request remote server status.
1748 Specifies file structure for file to be transferred.
1752 Reinitialize the connection, flushing all I/O and account information.
1756 =head1 REPORTING BUGS
1758 When reporting bugs/problems please include as much information as possible.
1759 It may be difficult for me to reproduce the problem as almost every setup
1762 A small script which yields the problem will probably be of help. It would
1763 also be useful if this script was run with the extra options C<Debug => 1>
1764 passed to the constructor, and the output sent with the bug report. If you
1765 cannot include a small script then please include a Debug trace from a
1766 run of your program which does yield the problem.
1770 Graham Barr <gbarr@pobox.com>
1777 ftp(1), ftpd(8), RFC 959
1778 http://www.cis.ohio-state.edu/htbin/rfc/rfc959.html
1782 For an example of the use of Net::FTP see
1786 =item http://www.csh.rit.edu/~adam/Progs/
1788 C<autoftp> is a program that can retrieve, send, or list files via
1789 the FTP protocol in a non-interactive manner.
1795 Henry Gabryjelski <henryg@WPI.EDU> - for the suggestion of creating directories
1798 Nathan Torkington <gnat@frii.com> - for some input on the documentation.
1800 Roderick Schertler <roderick@gate.net> - for various inputs
1804 Copyright (c) 1995-2004 Graham Barr. All rights reserved.
1805 This program is free software; you can redistribute it and/or modify it
1806 under the same terms as Perl itself.