#!/usr/bin/perl
use strict;
use warnings;
# Simple script for educational purposes
# It prints to STDOUT flags tcp packets from ftp server and client

use Net::RawIP; 
use Getopt::Long qw(GetOptions);
require 'getopts.pl';


my $device       = 'lo';
my $port         = 21;
my $packet_size  = 1500;
my $timeout      = 500;
my $count        = 20;
my $host         = 'localhost';

GetOptions(
    'host=s'   => \$host,
    'device=s' => \$device,
    'number=s' => \$count,
    'port=s'   => \$port,
) or usage();

usage() if (not ($host and $port and $device and $count));

print "Configuration: host: $host:$port on device $device for $count times\n";

print "Now please login to your ftp server\n";

my @flags   = qw/URG ACK PSH RST SYN FIN/; 
my $filter  = "dst host $host and dst port $port";
my $filter1 = "src host $host and src port $port";

my $parent;
my $child;

my $pid = fork();
if ($pid) { # parent
    $parent = Net::RawIP->new;
    my $pcap = $parent->pcapinit($device, $filter, $packet_size, $timeout);
    my @a;
    #loop $pcap, $count, \&cl, \@a;
sleep 3;
} elsif (defined $pid) { # child
    #$child = Net::RawIP->new;
    #my @a;
    #my $pcap = $child->pcapinit($device, $filter1, $packet_size, $timeout);
    #loop $pcap, $count, \&sv, \@a;
} else {
    die "System error. Could not fork\n";
}

sub cl {
    $parent->bset(substr( $_[2],14));
    my @fl = $parent->get({tcp=>
                    [qw(psh syn fin rst urg ack)]
	       });
    print "Client -> ";
    map { print "$flags[$_] "  if $fl[$_] } (0..5);
    print "\n"
}

sub sv {
    $child->bset(substr( $_[2],14));
    my @fl = $child->get({tcp=>
                    [qw(psh syn fin rst urg ack)]
	       });
    print "Server -> ";
    map { print "$flags[$_] "  if $fl[$_] } (0..5);
    print "\n"; 
}

sub usage {
    die "Usage $0 --host <ftp server> --device <eth device> --number <number packet for receive>"
}

