From 37b120d2e5a550332e6e164b876948113191ae1d Mon Sep 17 00:00:00 2001 From: Balakrishnan Balasubramanian Date: Sat, 1 Mar 2025 17:02:57 -0500 Subject: [PATCH] Replace hardcoded sleep with wait with timeout --- tunsocks.sh | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/tunsocks.sh b/tunsocks.sh index f51e532..a21aa69 100755 --- a/tunsocks.sh +++ b/tunsocks.sh @@ -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"