#!/usr/bin/perl
#
# Use try to connect to a FTP server, and
# wait for the right output.
#
# For use with "mon".
#
# Arguments are "-p port -t timeout host [host...]"
#
# Adapted from "http.monitor" by
# Jim Trocki
#
# http.monitor originally written by
#
# Jon Meek
# American Cyanamid Company
# Princeton, NJ
#
# $Id: ftp.monitor,v 1.1.1.1.4.1 2007/05/08 11:25:42 trockij Exp $
#
#    Copyright (C) 1998, Jim Trocki
#
#    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 Getopt::Std;
use English;

getopts ("p:t:");
$PORT = $opt_p || 21;
$TIMEOUT = $opt_t || 30;

my %good;
my %bad;

#
# collect the status on all the hosts
#
foreach my $host (@ARGV) {
    my $result = ftpGET ($host, $PORT);

    if (!$result->{"ok"}) {
    	$bad{$host} = $result;
    } else {
    	$good{$host} = $result;
    }
}

#
# summary line
#
if (keys %bad == 0)
{
    print "\n";
}

else
{
    print join (" ", sort keys %bad), "\n";
}

#
# detail
#
foreach my $host (keys %bad) {
    print "$host failed with error " . $bad{$host}->{"error"}, "\n";

    print "detail for $host\n";
    print "==============================================================================\n";

    if ($bad{$host}->{"detail"} ne "")
    {
	print $bad{$host}->{"detail"};
    }
    
    else
    {
    	print "no detail\n";
    }

    print "\n";
}

print "\n";

foreach my $host (keys %good)
{
    print "$host succeeded\n";

    print "detail for $host\n";
    print "==============================================================================\n";

    if ($good{$host}->{"detail"} ne "")
    {
	print $good{$host}->{"detail"};
    }

    else
    {
    	print "no detail\n";
    }

    print "\n";
}

if (keys %bad != 0)
{
    exit 1;
}

exit 0;


sub ftpGET {
    use Socket;
    use Sys::Hostname;

    my($Server, $Port) = @_;
    my($ok);

    my $result = {
    	"ok" => 0,
	"error" => undef,
	"detail" => undef,
    };

###############################################################
    eval {
	local $SIG{ALRM} = sub { die "Timeout Alarm" };
	alarm $TIMEOUT;

	my $err = &OpenSocket($Server, $Port); # Open a connection to the server

	if ($err ne "") { # Failure to open the socket
	    $result = {
	    	"ok" => 0,
		"error" => $err,
		"detail" => undef,
	    };

	    return $result;
	}

	while ($in = <S>) {
	    $result->{"detail"} .= "    < $in";
	    if ($in =~ /^220 /) {
    	    	$result->{"ok"} = 1;
    	    	last;
    	    }
    	}

    	if (!$result->{"ok"}) {
	    alarm 0;
	    $result->{"ok"} = 0;
	    $result->{"error"} = "Connection refused";
	    close(S);
	    return undef;
    	}

	print S "quit\r\n";
	$result->{"detail"} .= "    > quit\n";

	while ($in = <S>) {
		$result->{"detail"} .= "    < $in";
		next if ($in =~ /^[0-9]{3}\-/);
		if ($in !~ /^221 /) {
			alarm 0;
			$result->{"ok"} = 0;
			$result->{"error"} = "FTP server error after quit";
			close(S);
			return undef;
		}
	}

	close(S);
	alarm 0; # Cancel the alarm
    };

    #
    # catch timeout
    #
    if ($EVAL_ERROR and ($EVAL_ERROR =~ /^Timeout Alarm/)) {
	$result->{"ok"} = 0;
	$result->{"error"} = "timeout";
    }

    return $result;
}


#
# Make a Berkeley socket connection between this program and a TCP port
# on another (or this) host. Port can be a number or a named service
#
# returns "" on success, or an error string on failure
#
sub OpenSocket {
    my ($host, $port) = @_;

    my $proto = (getprotobyname('tcp'))[2];

    return ("could not get protocol") if (!defined $proto);

    my $conn_port;

    if ($port =~ /^\d+$/) {
    	$conn_port = $port;

    } else {
	$conn_port = (getservbyname($port, 'tcp'))[2];
	return ("could not getservbyname for $port")
		if (!defined $conn_port);
    }

    my $host_addr = (gethostbyname($host))[4];

    return ("gethostbyname failure")
    		if (!defined $host_addr);

    my $that = sockaddr_in ($conn_port, $host_addr);

    if (!socket (S, &PF_INET, &SOCK_STREAM, $proto)) {
    	return ("socket: $!");
    }

    if (!connect (S, $that)) {
    	return ("connect: $!");
    }

    select(S); $| = 1; select(STDOUT);

    "";
}
