1use super::{ExitPolicy, Kind, RouteCtx};
5
6#[derive(Clone, Debug, PartialEq, Eq, Hash)]
7pub enum Dest {
8 Domain(String),
10 Ip(std::net::IpAddr),
11}
12
13impl Dest {
14 pub fn parse(host: &str) -> Option<Dest> {
17 let h = host.trim_start_matches('[').trim_end_matches(']');
18 if h.is_empty() {
19 return None;
20 }
21 if let Ok(ip) = h.parse::<std::net::IpAddr>() {
22 return Some(Dest::Ip(ip));
23 }
24 let lower = h.to_ascii_lowercase();
25 let name = lower.strip_suffix('.').unwrap_or(&lower);
26 if name.is_empty() {
27 return None;
28 }
29 if let Ok(ip) = name.parse::<std::net::IpAddr>() {
30 return Some(Dest::Ip(ip));
31 }
32 Some(Dest::Domain(name.to_string()))
33 }
34
35 pub fn host(&self) -> String {
36 match self {
37 Dest::Domain(d) => d.clone(),
38 Dest::Ip(ip) => ip.to_string(),
39 }
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub enum Route {
45 Native { host: String, port: u16 },
47 Twin { host: String, via: String, port: u16 },
49 Exit { host: String, port: u16 },
51 Refuse(Refusal),
52}
53
54impl Route {
55 pub fn class(&self) -> &'static str {
56 match self {
57 Route::Native { .. } => "native",
58 Route::Twin { .. } => "twin",
59 Route::Exit { .. } => "exit",
60 Route::Refuse(_) => "refused",
61 }
62 }
63
64 pub fn host(&self) -> Option<&str> {
65 match self {
66 Route::Native { host, .. } | Route::Twin { host, .. } | Route::Exit { host, .. } => Some(host),
67 Route::Refuse(_) => None,
68 }
69 }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Refusal {
74 WrongNetwork { needs: Kind },
75 NotReachable { network: Kind },
77 ExitOff,
78 IpLiteral,
79 LocalName,
80 BadName,
81}
82
83impl Refusal {
84 pub fn text(&self) -> String {
85 match self {
86 Refusal::WrongNetwork { needs } => format!("This server is only reachable over {}.", needs.label()),
87 Refusal::NotReachable { network } => {
88 format!("Vector can't reach {} addresses yet.", network.native_suffixes().first().copied().unwrap_or("these"))
89 }
90 Refusal::ExitOff => "I2P-Only is on, so this server is off.".into(),
91 Refusal::IpLiteral => "I2P can't reach a bare IP address.".into(),
92 Refusal::LocalName => "Local addresses aren't reachable over I2P.".into(),
93 Refusal::BadName => "That isn't a valid server address.".into(),
94 }
95 }
96}
97
98pub fn valid_hostname(h: &str) -> bool {
101 if h.is_empty() || h.len() > 253 {
102 return false;
103 }
104 h.split('.').all(|label| {
105 !label.is_empty()
106 && label.len() <= 63
107 && label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
108 })
109}
110
111pub fn is_b32(h: &str) -> bool {
113 let Some(label) = h.strip_suffix(".b32.i2p") else { return false };
114 (label.len() == 52 || label.len() >= 56) && label.bytes().all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
115}
116
117pub fn is_onion(h: &str) -> bool {
119 let Some(label) = h.strip_suffix(".onion") else { return false };
120 label.len() == 56 && label.bytes().all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
121}
122
123pub fn is_local_name(h: &str) -> bool {
124 h == "localhost"
125 || !h.contains('.')
126 || [".localhost", ".local", ".lan", ".internal", ".home.arpa"].iter().any(|s| h.ends_with(s))
127}
128
129fn has_suffix(name: &str, suffix: &str) -> bool {
130 name.ends_with(suffix) || name == &suffix[1..]
131}
132
133pub fn pre_route(chosen: Kind, dest: &Dest) -> Option<Refusal> {
136 let Dest::Domain(name) = dest else { return None };
137 if !valid_hostname(name) {
138 return Some(Refusal::BadName);
139 }
140 for k in Kind::ALL {
141 if k.native_suffixes().iter().any(|s| has_suffix(name, s)) {
142 if !k.reaches_native() {
143 return Some(Refusal::NotReachable { network: k });
144 }
145 if k != chosen {
146 return Some(Refusal::WrongNetwork { needs: k });
147 }
148 }
149 }
150 None
151}
152
153fn twin_for(dest: &Dest, port: u16, kind: Kind, ctx: &RouteCtx) -> Option<Route> {
154 let Dest::Domain(name) = dest else { return None };
155 if port != 443 {
156 return None;
157 }
158 ctx.aliases
159 .twin(name, kind)
160 .map(|via| Route::Twin { host: name.clone(), via: via.to_string(), port: 443 })
161}
162
163pub fn route_tor(dest: &Dest, port: u16, ctx: &RouteCtx) -> Route {
164 if let Dest::Domain(name) = dest {
165 if Kind::Tor.native_suffixes().iter().any(|s| has_suffix(name, s)) {
166 return Route::Native { host: name.clone(), port };
167 }
168 }
169 if let Some(twin) = twin_for(dest, port, Kind::Tor, ctx) {
170 return twin;
171 }
172 Route::Exit { host: dest.host(), port }
173}
174
175pub fn route_i2p(dest: &Dest, port: u16, ctx: &RouteCtx) -> Route {
176 if let Dest::Domain(name) = dest {
177 if Kind::I2p.native_suffixes().iter().any(|s| has_suffix(name, s)) {
178 return Route::Native { host: name.clone(), port };
179 }
180 }
181 if let Some(twin) = twin_for(dest, port, Kind::I2p, ctx) {
182 return twin;
183 }
184 match dest {
185 Dest::Ip(_) => Route::Refuse(Refusal::IpLiteral),
186 Dest::Domain(name) if is_local_name(name) => Route::Refuse(Refusal::LocalName),
187 Dest::Domain(name) => {
188 let exit = ctx
189 .config
190 .downcast_ref::<super::i2p_config::I2pConfig>()
191 .map(|c| c.exit)
192 .unwrap_or_default();
193 match exit {
194 ExitPolicy::Allow => Route::Exit { host: name.clone(), port },
195 ExitPolicy::Off => Route::Refuse(Refusal::ExitOff),
196 }
197 }
198 }
199}
200
201const RELAY_SCHEME: &str = "Use wss://, or ws:// for an .i2p or .onion address.";
202
203pub fn nip11_url(relay_url: &str) -> Result<String, String> {
206 let bad = || "That isn't a valid server address.".to_string();
207 let mut u = url::Url::parse(relay_url.trim()).map_err(|_| bad())?;
208 let scheme = match u.scheme() {
209 "wss" | "https" => "https",
210 "ws" | "http" => "http",
211 _ => return Err(bad()),
212 };
213 u.set_scheme(scheme).map_err(|_| bad())?;
214 u.set_fragment(None);
215 Ok(u.to_string())
216}
217
218pub fn validate_relay_url(url: &str) -> Result<String, String> {
222 let trimmed = url.trim();
223 let (rest, plain) = match (trimmed.strip_prefix("wss://"), trimmed.strip_prefix("ws://")) {
224 (Some(r), _) => (r, false),
225 (None, Some(r)) => (r, true),
226 _ => return Err(RELAY_SCHEME.into()),
227 };
228 if rest.is_empty() || rest.starts_with('/') {
229 return Err("Relay URL must include a host".into());
230 }
231 if plain {
232 let host = url::Url::parse(trimmed).ok().and_then(|u| u.host_str().map(str::to_ascii_lowercase));
233 if !host.is_some_and(|h| (h.ends_with(".i2p") && h.len() > 4) || is_onion(&h)) {
234 return Err(RELAY_SCHEME.into());
235 }
236 }
237 Ok(trimmed.trim_end_matches('/').to_string())
238}