#!/bin/sh /etc/rc.common
# Copyright (C) 2018 Ycarus (Yannick Chabanois) <ycarus@zugaina.org>

START=99
STOP=10
USE_PROCD=1
EXTRA_COMMANDS="reload_rules bypass_asn"

. /usr/lib/unbound/iptools.sh

_add_proto() {
	protoname=$1
	if [ "$(dd if=/proc/net/xt_ndpi/proto bs=4096 2> /dev/null | grep $protoname)" = "" ]; then
		echo "add_custom $protoname" >/proc/net/xt_ndpi/proto
	fi
	hosts="$( uci -q get omr-bypass.$protoname.url )"
	for url in $hosts; do
		echo "$protoname:$url" >/proc/net/xt_ndpi/host_proto
	done
	ip="$( uci -q get omr-bypass.$protoname.ip )"
	for ip in $ips; do
		echo "$protoname:$ip" >/proc/net/xt_ndpi/ip_proto
	done
}

_bypass_ip() {
	local ip=$1
	local type=$2
	[ -z "$type" ] && type="all"
	valid_ip4=$( valid_subnet4 $ip)
	valid_ip6=$( valid_subnet6 $ip)
	if [ "$valid_ip4" = "ok" ]; then
		ipset -q add omr_dst_bypass_$type $ip
	elif [ "$valid_ip6" = "ok" ]; then
		ipset -q add omr6_dst_bypass_$type $ip
	fi
}

_bypass_domains() {
	local domain
	local intf
	config_get domain $1 name
	config_get intf $1 interface
	_bypass_domain $domain $intf
}

_bypass_domain() {
	local domain=$1
	local intf=$2

	[ -z "$intf" ] && intf="all"
	if [ -n "$domain" ]; then
		domain=$(echo $domain | sed 's:^\.::')
		#logger -t "omr-bypass" "Get IPs of $domain..."
		if [ -z $RELOAD ]; then
			resolve=$(dig a +timeout=1 +nocmd +noall +answer $domain | awk '{print $5}')
			for ip in $resolve; do
				_bypass_ip $ip $intf
			done
			if [ "$disableipv6" != "1" ]; then
				resolve=$(dig aaaa +timeout=1 +nocmd +noall +answer $domain | awk '{print $5}')
				for ip in $resolve; do
					_bypass_ip $ip $intf
				done
			fi
		fi
		if [ "$(uci -q get dhcp.@dnsmasq[0].ipset | grep /$domain/)" = "" ]; then
			uci -q add_list dhcp.@dnsmasq[0].ipset="/$domain/omr_dst_bypass_$intf,omr6_dst_bypass_$intf"
		else
			dnsmasqipset=$(uci -q get dhcp.@dnsmasq[0].ipset | sed 's/ /\n/g')
			for dnsipset in $dnsmasqipset; do
				if [ "$(echo $dnsipset | cut -d/ -f2)" = "$domain" ]; then
					uci -q del_list dhcp.@dnsmasq[0].ipset=$dnsipset
					uci -q add_list dhcp.@dnsmasq[0].ipset="$dnsipset,omr_dst_bypass_$intf,omr6_dst_bypass_$intf"
				fi
			done
		fi
		#logger -t "omr-bypass" "Get IPs of $domain... Done"
	fi
}

_bypass_mac() {
	local mac
	local intf
	config_get mac $1 mac
	config_get intf $1 interface
	local intfid="$(uci -q get omr-bypass.$intf.id)"

	[ -z "$intf" ] && intf="all"
	[ -z "$mac" ] && return
	if [ "$intf" = "all" ]; then
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass -m mac --mac-source $mac -j MARK --set-mark 0x539
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 -m mac --mac-source $mac -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
	else
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass -m mac --mac-source $mac -j MARK --set-mark 0x539$intfid
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 -m mac --mac-source $mac -j MARK --set-mark 0x6539$intfid
			COMMIT
			EOF
		fi
	fi
}

