From dd4474418cd6ada53d99448f8459d5cf9ed1bf54 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:04:26 +0800 Subject: [PATCH] feat(config): bind to a named interface, and drop the `lan` that never did MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Bind` had three values — `loopback`, `lan`, `all` — and **two of them were the same thing**. `lan` and `all` both resolved to `0.0.0.0`; the only difference between them was the default contents of `allow_from`. That made `lan` a whitelist concept wearing a network-interface costume. Someone picking "LAN" reasonably believes the gateway is listening on their local network interface. It is listening on **every** interface, including whichever one faces the internet, and the only thing standing between the two is a CIDR list they never saw. The field's own doc comment has always read `loopback | lan | all | 具体 IP`, so a concrete address was the intent; the enum just never grew one. So: `Loopback | All | Addr(IpAddr)`, with the serde impl written by hand because all three are plain strings in YAML. bind: loopback # 127.0.0.1 bind: 192.168.1.5 # one interface bind: all # 0.0.0.0 `lan` is gone rather than aliased. It is one of two names for the same address, and keeping it would preserve the confusion this commit exists to remove. Any config still carrying it now fails to load with an error that names the three valid forms — a bad `bind` takes the whole config down, so that message has to arrive with the answer in it. **`is_exposed` now asks the address, not the variant.** `bind: 127.0.0.1` written out longhand is loopback, and should not force key checking or auto-fill the private-range whitelist just because it took a different spelling to get there. ## `GET /interfaces` New, and the reason the above is usable: it lists this machine's interfaces so a picker can offer them. Without it, choosing an interface means reading `ifconfig` and copying an address into a YAML file by hand, where a typo surfaces as "Can't assign requested address" at startup. `getifaddrs` through `libc`, which is already a workspace dependency — the whole thing is under fifty lines, well below the cost of a crate. Interfaces that are down or have no address are skipped, because they cannot be bound and listing them only produces a choice that fails. IPv6 link-local is skipped too: it needs a scope id (`fe80::1%en0`) to be usable at all, and that spelling in a config file is a trap. Nothing is cached. Interfaces change when a cable moves, a different Wi-Fi connects, or a VPN comes up, and a cached list means offering an address that no longer exists. The tests assert only what holds on any machine — that a loopback entry exists, that no entry is malformed, that loopback sorts last so it never heads a picker whose other option already means "this machine only". Co-Authored-By: Claude Opus 5 --- Cargo.lock | 1 + crates/tw-api/src/lib.rs | 13 +++ crates/tw-config/src/lib.rs | 137 +++++++++++++++++++++++---- crates/tw-config/src/validate.rs | 2 +- crates/tw-control/Cargo.toml | 2 + crates/tw-control/src/lib.rs | 20 ++++ crates/tw-control/src/nics.rs | 111 ++++++++++++++++++++++ crates/tw-gateway/tests/hotreload.rs | 4 +- 8 files changed, 268 insertions(+), 22 deletions(-) create mode 100644 crates/tw-control/src/nics.rs diff --git a/Cargo.lock b/Cargo.lock index 606a1172..8fa7c42b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2825,6 +2825,7 @@ dependencies = [ "futures", "hyper", "hyper-util", + "libc", "reqwest", "serde", "serde_json", diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index e5340ca8..c3135d8c 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -546,6 +546,19 @@ pub struct ConfigText { pub version: String, } +/// 这台机器上的一张网卡(`GET /interfaces`)。 +/// +/// **界面上「绑在哪张网卡」那个选单要的就是它。**没有它,用户只能自己 +/// 去 `ifconfig` 抄一个地址填进配置文件,而填错的后果是网关起不来。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NicView { + /// `en0`、`lo0`、`utun3` + pub name: String, + pub addr: String, + /// 回环地址。界面上这一档叫「仅本机」,不该混在「选一张网卡」里 + pub loopback: bool, +} + /// 改配置。 /// /// **不是「把整份新配置发过来」**,是「基于哪一版、改哪几个字段」。 diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index bed05644..01bb7409 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -151,13 +151,13 @@ pub struct Listen { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GatewayListen { - /// loopback | lan | all | 具体 IP。默认 loopback —— 学 Surge, + /// `loopback` | `all` | 一张网卡的 IP。默认 loopback —— 学 Surge, /// 但默认值要保守。 #[serde(default)] pub bind: Bind, #[serde(default = "default_port")] pub port: u16, - /// 仅 lan / all 时生效的来源白名单(CIDR)。 + /// 只在绑到本机之外时生效的来源白名单(CIDR)。 #[serde(default)] pub allow_from: Vec, } @@ -173,11 +173,7 @@ impl GatewayListen { /// 迟早有一处忘了跟着改 —— 而它的表现是「监听在了一个谁也没想到的 /// 地址上」。 pub fn socket_addr(&self) -> std::net::SocketAddr { - format!("{}:{}", self.bind.addr(), self.port) - .parse() - // bind.addr() 只会返回两个字面量,port 是 u16 —— 拼不出 - // 非法地址。真拼出来了那是 bug,不是用户输入。 - .expect("bind + port 拼不出合法地址") + std::net::SocketAddr::new(self.bind.addr(), self.port) } } @@ -191,31 +187,93 @@ impl Default for GatewayListen { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "lowercase")] +/// 绑在哪张网卡上。 +/// +/// 三种写法,对应三个真实的选择: +/// +/// ```yaml +/// bind: loopback # 127.0.0.1,只有本机 +/// bind: 192.168.1.5 # 某一张具体的网卡 +/// bind: all # 0.0.0.0,所有网卡 +/// ``` +/// +/// **以前这里有个 `lan`,它是假的。**`lan` 和 `all` 绑的是同一个地址 +/// `0.0.0.0`,区别只在 `allow_from` 的默认值 —— 也就是说它是个白名单 +/// 概念,伪装成了网卡选择。用户在界面上选「局域网」,以为网关只在局域 +/// 网那张网卡上监听,实际上它在**所有**网卡上监听,包括公网那张。 +/// 现在要真的只在局域网网卡上听,就写那张网卡的地址。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Bind { #[default] Loopback, - Lan, All, + /// 一张具体的网卡。**地址会变** —— DHCP 续租、换网络都可能让它失效, + /// 那时网关起不来。这是选它要接受的代价,界面上必须说。 + Addr(std::net::IpAddr), } impl Bind { - pub fn addr(&self) -> &'static str { + pub fn addr(&self) -> std::net::IpAddr { match self { - Bind::Loopback => "127.0.0.1", - // lan 和 all 在监听层是同一件事;区别在 allow_from 的默认 - // 值和 UI 上的措辞。 - Bind::Lan | Bind::All => "0.0.0.0", + Bind::Loopback => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + Bind::All => std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), + Bind::Addr(a) => *a, } } - /// 非 loopback 吗。 + /// 本机之外连得上吗。 /// /// **这个判断决定了两件强制行为**:密钥校验不可关闭, /// 以及 `allow_from` 为空时自动填私网段。 + /// + /// 判的是地址本身而不是枚举变体 —— `bind: 127.0.0.1` 写成具体地址 + /// 的时候,它和 `loopback` 是同一件事,不该因为换了个写法就被当成 + /// 暴露在外。 pub fn is_exposed(&self) -> bool { - !matches!(self, Bind::Loopback) + !self.addr().is_loopback() + } +} + +impl Bind { + /// 给界面显示的地址字符串。`loopback`/`all` 展开成真实地址, + /// 具体网卡就是它自己。 + pub fn socket_string(&self) -> String { + self.addr().to_string() + } +} + +impl std::fmt::Display for Bind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Bind::Loopback => f.write_str("loopback"), + Bind::All => f.write_str("all"), + Bind::Addr(a) => write!(f, "{a}"), + } + } +} + +impl Serialize for Bind { + fn serialize(&self, s: S) -> Result { + s.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Bind { + fn deserialize>(d: D) -> Result { + let raw = String::deserialize(d)?; + match raw.as_str() { + "loopback" => Ok(Bind::Loopback), + "all" => Ok(Bind::All), + other => other.parse().map(Bind::Addr).map_err(|_| { + // **说清楚三种合法写法。**「invalid value」对着一个 + // 手写配置文件的人什么都没说,而这个字段写错的后果是 + // 整份配置加载失败、网关起不来。 + serde::de::Error::custom(format!( + "`bind` 只能是 `loopback`、`all`,或者一张网卡的 IP(比如 192.168.1.5)。\ + 收到的是 `{other}`" + )) + }), + } } } @@ -894,8 +952,49 @@ providers: #[test] fn bind_defaults_to_loopback_not_all_interfaces() { // 默认监听 0.0.0.0 会把网关暴露给整个局域网,而用户不会知道。 - assert_eq!(Bind::default().addr(), "127.0.0.1"); - assert_eq!(Bind::All.addr(), "0.0.0.0"); + assert_eq!(Bind::default().addr().to_string(), "127.0.0.1"); + assert_eq!(Bind::All.addr().to_string(), "0.0.0.0"); + assert!(!Bind::default().is_exposed()); + assert!(Bind::All.is_exposed()); + } + + #[test] + fn bind_accepts_a_concrete_interface_address() { + // 这是 `lan` 被换掉的理由:想「只在局域网那张网卡上听」, + // 以前只能写 `lan`,而它绑的是 0.0.0.0 —— 所有网卡,包括公网那张。 + let b: Bind = serde_yaml_ng::from_str("192.168.1.5").unwrap(); + assert_eq!(b, Bind::Addr("192.168.1.5".parse().unwrap())); + assert_eq!(b.socket_string(), "192.168.1.5"); + assert!(b.is_exposed()); + } + + #[test] + fn writing_the_loopback_address_out_longhand_is_not_exposure() { + // `is_exposed` 判的是地址,不是枚举变体 —— 换个写法不该让 + // 密钥校验被强制、白名单被自动填上。 + let b: Bind = serde_yaml_ng::from_str("127.0.0.1").unwrap(); + assert!(!b.is_exposed()); + } + + #[test] + fn every_bind_form_round_trips_through_yaml() { + for raw in ["loopback", "all", "192.168.1.5", "::1"] { + let b: Bind = serde_yaml_ng::from_str(raw).unwrap(); + let back = serde_yaml_ng::to_string(&b).unwrap(); + assert_eq!(back.trim(), raw, "{raw} 写回来变了样"); + } + } + + #[test] + fn a_bind_typo_says_what_the_three_forms_are() { + // 这个字段写错的后果是整份配置加载失败、网关起不来 —— + // 那条错误必须自带答案。 + let e = serde_yaml_ng::from_str::("lan") + .unwrap_err() + .to_string(); + assert!(e.contains("loopback"), "{e}"); + assert!(e.contains("all"), "{e}"); + assert!(e.contains("192.168.1.5"), "{e}"); } #[test] diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 25175006..358202df 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -305,7 +305,7 @@ mod tests { k.listen.gateway.effective_allow_from().is_empty(), "loopback 下不填" ); - k.listen.gateway.bind = crate::Bind::Lan; + k.listen.gateway.bind = crate::Bind::All; let eff = k.listen.gateway.effective_allow_from(); assert!(eff.iter().any(|s| s == "192.168.0.0/16"), "{eff:?}"); // 用户写了就用他的,不要偷偷加 diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 0982b15b..efcda5c9 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -9,6 +9,8 @@ description = "Control-plane API server over a unix socket" [dependencies] tw-api = { workspace = true } +# 列网卡用 getifaddrs —— 比引一个 crate 便宜 +libc = { workspace = true } tw-config = { workspace = true } tw-adopt = { workspace = true } # 更新那份价目表时给下载内容按指纹 —— 用户看的 diff 和落盘的必须是同一份 diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index cefaab75..cd7c3231 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -19,6 +19,7 @@ pub mod clients; pub mod config; pub mod diagnostics; pub mod dryrun; +pub mod nics; pub mod replay; pub mod rotation; pub mod scan; @@ -79,6 +80,7 @@ impl ControlState { pub fn router(state: ControlState) -> Router { Router::new() .route("/status", get(status)) + .route("/interfaces", get(interfaces)) .route("/events", get(events)) .route("/overview", get(overview)) .route("/probe", post(probe)) @@ -138,6 +140,24 @@ pub fn router(state: ControlState) -> Router { .with_state(state) } +/// 这台机器上有哪些网卡。 +/// +/// 不带任何状态 —— 每次现问系统。**网卡是会变的**:插拔网线、连上另一 +/// 个 Wi-Fi、起一条 VPN,清单就不一样了,缓存下来只会让选单里出现一个 +/// 已经不存在的地址。 +async fn interfaces() -> Json> { + Json( + crate::nics::list() + .into_iter() + .map(|n| tw_api::NicView { + name: n.name, + loopback: n.addr.is_loopback(), + addr: n.addr.to_string(), + }) + .collect(), + ) +} + async fn status(State(s): State) -> Json { let cfg = s.config(); Json(tw_api::Status { diff --git a/crates/tw-control/src/nics.rs b/crates/tw-control/src/nics.rs new file mode 100644 index 00000000..f3dd1201 --- /dev/null +++ b/crates/tw-control/src/nics.rs @@ -0,0 +1,111 @@ +//! 这台机器上有哪些网卡。 +//! +//! **界面上「绑在哪张网卡」那个选择要的就是这份清单。**没有它,用户只 +//! 能自己去 `ifconfig` 抄一个地址填进配置文件 —— 而填错的后果是网关起 +//! 不来,错误信息只会说 "Can't assign requested address"。 +//! +//! 用 `getifaddrs` 直接问系统,不引第三方 crate:`libc` 本来就在工作区 +//! 依赖里(tw-store 在用),而这件事一共不到五十行。 + +use std::ffi::CStr; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +/// 一张网卡上的一个地址。 +/// +/// 同一张网卡可以有多个地址(IPv4 一个、IPv6 若干),所以这里一行是 +/// 「网卡 + 地址」而不是「网卡」。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Nic { + /// `en0`、`lo0`、`utun3` + pub name: String, + pub addr: IpAddr, +} + +/// 列出所有已配好地址、并且已经 up 的网卡。 +/// +/// **跳过没有地址的和没 up 的** —— 一张插着网线但没拿到 IP 的网卡绑不 +/// 上去,列在选单里只会让人选了之后发现起不来。 +/// +/// 也跳过 IPv6 的链路本地地址(`fe80::/10`):它们要带 scope id 才能用 +/// (`fe80::1%en0`),而那个写法放进配置文件里几乎必然是个坑。 +pub fn list() -> Vec { + let mut out = Vec::new(); + // SAFETY: getifaddrs 成功时给出一条以空指针结尾的链表,freeifaddrs + // 负责释放。中间只读不写,且在 free 之前把需要的字段都拷出来。 + unsafe { + let mut head: *mut libc::ifaddrs = std::ptr::null_mut(); + if libc::getifaddrs(&mut head) != 0 { + return out; + } + let mut cur = head; + while !cur.is_null() { + let e = &*cur; + cur = e.ifa_next; + if e.ifa_addr.is_null() || e.ifa_flags & libc::IFF_UP as u32 == 0 { + continue; + } + let name = match CStr::from_ptr(e.ifa_name).to_str() { + Ok(n) => n.to_string(), + Err(_) => continue, + }; + let addr = match (*e.ifa_addr).sa_family as i32 { + libc::AF_INET => { + let s = &*(e.ifa_addr as *const libc::sockaddr_in); + IpAddr::V4(Ipv4Addr::from(u32::from_be(s.sin_addr.s_addr))) + } + libc::AF_INET6 => { + let s = &*(e.ifa_addr as *const libc::sockaddr_in6); + let a = Ipv6Addr::from(s.sin6_addr.s6_addr); + if a.segments()[0] & 0xffc0 == 0xfe80 { + continue; + } + IpAddr::V6(a) + } + _ => continue, + }; + out.push(Nic { name, addr }); + } + libc::freeifaddrs(head); + } + // 回环排最后:它在选单里对应的是「仅本机」那一档,不该混在 + // 「选一张网卡」的候选里排在前面。 + out.sort_by_key(|n| (n.addr.is_loopback(), n.name.clone(), n.addr.to_string())); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 这个测试不断言具体有哪些网卡 —— 那取决于跑它的机器。 + /// 它断言的是**任何一台机器都成立的事**。 + #[test] + fn every_machine_has_a_loopback_and_no_entry_is_malformed() { + let all = list(); + assert!( + all.iter().any(|n| n.addr.is_loopback()), + "一台机器不可能没有回环地址:{all:?}" + ); + for n in &all { + assert!(!n.name.is_empty(), "网卡名是空的:{n:?}"); + // 链路本地的 IPv6 要带 scope id 才能用,不该出现在这里 + if let IpAddr::V6(v6) = n.addr { + assert_ne!( + v6.segments()[0] & 0xffc0, + 0xfe80, + "漏掉了链路本地地址:{n:?}" + ); + } + } + } + + #[test] + fn loopback_sorts_last_so_it_does_not_head_the_picker() { + let all = list(); + let first_loopback = all.iter().position(|n| n.addr.is_loopback()); + let last_real = all.iter().rposition(|n| !n.addr.is_loopback()); + if let (Some(lb), Some(real)) = (first_loopback, last_real) { + assert!(lb > real, "回环排在真实网卡前面了:{all:?}"); + } + } +} diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index cbe294f8..aad678e9 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -144,7 +144,7 @@ async fn a_reload_that_cannot_build_leaves_the_old_config_serving() { let mut broken = cfg(vec![provider("a", a)], vec![]); // 白名单写错一个字。**校验层会先挡下来**,但这一层也必须挡 —— // 它是最后一道,而「校验过了但运行时对象建不起来」不是不可能。 - broken.listen.gateway.bind = tw_config::Bind::Lan; + broken.listen.gateway.bind = tw_config::Bind::All; broken.listen.gateway.allow_from = vec!["10.0.0.0/999".into()]; assert!(state.reload(broken).is_err(), "坏配置该被拒绝"); assert!(ask(gw).await.contains("\"a\""), "旧配置没能继续服务"); @@ -450,7 +450,7 @@ async fn the_allow_list_is_reloaded_too() { assert!(ask(gw).await.contains("\"a\"")); // 监听改成 lan 并且只放行一个不含 127.0.0.1 的段 - c.listen.gateway.bind = tw_config::Bind::Lan; + c.listen.gateway.bind = tw_config::Bind::All; c.listen.gateway.allow_from = vec!["10.0.0.0/8".into()]; state.reload(c).unwrap(); let after = ask(gw).await;