71 lines
1.3 KiB
Bash
Executable File
71 lines
1.3 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
set -xeuo pipefail
|
|
|
|
rtdir=${RUNTIME_DIRECTORY:-/tmp}
|
|
pidfile="$rtdir/tunsocks.pid"
|
|
|
|
nsname="$1"
|
|
device="tun${nsname}"
|
|
ns="${nsname}ns"
|
|
|
|
if [ "$2" = use_env ]; then
|
|
proxy="$SOCKS_PROXY"
|
|
shift
|
|
else
|
|
proxy="socks5:///run/nnss-${nsname}/sock"
|
|
fi
|
|
|
|
setup() {
|
|
ip tuntap add mode tun dev "$device"
|
|
|
|
chan="$rtdir/chan"
|
|
mkfifo "$chan"
|
|
|
|
{
|
|
sleep 10
|
|
echo TIMEOUT >"$chan"
|
|
} &
|
|
timeout_pid=$!
|
|
|
|
done_cmd="sh -c 'echo DONE > \"$chan\"'"
|
|
|
|
/usr/bin/tun2socks -device "$device" -proxy "$proxy" -tun-post-up "$done_cmd" &
|
|
echo "$!" >"$pidfile"
|
|
|
|
read -r status <"$chan"
|
|
|
|
if [ "$status" = DONE ]; then
|
|
kill "$timeout_pid"
|
|
else
|
|
echo "Failed: $status"
|
|
return 1
|
|
fi
|
|
|
|
ip netns add "$ns"
|
|
ip link set "$device" netns "$ns"
|
|
|
|
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
|
|
|
|
systemd-notify --ready
|
|
wait
|
|
}
|
|
|
|
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
|
|
kill "$(cat "$pidfile")"
|
|
ip -n "$ns" tuntap del mode tun dev "$device"
|
|
ip netns del "$ns"
|
|
}
|
|
|
|
$2
|