diff --git a/src/remote.rs b/src/remote.rs index b330611..4546e93 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1971,10 +1971,11 @@ pub fn why_refused(st: u16, v: &Value, whom: &str) -> String { /// Every request that carries the account password (sign in, sign up, 兩步驗證, 配對) or this /// computer's key goes to the account server through here or through `relay_agent`. pub fn relay_post(url: &str, bearer: &str, body: &Value) -> Result { - if let Some(why) = relay_plain_problem(url) { + let url = self_hop(url); + if let Some(why) = relay_plain_problem(&url) { return Err(why); } - let mut r = relay_agent(30, url).post(url).header("Content-Type", "application/json"); + let mut r = relay_agent(30, &url).post(&url).header("Content-Type", "application/json"); if !bearer.is_empty() { r = r.header("Authorization", &format!("Bearer {bearer}")); } @@ -2060,6 +2061,44 @@ pub(crate) fn relay_plain_problem(url: &str) -> Option { /// password on in the clear wherever it routes — and keeps no connection for the next request: /// each request opens its own, so each one is checked (a kept one would have been checked once, /// on a network that may since have changed). +/// 自己连自己的帳號伺服器走 Tailscale:hairpin 绕远方中继,每个请求实测 7–14 秒 +/// (Mac mini,App 重开後「连线慢」的主因:所有同步、状态、长轮询都走这条路)。 +/// 帐号伺服器的 ts.net 名字解析到本机自己的 Tailscale 地址时,改走循环地址。 +/// TLS 用 URL 里的名字(ts.net 证书照验、路由语义不变),只给「自己连自己」抄近道; +/// 别的机器连同一位址照走 tailnet。结果缓存 60 秒(MagicDNS 解析一次 250ms)。 +pub(crate) fn self_hop(url: &str) -> String { + static CACHE: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let cache = CACHE.get_or_init(Default::default); + if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(url).filter(|(_, t)| t.elapsed().as_secs() < 60).map(|(v, _)| v.clone()) { + return hit; + } + let out = rewrite_self(url, &crate::lantls::tunnel_addrs(), |h, p| { use std::net::ToSocketAddrs; (h, p).to_socket_addrs().map(|a| a.map(|s| s.ip()).collect()).unwrap_or_default() }); + cache.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_string(), (out.clone(), std::time::Instant::now())); + out +} + +/// `self_hop` 的纯函数部分(可测):https 的 *.ts.net 主机解析到 tunnel 里的地址 → 127.0.0.1。 +fn rewrite_self(url: &str, tunnel: &[std::net::IpAddr], resolve: impl Fn(&str, u16) -> Vec) -> String { + let (scheme, rest) = match url.get(..8) { + Some(p) if p.eq_ignore_ascii_case("https://") => ("https://", &url[8..]), + _ => return url.to_string(), + }; + let (hostport, path) = match rest.find('/') { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, ""), + }; + let host = hostport.rsplit('@').next().unwrap_or(hostport); + let host = host.split(':').next().unwrap_or(host); + if !host.to_ascii_lowercase().ends_with(".ts.net") || host.matches('.').count() < 3 { + return url.to_string(); + } + let port: u16 = hostport.rsplit(':').next().filter(|p| !p.is_empty() && *p != host && p.chars().all(|c| c.is_ascii_digit())).and_then(|p| p.parse().ok()).unwrap_or(443); + if resolve(host, port).into_iter().any(|a| tunnel.contains(&a)) { + return format!("{scheme}127.0.0.1:{port}{path}"); + } + url.to_string() +} + pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent { if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) { return agent(secs); @@ -2194,7 +2233,7 @@ fn alive(gen: u64) -> bool { fn relay_worker(url: &str, token: &str, gen: u64) { let mut backoff = 1u64; while alive(gen) { - let next = format!("{url}/relay/host/next"); + let next = self_hop(&format!("{url}/relay/host/next")); let r = relay_agent(40, &next).get(&next).header("Authorization", &format!("Bearer {token}")).call(); let mut resp = match r { Ok(r) => r, @@ -2292,7 +2331,7 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result = query.iter().map(|(k, v)| format!("{k}={}", httpd::url_encode(v))).collect(); - let url = brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?; + let url = self_hop(&brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?); let auth = format!("Bearer {}", s.host_token); let r = if method == "GET" { relay_agent(secs, &url).get(&url).header("Authorization", &auth).call() } else { relay_agent(secs, &url).post(&url).header("Authorization", &auth).header("Content-Type", "application/octet-stream").send(body) }; let mut resp = r.map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; @@ -2638,7 +2677,7 @@ pub fn publish_site(name: &str, local: &std::path::Path) -> Result Result, String> { - let mut r = relay_agent(10, &s.relay_url).get(&format!("{}/relay/host/members", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| e.to_string())?; + let mut r = relay_agent(10, &s.relay_url).get(&self_hop(&format!("{}/relay/host/members", s.relay_url))).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| e.to_string())?; let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); Ok(v["members"].as_array().map(|a| a.iter().map(|m| (m["user"].as_str().unwrap_or("").to_string(), format!("{}{}", m["role"].as_str().unwrap_or(""), if m["pending"] == true { "?" } else { "" }))).collect()).unwrap_or_default()) } @@ -2846,6 +2885,31 @@ pub fn page() -> Resp { mod tests { use super::*; + #[test] + fn self_hop_shortcuts_only_your_own_tunnel_address() { + use std::net::IpAddr; + let mine: IpAddr = "100.101.2.3".parse().unwrap(); + let other: IpAddr = "100.101.9.9".parse().unwrap(); + let ip = |s: &str| s.parse::().unwrap(); + // 自己的 ts.net 位址(解析到自己的 tailnet IP):改走循環,保留埠與路徑。 + assert_eq!( + rewrite_self("https://nobledesktop.tail1234.ts.net:8443/relay/host/next", &[mine], |_, _| vec![mine]), + "https://127.0.0.1:8443/relay/host/next" + ); + // 別人的帳號伺服器:照走 tailnet(不重寫)。 + assert_eq!(rewrite_self("https://host.tail1234.ts.net:8443/x", &[mine], |_, _| vec![other]), "https://host.tail1234.ts.net:8443/x"); + // 非 ts.net、非 https:不碰。 + assert_eq!(rewrite_self("https://api.example.com/v1", &[mine], |_, _| vec![mine]), "https://api.example.com/v1"); + assert_eq!(rewrite_self("http://host.tail1234.ts.net:8080/x", &[mine], |_, _| vec![mine]), "http://host.tail1234.ts.net:8080/x"); + // 沒寫埠 → 443;解析不到 → 不重寫;TS.NET 大寫也认。 + assert_eq!(rewrite_self("https://me.tail1234.ts.net/a", &[mine], |_, _| vec![mine]), "https://127.0.0.1:443/a"); + assert_eq!(rewrite_self("https://me.tail1234.ts.net:8443/a", &[mine], |_, _| vec![]), "https://me.tail1234.ts.net:8443/a"); + assert_eq!(rewrite_self("https://ME.TAIL1234.TS.NET:8443", &[mine], |_, _| vec![mine]), "https://127.0.0.1:8443"); + // 只有 ts.net 頂域名字式(x.ts.net)不是 MagicDNS 機器名:不重寫。 + assert_eq!(rewrite_self("https://x.ts.net:8443/a", &[mine], |_, _| vec![mine]), "https://x.ts.net:8443/a"); + assert!(!ip("100.101.2.3").to_string().is_empty()); + } + fn voice_req(path: &str, role: &str, body: &[u8]) -> Req { let (path, q) = path.split_once('?').unwrap_or((path, "")); let query = q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect();