#!/usr/bin/perl

# monTelnet  (c) Copyright 1998 Mark Black 

$version = 2 ;

# monTelnet - This is a little bit of perl network code to test the 
#           operation of the telnet daemon.
#           OUTPUT:
#                   1:      - Success
#                   0:info  - Failure
#           Note:  Exit status of script should always be  0

$inp = "" ;
foreach $i (0 .. $#ARGV) {
   $inp .= "@ARGV[$i] " ;
}
chop($inp) ;

# Output the version if requested
if($inp eq "-v") {
    print "$version\n" ;
    exit(0) ;
}

# Telnet port = 23
$port = 23 ;

$AF_INET = 2 ;
$SOCK_STREAM = 1 ;

$SIG{'INT'} = 'dokill' ;
$SIG{'TERM'} = 'dokill' ;

sub dokill {
    kill 9,$child if $child ;
}

$sockaddr = 'S n a4 x8' ;

chop($hostname = `hostname`) ;
$them = $hostname ;

($name,$aliases,$proto) = getprotobyname('tcp') ;
($name,$aliases,$port) = getservbyname($port,'tcp') unless $port =~ /^\d+$/;;
($name,$aliases,$type,$len,$thisaddr) = gethostbyname($hostname) ;
($name,$aliases,$type,$len,$thataddr) = gethostbyname($hostname) ;

$this = pack($sockaddr, $AF_INET, 0, $thisaddr) ;
$that = pack($sockaddr, $AF_INET, $port, $thataddr) ;

# Make the socket filehandle
if(!socket(S, $AF_INET, $SOCK_STREAM, $proto)) {
    print "0:Can't open socket\n" ;
    exit 0 ;
}

# Give the socket an address
if(!bind(S, $this)) {
    print "0:Can't bind to port\n" ;
    exit 0 ;
}

# Call up the server
if(!connect(S,$that)) {
    # Code fails here if the service is not available
    print "0:Service not running\n" ;
    exit 0 ;
}

# Set socket to be command buffered
select(S); $| = 1; select(STDOUT) ;

# Open pipe for parent child communications
pipe(Rhandle, Whandle) ;

# Avoid deadlock by forking
if($child = fork) {
    close(Whandle) ;
    select(Rhandle) ; $| = 1 ; select(STDOUT) ;

    # Search the data for a "220 ..." introduction
    print S "user\r\n" ;
    $data = <Rhandle> ;
    print "Data = $data\n" ;
    if( $data !~ /[Ll]ogin / ) {
	print "0:Service is nor running\n" ;
	exit 0 ;
    }

    # Send the quit signal, and check response
    print S "quit\n" ;
    $data = <Rhandle> ;
    if($data =~ /^221 / ) {
	print "1:Service running\n" ;
    } else {
	print "0:Service failure\n" ;
    }
    exit 0 ;
} else {
    close(Rhandle) ;
    select(Whandle) ; $| = 1 ;
    while(<S>) {
	# The child receives data from the remote server through S and sends it back through the pipe
	print Whandle $_ ;
    }
} 









