#!/bin/sh
# tcpmon: tcp monitoring using ip accounting (kernel 2.0.*)
# (C) M. Andreoli 2000

#set -x

help()
{
cat <<END
tcpmon: rustic packet monitor, (C) M. Andreoli
Usage: 'tcpmon' accept the same syntax of ipfwadm accounting program.
	# tcpmon -S host/net [port] -D host/net [port] [ -P protocol]
		... [ -W interface ]
Example:

	# tcpmon -S host1 -D host2  -P [protocol]
	# tcpmon -P icmp -D 192.168.1.0/24
	# tcpmon -P tcp -D 192.168.1.1 23 
	# tcpmon -W ppp0

Logging is made via pcspeaker, or via the commad specified with
the -run switch:
		# tcpmon -run 'command' ....
Example:
		reboot machine pinging from 192.168.1.4
		# tcpmon -run '/bin/reboot' -S 192.168.1.4 -P icmp 

If your command work in background, it will be started and stopped
periodically.

END
exit
}
acoustic_log()
{
	wave -c 220 1
}
monitor()
{
	echo "Flushing accounting rules ... "
	ipfwadm -A -f
	ipfwadm -A both -i $@
	ipfwadm -n -A -l
	before=`cat /proc/net/ip_acct`

while [ 1 ] ; do 
now=`cat /proc/net/ip_acct`

pid=`cat /var/run/tcpmon.pid 2>/dev/null`

if [ "$now" != "$before" ] ; then
	before="$now"	
	if [ -z "$pid" ] ; then
	eval $cmd &
	base=`basename $cmd`
	pid=`pidof $base`
	echo $pid > /var/run/tcpmon.pid
	fi
else
	(
	rm /var/run/tcpmon.pid
	kill -1  $pid
	) > /dev/null
fi
	sleep 1
done

}

quit()
{
echo "Ahia! flushing rules ..." 
ipfwadm -A -f
rm /var/run/tcpmon.pid 2>/dev/null
exit
}

# Main

trap quit 1 2 3

case "Z$1Z" in
Z-hZ|ZZ)
	help
	;;
Z-runZ)
	shift; cmd=$1; shift
	monitor $@
	;;
*)
	cmd=acoustic_log
	monitor $@
	;;
esac
