#!/bin/sh

local iface_id_min=1
local iface_id_max=32

SR_DIR="/tmp/special_route/"
SR_CUR_ID="/tmp/special_route/.cur_id"
SR_INFACE_ID="/tmp/special_route/.iface_id"

#为解决bug 964456的特殊处理 在mwan3配置文件内部使用
suffix_logical_iface_name()
{
	local iface="$1"
	if echo $iface | grep -Eq '^WAN[0-9]+_[0-9]+$';then
		iface="${iface:0:3}_V_${iface:3}"
	fi
	echo "$iface"
}

unsuffix_logical_iface_name()
{
	local iface="$1"
	if echo $iface | grep -Eq '^WAN_V_[0-9]+_[0-9]+$';then
		iface="${iface:0:3}${iface:6}"
	fi
	echo "$iface"
}

#$1:inface
specail_route_iface_id_alloc(){
    local iface=$1
	local cur_id

	if [ ! -d "$SR_DIR" ]; then
		mkdir -p $SR_DIR 
	fi
	
	if [ ! -f $SR_CUR_ID ]; then
		#touch $SR_CUR_ID
		echo $iface_id_min > $SR_CUR_ID
	fi

	if [ ! -f $SR_INFACE_ID ]; then
		touch $SR_INFACE_ID
	fi

	ret=`grep "^${iface}=.*" "$SR_INFACE_ID"`
	if [ -n "$ret" ];then
		echo "`cat $SR_INFACE_ID |grep "\<${iface}\>" |cut -d '=' -f 2`"
	else
	    cur_id=`cat $SR_CUR_ID`

		if [ $cur_id -gt 1 ];then
			cur_id=$((cur_id+1)) 
			if [ $cur_id -gt $iface_id_max ]; then
				cur_id=$iface_id_min
		    fi
		fi

		while [ 1 -eq 1 ]
		do		
			local id=`cat $SR_INFACE_ID |grep "${cur_id}$"`
			if [ -z $id  ]; then
			   break;
			else 
			   cur_id=$((cur_id+1))
			   if [ $cur_id -gt $iface_id_max ]; then
			       cur_id=$iface_id_min
			   fi
			fi
		done
		echo $cur_id > $SR_CUR_ID 		

		echo "${iface}=${cur_id}" >> "$SR_INFACE_ID"
		echo "$cur_id"
	fi
}

