#!/bin/bash

source /usr/local/share/dynfw.sh

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

RATE=${2}
SCALE=${3}

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

