#!/bin/sh

# policy is either allow or deny
DEFAULTPOLICY=deny
SETNAME=ACCESS
INT_TO_USER=eth1

## don't forget to create the set && add iptables rule like:
# /usr/sbin/ipset -N $SETNAME iphash --hashsize 1024
# /usr/sbin/ipset -F $SETNAME
# /sbin/iptables -A INPUT -m set --set $SETNAME src -j LOG
#
# for bandwidth control, add this:
# tc qdisc add dev $INT_TO_USER root handle 1: htb 
# tc class add dev $INT_TO_USER parent 1: classid 1:1 htb rate 1000Mbit 

# ===== do not modify below this line ====

ACTION=$1
ADDR=`echo "$2"| sed 's/\/32$//'`
MASK=$3
AUID=$4
RULE=`echo "$5" | sed "s/'//g"`
TS=$6

if [ "$DEFAULTPOLICY" = allow ]; then
	PERMIT_ACTION=--del
	BLOCK_ACTION=--add
fi
if [ "$DEFAULTPOLICY" = deny ]; then
        PERMIT_ACTION=--add
        BLOCK_ACTION=--del
fi

echo `date` $ACTION $ADDR $AUID $RULE >> /tmp/access_sh.log                	        

if [ "$ACTION" = PERMIT -o "$ACTION" = LOGIN ]; then
        /usr/sbin/ipset $PERMIT_ACTION $SETNAME $ADDR
	/sbin/iptables -t mangle -A POSTROUTING -d $ADDR -j CLASSIFY --set-class 1:9$AUID
	/sbin/tc class add dev $INT_TO_USER parent 1 classid 1:9$AUID htb prio 2 rate $RULE
	/sbin/tc qdisc add dev $INT_TO_USER parent 1:9$AUID handle 9$AUID: sfq perturb 10
fi
if [ "$ACTION" = BLOCK -o "$ACTION" = LOGOUT ]; then
     	/usr/sbin/ipset $BLOCK_ACTION $SETNAME $ADDR
	/sbin/tc qdisc del dev $INT_TO_USER parent 1:9$AUID handle 9$AUID: sfq perturb 10
	/sbin/tc class del dev $INT_TO_USER parent 1 classid 1:9$AUID
	/sbin/iptables -t mangle -D POSTROUTING -d $ADDR -j CLASSIFY --set-class 1:9$AUID
fi
