Skip to main content

vector_core/transport/
mod.rs

1//! The transport meta-glue: one egress decision for every TCP connection Vector opens, and one
2//! process bridge that any anonymity network plugs into.
3//!
4//! Clearnet is `Egress::Direct`. Every other kind (Tor, I2P, …) is a [`Transport`] installed in
5//! the [`host`] slot, reached through the authenticated SOCKS5 [`bridge`]. A chosen kind that is
6//! not ready refuses in process: nothing ever falls back to a direct socket.
7//!
8//! Inside `community/` refer to this module as `crate::transport::…`: the name collides with
9//! `community::transport`.
10
11pub mod aliases;
12pub mod budget;
13pub mod cycle;
14pub mod guard;
15pub mod host;
16pub mod i2p_config;
17pub mod tor_config;
18pub mod kinds;
19pub mod prefs;
20pub mod prelogin;
21pub mod realtime;
22pub mod route;
23pub mod status;
24pub mod ws;
25#[cfg(not(target_arch = "wasm32"))]
26pub mod bridge;
27#[cfg(not(target_arch = "wasm32"))]
28pub mod runtime;
29#[cfg(all(feature = "twin-check", not(target_arch = "wasm32")))]
30pub mod twins;
31#[cfg(test)]
32mod tests;
33
34#[cfg(not(target_arch = "wasm32"))]
35pub use runtime::{runtime, spawn_on};
36
37use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
38use std::sync::OnceLock;
39
40pub use budget::{budget, Budgets, Op};
41pub use route::{nip11_url, validate_relay_url, Dest, Refusal, Route};
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
44#[serde(rename_all = "lowercase")]
45pub enum Kind {
46    Clearnet,
47    Tor,
48    I2p,
49}
50
51impl Kind {
52    pub const ALL: [Kind; 3] = [Kind::Clearnet, Kind::Tor, Kind::I2p];
53
54    pub fn as_str(self) -> &'static str {
55        match self {
56            Kind::Clearnet => "clearnet",
57            Kind::Tor => "tor",
58            Kind::I2p => "i2p",
59        }
60    }
61
62    pub fn parse(s: &str) -> Option<Kind> {
63        Kind::ALL.into_iter().find(|k| k.as_str() == s)
64    }
65
66    pub fn label(self) -> &'static str {
67        match self {
68            Kind::Clearnet => "Standard",
69            Kind::Tor => "Tor",
70            Kind::I2p => "I2P",
71        }
72    }
73
74    /// Whether this build can run the kind. Never true for an anonymity kind on wasm32.
75    pub fn compiled(self) -> bool {
76        match self {
77            Kind::Clearnet => true,
78            Kind::Tor => cfg!(all(feature = "tor", not(target_arch = "wasm32"))),
79            Kind::I2p => cfg!(all(feature = "i2p", not(target_arch = "wasm32"))),
80        }
81    }
82
83    /// Names only this kind can reach. Known in every build, so a build without the kind still
84    /// refuses them before any DNS.
85    pub fn native_suffixes(self) -> &'static [&'static str] {
86        match self {
87            Kind::Clearnet => &[],
88            Kind::Tor => &[".onion"],
89            Kind::I2p => &[".i2p"],
90        }
91    }
92
93    /// Whether this build reaches the kind's own addresses: a `.onion` needs the embedded Tor.
94    pub fn reaches_native(self) -> bool {
95        match self {
96            Kind::I2p => true,
97            Kind::Tor => cfg!(all(feature = "tor", not(target_arch = "wasm32"))),
98            Kind::Clearnet => false,
99        }
100    }
101
102    /// What a server's address inside this network is called, for a twin.
103    pub fn address_noun(self) -> &'static str {
104        match self {
105            Kind::Tor => "onion address",
106            Kind::I2p => "I2P address",
107            Kind::Clearnet => "address",
108        }
109    }
110
111    pub fn budgets(self) -> &'static Budgets {
112        budget::table(self)
113    }
114
115    fn code(self) -> u8 {
116        match self {
117            Kind::Clearnet => 1,
118            Kind::Tor => 2,
119            Kind::I2p => 3,
120        }
121    }
122
123    fn from_code(c: u8) -> Option<Kind> {
124        match c {
125            1 => Some(Kind::Clearnet),
126            2 => Some(Kind::Tor),
127            3 => Some(Kind::I2p),
128            _ => None,
129        }
130    }
131}
132
133/// Compiled kinds, in `Kind` order.
134pub fn supported() -> Vec<Kind> {
135    Kind::ALL.into_iter().filter(|k| k.compiled()).collect()
136}
137
138/// Which identity a connection speaks for. I2P gives each lane its own destination, so a host a
139/// stranger names only ever learns the Shared one.
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
141pub enum Lane {
142    Account,
143    Shared,
144}
145
146#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
147impl Lane {
148    fn tag(self) -> char {
149        match self {
150            Lane::Account => 'a',
151            Lane::Shared => 's',
152        }
153    }
154
155    fn from_tag(c: &str) -> Option<Lane> {
156        match c {
157            "a" => Some(Lane::Account),
158            "s" => Some(Lane::Shared),
159            _ => None,
160        }
161    }
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
165#[serde(rename_all = "lowercase")]
166pub enum ExitPolicy {
167    #[default]
168    Allow,
169    Off,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum TransportState {
174    /// Preference not loaded or unparseable: blocked.
175    Unknown,
176    Clearnet,
177    /// The chosen kind's instance is installed, owned by the live session and ready.
178    Active { kind: Kind },
179    /// Kind chosen but not ready (starting, retrying, failed, not in this build): blocked.
180    RequiredButInactive { kind: Kind },
181}
182
183/// What a proxied connection proves to the bridge: the session that built the client, the epoch
184/// it was decided in, and the lane it speaks for.
185#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
186pub struct Ticket {
187    pub owner: u64,
188    pub epoch: u64,
189    pub lane: Lane,
190}
191
192#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
193impl Ticket {
194    pub(crate) fn encode(&self) -> String {
195        format!("t1.{:x}.{:x}.{}", self.owner, self.epoch, self.lane.tag())
196    }
197
198    pub(crate) fn decode(s: &str) -> Option<Ticket> {
199        let mut parts = s.split('.');
200        if parts.next()? != "t1" {
201            return None;
202        }
203        let owner = u64::from_str_radix(parts.next()?, 16).ok()?;
204        let epoch = u64::from_str_radix(parts.next()?, 16).ok()?;
205        let lane = Lane::from_tag(parts.next()?)?;
206        if parts.next().is_some() {
207            return None;
208        }
209        Some(Ticket { owner, epoch, lane })
210    }
211
212    /// Owned by the live session and decided in the current epoch.
213    pub fn is_live(&self) -> bool {
214        self.owner == crate::db::live_session_id() && self.epoch == epoch()
215    }
216}
217
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub enum Egress {
220    Direct,
221    Proxy(Ticket),
222    Refuse(ConnectError),
223}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
226pub enum ConnectError {
227    Refused(Refusal),
228    /// `None` while the preference is Unknown.
229    NotReady(Option<Kind>),
230    /// The chosen kind is blocked with a status reason: that reason's text.
231    Blocked(String),
232    /// A ticket from an older epoch, or a session that is no longer live.
233    Stale,
234    RouterDown { port: u16 },
235    UnknownName,
236    /// The destination or exit is unreachable; the detail is for logs (Tor: arti's text).
237    Unreachable(String),
238    /// The exit was reached and couldn't reach the server itself; the exit's name.
239    ExitUnreachable(String),
240    NoExit,
241    ExitRefusedPort(u16),
242    Timeout,
243    /// The SOCKS client hung up mid-dial.
244    Cancelled,
245    /// The bridge could not bind; the detail is for logs.
246    Bridge(String),
247}
248
249impl ConnectError {
250    pub fn socks_reply(&self) -> u8 {
251        match self {
252            ConnectError::Refused(_) | ConnectError::Stale => 0x02,
253            ConnectError::NotReady(_) | ConnectError::Blocked(_) | ConnectError::Bridge(_) | ConnectError::Cancelled => 0x01,
254            ConnectError::RouterDown { .. } => 0x03,
255            ConnectError::UnknownName
256            | ConnectError::Unreachable(_)
257            | ConnectError::ExitUnreachable(_)
258            | ConnectError::NoExit
259            | ConnectError::ExitRefusedPort(_) => 0x04,
260            ConnectError::Timeout => 0x06,
261        }
262    }
263
264    /// The line the UI shows. `Unreachable` keeps arti's text under Tor.
265    pub fn text(&self) -> String {
266        match self {
267            ConnectError::Refused(r) => r.text(),
268            ConnectError::NotReady(None) => "Vector is still connecting.".into(),
269            ConnectError::NotReady(Some(k)) => format!("{} is still connecting.", k.label()),
270            ConnectError::Blocked(t) => t.clone(),
271            ConnectError::Stale => "The network changed. Try again.".into(),
272            ConnectError::RouterDown { port } => match preference() {
273                Some(Kind::Tor) => format!("Can't reach Tor at 127.0.0.1:{port}."),
274                _ => format!("Can't reach your I2P router at 127.0.0.1:{port}."),
275            },
276            ConnectError::UnknownName => "This I2P name isn't in your router's address book. Use its .b32.i2p address.".into(),
277            ConnectError::Unreachable(detail) => match preference() {
278                Some(Kind::I2p) => "This I2P address isn't online right now.".into(),
279                _ => detail.clone(),
280            },
281            ConnectError::ExitUnreachable(name) => format!("The {name} outproxy couldn't reach this server."),
282            ConnectError::NoExit => "No outproxy is reachable right now.".into(),
283            ConnectError::ExitRefusedPort(p) => format!("No outproxy here allows port {p}."),
284            ConnectError::Timeout => "Timed out.".into(),
285            ConnectError::Cancelled => "Cancelled.".into(),
286            ConnectError::Bridge(_) => "Vector couldn't open its local proxy.".into(),
287        }
288    }
289
290    /// The network will come back on its own: a policy refusal won't, nor will a stale owner (a
291    /// session never becomes live again once replaced), nor a block only the user can lift.
292    pub fn is_transient(&self) -> bool {
293        match self {
294            ConnectError::NotReady(_) => true,
295            ConnectError::Blocked(_) => !status::waits_for_user(),
296            _ => false,
297        }
298    }
299
300    /// Our side of the connection failed (the network, its router, its exits), so the failure
301    /// says nothing about the server.
302    pub fn is_network(&self) -> bool {
303        matches!(
304            self,
305            ConnectError::NotReady(_)
306                | ConnectError::Blocked(_)
307                | ConnectError::Stale
308                | ConnectError::RouterDown { .. }
309                | ConnectError::NoExit
310                | ConnectError::ExitRefusedPort(_)
311                | ConnectError::Bridge(_)
312        )
313    }
314}
315
316impl std::fmt::Display for ConnectError {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        f.write_str(&self.text())
319    }
320}
321
322impl std::error::Error for ConnectError {}
323
324pub trait AsyncStream: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin {}
325impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> AsyncStream for T {}
326pub type BoxedStream = Box<dyn AsyncStream>;
327
328/// A kind's parsed config, opaque to shared code; each kind downcasts its own type.
329pub type KindConfig = std::sync::Arc<dyn std::any::Any + Send + Sync>;
330
331/// The live session's routing inputs, read per dial so an instance never holds a stale copy.
332pub struct RouteCtx<'a> {
333    pub aliases: &'a aliases::AliasTable,
334    pub config: &'a KindConfig,
335}
336
337#[derive(Clone, Debug, Default)]
338pub struct Dialed {
339    /// The outproxy id an `Exit` used.
340    pub outproxy: Option<String>,
341}
342
343#[async_trait::async_trait]
344pub trait Transport: Send + Sync + 'static {
345    fn kind(&self) -> Kind;
346    /// This kind's rules, after the shared pre-router. Pure, no I/O.
347    fn route(&self, dest: &Dest, port: u16, ctx: &RouteCtx) -> Route;
348    /// Open the stream `route` names for `lane`. Ok only once the far end exists.
349    async fn dial(&self, route: &Route, lane: Lane) -> Result<(BoxedStream, Dialed), ConnectError>;
350    fn ready(&self) -> bool;
351    fn kind_status(&self) -> status::KindStatus;
352    /// Unlinkable from here on.
353    async fn new_identity(&self);
354    async fn shutdown(&self);
355    fn into_any(self: std::sync::Arc<Self>) -> std::sync::Arc<dyn std::any::Any + Send + Sync>;
356    /// The instance itself, for a factory's `compatible` (which holds no `Arc`).
357    fn as_any(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
358        None
359    }
360}
361
362pub struct StartCtx {
363    pub owner: u64,
364    pub started_prelogin: bool,
365    /// Tor: state and cache dirs.
366    pub dirs: Option<(std::path::PathBuf, std::path::PathBuf)>,
367    pub config: KindConfig,
368}
369
370#[async_trait::async_trait]
371pub trait TransportFactory: Send + Sync + 'static {
372    fn kind(&self) -> Kind;
373    /// Tor bootstraps within `budget(Startup)` and returns a ready instance; others may return at
374    /// once and report Ready through `host::notify`.
375    async fn start(&self, ctx: StartCtx) -> Result<std::sync::Arc<dyn Transport>, String>;
376    /// Keep a welcome-screen instance when an existing account is unlocked.
377    fn adopt_on_unlock(&self) -> bool;
378    /// Whether `inst` can serve an account whose config is `cfg`.
379    fn compatible(&self, inst: &dyn Transport, cfg: &KindConfig) -> bool;
380}
381
382// ── Epoch and policy generation ──────────────────────────────────────────────
383
384static EPOCH: AtomicU64 = AtomicU64::new(1);
385static POLICY_GEN: AtomicU64 = AtomicU64::new(1);
386
387fn epoch_tx() -> &'static tokio::sync::watch::Sender<u64> {
388    static TX: OnceLock<tokio::sync::watch::Sender<u64>> = OnceLock::new();
389    TX.get_or_init(|| tokio::sync::watch::channel(EPOCH.load(Ordering::Acquire)).0)
390}
391
392/// Bumped only when the egress decision can change: preference, live session, an instance
393/// installed or removed, or its readiness.
394pub fn epoch() -> u64 {
395    EPOCH.load(Ordering::Acquire)
396}
397
398/// Bumped when a routing input of the live session changes: exit policy, outproxies, aliases.
399pub fn policy_gen() -> u64 {
400    POLICY_GEN.load(Ordering::Acquire)
401}
402
403pub(crate) fn bump_policy_gen() -> u64 {
404    POLICY_GEN.fetch_add(1, Ordering::AcqRel) + 1
405}
406
407/// Advance the epoch: drop every HTTP client, abort every bridge connection of an older epoch,
408/// then wake guarded streams and body reads.
409pub(crate) fn bump_epoch() -> u64 {
410    let next = EPOCH.fetch_add(1, Ordering::AcqRel) + 1;
411    crate::net::forget_clients();
412    #[cfg(not(target_arch = "wasm32"))]
413    bridge::abort_where(|c| c.ticket.is_some_and(|t| t.epoch < next));
414    epoch_tx().send_replace(next);
415    next
416}
417
418/// Resolves once `epoch() != since`.
419pub async fn changed(since: u64) {
420    let mut rx = epoch_tx().subscribe();
421    loop {
422        if *rx.borrow_and_update() != since || epoch() != since {
423            return;
424        }
425        if rx.changed().await.is_err() {
426            std::future::pending::<()>().await;
427        }
428    }
429}
430
431/// The installed session changed: guarded sockets of the outgoing account close.
432pub(crate) fn on_session_installed(prev: u64, next: u64) {
433    if prev != next {
434        bump_epoch();
435    }
436}
437
438// ── Preference and state ─────────────────────────────────────────────────────
439
440static STRICT: AtomicBool = AtomicBool::new(false);
441
442/// First-party binaries that hold accounts call this once at startup: every session from here on
443/// starts Unknown (blocked) until its stored network is loaded.
444pub fn strict_boot() {
445    STRICT.store(true, Ordering::Release);
446}
447
448pub(crate) fn is_strict() -> bool {
449    STRICT.load(Ordering::Acquire)
450}
451
452#[cfg(test)]
453pub(crate) fn set_strict_for_test(on: bool) {
454    STRICT.store(on, Ordering::Release);
455}
456
457/// The live session's chosen kind. `None` = Unknown.
458pub fn preference() -> Option<Kind> {
459    prefs::live().kind()
460}
461
462/// Set the live session's kind. Bumps the epoch when it changes; a kind change also drops that
463/// session's realtime consent.
464pub fn set_preference(kind: Option<Kind>) {
465    prefs::set_kind(&crate::db::live_session(), kind);
466}
467
468pub fn state() -> TransportState {
469    state_for(preference())
470}
471
472fn state_for(pref: Option<Kind>) -> TransportState {
473    match pref {
474        None => TransportState::Unknown,
475        Some(Kind::Clearnet) => TransportState::Clearnet,
476        Some(k) => match host::active() {
477            Some(a) if a.kind == k && a.owner() == crate::db::live_session_id() && a.transport().ready() => {
478                TransportState::Active { kind: k }
479            }
480            _ => TransportState::RequiredButInactive { kind: k },
481        },
482    }
483}
484
485/// Why nothing can leave right now, while the chosen network isn't usable.
486pub fn blocked_reason() -> Option<String> {
487    match state() {
488        TransportState::Clearnet | TransportState::Active { .. } => None,
489        TransportState::Unknown => Some(ConnectError::NotReady(None).text()),
490        TransportState::RequiredButInactive { kind } => Some(blocked_error(kind).text()),
491    }
492}
493
494/// Why the chosen kind refuses right now, for `RequiredButInactive`.
495fn blocked_error(k: Kind) -> ConnectError {
496    match status::reason_for(k) {
497        Some(r) => ConnectError::Blocked(r.text),
498        None => ConnectError::NotReady(Some(k)),
499    }
500}
501
502/// The one decision every TCP egress makes. `owner` is the session the client was built under.
503pub fn egress(owner: u64, lane: Lane, host: &str, port: u16) -> Egress {
504    if owner != crate::db::live_session_id() {
505        return Egress::Refuse(ConnectError::Stale);
506    }
507    let dest = match Dest::parse(host) {
508        Some(d) => d,
509        None => return Egress::Refuse(ConnectError::Refused(Refusal::BadName)),
510    };
511    let pref = preference();
512    if let Some(r) = route::pre_route(pref.unwrap_or(Kind::Clearnet), &dest) {
513        return Egress::Refuse(ConnectError::Refused(r));
514    }
515    match state_for(pref) {
516        TransportState::Clearnet => Egress::Direct,
517        TransportState::Unknown => Egress::Refuse(ConnectError::NotReady(None)),
518        TransportState::RequiredButInactive { kind } => Egress::Refuse(blocked_error(kind)),
519        TransportState::Active { kind } => {
520            let Some(active) = host::active().filter(|a| a.kind == kind) else {
521                return Egress::Refuse(ConnectError::NotReady(Some(kind)));
522            };
523            let p = prefs::live();
524            let (aliases, config) = (p.aliases(), p.config(kind));
525            let ctx = RouteCtx { aliases: &aliases, config: &config };
526            match active.transport().route(&dest, port, &ctx) {
527                Route::Refuse(r) => Egress::Refuse(ConnectError::Refused(r)),
528                _ => Egress::Proxy(Ticket { owner, epoch: epoch(), lane }),
529            }
530        }
531    }
532}
533
534/// Host and port of a URL, with the scheme's default port.
535pub(crate) fn host_port(url_or_host: &str) -> Option<(String, u16)> {
536    if let Ok(u) = url::Url::parse(url_or_host) {
537        if let (Some(h), Some(p)) = (u.host_str(), u.port_or_known_default()) {
538            return Some((h.trim_start_matches('[').trim_end_matches(']').to_string(), p));
539        }
540    }
541    if url_or_host.contains("://") || url_or_host.is_empty() {
542        return None;
543    }
544    Some((url_or_host.to_string(), 443))
545}
546
547/// The refusal text when the live account's route can never reach this URL or host (relay
548/// lists, community targets). Transient blocks are not refusals.
549pub fn refuses(url_or_host: &str) -> Option<String> {
550    refusal(url_or_host).map(|r| r.text())
551}
552
553/// The rule behind [`refuses`].
554pub fn refusal(url_or_host: &str) -> Option<Refusal> {
555    let (host, port) = host_port(url_or_host)?;
556    let dest = Dest::parse(&host)?;
557    let pref = preference()?;
558    if let Some(r) = route::pre_route(pref, &dest) {
559        return Some(r);
560    }
561    if let TransportState::Active { kind } = state_for(Some(pref)) {
562        let active = host::active().filter(|a| a.kind == kind)?;
563        let p = prefs::live();
564        let (aliases, config) = (p.aliases(), p.config(kind));
565        if let Route::Refuse(r) = active.transport().route(&dest, port, &RouteCtx { aliases: &aliases, config: &config }) {
566            return Some(r);
567        }
568    }
569    None
570}
571
572pub fn route_view(url: &str) -> status::RouteView {
573    status::route_view(url)
574}
575
576/// Hold until the chosen kind is ready or `max` passes. A block only the user can lift (a
577/// failed start, a router that turned Vector down) ends the wait at once with its reason.
578pub async fn wait_ready(max: std::time::Duration) -> Result<(), String> {
579    let deadline = web_time::Instant::now() + max;
580    loop {
581        let since = epoch();
582        match state() {
583            TransportState::Clearnet | TransportState::Active { .. } => return Ok(()),
584            TransportState::Unknown => {
585                if web_time::Instant::now() >= deadline {
586                    return Err(ConnectError::NotReady(None).text());
587                }
588            }
589            TransportState::RequiredButInactive { kind } => {
590                if status::waits_for_user() || web_time::Instant::now() >= deadline {
591                    return Err(blocked_error(kind).text());
592                }
593            }
594        }
595        let left = deadline.saturating_duration_since(web_time::Instant::now());
596        // A ready flip always bumps the epoch; the short tick covers a state read between bumps.
597        let _ = crate::rt::time::timeout(left.min(std::time::Duration::from_secs(1)), changed(since)).await;
598    }
599}