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