File size: 7,681 Bytes
0ca462b
 
 
6a81ad7
 
 
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a81ad7
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a81ad7
0ca462b
 
 
6a81ad7
0ca462b
 
 
 
 
6a81ad7
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#![allow(dead_code)]

use anyhow::Result;
use std::process::Command;
use std::time::Duration;
use tracing::{info, warn};

/// Tor integration.
///
/// When compiled with `--features tor`, starts a local Tor daemon and provides
/// a reqwest::Client that routes all HTTP traffic through the Tor SOCKS proxy (127.0.0.1:9050).
/// Without the feature, it's a no-op stub.
pub struct TorManager {
    #[cfg(feature = "tor")]
    tor_client: Option<reqwest::Client>,
    #[cfg(not(feature = "tor"))]
    available: bool,
}

#[cfg(feature = "tor")]
fn start_tor_daemon() -> Result<()> {
    // Check if Tor is already running
    let check = Command::new("nc")
        .args(["-z", "127.0.0.1", "9050"])
        .output();
    if let Ok(out) = check {
        if out.status.success() {
            info!("Tor daemon already running on 127.0.0.1:9050");
            return Ok(());
        }
    }

    info!("Starting Tor daemon with Snowflake bridges (bypasses exit node blocking)...");
    // Ensure directories exist
    std::fs::create_dir_all("/tmp/tor").ok();
    std::fs::create_dir_all("/tmp/tor-data").ok();

    // Tor configuration with Snowflake bridges
    // Snowflake routes traffic through volunteer browsers, making exits appear
    // as regular residential IPs instead of known Tor exit nodes.
    // This bypasses services that block Tor exit nodes (Google, Bing, etc.)
    let tor_config = r#"
# SOCKS proxy for applications
SOCKSPort 127.0.0.1:9050
DataDirectory /tmp/tor-data

# Snowflake bridge configuration
# Routes traffic through volunteer WebRTC peers
# Exit IPs appear as regular residential/consumer IPs
ClientTransportPlugin snowflake exec /usr/bin/snowflake-client -url https://snowflake-broker.torproject.net/ -front https://www.google.com/

# Use Snowflake as bridge
Bridge snowflake 192.0.2.3:1
UseBridges 1

# Prefer circuits through Snowflake bridges
# This gives us diverse, non-blocked exit nodes
ExitNodes {us} {gb} {de} {ca} {nl} {fr} {jp}
StrictNodes 0

# Circuit building settings for reliability
CircuitBuildTimeout 30
LearnCircuitBuildTimeout 1
MaxCircuitDirtiness 600

# Logging (minimal)
Log notice stdout
"#;
    std::fs::write("/tmp/tor/torrc", tor_config)
        .map_err(|e| anyhow::anyhow!("Failed to write torrc: {}", e))?;

    // Check if snowflake-client is available
    let snowflake_available = Command::new("which")
        .arg("snowflake-client")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !snowflake_available {
        info!("Snowflake client not found, using standard Tor with exit node rotation");
        // Fallback: standard Tor with diverse exit nodes
        let fallback_config = r#"
SOCKSPort 127.0.0.1:9050
DataDirectory /tmp/tor-data
ExitNodes {us} {gb} {de} {ca} {nl} {fr} {jp} {au} {se} {no}
StrictNodes 0
CircuitBuildTimeout 30
MaxCircuitDirtiness 300
Log notice stdout
"#;
        std::fs::write("/tmp/tor/torrc", fallback_config)
            .map_err(|e| anyhow::anyhow!("Failed to write torrc: {}", e))?;
    }

    Command::new("tor")
        .args(["-f", "/tmp/tor/torrc"])
        .spawn()
        .map_err(|e| anyhow::anyhow!("Failed to start tor daemon: {}", e))?;

    // Wait for Tor to fully bootstrap (up to 90 seconds)
    // Tor needs to establish circuits through the network before it can route traffic
    for attempt in 0..90 {
        std::thread::sleep(Duration::from_secs(1));
        // Try a simple TCP connection through Tor to verify it's working
        let check = Command::new("nc")
            .args(["-z", "-w", "2", "127.0.0.1", "9050"])
            .output();
        if let Ok(out) = check {
            if out.status.success() {
                // Port is open, but we need to wait for full bootstrap
                // Tor typically takes 20-40 seconds to fully bootstrap
                if attempt >= 20 {
                    info!(
                        "Tor daemon bootstrapped and ready (attempt {})",
                        attempt + 1
                    );
                    return Ok(());
                }
            }
        }
        if attempt % 10 == 9 {
            info!(
                "Waiting for Tor to bootstrap... (attempt {}/{})",
                attempt + 1,
                90
            );
        }
    }

    Err(anyhow::anyhow!(
        "Tor daemon failed to start within 90 seconds"
    ))
}

impl TorManager {
    /// Attempt to initialize a Tor-routed HTTP client.
    /// Never blocks startup — returns a disabled manager if it fails.
    pub async fn new() -> Result<Self> {
        #[cfg(feature = "tor")]
        {
            info!("Initializing Tor-routed HTTP client (SOCKS5 127.0.0.1:9050)...");

            // Start Tor daemon if not already running
            if let Err(e) = start_tor_daemon() {
                warn!(
                    "Tor daemon failed to start: {}. Falling back to proxies.",
                    e
                );
                return Ok(Self { tor_client: None });
            }

            match reqwest::Client::builder()
                .proxy(reqwest::Proxy::all("socks5://127.0.0.1:9050").map_err(|e| anyhow::anyhow!("Failed to create Tor proxy: {}", e))?)
                .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1")
                .timeout(Duration::from_secs(30))
                .connect_timeout(Duration::from_secs(15))
                .pool_idle_timeout(Duration::from_secs(120))
                .build()
            {
                Ok(client) => {
                    // Verify Tor is actually working
                    match client.get("https://check.torproject.org/api/ip").send().await {
                        Ok(resp) if resp.status().is_success() => {
                            let body = resp.text().await.unwrap_or_default();
                            info!("Tor client verified successfully. Response: {}", body.chars().take(100).collect::<String>());
                            Ok(Self { tor_client: Some(client) })
                        }
                        Ok(resp) => {
                            warn!("Tor proxy responded with status {}. Tor may not be fully bootstrapped.", resp.status());
                            Ok(Self { tor_client: Some(client) })
                        }
                        Err(e) => {
                            warn!("Tor verification failed ({}). Tor may not be bootstrapped yet, but client is available.", e);
                            Ok(Self { tor_client: Some(client) })
                        }
                    }
                }
                Err(e) => {
                    warn!("Tor HTTP client creation failed ({}). Tor disabled.", e);
                    Ok(Self { tor_client: None })
                }
            }
        }

        #[cfg(not(feature = "tor"))]
        {
            info!(
                "Tor feature not enabled. Build with `--features tor` for Tor support. \
                 Continuing with public proxies only."
            );
            Ok(Self { available: false })
        }
    }

    pub fn is_available(&self) -> bool {
        #[cfg(feature = "tor")]
        {
            self.tor_client.is_some()
        }
        #[cfg(not(feature = "tor"))]
        {
            self.available
        }
    }

    /// Get a Tor-routed HTTP client. Returns None if Tor is not available.
    pub fn get_client(&self) -> Option<&reqwest::Client> {
        #[cfg(feature = "tor")]
        {
            self.tor_client.as_ref()
        }
        #[cfg(not(feature = "tor"))]
        {
            None
        }
    }
}