1use std::collections::{BTreeMap, HashMap};
6use std::sync::Arc;
7
8use super::Kind;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum AliasSource {
13 #[default]
14 User,
15 Nip11,
16 BuiltIn,
18}
19
20pub const BUILT_IN: &[(&str, Kind, &str)] = &[
23 ("jskitty.com", Kind::Tor, "jskittynoz22rnwlzyg2akvixkyqp243dd4iq7rs2imry5d6imv4uoyd.onion"),
24 ("jskitty.com", Kind::I2p, "nk7ghqbv2nwrleccnq5yz5nsvbkkufhwvcya5gqskxv37bnbfaea.b32.i2p"),
25 ("asia.vectorapp.io", Kind::Tor, "asiawyhvqt5cn3orhwogcxviob4pjkeipjpeznkf4neyyuisgzplllad.onion"),
26 ("asia.vectorapp.io", Kind::I2p, "jsctxliao4jvgyqmojuvn52cnicbuum6nocb23i53b2zha2vfpca.b32.i2p"),
27 ("magnitude.vectorapp.io", Kind::Tor, "mag2izmzc7nlzx3iixzi7kdppr7hm2p7kcwnqg6j7kluhp2htcrfphqd.onion"),
28 ("magnitude.vectorapp.io", Kind::I2p, "hr4zsnf7jpgayicqxmhxyrmhufftfix4ru373wujs6s53kzi5ijq.b32.i2p"),
29 ("magnitude.jskitty.com", Kind::Tor, "mag2izmzc7nlzx3iixzi7kdppr7hm2p7kcwnqg6j7kluhp2htcrfphqd.onion"),
30 ("magnitude.jskitty.com", Kind::I2p, "hr4zsnf7jpgayicqxmhxyrmhufftfix4ru373wujs6s53kzi5ijq.b32.i2p"),
31];
32
33#[cfg(test)]
34static BUILT_INS_OFF: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
35
36#[cfg(test)]
38pub(crate) fn built_ins_for_test(on: bool) {
39 BUILT_INS_OFF.store(!on, std::sync::atomic::Ordering::Release);
40}
41
42fn built_ins() -> &'static [(&'static str, Kind, &'static str)] {
43 #[cfg(test)]
44 if BUILT_INS_OFF.load(std::sync::atomic::Ordering::Acquire) {
45 return &[];
46 }
47 BUILT_IN
48}
49
50fn has_built_in(host: &str) -> bool {
51 built_ins().iter().any(|(h, _, _)| *h == host)
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
55#[serde(rename_all = "lowercase")]
56pub enum CheckState {
57 #[default]
58 Unchecked,
59 Ok,
60 Failed,
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
64pub struct AliasCheck {
65 pub state: CheckState,
66 #[serde(default)]
67 pub at: Option<u64>,
68 #[serde(default)]
69 pub text: Option<String>,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub struct AliasEntry {
74 pub host: String,
75 pub twins: BTreeMap<Kind, String>,
76 #[serde(default)]
77 pub source: AliasSource,
78 #[serde(default)]
79 pub check: AliasCheck,
80}
81
82#[derive(Clone, Debug)]
83pub struct AliasTable {
84 by_host: HashMap<String, AliasEntry>,
85}
86
87impl Default for AliasTable {
88 fn default() -> Self {
89 Self::from_entries(Vec::new())
90 }
91}
92
93impl AliasTable {
94 pub fn from_entries(entries: Vec<AliasEntry>) -> Self {
96 let mut by_host: HashMap<String, AliasEntry> = entries.into_iter().map(|e| (e.host.clone(), e)).collect();
97 for (host, kind, addr) in built_ins() {
98 let e = by_host.entry(host.to_string()).or_insert_with(|| AliasEntry {
99 host: host.to_string(),
100 twins: BTreeMap::new(),
101 source: AliasSource::BuiltIn,
102 check: AliasCheck::default(),
103 });
104 if e.source == AliasSource::BuiltIn {
105 e.twins.entry(*kind).or_insert_with(|| addr.to_string());
106 }
107 }
108 AliasTable { by_host }
109 }
110
111 pub fn parse(json: Option<&str>) -> Self {
112 Self::from_entries(json.and_then(|j| serde_json::from_str::<Vec<AliasEntry>>(j).ok()).unwrap_or_default())
113 }
114
115 pub fn twin(&self, host: &str, kind: Kind) -> Option<&str> {
117 let e = self.by_host.get(host)?;
118 if e.check.state == CheckState::Failed {
119 return None;
120 }
121 e.twins.get(&kind).map(String::as_str)
122 }
123
124 pub fn get(&self, host: &str) -> Option<&AliasEntry> {
125 self.by_host.get(host)
126 }
127
128 pub fn entries(&self) -> Vec<AliasEntry> {
129 let mut v: Vec<AliasEntry> = self.by_host.values().cloned().collect();
130 v.sort_by(|a, b| a.host.cmp(&b.host));
131 v
132 }
133
134 fn to_json(&self) -> String {
135 let saved: Vec<AliasEntry> = self.entries().into_iter().filter(|e| e.source != AliasSource::BuiltIn).collect();
136 serde_json::to_string(&saved).unwrap_or_else(|_| "[]".into())
137 }
138}
139
140pub fn table() -> Arc<AliasTable> {
142 super::prefs::live().aliases()
143}
144
145pub fn normalize_host(input: &str) -> Result<String, String> {
147 let (host, _) = super::host_port(input.trim()).ok_or_else(|| "That isn't a valid server address.".to_string())?;
148 match super::Dest::parse(&host) {
149 Some(super::Dest::Domain(d)) if super::route::valid_hostname(&d) => Ok(d),
150 _ => Err("That isn't a valid server address.".into()),
151 }
152}
153
154pub fn validate_twin(kind: Kind, addr: &str) -> Result<String, String> {
155 match kind {
156 Kind::I2p if super::i2p_config::is_i2p_address(addr) => Ok(addr.trim().to_ascii_lowercase()),
157 Kind::I2p => Err("Enter a .b32.i2p address.".into()),
158 Kind::Tor if super::route::is_onion(&addr.trim().to_ascii_lowercase()) => Ok(addr.trim().to_ascii_lowercase()),
159 Kind::Tor => Err("Enter a .onion address.".into()),
160 _ => Err(format!("{} addresses aren't supported yet.", kind.label())),
161 }
162}
163
164fn now() -> u64 {
165 crate::clock::now_secs()
166}
167
168struct AliasWrites;
169
170fn write_lock(session: &Arc<crate::db::Session>) -> Arc<std::sync::Mutex<()>> {
173 session.scoped::<AliasWrites, std::sync::Mutex<()>>()
174}
175
176pub fn set(host: &str, kind: Kind, addr: Option<&str>, source: AliasSource) -> Result<Option<AliasEntry>, String> {
180 let host = normalize_host(host)?;
181 let addr = addr.map(|a| validate_twin(kind, a)).transpose()?;
182 let session = crate::db::current_session();
183 let lock = write_lock(&session);
184 let _write = lock.lock().unwrap_or_else(|e| e.into_inner());
185 let prefs = super::prefs::of(&session);
186 let current = prefs.aliases();
187 let mut map = current.by_host.clone();
188 let result = match addr {
189 Some(a) => {
190 let e = map.entry(host.clone()).or_insert_with(|| AliasEntry {
191 host: host.clone(),
192 twins: BTreeMap::new(),
193 source,
194 check: AliasCheck::default(),
195 });
196 if e.twins.get(&kind) != Some(&a) {
197 e.twins.insert(kind, a);
198 e.check = AliasCheck::default();
199 }
200 e.source = source;
201 Some(e.clone())
202 }
203 None => {
204 if let Some(e) = map.get_mut(&host) {
205 e.twins.remove(&kind);
206 e.source = source;
207 if e.twins.is_empty() && !has_built_in(&host) {
209 map.remove(&host);
210 }
211 }
212 None
213 }
214 };
215 let next = AliasTable { by_host: map };
216 super::prefs::persist_setting(super::prefs::KEY_ALIASES, &next.to_json())?;
217 apply(&session, next, &host);
218 Ok(result)
219}
220
221pub fn record_check(host: &str, check: AliasCheck) -> Result<(), String> {
223 write_check(host, None, check)
224}
225
226pub fn record_check_for(host: &str, kind: Kind, via: &str, check: AliasCheck) -> Result<(), String> {
229 write_check(host, Some((kind, via)), check)
230}
231
232fn write_check(host: &str, probed: Option<(Kind, &str)>, check: AliasCheck) -> Result<(), String> {
233 let host = normalize_host(host)?;
234 let session = crate::db::current_session();
235 let lock = write_lock(&session);
236 let _write = lock.lock().unwrap_or_else(|e| e.into_inner());
237 let prefs = super::prefs::of(&session);
238 let mut map = prefs.aliases().by_host.clone();
239 let Some(e) = map.get_mut(&host) else { return Ok(()) };
240 if let Some((kind, via)) = probed {
241 if e.twins.get(&kind).map(String::as_str) != Some(via) {
242 return Ok(());
243 }
244 }
245 let mut check = check;
246 if check.at.is_none() {
247 check.at = Some(now());
248 }
249 e.check = check;
250 let next = AliasTable { by_host: map };
251 super::prefs::persist_setting(super::prefs::KEY_ALIASES, &next.to_json())?;
252 apply(&session, next, &host);
253 Ok(())
254}
255
256fn apply(session: &Arc<crate::db::Session>, next: AliasTable, host: &str) {
257 #[cfg(target_arch = "wasm32")]
258 let _ = host;
259 super::prefs::of(session).set_aliases(Arc::new(next));
260 if session.is_live() {
261 super::bump_policy_gen();
262 #[cfg(not(target_arch = "wasm32"))]
263 super::bridge::abort_where(|c| matches!(&c.route, Some(super::Route::Twin { host: h, .. }) if h == host));
264 super::host::notify(super::host::TransportEvent::Changed);
265 }
266}