#! /bin/sh
:
#
#	checkrbls - lookup an IP address (or name) in the RBLs for TCP Wrappers sendmail
#
# (c) Copyright 1999 Greg A. Woods.
# Freely redistibutable.
# All other rights reserved.
# Return all fixes/modifications to <woods@planix.com>.
#
#ident	"@(#)src:checkrbls.sh	1.2	99/10/12 11:43:12 (woods)"

# TODO:
#
# - add a '-q' option ala checksmtp
#
# - add a '-R RBLs' option to accept an explicit list of RBLs

argv0=`basename $0`

USAGE="Usage: $argv0 [-v] IP-or-domain ..."

HELP="$USAGE
	-v	be verbose and show what is happening under the hood
"

PATH=/usr/sbin:$PATH
export PATH

VERBOSE=false

while getopts "Hv" OPTCHAR ; do
	case $OPTCHAR in
	H)
		echo "$HELP" 1>&2
		exit 2
		;;
	v)
		VERBOSE=true
		;;
	\?)
		echo "$USAGE" 1>&2
		exit 2
		;;
	esac
done
shift `expr $OPTIND - 1`

if [ $# -lt 1 ] ; then
	echo "$USAGE" 1>&2
	exit 2
fi

RBLS=$(awk -F: '$2 ~ /{RBL}/ {print $2}' /etc/hosts.allow /etc/hosts.deny 2>/dev/null | sed 's/{RBL}//' | tr '[A-Z]' '[a-z]')

if [ -z "$RBLS" ] ; then
	echo "$argv0: error: no RBL entries in /etc/hosts.{allow,deny}" 1>&2
	exit 1
fi

while [ $# -gt 0 ] ; do

	QUERY=$(echo "$1" | tr '[A-Z]' '[a-z]')
	shift
	
	$VERBOSE && echo "$argv0: processing $QUERY" 1>&2

	tcpdmatch sendmail $QUERY |
		awk '$2 == "address" {printf("%s\n", $3);}' |
		while read addr junk ; do
			inaddr=$(echo "$addr" | awk -F. '{printf("%d.%d.%d.%d", $4, $3, $2, $1);}')
			$VERBOSE && echo "$argv0: address: $addr, inverse: $inaddr" 1>&2
			for RBL in $RBLS ; do
				host -a ${inaddr}${RBL} 2>/dev/null
			done
		done
done

exit 0
