#! /bin/sh
#
# This script will be called each time a remote peer change its address as
# well as at the beginning of pipsecd.
#
# The arguments on the command line will be the interface name and the real
# remote address.
#

ifname=$1
remaddr=$2

ARP=/usr/sbin/arp
ECHO=/bin/echo
IFCONFIG=/sbin/ifconfig
IPCHAINS=/sbin/ipchains
RM=/bin/rm
ROUTE=/sbin/route

TUNMTU=1440

# Turnon will be called with the tunnel address pair,
# the gateway and the physical interface (opt) by which the real host
# can be reached. If no gateway is specified, no additionnal route
# is added.
turnon () {
    tunloc=$1
    tunrem=$2
    gateway=$3
    physint=$4

    # Turn the interface on before turning it on, to remove the
    # old parameters
    turnoff

    if [ -n "$gateway" -a "$remaddr" != 0.0.0.0 ]; then
	# We have a gateway and a remote address, let's use both
	ip route add $remaddr via $gateway dev $physint
    fi
    ip address add $tunloc peer $tunrem dev $ifname
    ip link set $ifname mtu $TUNMTU
    ip link set $ifname up
    ip neighbour add proxy $tunrem dev eth0
    $IPCHAINS -I output -i $ifname -j ACCEPT
    $IPCHAINS -I forward -d $tunrem -j ACCEPT
    $ECHO 1 > /proc/sys/net/ipv4/ip_forward
    $ECHO 1 > /proc/sys/net/ipv4/conf/$ifname/log_martians
    if [ "$remaddr" != 0.0.0.0 ]; then
	# Input from this interface will be accepted only when it is up
	$IPCHAINS -I input -i $ifname -j ACCEPT
	$IPCHAINS -I forward -s $tunrem -j ACCEPT
	$ECHO 0 > /proc/sys/net/ipv4/conf/$ifname/rp_filter
    fi

    $ECHO "$remaddr $tunloc $tunrem $gateway $physint" > \
	/var/run/pipsecd/$ifname
}

# Turnoff will be called to turn an interface off
turnoff () {
    if [ -f /var/run/pipsecd/$ifname ]; then
	set `cat /var/run/pipsecd/$ifname`
	oldaddr=$1
	oldtunloc=$2
	oldtunrem=$3
	oldgateway=$4
	oldphysint=$5
	rm -f /var/run/pipsecd/$ifname
	if [ -n "$oldgateway" -a "$oldaddr" != 0.0.0.0 ]; then
	    ip route del $oldaddr via $oldgateway dev $oldphysint
	fi
	$IPCHAINS -D input -i $ifname -j ACCEPT
	$IPCHAINS -D output -i $ifname -j ACCEPT
	$IPCHAINS -D forward -s $oldtunrem -j ACCEPT
	$IPCHAINS -D forward -d $oldtunrem -j ACCEPT
    fi
    ip link set $ifname down
}
