lots: shellcheck, streaming stuff, fixes
[distro-setup] / vpn-mail-forward
1 #!/bin/bash
2
3 set -eE -o pipefail
4 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
5 m() { printf "%s\n" "$*"; "$@"; }
6 found=false
7
8 ifname=$1
9 shift
10
11 # wait up to 10 seconds for the gateway to appear
12 for ((i=0; i<10; i++)); do
13 gw=$(/usr/sbin/ip route | sed -rn 's/^default via .* dev (\S+).*/\1/p')
14 if [[ $gw ]]; then
15 found=true
16 fi
17 sleep 1
18 done
19 if ! $found; then
20 echo $0: error: couldnt find gateway interface in 10 seconds >&2
21 exit 1
22 fi
23 do-forward() {
24 cmd=$1; shift
25 for port; do
26 m /sbin/iptables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 10.8.0.4
27 m /sbin/ip6tables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 2600:3c00:e002:3800::4
28 done
29 # for bk to talk to MAIL_HOST, only need port 25.
30 ip6tables -t nat $cmd PREROUTING -i $ifname -s 2600:3c00:e002:3800::5 -d 2600:3c00:e000:280::2 -p tcp -m tcp --dport 25 -j DNAT --to-destination 2600:3c00:e002:3800::4
31 # we could leave these on all the time but its convenient to do it here
32 m /sbin/iptables $cmd FORWARD -i $ifname -o $gw -j ACCEPT
33 m /sbin/iptables $cmd FORWARD -i $gw -o $ifname -j ACCEPT
34
35 case $ifname in
36 wg*)
37 /sbin/iptables -t nat $cmd POSTROUTING -s 10.8.0.0/24 -o $gw -j MASQUERADE
38 /sbin/ip6tables -t nat $cmd POSTROUTING -s 2600:3c00:e002:3800::/64 -o $gw -j MASQUERADE
39 ;;
40 esac
41
42 }
43
44 ports=(25 143 587)
45 case $1 in
46 start)
47 do-forward -A ${ports[@]}
48 ;;
49 stop)
50 do-forward -D ${ports[@]}
51 ;;
52 *)
53 echo "$0: error: expected 1 argument of start or stop"
54 exit 1
55 ;;
56 esac