vector_core/transport/
twins.rs1use std::sync::Arc;
7use std::time::Duration;
8
9use super::aliases::{self, AliasCheck, AliasEntry, CheckState};
10use super::host::ActiveTransport;
11use super::{ConnectError, ExitPolicy, Kind, Lane, Route};
12
13const TLS_DEADLINE: Duration = Duration::from_secs(60);
14const NIP11_TIMEOUT: Duration = Duration::from_secs(60);
15
16fn tls_config() -> Result<Arc<rustls::ClientConfig>, String> {
17 let roots = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec() };
18 let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
19 .with_safe_default_protocol_versions()
20 .map_err(|e| e.to_string())?
21 .with_root_certificates(roots)
22 .with_no_client_auth();
23 Ok(Arc::new(cfg))
24}
25
26pub fn served_text(host: &str) -> String {
27 format!("Checked. It serves {host}.")
28}
29
30pub fn not_served_text(host: &str) -> String {
31 format!("This address doesn't serve {host}. Vector won't use it.")
32}
33
34pub async fn tls_check<S>(host: &str, stream: Result<S, ConnectError>) -> AliasCheck
37where
38 S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
39{
40 let unchecked = |text: String| AliasCheck { state: CheckState::Unchecked, at: None, text: Some(text) };
41 let stream = match stream {
42 Ok(s) => s,
43 Err(e) => return unchecked(e.text()),
44 };
45 let Ok(name) = rustls::pki_types::ServerName::try_from(host.to_string()) else {
46 return AliasCheck { state: CheckState::Failed, at: None, text: Some(not_served_text(host)) };
47 };
48 let config = match tls_config() {
49 Ok(c) => c,
50 Err(e) => return unchecked(e),
51 };
52 let connector = tokio_rustls::TlsConnector::from(config);
53 match tokio::time::timeout(TLS_DEADLINE, connector.connect(name, stream)).await {
54 Ok(Ok(_)) => AliasCheck { state: CheckState::Ok, at: None, text: Some(served_text(host)) },
55 Ok(Err(e)) => {
56 crate::log_debug!("[Twins] check for {host}: {e}");
57 AliasCheck { state: CheckState::Failed, at: None, text: Some(not_served_text(host)) }
58 }
59 Err(_) => unchecked(ConnectError::Timeout.text()),
60 }
61}
62
63pub async fn probe(a: &ActiveTransport, host: &str, via: &str) -> AliasCheck {
65 let route = Route::Twin { host: host.to_string(), via: via.to_string(), port: 443 };
66 tls_check(host, a.transport().dial(&route, Lane::Shared).await.map(|(s, _)| s)).await
67}
68
69fn ready_active() -> Result<Arc<ActiveTransport>, String> {
71 let chosen = super::preference().filter(|k| *k != Kind::Clearnet);
72 match (chosen, super::host::active()) {
73 (Some(k), Some(a)) if a.kind == k && a.serves_live() && a.transport().ready() => Ok(a),
74 (Some(k), _) => Err(format!("Connect to {} to check this address.", k.label())),
75 (None, _) => Err("Use Tor or I2P to check this address.".into()),
76 }
77}
78
79pub async fn check_alias(host: &str) -> Result<AliasEntry, String> {
81 let host = aliases::normalize_host(host)?;
82 let a = ready_active()?;
83 let missing = || format!("This server has no {} yet.", a.kind.address_noun());
84 let via = aliases::table().get(&host).and_then(|e| e.twins.get(&a.kind).cloned()).ok_or_else(missing)?;
85 let check = probe(&a, &host, &via).await;
86 aliases::record_check_for(&host, a.kind, &via, check)?;
87 aliases::table().get(&host).cloned().ok_or_else(missing)
88}
89
90#[derive(Clone, Debug, serde::Serialize)]
91pub struct FindAlias {
92 pub found: Option<String>,
93 pub check: Option<AliasCheck>,
94 pub text: String,
95}
96
97pub async fn find_alias(url: &str) -> Result<FindAlias, String> {
100 let host = aliases::normalize_host(url)?;
101 let a = ready_active()?;
102 if a.kind == Kind::I2p {
103 let cfg = super::prefs::current().config(Kind::I2p);
104 if cfg.downcast_ref::<super::i2p_config::I2pConfig>().is_some_and(|c| c.exit == ExitPolicy::Off) {
105 return Err("Can't look it up in I2P-Only mode.".into());
106 }
107 }
108 let noun = a.kind.address_noun();
109 match find_privacy_address(url, a.kind).await? {
110 None => Ok(FindAlias { found: None, check: None, text: format!("This relay doesn't list an {noun}.") }),
111 Some(addr) => {
112 let mut check = probe(&a, &host, &addr).await;
113 check.at = Some(now_secs());
114 Ok(FindAlias { found: Some(addr), check: Some(check), text: format!("This relay lists an {noun}.") })
115 }
116 }
117}
118
119fn now_secs() -> u64 {
120 crate::clock::now_secs()
121}
122
123pub async fn find_privacy_address(relay_url: &str, kind: Kind) -> Result<Option<String>, String> {
126 let client = crate::net::build_http_client(NIP11_TIMEOUT)?;
127 let resp = client
128 .get(nip11_url(relay_url)?)
129 .header("Accept", "application/nostr+json")
130 .send()
131 .await
132 .map_err(|e| e.to_string())?;
133 if !resp.status().is_success() {
134 return Ok(None);
135 }
136 let Ok(doc) = resp.json::<serde_json::Value>().await else { return Ok(None) };
137 Ok(first_privacy_address(&doc, kind))
138}
139
140pub use super::route::nip11_url;
141
142pub fn first_privacy_address(doc: &serde_json::Value, kind: Kind) -> Option<String> {
145 let list = doc.get("privacy_addresses")?.as_array()?;
146 list.iter().filter_map(|v| v.as_str()).find_map(|s| {
147 let s = s.trim();
148 let host = match url::Url::parse(s) {
149 Ok(u) if u.host_str().is_some() => u.host_str().map(str::to_ascii_lowercase),
150 _ => Some(s.split(['/', ':']).next().unwrap_or("").to_ascii_lowercase()),
151 }?;
152 let ours = match kind {
153 Kind::I2p => super::route::is_b32(&host),
154 Kind::Tor => super::route::is_onion(&host),
155 Kind::Clearnet => false,
156 };
157 ours.then_some(host)
158 })
159}
160
161pub fn check_pending() {
164 let Some(a) = super::host::active().filter(|a| a.serves_live() && a.transport().ready()) else { return };
165 let session = crate::db::live_session();
166 let pending: Vec<(String, String)> = super::prefs::of(&session)
167 .aliases()
168 .entries()
169 .into_iter()
170 .filter(|e| e.check.state == CheckState::Unchecked)
171 .filter_map(|e| e.twins.get(&a.kind).cloned().map(|v| (e.host, v)))
172 .collect();
173 if pending.is_empty() {
174 return;
175 }
176 drop(super::spawn_on(crate::db::with_session(session, async move {
178 for (host, via) in pending {
179 if !a.serves_live() || !a.transport().ready() {
180 return;
181 }
182 let check = probe(&a, &host, &via).await;
183 if check.state == CheckState::Unchecked {
184 continue;
185 }
186 if let Err(e) = aliases::record_check_for(&host, a.kind, &via, check) {
187 crate::log_warn!("[Twins] could not save a twin check: {e}");
188 }
189 }
190 })));
191}