Skip to main content

vector_core/i2p/
mod.rs

1//! I2P as a transport kind, over a router the user already runs (i2pd, Java I2P,
2//! i2pd-android) through its SAMv3 bridge.
3//!
4//! An instance keeps two transient STREAM sessions, one per lane, so a host a stranger names
5//! only ever learns the Shared destination. `.i2p` hosts are dialed inside I2P, clearnet hosts
6//! through the user's outproxy list, and an alias twin carries TLS on 443 untouched. Nothing
7//! here ever accepts a connection: sessions are client-only and their LeaseSets unpublished.
8
9pub mod keeper;
10pub mod names;
11pub mod outproxy;
12pub mod probe;
13pub mod sam;
14#[cfg(test)]
15mod mock_sam;
16#[cfg(test)]
17mod tests;
18
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, Mutex, RwLock};
21use std::time::Duration;
22
23use tokio::net::TcpStream;
24use web_time::Instant;
25
26use crate::transport::host::{self, ActiveTransport, TransportEvent};
27use crate::transport::i2p_config::I2pConfig;
28use crate::transport::status::{KindStatus, Phase, Reason, Step};
29use crate::transport::{
30    BoxedStream, ConnectError, Dest, Dialed, ExitPolicy, Kind, KindConfig, Lane, Refusal, Route, RouteCtx, StartCtx, Transport,
31    TransportFactory,
32};
33
34use sam::{SamAuth, SamVersion, StreamFail};
35
36/// The keeper's clock. Tests run it in milliseconds.
37#[derive(Clone, Debug)]
38pub(crate) struct Timing {
39    pub backoff: Vec<Duration>,
40    pub watch: Duration,
41    pub not_sam: Duration,
42    pub rejected: Duration,
43    pub session_cap: Duration,
44    pub head_deadline: Duration,
45    /// How often an unreachable router's port is checked for its return.
46    pub port_watch: Duration,
47    /// How long after its sessions are made the router may not know an outproxy's LeaseSet yet.
48    pub fresh_session: Duration,
49}
50
51impl Default for Timing {
52    fn default() -> Self {
53        let s = Duration::from_secs;
54        Timing {
55            backoff: vec![s(2), s(5), s(10), s(20), s(40), s(60)],
56            watch: s(15),
57            not_sam: s(60),
58            rejected: s(120),
59            session_cap: sam::SESSION_CAP,
60            head_deadline: outproxy::HEAD_DEADLINE,
61            port_watch: s(2),
62            fresh_session: outproxy::FRESH_SESSION,
63        }
64    }
65}
66
67/// Where the keeper is. Only the keeper task changes it.
68#[derive(Clone, Debug)]
69pub(crate) enum I2pPhase {
70    Probing,
71    RouterUnreachable { next: Instant },
72    SamRejected { next: Instant, code: &'static str, text: String },
73    CreatingSessions { since: Instant },
74    Ready { since: Instant },
75    SessionFailed { next: Instant, why: String },
76    Lost { next: Instant },
77    /// The session that owns this instance is no longer on screen: no router sessions held.
78    Parked,
79}
80
81impl I2pPhase {
82    fn name(&self) -> &'static str {
83        match self {
84            I2pPhase::Probing => "probing",
85            I2pPhase::RouterUnreachable { .. } => "router_unreachable",
86            I2pPhase::SamRejected { .. } => "sam_rejected",
87            I2pPhase::CreatingSessions { .. } => "creating_sessions",
88            I2pPhase::Ready { .. } => "ready",
89            I2pPhase::SessionFailed { .. } => "session_failed",
90            I2pPhase::Lost { .. } => "lost",
91            I2pPhase::Parked => "parked",
92        }
93    }
94}
95
96struct PhaseState {
97    phase: I2pPhase,
98    version: Option<SamVersion>,
99    /// Whether the router answered the last time anyone asked.
100    router_up: Option<bool>,
101}
102
103/// The destinations an instance dials from: one transient session per lane.
104#[derive(Clone, Debug)]
105pub(crate) struct Sessions {
106    pub account: String,
107    pub shared: String,
108    /// The `.b32.i2p` each lane is seen as, when the router said.
109    pub account_address: Option<String>,
110    pub shared_address: Option<String>,
111}
112
113pub(crate) struct Inner {
114    pub(crate) port: u16,
115    pub(crate) auth: Option<SamAuth>,
116    pub(crate) owner: u64,
117    pub(crate) timing: Timing,
118    sessions: RwLock<Option<Arc<Sessions>>>,
119    state: Mutex<PhaseState>,
120    pub(crate) outproxies: outproxy::Health,
121    pub(crate) names: names::NameCache,
122    /// Wakes the keeper: retry now, or check the sessions now.
123    pub(crate) kick: tokio::sync::Notify,
124    renew: AtomicBool,
125    renewed: tokio::sync::Notify,
126    keeper: Mutex<Option<tokio::task::JoinHandle<()>>>,
127}
128
129pub struct I2pTransport {
130    pub(crate) inner: Arc<Inner>,
131}
132
133fn auth_of(cfg: &I2pConfig) -> Option<SamAuth> {
134    match (cfg.sam_user.as_deref(), cfg.sam_password.as_deref()) {
135        (Some(u), Some(p)) if !u.is_empty() && !p.is_empty() => Some(SamAuth::new(u, p)),
136        _ => None,
137    }
138}
139
140fn secs_until(t: Instant) -> u64 {
141    let now = Instant::now();
142    if t <= now {
143        0
144    } else {
145        t.duration_since(now).as_secs_f64().ceil() as u64
146    }
147}
148
149/// Read the live account's I2P settings in place: a copy would leave the SAM password behind in
150/// freed memory on every status view and every exit dial.
151fn with_live_config<R>(f: impl FnOnce(&I2pConfig) -> R) -> R {
152    let cfg = crate::transport::prefs::live().config(Kind::I2p);
153    match cfg.downcast_ref::<I2pConfig>() {
154        Some(c) => f(c),
155        None => f(&I2pConfig::default()),
156    }
157}
158
159impl Inner {
160    fn new(cfg: &I2pConfig, owner: u64, timing: Timing) -> Self {
161        Inner {
162            port: cfg.sam_port,
163            auth: auth_of(cfg),
164            owner,
165            timing,
166            sessions: RwLock::new(None),
167            state: Mutex::new(PhaseState { phase: I2pPhase::Probing, version: None, router_up: None }),
168            outproxies: outproxy::Health::default(),
169            names: names::NameCache::default(),
170            kick: tokio::sync::Notify::new(),
171            renew: AtomicBool::new(false),
172            renewed: tokio::sync::Notify::new(),
173            keeper: Mutex::new(None),
174        }
175    }
176
177    pub(crate) fn owner_live(&self) -> bool {
178        crate::db::live_session_id() == self.owner
179    }
180
181    pub(crate) fn sessions(&self) -> Option<Arc<Sessions>> {
182        self.sessions.read().unwrap_or_else(|e| e.into_inner()).clone()
183    }
184
185    pub(crate) fn set_sessions(&self, s: Option<Sessions>) {
186        *self.sessions.write().unwrap_or_else(|e| e.into_inner()) = s.map(Arc::new);
187    }
188
189    pub(crate) fn nick(&self, lane: Lane) -> Option<String> {
190        self.sessions().map(|s| match lane {
191            Lane::Account => s.account.clone(),
192            Lane::Shared => s.shared.clone(),
193        })
194    }
195
196    pub(crate) fn phase(&self) -> I2pPhase {
197        self.state.lock().unwrap_or_else(|e| e.into_inner()).phase.clone()
198    }
199
200    pub(crate) fn is_ready(&self) -> bool {
201        matches!(self.phase(), I2pPhase::Ready { .. })
202    }
203
204    /// How long the current sessions have been up.
205    pub(crate) fn session_age(&self) -> Option<std::time::Duration> {
206        match self.phase() {
207            I2pPhase::Ready { since } => Some(since.elapsed()),
208            _ => None,
209        }
210    }
211
212    pub(crate) fn set_router(&self, up: bool, version: Option<SamVersion>) {
213        let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
214        st.router_up = Some(up);
215        if version.is_some() {
216            st.version = version;
217        }
218    }
219
220    /// Move to `next` and tell the host. A readiness flip is Ready or Lost (they move the epoch);
221    /// anything else only refreshes the view.
222    pub(crate) fn set_phase(self: &Arc<Self>, next: I2pPhase, recovered: bool) {
223        let (was, now) = {
224            let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
225            let was = matches!(st.phase, I2pPhase::Ready { .. });
226            st.phase = next;
227            (was, matches!(st.phase, I2pPhase::Ready { .. }))
228        };
229        crate::log_debug!("[I2P] {}", self.phase().name());
230        let Some(a) = self.active_entry() else { return };
231        let (instance, owner) = (a.id(), a.owner());
232        match (was, now) {
233            (false, true) => host::notify(TransportEvent::Ready { kind: Kind::I2p, instance, owner, recovered }),
234            (true, false) => host::notify(TransportEvent::Lost { kind: Kind::I2p, instance, owner }),
235            _ if owner == crate::db::live_session_id() => host::notify(TransportEvent::Changed),
236            _ => {}
237        }
238    }
239
240    /// The host's entry for this instance, when it is the installed one.
241    pub(crate) fn active_entry(self: &Arc<Self>) -> Option<Arc<ActiveTransport>> {
242        let a = host::active()?;
243        let t = a.transport().as_any()?.downcast_ref::<I2pTransport>()?;
244        Arc::ptr_eq(&t.inner, self).then_some(a)
245    }
246
247    /// A router-side failure as the caller sees it. Anything that hints the session or router
248    /// went away wakes the keeper to check now.
249    pub(crate) fn fail(&self, e: StreamFail) -> ConnectError {
250        match e {
251            StreamFail::RouterDown => {
252                self.kick.notify_one();
253                ConnectError::RouterDown { port: self.port }
254            }
255            StreamFail::SessionGone => {
256                self.kick.notify_one();
257                ConnectError::NotReady(Some(Kind::I2p))
258            }
259            StreamFail::SessionSuspect(m) => {
260                self.kick.notify_one();
261                ConnectError::Unreachable(m)
262            }
263            StreamFail::Unreachable(m) => ConnectError::Unreachable(m),
264            StreamFail::Timeout => ConnectError::Timeout,
265            StreamFail::BadKey => ConnectError::Refused(Refusal::BadName),
266        }
267    }
268
269    /// A stream to `dest` (a `.b32.i2p` address or an address-book name) on `port`. A router
270    /// that only takes base64 destinations gets a lookup and one retry.
271    pub(crate) async fn open_raw(&self, nick: &str, dest: &str, port: u16) -> Result<TcpStream, StreamFail> {
272        let auth = self.auth.as_ref();
273        if crate::transport::route::is_b32(dest) {
274            return match sam::connect(self.port, auth, nick, dest, port).await {
275                Err(StreamFail::BadKey) => {
276                    let b64 = sam::lookup(self.port, auth, dest).await?;
277                    sam::connect(self.port, auth, nick, &b64, port).await
278                }
279                r => r,
280            };
281        }
282        let b64 = match self.names.get(dest) {
283            Some(v) => v,
284            None => {
285                let v = sam::lookup(self.port, auth, dest).await?;
286                self.names.put(dest, v.clone());
287                v
288            }
289        };
290        match sam::connect(self.port, auth, nick, &b64, port).await {
291            Err(StreamFail::BadKey) => {
292                self.names.forget(dest);
293                Err(StreamFail::BadKey)
294            }
295            r => r,
296        }
297    }
298
299    pub(crate) async fn open(&self, nick: &str, dest: &str, port: u16) -> Result<TcpStream, ConnectError> {
300        match self.open_raw(nick, dest, port).await {
301            Ok(s) => Ok(s),
302            Err(StreamFail::BadKey) if !crate::transport::route::is_b32(dest) => Err(ConnectError::UnknownName),
303            Err(e) => Err(self.fail(e)),
304        }
305    }
306
307    fn router_step(&self, st: &PhaseState) -> Step {
308        let ok = || Step::new("router", "Router", "ok", format!("SAM {} on port {}", st.version.map(|v| v.to_string()).unwrap_or_else(|| "3".into()), self.port));
309        let fail = || Step::new("router", "Router", "fail", "Not answering");
310        let looking = || Step::new("router", "Router", "pending", "Looking…");
311        match &st.phase {
312            I2pPhase::Probing | I2pPhase::Parked => looking(),
313            I2pPhase::RouterUnreachable { .. } | I2pPhase::SamRejected { .. } => fail(),
314            I2pPhase::CreatingSessions { .. } | I2pPhase::Ready { .. } | I2pPhase::SessionFailed { .. } => ok(),
315            I2pPhase::Lost { .. } => match st.router_up {
316                Some(true) => ok(),
317                Some(false) => fail(),
318                None => looking(),
319            },
320        }
321    }
322
323    fn tunnels_step(st: &PhaseState) -> Step {
324        match &st.phase {
325            I2pPhase::CreatingSessions { since } => {
326                Step::new("tunnels", "Tunnels", "pending", format!("Building… {}s", since.elapsed().as_secs()))
327            }
328            I2pPhase::Ready { .. } => Step::new("tunnels", "Tunnels", "ok", "Ready"),
329            I2pPhase::SessionFailed { .. } => Step::new("tunnels", "Tunnels", "fail", "Failed"),
330            _ => Step::new("tunnels", "Tunnels", "pending", "Waiting…"),
331        }
332    }
333
334    fn exit_step(&self, st: &PhaseState, cfg: &I2pConfig) -> Step {
335        let list = cfg.outproxy_list();
336        if cfg.exit == ExitPolicy::Off {
337            return Step::new("exit", "Clearnet", "off", "Off (I2P-Only)");
338        }
339        // Nothing reaches an outproxy without sessions: the last one that worked says nothing now.
340        if !matches!(st.phase, I2pPhase::Ready { .. }) {
341            return Step::new("exit", "Clearnet", "pending", "Waiting…");
342        }
343        // Health counts failures; a tunnel still carrying traffic means something gets through.
344        let carrying = || {
345            crate::transport::bridge::count_where(|c| {
346                c.spliced && c.ticket.is_some_and(|t| t.owner == self.owner) && c.outproxy.as_ref().is_some_and(|id| list.iter().any(|o| &o.id == id))
347            }) > 0
348        };
349        if self.outproxies.all_failing(&list) && !carrying() {
350            return Step::new("exit", "Clearnet", "fail", "No outproxy answering");
351        }
352        let worked = self.outproxies.last_ok().and_then(|id| list.iter().find(|o| o.id == id).map(|o| o.name.clone()));
353        match worked {
354            Some(name) => Step::new("exit", "Clearnet", "ok", format!("Through {name}")),
355            None => Step::new("exit", "Clearnet", "unknown", "Not used yet"),
356        }
357    }
358
359    fn status(&self) -> KindStatus {
360        with_live_config(|cfg| self.status_with(cfg))
361    }
362
363    fn status_with(&self, cfg: &I2pConfig) -> KindStatus {
364        let st = self.state.lock().unwrap_or_else(|e| e.into_inner());
365        let port = self.port;
366        let (phase, reason, retry_in) = match &st.phase {
367            I2pPhase::Probing | I2pPhase::CreatingSessions { .. } => (Phase::Starting, None, None),
368            I2pPhase::Ready { .. } => (Phase::Ready, None, None),
369            I2pPhase::RouterUnreachable { next } => (
370                Phase::Waiting,
371                Some(Reason::new("router_unreachable", format!("Can't reach your I2P router at 127.0.0.1:{port}."))),
372                Some(secs_until(*next)),
373            ),
374            I2pPhase::SamRejected { next, code, text } => (Phase::Waiting, Some(Reason::new(code, text.clone())), Some(secs_until(*next))),
375            I2pPhase::SessionFailed { next, why } => (
376                Phase::Waiting,
377                Some(Reason::new("session_failed", format!("Your router couldn't open a session: {why}"))),
378                Some(secs_until(*next)),
379            ),
380            I2pPhase::Lost { next } => {
381                (Phase::Waiting, Some(Reason::new("session_lost", "Lost the I2P session. Reconnecting.")), Some(secs_until(*next)))
382            }
383            I2pPhase::Parked => (Phase::Waiting, None, None),
384        };
385        let session_age = match &st.phase {
386            I2pPhase::Ready { since } => Some(since.elapsed().as_secs()),
387            _ => None,
388        };
389        let addresses = self.sessions().filter(|_| session_age.is_some()).map(|s| {
390            serde_json::json!({ "account": s.account_address, "shared": s.shared_address })
391        });
392        let steps = vec![self.router_step(&st), Self::tunnels_step(&st), self.exit_step(&st, cfg)];
393        let detail = serde_json::json!({
394            "sam_port": port,
395            "sam_version": st.version.map(|v| v.to_string()),
396            "sam_auth": self.auth.is_some(),
397            "session_age": session_age,
398            "addresses": addresses,
399            "exit": cfg.exit,
400            "outproxies": self.outproxies.view(&cfg.outproxy_list()),
401        });
402        KindStatus { phase, progress: None, reason, retry_in, steps, detail }
403    }
404}
405
406impl I2pTransport {
407    pub(crate) fn new(cfg: &I2pConfig, owner: u64, timing: Timing) -> Self {
408        I2pTransport { inner: Arc::new(Inner::new(cfg, owner, timing)) }
409    }
410
411    pub(crate) fn spawn_keeper(&self) {
412        let inner = self.inner.clone();
413        // spawn-detached: the keeper owns only this instance's router sessions.
414        let h = crate::transport::spawn_on(keeper::run(inner));
415        *self.inner.keeper.lock().unwrap_or_else(|e| e.into_inner()) = Some(h);
416    }
417
418    pub fn sam_port(&self) -> u16 {
419        self.inner.port
420    }
421
422    /// Whether this instance talks to the router `cfg` names (same port and credentials).
423    pub fn serves(&self, cfg: &I2pConfig) -> bool {
424        self.inner.port == cfg.sam_port && self.inner.auth == auth_of(cfg)
425    }
426
427    /// Skip the keeper's wait and try the router now.
428    pub fn retry_now(&self) {
429        self.inner.kick.notify_one();
430    }
431
432    /// The keeper's phase, for logs and the soak tool.
433    pub fn phase_name(&self) -> &'static str {
434        self.inner.phase().name()
435    }
436}
437
438/// Checks an instance's two sessions with the router without handing out their names.
439pub struct SessionProbe {
440    port: u16,
441    auth: Option<SamAuth>,
442    nicks: [String; 2],
443}
444
445impl SessionProbe {
446    /// Account lane first, then Shared.
447    pub async fn check(&self) -> [sam::Liveness; 2] {
448        let (a, s) = tokio::join!(
449            sam::liveness(self.port, self.auth.as_ref(), &self.nicks[0]),
450            sam::liveness(self.port, self.auth.as_ref(), &self.nicks[1]),
451        );
452        [a, s]
453    }
454}
455
456impl I2pTransport {
457    /// A probe of the sessions up right now, if any.
458    pub fn session_probe(&self) -> Option<SessionProbe> {
459        let s = self.inner.sessions()?;
460        Some(SessionProbe { port: self.inner.port, auth: self.inner.auth.clone(), nicks: [s.account.clone(), s.shared.clone()] })
461    }
462}
463
464impl Drop for I2pTransport {
465    fn drop(&mut self) {
466        if let Some(h) = self.inner.keeper.lock().unwrap_or_else(|e| e.into_inner()).take() {
467            h.abort();
468        }
469    }
470}
471
472#[async_trait::async_trait]
473impl Transport for I2pTransport {
474    fn kind(&self) -> Kind {
475        Kind::I2p
476    }
477
478    fn route(&self, dest: &Dest, port: u16, ctx: &RouteCtx) -> Route {
479        crate::transport::route::route_i2p(dest, port, ctx)
480    }
481
482    async fn dial(&self, route: &Route, lane: Lane) -> Result<(BoxedStream, Dialed), ConnectError> {
483        let inner = &self.inner;
484        let nick = inner.nick(lane).ok_or(ConnectError::NotReady(Some(Kind::I2p)))?;
485        match route {
486            Route::Native { host, port } => {
487                let s = inner.open(&nick, host, *port).await?;
488                Ok((Box::new(s), Dialed::default()))
489            }
490            Route::Twin { via, port, .. } => {
491                let s = inner.open(&nick, via, *port).await?;
492                Ok((Box::new(s), Dialed::default()))
493            }
494            Route::Exit { host, port } => {
495                let list = with_live_config(I2pConfig::outproxy_list);
496                let allowed = |id: &str| host::outproxy_allowed(Kind::I2p, id);
497                let (s, id) = outproxy::connect(inner, &nick, &list, host, *port, &allowed).await?;
498                Ok((Box::new(s), Dialed { outproxy: Some(id) }))
499            }
500            Route::Refuse(r) => Err(ConnectError::Refused(*r)),
501        }
502    }
503
504    fn ready(&self) -> bool {
505        self.inner.is_ready()
506    }
507
508    fn kind_status(&self) -> KindStatus {
509        self.inner.status()
510    }
511
512    /// Both destinations replaced; returns once the old ones are gone (or the keeper is busy
513    /// building, when the next sessions are fresh anyway).
514    async fn new_identity(&self) {
515        if !self.inner.is_ready() {
516            return;
517        }
518        let renewed = self.inner.renewed.notified();
519        tokio::pin!(renewed);
520        renewed.as_mut().enable();
521        self.inner.renew.store(true, Ordering::Release);
522        self.inner.kick.notify_one();
523        let _ = tokio::time::timeout(Duration::from_secs(5), renewed).await;
524    }
525
526    /// Ends the keeper, which closes both control sockets: the router drops the sessions.
527    async fn shutdown(&self) {
528        let h = self.inner.keeper.lock().unwrap_or_else(|e| e.into_inner()).take();
529        if let Some(h) = h {
530            h.abort();
531            let _ = h.await;
532        }
533        self.inner.set_sessions(None);
534    }
535
536    fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync> {
537        self
538    }
539
540    fn as_any(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
541        Some(self)
542    }
543}
544
545pub struct I2pFactory;
546
547#[async_trait::async_trait]
548impl TransportFactory for I2pFactory {
549    fn kind(&self) -> Kind {
550        Kind::I2p
551    }
552
553    /// Returns at once; the keeper reports Ready once both sessions exist.
554    async fn start(&self, ctx: StartCtx) -> Result<Arc<dyn Transport>, String> {
555        let cfg = ctx.config.downcast_ref::<I2pConfig>().cloned().unwrap_or_default();
556        let t = Arc::new(I2pTransport::new(&cfg, ctx.owner, Timing::default()));
557        t.spawn_keeper();
558        Ok(t)
559    }
560
561    fn adopt_on_unlock(&self) -> bool {
562        true
563    }
564
565    fn compatible(&self, inst: &dyn Transport, cfg: &KindConfig) -> bool {
566        let Some(t) = inst.as_any().and_then(|a| a.downcast_ref::<I2pTransport>()) else { return false };
567        t.serves(&cfg.downcast_ref::<I2pConfig>().cloned().unwrap_or_default())
568    }
569}
570
571/// The installed I2P instance, when it belongs to the account on screen.
572pub fn active() -> Option<Arc<I2pTransport>> {
573    let a = host::active().filter(|a| a.kind == Kind::I2p && a.owner() == crate::db::live_session_id())?;
574    a.transport().clone().into_any().downcast::<I2pTransport>().ok()
575}