_bypass_lan_ip() {
	local ip
	local intf
	config_get ip $1 ip
	config_get intf $1 interface
	local intfid="$(uci -q get omr-bypass.$intf.id)"

	[ -z "$intf" ] && intf="all"
	[ -z "$ip" ] && return
	valid_ip4=$(valid_subnet4 $ip)
	valid_ip6=$(valid_subnet6 $ip)
	if [ "$intf" = "all" ]; then
		if [ "$valid_ip4" = "ok" ]; then
			iptables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass -s $ip -j MARK --set-mark 0x539
			COMMIT
			EOF
		elif [ "$valid_ip6" = "ok" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 -s $ip -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
	else
		if [ "$valid_ip4" = "ok" ]; then
			iptables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass -s $ip -j MARK --set-mark 0x539$intfid
			COMMIT
			EOF
		elif [ "$valid_ip6" = "ok" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 -s $ip -j MARK --set-mark 0x6539$intfid
			COMMIT
			EOF
		fi
	fi
}

_bypass_dest_port() {
	local intf
	config_get dport $1 dport
	config_get proto $1 proto
	config_get intf $1 interface
	local intfid="$(uci -q get omr-bypass.$intf.id)"

	[ -z "$intf" ] && intf="all"
	[ -z "$dport" ] && return
	dport="$(echo $dport | sed 's/-/:/')"
	[ -z "$proto" ] && return
	if [ "$intf" = "all" ]; then
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass --protocol $proto --destination-port $dport -j MARK --set-mark 0x539
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 --protocol $proto --destination-port $dport -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
	else
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass --protocol $proto --destination-port $dport -j MARK --set-mark 0x539$intfid
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 --protocol $proto --destination-port $dport -j MARK --set-mark 0x6539$intfid
			COMMIT
			EOF
		fi
	fi
}

_bypass_src_port() {
	local intf
	config_get sport $1 sport
	config_get proto $1 proto
	config_get intf $1 interface
	local intfid="$(uci -q get omr-bypass.$intf.id)"

	[ -z "$intf" ] && intf="all"
	[ -z "$sport" ] && return
	sport="$(echo $sport | sed 's/-/:/')"
	[ -z "$proto" ] && return
	if [ "$intf" = "all" ]; then
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass --protocol $proto --source-port $sport -j MARK --set-mark 0x539
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 --protocol $proto --source-port $sport -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
	else
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass --protocol $proto --source-port $sport -j MARK --set-mark 0x539$intfid
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6 --protocol $proto --source-port $sport -j MARK --set-mark 0x6539$intfid
			COMMIT
			EOF
		fi
	fi
}

_bypass_proto() {
	local proto
	local intf
	config_get proto $1 proto
	config_get intf $1 interface
	local intfid="$(uci -q get omr-bypass.$intf.id)"

	[ -z "$intf" ] && intf="all"
	[ -z "$proto" ] && return
	if [ "$intf" = "all" ]; then
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass-dpi -m ndpi --proto $proto -j MARK --set-mark 0x539
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6-dpi -m ndpi --proto $proto -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
	else
		iptables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		-A omr-bypass-dpi -m ndpi --proto $proto -j MARK --set-mark 0x539$intfid
		COMMIT
		EOF
		if [ "$disableipv6" != "1" ]; then
			ip6tables-restore -w --wait=60  --noflush <<-EOF
			*mangle
			-A omr-bypass6-dpi -m ndpi --proto $proto -j MARK --set-mark 0x6539$intfid
			COMMIT
			EOF
		fi
	fi
	# Use dnsmasq ipset to bypass domains of the proto
	local domains
	domains="$(cat /proc/net/xt_ndpi/host_proto | grep $proto: | sed -e "s/$proto://" -e 's/*//' -e 's/,/ /g')"
	if [ -n "$domains" ]; then
		for domain in $domains; do
			if [ -n "$domain" ] && [ "$(uci -q show omr-bypass | grep $domain)" = "" ]; then
				_bypass_domain $domain $intf
			fi
		done
	fi
}

_intf_rule_ss_rules() {
	rule_name=$1
	[ "$rule_name" = "ss_rules" ] && rule_name="default"
	if [ "$(iptables --wait=40 -t nat -L -n | grep ss_rules_${rule_name}_pre_src)" != "" ] && [ "$(iptables --wait=40 -t nat -L -n | grep omr_dst_bypass_$intf)" = "" ]; then
		iptables-restore -w --wait=60 --noflush <<-EOF
		*nat
		-I ss_rules_${rule_name}_dst 1 -m set --match-set omr_dst_bypass_$intf dst -j RETURN
		-I ss_rules_${rule_name}_local_out 1 -m set --match-set omr_dst_bypass_$intf dst -j RETURN
		-I ss_rules_${rule_name}_local_out 2 -m mark --mark 0x539$count -j RETURN
		-I ss_rules_${rule_name}_pre_src 1 -m set --match-set omr_dst_bypass_$intf dst -j MARK --set-mark 0x539$count
		-I ss_rules_${rule_name}_pre_src 2 -m mark --mark 0x539$count -j RETURN
		COMMIT
		EOF
	fi
	if [ "$disableipv6" != "1" ]; then
		if [ "$(ip6tables --wait=40 -t mangle -L | grep omr6_dst_bypass_$intf)" = "" ]; then
			ip6tables-restore -w --wait=60 --noflush <<-EOF
			*mangle
			-I omr-bypass6 1 -m set --match-set omr6_dst_bypass_$intf dst -j MARK --set-mark 0x6539$count
			COMMIT
			EOF
		fi
		if [ "$(ip6tables --wait=40 -t nat -L | grep ss_rules6_${rule_name}_pre_src)" != "" ] && [ "$(ip6tables --wait=40 -t nat -L | grep omr6_dst_bypass_$intf)" = "" ]; then
			ip6tables-restore -w --wait=60 --noflush <<-EOF
			*nat
			-I ss_rules6_${rule_name}_dst 1 -m set --match-set omr6_dst_bypass_$intf dst -j RETURN
			-I ss_rules6_${rule_name}_local_out 1 -m set --match-set omr6_dst_bypass_$intf dst -j RETURN
			-I ss_rules6_${rule_name}_local_out 2 -m mark --mark 0x6539$count -j RETURN
			-I ss_rules6_${rule_name}_pre_src 1 -m set --match-set omr6_dst_bypass_$intf dst -j MARK --set-mark 0x6539$count
			-I ss_rules6_${rule_name}_pre_src 2 -m mark --mark 0x6539$count -j RETURN
			COMMIT
			EOF
		fi
	fi
}

_intf_rule() {
	local intf
	config_get intf $1 ifname
	[ -z "$intf" ] && intf=$(ifstatus "$1" | jsonfilter -q -e '@["l3_device"]')
	#count=$((count+1))
	config_get count $1 metric
	local mode
	#config_get mode $1 multipath "off"
	#[ "$mode" = "off" ] && return
	[ -z "$count" ] && return
	[ -z "$intf" ] && return
	[ "$(echo $1 | grep _dev)" != "" ] && return
	[ -z "$RELOAD" ] || [ "$(ipset --list | grep omr_dst_bypass_$intf)" = "" ] && {
		unset RELOAD
		ipset -q flush omr_dst_bypass_$intf > /dev/null 2>&1
		ipset -q flush omr6_dst_bypass_$intf > /dev/null 2>&1
		ipset -q --exist restore <<-EOF
		create omr_dst_bypass_$intf hash:net hashsize 64
		create omr6_dst_bypass_$intf hash:net family inet6 hashsize 64
		EOF
		if [ "$(uci -q get openmptcprouter.settings.uci_rules)" = "1" ]; then
			uci -q batch <<-EOF >/dev/null
				delete network.${1}_fw_rule=rule
				set network.${1}_fw_rule=rule
				set network.${1}_fw_rule.priority=1
				set network.${1}_fw_rule.mark=0x539${count}
				set network.${1}_fw_rule.lookup=${count}
				delete network.${1}_fw_rule6=rule6
				set network.${1}_fw_rule6=rule6
				set network.${1}_fw_rule6.priority=1
				set network.${1}_fw_rule6.mark=0x6539${count}
				set network.${1}_fw_rule6.lookup=${count}
				commit network
			EOF
		else
			ip rule add prio 1 fwmark 0x539$count lookup $count pref 1 > /dev/null 2>&1
			ip -6 rule add prio 1 fwmark 0x6539$count lookup 6$count > /dev/null 2>&1
		fi
	}
	if [ "$(iptables --wait=40 -t mangle -L -n | grep omr_dst_bypass_$intf)" = "" ]; then
		iptables-restore -w --wait=60 --noflush <<-EOF
		*mangle
		-I omr-bypass 1 -m set --match-set omr_dst_bypass_$intf dst -j MARK --set-mark 0x539$count
		COMMIT
		EOF
	fi
	config_load shadowsocks-libev
	config_foreach _intf_rule_ss_rules ss_rules

	uci -q set omr-bypass.$intf=interface
	uci -q set omr-bypass.$intf.id=$count
}

_bypass_ip_set() {
	local ip
	local interface
	config_get ip $1 ip
	config_get interface $1 interface
	_bypass_ip $ip $interface
}

_bypass_asn() {
	local asn
	local interface
	config_get asn $1 asn
	config_get interface $1 interface
	local asnips
	asnips=`curl --max-time 4 -s -k https://stat.ripe.net/data/announced-prefixes/data.json?resource=${asn} | jsonfilter -q -e '@.data.prefixes.*.prefix'`
	for ip in $asnips; do
		_bypass_ip $ip $interface
	done

}

bypass_asn() {
	config_load omr-bypass
	config_foreach _bypass_asn asns
}

_bypass_omr_server() {
	local ip
	config_get ip $1 ip
	_bypass_ip $ip
}


_ss_rules_config() {
	rule_name=$1
	[ "$rule_name" = "ss_rules" ] && rule_name="default"
	if [ "$(iptables --wait=40 -t nat -L -n | grep ss_rules_${rule_name}_pre_src)" != "" ] && [ "$(iptables --wait=40 -t nat -L -n | grep omr_dst_bypass_all)" = "" ]; then
		iptables-restore -w --wait=60 --noflush <<-EOF
		*nat
		-I ss_rules_${rule_name}_dst 1 -m set --match-set omr_dst_bypass_all dst -j RETURN
		-I ss_rules_${rule_name}_local_out 1 -m set --match-set omr_dst_bypass_all dst -j RETURN
		-I ss_rules_${rule_name}_local_out 2 -m mark --mark 0x539 -j RETURN
		-I ss_rules_${rule_name}_pre_src 1 -m set --match-set omr_dst_bypass_all dst -j MARK --set-mark 0x539
		-I ss_rules_${rule_name}_pre_src 2 -m mark --mark 0x539 -j RETURN
		COMMIT
		EOF
	fi
	if [ "$disableipv6" != "1" ]; then
		if [ "$(ip6tables --wait=40 -t mangle -L | grep 'match-set omr6_dst_bypass_all dst MARK set')" = "" ]; then
			ip6tables-restore -w --wait=60 --noflush <<-EOF
			*mangle
			-A omr-bypass6 -m set --match-set omr6_dst_bypass_all dst -j MARK --set-mark 0x6539
			COMMIT
			EOF
		fi
		if [ "$(ip6tables --wait=40 -t nat -L | grep ss_rules6_default_pre_src)" != "" ] && [ "$(ip6tables --wait=40 -t nat -L | grep omr6_dst_bypass_all)" = "" ]; then
			ip6tables-restore -w --wait=60 --noflush <<-EOF
			*nat
			-I ss_rules6_${rule_name}_dst 1 -m set --match-set omr6_dst_bypass_all dst -j RETURN
			-I ss_rules6_${rule_name}_local_out 1 -m set --match-set omr6_dst_bypass_all dst -j RETURN
			-I ss_rules6_${rule_name}_local_out 2 -m mark --mark 0x6539 -j RETURN
			-I ss_rules6_${rule_name}_pre_src 1 -m set --match-set omr6_dst_bypass_all dst -j MARK --set-mark 0x6539
			-I ss_rules6_${rule_name}_pre_src 2 -m mark --mark 0x6539 -j RETURN
			COMMIT
			EOF
		fi
	fi
}

boot() {
	BOOT=1
	start "$@"
}

start_service() {
	#local count
	logger -t "omr-bypass" "Starting OMR-ByPass..."
	config_load omr-bypass
	config_foreach _add_proto proto
	disableipv6="$(uci -q get openmptcprouter.settings.disable_ipv6)"

	[ -n "$RELOAD" ] && [ "$(ipset --list | grep omr_dst_bypass_all)" = "" ] && {
		unset RELOAD
	}
	[ -z "$RELOAD" ] && {
		ipset -q flush omr_dst_bypass_all > /dev/null 2>&1
		ipset -q flush omr6_dst_bypass_all > /dev/null 2>&1
		ipset -q --exist restore <<-EOF
		create omr_dst_bypass_all hash:net hashsize 64
		create omr6_dst_bypass_all hash:net family inet6 hashsize 64
		EOF
	}
	iptables-save --counters | grep -v omr-bypass | iptables-restore -w --counters
	iptables-restore -w --wait=60  --noflush <<-EOF
	*mangle
	:omr-bypass -
	-I PREROUTING 1 -m addrtype ! --dst-type LOCAL -j omr-bypass
	COMMIT
	EOF
	if [ "$disableipv6" != "1" ]; then
		ip6tables-save --counters | grep -v omr-bypass6 | ip6tables-restore -w --counters
		ip6tables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		:omr-bypass6 -
		-I PREROUTING 1 -m addrtype ! --dst-type LOCAL -j omr-bypass6
		COMMIT
		EOF
	fi
	
	config_load network
	config_foreach _intf_rule interface
	local ndpi_rules=""
	config_load openmptcprouter
	config_foreach _bypass_omr_server server
	config_load omr-bypass
	config_foreach _bypass_ip_set ips
	config_foreach _bypass_mac macs
	config_foreach _bypass_lan_ip lan_ip
	config_foreach _bypass_dest_port dest_port
	config_foreach _bypass_src_port src_port
	config_foreach _bypass_asn asns
	dnsmasqipset=$(uci -q get dhcp.@dnsmasq[0].ipset | sed 's/ /\n/g' | grep -v dst_bypass)
	uci -q delete dhcp.@dnsmasq[0].ipset
	if [ -n "$dnsmasqipset" ]; then
		for dnsipset in $dnsmasqipset; do
			ipsets=""
			allipsets=$(echo $dnsipset | cut -d/ -f3 | sed 's/,/\n/g')
			for ipset in $allipsets; do
				[ "$(echo $ipset | grep -v dst_bypass)" != "" ] && {
					[ "$ipsets" != "" ] && ipsets="$ipsets,$ipset"
					[ "$ipsets" = "" ] && ipsets="$ipset"
				}
			done
			if [ "$ipsets" != "" ]; then
				resultipset="/$(echo $dnsipset | cut -d/ -f2)/$ipsets"
				uci -q add_list dhcp.@dnsmasq[0].ipset=$resultipset
			fi
		done
	fi
	config_foreach _bypass_domains domains
	uci -q commit dhcp

	ip rule add prio 1 fwmark 0x539 lookup 991337 > /dev/null 2>&1
	ip -6 rule add prio 1 fwmark 0x6539 lookup 6991337 > /dev/null 2>&1

	if [ "$(iptables --wait=40 -t mangle -L -n | grep 'match-set omr_dst_bypass_all dst MARK set')" = "" ]; then
		iptables-restore -w --wait=60 --noflush <<-EOF
		*mangle
		-A omr-bypass -m set --match-set omr_dst_bypass_all dst -j MARK --set-mark 0x539
		COMMIT
		EOF
	fi

	config_load shadowsocks-libev
	config_foreach _ss_rules_config

	iptables-save --counters | grep -v omr-bypass-dpi | iptables-restore -w --counters
	iptables-restore -w --wait=60  --noflush <<-EOF
	*mangle
	:omr-bypass-dpi -
	-A PREROUTING -m addrtype ! --dst-type LOCAL -j omr-bypass-dpi
	-A POSTROUTING -m addrtype --dst-type LOCAL -j omr-bypass-dpi
	COMMIT
	EOF
	if [ "$disableipv6" != "1" ]; then
		ip6tables-save --counters | grep -v omr-bypass6-dpi | ip6tables-restore -w --counters
		ip6tables-restore -w --wait=60  --noflush <<-EOF
		*mangle
		:omr-bypass6-dpi -
		-A PREROUTING -m addrtype ! --dst-type LOCAL -j omr-bypass6-dpi
		-A POSTROUTING -m addrtype --dst-type LOCAL -j omr-bypass6-dpi
		COMMIT
		EOF
	fi
	config_load omr-bypass
	config_foreach _bypass_proto dpis

	[ -z "$RELOAD" ] && {
		logger -t "omr-bypass" "Restart dnsmasq..."
		/etc/init.d/dnsmasq restart
	}
	[ -n "$RELOAD" ] && {
		logger -t "omr-bypass" "Reload dnsmasq..."
		/etc/init.d/dnsmasq reload
	}
	logger -t "omr-bypass" "OMR-ByPass is running"
}

stop_service() {
	iptables-save --counters | grep -v omr-bypass | iptables-restore -w --counters
	iptables-save --counters | grep -v omr_dst | iptables-restore -w --counters
	ip6tables-save --counters | grep -v omr-bypass6 | ip6tables-restore -w --counters
	ip6tables-save --counters | grep -v omr6_dst | ip6tables-restore -w --counters
	for setname in $(ipset -n list | grep "omr_"); do
		ipset destroy "$setname" 2>/dev/null || true
	done
}

service_triggers() {
	PROCD_RELOAD_DELAY=1000
	procd_add_reload_trigger omr-bypass
	procd_add_raw_trigger "interface.*" 2000 /etc/init.d/omr-bypass restart
}

reload_service() {
	start
}

reload_rules() {
	[ "$( ipset -n list | grep omr_ )" = "" ] && return 0
	RELOAD=1
	start
}
