Skip to main content

vector_core/i2p/
keeper.rs

1//! The session keeper: one task per instance that finds the router, opens both lane sessions,
2//! watches them, and starts over with backoff whenever they go. Never sends PING: i2pd answers
3//! it and then destroys the session.
4
5use std::sync::atomic::Ordering;
6use std::sync::Arc;
7use std::time::Duration;
8
9use web_time::Instant;
10
11use super::sam::{self, ControlEvent, ControlSocket, HelloError, Liveness};
12use super::{I2pPhase, Inner, Sessions};
13
14struct Backoff {
15    steps: Vec<Duration>,
16    i: usize,
17}
18
19impl Backoff {
20    fn new(steps: &[Duration]) -> Self {
21        Backoff { steps: steps.to_vec(), i: 0 }
22    }
23
24    fn next(&mut self) -> Duration {
25        let d = self.steps.get(self.i).or(self.steps.last()).copied().unwrap_or(Duration::from_secs(60));
26        self.i = (self.i + 1).min(self.steps.len().saturating_sub(1));
27        d
28    }
29
30    fn reset(&mut self) {
31        self.i = 0;
32    }
33}
34
35/// Sleep `d`, cut short by a kick or by the owner leaving the screen.
36async fn rest(inner: &Inner, d: Duration) {
37    tokio::select! {
38        _ = tokio::time::sleep(d) => {}
39        _ = inner.kick.notified() => {}
40        _ = wait_owner_gone(inner) => {}
41    }
42}
43
44/// Resolves once something accepts on the SAM port: a bare loopback connect, nothing sent, so a
45/// router that comes back is noticed within seconds instead of at the end of a long backoff.
46async fn router_back(inner: &Inner) {
47    loop {
48        tokio::time::sleep(inner.timing.port_watch).await;
49        if tokio::net::TcpStream::connect((sam::SAM_HOST, inner.port)).await.is_ok() {
50            return;
51        }
52    }
53}
54
55/// Hold no router sessions while the owning account is off screen.
56async fn park(inner: &Arc<Inner>) {
57    inner.set_sessions(None);
58    inner.set_phase(I2pPhase::Parked, false);
59    while !inner.owner_live() {
60        let since = crate::transport::epoch();
61        tokio::select! {
62            _ = crate::transport::changed(since) => {}
63            _ = inner.kick.notified() => {}
64            _ = tokio::time::sleep(Duration::from_secs(60)) => {}
65        }
66    }
67}
68
69enum WatchEnd {
70    Lost,
71    Renew,
72    Parked,
73}
74
75pub(crate) async fn run(inner: Arc<Inner>) {
76    let mut backoff = Backoff::new(&inner.timing.backoff);
77    let mut ever_ready = false;
78    let mut skip_probe = false;
79    // After a failure, a retry probe keeps the waiting phase (and its reason) until the router
80    // answers: a quarter second of "starting" per retry only makes the UI blink.
81    let mut waiting = false;
82    loop {
83        if !inner.owner_live() {
84            park(&inner).await;
85            waiting = false;
86            continue;
87        }
88        if !skip_probe {
89            if !waiting {
90                inner.set_phase(I2pPhase::Probing, false);
91            }
92            match sam::hello(inner.port, inner.auth.as_ref()).await {
93                Ok((s, v)) => {
94                    drop(s);
95                    inner.set_router(true, Some(v));
96                }
97                Err(e) => {
98                    let (wait, phase) = rejection(&inner, &e, &mut backoff);
99                    let refused = e == HelloError::Refused;
100                    inner.set_router(false, None);
101                    inner.set_phase(phase, false);
102                    waiting = true;
103                    if refused {
104                        tokio::select! {
105                            _ = rest(&inner, wait) => {}
106                            _ = router_back(&inner) => {}
107                        }
108                    } else {
109                        rest(&inner, wait).await;
110                    }
111                    continue;
112                }
113            }
114        }
115        skip_probe = false;
116        waiting = false;
117
118        let since = Instant::now();
119        inner.set_phase(I2pPhase::CreatingSessions { since }, false);
120        let (acct_nick, shared_nick) = (sam::new_nick(), sam::new_nick());
121        let both = async {
122            tokio::join!(
123                sam::create_session(inner.port, inner.auth.as_ref(), &acct_nick),
124                sam::create_session(inner.port, inner.auth.as_ref(), &shared_nick),
125            )
126        };
127        let created = tokio::select! {
128            r = tokio::time::timeout(inner.timing.session_cap, both) => r,
129            _ = wait_owner_gone(&inner) => continue,
130        };
131        let (mut acct, mut shared) = match created {
132            Ok((Ok(a), Ok(s))) => (a, s),
133            Ok((a, s)) => {
134                let why = a.err().or(s.err()).unwrap_or_default();
135                crate::log_warn!("[I2P] the router couldn't open a session: {why}");
136                let wait = backoff.next();
137                inner.set_phase(I2pPhase::SessionFailed { next: Instant::now() + wait, why }, false);
138                waiting = true;
139                rest(&inner, wait).await;
140                continue;
141            }
142            Err(_) => {
143                let wait = backoff.next();
144                inner.set_phase(I2pPhase::SessionFailed { next: Instant::now() + wait, why: "timed out".into() }, false);
145                waiting = true;
146                rest(&inner, wait).await;
147                continue;
148            }
149        };
150        if !inner.owner_live() {
151            continue;
152        }
153        crate::log_info!("[I2P] sessions ready after {:.1}s", since.elapsed().as_secs_f64());
154        inner.set_sessions(Some(Sessions {
155            account: acct_nick.clone(),
156            shared: shared_nick.clone(),
157            account_address: acct.address().map(str::to_string),
158            shared_address: shared.address().map(str::to_string),
159        }));
160        inner.renew.store(false, Ordering::Release);
161        inner.set_phase(I2pPhase::Ready { since: Instant::now() }, ever_ready);
162        ever_ready = true;
163        backoff.reset();
164        crate::transport::twins::check_pending();
165
166        let end = watch(&inner, &acct_nick, &shared_nick, &mut acct, &mut shared).await;
167        inner.set_sessions(None);
168        drop(acct);
169        drop(shared);
170        match end {
171            WatchEnd::Renew => {
172                inner.set_phase(I2pPhase::Lost { next: Instant::now() }, false);
173                inner.renewed.notify_waiters();
174                skip_probe = true;
175            }
176            WatchEnd::Lost => {
177                let wait = backoff.next();
178                inner.set_phase(I2pPhase::Lost { next: Instant::now() + wait }, false);
179                waiting = true;
180                rest(&inner, wait).await;
181            }
182            WatchEnd::Parked => {}
183        }
184    }
185}
186
187async fn wait_owner_gone(inner: &Inner) {
188    while inner.owner_live() {
189        let since = crate::transport::epoch();
190        crate::transport::changed(since).await;
191    }
192}
193
194fn rejection(inner: &Inner, e: &HelloError, backoff: &mut Backoff) -> (Duration, I2pPhase) {
195    let port = inner.port;
196    let rejected = |wait: Duration, code: &'static str, text: String| {
197        (wait, I2pPhase::SamRejected { next: Instant::now() + wait, code, text })
198    };
199    match e {
200        // A silent port may be a router still waking: the backoff, not the not-SAM wait.
201        HelloError::Refused | HelloError::Timeout | HelloError::Silent => {
202            let wait = backoff.next();
203            (wait, I2pPhase::RouterUnreachable { next: Instant::now() + wait })
204        }
205        HelloError::NotSam => {
206            rejected(inner.timing.not_sam, "sam_refused", format!("The service on port {port} isn't an I2P SAM bridge."))
207        }
208        HelloError::NoVersion(v) => rejected(inner.timing.rejected, "sam_too_old", sam::too_old_text(v)),
209        HelloError::AuthRequired => {
210            rejected(inner.timing.rejected, "sam_auth_required", "Your router asks for a SAM username and password.".into())
211        }
212        HelloError::AuthFailed => {
213            rejected(inner.timing.rejected, "sam_auth_failed", "Your router turned down the SAM username or password.".into())
214        }
215    }
216}
217
218/// Watch both sessions until one goes, the owner leaves the screen, or new addresses are asked
219/// for. Liveness runs every `watch` interval and at once on a kick.
220async fn watch(inner: &Arc<Inner>, acct_nick: &str, shared_nick: &str, acct: &mut ControlSocket, shared: &mut ControlSocket) -> WatchEnd {
221    let mut quiet_until: Option<Instant> = None;
222    loop {
223        let event = tokio::select! {
224            _ = tokio::time::sleep(inner.timing.watch) => None,
225            _ = inner.kick.notified() => None,
226            _ = wait_owner_gone(inner) => None,
227            e = acct.next_event() => Some((true, e)),
228            e = shared.next_event() => Some((false, e)),
229        };
230        match event {
231            Some((_, ControlEvent::Closed(why))) => {
232                crate::log_warn!("[I2P] a session closed: {why}");
233                return WatchEnd::Lost;
234            }
235            Some((is_acct, ControlEvent::Ping(text))) => {
236                let sock = if is_acct { &mut *acct } else { &mut *shared };
237                if sock.pong(&text).await.is_err() {
238                    return WatchEnd::Lost;
239                }
240                continue;
241            }
242            Some((_, ControlEvent::Other)) => continue,
243            None => {}
244        }
245        if !inner.owner_live() {
246            return WatchEnd::Parked;
247        }
248        if inner.renew.swap(false, Ordering::AcqRel) {
249            return WatchEnd::Renew;
250        }
251        let (a, s) = tokio::join!(
252            sam::liveness(inner.port, inner.auth.as_ref(), acct_nick),
253            sam::liveness(inner.port, inner.auth.as_ref(), shared_nick),
254        );
255        for l in [&a, &s] {
256            match l {
257                Liveness::Gone => {
258                    inner.set_router(true, None);
259                    return WatchEnd::Lost;
260                }
261                Liveness::RouterDown => {
262                    inner.set_router(false, None);
263                    return WatchEnd::Lost;
264                }
265                Liveness::Inconclusive(why) => {
266                    if quiet_until.is_none_or(|t| Instant::now() >= t) {
267                        crate::log_warn!("[I2P] liveness inconclusive: {why}");
268                        quiet_until = Some(Instant::now() + Duration::from_secs(60));
269                    }
270                }
271                Liveness::Alive => {}
272            }
273        }
274    }
275}