#!/bin/bash

source /usr/local/share/dynfw.sh

args 5 $# "${0} IPADDR PORT RATE {second/minute/hour/day} {on/off}" "Limits rate of incoming TCP connections from IPADDR to local PORT"

RATE=${3}
SCALE=${4}

if [ "$5" = "on" ] 
then
	rec_check host-tcplimit $1 "$1 already limited" on
	record host-tcplimit "$1:$2:$3:$4"
	iptables -N ip${1}-${2}
	iptables -A ip${1}-${2} -p tcp -m limit --limit ${RATE}/${SCALE} --limit-burst ${RATE} -j RETURN
	iptables -A ip${1}-${2} -p tcp -j REJECT --reject-with tcp-reset
	iptables -I INPUT -p tcp -s ${1} --dport ${2} -m state --state NEW -j ip${1}-${2}
	echo "${1} new connection limit to port ${2} (${RATE}/${SCALE}, burst=${RATE}) on."
elif [ "$5" = "off" ]
then
	rec_check host-tcplimit "$1:$2" "${1}/port ${2} not currently limited" off
	unrecord host-tcplimit "$1:$2"
	iptables -D INPUT -p tcp -s ${1} --dport ${2} -m state --state NEW -j ip${1}-${2}
	iptables -F ip${1}-${2}
	iptables -X ip${1}-${2}
	echo "${1} new connection limit to port ${2} off."
else
	echo "Error: \"off\" or \"on\" expected as fifth argument."
	exit 1
fi	
