#!/usr/bin/perl

#File: Intruder.pl
#Description: This is the client that connects to the hosr server.
#				  It can read both secure and unsecure diles. It can update
#				  unsecure files but not secure files. When it tries to update
#				  a secure file it will be detected by the IDS


use strict;
use IO::Socket::INET;
use Net::hostent;

#Ask for user info to set up connection
print "Open a connection to the host machine using command open.\nCommand: ";
my $comm = <STDIN>;
while (!($comm =~ /open/)){
	print STDOUT "Not Connected\n";
	print STDOUT "ftp> ";
	$comm = <STDIN>;
}
print STDOUT "To: ";
my $to = <STDIN>;
chop($to);
connect1($to);



########## Subroutines  ########
sub callItQuits{
	my($socket) = @_;
	shutdown($socket, 2);
	exit(0);
}

sub connect1{
	my ($interactiveSocket, $dataSocket, $childProcessID);
	my($peerAddr) = @_;
	my $closed = 0;
	my $end = 0;
	#Set up socket connection to the host machine
	$interactiveSocket = new IO::Socket::INET (
		PeerAddr => "$peerAddr",
		PeerPort => 8000,
		Proto => 'tcp'
	);

	print "Established socket connection to $peerAddr\n";
	die "Couldn't connect to host: $!" unless $interactiveSocket;

	#Print the host information
	my $hostInfo = gethostbyaddr($interactiveSocket -> peeraddr);
	my $hostName = $hostInfo->name();
	print "Host information:\n$hostInfo\n";
	print "[Created a TCP socket with $hostName]\n";

	$childProcessID = fork();
	die "Fork failed:  $!" unless defined ($childProcessID);

	if($childProcessID >0) {
		while (defined(my $responseLine = <$interactiveSocket>)){
			print STDOUT $responseLine;
			if($responseLine =~ m/refused/) {
				exit(0);
			}
		}
		kill("TERM", $childProcessID);
		callItQuits($interactiveSocket);
	}
	else {
		sleep(1);
		print "Command : ";
		#Process client commands
		while(defined (my $command = <STDIN>)) {
			#process read command
			if($command =~ /read/) {
				print STDOUT "remote file: ";
				my $remotefile = <STDIN>;
				print $interactiveSocket "read $remotefile";
				 
			}
			#process update command
			elsif($command =~ /update/) {
				print STDOUT "remote file: ";
				my $remotefile = <STDIN>;
				print $interactiveSocket "update $remotefile";
				 
			}
			else{
				print STDOUT "Not a valid command\n";
			}
			print "Command: ";
		}
	}

}

