2 # ip source routing ifupdown script
3 # (C) 2015 Nirgal Vourgère
6 # This script set up source routing for a given interface
7 # Optionnal argument $1: The gateway. If missing, the interface gateway is required.
8 # Example usage: In /etc/network/interfaces
9 # iface eth7 inet static
10 # address 192.168.5.42/24
11 # post-up source-route 192.168.1.1
13 # iface eth7 inet static
14 # address 192.168.5.42/24
16 # post-up source-route
20 LOGGER="logger -t source-route -s"
22 if test "$VERBOSITY" = 1
24 $LOGGER -p user.debug -- IFACE=$IFACE LOGICAL=$LOGICAL ADDRFAM=$ADDRFAM METHOD=$METHOD MODE=$MODE PHASE=$PHASE VERBOSITY=$VERBOSITY PATH=$PATH
27 if ! which ipv4calc >/dev/null
29 $LOGGER -p user.crit -- "ipv4calc not found: apt-get install libnetwork-ipv4addr-perl"
32 if ! which ipv6calc >/dev/null
34 $LOGGER -p user.crit -- "ipv6calc not found: apt-get install ipv6calc"
39 $LOGGER -p user.crit -- "\$IFACE is empty. Are you really running from /etc/network/interfaces ?"
42 if test "$PHASE" != "post-up"
44 $LOGGER -p user.error -- "Invalid \$PHASE. $0 is only valid in 'post-up'. Ignoring."
48 RT_TABLES=/etc/iproute2/rt_tables
49 if ! grep -q $RTTABLE /etc/iproute2/rt_tables
51 $LOGGER -p user.crit -- "$RT_TABLES does not have $RTTABLE entry."
63 $LOGGER -p user.error -- "\$ADDRFAM must be inet or inet6. Ignoring."
67 IPADDR=$(ip $IPFLAG -o addr show $IFACE | grep -w $ADDRFAM | grep global | sed -re "s/.*$ADDRFAM (.*)\/.*/\1/")
68 IPCIDR=$(ip $IPFLAG -o addr show $IFACE | grep -w $ADDRFAM | grep global | sed -re "s/.*$ADDRFAM .*\/([^ ]*).*/\1/")
69 if test "$ADDRFAM" = "inet6"
71 IPNET=$(ipv6calc --in ipv6 --out ipv6 --maskprefix $IPADDR/$IPCIDR)
73 IPNET=$(ipv4calc --network $IPADDR/$IPCIDR)/$IPCIDR
79 IPGW=$(ip $IPFLAG -o route show | grep default | sed -re "s/.*via ([^ ]*) .*/\1/")
83 $LOGGER -p user.crit "Could not find the gateway and none was given."
87 # Setting up source routing on $IFACE, so that packets from $IFACE don't get answered on another interface
88 $LOGGER -- "Setting up source routing on $IFACE: from $IPADDR -> route $IPNET via $IPGW"
90 if ! ip $IPFLAG route show table $RTTABLE | grep -q default # Once only
92 if test "$VERBOSITY" = 1
94 $LOGGER -p user.debug -- ip $IPFLAG route add $IPNET dev "$IFACE" scope link table $RTTABLE
95 $LOGGER -p user.debug -- ip $IPFLAG route add default via "$IPGW" dev "$IFACE" table $RTTABLE
97 ip $IPFLAG route add $IPNET dev "$IFACE" scope link table $RTTABLE
98 ip $IPFLAG route add default via "$IPGW" dev "$IFACE" table $RTTABLE
100 if ! ip $IPFLAG rule show | grep -q $RTTABLE # Once only
102 if test "$VERBOSITY" = 1
104 $LOGGER -p user.debug -- ip $IPFLAG rule add from $IPADDR table $RTTABLE
106 ip $IPFLAG rule add from $IPADDR table $RTTABLE
109 ip $IPFLAG route flush cache