#!/bin/sh /etc/rc.common
# Copyright (C) 2008 OpenWrt.org

IPTABLES=ip6tables

fw6_setrule(){
	local SET_S_IP=
	local SET_D_IP=
	local SET_s_PORT=
	local SET_D_PORT=

	local sip_type
	local sip
	local smask
	local smask_len	
	local dip_type
	local dip
	local dmask
	local dmask_len
	local proto
	local sport1
	local sport2
	local dport1
	local dport2
	local action	
	
	#IP setting
	config_get sip_type $1 sip_type
	config_get sip $1 sip
	config_get smask $1 smask
	config_get smask_len $1 smask_len
	config_get dip_type $1 dip_type
	config_get dip $1 dip
	config_get dmask $1 dmask
	config_get dmask_len $1 dmask_len
	
	#protocol and port
	config_get proto $1 proto
	config_get sport1 $1 sport1
	config_get sport2 $1 sport2
	config_get dport1 $1 dport1
	config_get dport2 $1 dport2
	config_get action $1 action
	
	#sip type: none, single, subnet 
	if [ "$sip_type" = "single" ]; then
		SET_S_IP="-s $sip"
	elif [ "$sip_type" = "subnet" ]; then
		SET_S_IP="-s $smask/$smask_len"
	fi
	#dip type: none, single, subnet 
	if [ "$dip_type" = "single" ]; then
		SET_D_IP="-d $dip"
	elif [ "$dip_type" = "subnet" ]; then
		SET_D_IP="-d $dmask/$dmask_len"
	fi
	
	#protocol tcp or udp has port
	if [ "$proto" = "tcp" -o "$proto" = "udp" ]; then
		#sport:  single, range 
		if [ "$sport1" != "" -a "$sport2" != "" ]; then
			SET_S_PORT="--sport $sport1:$sport2"
		elif [ "$sport1" != "" ]; then  
			SET_S_PORT="--sport $sport1"
		fi
		#dport:  single, range 
		if [ "$dport1" != "" -a "$dport2" != "" ]; then
			SET_D_PORT="--dport $dport1:$dport2"
		elif [ "$dport1" != "" ]; then
			SET_D_PORT="--dport $dport1"
		fi
	fi
	
	$IPTABLES -A FORWARD $SET_S_IP $SET_D_IP -p $proto $SET_S_PORT $SET_D_PORT -j $action
}

fw6_defaults() {
	[ -n "$DEFAULTS_APPLIED" ] && {
		echo "Error: multiple defaults sections detected"
		return;
	}
	DEFAULTS_APPLIED=1
	
	$IPTABLES -F FORWARD
	$IPTABLES -t mangle -F
	$IPTABLES -t raw -F
	
	if [ -f /etc/config/firewall6 ]; then	
		config_load firewall6
		config_foreach fw6_setrule fw6_rule 
	fi
	#default reject tcp/udp new connection from WAN
	ip6tables -A FORWARD -i sit+ -m state --state NEW -j DROP
}

fw6_init() {
	DEFAULTS_APPLIED=
	lock /var/lock/lock_firewall6
	fw6_defaults	
	lock -u /var/lock/lock_firewall6
}

fw6_stop() {
	lock /var/lock/lock_firewall6
	$IPTABLES -F FORWARD
	$IPTABLES -t mangle -F
	$IPTABLES -t raw -F
	lock -u /var/lock/lock_firewall6
}


#ipv6 firewall start
start() {
	fw6_init
}

#ipv6 firewall stop
stop() {
	fw6_stop	
}