1pub 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 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 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 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 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
133pub fn supported() -> Vec<Kind> {
135 Kind::ALL.into_iter().filter(|k| k.compiled()).collect()
136}
137
138#[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 Unknown,
176 Clearnet,
177 Active { kind: Kind },
179 RequiredButInactive { kind: Kind },
181}
182
183#[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 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 NotReady(Option<Kind>),
230 Blocked(String),
232 Stale,
234 RouterDown { port: u16 },
235 UnknownName,
236 Unreachable(String),
238 ExitUnreachable(String),
240 NoExit,
241 ExitRefusedPort(u16),
242 Timeout,
243 Cancelled,
245 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 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 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 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
328pub type KindConfig = std::sync::Arc<dyn std::any::Any + Send + Sync>;
330
331pub 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 pub outproxy: Option<String>,
341}
342
343#[async_trait::async_trait]
344pub trait Transport: Send + Sync + 'static {
345 fn kind(&self) -> Kind;
346 fn route(&self, dest: &Dest, port: u16, ctx: &RouteCtx) -> Route;
348 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 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 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 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 async fn start(&self, ctx: StartCtx) -> Result<std::sync::Arc<dyn Transport>, String>;
376 fn adopt_on_unlock(&self) -> bool;
378 fn compatible(&self, inst: &dyn Transport, cfg: &KindConfig) -> bool;
380}
381
382static 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
392pub fn epoch() -> u64 {
395 EPOCH.load(Ordering::Acquire)
396}
397
398pub 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
407pub(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
418pub 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
431pub(crate) fn on_session_installed(prev: u64, next: u64) {
433 if prev != next {
434 bump_epoch();
435 }
436}
437
438static STRICT: AtomicBool = AtomicBool::new(false);
441
442pub 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
457pub fn preference() -> Option<Kind> {
459 prefs::live().kind()
460}
461
462pub 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
485pub 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
494fn 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
502pub 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
534pub(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
547pub fn refuses(url_or_host: &str) -> Option<String> {
550 refusal(url_or_host).map(|r| r.text())
551}
552
553pub 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
576pub 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 let _ = crate::rt::time::timeout(left.min(std::time::Duration::from_secs(1)), changed(since)).await;
598 }
599}