Skip to main content

vector_core/i2p/
outproxy.rs

1//! Clearnet hosts over I2P: an I2P stream to an outproxy, then an HTTP CONNECT through it. The
2//! list is the user's, tried in order; health, cooling and refused ports are remembered per
3//! instance only.
4
5use std::collections::HashMap;
6use std::sync::Mutex;
7use std::time::Duration;
8
9use tokio::io::{AsyncReadExt, AsyncWriteExt};
10use tokio::net::TcpStream;
11use web_time::Instant;
12
13use crate::transport::i2p_config::Outproxy;
14use crate::transport::ConnectError;
15
16use super::sam::StreamFail;
17use super::Inner;
18
19const HEAD_CAP: usize = 8 * 1024;
20pub(crate) const HEAD_DEADLINE: Duration = Duration::from_secs(30);
21/// An outproxy that refused a port is not asked for it again for this long.
22const PORT_MEMORY: Duration = Duration::from_secs(6 * 3600);
23const COOL_BASE: Duration = Duration::from_secs(15);
24const COOL_CAP: Duration = Duration::from_secs(600);
25/// A router that just made its sessions hasn't looked the outproxies up yet: an unknown LeaseSet
26/// then is the router's, not the outproxy's.
27pub(crate) const FRESH_SESSION: Duration = Duration::from_secs(60);
28/// Outproxies tried for one connect.
29pub const MAX_ATTEMPTS: usize = 2;
30
31#[derive(Clone, Debug, Default)]
32struct Entry {
33    failures: u32,
34    cooling_until: Option<Instant>,
35    last_ok: Option<u64>,
36    ok_at: Option<Instant>,
37    fault_at: Option<Instant>,
38    last_error: Option<String>,
39    refused_ports: HashMap<u16, Instant>,
40}
41
42impl Entry {
43    fn cooling(&self, now: Instant) -> bool {
44        self.cooling_until.is_some_and(|t| t > now)
45    }
46
47    fn refuses(&self, port: u16) -> bool {
48        self.refused_ports.get(&port).is_some_and(|at| at.elapsed() < PORT_MEMORY)
49    }
50}
51
52#[derive(Default)]
53pub struct Health {
54    map: Mutex<HashMap<String, Entry>>,
55    last_ok: Mutex<Option<String>>,
56}
57
58fn now_secs() -> u64 {
59    crate::clock::now_secs()
60}
61
62fn cool_for(failures: u32) -> Duration {
63    let shift = failures.saturating_sub(1).min(16);
64    COOL_BASE.saturating_mul(1u32 << shift).min(COOL_CAP)
65}
66
67impl Health {
68    fn with<R>(&self, id: &str, f: impl FnOnce(&mut Entry) -> R) -> R {
69        let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner());
70        f(map.entry(id.to_string()).or_default())
71    }
72
73    fn entry(&self, id: &str) -> Entry {
74        self.map.lock().unwrap_or_else(|e| e.into_inner()).get(id).cloned().unwrap_or_default()
75    }
76
77    /// Apply `f`; when what Settings shows for `id` (its state, or which outproxy carried the
78    /// last tunnel) moved, say so: nothing else would refresh it once I2P is up.
79    fn update(&self, id: &str, f: impl FnOnce(&mut Entry)) {
80        let before = (self.state_of(id), self.last_ok());
81        self.with(id, f);
82        if (self.state_of(id), self.last_ok()) != before {
83            crate::transport::host::notify(crate::transport::host::TransportEvent::Changed);
84        }
85    }
86
87    pub fn ok(&self, id: &str) {
88        self.update(id, |e| {
89            e.failures = 0;
90            e.cooling_until = None;
91            e.last_ok = Some(now_secs());
92            e.ok_at = Some(Instant::now());
93            e.last_error = None;
94            *self.last_ok.lock().unwrap_or_else(|e| e.into_inner()) = Some(id.to_string());
95        });
96    }
97
98    /// A dial that began at `started` failed through `id`. Dials that began together and failed
99    /// together are one failure, and one a later success overtook is none: neither says more.
100    pub fn fault(&self, id: &str, why: &str, started: Instant) {
101        self.update(id, |e| {
102            if e.ok_at.is_some_and(|t| t >= started) {
103                return;
104            }
105            e.last_error = Some(why.to_string());
106            if e.fault_at.is_some_and(|t| t >= started) {
107                return;
108            }
109            let now = Instant::now();
110            e.failures = e.failures.saturating_add(1);
111            e.cooling_until = Some(now + cool_for(e.failures));
112            e.fault_at = Some(now);
113        });
114    }
115
116    /// A failure that isn't the outproxy's to answer for: shown, never held against it.
117    pub fn note(&self, id: &str, why: &str) {
118        self.update(id, |e| e.last_error = Some(why.to_string()));
119    }
120
121    pub fn refused_port(&self, id: &str, port: u16, why: &str) {
122        self.update(id, |e| {
123            e.refused_ports.insert(port, Instant::now());
124            e.last_error = Some(why.to_string());
125        });
126    }
127
128    /// The outproxy id that last opened a tunnel on this instance.
129    pub fn last_ok(&self) -> Option<String> {
130        self.last_ok.lock().unwrap_or_else(|e| e.into_inner()).clone()
131    }
132
133    /// Which outproxies to try for `port`, in order: enabled ones that haven't refused the
134    /// port, skipping those cooling down; if all are cooling, the one that cools first.
135    pub fn plan(&self, list: &[Outproxy], port: u16) -> Result<Vec<Outproxy>, ConnectError> {
136        let enabled: Vec<&Outproxy> = list.iter().filter(|o| o.enabled).collect();
137        if enabled.is_empty() {
138            return Err(ConnectError::NoExit);
139        }
140        let now = Instant::now();
141        let open: Vec<(&Outproxy, Entry)> =
142            enabled.into_iter().map(|o| (o, self.entry(&o.id))).filter(|(_, e)| !e.refuses(port)).collect();
143        if open.is_empty() {
144            return Err(ConnectError::ExitRefusedPort(port));
145        }
146        let warm: Vec<Outproxy> = open.iter().filter(|(_, e)| !e.cooling(now)).map(|(o, _)| (*o).clone()).collect();
147        if !warm.is_empty() {
148            return Ok(warm);
149        }
150        let soonest = open.iter().min_by_key(|(_, e)| e.cooling_until).map(|(o, _)| (*o).clone());
151        Ok(soonest.into_iter().collect())
152    }
153
154    /// `ok` (worked last), `unknown` (not tried), `cooling`, or `failing`.
155    pub fn state_of(&self, id: &str) -> &'static str {
156        let e = self.entry(id);
157        if e.cooling(Instant::now()) {
158            "cooling"
159        } else if e.failures > 0 {
160            "failing"
161        } else if e.last_ok.is_some() {
162            "ok"
163        } else {
164            "unknown"
165        }
166    }
167
168    /// `detail.outproxies` of the status view.
169    pub fn view(&self, list: &[Outproxy]) -> serde_json::Value {
170        let now = Instant::now();
171        let mut out = serde_json::Map::new();
172        for o in list {
173            let e = self.entry(&o.id);
174            let mut ports: Vec<u16> = e.refused_ports.iter().filter(|(_, at)| at.elapsed() < PORT_MEMORY).map(|(p, _)| *p).collect();
175            ports.sort_unstable();
176            let cooling_for = e.cooling_until.filter(|t| *t > now).map(|t| t.duration_since(now).as_secs().max(1));
177            out.insert(
178                o.id.clone(),
179                serde_json::json!({
180                    "state": self.state_of(&o.id),
181                    "last_ok": e.last_ok,
182                    "last_error": e.last_error,
183                    "cooling_for": cooling_for,
184                    "refused_ports": ports,
185                }),
186            );
187        }
188        serde_json::Value::Object(out)
189    }
190
191    /// Whether every enabled outproxy is cooling or failing right now.
192    pub fn all_failing(&self, list: &[Outproxy]) -> bool {
193        let enabled: Vec<&Outproxy> = list.iter().filter(|o| o.enabled).collect();
194        !enabled.is_empty() && enabled.iter().all(|o| matches!(self.state_of(&o.id), "cooling" | "failing"))
195    }
196}
197
198/// How an outproxy answered a CONNECT.
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub enum Head {
201    Open,
202    /// 400, 403, 405: it won't carry this port or request.
203    RefusedPort(u16),
204    /// 429, 503: overloaded or rate limited.
205    Overloaded(u16),
206    /// 502, 504: the target is unreachable from the exit.
207    TargetUnreachable(u16),
208    /// Not HTTP, too long, too slow, or a status that makes no sense here.
209    Fault(String),
210}
211
212/// Send the CONNECT and read the response head a byte at a time, so the first tunnel byte stays
213/// in the socket.
214pub async fn handshake(s: &mut TcpStream, host: &str, port: u16, deadline: Duration) -> Head {
215    let req = format!("CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nUser-Agent: MYOB/6.66 (AN/ON)\r\n\r\n");
216    if let Err(e) = s.write_all(req.as_bytes()).await {
217        return Head::Fault(format!("write: {e}"));
218    }
219    match tokio::time::timeout(deadline, read_head(s)).await {
220        Err(_) => Head::Fault("no answer".into()),
221        Ok(Err(e)) => Head::Fault(e),
222        Ok(Ok(head)) => classify(&head),
223    }
224}
225
226async fn read_head(s: &mut TcpStream) -> Result<Vec<u8>, String> {
227    let mut head = Vec::with_capacity(128);
228    let mut b = [0u8; 1];
229    loop {
230        match s.read(&mut b).await {
231            Ok(0) => return Err("closed before answering".into()),
232            Ok(_) => {
233                head.push(b[0]);
234                if head.ends_with(b"\r\n\r\n") || head.ends_with(b"\n\n") {
235                    return Ok(head);
236                }
237                if head.len() >= HEAD_CAP {
238                    return Err("an oversized answer".into());
239                }
240            }
241            Err(e) => return Err(e.to_string()),
242        }
243    }
244}
245
246fn classify(head: &[u8]) -> Head {
247    let text = String::from_utf8_lossy(head);
248    let status = text.lines().next().unwrap_or("");
249    let mut parts = status.split_whitespace();
250    let (Some(proto), Some(code)) = (parts.next(), parts.next()) else {
251        return Head::Fault("not HTTP".into());
252    };
253    if !proto.starts_with("HTTP/1.") {
254        return Head::Fault("not HTTP".into());
255    }
256    let Ok(code) = code.parse::<u16>() else {
257        return Head::Fault("not HTTP".into());
258    };
259    match code {
260        200 => Head::Open,
261        400 | 403 | 405 => Head::RefusedPort(code),
262        429 | 503 => Head::Overloaded(code),
263        502 | 504 => Head::TargetUnreachable(code),
264        other => Head::Fault(format!("answered {other}")),
265    }
266}
267
268/// Reach `host:port` through the list, in order, at most [`MAX_ATTEMPTS`] outproxies. Returns
269/// the open tunnel and the id of the outproxy that carried it. `allowed` is asked again right
270/// before each outproxy is dialed and again before it gets the CONNECT.
271pub(crate) async fn connect(
272    inner: &Inner,
273    nick: &str,
274    list: &[Outproxy],
275    host: &str,
276    port: u16,
277    allowed: &(dyn Fn(&str) -> bool + Send + Sync),
278) -> Result<(TcpStream, String), ConnectError> {
279    let started = Instant::now();
280    let plan = inner.outproxies.plan(list, port)?;
281    let mut tried = 0;
282    let mut all_refused = true;
283    for o in plan.iter().take(MAX_ATTEMPTS) {
284        // Removed or turned off since the plan was made: its operator never sees the CONNECT.
285        if !allowed(&o.id) {
286            continue;
287        }
288        tried += 1;
289        let mut stream = match inner.open_raw(nick, &o.address, o.port).await {
290            Ok(s) => s,
291            // Our own router or session failed: not the outproxy's fault, and no other one
292            // would fare better.
293            Err(StreamFail::RouterDown) => return Err(inner.fail(StreamFail::RouterDown)),
294            Err(StreamFail::SessionGone) => return Err(inner.fail(StreamFail::SessionGone)),
295            Err(e) => {
296                if matches!(e, StreamFail::SessionSuspect(_)) {
297                    if let Some(ours) = ours_failed(inner, nick).await {
298                        return Err(inner.fail(ours));
299                    }
300                    inner.kick.notify_one();
301                }
302                if lookup_pending(inner, &e) {
303                    inner.outproxies.note(&o.id, &stream_text(&e));
304                } else {
305                    inner.outproxies.fault(&o.id, &stream_text(&e), started);
306                }
307                all_refused = false;
308                continue;
309            }
310        };
311        if !allowed(&o.id) {
312            continue;
313        }
314        match handshake(&mut stream, host, port, inner.timing.head_deadline).await {
315            Head::Open => {
316                inner.outproxies.ok(&o.id);
317                return Ok((stream, o.id.clone()));
318            }
319            Head::RefusedPort(code) => inner.outproxies.refused_port(&o.id, port, &format!("refused port {port} ({code})")),
320            Head::Overloaded(code) => {
321                inner.outproxies.fault(&o.id, &format!("busy ({code})"), started);
322                all_refused = false;
323            }
324            Head::TargetUnreachable(code) => {
325                crate::log_debug!("[I2P] {} could not reach {host} ({code})", o.name);
326                return Err(ConnectError::ExitUnreachable(o.name.clone()));
327            }
328            Head::Fault(why) => {
329                if let Some(ours) = ours_failed(inner, nick).await {
330                    return Err(inner.fail(ours));
331                }
332                inner.outproxies.fault(&o.id, &why, started);
333                all_refused = false;
334            }
335        }
336    }
337    if tried > 0 && all_refused {
338        Err(ConnectError::ExitRefusedPort(port))
339    } else {
340        Err(ConnectError::NoExit)
341    }
342}
343
344/// The router hasn't found the outproxy's LeaseSet yet, on a session it only just made.
345fn lookup_pending(inner: &Inner, e: &StreamFail) -> bool {
346    matches!(e, StreamFail::Unreachable(m) if m.to_ascii_lowercase().contains("leaseset"))
347        && inner.session_age().is_some_and(|age| age < inner.timing.fresh_session)
348}
349
350/// A stream that dies without a word may have died with our own router or session: then no
351/// outproxy is to blame, and no other one would fare better.
352async fn ours_failed(inner: &Inner, nick: &str) -> Option<StreamFail> {
353    if !inner.is_ready() {
354        return Some(StreamFail::SessionGone);
355    }
356    match super::sam::liveness(inner.port, inner.auth.as_ref(), nick).await {
357        super::sam::Liveness::RouterDown => Some(StreamFail::RouterDown),
358        super::sam::Liveness::Gone => Some(StreamFail::SessionGone),
359        super::sam::Liveness::Alive | super::sam::Liveness::Inconclusive(_) => None,
360    }
361}
362
363fn stream_text(e: &StreamFail) -> String {
364    match e {
365        StreamFail::Unreachable(m) => format!("unreachable: {m}"),
366        StreamFail::Timeout => "timed out".into(),
367        StreamFail::BadKey => "bad address".into(),
368        StreamFail::SessionSuspect(m) => format!("router: {m}"),
369        StreamFail::RouterDown => "router down".into(),
370        StreamFail::SessionGone => "session gone".into(),
371    }
372}