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