special_route_set_general_iptables()
{
	if ! $IPT -S TP_sr_rules  &> /dev/null; then
		$IPT -N TP_sr_rules 
	fi

	if ! $IPT -S TP_sr_connected &> /dev/null; then
		$IPT -N TP_sr_connected 
	fi

	{
		flock -x 72
		if ! $IPT -S TP_sr_hook &> /dev/null; then
			$IPT -N TP_sr_hook 
		fi

		if $IPT -S TP_sr_hook &> /dev/null; then
			$IPT -F TP_sr_hook
			#save conneted's mark to all packages
			$IPT -A TP_sr_hook -j CONNMARK --restore-mark --nfmask 0x7f --ctmask 0x7f
			#except the policy_route's packages, the mark is 0x60-0x7F
			#because the policy_route's priority is greater than special_route's
			$IPT -A TP_sr_hook -m conntrack --ctstate NEW -m mark ! --mark 0x60/0x60 -j TP_sr_rules
			#save package's mark to conneted
			$IPT -A TP_sr_hook -j CONNMARK --save-mark --nfmask 0x7f --ctmask 0x7f
			$IPT -A TP_sr_hook -j TP_sr_connected
		fi
		flock -u 72
	} 72<>/tmp/.TP_sr_hook_lock

	if ! $IPT -S TP_sr_post_rules  &> /dev/null; then
		$IPT -N TP_sr_post_rules 
	fi


	{
		flock -x 72

		if ! $IPT -S TP_sr_post_hook &> /dev/null; then
			$IPT -N TP_sr_post_hook
		fi

		if $IPT -S TP_sr_post_hook &> /dev/null; then
			$IPT -F TP_sr_post_hook
			$IPT -A TP_sr_post_hook -m mark ! --mark 0x60/0x60 -j TP_sr_post_rules
			$IPT -A TP_sr_post_hook -j CONNMARK --save-mark --nfmask 0x7f --ctmask 0x7f
		fi
		flock -u 72
	} 72<>/tmp/.TP_sr_post_hook_lock

	if ! $IPT -S POSTROUTING |grep TP_sr_post_hook &>/dev/null; then
		#check the wifidog
		wifidog_income=`$IPT -n --line-number -L POSTROUTING |grep WiFiDog_Incoming`
		if [ -n "$wifidog_income" ];then
			num=`echo $wifidog_income |cut -d " " -f 1`
			$IPT -I POSTROUTING $num -m conntrack --ctstate NEW -j TP_sr_post_hook
		else
			$IPT -A POSTROUTING -m conntrack --ctstate NEW -j TP_sr_post_hook
		fi	
	fi
	
	##policy_route[TP_pr_hook]---->special_route[TP_sr_hook]------>isp_route---->load_balance--->default_balance--->wifidog
	if ! $IPT -S PREROUTING | grep TP_sr_hook &> /dev/null; then
		TP_policy_route=`$IPT -n --line-number -L PREROUTING |grep TP_pr_hook`
		if [ -n "$TP_policy_route" ];then
			num=`echo $TP_policy_route |cut -d " " -f 1`
			let num++
			$IPT -I PREROUTING $num -j TP_sr_hook	
		else
			isp_route=`$IPT -n --line-number -L PREROUTING |grep isp_route`
			if [ -n "$isp_route" ]; then
				num=`echo $isp_route |cut -d " " -f 1`			
				$IPT -I PREROUTING $num -j TP_sr_hook
			else
				load_balance=`$IPT -n --line-number -L PREROUTING |grep load_balance`
				default_balance=`$IPT -n --line-number -L PREROUTING |grep default_balance`
				if [ -n "$load_balance" ]; then
					num=`echo $load_balance |cut -d " " -f 1`			
					$IPT -I PREROUTING $num -j TP_sr_hook
				elif [ -n "$default_balance" ]; then
					num=`echo $default_balance |cut -d " " -f 1`			
					$IPT -I PREROUTING $num -j TP_sr_hook
				else
					#check the wifidog
					local wechat_num=0 trust_num=0 outgo_num=0 min_num=65535
					wifidog_trust=`$IPT -n --line-number -L PREROUTING |grep WiFiDog_Trusted`
					wifidog_outgo=`$IPT -n --line-number -L PREROUTING |grep WiFiDog_Outgoing`
					wifidog_wechat=`$IPT -n --line-number -L PREROUTING |grep WiFiDog_Wechat`

					if [ -n "$wifidog_wechat" ];then
						wechat_num=`echo $wifidog_wechat |cut -d " " -f 1`   
						[ $wechat_num -lt $min_num ] && min_num=$wechat_num
					fi

					if [ -n "$wifidog_trust" ]; then
						trust_num=`echo $wifidog_trust |cut -d " " -f 1`
						[ $trust_num -lt $min_num ] && min_num=$trust_num
					fi

					if [ -n "$wifidog_outgo" ]; then
						outgo_num=`echo $wifidog_outgo |cut -d " " -f 1` 
						[ $outgo_num -lt $min_num ] && min_num=$outgo_num
					fi

					if ! $IPT -S PREROUTING | grep TP_sr_hook &> /dev/null; then
						if [ $min_num -eq 65535 ];then
							$IPT -A PREROUTING -j TP_sr_hook
						else
							$IPT -I PREROUTING $num -j TP_sr_hook
						fi					
					fi
				fi
			fi
		fi
	fi
	
	[ "$ACTION" = "ifdown" ] && $IPT -F TP_sr_rules 
	[ "$ACTION" = "ifdown" ] && $IPT -F TP_sr_post_rules 
}

special_route_set_connected_iptables()
{
	local connected_networks

	if $IPT -S TP_sr_connected  &> /dev/null; then
		$IPT -F TP_sr_connected 

		ipset -! create TP_sr_connected hash:net
		ipset flush TP_sr_connected
		for connected_network in $(ip -4 route | awk '{print $1}' | egrep '[0-9]{1,3}(\.[0-9]{1,3}){3}'); do			
			ipset -! add TP_sr_connected $connected_network
		done

		for connected_network in $(ip -4 route list table 0 | awk '{print $2}' | egrep '[0-9]{1,3}(\.[0-9]{1,3}){3}'); do
			ipset -! add TP_sr_connected $connected_network
		done
		#fix buf Bug 901285: 0x7f is used for ip rule unreachable, 0x7e is free, here used 0x7e.	
		$IPT -A TP_sr_connected -m set --match-set TP_sr_connected dst -j MARK --set-mark 0x7e/0x7f
	fi
}

