various important fixes and improvements
[distro-setup] / mail-route
index d130ca966f6f037aa219ab2056858e48843540df..03683651110bd592b9efd72ff860bb21fcbee4a3 100755 (executable)
@@ -34,11 +34,17 @@ case $1 in
     start)
         iptables_op=-A
         ip_op=add
+        tun_dev=$(ip a show to 10.8.0.4/24 | sed -rn '1s/^\S+\s+([^:]+).*/\1/p')
+        if [[ $tun_dev != tun* ]]; then
+            echo "$0: error: failed to find tun device"
+            exit 1
+        fi
         e() { "$@"; }
         ;;
     stop)
         iptables_op=-D
         ip_op=del
+        tun_dev=$(iptables -t nat -S | sed -rn "s/^-A POSTROUTING -o (tun[[:digit:]]+) -m mark --mark 0x1 -j SNAT --to-source 10.8.0.4$/\1/p"|head -n1) || printf "failed to find tun device.\n"
         e() { "$@" || printf "maybe ok failure: %s\n" "$*"; }
         ;;
     show)
@@ -66,13 +72,13 @@ for port in 25 143; do # smtp and imap.
     e iptables -t mangle $iptables_op \
       OUTPUT -m tcp -p tcp -m multiport --ports $port -j MARK --set-mark 0x1
     e iptables -t mangle $iptables_op \
-    OUTPUT -m tcp -p tcp -m multiport --ports $port -j MARK --set-mark 0x0 \
-    -d 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
-# note, we could have used a custom chain and returned instead of setting the mark again.
+      OUTPUT -m tcp -p tcp -m multiport --ports $port -j MARK --set-mark 0x0 \
+      -d 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
+    # note, we could have used a custom chain and returned instead of setting the mark again.
     # in case anyone was ever curious, the inverse of private ips is:   #0.0.0.0/5,8.0.0.0/7,11.0.0.0/8,12.0.0.0/6,16.0.0.0/4,32.0.0.0/3,64.0.0.0/2,128.0.0.0/3,160.0.0.0/5,168.0.0.0/6,172.0.0.0/12,172.32.0.0/11,172.64.0.0/10,172.128.0.0/9,173.0.0.0/8,174.0.0.0/7,176.0.0.0/4,192.0.0.0/9,192.128.0.0/11,192.160.0.0/13,192.169.0.0/16,192.170.0.0/15,192.172.0.0/14,192.176.0.0/12,192.192.0.0/10,193.0.0.0/8,194.0.0.0/7,196.0.0.0/6,200.0.0.0/5,208.0.0.0/4,224.0.0.0/3
 
 done
-e iptables -t nat $iptables_op POSTROUTING -o tun0 -m mark --mark 0x1 -j SNAT --to-source 10.8.0.4
+e iptables -t nat $iptables_op POSTROUTING -o $tun_dev -m mark --mark 0x1 -j SNAT --to-source 10.8.0.4
 e ip rule $ip_op fwmark 1 table 1
 # note, this rule does not persist when the tun interface is deleted
 e ip route $ip_op default via 10.8.0.1 table 1