--- /dev/null
+#!/bin/sh
+# This script set up source routing for a given interface
+# Argument $1: The gateway
+# Example usage: In /etc/network/interfaces
+# iface eth7 inet static
+# address 192.168.5.42/24
+# /root/source-route-via-v4 192.168.1.15
+
+#set -x
+iface=$LOGICAL
+rttable=from$LOGICAL
+LOGGER="logger -t source-route-via"
+
+$LOGGER -- IFACE=$IFACE LOGICAL=$LOGICAL ADDRFAM=$ADDRFAM METHOD=$METHOD MODE=$MODE PHASE=$PHASE VERBOSITY=$VERBOSITY PATH=$PATH
+
+if ! which ipv4calc >/dev/null
+then
+ echo ipv4calc not found: apt-get install libnetwork-ipv4addr-perl >&2
+ exit 2
+fi
+if ! which ipv6calc >/dev/null
+then
+ echo ipv6calc not found: apt-get install ipv6calc >&2
+ exit 2
+fi
+if test -z "$LOGICAL"
+then
+ echo \$LOGICAL var is empty. >&2
+ exit 2
+fi
+if test "$PHASE" != "post-up"
+then
+ echo $0 is only valid in "post-up". >&2
+ exit 2
+fi
+if test -z "$1"
+then
+ echo Missing gateway parameter. >&2
+ exit 2
+fi
+
+RT_TABLES=/etc/iproute2/rt_tables
+if ! grep -q $rttable /etc/iproute2/rt_tables
+then
+ $LOGGER $RT_TABLES does not have $rttable entry.
+ echo $RT_TABLES does not have $rttable entry. >&2
+ exit 2
+fi
+
+case $ADDRFAM in
+inet)
+ IPFLAG=-4
+ ;;
+inet6)
+ IPFLAG=-6
+ ;;
+*)
+ $LOGGER \$ADDRFAM must be inet or inet6. Ignoring.
+ exit 0
+ ;;
+esac
+IPADDR=$(ip $IPFLAG -o addr show $LOGICAL | grep -w $ADDRFAM | grep global | sed -re "s/.*$ADDRFAM (.*)\/.*/\1/")
+IPCIDR=$(ip -o addr show $LOGICAL | grep -w $ADDRFAM | grep global | sed -re "s/.*$ADDRFAM .*\/([^ ]*).*/\1/")
+if test "$ADDRFAM" = "inet6"
+then
+ IPNET=$(ipv6calc --in ipv6 --out ipv6 --maskprefix $IPADDR/$IPCIDR)
+else
+ IPNET=$(ipv4calc --network $IPADDR/$IPCIDR)/$IPCIDR
+fi
+echo IP address: $IPADDR >&2
+echo CIDR: $IPCIDR >&2
+echo Network: $IPNET >&2
+
+# Setting up source routing on $iface, so that packets from $iface don't get answered on another interface
+if ! ip $IPFLAG route show table $rttable | grep -q default # Once only
+then
+ $LOGGER Setting up default gateway on iproute2 table $rttable
+ $LOGGER -- ip $IPFLAG route add $IPNET dev "$iface" scope link table $rttable
+ ip $IPFLAG route add $IPNET dev "$iface" scope link table $rttable
+ $LOGGER -- ip $IPFLAG route add default via "$1" dev "$iface" table $rttable
+ ip $IPFLAG route add default via "$1" dev "$iface" table $rttable
+fi
+if ! ip $IPFLAG rule show | grep -q $rttable # Once only
+then
+ $LOGGER Setting up source routing on "$iface" from $IPADDR
+ $LOGGER -- ip $IPFLAG rule add from $IPADDR table $rttable
+ ip $IPFLAG rule add from $IPADDR table $rttable
+fi
+
+ip $IPFLAG route flush cache