vector-core 0.11.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! The transport meta-glue: one egress decision for every TCP connection Vector opens, and one
//! process bridge that any anonymity network plugs into.
//!
//! Clearnet is `Egress::Direct`. Every other kind (Tor, I2P, …) is a [`Transport`] installed in
//! the [`host`] slot, reached through the authenticated SOCKS5 [`bridge`]. A chosen kind that is
//! not ready refuses in process: nothing ever falls back to a direct socket.
//!
//! Inside `community/` refer to this module as `crate::transport::…`: the name collides with
//! `community::transport`.

pub mod aliases;
pub mod budget;
pub mod cycle;
pub mod guard;
pub mod host;
pub mod i2p_config;
pub mod tor_config;
pub mod kinds;
pub mod prefs;
pub mod prelogin;
pub mod realtime;
pub mod route;
pub mod status;
pub mod ws;
#[cfg(not(target_arch = "wasm32"))]
pub mod bridge;
#[cfg(not(target_arch = "wasm32"))]
pub mod runtime;
#[cfg(all(feature = "twin-check", not(target_arch = "wasm32")))]
pub mod twins;
#[cfg(test)]
mod tests;

#[cfg(not(target_arch = "wasm32"))]
pub use runtime::{runtime, spawn_on};

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::OnceLock;

pub use budget::{budget, Budgets, Op};
pub use route::{nip11_url, validate_relay_url, Dest, Refusal, Route};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    Clearnet,
    Tor,
    I2p,
}

impl Kind {
    pub const ALL: [Kind; 3] = [Kind::Clearnet, Kind::Tor, Kind::I2p];

    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Clearnet => "clearnet",
            Kind::Tor => "tor",
            Kind::I2p => "i2p",
        }
    }

    pub fn parse(s: &str) -> Option<Kind> {
        Kind::ALL.into_iter().find(|k| k.as_str() == s)
    }

    pub fn label(self) -> &'static str {
        match self {
            Kind::Clearnet => "Standard",
            Kind::Tor => "Tor",
            Kind::I2p => "I2P",
        }
    }

    /// Whether this build can run the kind. Never true for an anonymity kind on wasm32.
    pub fn compiled(self) -> bool {
        match self {
            Kind::Clearnet => true,
            Kind::Tor => cfg!(all(feature = "tor", not(target_arch = "wasm32"))),
            Kind::I2p => cfg!(all(feature = "i2p", not(target_arch = "wasm32"))),
        }
    }

    /// Names only this kind can reach. Known in every build, so a build without the kind still
    /// refuses them before any DNS.
    pub fn native_suffixes(self) -> &'static [&'static str] {
        match self {
            Kind::Clearnet => &[],
            Kind::Tor => &[".onion"],
            Kind::I2p => &[".i2p"],
        }
    }

    /// Whether this build reaches the kind's own addresses: a `.onion` needs the embedded Tor.
    pub fn reaches_native(self) -> bool {
        match self {
            Kind::I2p => true,
            Kind::Tor => cfg!(all(feature = "tor", not(target_arch = "wasm32"))),
            Kind::Clearnet => false,
        }
    }

    /// What a server's address inside this network is called, for a twin.
    pub fn address_noun(self) -> &'static str {
        match self {
            Kind::Tor => "onion address",
            Kind::I2p => "I2P address",
            Kind::Clearnet => "address",
        }
    }

    pub fn budgets(self) -> &'static Budgets {
        budget::table(self)
    }

    fn code(self) -> u8 {
        match self {
            Kind::Clearnet => 1,
            Kind::Tor => 2,
            Kind::I2p => 3,
        }
    }

    fn from_code(c: u8) -> Option<Kind> {
        match c {
            1 => Some(Kind::Clearnet),
            2 => Some(Kind::Tor),
            3 => Some(Kind::I2p),
            _ => None,
        }
    }
}

/// Compiled kinds, in `Kind` order.
pub fn supported() -> Vec<Kind> {
    Kind::ALL.into_iter().filter(|k| k.compiled()).collect()
}

/// Which identity a connection speaks for. I2P gives each lane its own destination, so a host a
/// stranger names only ever learns the Shared one.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Lane {
    Account,
    Shared,
}

