1# Net::FTP.pm
2#
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.
6#
7# Documentation (at end) improved 1996 by Nathan Torkington <gnat@frii.com>.
8
9package Net::FTP;
10
11require 5.001;
12
13use strict;
14use vars qw(@ISA $VERSION);
15use Carp;
16
17use Socket 1.3;
18use IO::Socket;
19use Time::Local;
20use Net::Cmd;
21use Net::Config;
22use Fcntl qw(O_WRONLY O_RDONLY O_APPEND O_CREAT O_TRUNC);
23# use AutoLoader qw(AUTOLOAD);
24
25$VERSION = "2.72"; # $Id: //depot/libnet/Net/FTP.pm#80 $
26@ISA     = qw(Exporter Net::Cmd IO::Socket::INET);
27
28# Someday I will "use constant", when I am not bothered to much about
29# compatability with older releases of perl
30
31use vars qw($TELNET_IAC $TELNET_IP $TELNET_DM);
32($TELNET_IAC,$TELNET_IP,$TELNET_DM) = (255,244,242);
33
34# Name is too long for AutoLoad, it clashes with pasv_xfer
35sub pasv_xfer_unique {
36    my($sftp,$sfile,$dftp,$dfile) = @_;
37    $sftp->pasv_xfer($sfile,$dftp,$dfile,1);
38}
39
40BEGIN {
41  # make a constant so code is fast'ish
42  my $is_os390 = $^O eq 'os390';
43  *trEBCDIC = sub () { $is_os390 }
44}
45
461;
47# Having problems with AutoLoader
48#__END__
49
50sub new
51{
52 my $pkg  = shift;
53 my $peer = shift;
54 my %arg  = @_;
55
56 my $host = $peer;
57 my $fire = undef;
58 my $fire_type = undef;
59
60 if(exists($arg{Firewall}) || Net::Config->requires_firewall($peer))
61  {
62   $fire = $arg{Firewall}
63	|| $ENV{FTP_FIREWALL}
64	|| $NetConfig{ftp_firewall}
65	|| undef;
66
67   if(defined $fire)
68    {
69     $peer = $fire;
70     delete $arg{Port};
71	 $fire_type = $arg{FirewallType}
72	 || $ENV{FTP_FIREWALL_TYPE}
73	 || $NetConfig{firewall_type}
74	 || undef;
75    }
76  }
77
78 my $ftp = $pkg->SUPER::new(PeerAddr => $peer,
79			    PeerPort => $arg{Port} || 'ftp(21)',
80			    LocalAddr => $arg{'LocalAddr'},
81			    Proto    => 'tcp',
82			    Timeout  => defined $arg{Timeout}
83						? $arg{Timeout}
84						: 120
85			   ) or return undef;
86
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);
90
91 ${*$ftp}{'net_ftp_localaddr'} = $arg{'LocalAddr'};
92
93 ${*$ftp}{'net_ftp_firewall'} = $fire
94	if(defined $fire);
95 ${*$ftp}{'net_ftp_firewall_type'} = $fire_type
96	if(defined $fire_type);
97
98 ${*$ftp}{'net_ftp_passive'} = int
99	exists $arg{Passive}
100	    ? $arg{Passive}
101	    : exists $ENV{FTP_PASSIVE}
102		? $ENV{FTP_PASSIVE}
103		: defined $fire
104		    ? $NetConfig{ftp_ext_passive}
105		    : $NetConfig{ftp_int_passive};	# Whew! :-)
106
107 $ftp->hash(exists $arg{Hash} ? $arg{Hash} : 0, 1024);
108
109 $ftp->autoflush(1);
110
111 $ftp->debug(exists $arg{Debug} ? $arg{Debug} : undef);
112
113 unless ($ftp->response() == CMD_OK)
114  {
115   $ftp->close();
116   $@ = $ftp->message;
117   undef $ftp;
118  }
119
120 $ftp;
121}
122
123##
124## User interface methods
125##
126
127sub hash {
128    my $ftp = shift;		# self
129
130    my($h,$b) = @_;
131    unless($h) {
132      delete ${*$ftp}{'net_ftp_hash'};
133      return [\*STDERR,0];
134    }
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];
139}
140
141sub quit
142{
143 my $ftp = shift;
144
145 $ftp->_QUIT;
146 $ftp->close;
147}
148
149sub DESTROY {}
150
151sub ascii  { shift->type('A',@_); }
152sub binary { shift->type('I',@_); }
153
154sub ebcdic
155{
156 carp "TYPE E is unsupported, shall default to I";
157 shift->type('E',@_);
158}
159
160sub byte
161{
162 carp "TYPE L is unsupported, shall default to I";
163 shift->type('L',@_);
164}
165
166# Allow the user to send a command directly, BE CAREFUL !!
167
168sub quot
169{
170 my $ftp = shift;
171 my $cmd = shift;
172
173 $ftp->command( uc $cmd, @_);
174 $ftp->response();
175}
176
177sub site
178{
179 my $ftp = shift;
180
181 $ftp->command("SITE", @_);
182 $ftp->response();
183}
184
185sub mdtm
186{
187 my $ftp  = shift;
188 my $file = shift;
189
190 # Server Y2K bug workaround
191 #
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.
197
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))
200    : undef;
201}
202
203sub size {
204  my $ftp  = shift;
205  my $file = shift;
206  my $io;
207  if($ftp->supported("SIZE")) {
208    return $ftp->_SIZE($file)
209	? ($ftp->message =~ /(\d+)\s*$/)[0]
210	: undef;
211 }
212 elsif($ftp->supported("STAT")) {
213   my @msg;
214   return undef
215       unless $ftp->_STAT($file) && (@msg = $ftp->message) == 3;
216   my $line;
217   foreach $line (@msg) {
218     return (split(/\s+/,$line))[4]
219	 if $line =~ /^[-rwxSsTt]{10}/
220   }
221 }
222 else {
223   my @files = $ftp->dir($file);
224   if(@files) {
225     return (split(/\s+/,$1))[4]
226	 if $files[0] =~ /^([-rwxSsTt]{10}.*)$/;
227   }
228 }
229 undef;
230}
231
232sub login {
233  my($ftp,$user,$pass,$acct) = @_;
234  my($ok,$ruser,$fwtype);
235
236  unless (defined $user) {
237    require Net::Netrc;
238
239    my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'});
240
241    ($user,$pass,$acct) = $rc->lpa()
242	 if ($rc);
243   }
244
245  $user ||= "anonymous";
246  $ruser = $user;
247
248  $fwtype = ${*$ftp}{'net_ftp_firewall_type'}
249  || $NetConfig{'ftp_firewall_type'}
250  || 0;
251
252  if ($fwtype && defined ${*$ftp}{'net_ftp_firewall'}) {
253    if ($fwtype == 1 || $fwtype == 7) {
254      $user .= '@' . ${*$ftp}{'net_ftp_host'};
255    }
256    else {
257      require Net::Netrc;
258
259      my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
260
261      my($fwuser,$fwpass,$fwacct) = $rc ? $rc->lpa() : ();
262
263      if ($fwtype == 5) {
264	$user = join('@',$user,$fwuser,${*$ftp}{'net_ftp_host'});
265	$pass = $pass . '@' . $fwpass;
266      }
267      else {
268	if ($fwtype == 2) {
269	  $user .= '@' . ${*$ftp}{'net_ftp_host'};
270	}
271	elsif ($fwtype == 6) {
272	  $fwuser .= '@' . ${*$ftp}{'net_ftp_host'};
273	}
274
275	$ok = $ftp->_USER($fwuser);
276
277	return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
278
279	$ok = $ftp->_PASS($fwpass || "");
280
281	return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
282
283	$ok = $ftp->_ACCT($fwacct)
284	  if defined($fwacct);
285
286	if ($fwtype == 3) {
287          $ok = $ftp->command("SITE",${*$ftp}{'net_ftp_host'})->response;
288	}
289	elsif ($fwtype == 4) {
290          $ok = $ftp->command("OPEN",${*$ftp}{'net_ftp_host'})->response;
291	}
292
293	return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
294      }
295    }
296  }
297
298  $ok = $ftp->_USER($user);
299
300  # Some dumb firewalls don't prefix the connection messages
301  $ok = $ftp->response()
302	 if ($ok == CMD_OK && $ftp->code == 220 && $user =~ /\@/);
303
304  if ($ok == CMD_MORE) {
305    unless(defined $pass) {
306      require Net::Netrc;
307
308      my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'}, $ruser);
309
310      ($ruser,$pass,$acct) = $rc->lpa()
311	 if ($rc);
312
313      $pass = '-anonymous@'
314         if (!defined $pass && (!defined($ruser) || $ruser =~ /^anonymous/o));
315    }
316
317    $ok = $ftp->_PASS($pass || "");
318  }
319
320  $ok = $ftp->_ACCT($acct)
321	 if (defined($acct) && ($ok == CMD_MORE || $ok == CMD_OK));
322
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);
326  }
327
328  $ok == CMD_OK;
329}
330
331sub account
332{
333 @_ == 2 or croak 'usage: $ftp->account( ACCT )';
334 my $ftp = shift;
335 my $acct = shift;
336 $ftp->_ACCT($acct) == CMD_OK;
337}
338
339sub _auth_id {
340 my($ftp,$auth,$resp) = @_;
341
342 unless(defined $resp)
343  {
344   require Net::Netrc;
345
346   $auth ||= eval { (getpwuid($>))[0] } || $ENV{NAME};
347
348   my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'}, $auth)
349        || Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
350
351   ($auth,$resp) = $rc->lpa()
352     if ($rc);
353  }
354  ($ftp,$auth,$resp);
355}
356
357sub authorize
358{
359 @_ >= 1 || @_ <= 3 or croak 'usage: $ftp->authorize( [AUTH [, RESP]])';
360
361 my($ftp,$auth,$resp) = &_auth_id;
362
363 my $ok = $ftp->_AUTH($auth || "");
364
365 $ok = $ftp->_RESP($resp || "")
366	if ($ok == CMD_MORE);
367
368 $ok == CMD_OK;
369}
370
371sub rename
372{
373 @_ == 3 or croak 'usage: $ftp->rename(FROM, TO)';
374
375 my($ftp,$from,$to) = @_;
376
377 $ftp->_RNFR($from)
378    && $ftp->_RNTO($to);
379}
380
381sub type
382{
383 my $ftp = shift;
384 my $type = shift;
385 my $oldval = ${*$ftp}{'net_ftp_type'};
386
387 return $oldval
388	unless (defined $type);
389
390 return undef
391	unless ($ftp->_TYPE($type,@_));
392
393 ${*$ftp}{'net_ftp_type'} = join(" ",$type,@_);
394
395 $oldval;
396}
397
398sub alloc
399{
400 my $ftp = shift;
401 my $size = shift;
402 my $oldval = ${*$ftp}{'net_ftp_allo'};
403
404 return $oldval
405	unless (defined $size);
406
407 return undef
408	unless ($ftp->_ALLO($size,@_));
409
410 ${*$ftp}{'net_ftp_allo'} = join(" ",$size,@_);
411
412 $oldval;
413}
414
415sub abort
416{
417 my $ftp = shift;
418
419 send($ftp,pack("CCC", $TELNET_IAC, $TELNET_IP, $TELNET_IAC),MSG_OOB);
420
421 $ftp->command(pack("C",$TELNET_DM) . "ABOR");
422
423 ${*$ftp}{'net_ftp_dataconn'}->close()
424    if defined ${*$ftp}{'net_ftp_dataconn'};
425
426 $ftp->response();
427
428 $ftp->status == CMD_OK;
429}
430
431sub get
432{
433 my($ftp,$remote,$local,$where) = @_;
434
435 my($loc,$len,$buf,$resp,$data);
436 local *FD;
437
438 my $localfd = ref($local) || ref(\$local) eq "GLOB";
439
440 ($local = $remote) =~ s#^.*/##
441	unless(defined $local);
442
443 croak("Bad remote filename '$remote'\n")
444	if $remote =~ /[\r\n]/s;
445
446 ${*$ftp}{'net_ftp_rest'} = $where
447	if ($where);
448
449 delete ${*$ftp}{'net_ftp_port'};
450 delete ${*$ftp}{'net_ftp_pasv'};
451
452 $data = $ftp->retr($remote) or
453	return undef;
454
455 if($localfd)
456  {
457   $loc = $local;
458  }
459 else
460  {
461   $loc = \*FD;
462
463   unless(sysopen($loc, $local, O_CREAT | O_WRONLY | ($where ? O_APPEND : O_TRUNC)))
464    {
465     carp "Cannot open Local file $local: $!\n";
466     $data->abort;
467     return undef;
468    }
469  }
470
471 if($ftp->type eq 'I' && !binmode($loc))
472  {
473   carp "Cannot binmode Local file $local: $!\n";
474   $data->abort;
475   close($loc) unless $localfd;
476   return undef;
477  }
478
479 $buf = '';
480 my($count,$hashh,$hashb,$ref) = (0);
481
482 ($hashh,$hashb) = @$ref
483   if($ref = ${*$ftp}{'net_ftp_hash'});
484
485 my $blksize = ${*$ftp}{'net_ftp_blksize'};
486 local $\; # Just in case
487
488 while(1)
489  {
490   last unless $len = $data->read($buf,$blksize);
491
492   if (trEBCDIC && $ftp->type ne 'I')
493    {
494     $buf = $ftp->toebcdic($buf);
495     $len = length($buf);
496    }
497
498   if($hashh) {
499    $count += $len;
500    print $hashh "#" x (int($count / $hashb));
501    $count %= $hashb;
502   }
503   unless(print $loc $buf)
504    {
505     carp "Cannot write to Local file $local: $!\n";
506     $data->abort;
507     close($loc)
508        unless $localfd;
509     return undef;
510    }
511  }
512
513 print $hashh "\n" if $hashh;
514
515 unless ($localfd)
516  {
517   unless (close($loc))
518    {
519     carp "Cannot close file $local (perhaps disk space) $!\n";
520     return undef;
521    }
522  }
523
524 unless ($data->close()) # implied $ftp->response
525  {
526   carp "Unable to close datastream";
527   return undef;
528  }
529
530 return $local;
531}
532
533sub cwd
534{
535 @_ == 1 || @_ == 2 or croak 'usage: $ftp->cwd( [ DIR ] )';
536
537 my($ftp,$dir) = @_;
538
539 $dir = "/" unless defined($dir) && $dir =~ /\S/;
540
541 $dir eq ".."
542    ? $ftp->_CDUP()
543    : $ftp->_CWD($dir);
544}
545
546sub cdup
547{
548 @_ == 1 or croak 'usage: $ftp->cdup()';
549 $_[0]->_CDUP;
550}
551
552sub pwd
553{
554 @_ == 1 || croak 'usage: $ftp->pwd()';
555 my $ftp = shift;
556
557 $ftp->_PWD();
558 $ftp->_extract_path;
559}
560
561# rmdir( $ftp, $dir, [ $recurse ] )
562#
563# Removes $dir on remote host via FTP.
564# $ftp is handle for remote host
565#
566# If $recurse is TRUE, the directory and deleted recursively.
567# This means all of its contents and subdirectories.
568#
569# Initial version contributed by Dinkum Software
570#
571sub rmdir
572{
573    @_ == 2 || @_ == 3 or croak('usage: $ftp->rmdir( DIR [, RECURSE ] )');
574
575    # Pick off the args
576    my ($ftp, $dir, $recurse) = @_ ;
577    my $ok;
578
579    return $ok
580	if $ok = $ftp->_RMD( $dir ) or !$recurse;
581
582    # Try to delete the contents
583    # Get a list of all the files in the directory
584    my $filelist = $ftp->ls($dir);
585
586    return undef
587	unless $filelist && @$filelist; # failed, it is probably not a directory
588
589    # Go thru and delete each file or the directory
590    my $file;
591    foreach $file (map { m,/, ? $_ : "$dir/$_" } @$filelist)
592    {
593	next  # successfully deleted the file
594	    if $ftp->delete($file);
595
596	# Failed to delete it, assume its a directory
597	# Recurse and ignore errors, the final rmdir() will
598	# fail on any errors here
599	return $ok
600	    unless $ok = $ftp->rmdir($file, 1) ;
601    }
602
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) ;
609}
610
611sub restart
612{
613  @_ == 2 || croak 'usage: $ftp->restart( BYTE_OFFSET )';
614
615  my($ftp,$where) = @_;
616
617  ${*$ftp}{'net_ftp_rest'} = $where;
618
619  return undef;
620}
621
622
623sub mkdir
624{
625 @_ == 2 || @_ == 3 or croak 'usage: $ftp->mkdir( DIR [, RECURSE ] )';
626
627 my($ftp,$dir,$recurse) = @_;
628
629 $ftp->_MKD($dir) || $recurse or
630    return undef;
631
632 my $path = $dir;
633
634 unless($ftp->ok)
635  {
636   my @path = split(m#(?=/+)#, $dir);
637
638   $path = "";
639
640   while(@path)
641    {
642     $path .= shift @path;
643
644     $ftp->_MKD($path);
645
646     $path = $ftp->_extract_path($path);
647    }
648
649   # If the creation of the last element was not successful, see if we
650   # can cd to it, if so then return path
651
652   unless($ftp->ok)
653    {
654     my($status,$message) = ($ftp->status,$ftp->message);
655     my $pwd = $ftp->pwd;
656
657     if($pwd && $ftp->cwd($dir))
658      {
659       $path = $dir;
660       $ftp->cwd($pwd);
661      }
662     else
663      {
664       undef $path;
665      }
666     $ftp->set_status($status,$message);
667    }
668  }
669
670 $path;
671}
672
673sub delete
674{
675 @_ == 2 || croak 'usage: $ftp->delete( FILENAME )';
676
677 $_[0]->_DELE($_[1]);
678}
679
680sub put        { shift->_store_cmd("stor",@_) }
681sub put_unique { shift->_store_cmd("stou",@_) }
682sub append     { shift->_store_cmd("appe",@_) }
683
684sub nlst { shift->_data_cmd("NLST",@_) }
685sub list { shift->_data_cmd("LIST",@_) }
686sub retr { shift->_data_cmd("RETR",@_) }
687sub stor { shift->_data_cmd("STOR",@_) }
688sub stou { shift->_data_cmd("STOU",@_) }
689sub appe { shift->_data_cmd("APPE",@_) }
690
691sub _store_cmd
692{
693 my($ftp,$cmd,$local,$remote) = @_;
694 my($loc,$sock,$len,$buf);
695 local *FD;
696
697 my $localfd = ref($local) || ref(\$local) eq "GLOB";
698
699 unless(defined $remote)
700  {
701   croak 'Must specify remote filename with stream input'
702	if $localfd;
703
704   require File::Basename;
705   $remote = File::Basename::basename($local);
706  }
707 if( defined ${*$ftp}{'net_ftp_allo'} )
708  {
709   delete ${*$ftp}{'net_ftp_allo'};
710  } else
711  {
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;
718  }
719 croak("Bad remote filename '$remote'\n")
720	if $remote =~ /[\r\n]/s;
721
722 if($localfd)
723  {
724   $loc = $local;
725  }
726 else
727  {
728   $loc = \*FD;
729
730   unless(sysopen($loc, $local, O_RDONLY))
731    {
732     carp "Cannot open Local file $local: $!\n";
733     return undef;
734    }
735  }
736
737 if($ftp->type eq 'I' && !binmode($loc))
738  {
739   carp "Cannot binmode Local file $local: $!\n";
740   return undef;
741  }
742
743 delete ${*$ftp}{'net_ftp_port'};
744 delete ${*$ftp}{'net_ftp_pasv'};
745
746 $sock = $ftp->_data_cmd($cmd, $remote) or
747	return undef;
748
749 $remote = ($ftp->message =~ /FILE:\s*(.*)/)[0]
750   if 'STOU' eq uc $cmd;
751
752 my $blksize = ${*$ftp}{'net_ftp_blksize'};
753
754 my($count,$hashh,$hashb,$ref) = (0);
755
756 ($hashh,$hashb) = @$ref
757   if($ref = ${*$ftp}{'net_ftp_hash'});
758
759 while(1)
760  {
761   last unless $len = read($loc,$buf="",$blksize);
762
763   if (trEBCDIC && $ftp->type ne 'I')
764    {
765     $buf = $ftp->toascii($buf);
766     $len = length($buf);
767    }
768
769   if($hashh) {
770    $count += $len;
771    print $hashh "#" x (int($count / $hashb));
772    $count %= $hashb;
773   }
774
775   my $wlen;
776   unless(defined($wlen = $sock->write($buf,$len)) && $wlen == $len)
777    {
778     $sock->abort;
779     close($loc)
780	unless $localfd;
781     print $hashh "\n" if $hashh;
782     return undef;
783    }
784  }
785
786 print $hashh "\n" if $hashh;
787
788 close($loc)
789	unless $localfd;
790
791 $sock->close() or
792	return undef;
793
794 if ('STOU' eq uc $cmd and $ftp->message =~ m/unique\s+file\s*name\s*:\s*(.*)\)|"(.*)"/)
795  {
796   require File::Basename;
797   $remote = File::Basename::basename($+)
798  }
799
800 return $remote;
801}
802
803sub port
804{
805 @_ == 1 || @_ == 2 or croak 'usage: $ftp->port([PORT])';
806
807 my($ftp,$port) = @_;
808 my $ok;
809
810 delete ${*$ftp}{'net_ftp_intern_port'};
811
812 unless(defined $port)
813  {
814   # create a Listen socket at same address as the command socket
815
816   ${*$ftp}{'net_ftp_listen'} ||= IO::Socket::INET->new(Listen    => 5,
817				    	    	        Proto     => 'tcp',
818							Timeout   => $ftp->timeout,
819							LocalAddr => $ftp->sockhost,
820				    	    	       );
821
822   my $listen = ${*$ftp}{'net_ftp_listen'};
823
824   my($myport, @myaddr) = ($listen->sockport, split(/\./,$listen->sockhost));
825
826   $port = join(',', @myaddr, $myport >> 8, $myport & 0xff);
827
828   ${*$ftp}{'net_ftp_intern_port'} = 1;
829  }
830
831 $ok = $ftp->_PORT($port);
832
833 ${*$ftp}{'net_ftp_port'} = $port;
834
835 $ok;
836}
837
838sub ls  { shift->_list_cmd("NLST",@_); }
839sub dir { shift->_list_cmd("LIST",@_); }
840
841sub pasv
842{
843 @_ == 1 or croak 'usage: $ftp->pasv()';
844
845 my $ftp = shift;
846
847 delete ${*$ftp}{'net_ftp_intern_port'};
848
849 $ftp->_PASV && $ftp->message =~ /(\d+(,\d+)+)/
850    ? ${*$ftp}{'net_ftp_pasv'} = $1
851    : undef;
852}
853
854sub unique_name
855{
856 my $ftp = shift;
857 ${*$ftp}{'net_ftp_unique'} || undef;
858}
859
860sub supported {
861    @_ == 2 or croak 'usage: $ftp->supported( CMD )';
862    my $ftp = shift;
863    my $cmd = uc shift;
864    my $hash = ${*$ftp}{'net_ftp_supported'} ||= {};
865
866    return $hash->{$cmd}
867        if exists $hash->{$cmd};
868
869    return $hash->{$cmd} = 0
870	unless $ftp->_HELP($cmd);
871
872    my $text = $ftp->message;
873    if($text =~ /following\s+commands/i) {
874	$text =~ s/^.*\n//;
875        while($text =~ /(\*?)(\w+)(\*?)/sg) {
876            $hash->{"\U$2"} = !length("$1$3");
877        }
878    }
879    else {
880	$hash->{$cmd} = $text !~ /unimplemented/i;
881    }
882
883    $hash->{$cmd} ||= 0;
884}
885
886##
887## Deprecated methods
888##
889
890sub lsl
891{
892 carp "Use of Net::FTP::lsl deprecated, use 'dir'"
893    if $^W;
894 goto &dir;
895}
896
897sub authorise
898{
899 carp "Use of Net::FTP::authorise deprecated, use 'authorize'"
900    if $^W;
901 goto &authorize;
902}
903
904
905##
906## Private methods
907##
908
909sub _extract_path
910{
911 my($ftp, $path) = @_;
912
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.
917 $ftp->ok &&
918    $ftp->message =~ /(?:^|\s)\"(.*)\"(?:$|\s)/ &&
919    ($path = $1) =~ s/\"\"/\"/g;
920
921 $path;
922}
923
924##
925## Communication methods
926##
927
928sub _dataconn
929{
930 my $ftp = shift;
931 my $data = undef;
932 my $pkg = "Net::FTP::" . $ftp->type;
933
934 eval "require " . $pkg;
935
936 $pkg =~ s/ /_/g;
937
938 delete ${*$ftp}{'net_ftp_dataconn'};
939
940 if(defined ${*$ftp}{'net_ftp_pasv'})
941  {
942   my @port = split(/,/,${*$ftp}{'net_ftp_pasv'});
943
944   $data = $pkg->new(PeerAddr => join(".",@port[0..3]),
945    	    	     PeerPort => $port[4] * 256 + $port[5],
946		     LocalAddr => ${*$ftp}{'net_ftp_localaddr'},
947    	    	     Proto    => 'tcp'
948    	    	    );
949  }
950 elsif(defined ${*$ftp}{'net_ftp_listen'})
951  {
952   $data = ${*$ftp}{'net_ftp_listen'}->accept($pkg);
953   close(delete ${*$ftp}{'net_ftp_listen'});
954  }
955
956 if($data)
957  {
958   ${*$data} = "";
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'};
963  }
964
965 $data;
966}
967
968sub _list_cmd
969{
970 my $ftp = shift;
971 my $cmd = uc shift;
972
973 delete ${*$ftp}{'net_ftp_port'};
974 delete ${*$ftp}{'net_ftp_pasv'};
975
976 my $data = $ftp->_data_cmd($cmd,@_);
977
978 return
979	unless(defined $data);
980
981 require Net::FTP::A;
982 bless $data, "Net::FTP::A"; # Force ASCII mode
983
984 my $databuf = '';
985 my $buf = '';
986 my $blksize = ${*$ftp}{'net_ftp_blksize'};
987
988 while($data->read($databuf,$blksize)) {
989   $buf .= $databuf;
990 }
991
992 my $list = [ split(/\n/,$buf) ];
993
994 $data->close();
995
996 if (trEBCDIC)
997  {
998   for (@$list) { $_ = $ftp->toebcdic($_) }
999  }
1000
1001 wantarray ? @{$list}
1002           : $list;
1003}
1004
1005sub _data_cmd
1006{
1007 my $ftp = shift;
1008 my $cmd = uc shift;
1009 my $ok = 1;
1010 my $where = delete ${*$ftp}{'net_ftp_rest'} || 0;
1011 my $arg;
1012
1013 for $arg (@_) {
1014   croak("Bad argument '$arg'\n")
1015	if $arg =~ /[\r\n]/s;
1016 }
1017
1018 if(${*$ftp}{'net_ftp_passive'} &&
1019     !defined ${*$ftp}{'net_ftp_pasv'} &&
1020     !defined ${*$ftp}{'net_ftp_port'})
1021  {
1022   my $data = undef;
1023
1024   $ok = defined $ftp->pasv;
1025   $ok = $ftp->_REST($where)
1026	if $ok && $where;
1027
1028   if($ok)
1029    {
1030     $ftp->command($cmd,@_);
1031     $data = $ftp->_dataconn();
1032     $ok = CMD_INFO == $ftp->response();
1033     if($ok)
1034      {
1035       $data->reading
1036         if $data && $cmd =~ /RETR|LIST|NLST/;
1037       return $data
1038      }
1039     $data->_close
1040	if $data;
1041    }
1042   return undef;
1043  }
1044
1045 $ok = $ftp->port
1046    unless (defined ${*$ftp}{'net_ftp_port'} ||
1047            defined ${*$ftp}{'net_ftp_pasv'});
1048
1049 $ok = $ftp->_REST($where)
1050    if $ok && $where;
1051
1052 return undef
1053    unless $ok;
1054
1055 $ftp->command($cmd,@_);
1056
1057 return 1
1058    if(defined ${*$ftp}{'net_ftp_pasv'});
1059
1060 $ok = CMD_INFO == $ftp->response();
1061
1062 return $ok
1063    unless exists ${*$ftp}{'net_ftp_intern_port'};
1064
1065 if($ok) {
1066   my $data = $ftp->_dataconn();
1067
1068   $data->reading
1069         if $data && $cmd =~ /RETR|LIST|NLST/;
1070
1071   return $data;
1072 }
1073
1074
1075 close(delete ${*$ftp}{'net_ftp_listen'});
1076
1077 return undef;
1078}
1079
1080##
1081## Over-ride methods (Net::Cmd)
1082##
1083
1084sub debug_text { $_[2] =~ /^(pass|resp|acct)/i ? "$1 ....\n" : $_[2]; }
1085
1086sub command
1087{
1088 my $ftp = shift;
1089
1090 delete ${*$ftp}{'net_ftp_port'};
1091 $ftp->SUPER::command(@_);
1092}
1093
1094sub response
1095{
1096 my $ftp = shift;
1097 my $code = $ftp->SUPER::response();
1098
1099 delete ${*$ftp}{'net_ftp_pasv'}
1100    if ($code != CMD_MORE && $code != CMD_INFO);
1101
1102 $code;
1103}
1104
1105sub parse_response
1106{
1107 return ($1, $2 eq "-")
1108    if $_[1] =~ s/^(\d\d\d)(.?)//o;
1109
1110 my $ftp = shift;
1111
1112 # Darn MS FTP server is a load of CRAP !!!!
1113 return ()
1114	unless ${*$ftp}{'net_cmd_code'} + 0;
1115
1116 (${*$ftp}{'net_cmd_code'},1);
1117}
1118
1119##
1120## Allow 2 servers to talk directly
1121##
1122
1123sub pasv_xfer {
1124    my($sftp,$sfile,$dftp,$dfile,$unique) = @_;
1125
1126    ($dfile = $sfile) =~ s#.*/##
1127	unless(defined $dfile);
1128
1129    my $port = $sftp->pasv or
1130	return undef;
1131
1132    $dftp->port($port) or
1133	return undef;
1134
1135    return undef
1136	unless($unique ? $dftp->stou($dfile) : $dftp->stor($dfile));
1137
1138    unless($sftp->retr($sfile) && $sftp->response == CMD_INFO) {
1139	$sftp->retr($sfile);
1140	$dftp->abort;
1141	$dftp->response();
1142	return undef;
1143    }
1144
1145    $dftp->pasv_wait($sftp);
1146}
1147
1148sub pasv_wait
1149{
1150 @_ == 2 or croak 'usage: $ftp->pasv_wait(NON_PASV_FTP)';
1151
1152 my($ftp, $non_pasv) = @_;
1153 my($file,$rin,$rout);
1154
1155 vec($rin='',fileno($ftp),1) = 1;
1156 select($rout=$rin, undef, undef, undef);
1157
1158 $ftp->response();
1159 $non_pasv->response();
1160
1161 return undef
1162	unless $ftp->ok() && $non_pasv->ok();
1163
1164 return $1
1165	if $ftp->message =~ /unique file name:\s*(\S*)\s*\)/;
1166
1167 return $1
1168	if $non_pasv->message =~ /unique file name:\s*(\S*)\s*\)/;
1169
1170 return 1;
1171}
1172
1173sub cmd { shift->command(@_)->response() }
1174
1175########################################
1176#
1177# RFC959 commands
1178#
1179
1180sub _ABOR { shift->command("ABOR")->response()	 == CMD_OK }
1181sub _ALLO { shift->command("ALLO",@_)->response() == CMD_OK}
1182sub _CDUP { shift->command("CDUP")->response()	 == CMD_OK }
1183sub _NOOP { shift->command("NOOP")->response()	 == CMD_OK }
1184sub _PASV { shift->command("PASV")->response()	 == CMD_OK }
1185sub _QUIT { shift->command("QUIT")->response()	 == CMD_OK }
1186sub _DELE { shift->command("DELE",@_)->response() == CMD_OK }
1187sub _CWD  { shift->command("CWD", @_)->response() == CMD_OK }
1188sub _PORT { shift->command("PORT",@_)->response() == CMD_OK }
1189sub _RMD  { shift->command("RMD", @_)->response() == CMD_OK }
1190sub _MKD  { shift->command("MKD", @_)->response() == CMD_OK }
1191sub _PWD  { shift->command("PWD", @_)->response() == CMD_OK }
1192sub _TYPE { shift->command("TYPE",@_)->response() == CMD_OK }
1193sub _RNTO { shift->command("RNTO",@_)->response() == CMD_OK }
1194sub _RESP { shift->command("RESP",@_)->response() == CMD_OK }
1195sub _MDTM { shift->command("MDTM",@_)->response() == CMD_OK }
1196sub _SIZE { shift->command("SIZE",@_)->response() == CMD_OK }
1197sub _HELP { shift->command("HELP",@_)->response() == CMD_OK }
1198sub _STAT { shift->command("STAT",@_)->response() == CMD_OK }
1199sub _APPE { shift->command("APPE",@_)->response() == CMD_INFO }
1200sub _LIST { shift->command("LIST",@_)->response() == CMD_INFO }
1201sub _NLST { shift->command("NLST",@_)->response() == CMD_INFO }
1202sub _RETR { shift->command("RETR",@_)->response() == CMD_INFO }
1203sub _STOR { shift->command("STOR",@_)->response() == CMD_INFO }
1204sub _STOU { shift->command("STOU",@_)->response() == CMD_INFO }
1205sub _RNFR { shift->command("RNFR",@_)->response() == CMD_MORE }
1206sub _REST { shift->command("REST",@_)->response() == CMD_MORE }
1207sub _USER { shift->command("user",@_)->response() } # A certain brain dead firewall :-)
1208sub _PASS { shift->command("PASS",@_)->response() }
1209sub _ACCT { shift->command("ACCT",@_)->response() }
1210sub _AUTH { shift->command("AUTH",@_)->response() }
1211
1212sub _SMNT { shift->unsupported(@_) }
1213sub _MODE { shift->unsupported(@_) }
1214sub _SYST { shift->unsupported(@_) }
1215sub _STRU { shift->unsupported(@_) }
1216sub _REIN { shift->unsupported(@_) }
1217
12181;
1219
1220__END__
1221
1222=head1 NAME
1223
1224Net::FTP - FTP Client class
1225
1226=head1 SYNOPSIS
1227
1228    use Net::FTP;
1229
1230    $ftp = Net::FTP->new("some.host.name", Debug => 0)
1231      or die "Cannot connect to some.host.name: $@";
1232
1233    $ftp->login("anonymous",'-anonymous@')
1234      or die "Cannot login ", $ftp->message;
1235
1236    $ftp->cwd("/pub")
1237      or die "Cannot change working directory ", $ftp->message;
1238
1239    $ftp->get("that.file")
1240      or die "get failed ", $ftp->message;
1241
1242    $ftp->quit;
1243
1244=head1 DESCRIPTION
1245
1246C<Net::FTP> is a class implementing a simple FTP client in Perl as
1247described in RFC959.  It provides wrappers for a subset of the RFC959
1248commands.
1249
1250=head1 OVERVIEW
1251
1252FTP stands for File Transfer Protocol.  It is a way of transferring
1253files between networked machines.  The protocol defines a client
1254(whose commands are provided by this module) and a server (not
1255implemented in this module).  Communication is always initiated by the
1256client, and the server responds with a message and a status code (and
1257sometimes with data).
1258
1259The FTP protocol allows files to be sent to or fetched from the
1260server.  Each transfer involves a B<local file> (on the client) and a
1261B<remote file> (on the server).  In this module, the same file name
1262will be used for both local and remote if only one is specified.  This
1263means that transferring remote file C</path/to/file> will try to put
1264that file in C</path/to/file> locally, unless you specify a local file
1265name.
1266
1267The protocol also defines several standard B<translations> which the
1268file can undergo during transfer.  These are ASCII, EBCDIC, binary,
1269and byte.  ASCII is the default type, and indicates that the sender of
1270files will translate the ends of lines to a standard representation
1271which the receiver will then translate back into their local
1272representation.  EBCDIC indicates the file being transferred is in
1273EBCDIC format.  Binary (also known as image) format sends the data as
1274a contiguous bit stream.  Byte format transfers the data as bytes, the
1275values of which remain the same regardless of differences in byte size
1276between the two machines (in theory - in practice you should only use
1277this if you really know what you're doing).
1278
1279=head1 CONSTRUCTOR
1280
1281=over 4
1282
1283=item new (HOST [,OPTIONS])
1284
1285This is the constructor for a new Net::FTP object. C<HOST> is the
1286name of the remote host to which an FTP connection is required.
1287
1288C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
1289Possible options are:
1290
1291B<Firewall> - The name of a machine which acts as an FTP firewall. This can be
1292overridden by an environment variable C<FTP_FIREWALL>. If specified, and the
1293given host cannot be directly connected to, then the
1294connection is made to the firewall machine and the string C<@hostname> is
1295appended to the login identifier. This kind of setup is also refered to
1296as an ftp proxy.
1297
1298B<FirewallType> - The type of firewall running on the machine indicated by
1299B<Firewall>. This can be overridden by an environment variable
1300C<FTP_FIREWALL_TYPE>. For a list of permissible types, see the description of
1301ftp_firewall_type in L<Net::Config>.
1302
1303B<BlockSize> - This is the block size that Net::FTP will use when doing
1304transfers. (defaults to 10240)
1305
1306B<Port> - The port number to connect to on the remote machine for the
1307FTP connection
1308
1309B<Timeout> - Set a timeout value (defaults to 120)
1310
1311B<Debug> - debug level (see the debug method in L<Net::Cmd>)
1312
1313B<Passive> - If set to a non-zero value then all data transfers will be done
1314using passive mode. This is not usually required except for some I<dumb>
1315servers, and some firewall configurations. This can also be set by the
1316environment variable C<FTP_PASSIVE>.
1317
1318B<Hash> - If given a reference to a file handle (e.g., C<\*STDERR>),
1319print hash marks (#) on that filehandle every 1024 bytes.  This
1320simply invokes the C<hash()> method for you, so that hash marks
1321are displayed for all transfers.  You can, of course, call C<hash()>
1322explicitly whenever you'd like.
1323
1324B<LocalAddr> - Local address to use for all socket connections, this
1325argument will be passed to L<IO::Socket::INET>
1326
1327If the constructor fails undef will be returned and an error message will
1328be in $@
1329
1330=back
1331
1332=head1 METHODS
1333
1334Unless otherwise stated all methods return either a I<true> or I<false>
1335value, with I<true> meaning that the operation was a success. When a method
1336states that it returns a value, failure will be returned as I<undef> or an
1337empty list.
1338
1339=over 4
1340
1341=item login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
1342
1343Log into the remote FTP server with the given login information. If
1344no arguments are given then the C<Net::FTP> uses the C<Net::Netrc>
1345package to lookup the login information for the connected host.
1346If no information is found then a login of I<anonymous> is used.
1347If no password is given and the login is I<anonymous> then I<anonymous@>
1348will be used for password.
1349
1350If the connection is via a firewall then the C<authorize> method will
1351be called with no arguments.
1352
1353=item authorize ( [AUTH [, RESP]])
1354
1355This is a protocol used by some firewall ftp proxies. It is used
1356to authorise the user to send data out.  If both arguments are not specified
1357then C<authorize> uses C<Net::Netrc> to do a lookup.
1358
1359=item site (ARGS)
1360
1361Send a SITE command to the remote server and wait for a response.
1362
1363Returns most significant digit of the response code.
1364
1365=item ascii
1366
1367Transfer file in ASCII. CRLF translation will be done if required
1368
1369=item binary
1370
1371Transfer file in binary mode. No transformation will be done.
1372
1373B<Hint>: If both server and client machines use the same line ending for
1374text files, then it will be faster to transfer all files in binary mode.
1375
1376=item rename ( OLDNAME, NEWNAME )
1377
1378Rename a file on the remote FTP server from C<OLDNAME> to C<NEWNAME>. This
1379is done by sending the RNFR and RNTO commands.
1380
1381=item delete ( FILENAME )
1382
1383Send a request to the server to delete C<FILENAME>.
1384
1385=item cwd ( [ DIR ] )
1386
1387Attempt to change directory to the directory given in C<$dir>.  If
1388C<$dir> is C<"..">, the FTP C<CDUP> command is used to attempt to
1389move up one directory. If no directory is given then an attempt is made
1390to change the directory to the root directory.
1391
1392=item cdup ()
1393
1394Change directory to the parent of the current directory.
1395
1396=item pwd ()
1397
1398Returns the full pathname of the current directory.
1399
1400=item restart ( WHERE )
1401
1402Set the byte offset at which to begin the next data transfer. Net::FTP simply
1403records this value and uses it when during the next data transfer. For this
1404reason this method will not return an error, but setting it may cause
1405a subsequent data transfer to fail.
1406
1407=item rmdir ( DIR [, RECURSE ])
1408
1409Remove the directory with the name C<DIR>. If C<RECURSE> is I<true> then
1410C<rmdir> will attempt to delete everything inside the directory.
1411
1412=item mkdir ( DIR [, RECURSE ])
1413
1414Create a new directory with the name C<DIR>. If C<RECURSE> is I<true> then
1415C<mkdir> will attempt to create all the directories in the given path.
1416
1417Returns the full pathname to the new directory.
1418
1419=item ls ( [ DIR ] )
1420
1421=item alloc ( SIZE [, RECORD_SIZE] )
1422
1423The alloc command allows you to give the ftp server a hint about the size
1424of the file about to be transfered using the ALLO ftp command. Some storage
1425systems use this to make intelligent decisions about how to store the file.
1426The C<SIZE> argument represents the size of the file in bytes. The
1427C<RECORD_SIZE> argument indicates a mazimum record or page size for files
1428sent with a record or page structure.
1429
1430The size of the file will be determined, and sent to the server
1431automatically for normal files so that this method need only be called if
1432you are transfering data from a socket, named pipe, or other stream not
1433associated with a normal file.
1434
1435Get a directory listing of C<DIR>, or the current directory.
1436
1437In an array context, returns a list of lines returned from the server. In
1438a scalar context, returns a reference to a list.
1439
1440=item dir ( [ DIR ] )
1441
1442Get a directory listing of C<DIR>, or the current directory in long format.
1443
1444In an array context, returns a list of lines returned from the server. In
1445a scalar context, returns a reference to a list.
1446
1447=item get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )
1448
1449Get C<REMOTE_FILE> from the server and store locally. C<LOCAL_FILE> may be
1450a filename or a filehandle. If not specified, the file will be stored in
1451the current directory with the same leafname as the remote file.
1452
1453If C<WHERE> is given then the first C<WHERE> bytes of the file will
1454not be transfered, and the remaining bytes will be appended to
1455the local file if it already exists.
1456
1457Returns C<LOCAL_FILE>, or the generated local file name if C<LOCAL_FILE>
1458is not given. If an error was encountered undef is returned.
1459
1460=item put ( LOCAL_FILE [, REMOTE_FILE ] )
1461
1462Put a file on the remote server. C<LOCAL_FILE> may be a name or a filehandle.
1463If C<LOCAL_FILE> is a filehandle then C<REMOTE_FILE> must be specified. If
1464C<REMOTE_FILE> is not specified then the file will be stored in the current
1465directory with the same leafname as C<LOCAL_FILE>.
1466
1467Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1468is not given.
1469
1470B<NOTE>: If for some reason the transfer does not complete and an error is
1471returned then the contents that had been transfered will not be remove
1472automatically.
1473
1474=item put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
1475
1476Same as put but uses the C<STOU> command.
1477
1478Returns the name of the file on the server.
1479
1480=item append ( LOCAL_FILE [, REMOTE_FILE ] )
1481
1482Same as put but appends to the file on the remote server.
1483
1484Returns C<REMOTE_FILE>, or the generated remote filename if C<REMOTE_FILE>
1485is not given.
1486
1487=item unique_name ()
1488
1489Returns the name of the last file stored on the server using the
1490C<STOU> command.
1491
1492=item mdtm ( FILE )
1493
1494Returns the I<modification time> of the given file
1495
1496=item size ( FILE )
1497
1498Returns the size in bytes for the given file as stored on the remote server.
1499
1500B<NOTE>: The size reported is the size of the stored file on the remote server.
1501If the file is subsequently transfered from the server in ASCII mode
1502and 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
1504may be different.
1505
1506=item supported ( CMD )
1507
1508Returns TRUE if the remote server supports the given command.
1509
1510=item hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] )
1511
1512Called without parameters, or with the first argument false, hash marks
1513are suppressed.  If the first argument is true but not a reference to a
1514file handle glob, then \*STDERR is used.  The second argument is the number
1515of bytes per hash mark printed, and defaults to 1024.  In all cases the
1516return value is a reference to an array of two:  the filehandle glob reference
1517and the bytes per hash mark.
1518
1519=back
1520
1521The following methods can return different results depending on
1522how they are called. If the user explicitly calls either
1523of the C<pasv> or C<port> methods then these methods will
1524return a I<true> or I<false> value. If the user does not
1525call either of these methods then the result will be a
1526reference to a C<Net::FTP::dataconn> based object.
1527
1528=over 4
1529
1530=item nlst ( [ DIR ] )
1531
1532Send an C<NLST> command to the server, with an optional parameter.
1533
1534=item list ( [ DIR ] )
1535
1536Same as C<nlst> but using the C<LIST> command
1537
1538=item retr ( FILE )
1539
1540Begin the retrieval of a file called C<FILE> from the remote server.
1541
1542=item stor ( FILE )
1543
1544Tell the server that you wish to store a file. C<FILE> is the
1545name of the new file that should be created.
1546
1547=item stou ( FILE )
1548
1549Same as C<stor> but using the C<STOU> command. The name of the unique
1550file which was created on the server will be available via the C<unique_name>
1551method after the data connection has been closed.
1552
1553=item appe ( FILE )
1554
1555Tell the server that we want to append some data to the end of a file
1556called C<FILE>. If this file does not exist then create it.
1557
1558=back
1559
1560If for some reason you want to have complete control over the data connection,
1561this includes generating it and calling the C<response> method when required,
1562then the user can use these methods to do so.
1563
1564However calling these methods only affects the use of the methods above that
1565can return a data connection. They have no effect on methods C<get>, C<put>,
1566C<put_unique> and those that do not require data connections.
1567
1568=over 4
1569
1570=item port ( [ PORT ] )
1571
1572Send a C<PORT> command to the server. If C<PORT> is specified then it is sent
1573to the server. If not, then a listen socket is created and the correct information
1574sent to the server.
1575
1576=item pasv ()
1577
1578Tell the server to go into passive mode. Returns the text that represents the
1579port on which the server is listening, this text is in a suitable form to
1580sent to another ftp server using the C<port> method.
1581
1582=back
1583
1584The following methods can be used to transfer files between two remote
1585servers, providing that these two servers can connect directly to each other.
1586
1587=over 4
1588
1589=item pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1590
1591This method will do a file transfer between two remote ftp servers. If
1592C<DEST_FILE> is omitted then the leaf name of C<SRC_FILE> will be used.
1593
1594=item pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
1595
1596Like C<pasv_xfer> but the file is stored on the remote server using
1597the STOU command.
1598
1599=item pasv_wait ( NON_PASV_SERVER )
1600
1601This method can be used to wait for a transfer to complete between a passive
1602server and a non-passive server. The method should be called on the passive
1603server with the C<Net::FTP> object for the non-passive server passed as an
1604argument.
1605
1606=item abort ()
1607
1608Abort the current data transfer.
1609
1610=item quit ()
1611
1612Send the QUIT command to the remote FTP server and close the socket connection.
1613
1614=back
1615
1616=head2 Methods for the adventurous
1617
1618C<Net::FTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
1619be used to send commands to the remote FTP server.
1620
1621=over 4
1622
1623=item quot (CMD [,ARGS])
1624
1625Send a command, that Net::FTP does not directly support, to the remote
1626server and wait for a response.
1627
1628Returns most significant digit of the response code.
1629
1630B<WARNING> This call should only be used on commands that do not require
1631data connections. Misuse of this method can hang the connection.
1632
1633=back
1634
1635=head1 THE dataconn CLASS
1636
1637Some of the methods defined in C<Net::FTP> return an object which will
1638be derived from this class.The dataconn class itself is derived from
1639the C<IO::Socket::INET> class, so any normal IO operations can be performed.
1640However the following methods are defined in the dataconn class and IO should
1641be performed using these.
1642
1643=over 4
1644
1645=item read ( BUFFER, SIZE [, TIMEOUT ] )
1646
1647Read C<SIZE> bytes of data from the server and place it into C<BUFFER>, also
1648performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1649given, the timeout value from the command connection will be used.
1650
1651Returns the number of bytes read before any <CRLF> translation.
1652
1653=item write ( BUFFER, SIZE [, TIMEOUT ] )
1654
1655Write C<SIZE> bytes of data from C<BUFFER> to the server, also
1656performing any <CRLF> translation necessary. C<TIMEOUT> is optional, if not
1657given, the timeout value from the command connection will be used.
1658
1659Returns the number of bytes written before any <CRLF> translation.
1660
1661=item bytes_read ()
1662
1663Returns the number of bytes read so far.
1664
1665=item abort ()
1666
1667Abort the current data transfer.
1668
1669=item close ()
1670
1671Close the data connection and get a response from the FTP server. Returns
1672I<true> if the connection was closed successfully and the first digit of
1673the response from the server was a '2'.
1674
1675=back
1676
1677=head1 UNIMPLEMENTED
1678
1679The following RFC959 commands have not been implemented:
1680
1681=over 4
1682
1683=item B<SMNT>
1684
1685Mount a different file system structure without changing login or
1686accounting information.
1687
1688=item B<HELP>
1689
1690Ask the server for "helpful information" (that's what the RFC says) on
1691the commands it accepts.
1692
1693=item B<MODE>
1694
1695Specifies transfer mode (stream, block or compressed) for file to be
1696transferred.
1697
1698=item B<SYST>
1699
1700Request remote server system identification.
1701
1702=item B<STAT>
1703
1704Request remote server status.
1705
1706=item B<STRU>
1707
1708Specifies file structure for file to be transferred.
1709
1710=item B<REIN>
1711
1712Reinitialize the connection, flushing all I/O and account information.
1713
1714=back
1715
1716=head1 REPORTING BUGS
1717
1718When reporting bugs/problems please include as much information as possible.
1719It may be difficult for me to reproduce the problem as almost every setup
1720is different.
1721
1722A small script which yields the problem will probably be of help. It would
1723also be useful if this script was run with the extra options C<Debug => 1>
1724passed to the constructor, and the output sent with the bug report. If you
1725cannot include a small script then please include a Debug trace from a
1726run of your program which does yield the problem.
1727
1728=head1 AUTHOR
1729
1730Graham Barr <gbarr@pobox.com>
1731
1732=head1 SEE ALSO
1733
1734L<Net::Netrc>
1735L<Net::Cmd>
1736
1737ftp(1), ftpd(8), RFC 959
1738http://www.cis.ohio-state.edu/htbin/rfc/rfc959.html
1739
1740=head1 USE EXAMPLES
1741
1742For an example of the use of Net::FTP see
1743
1744=over 4
1745
1746=item http://www.csh.rit.edu/~adam/Progs/
1747
1748C<autoftp> is a program that can retrieve, send, or list files via
1749the FTP protocol in a non-interactive manner.
1750
1751=back
1752
1753=head1 CREDITS
1754
1755Henry Gabryjelski <henryg@WPI.EDU> - for the suggestion of creating directories
1756recursively.
1757
1758Nathan Torkington <gnat@frii.com> - for some input on the documentation.
1759
1760Roderick Schertler <roderick@gate.net> - for various inputs
1761
1762=head1 COPYRIGHT
1763
1764Copyright (c) 1995-1998 Graham Barr. All rights reserved.
1765This program is free software; you can redistribute it and/or modify it
1766under the same terms as Perl itself.
1767
1768=for html <hr>
1769
1770I<$Id: //depot/libnet/Net/FTP.pm#80 $>
1771
1772=cut
1773