Replace hardcoded sleep with wait with timeout

This commit is contained in:
Balakrishnan Balasubramanian 2025-03-01 17:02:57 -05:00
parent ba4bbfa18c
commit 37b120d2e5

View File

@ -2,7 +2,8 @@
set -xeuo pipefail
pidfile=${RUNTIME_DIRECTORY:-/tmp}/tunsocks.pid
rtdir=${RUNTIME_DIRECTORY:-/tmp}
pidfile="$rtdir/tunsocks.pid"
nsname="$1"
device="tun${nsname}"
@ -18,9 +19,28 @@ fi
setup() {
ip tuntap add mode tun dev "$device"
/usr/bin/tun2socks -device "$device" -proxy "$proxy" &
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"
sleep 5
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"
@ -29,12 +49,19 @@ setup() {
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() {
ip tuntap del mode tun dev "$device" || true
# 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"