forked from
lass.pds.lassul.us/superconfig
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# Check if we're on Darwin
64if [[ "$(uname)" == "Darwin" ]]; then
65 if [[ "$1" == "ssh" ]]; then
66 # Direct SSH call - use old behavior
67 shift # remove 'ssh' from arguments
68 exec ssh -o ProxyCommand="nc -x 127.0.0.1:$SOCKS_PORT %h %p" "$@"
69 else
70 # Other commands - create SSH wrapper and add to PATH
71 SSH_WRAPPER="$TOR_DIR/ssh"
72 cat > "$SSH_WRAPPER" <<EOF
73#!/usr/bin/env bash
74# SSH wrapper that routes through Tor on Darwin
75exec /usr/bin/ssh -o ProxyCommand="nc -x 127.0.0.1:$SOCKS_PORT %h %p" "\$@"
76EOF
77 chmod +x "$SSH_WRAPPER"
78 export PATH="$TOR_DIR:$PATH"
79 fi
80fi
81
82# Execute the command
83export TORSOCKS_TOR_PORT=$SOCKS_PORT
84export TOR_CONTROL_PORT=$CONTROL_PORT
85exec torsocks "$@"