#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
impl Lane {
    fn tag(self) -> char {
        match self {
            Lane::Account => 'a',
            Lane::Shared => 's',
        }
    }

    fn from_tag(c: &str) -> Option<Lane> {
        match c {
            "a" => Some(Lane::Account),
            "s" => Some(Lane::Shared),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExitPolicy {
    #[default]
    Allow,
    Off,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransportState {
    /// Preference not loaded or unparseable: blocked.
    Unknown,
    Clearnet,
    /// The chosen kind's instance is installed, owned by the live session and ready.
    Active { kind: Kind },
    /// Kind chosen but not ready (starting, retrying, failed, not in this build): blocked.
    RequiredButInactive { kind: Kind },
}

/// What a proxied connection proves to the bridge: the session that built the client, the epoch
/// it was decided in, and the lane it speaks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Ticket {
    pub owner: u64,
    pub epoch: u64,
    pub lane: Lane,
}

#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
impl Ticket {
    pub(crate) fn encode(&self) -> String {
        format!("t1.{:x}.{:x}.{}", self.owner, self.epoch, self.lane.tag())
    }

    pub(crate) fn decode(s: &str) -> Option<Ticket> {
        let mut parts = s.split('.');
        if parts.next()? != "t1" {
            return None;
        }
        let owner = u64::from_str_radix(parts.next()?, 16).ok()?;
        let epoch = u64::from_str_radix(parts.next()?, 16).ok()?;
        let lane = Lane::from_tag(parts.next()?)?;
        if parts.next().is_some() {
            return None;
        }
        Some(Ticket { owner, epoch, lane })
    }

    /// Owned by the live session and decided in the current epoch.
    pub fn is_live(&self) -> bool {
        self.owner == crate::db::live_session_id() && self.epoch == epoch()
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Egress {
    Direct,
    Proxy(Ticket),
    Refuse(ConnectError),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConnectError {
    Refused(Refusal),
    /// `None` while the preference is Unknown.
    NotReady(Option<Kind>),
    /// The chosen kind is blocked with a status reason: that reason's text.
    Blocked(String),
    /// A ticket from an older epoch, or a session that is no longer live.
    Stale,
    RouterDown { port: u16 },
    UnknownName,
    /// The destination or exit is unreachable; the detail is for logs (Tor: arti's text).
    Unreachable(String),
    /// The exit was reached and couldn't reach the server itself; the exit's name.
    ExitUnreachable(String),
    NoExit,
    ExitRefusedPort(u16),
    Timeout,
    /// The SOCKS client hung up mid-dial.
    Cancelled,
    /// The bridge could not bind; the detail is for logs.
    Bridge(String),
}

impl ConnectError {
    pub fn socks_reply(&self) -> u8 {
        match self {
            ConnectError::Refused(_) | ConnectError::Stale => 0x02,
            ConnectError::NotReady(_) | ConnectError::Blocked(_) | ConnectError::Bridge(_) | ConnectError::Cancelled => 0x01,
            ConnectError::RouterDown { .. } => 0x03,
            ConnectError::UnknownName
            | ConnectError::Unreachable(_)
            | ConnectError::ExitUnreachable(_)
            | ConnectError::NoExit
            | ConnectError::ExitRefusedPort(_) => 0x04,
            ConnectError::Timeout => 0x06,
        }
    }

    /// The line the UI shows. `Unreachable` keeps arti's text under Tor.
    pub fn text(&self) -> String {
        match self {
            ConnectError::Refused(r) => r.text(),
            ConnectError::NotReady(None) => "Vector is still connecting.".into(),
            ConnectError::NotReady(Some(k)) => format!("{} is still connecting.", k.label()),
            ConnectError::Blocked(t) => t.clone(),
            ConnectError::Stale => "The network changed. Try again.".into(),
            ConnectError::RouterDown { port } => match preference() {
                Some(Kind::Tor) => format!("Can't reach Tor at 127.0.0.1:{port}."),
                _ => format!("Can't reach your I2P router at 127.0.0.1:{port}."),
            },
            ConnectError::UnknownName => "This I2P name isn't in your router's address book. Use its .b32.i2p address.".into(),
            ConnectError::Unreachable(detail) => match preference() {
                Some(Kind::I2p) => "This I2P address isn't online right now.".into(),
                _ => detail.clone(),
            },
            ConnectError::ExitUnreachable(name) => format!("The {name} outproxy couldn't reach this server."),
            ConnectError::NoExit => "No outproxy is reachable right now.".into(),
            ConnectError::ExitRefusedPort(p) => format!("No outproxy here allows port {p}."),
            ConnectError::Timeout => "Timed out.".into(),
            ConnectError::Cancelled => "Cancelled.".into(),
            ConnectError::Bridge(_) => "Vector couldn't open its local proxy.".into(),
        }
    }

    /// The network will come back on its own: a policy refusal won't, nor will a stale owner (a
    /// session never becomes live again once replaced), nor a block only the user can lift.
    pub fn is_transient(&self) -> bool {
        match self {
            ConnectError::NotReady(_) => true,
            ConnectError::Blocked(_) => !status::waits_for_user(),
            _ => false,
        }
    }

    /// Our side of the connection failed (the network, its router, its exits), so the failure
    /// says nothing about the server.
    pub fn is_network(&self) -> bool {
        matches!(
            self,
            ConnectError::NotReady(_)
                | ConnectError::Blocked(_)
                | ConnectError::Stale
                | ConnectError::RouterDown { .. }
                | ConnectError::NoExit
                | ConnectError::ExitRefusedPort(_)
                | ConnectError::Bridge(_)
        )
    }
}

impl std::fmt::Display for ConnectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text())
    }
}

impl std::error::Error for ConnectError {}

pub trait AsyncStream: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin {}
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> AsyncStream for T {}
pub type BoxedStream = Box<dyn AsyncStream>;

/// A kind's parsed config, opaque to shared code; each kind downcasts its own type.
pub type KindConfig = std::sync::Arc<dyn std::any::Any + Send + Sync>;

/// The live session's routing inputs, read per dial so an instance never holds a stale copy.
pub struct RouteCtx<'a> {
    pub aliases: &'a aliases::AliasTable,
    pub config: &'a KindConfig,
}

#[derive(Clone, Debug, Default)]
pub struct Dialed {
    /// The outproxy id an `Exit` used.
    pub outproxy: Option<String>,
}

#[async_trait::async_trait]
pub trait Transport: Send + Sync + 'static {
    fn kind(&self) -> Kind;
    /// This kind's rules, after the shared pre-router. Pure, no I/O.
    fn route(&self, dest: &Dest, port: u16, ctx: &RouteCtx) -> Route;
    /// Open the stream `route` names for `lane`. Ok only once the far end exists.
    async fn dial(&self, route: &Route, lane: Lane) -> Result<(BoxedStream, Dialed), ConnectError>;
    fn ready(&self) -> bool;
    fn kind_status(&self) -> status::KindStatus;
    /// Unlinkable from here on.
    async fn new_identity(&self);
    async fn shutdown(&self);
    fn into_any(self: std::sync::Arc<Self>) -> std::sync::Arc<dyn std::any::Any + Send + Sync>;
    /// The instance itself, for a factory's `compatible` (which holds no `Arc`).
    fn as_any(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
        None
    }
}

pub struct StartCtx {
    pub owner: u64,
    pub started_prelogin: bool,
    /// Tor: state and cache dirs.
    pub dirs: Option<(std::path::PathBuf, std::path::PathBuf)>,
    pub config: KindConfig,
}

#[async_trait::async_trait]
pub trait TransportFactory: Send + Sync + 'static {
    fn kind(&self) -> Kind;
    /// Tor bootstraps within `budget(Startup)` and returns a ready instance; others may return at
    /// once and report Ready through `host::notify`.
    async fn start(&self, ctx: StartCtx) -> Result<std::sync::Arc<dyn Transport>, String>;
    /// Keep a welcome-screen instance when an existing account is unlocked.
    fn adopt_on_unlock(&self) -> bool;
    /// Whether `inst` can serve an account whose config is `cfg`.
    fn compatible(&self, inst: &dyn Transport, cfg: &KindConfig) -> bool;
}

