#!/bin/sh

#(C) Fredrik Widell (fredrik@widell.net) 2003
#use as you wish, modify as you wish
#this script will probably destroy your whole
#network in a second, dont blame me. send me
#a email if you want to. This script runs best
#via inetd, f.ex like this:
#prefixlookup      stream  tcp     nowait  youruserid /home/youruserid/scripts/prefixlookup prefixlookup
#and change /etc/services to reflect this aswell via:
#prefixlookup      43/tcp    whois
#This script makes use of a zebra that receives a full bgp-table, 
#easily changed to a cisco-router if you read the flags to the
#routerexec.pl which is needed to this script aswell

logfile="/home/youruserid/log/whoislog"
routerexec="/home/youruserid/scripts/routerexec.pl"
router="your.zebrarouter.se"



input=`head -1 /dev/stdin`

connecting=`netstat -f inet -an | egrep "\.43 " | egrep ESTABLISHED | awk '{print $4 " " $5}'`

echo "`date`	data=\"$input\"	to-from=$connecting" >> $logfile

errormsg="Please specify an ip-adress or regexp AS: f.ex 192.168.1.1 or _65535$"

rens=`echo "$input" | 
	sed 's/\.//g' | 
	sed 's/[0-9]//g' | 
	tr "\n" " " |
	sed 's/ //g' | 
	sed 's/\^//g' | 
	sed 's/_//g' |
	sed 's/$\$//g'`

if test "$rens" ; then
	echo $errormsg
	exit 1
fi

iptest=`echo $input | egrep "[1-9]*.[0-9]*.[0-9]*.[0-9]" | awk -F. '{print $1 " " $2 " " $3 " " $4 " " $5}' | wc -w | sed 's/ //g'`

astest=`echo $input | sed 's/[._^$]//g'`

if test "$iptest" -ne "4" ; then
	#echo "probably not ipadress $input"
	if test "$astest" -gt 65535 ; then	
		#echo "probably not correct regexp $input "
		echo $errormsg
		exit 1
	else
		if ! test `echo "$astest" | egrep "[0-9]"` > /dev/null ; then
			echo $errormsg
			exit 1
		else
			#echo "probably as regexp $input"
			flagga=1
		fi
	fi
else
	#echo "probably correct ip $input"
	flagga=2
fi

if test "$flagga" -eq 2 ; then
	for siffra in `echo $input | egrep "[1-9]*.[0-9]*.[0-9]*.[0-9]" | sed 's/\./ /g'` ; do
		if test $siffra -gt 255 ; then
			echo $errormsg
			exit 1
		fi
	done
fi


if test "$flagga" -eq 1 ; then
	$routerexec -n -c "sh ip bgp regexp $input" -t 2605  $router > /tmp/x.$$
	c=`wc -l /tmp/x.$$ | awk '{print $1}'`
	c=`expr $c - 4`
	tail -$c /tmp/x.$$
	rm /tmp/x.$$
else
	$routerexec -n -c "sh ip bgp $input" -t 2605  $router > /tmp/x.$$
	c=`wc -l /tmp/x.$$ | awk '{print $1}'`
	c=`expr $c - 4`
	tail -$c /tmp/x.$$
	rm /tmp/x.$$
fi

