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(),
455 my ($self, $attr) = @_;
467 my ($caller, %args) = @_;
468 my $caller_is_obj = ref($caller);
469 my $class = $caller_is_obj || $caller;
470 my $self = bless {}, $class;
471 foreach my $attrname ($self->_standard_keys()) {
472 my ($argname) = ($attrname =~ /^_(.*)/);
473 if (exists $args{$argname}) {
474 $self->{$attrname} = $args{$argname};
475 } elsif ($caller_is_obj) {
476 $self->{$attrname} = $caller->{$attrname};
478 $self->{$attrname} = $self->_default_for($attrname);
481 # create server socket
482 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
483 $self->{_server_sock}
484 = IO::Socket::INET->new (LocalHost => $self->{_localAddr},
485 LocalPort => $self->{_localPort},
487 Reuse => $self->{_reuseAddr},
497 my ($self, $synch_callback) = @_;
500 # turn buffering off on STDERR
501 select((select(STDERR), $|=1)[0]);
503 # initialize command table
504 my $command_table = {};
505 foreach (keys %_commands) {
506 my $subname = "_${_}_command";
507 $command_table->{$_} = \&$subname;
518 $SIG{CHLD} = sub { wait };
519 my $server_sock = $self->{_server_sock};
522 while (my $client_addr = accept (my $socket, $server_sock))
524 # turn buffering off on $socket
525 select((select($socket), $|=1)[0]);
527 # find out who connected
528 my ($client_port, $client_ip) = sockaddr_in ($client_addr);
529 my $client_ipnum = inet_ntoa ($client_ip);
531 # print who connected
532 print STDERR "got a connection from: $client_ipnum\n" if $log;
534 # fork off a process to handle this connection.
536 # unless (defined $pid) {
538 # sleep 5; # Back off in case system is overloaded.
542 if (1) { # Child process.
550 print STDERR "Client closed connection abruptly.\n";
555 print STDERR "Connection idle timeout expired. Closing server.\n";
559 #$SIG{CHLD} = 'IGNORE';
562 print STDERR "in child\n" if $log;
565 'paths' => FTPPaths->new($self->{'_input'}),
567 'state' => $_connection_states{NEWCONN},
570 'idle_timeout' => 60, # 1 minute timeout
571 'rootdir' => $self->{_rootDir},
574 print {$conn->{socket}} "220 GNU Wget Testing FTP Server ready.\r\n";
576 # command handling loop
578 print STDERR "waiting for request\n" if $log;
580 last unless defined (my $req = <$socket>);
582 # Remove trailing CRLF.
583 $req =~ s/[\n\r]+$//;
585 print STDERR "received request $req\n" if $log;
588 # See also RFC 2640 section 3.1.
589 unless ($req =~ m/^([A-Z]{3,4})\s?(.*)/i) {
590 # badly formed command
594 # The following strange 'eval' is necessary to work around a
595 # very odd bug in Perl 5.6.0. The following assignment to
596 # $cmd will fail in some cases unless you use $1 in some sort
597 # of an expression beforehand.
601 my ($cmd, $rest) = (uc $1, $2);
603 # Got a command which matches in the table?
604 unless (exists $command_table->{$cmd}) {
605 print {$conn->{socket}} "500 Unrecognized command.\r\n";
609 # Command requires user to be authenticated?
610 unless ($_commands{$cmd} | $conn->{state}) {
611 print {$conn->{socket}} "530 Not logged in.\r\n";
615 # Handle the QUIT command specially.
616 if ($cmd eq "QUIT") {
617 print {$conn->{socket}} "221 Goodbye. Service closing connection.\r\n";
622 &{$command_table->{$cmd}} ($conn, $cmd, $rest);
634 return $self->{_server_sock}->sockport;
640 use POSIX qw(strftime);
643 sub final_component {
662 my @components = split('/', $b);
664 foreach my $c (@components) {
667 } elsif ($c eq '..') {
679 my ($this, @args) = @_;
680 my $class = ref($this) || $this;
683 $self->initialize(@args);
688 my ($self, $urls) = @_;
689 my $paths = {_type => 'd'};
691 # From a path like '/foo/bar/baz.txt', construct $paths such that
692 # $paths->{'foo'}->{'bar'}->{'baz.txt'} is
693 # $urls->{'/foo/bar/baz.txt'}.
694 for my $path (keys %$urls) {
695 my @components = split('/', $path);
698 for my $c (@components) {
699 unless (exists $x->{$c}) {
700 $x->{$c} = {_type => 'd'};
704 %$x = %{$urls->{$path}};
708 $self->{'_paths'} = $paths;
712 my ($self, $path, $node) = @_;
713 $node = $self->{'_paths'} unless $node;
714 my @components = split('/', $path);
715 shift @components if @components && $components[0] eq '';
717 for my $c (@components) {
718 if ($node->{'_type'} eq 'd') {
728 my ($self, $path) = @_;
729 return $self->exists($path, 'd');
733 # type is optional, in which case we don't check it.
734 my ($self, $path, $type) = @_;
735 my $paths = $self->{'_paths'};
737 die "Invalid path $path (not absolute).\n" unless $path =~ m.^/.;
738 my $info = $self->get_info($path);
739 return 0 unless defined($info);
740 return $info->{'_type'} eq $type if defined($type);
744 sub _format_for_list {
745 my ($self, $name, $info) = @_;
747 # XXX: mode should be specifyable as part of the node info.
749 if ($info->{'_type'} eq 'd') {
750 $mode_str = 'dr-xr-xr-x';
752 $mode_str = '-r--r--r--';
756 if ($info->{'_type'} eq 'f') {
757 $size = length $info->{'content'};
759 my $date = strftime ("%b %e %H:%M", localtime);
760 return "$mode_str 1 0 0 $size $date $name";
764 my ($self, $path) = @_;
765 my $info = $self->get_info($path);
766 return undef unless defined $info;
769 if ($info->{'_type'} eq 'd') {
770 for my $item (keys %$info) {
771 next if $item =~ /^_/;
772 push @$list, $self->_format_for_list($item, $info->{$item});
775 push @$list, $self->_format_for_list(final_component($path), $info);