+case "${IP}" in
+ *:* ) IPTABLES=$IP6TABLES;;
+ *.* ) IPTABLES=$IP4TABLES;;
+ * ) echo "`date` Unable to run active response (invalid IP: '${IP}')." >> ${LOG_FILE} && exit 1;;
+esac
+
+# This number should be more than enough (even if a hundred
+# instances of this script is ran together). If you have
+# a really loaded env, you can increase it to 75 or 100.
+MAX_ITERATION="50"
+
+# Lock function
+lock()
+{
+ i=0;
+ # Providing a lock.
+ while [ 1 ]; do
+ mkdir ${LOCK} > /dev/null 2>&1
+ MSL=$?
+ if [ "${MSL}" = "0" ]; then
+ # Lock aquired (setting the pid)
+ echo "$$" > ${LOCK_PID}
+ return;
+ fi
+
+ # Getting currently/saved PID locking the file
+ C_PID=`cat ${LOCK_PID} 2>/dev/null`
+ if [ "x" = "x${S_PID}" ]; then
+ S_PID=${C_PID}
+ fi
+
+ # Breaking out of the loop after X attempts
+ if [ "x${C_PID}" = "x${S_PID}" ]; then
+ i=`expr $i + 1`;
+ fi
+
+ # Sleep 1 after 10/25 interactions
+ if [ "$i" = "10" -o "$i" = "25" ]; then
+ sleep 1;
+ fi
+
+ i=`expr $i + 1`;
+
+ # So i increments 2 by 2 if the pid does not change.
+ # If the pid keeps changing, we will increments one
+ # by one and fail after MAX_ITERACTION
+
+ if [ "$i" = "${MAX_ITERATION}" ]; then
+ kill="false"
+ for pid in `pgrep -f "${filename}"`; do
+ if [ "x${pid}" = "x${C_PID}" ]; then
+ # Unlocking and exiting
+ kill -9 ${C_PID}
+ echo "`date` Killed process ${C_PID} holding lock." >> ${LOG_FILE}
+ kill="true"
+ unlock;
+ i=0;
+ S_PID="";
+ break;
+ fi
+ done
+
+ if [ "x${kill}" = "xfalse" ]; then
+ echo "`date` Unable kill process ${C_PID} holding lock." >> ${LOG_FILE}
+ # Unlocking and exiting
+ unlock;
+ exit 1;
+ fi
+ fi
+ done
+}
+
+# Unlock function
+unlock()
+{
+ rm -rf ${LOCK}
+}
+