special_route_set_iface_rules()
{
	local iface_id
	local iface=$1  #尽量减少从zone中获取iface，文件锁效率较低

	iface_id=`specail_route_iface_id_alloc $INTERFACE`

	[ -n "$iface_id" ] || return 0

	if [ $ACTION == "ifdown" ];then
		while [ -n "$(ip -4 rule list | awk '$1 == "'$(($iface_id+3000)):'"')" ]; do
			ip -4 rule del pref $(($iface_id+3000)) &> /dev/null
		done

		while [ -n "$(ip -4 rule list | awk '$1 == "'$(($iface_id+4000)):'"')" ]; do
			ip -4 rule del pref $(($iface_id+4000)) &> /dev/null
		done
	fi

	#iface=`zone_get_effect_ifaces $INTERFACE`
	#[ -z "$iface" ] && return 0
	if [ $ACTION == "ifup" ];then
		state=`balance_get_state $INTERFACE`               
		[ "$state" != "on" or -z "$iface" ] && return 0

		[ -n "$(ip -4 rule list | awk '$1 == "'$(($iface_id+3000)):'"')" ] || ip -4 rule add pref $(($iface_id+3000)) iif $DEVICE lookup main
		[ -n "$(ip -4 rule list | awk '$1 == "'$(($iface_id+4000)):'"')" ] || ip -4 rule add pref $(($iface_id+4000)) fwmark $iface_id/0x7f lookup $iface
	fi       
                          
}


special_route_set_find_mark_iptables()
{
	if ! $IPT -C TP_sr_rules -m mark --mark 0/0x7f -j special_route --mask 0x7f -m comment --comment "Special route find mark" &> /dev/null;then
		$IPT -A TP_sr_rules -m mark --mark 0/0x7f -j special_route --mask 0x7f -m comment --comment "Special route find mark"
	fi
}

special_set_post_policy()
{	
	local iface_id

	local iface=$(unsuffix_logical_iface_name $1)

	state=`balance_get_state $iface`               
	[ "$state" == "on" ] || return 0

	iface_id=`specail_route_iface_id_alloc $iface`

	[ -n "$iface_id" ] || return 0

	device=`zone_get_effect_devices $iface`
	if ! $IPT -C TP_sr_post_rules -o $device -m comment --comment "inface=[$iface]" -j MARK --set-mark $iface_id/0x7f &> /dev/null;then
		$IPT -A TP_sr_post_rules -o $device -m comment --comment "inface=[$iface]" -j MARK --set-mark $iface_id/0x7f
	fi
}

special_route_set_post_iptables()
{
	config_list_foreach $policy use_iface special_set_post_policy
}

#check the iface in use_policy
#flag = 1 inside
#flag = 0 outside
special_route_check()
{
	policy=`uci get mwan3.special_rule.use_policy 2>/dev/null`

	local iface=$(suffix_logical_iface_name $INTERFACE)
	if [ -n  "$policy" ];then
		flag=`uci get mwan3.$iface.balance 2>/dev/null`
	fi
}

#clean the iptables when the policy_ifaces down
special_route_clean_rule()
{
	ifaces=`uci get mwan3.$policy.use_iface 2>/dev/null`
	for iface in $ifaces;do
		local _iface=$(unsuffix_logical_iface_name $iface)
		state=`balance_get_state $_iface`               
		if [ "$state" == "on" ];then
			return
		fi
	done

	$IPT -D PREROUTING -j TP_sr_hook &> /dev/null
	$IPT -D POSTROUTING -m conntrack --ctstate NEW -j TP_sr_post_hook &> /dev/null

	for table in $($IPT -S | awk '{print $2}' | grep TP_sr | sort -u); do
		$IPT -F $table &> /dev/null
	done

	for table in $($IPT -S | awk '{print $2}' | grep TP_sr | sort -u); do
		$IPT -X $table &> /dev/null
	done
}

special_route_ifupdown()
{
	local flag=0 policy 
	local error="table id value is invalid"
	[ -n "$DEVICE" ] || exit 0
	[ -n "$INTERFACE" ] || exit 0

	special_route_check

	#the iface outside of the special_route
	[ $flag -eq 0 ] && exit 0

	local iface=`zone_get_effect_ifaces $INTERFACE`

	if [ $ACTION == "ifup" ]; then
		ret=`ip route list table $iface 2>&1 |grep "$error"`
		[ -n "$ret" ] && exit 0
	fi

	config_load mwan3
	special_route_set_general_iptables	

	special_route_set_iface_rules $iface

	special_route_set_find_mark_iptables 
	
	special_route_set_post_iptables

	special_route_set_connected_iptables

	[ $ACTION == "ifdown" ] && special_route_clean_rule
}

IPT="iptables -t mangle -w"

. /lib/functions.sh
. /lib/zone/zone_api.sh
. /lib/balance/api.sh 

state=`get_balance_global_state`
[ "$state" == "off" ] && return 

state=`uci get mwan3.special_rule.state 2>/dev/null`
[ "$state" == "off" ] && return 

case "$ACTION" in
	ifup|ifdown)
		special_route_ifupdown		
	;;
esac
