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 # This is something of a hack. Some clients expect a Unix server
85 # to respond to flags on the 'ls command line'. Remove these flags
86 # and ignore them. This is particularly an issue with ncftp 2.4.3.
87 $path =~ s/^-[a-zA-Z0-9]+\s?//;
89 my $dir = $conn->{'dir'};
91 print STDERR "_LIST_command - dir is: $dir\n";
93 # Parse the first elements of the path until we find the appropriate
97 $dir = FTPPaths::path_merge($dir, $path);
98 my $listing = $paths->get_list($dir);
100 print {$conn->{socket}} "550 File or directory not found.\r\n";
104 print STDERR "_LIST_command - dir is: $dir\n" if $log;
106 print {$conn->{socket}} "150 Opening data connection for file listing.\r\n";
108 # Open a path back to the client.
109 my $sock = __open_data_connection ($conn);
111 print {$conn->{socket}} "425 Can't open data connection.\r\n";
115 for my $item (@$listing) {
116 print $sock "$item\r\n";
119 unless ($sock->close) {
120 print {$conn->{socket}} "550 Error closing data connection: $!\r\n";
124 print {$conn->{socket}} "226 Listing complete. Data connection has been closed.\r\n";
129 my ($conn, $cmd, $pass) = @_;
131 # TODO: implement authentication?
133 print STDERR "switching to LOGGEDIN state\n" if $log;
134 $conn->{state} = $_connection_states{LOGGEDIN};
136 if ($conn->{username} eq "anonymous") {
137 print {$conn->{socket}} "202 Anonymous user access is always granted.\r\n";
139 print {$conn->{socket}} "230 Authentication not implemented yet, access is always granted.\r\n";
145 my ($conn, $cmd, $rest) = @_;
147 # Open a listening socket - but don't actually accept on it yet.
148 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
149 my $sock = IO::Socket::INET->new (LocalHost => '127.0.0.1',
154 Type => SOCK_STREAM);
157 # Return a code 550 here, even though this is not in the RFC. XXX
158 print {$conn->{socket}} "550 Can't open a listening socket.\r\n";
162 $conn->{passive} = 1;
163 $conn->{passive_socket} = $sock;
165 # Get our port number.
166 my $sockport = $sock->sockport;
168 # Split the port number into high and low components.
169 my $p1 = int ($sockport / 256);
170 my $p2 = $sockport % 256;
172 $conn->{state} = $_connection_states{TWOSOCKS};
174 # We only accept connections from localhost.
175 print {$conn->{socket}} "227 Entering Passive Mode (127,0,0,1,$p1,$p2)\r\n";
180 my ($conn, $cmd, $rest) = @_;
182 # The arguments to PORT are a1,a2,a3,a4,p1,p2 where a1 is the
183 # most significant part of the address (eg. 127,0,0,1) and
184 # p1 is the most significant part of the port.
185 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})/) {
186 print {$conn->{socket}} "501 Syntax error in PORT command.\r\n";
190 # Check host address.
191 unless ($1 > 0 && $1 < 224 &&
192 $2 >= 0 && $2 < 256 &&
193 $3 >= 0 && $3 < 256 &&
194 $4 >= 0 && $4 < 256) {
195 print {$conn->{socket}} "501 Invalid host address.\r\n";
199 # Construct host address and port number.
200 my $peeraddrstring = "$1.$2.$3.$4";
201 my $peerport = $5 * 256 + $6;
204 unless ($peerport > 0 && $peerport < 65536) {
205 print {$conn->{socket}} "501 Invalid port number.\r\n";
208 $conn->{peeraddrstring} = $peeraddrstring;
209 $conn->{peeraddr} = inet_aton ($peeraddrstring);
210 $conn->{peerport} = $peerport;
211 $conn->{passive} = 0;
213 $conn->{state} = $_connection_states{TWOSOCKS};
215 print {$conn->{socket}} "200 PORT command OK.\r\n";
220 my ($conn, $cmd, $rest) = @_;
222 # See RFC 959 Appendix II and draft-ietf-ftpext-mlst-11.txt section 6.2.1.
223 my $pathname = $conn->{dir};
224 $pathname =~ s,/+$,, unless $pathname eq "/";
225 $pathname =~ tr,/,/,s;
227 print {$conn->{socket}} "257 \"$pathname\"\r\n";
232 my ($conn, $cmd, $restart_from) = @_;
234 unless ($restart_from =~ /^([1-9][0-9]*|0)$/) {
235 print {$conn->{socket}} "501 REST command needs a numeric argument.\r\n";
239 $conn->{restart} = $1;
241 print {$conn->{socket}} "350 Restarting next transfer at $1.\r\n";
246 my ($conn, $cmd, $path) = @_;
248 $path = FTPPaths::path_merge($conn->{dir}, $path);
249 my $info = $conn->{'paths'}->get_info($path);
251 unless ($info->{'_type'} eq 'f') {
252 print {$conn->{socket}} "550 File not found.\r\n";
256 print {$conn->{socket}} "150 Opening " .
257 ($conn->{type} eq 'A' ? "ASCII mode" : "BINARY mode") .
258 " data connection.\r\n";
260 # Open a path back to the client.
261 my $sock = __open_data_connection ($conn);
264 print {$conn->{socket}} "425 Can't open data connection.\r\n";
268 my $content = $info->{'content'};
270 # Restart the connection from previous point?
271 if ($conn->{restart}) {
272 $content = substr($content, $conn->{restart});
273 $conn->{restart} = 0;
276 # What mode are we sending this file in?
277 unless ($conn->{type} eq 'A') # Binary type.
279 my ($r, $buffer, $n, $w);
283 while ($buffer = substr($content, 0, 65536))
287 # Restart alarm clock timer.
288 alarm $conn->{idle_timeout};
290 for ($n = 0; $n < $r; )
292 $w = syswrite ($sock, $buffer, $r - $n, $n);
294 # Cleanup and exit if there was an error.
295 unless (defined $w) {
297 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
304 # Transfer aborted by client?
308 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
313 # Cleanup and exit if there was an error.
314 unless (defined $r) {
316 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
319 } else { # ASCII type.
321 my @lines = split /\r\n?|\n/, $content;
323 # Remove any native line endings.
326 # Restart alarm clock timer.
327 alarm $conn->{idle_timeout};
329 # Write the line with telnet-format line endings.
330 print $sock "$_\r\n";
332 # Transfer aborted by client?
336 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
342 unless (close ($sock)) {
343 print {$conn->{socket}} "550 File retrieval error: $!.\r\n";
347 print {$conn->{socket}} "226 File retrieval complete. Data connection has been closed.\r\n";
352 my ($conn, $cmd, $path) = @_;
354 $path = FTPPaths::path_merge($conn->{dir}, $path);
355 my $info = $conn->{'paths'}->get_info($path);
357 print {$conn->{socket}} "550 File or directory not found.\r\n";
361 if ($info->{'_type'} eq 'd') {
362 print {$conn->{socket}} "550 SIZE command is not supported on directories.\r\n";
366 my $size = length $info->{'content'};
368 print {$conn->{socket}} "213 $size\r\n";
373 my ($conn, $cmd, $dummy) = @_;
375 print {$conn->{socket}} "215 UNIX Type: L8\r\n";
380 my ($conn, $cmd, $type) = @_;
382 # See RFC 959 section 5.3.2.
383 if ($type =~ /^([AI])$/i) {
385 } elsif ($type =~ /^([AI])\sN$/i) {
387 } elsif ($type =~ /^L\s8$/i) {
388 $conn->{type} = 'L8';
390 print {$conn->{socket}} "504 This server does not support TYPE $type.\r\n";
394 print {$conn->{socket}} "200 TYPE changed to $type.\r\n";
399 my ($conn, $cmd, $username) = @_;
401 print STDERR "username: $username\n" if $log;
402 $conn->{username} = $username;
404 print STDERR "switching to WAIT4PWD state\n" if $log;
405 $conn->{state} = $_connection_states{WAIT4PWD};
407 if ($conn->{username} eq "anonymous") {
408 print {$conn->{socket}} "230 Anonymous user access granted.\r\n";
410 print {$conn->{socket}} "331 Password required.\r\n";
417 sub __open_data_connection
423 if ($conn->{passive}) {
424 # Passive mode - wait for a connection from the client.
425 accept ($sock, $conn->{passive_socket}) or return undef;
427 # Active mode - connect back to the client.
428 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
429 $sock = IO::Socket::INET->new (LocalAddr => '127.0.0.1',
430 PeerAddr => $conn->{peeraddrstring},
431 PeerPort => $conn->{peerport},
433 Type => SOCK_STREAM) or return undef;
440 ###########################################################################
442 ###########################################################################
445 my %_attr_data = ( # DEFAULT
447 _localAddr => 'localhost',
450 _rootDir => Cwd::getcwd(),
451 _server_behavior => {},
456 my ($self, $attr) = @_;
468 my ($caller, %args) = @_;
469 my $caller_is_obj = ref($caller);
470 my $class = $caller_is_obj || $caller;
471 my $self = bless {}, $class;
472 foreach my $attrname ($self->_standard_keys()) {
473 my ($argname) = ($attrname =~ /^_(.*)/);
474 if (exists $args{$argname}) {
475 $self->{$attrname} = $args{$argname};
476 } elsif ($caller_is_obj) {
477 $self->{$attrname} = $caller->{$attrname};
479 $self->{$attrname} = $self->_default_for($attrname);
482 # create server socket
483 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
484 $self->{_server_sock}
485 = IO::Socket::INET->new (LocalHost => $self->{_localAddr},
486 LocalPort => $self->{_localPort},
488 Reuse => $self->{_reuseAddr},
493 foreach my $file (keys %{$self->{_input}}) {
494 my $ref = \$self->{_input}{$file}{content};
495 $$ref =~ s/{{port}}/$self->sockport/eg;
504 my ($self, $synch_callback) = @_;
507 # turn buffering off on STDERR
508 select((select(STDERR), $|=1)[0]);
510 # initialize command table
511 my $command_table = {};
512 foreach (keys %_commands) {
513 my $subname = "_${_}_command";
514 $command_table->{$_} = \&$subname;
525 $SIG{CHLD} = sub { wait };
526 my $server_sock = $self->{_server_sock};
529 while (my $client_addr = accept (my $socket, $server_sock))
531 # turn buffering off on $socket
532 select((select($socket), $|=1)[0]);
534 # find out who connected
535 my ($client_port, $client_ip) = sockaddr_in ($client_addr);
536 my $client_ipnum = inet_ntoa ($client_ip);
538 # print who connected
539 print STDERR "got a connection from: $client_ipnum\n" if $log;
541 # fork off a process to handle this connection.
543 # unless (defined $pid) {
545 # sleep 5; # Back off in case system is overloaded.
549 if (1) { # Child process.
557 print STDERR "Client closed connection abruptly.\n";
562 print STDERR "Connection idle timeout expired. Closing server.\n";
566 #$SIG{CHLD} = 'IGNORE';
569 print STDERR "in child\n" if $log;
572 'paths' => FTPPaths->new($self->{'_input'},
573 $self->{'_server_behavior'}),
575 'state' => $_connection_states{NEWCONN},
578 'idle_timeout' => 60, # 1 minute timeout
579 'rootdir' => $self->{_rootDir},
582 print {$conn->{socket}} "220 GNU Wget Testing FTP Server ready.\r\n";
584 # command handling loop
586 print STDERR "waiting for request\n" if $log;
588 last unless defined (my $req = <$socket>);
590 # Remove trailing CRLF.
591 $req =~ s/[\n\r]+$//;
593 print STDERR "received request $req\n" if $log;
596 # See also RFC 2640 section 3.1.
597 unless ($req =~ m/^([A-Z]{3,4})\s?(.*)/i) {
598 # badly formed command
602 # The following strange 'eval' is necessary to work around a
603 # very odd bug in Perl 5.6.0. The following assignment to
604 # $cmd will fail in some cases unless you use $1 in some sort
605 # of an expression beforehand.
609 my ($cmd, $rest) = (uc $1, $2);
611 # Got a command which matches in the table?
612 unless (exists $command_table->{$cmd}) {
613 print {$conn->{socket}} "500 Unrecognized command.\r\n";
617 # Command requires user to be authenticated?
618 unless ($_commands{$cmd} | $conn->{state}) {
619 print {$conn->{socket}} "530 Not logged in.\r\n";
623 # Handle the QUIT command specially.
624 if ($cmd eq "QUIT") {
625 print {$conn->{socket}} "221 Goodbye. Service closing connection.\r\n";
629 if (defined ($self->{_server_behavior}{fail_on_pasv})
631 undef $self->{_server_behavior}{fail_on_pasv};
637 &{$command_table->{$cmd}} ($conn, $cmd, $rest);
649 return $self->{_server_sock}->sockport;
655 use POSIX qw(strftime);
658 sub final_component {
677 my @components = split('/', $b);
679 foreach my $c (@components) {
682 } elsif ($c eq '..') {
694 my ($this, @args) = @_;
695 my $class = ref($this) || $this;
698 $self->initialize(@args);
703 my ($self, $urls, $behavior) = @_;
704 my $paths = {_type => 'd'};
706 # From a path like '/foo/bar/baz.txt', construct $paths such that
707 # $paths->{'foo'}->{'bar'}->{'baz.txt'} is
708 # $urls->{'/foo/bar/baz.txt'}.
709 for my $path (keys %$urls) {
710 my @components = split('/', $path);
713 for my $c (@components) {
714 unless (exists $x->{$c}) {
715 $x->{$c} = {_type => 'd'};
719 %$x = %{$urls->{$path}};
723 $self->{'_paths'} = $paths;
724 $self->{'_behavior'} = $behavior;
728 my ($self, $path, $node) = @_;
729 $node = $self->{'_paths'} unless $node;
730 my @components = split('/', $path);
731 shift @components if @components && $components[0] eq '';
733 for my $c (@components) {
734 if ($node->{'_type'} eq 'd') {
744 my ($self, $path) = @_;
745 return $self->exists($path, 'd');
749 # type is optional, in which case we don't check it.
750 my ($self, $path, $type) = @_;
751 my $paths = $self->{'_paths'};
753 die "Invalid path $path (not absolute).\n" unless $path =~ m.^/.;
754 my $info = $self->get_info($path);
755 return 0 unless defined($info);
756 return $info->{'_type'} eq $type if defined($type);
760 sub _format_for_list {
761 my ($self, $name, $info) = @_;
763 # XXX: mode should be specifyable as part of the node info.
765 if ($info->{'_type'} eq 'd') {
766 $mode_str = 'dr-xr-xr-x';
768 $mode_str = '-r--r--r--';
772 if ($info->{'_type'} eq 'f') {
773 $size = length $info->{'content'};
774 if ($self->{'_behavior'}{'bad_list'}) {
778 my $date = strftime ("%b %e %H:%M", localtime);
779 return "$mode_str 1 0 0 $size $date $name";
783 my ($self, $path) = @_;
784 my $info = $self->get_info($path);
785 return undef unless defined $info;
788 if ($info->{'_type'} eq 'd') {
789 for my $item (keys %$info) {
790 next if $item =~ /^_/;
791 push @$list, $self->_format_for_list($item, $info->{$item});
794 push @$list, $self->_format_for_list(final_component($path), $info);