nnss/tunsocks.sh

71 lines
1.3 KiB
Bash
Raw Permalink Normal View History

2025-01-30 15:43:45 -05:00
#!/bin/bash
set -xeuo pipefail
rtdir=${RUNTIME_DIRECTORY:-/tmp}
pidfile="$rtdir/tunsocks.pid"
2025-01-30 15:43:45 -05:00
nsname="$1"
device="tun${nsname}"
ns="${nsname}ns"
2025-02-27 11:05:11 -05:00
2025-03-01 16:56:40 -05:00
if [ "$2" = use_env ]; then
proxy="$SOCKS_PROXY"
shift
2025-02-27 11:05:11 -05:00
else
2025-03-01 16:56:40 -05:00
proxy="socks5:///run/nnss-${nsname}/sock"
2025-02-27 11:05:11 -05:00
fi
2025-01-30 15:43:45 -05:00
2025-03-01 16:56:40 -05:00
setup() {
ip tuntap add mode tun dev "$device"
2025-01-30 15:43:45 -05:00
chan="$rtdir/chan"
mkfifo "$chan"
{
sleep 10
echo TIMEOUT >"$chan"
} &
timeout_pid=$!
done_cmd="sh -c 'echo DONE > \"$chan\"'"
2025-03-01 19:00:11 -05:00
tun2socks -device "$device" -proxy "$proxy" -tun-post-up "$done_cmd" &
2025-03-01 16:56:40 -05:00
echo "$!" >"$pidfile"
read -r status <"$chan"
if [ "$status" = DONE ]; then
kill "$timeout_pid"
else
echo "Failed: $status"
return 1
fi
2025-01-30 15:43:45 -05:00
2025-03-01 16:56:40 -05:00
ip netns add "$ns"
ip link set "$device" netns "$ns"
2025-01-30 15:43:45 -05:00
2025-03-01 16:56:40 -05:00
ip -n "$ns" addr add 198.19.1.1/30 dev "$device"
ip -n "$ns" link set dev "$device" up
ip -n "$ns" route add default via 198.19.1.1 dev "$device" metric 100
ip -n "$ns" link set lo up
2025-03-01 16:56:40 -05:00
systemd-notify --ready
wait
2025-01-30 15:43:45 -05:00
}
2025-03-01 16:56:40 -05:00
cleanup() {
# Cleanup as much as possible. Don't stop on first error
set +e
# If the script failed after creating the device before moving it to namespace
ip tuntap del mode tun dev "$device"
# Regular cleanup when when shutdown normally
2025-03-01 16:56:40 -05:00
kill "$(cat "$pidfile")"
ip -n "$ns" tuntap del mode tun dev "$device"
ip netns del "$ns"
2025-01-30 15:43:45 -05:00
}
$2