1 # Part of this code was borrowed from Richard Jones's Net::FTPServer
2 # http://www.annexia.org/freeware/netftpserver
13 use POSIX qw(strftime);
21 my %_connection_states = (
28 # subset of FTP commands supported by these server and the respective
29 # connection states in which they are allowed
31 # Standard commands from RFC 959.
32 'CWD' => $_connection_states{LOGGEDIN} |
33 $_connection_states{TWOSOCKS},
34 # 'EPRT' => $_connection_states{LOGGEDIN},
35 # 'EPSV' => $_connection_states{LOGGEDIN},
36 'LIST' => $_connection_states{TWOSOCKS},
37 # 'LPRT' => $_connection_states{LOGGEDIN},
38 # 'LPSV' => $_connection_states{LOGGEDIN},
39 'PASS' => $_connection_states{WAIT4PWD},
40 'PASV' => $_connection_states{LOGGEDIN},
41 'PORT' => $_connection_states{LOGGEDIN},
42 'PWD' => $_connection_states{LOGGEDIN} |
43 $_connection_states{TWOSOCKS},
44 'QUIT' => $_connection_states{LOGGEDIN} |
45 $_connection_states{TWOSOCKS},
46 'REST' => $_connection_states{TWOSOCKS},
47 'RETR' => $_connection_states{TWOSOCKS},
48 'SYST' => $_connection_states{LOGGEDIN},
49 'TYPE' => $_connection_states{LOGGEDIN} |
50 $_connection_states{TWOSOCKS},
51 'USER' => $_connection_states{NEWCONN},
52 # From ftpexts Internet Draft.
53 'SIZE' => $_connection_states{LOGGEDIN} |
54 $_connection_states{TWOSOCKS},
59 # COMMAND-HANDLING ROUTINES
63 my ($conn, $cmd, $path) = @_;
64 my $paths = $conn->{'paths'};
67 my $new_path = FTPPaths::path_merge($conn->{'dir'}, $path);
69 # Split the path into its component parts and process each separately.
70 if (! $paths->dir_exists($new_path)) {
71 print {$conn->{socket}} "550 Directory not found.\r\n";
75 $conn->{'dir'} = $new_path;
76 print {$conn->{socket}} "200 directory changed to $new_path.\r\n";
81 my ($conn, $cmd, $path) = @_;
82 my $paths = $conn->{'paths'};
84 my $ReturnEmptyList = ( $paths->GetBehavior('list_empty_if_list_a') &&
86 my $SkipHiddenFiles = ( $paths->GetBehavior('list_no_hidden_if_list') &&
89 if ($paths->GetBehavior('list_fails_if_list_a') && $path eq '-a')
91 print {$conn->{socket}} "500 Unknown command\r\n";
96 if (!$paths->GetBehavior('list_dont_clean_path'))
98 # This is something of a hack. Some clients expect a Unix server
99 # to respond to flags on the 'ls command line'. Remove these flags
100 # and ignore them. This is particularly an issue with ncftp 2.4.3.
101 $path =~ s/^-[a-zA-Z0-9]+\s?//;
104 my $dir = $conn->{'dir'};
106 print STDERR "_LIST_command - dir is: $dir\n";
108 # Parse the first elements of the path until we find the appropriate
113 if (!$ReturnEmptyList)
115 $dir = FTPPaths::path_merge($dir, $path);
116 $listing = $paths->get_list($dir,$SkipHiddenFiles);
118 print {$conn->{socket}} "550 File or directory not found.\r\n";
123 print STDERR "_LIST_command - dir is: $dir\n" if $log;
125 print {$conn->{socket}} "150 Opening data connection for file listing.\r\n";
127 # Open a path back to the client.
128 my $sock = __open_data_connection ($conn);
130 print {$conn->{socket}} "425 Can't open data connection.\r\n";
134 if (!$ReturnEmptyList)
136 for my $item (@$listing) {
137 print $sock "$item\r\n";
141 unless ($sock->close) {
142 print {$conn->{socket}} "550 Error closing data connection: $!\r\n";
146 print {$conn->{socket}} "226 Listing complete. Data connection has been closed.\r\n";
151 my ($conn, $cmd, $pass) = @_;
153 # TODO: implement authentication?
155 print STDERR "switching to LOGGEDIN state\n" if $log;
156 $conn->{state} = $_connection_states{LOGGEDIN};
158 if ($conn->{username} eq "anonymous") {
159 print {$conn->{socket}} "202 Anonymous user access is always granted.\r\n";
161 print {$conn->{socket}} "230 Authentication not implemented yet, access is always granted.\r\n";
167 my ($conn, $cmd, $rest) = @_;
169 # Open a listening socket - but don't actually accept on it yet.
170 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
171 my $sock = IO::Socket::INET->new (LocalHost => '127.0.0.1',
176 Type => SOCK_STREAM);
179 # Return a code 550 here, even though this is not in the RFC. XXX
180 print {$conn->{socket}} "550 Can't open a listening socket.\r\n";
184 $conn->{passive} = 1;
185 $conn->{passive_socket} = $sock;
187 # Get our port number.
188 my $sockport = $sock->sockport;
190 # Split the port number into high and low components.
191 my $p1 = int ($sockport / 256);
192 my $p2 = $sockport % 256;
194 $conn->{state} = $_connection_states{TWOSOCKS};
196 # We only accept connections from localhost.
197 print {$conn->{socket}} "227 Entering Passive Mode (127,0,0,1,$p1,$p2)\r\n";
202 my ($conn, $cmd, $rest) = @_;
204 # The arguments to PORT are a1,a2,a3,a4,p1,p2 where a1 is the
205 # most significant part of the address (eg. 127,0,0,1) and
206 # p1 is the most significant part of the port.
207 unless ($rest =~ /^\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})/) {
208 print {$conn->{socket}} "501 Syntax error in PORT command.\r\n";
212 # Check host address.
213 unless ($1 > 0 && $1 < 224 &&
214 $2 >= 0 && $2 < 256 &&
215 $3 >= 0 && $3 < 256 &&
216 $4 >= 0 && $4 < 256) {
217 print {$conn->{socket}} "501 Invalid host address.\r\n";
221 # Construct host address and port number.
222 my $peeraddrstring = "$1.$2.$3.$4";
223 my $peerport = $5 * 256 + $6;
226 unless ($peerport > 0 && $peerport < 65536) {
227 print {$conn->{socket}} "501 Invalid port number.\r\n";
230 $conn->{peeraddrstring} = $peeraddrstring;
231 $conn->{peeraddr} = inet_aton ($peeraddrstring);
232 $conn->{peerport} = $peerport;
233 $conn->{passive} = 0;
235 $conn->{state} = $_connection_states{TWOSOCKS};
237 print {$conn->{socket}} "200 PORT command OK.\r\n";
242 my ($conn, $cmd, $rest) = @_;
244 # See RFC 959 Appendix II and draft-ietf-ftpext-mlst-11.txt section 6.2.1.
245 my $pathname = $conn->{dir};
246 $pathname =~ s,/+$,, unless $pathname eq "/";
247 $pathname =~ tr,/,/,s;
249 print {$conn->{socket}} "257 \"$pathname\"\r\n";
254 my ($conn, $cmd, $restart_from) = @_;
256 unless ($restart_from =~ /^([1-9][0-9]*|0)$/) {
257 print {$conn->{socket}} "501 REST command needs a numeric argument.\r\n";
261 $conn->{restart} = $1;
263 print {$conn->{socket}} "350 Restarting next transfer at $1.\r\n";
268 my ($conn, $cmd, $path) = @_;
270 $path = FTPPaths::path_merge($conn->{dir}, $path);
271 my $info = $conn->{'paths'}->get_info($path);
273 unless ($info->{'_type'} eq 'f') {
274 print {$conn->{socket}} "550 File not found.\r\n";
278 print {$conn->{socket}} "150 Opening " .
279 ($conn->{type} eq 'A' ? "ASCII mode" : "BINARY mode") .
280 " data connection.\r\n";
282 # Open a path back to the client.
283 my $sock = __open_data_connection ($conn);
286 print {$conn->{socket}} "425 Can't open data connection.\r\n";
290 my $content = $info->{'content'};
292 # Restart the connection from previous point?
293 if ($conn->{restart}) {
294 $content = substr($content, $conn->{restart});
295 $conn->{restart} = 0;
298 # What mode are we sending this file in?
299 unless ($conn->{type} eq 'A') # Binary type.
301 my ($r, $buffer, $n, $w);
305 while ($buffer = substr($content, 0, 65536))
309 # Restart alarm clock timer.
310 alarm $conn->{idle_timeout};
312 for ($n = 0; $n < $r; )
314 $w = syswrite ($sock, $buffer, $r - $n, $n);
316 # Cleanup and exit if there was an error.
317 unless (defined $w) {
319 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
326 # Transfer aborted by client?
330 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
335 # Cleanup and exit if there was an error.
336 unless (defined $r) {
338 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
341 } else { # ASCII type.
343 my @lines = split /\r\n?|\n/, $content;
345 # Remove any native line endings.
348 # Restart alarm clock timer.
349 alarm $conn->{idle_timeout};
351 # Write the line with telnet-format line endings.
352 print $sock "$_\r\n";
354 # Transfer aborted by client?
358 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
364 unless (close ($sock)) {
365 print {$conn->{socket}} "550 File retrieval error: $!.\r\n";
369 print {$conn->{socket}} "226 File retrieval complete. Data connection has been closed.\r\n";
374 my ($conn, $cmd, $path) = @_;
376 $path = FTPPaths::path_merge($conn->{dir}, $path);
377 my $info = $conn->{'paths'}->get_info($path);
379 print {$conn->{socket}} "550 File or directory not found.\r\n";
383 if ($info->{'_type'} eq 'd') {
384 print {$conn->{socket}} "550 SIZE command is not supported on directories.\r\n";
388 my $size = length $info->{'content'};
390 print {$conn->{socket}} "213 $size\r\n";
395 my ($conn, $cmd, $dummy) = @_;
397 if ($conn->{'paths'}->GetBehavior('syst_response'))
399 print {$conn->{socket}} $conn->{'paths'}->GetBehavior('syst_response') . "\r\n";
403 print {$conn->{socket}} "215 UNIX Type: L8\r\n";
409 my ($conn, $cmd, $type) = @_;
411 # See RFC 959 section 5.3.2.
412 if ($type =~ /^([AI])$/i) {
414 } elsif ($type =~ /^([AI])\sN$/i) {
416 } elsif ($type =~ /^L\s8$/i) {
417 $conn->{type} = 'L8';
419 print {$conn->{socket}} "504 This server does not support TYPE $type.\r\n";
423 print {$conn->{socket}} "200 TYPE changed to $type.\r\n";
428 my ($conn, $cmd, $username) = @_;
430 print STDERR "username: $username\n" if $log;
431 $conn->{username} = $username;
433 print STDERR "switching to WAIT4PWD state\n" if $log;
434 $conn->{state} = $_connection_states{WAIT4PWD};
436 if ($conn->{username} eq "anonymous") {
437 print {$conn->{socket}} "230 Anonymous user access granted.\r\n";
439 print {$conn->{socket}} "331 Password required.\r\n";
446 sub __open_data_connection
452 if ($conn->{passive}) {
453 # Passive mode - wait for a connection from the client.
454 accept ($sock, $conn->{passive_socket}) or return undef;
456 # Active mode - connect back to the client.
457 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
458 $sock = IO::Socket::INET->new (LocalAddr => '127.0.0.1',
459 PeerAddr => $conn->{peeraddrstring},
460 PeerPort => $conn->{peerport},
462 Type => SOCK_STREAM) or return undef;
469 ###########################################################################
471 ###########################################################################
474 my %_attr_data = ( # DEFAULT
476 _localAddr => 'localhost',
479 _rootDir => Cwd::getcwd(),
480 _server_behavior => {},
485 my ($self, $attr) = @_;
497 my ($caller, %args) = @_;
498 my $caller_is_obj = ref($caller);
499 my $class = $caller_is_obj || $caller;
500 my $self = bless {}, $class;
501 foreach my $attrname ($self->_standard_keys()) {
502 my ($argname) = ($attrname =~ /^_(.*)/);
503 if (exists $args{$argname}) {
504 $self->{$attrname} = $args{$argname};
505 } elsif ($caller_is_obj) {
506 $self->{$attrname} = $caller->{$attrname};
508 $self->{$attrname} = $self->_default_for($attrname);
511 # create server socket
512 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
513 $self->{_server_sock}
514 = IO::Socket::INET->new (LocalHost => $self->{_localAddr},
515 LocalPort => $self->{_localPort},
517 Reuse => $self->{_reuseAddr},
522 foreach my $file (keys %{$self->{_input}}) {
523 my $ref = \$self->{_input}{$file}{content};
524 $$ref =~ s/{{port}}/$self->sockport/eg;
533 my ($self, $synch_callback) = @_;
536 # turn buffering off on STDERR
537 select((select(STDERR), $|=1)[0]);
539 # initialize command table
540 my $command_table = {};
541 foreach (keys %_commands) {
542 my $subname = "_${_}_command";
543 $command_table->{$_} = \&$subname;
554 $SIG{CHLD} = sub { wait };
555 my $server_sock = $self->{_server_sock};
558 while (my $client_addr = accept (my $socket, $server_sock))
560 # turn buffering off on $socket
561 select((select($socket), $|=1)[0]);
563 # find out who connected
564 my ($client_port, $client_ip) = sockaddr_in ($client_addr);
565 my $client_ipnum = inet_ntoa ($client_ip);
567 # print who connected
568 print STDERR "got a connection from: $client_ipnum\n" if $log;
570 # fork off a process to handle this connection.
572 # unless (defined $pid) {
574 # sleep 5; # Back off in case system is overloaded.
578 if (1) { # Child process.
586 print STDERR "Client closed connection abruptly.\n";
591 print STDERR "Connection idle timeout expired. Closing server.\n";
595 #$SIG{CHLD} = 'IGNORE';
598 print STDERR "in child\n" if $log;
601 'paths' => FTPPaths->new($self->{'_input'},
602 $self->{'_server_behavior'}),
604 'state' => $_connection_states{NEWCONN},
607 'idle_timeout' => 60, # 1 minute timeout
608 'rootdir' => $self->{_rootDir},
611 print {$conn->{socket}} "220 GNU Wget Testing FTP Server ready.\r\n";
613 # command handling loop
615 print STDERR "waiting for request\n" if $log;
617 last unless defined (my $req = <$socket>);
619 # Remove trailing CRLF.
620 $req =~ s/[\n\r]+$//;
622 print STDERR "received request $req\n" if $log;
625 # See also RFC 2640 section 3.1.
626 unless ($req =~ m/^([A-Z]{3,4})\s?(.*)/i) {
627 # badly formed command
631 # The following strange 'eval' is necessary to work around a
632 # very odd bug in Perl 5.6.0. The following assignment to
633 # $cmd will fail in some cases unless you use $1 in some sort
634 # of an expression beforehand.
638 my ($cmd, $rest) = (uc $1, $2);
640 # Got a command which matches in the table?
641 unless (exists $command_table->{$cmd}) {
642 print {$conn->{socket}} "500 Unrecognized command.\r\n";
646 # Command requires user to be authenticated?
647 unless ($_commands{$cmd} | $conn->{state}) {
648 print {$conn->{socket}} "530 Not logged in.\r\n";
652 # Handle the QUIT command specially.
653 if ($cmd eq "QUIT") {
654 print {$conn->{socket}} "221 Goodbye. Service closing connection.\r\n";
658 if (defined ($self->{_server_behavior}{fail_on_pasv})
660 undef $self->{_server_behavior}{fail_on_pasv};
666 &{$command_table->{$cmd}} ($conn, $cmd, $rest);
678 return $self->{_server_sock}->sockport;
684 use POSIX qw(strftime);
687 sub final_component {
706 my @components = split('/', $b);
708 foreach my $c (@components) {
711 } elsif ($c eq '..') {
723 my ($this, @args) = @_;
724 my $class = ref($this) || $this;
727 $self->initialize(@args);
732 my ($self, $urls, $behavior) = @_;
733 my $paths = {_type => 'd'};
735 # From a path like '/foo/bar/baz.txt', construct $paths such that
736 # $paths->{'foo'}->{'bar'}->{'baz.txt'} is
737 # $urls->{'/foo/bar/baz.txt'}.
738 for my $path (keys %$urls) {
739 my @components = split('/', $path);
742 for my $c (@components) {
743 unless (exists $x->{$c}) {
744 $x->{$c} = {_type => 'd'};
748 %$x = %{$urls->{$path}};
752 $self->{'_paths'} = $paths;
753 $self->{'_behavior'} = $behavior;
757 my ($self, $path, $node) = @_;
758 $node = $self->{'_paths'} unless $node;
759 my @components = split('/', $path);
760 shift @components if @components && $components[0] eq '';
762 for my $c (@components) {
763 if ($node->{'_type'} eq 'd') {
773 my ($self, $path) = @_;
774 return $self->exists($path, 'd');
778 # type is optional, in which case we don't check it.
779 my ($self, $path, $type) = @_;
780 my $paths = $self->{'_paths'};
782 die "Invalid path $path (not absolute).\n" unless $path =~ m.^/.;
783 my $info = $self->get_info($path);
784 return 0 unless defined($info);
785 return $info->{'_type'} eq $type if defined($type);
789 sub _format_for_list {
790 my ($self, $name, $info) = @_;
792 # XXX: mode should be specifyable as part of the node info.
794 if ($info->{'_type'} eq 'd') {
795 $mode_str = 'dr-xr-xr-x';
797 $mode_str = '-r--r--r--';
801 if ($info->{'_type'} eq 'f') {
802 $size = length $info->{'content'};
803 if ($self->{'_behavior'}{'bad_list'}) {
807 my $date = strftime ("%b %e %H:%M", localtime);
808 return "$mode_str 1 0 0 $size $date $name";
812 my ($self, $path, $no_hidden) = @_;
813 my $info = $self->get_info($path);
814 return undef unless defined $info;
817 if ($info->{'_type'} eq 'd') {
818 for my $item (keys %$info) {
819 next if $item =~ /^_/;
820 # 2013-10-17 Andrea Urbani (matfanjol)
821 # I skip the hidden files if requested
823 (defined($info->{$item}->{'attr'})) &&
824 (index($info->{$item}->{'attr'}, "H")>=0))
826 # This is an hidden file and I don't want to see it!
827 print STDERR "get_list: Skipped hidden file [$item]\n";
831 push @$list, $self->_format_for_list($item, $info->{$item});
835 push @$list, $self->_format_for_list(final_component($path), $info);
841 # 2013-10-17 Andrea Urbani (matfanjol)
842 # It returns the behavior of the given name.
843 # In this file I handle also the following behaviors:
844 # list_dont_clean_path : if defined, the command
845 # $path =~ s/^-[a-zA-Z0-9]+\s?//;
846 # is not runt and the given path
847 # remains the original one
848 # list_empty_if_list_a : if defined, "LIST -a" returns an
850 # list_fails_if_list_a : if defined, "LIST -a" returns an
852 # list_no_hidden_if_list: if defined, "LIST" doesn't return
854 # To define an hidden file add
857 # syst_response : if defined, its content is printed
858 # out as SYST response
860 my ($self, $name) = @_;
861 return $self->{'_behavior'}{$name};