// ── Epoch and policy generation ──────────────────────────────────────────────

static EPOCH: AtomicU64 = AtomicU64::new(1);
static POLICY_GEN: AtomicU64 = AtomicU64::new(1);

fn epoch_tx() -> &'static tokio::sync::watch::Sender<u64> {
    static TX: OnceLock<tokio::sync::watch::Sender<u64>> = OnceLock::new();
    TX.get_or_init(|| tokio::sync::watch::channel(EPOCH.load(Ordering::Acquire)).0)
}

/// Bumped only when the egress decision can change: preference, live session, an instance
/// installed or removed, or its readiness.
pub fn epoch() -> u64 {
    EPOCH.load(Ordering::Acquire)
}

/// Bumped when a routing input of the live session changes: exit policy, outproxies, aliases.
pub fn policy_gen() -> u64 {
    POLICY_GEN.load(Ordering::Acquire)
}

pub(crate) fn bump_policy_gen() -> u64 {
    POLICY_GEN.fetch_add(1, Ordering::AcqRel) + 1
}

/// Advance the epoch: drop every HTTP client, abort every bridge connection of an older epoch,
/// then wake guarded streams and body reads.
pub(crate) fn bump_epoch() -> u64 {
    let next = EPOCH.fetch_add(1, Ordering::AcqRel) + 1;
    crate::net::forget_clients();
    #[cfg(not(target_arch = "wasm32"))]
    bridge::abort_where(|c| c.ticket.is_some_and(|t| t.epoch < next));
    epoch_tx().send_replace(next);
    next
}

