#!/usr/bin/perl
# Copyright (C) 2005 Florian Weimer <fw@deneb.enyo.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

use strict;
use warnings;
use Socket;
use Unix::Syslog;

$| = 1;				# unbuffer standard input and output

Unix::Syslog::openlog 'ftpd', Unix::Syslog::LOG_PID, Unix::Syslog::LOG_DAEMON;

my $ip;
{
    my $saddr = getpeername STDIN;
    my ($port, $iaddr) = sockaddr_in $saddr;
    $ip = join ('.', map { ord $_ } split //, $iaddr);
}

# log a client response to syslog
sub l ($) {
    my $msg = shift;
    $msg =~ s/([\000-\037\177-\377])/sprintf '\%03o', ord $1/ge;
    Unix::Syslog::syslog Unix::Syslog::LOG_INFO, "%s %s\n", $ip, $msg;
}

# write a CRLF-terminated response
sub w ($) {
    my $msg = shift;
    print "$msg\r\n";
}

# reada CRLF-terminated command
sub r () {
    my $result = <STDIN>;
    $result =~ s/\r?\n$//;
    l $result;
    return $result;
}

w "220 PORT $ip";
while (my $line = r) {
    # Use somewhat realistic response codes.  May need further
    # adjustments to fool stricter firewalls.

    if ($line =~ /^USER\s/) {
	w '331 Please specify the password';
    } elsif ($line =~ /^PASS\s/) {
	w '230 Welcome  this FTP server';
    } elsif ($line =~ /^LIST/) {
	sleep 300;
	w '150 okay';
    } else {
	w '200 okay';
    }
}

