3 # Part of this code was borrowed from Richard Jones's Net::FTPServer
4 # http://www.annexia.org/freeware/netftpserver
14 use POSIX qw(strftime);
22 my %_connection_states = (
29 # subset of FTP commands supported by these server and the respective
30 # connection states in which they are allowed
32 # Standard commands from RFC 959.
33 'CWD' => $_connection_states{LOGGEDIN} |
34 $_connection_states{TWOSOCKS},
35 # 'EPRT' => $_connection_states{LOGGEDIN},
36 # 'EPSV' => $_connection_states{LOGGEDIN},
37 'LIST' => $_connection_states{TWOSOCKS},
38 # 'LPRT' => $_connection_states{LOGGEDIN},
39 # 'LPSV' => $_connection_states{LOGGEDIN},
40 'PASS' => $_connection_states{WAIT4PWD},
41 'PASV' => $_connection_states{LOGGEDIN},
42 'PORT' => $_connection_states{LOGGEDIN},
43 'PWD' => $_connection_states{LOGGEDIN} |
44 $_connection_states{TWOSOCKS},
45 'QUIT' => $_connection_states{LOGGEDIN} |
46 $_connection_states{TWOSOCKS},
47 'REST' => $_connection_states{TWOSOCKS},
48 'RETR' => $_connection_states{TWOSOCKS},
49 'SYST' => $_connection_states{LOGGEDIN},
50 'TYPE' => $_connection_states{LOGGEDIN} |
51 $_connection_states{TWOSOCKS},
52 'USER' => $_connection_states{NEWCONN},
53 # From ftpexts Internet Draft.
54 'SIZE' => $_connection_states{LOGGEDIN} |
55 $_connection_states{TWOSOCKS},
60 # COMMAND-HANDLING ROUTINES
64 my ($conn, $cmd, $path) = @_;
67 my $newdir = $conn->{dir};
69 # If the path starts with a "/" then it's an absolute path.
70 if (substr ($path, 0, 1) eq "/") {
75 # Split the path into its component parts and process each separately.
76 my @elems = split /\//, $path;
79 if ($_ eq "" || $_ eq ".") {
82 } elsif ($_ eq "..") {
83 # Go to parent directory.
85 print {$conn->{socket}} "550 Directory not found.\r\n";
88 $newdir = substr ($newdir, 0, rindex ($newdir, "/"));
90 # Go into subdirectory, if it exists.
91 $newdir .= ("/" . $_);
92 if (! -d $conn->{rootdir} . $newdir) {
93 print {$conn->{socket}} "550 Directory not found.\r\n";
99 $conn->{dir} = $newdir;
104 my ($conn, $cmd, $path) = @_;
106 # This is something of a hack. Some clients expect a Unix server
107 # to respond to flags on the 'ls command line'. Remove these flags
108 # and ignore them. This is particularly an issue with ncftp 2.4.3.
109 $path =~ s/^-[a-zA-Z0-9]+\s?//;
111 my $dir = $conn->{dir};
113 print STDERR "_LIST_command - dir is: $dir\n";
116 if (substr ($path, 0, 1) eq "/") {
121 # Parse the first elements of the path until we find the appropriate
123 my @elems = split /\//, $path;
124 my ($wildcard, $filename);
127 for (my $i = 0; $i < @elems; ++$i) {
129 my $lastelement = $i == @elems-1;
131 if ($_ eq "" || $_ eq ".") { next } # Ignore these.
133 # Go to parent directory.
134 unless ($dir eq "/") {
135 $dir = substr ($dir, 0, rindex ($dir, "/"));
138 if (!$lastelement) { # These elements can only be directories.
139 unless (-d $conn->{rootdir} . $dir . $_) {
140 print {$conn->{socket}} "550 File or directory not found.\r\n";
144 } else { # It's the last element: check if it's a file, directory or wildcard.
145 if (-f $conn->{rootdir} . $dir . $_) {
148 } elsif (-d $conn->{rootdir} . $dir . $_) {
151 } elsif (/\*/ || /\?/) {
155 print {$conn->{socket}} "550 File or directory not found.\r\n";
162 print STDERR "_LIST_command - dir is: $dir\n" if $log;
164 print {$conn->{socket}} "150 Opening data connection for file listing.\r\n";
166 # Open a path back to the client.
167 my $sock = __open_data_connection ($conn);
170 print {$conn->{socket}} "425 Can't open data connection.\r\n";
174 # If the path contains a directory name, extract it so that
175 # we can prefix it to every filename listed.
176 my $prefix = (($filename || $wildcard) && $path =~ /(.*\/).*/) ? $1 : "";
178 print STDERR "_LIST_command - prefix is: $prefix\n" if $log;
180 # OK, we're either listing a full directory, listing a single
181 # file or listing a wildcard.
182 if ($filename) { # Single file.
183 __list_file ($sock, $prefix . $filename);
184 } else { # Wildcard or full directory $dirh.
186 # Synthesize (fake) "total" field for directory listing.
187 print $sock "total 1 \r\n";
190 foreach (__get_file_list ($conn->{rootdir} . $dir, $wildcard)) {
191 __list_file ($sock, $prefix . $_);
195 unless ($sock->close) {
196 print {$conn->{socket}} "550 Error closing data connection: $!\r\n";
200 print {$conn->{socket}} "226 Listing complete. Data connection has been closed.\r\n";
205 my ($conn, $cmd, $pass) = @_;
207 # TODO: implement authentication?
209 print STDERR "switching to LOGGEDIN state\n" if $log;
210 $conn->{state} = $_connection_states{LOGGEDIN};
212 if ($conn->{username} eq "anonymous") {
213 print {$conn->{socket}} "202 Anonymous user access is always granted.\r\n";
215 print {$conn->{socket}} "230 Authentication not implemented yet, access is always granted.\r\n";
221 my ($conn, $cmd, $rest) = @_;
223 # Open a listening socket - but don't actually accept on it yet.
224 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
225 my $sock = IO::Socket::INET->new (LocalHost => '127.0.0.1',
230 Type => SOCK_STREAM);
233 # Return a code 550 here, even though this is not in the RFC. XXX
234 print {$conn->{socket}} "550 Can't open a listening socket.\r\n";
238 $conn->{passive} = 1;
239 $conn->{passive_socket} = $sock;
241 # Get our port number.
242 my $sockport = $sock->sockport;
244 # Split the port number into high and low components.
245 my $p1 = int ($sockport / 256);
246 my $p2 = $sockport % 256;
248 $conn->{state} = $_connection_states{TWOSOCKS};
250 # We only accept connections from localhost.
251 print {$conn->{socket}} "227 Entering Passive Mode (127,0,0,1,$p1,$p2)\r\n";
256 my ($conn, $cmd, $rest) = @_;
258 # The arguments to PORT are a1,a2,a3,a4,p1,p2 where a1 is the
259 # most significant part of the address (eg. 127,0,0,1) and
260 # p1 is the most significant part of the port.
261 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})/) {
262 print {$conn->{socket}} "501 Syntax error in PORT command.\r\n";
266 # Check host address.
267 unless ($1 > 0 && $1 < 224 &&
268 $2 >= 0 && $2 < 256 &&
269 $3 >= 0 && $3 < 256 &&
270 $4 >= 0 && $4 < 256) {
271 print {$conn->{socket}} "501 Invalid host address.\r\n";
275 # Construct host address and port number.
276 my $peeraddrstring = "$1.$2.$3.$4";
277 my $peerport = $5 * 256 + $6;
280 unless ($peerport > 0 && $peerport < 65536) {
281 print {$conn->{socket}} "501 Invalid port number.\r\n";
284 $conn->{peeraddrstring} = $peeraddrstring;
285 $conn->{peeraddr} = inet_aton ($peeraddrstring);
286 $conn->{peerport} = $peerport;
287 $conn->{passive} = 0;
289 $conn->{state} = $_connection_states{TWOSOCKS};
291 print {$conn->{socket}} "200 PORT command OK.\r\n";
296 my ($conn, $cmd, $rest) = @_;
298 # See RFC 959 Appendix II and draft-ietf-ftpext-mlst-11.txt section 6.2.1.
299 my $pathname = $conn->{dir};
300 $pathname =~ s,/+$,, unless $pathname eq "/";
301 $pathname =~ tr,/,/,s;
303 print {$conn->{socket}} "257 \"$pathname\"\r\n";
308 my ($conn, $cmd, $restart_from) = @_;
310 unless ($restart_from =~ /^([1-9][0-9]*|0)$/) {
311 print {$conn->{socket}} "501 REST command needs a numeric argument.\r\n";
315 $conn->{restart} = $1;
317 print {$conn->{socket}} "350 Restarting next transfer at $1.\r\n";
322 my ($conn, $cmd, $path) = @_;
324 my $dir = $conn->{dir};
327 if (substr ($path, 0, 1) eq "/") {
330 $path = "." if $path eq "";
333 # Parse the first elements of path until we find the appropriate
335 my @elems = split /\//, $path;
336 my $filename = pop @elems;
339 if ($_ eq "" || $_ eq ".") {
341 } elsif ($_ eq "..") {
342 # Go to parent directory.
343 unless ($dir eq "/") {
344 $dir = substr ($dir, 0, rindex ($dir, "/"));
347 unless (-d $conn->{rootdir} . $dir . $_) {
348 print {$conn->{socket}} "550 File or directory not found.\r\n";
355 unless (defined $filename && length $filename) {
356 print {$conn->{socket}} "550 File or directory not found.\r\n";
360 if ($filename eq "." || $filename eq "..") {
361 print {$conn->{socket}} "550 RETR command is not supported on directories.\r\n";
365 my $fullname = $conn->{rootdir} . $dir . $filename;
366 unless (-f $fullname) {
367 print {$conn->{socket}} "550 RETR command is only supported on plain files.\r\n";
371 # Try to open the file.
372 unless (open (FILE, '<', $fullname)) {
373 print {$conn->{socket}} "550 File or directory not found.\r\n";
377 print {$conn->{socket}} "150 Opening " .
378 ($conn->{type} eq 'A' ? "ASCII mode" : "BINARY mode") .
379 " data connection for file $filename.\r\n";
381 # Open a path back to the client.
382 my $sock = __open_data_connection ($conn);
385 print {$conn->{socket}} "425 Can't open data connection.\r\n";
389 # What mode are we sending this file in?
390 unless ($conn->{type} eq 'A') # Binary type.
392 my ($r, $buffer, $n, $w);
394 # Restart the connection from previous point?
395 if ($conn->{restart}) {
396 # VFS seek method only required to support relative forward seeks
398 # In Perl = 5.00503, SEEK_CUR is exported by IO::Seekable,
399 # in Perl >= 5.6, SEEK_CUR is exported by both IO::Seekable
400 # and Fcntl. Hence we 'use IO::Seekable' at the top of the
401 # file to get this symbol reliably in both cases.
402 sysseek (FILE, $conn->{restart}, SEEK_CUR);
403 $conn->{restart} = 0;
407 while ($r = sysread (FILE, $buffer, 65536))
409 # Restart alarm clock timer.
410 alarm $conn->{idle_timeout};
412 for ($n = 0; $n < $r; )
414 $w = syswrite ($sock, $buffer, $r - $n, $n);
416 # Cleanup and exit if there was an error.
417 unless (defined $w) {
420 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
427 # Transfer aborted by client?
432 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
437 # Cleanup and exit if there was an error.
438 unless (defined $r) {
441 print {$conn->{socket}} "426 File retrieval error: $!. Data connection has been closed.\r\n";
444 } else { # ASCII type.
445 # Restart the connection from previous point?
446 if ($conn->{restart}) {
447 for (my $i = 0; $i < $conn->{restart}; ++$i) {
450 $conn->{restart} = 0;
454 while (defined ($_ = <FILE>)) {
455 # Remove any native line endings.
458 # Restart alarm clock timer.
459 alarm $conn->{idle_timeout};
461 # Write the line with telnet-format line endings.
462 print $sock "$_\r\n";
464 # Transfer aborted by client?
469 print {$conn->{socket}} "426 Transfer aborted. Data connection closed.\r\n";
475 unless (close ($sock) && close (FILE)) {
476 print {$conn->{socket}} "550 File retrieval error: $!.\r\n";
480 print {$conn->{socket}} "226 File retrieval complete. Data connection has been closed.\r\n";
485 my ($conn, $cmd, $path) = @_;
487 my $dir = $conn->{dir};
490 if (substr ($path, 0, 1) eq "/") {
493 $path = "." if $path eq "";
496 # Parse the first elements of path until we find the appropriate
498 my @elems = split /\//, $path;
499 my $filename = pop @elems;
502 if ($_ eq "" || $_ eq ".") {
504 } elsif ($_ eq "..") {
505 # Go to parent directory.
506 unless ($dir eq "/") {
507 $dir = substr ($dir, 0, rindex ($dir, "/"));
510 unless (-d $conn->{rootdir} . $dir . $_) {
511 print {$conn->{socket}} "550 File or directory not found.\r\n";
518 unless (defined $filename && length $filename) {
519 print {$conn->{socket}} "550 File or directory not found.\r\n";
523 if ($filename eq "." || $filename eq "..") {
524 print {$conn->{socket}} "550 SIZE command is not supported on directories.\r\n";
528 my $fullname = $conn->{rootdir} . $dir . $filename;
529 unless (-f $fullname) {
530 print {$conn->{socket}} "550 SIZE command is only supported on plain files.\r\n";
535 if ($conn->{type} eq 'A') {
536 # ASCII mode: we have to count the characters by hand.
537 unless (open (FILE, '<', $filename)) {
538 print {$conn->{socket}} "550 Cannot calculate size of $filename.\r\n";
541 $size++ while (defined (getc(FILE)));
544 # BINARY mode: we can use stat
545 $size = (stat($filename))[7];
548 print {$conn->{socket}} "213 $size\r\n";
553 my ($conn, $cmd, $dummy) = @_;
555 print {$conn->{socket}} "215 UNIX Type: L8\r\n";
560 my ($conn, $cmd, $type) = @_;
562 # See RFC 959 section 5.3.2.
563 if ($type =~ /^([AI])$/i) {
565 } elsif ($type =~ /^([AI])\sN$/i) {
567 } elsif ($type =~ /^L\s8$/i) {
568 $conn->{type} = 'L8';
570 print {$conn->{socket}} "504 This server does not support TYPE $type.\r\n";
574 print {$conn->{socket}} "200 TYPE changed to $type.\r\n";
579 my ($conn, $cmd, $username) = @_;
581 print STDERR "username: $username\n" if $log;
582 $conn->{username} = $username;
584 print STDERR "switching to WAIT4PWD state\n" if $log;
585 $conn->{state} = $_connection_states{WAIT4PWD};
587 if ($conn->{username} eq "anonymous") {
588 print {$conn->{socket}} "230 Anonymous user access granted.\r\n";
590 print {$conn->{socket}} "331 Password required.\r\n";
597 sub __open_data_connection
603 if ($conn->{passive}) {
604 # Passive mode - wait for a connection from the client.
605 accept ($sock, $conn->{passive_socket}) or return undef;
607 # Active mode - connect back to the client.
608 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
609 $sock = IO::Socket::INET->new (LocalAddr => '127.0.0.1',
610 PeerAddr => $conn->{peeraddrstring},
611 PeerPort => $conn->{peerport},
613 Type => SOCK_STREAM) or return undef;
623 my $filename = shift;
625 # Get the status information.
626 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
627 $atime, $mtime, $ctime, $blksize, $blocks)
630 # If the file has been removed since we created this
631 # handle, then $dev will be undefined. Return immediately.
632 return unless defined $dev;
634 # Generate printable user/group.
635 my $user = getpwuid ($uid) || "-";
636 my $group = getgrgid ($gid) || "-";
638 # Permissions from mode.
639 my $perms = $mode & 0777;
641 # Work out the mode using special "_" operator which causes Perl
642 # to use the result of the previous stat call.
643 $mode = (-f _ ? 'f' :
649 (-c _ ? 'c' : '?')))))));
651 # Generate printable date (this logic is taken from GNU fileutils:
652 # src/ls.c: print_long_format).
655 if ($time > $mtime + 6 * 30 * 24 * 60 * 60 || $time < $mtime - 60 * 60) {
658 $fmt = "%b %e %H:%M";
661 my $fmt_time = strftime $fmt, localtime ($mtime);
663 # Generate printable permissions.
664 my $fmt_perms = join "",
665 ($perms & 0400 ? 'r' : '-'),
666 ($perms & 0200 ? 'w' : '-'),
667 ($perms & 0100 ? 'x' : '-'),
668 ($perms & 040 ? 'r' : '-'),
669 ($perms & 020 ? 'w' : '-'),
670 ($perms & 010 ? 'x' : '-'),
671 ($perms & 04 ? 'r' : '-'),
672 ($perms & 02 ? 'w' : '-'),
673 ($perms & 01 ? 'x' : '-');
675 # Printable file type.
676 my $fmt_mode = $mode eq 'f' ? '-' : $mode;
678 # If it's a symbolic link, display the link.
681 $link = readlink $filename;
682 die "readlink: $!" unless defined $link;
684 my $fmt_link = defined $link ? " -> $link" : "";
688 ("%s%s%4d %-8s %-8s %8d %s %s%s\r\n",
698 $sock->print ($line);
705 my $wildcard = shift;
707 opendir (DIRHANDLE, $dir)
708 or die "Cannot open directory!!!";
710 my @allfiles = readdir DIRHANDLE;
714 # Get rid of . and ..
715 @allfiles = grep !/^\.{1,2}$/, @allfiles;
717 # Convert wildcard to a regular expression.
718 $wildcard = __wildcard_to_regex ($wildcard);
720 @filenames = grep /$wildcard/, @allfiles;
722 @filenames = @allfiles;
725 closedir (DIRHANDLE);
727 return sort @filenames;
731 sub __wildcard_to_regex
733 my $wildcard = shift;
735 $wildcard =~ s,([^?*a-zA-Z0-9]),\\$1,g; # Escape punctuation.
736 $wildcard =~ s,\*,.*,g; # Turn * into .*
737 $wildcard =~ s,\?,.,g; # Turn ? into .
738 $wildcard = "^$wildcard\$"; # Bracket it.
744 ###########################################################################
746 ###########################################################################
749 my %_attr_data = ( # DEFAULT
750 _localAddr => 'localhost',
753 _rootDir => Cwd::getcwd(),
758 my ($self, $attr) = @_;
770 my ($caller, %args) = @_;
771 my $caller_is_obj = ref($caller);
772 my $class = $caller_is_obj || $caller;
773 my $self = bless {}, $class;
774 foreach my $attrname ($self->_standard_keys()) {
775 my ($argname) = ($attrname =~ /^_(.*)/);
776 if (exists $args{$argname}) {
777 $self->{$attrname} = $args{$argname};
778 } elsif ($caller_is_obj) {
779 $self->{$attrname} = $caller->{$attrname};
781 $self->{$attrname} = $self->_default_for($attrname);
790 my ($self, $synch_callback) = @_;
793 # turn buffering off on STDERR
794 select((select(STDERR), $|=1)[0]);
796 # initialize command table
797 my $command_table = {};
798 foreach (keys %_commands) {
799 my $subname = "_${_}_command";
800 $command_table->{$_} = \&$subname;
806 # create server socket
807 "0" =~ /(0)/; # Perl 5.7 / IO::Socket::INET bug workaround.
808 my $server_sock = IO::Socket::INET->new (LocalHost => $self->{_localAddr},
809 LocalPort => $self->{_localPort},
811 Reuse => $self->{_reuseAddr},
813 Type => SOCK_STREAM) or die "bind: $!";
820 $SIG{CHLD} = sub { wait };
823 while (my $client_addr = accept (my $socket, $server_sock))
825 # turn buffering off on $socket
826 select((select($socket), $|=1)[0]);
828 # find out who connected
829 my ($client_port, $client_ip) = sockaddr_in ($client_addr);
830 my $client_ipnum = inet_ntoa ($client_ip);
832 # print who connected
833 print STDERR "got a connection from: $client_ipnum\n" if $log;
835 # fork off a process to handle this connection.
837 unless (defined $pid) {
839 sleep 5; # Back off in case system is overloaded.
843 if ($pid == 0) { # Child process.
851 print STDERR "Client closed connection abruptly.\n";
856 print STDERR "Connection idle timeout expired. Closing server.\n";
860 #$SIG{CHLD} = 'IGNORE';
863 print STDERR "in child\n" if $log;
867 'state' => $_connection_states{NEWCONN},
870 'idle_timeout' => 60, # 1 minute timeout
871 'rootdir' => $self->{_rootDir},
874 print {$conn->{socket}} "220 GNU Wget Testing FTP Server ready.\r\n";
876 # command handling loop
878 print STDERR "waiting for request\n" if $log;
880 last unless defined (my $req = <$socket>);
882 # Remove trailing CRLF.
883 $req =~ s/[\n\r]+$//;
885 print STDERR "received request $req\n" if $log;
888 # See also RFC 2640 section 3.1.
889 unless ($req =~ m/^([A-Z]{3,4})\s?(.*)/i) {
890 # badly formed command
894 # The following strange 'eval' is necessary to work around a
895 # very odd bug in Perl 5.6.0. The following assignment to
896 # $cmd will fail in some cases unless you use $1 in some sort
897 # of an expression beforehand.
901 my ($cmd, $rest) = (uc $1, $2);
903 # Got a command which matches in the table?
904 unless (exists $command_table->{$cmd}) {
905 print {$conn->{socket}} "500 Unrecognized command.\r\n";
909 # Command requires user to be authenticated?
910 unless ($_commands{$cmd} | $conn->{state}) {
911 print {$conn->{socket}} "530 Not logged in.\r\n";
915 # Handle the QUIT command specially.
916 if ($cmd eq "QUIT") {
917 print {$conn->{socket}} "221 Goodbye. Service closing connection.\r\n";
922 &{$command_table->{$cmd}} ($conn, $cmd, $rest);