/// Resolves once `epoch() != since`.
pub async fn changed(since: u64) {
    let mut rx = epoch_tx().subscribe();
    loop {
        if *rx.borrow_and_update() != since || epoch() != since {
            return;
        }
        if rx.changed().await.is_err() {
            std::future::pending::<()>().await;
        }
    }
}

/// The installed session changed: guarded sockets of the outgoing account close.
pub(crate) fn on_session_installed(prev: u64, next: u64) {
    if prev != next {
        bump_epoch();
    }
}

// ── Preference and state ─────────────────────────────────────────────────────

static STRICT: AtomicBool = AtomicBool::new(false);

/// First-party binaries that hold accounts call this once at startup: every session from here on
/// starts Unknown (blocked) until its stored network is loaded.
pub fn strict_boot() {
    STRICT.store(true, Ordering::Release);
}

pub(crate) fn is_strict() -> bool {
    STRICT.load(Ordering::Acquire)
}

#[cfg(test)]
pub(crate) fn set_strict_for_test(on: bool) {
    STRICT.store(on, Ordering::Release);
}

/// The live session's chosen kind. `None` = Unknown.
pub fn preference() -> Option<Kind> {
    prefs::live().kind()
}

/// Set the live session's kind. Bumps the epoch when it changes; a kind change also drops that
/// session's realtime consent.
pub fn set_preference(kind: Option<Kind>) {
    prefs::set_kind(&crate::db::live_session(), kind);
}

pub fn state() -> TransportState {
    state_for(preference())
}

fn state_for(pref: Option<Kind>) -> TransportState {
    match pref {
        None => TransportState::Unknown,
        Some(Kind::Clearnet) => TransportState::Clearnet,
        Some(k) => match host::active() {
            Some(a) if a.kind == k && a.owner() == crate::db::live_session_id() && a.transport().ready() => {
                TransportState::Active { kind: k }
            }
            _ => TransportState::RequiredButInactive { kind: k },
        },
    }
}

/// Why nothing can leave right now, while the chosen network isn't usable.
pub fn blocked_reason() -> Option<String> {
    match state() {
        TransportState::Clearnet | TransportState::Active { .. } => None,
        TransportState::Unknown => Some(ConnectError::NotReady(None).text()),
        TransportState::RequiredButInactive { kind } => Some(blocked_error(kind).text()),
    }
}

/// Why the chosen kind refuses right now, for `RequiredButInactive`.
fn blocked_error(k: Kind) -> ConnectError {
    match status::reason_for(k) {
        Some(r) => ConnectError::Blocked(r.text),
        None => ConnectError::NotReady(Some(k)),
    }
}

