This repository has no description
2.3 kB
85 lines
1#!/usr/bin/env bash
2set -euo pipefail
3
4# Create temporary directory for this tor instance
5TOR_DIR=$(mktemp -d -t tornade.XXXXXX)
6
7# Generate random ports in ephemeral range (49152-65535) to avoid collisions
8SOCKS_PORT=$((49152 + RANDOM % 16383))
9CONTROL_PORT=$((SOCKS_PORT + 1))
10
11# Track tor PID for cleanup
12TOR_PID=""
13
14# Cleanup function - must be defined before trap
15cleanup() {
16 if [ -n "$TOR_PID" ] && kill -0 "$TOR_PID" 2>/dev/null; then
17 kill "$TOR_PID" 2>/dev/null || true
18 wait "$TOR_PID" 2>/dev/null || true
19 fi
20 rm -rf "$TOR_DIR"
21}
22trap cleanup EXIT INT TERM
23
24# Create tor configuration
25cat > "$TOR_DIR/torrc" <<EOF
26DataDirectory $TOR_DIR/data
27SocksPort 127.0.0.1:$SOCKS_PORT
28ControlPort 127.0.0.1:$CONTROL_PORT
29Log notice file $TOR_DIR/tor.log
30RunAsDaemon 0
31
32# Hidden service optimizations - longer timeouts for .onion addresses
33CircuitBuildTimeout 60
34LearnCircuitBuildTimeout 0
35SocksTimeout 300
36
37# Keep circuits stable for longer sessions
38MaxCircuitDirtiness 900
39KeepalivePeriod 60
40EOF
41
42# Start tor in background - suppress output to avoid protocol interference
43tor -f "$TOR_DIR/torrc" >/dev/null 2>&1 &
44TOR_PID=$!
45
46# Wait for Tor to bootstrap (up to 90 seconds)
47for i in {1..90}; do
48 if [ -f "$TOR_DIR/tor.log" ] && grep -q "Bootstrapped 100%" "$TOR_DIR/tor.log" 2>/dev/null; then
49 break
50 fi
51 # If log file doesn't exist after 5 seconds, tor likely failed to start
52 if [ "$i" -eq 5 ] && [ ! -f "$TOR_DIR/tor.log" ]; then
53 exit 1
54 fi
55 sleep 1
56done
57
58# Final check - if still not ready after all attempts, exit
59if ! grep -q "Bootstrapped 100%" "$TOR_DIR/tor.log" 2>/dev/null; then
60 exit 1
61fi
62
63# Execute the command (don't use exec - need cleanup trap to run)
64export TORSOCKS_TOR_PORT=$SOCKS_PORT
65export TOR_CONTROL_PORT=$CONTROL_PORT
66
67if [[ "$(uname)" == "Darwin" ]]; then
68 if [[ "$1" == "ssh" ]]; then
69 # Direct SSH call via nc SOCKS proxy
70 shift
71 ssh -o ProxyCommand="nc -x 127.0.0.1:$SOCKS_PORT %h %p" "$@"
72 else
73 # Other commands - create SSH wrapper and add to PATH
74 SSH_WRAPPER="$TOR_DIR/ssh"
75 cat > "$SSH_WRAPPER" <<'SSHEOF'
76#!/usr/bin/env bash
77exec /usr/bin/ssh -o ProxyCommand="nc -x 127.0.0.1:$TORSOCKS_TOR_PORT %h %p" "$@"
78SSHEOF
79 chmod +x "$SSH_WRAPPER"
80 PATH="$TOR_DIR:$PATH" torsocks "$@"
81 fi
82else
83 torsocks "$@"
84fi
85# cleanup trap runs on exit