/// The one decision every TCP egress makes. `owner` is the session the client was built under.
pub fn egress(owner: u64, lane: Lane, host: &str, port: u16) -> Egress {
    if owner != crate::db::live_session_id() {
        return Egress::Refuse(ConnectError::Stale);
    }
    let dest = match Dest::parse(host) {
        Some(d) => d,
        None => return Egress::Refuse(ConnectError::Refused(Refusal::BadName)),
    };
    let pref = preference();
    if let Some(r) = route::pre_route(pref.unwrap_or(Kind::Clearnet), &dest) {
        return Egress::Refuse(ConnectError::Refused(r));
    }
    match state_for(pref) {
        TransportState::Clearnet => Egress::Direct,
        TransportState::Unknown => Egress::Refuse(ConnectError::NotReady(None)),
        TransportState::RequiredButInactive { kind } => Egress::Refuse(blocked_error(kind)),
        TransportState::Active { kind } => {
            let Some(active) = host::active().filter(|a| a.kind == kind) else {
                return Egress::Refuse(ConnectError::NotReady(Some(kind)));
            };
            let p = prefs::live();
            let (aliases, config) = (p.aliases(), p.config(kind));
            let ctx = RouteCtx { aliases: &aliases, config: &config };
            match active.transport().route(&dest, port, &ctx) {
                Route::Refuse(r) => Egress::Refuse(ConnectError::Refused(r)),
                _ => Egress::Proxy(Ticket { owner, epoch: epoch(), lane }),
            }
        }
    }
}

/// Host and port of a URL, with the scheme's default port.
pub(crate) fn host_port(url_or_host: &str) -> Option<(String, u16)> {
    if let Ok(u) = url::Url::parse(url_or_host) {
        if let (Some(h), Some(p)) = (u.host_str(), u.port_or_known_default()) {
            return Some((h.trim_start_matches('[').trim_end_matches(']').to_string(), p));
        }
    }
    if url_or_host.contains("://") || url_or_host.is_empty() {
        return None;
    }
    Some((url_or_host.to_string(), 443))
}

/// The refusal text when the live account's route can never reach this URL or host (relay
/// lists, community targets). Transient blocks are not refusals.
pub fn refuses(url_or_host: &str) -> Option<String> {
    refusal(url_or_host).map(|r| r.text())
}

/// The rule behind [`refuses`].
pub fn refusal(url_or_host: &str) -> Option<Refusal> {
    let (host, port) = host_port(url_or_host)?;
    let dest = Dest::parse(&host)?;
    let pref = preference()?;
    if let Some(r) = route::pre_route(pref, &dest) {
        return Some(r);
    }
    if let TransportState::Active { kind } = state_for(Some(pref)) {
        let active = host::active().filter(|a| a.kind == kind)?;
        let p = prefs::live();
        let (aliases, config) = (p.aliases(), p.config(kind));
        if let Route::Refuse(r) = active.transport().route(&dest, port, &RouteCtx { aliases: &aliases, config: &config }) {
            return Some(r);
        }
    }
    None
}

pub fn route_view(url: &str) -> status::RouteView {
    status::route_view(url)
}

/// Hold until the chosen kind is ready or `max` passes. A block only the user can lift (a
/// failed start, a router that turned Vector down) ends the wait at once with its reason.
pub async fn wait_ready(max: std::time::Duration) -> Result<(), String> {
    let deadline = web_time::Instant::now() + max;
    loop {
        let since = epoch();
        match state() {
            TransportState::Clearnet | TransportState::Active { .. } => return Ok(()),
            TransportState::Unknown => {
                if web_time::Instant::now() >= deadline {
                    return Err(ConnectError::NotReady(None).text());
                }
            }
            TransportState::RequiredButInactive { kind } => {
                if status::waits_for_user() || web_time::Instant::now() >= deadline {
                    return Err(blocked_error(kind).text());
                }
            }
        }
        let left = deadline.saturating_duration_since(web_time::Instant::now());
        // A ready flip always bumps the epoch; the short tick covers a state read between bumps.
        let _ = crate::rt::time::timeout(left.min(std::time::Duration::from_secs(1)), changed(since)).await;
    }
}