diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index ea475423..054969d4 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -719,10 +719,11 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; - let socket = dir.join("twcore.sock"); + // 控制面听在哪由平台决定,见 `tw_api::control::Endpoint`。 + let endpoint = tw_api::control::Endpoint::in_dir(&dir); // **在起任何东西之前问**。等到 bind 失败时,网关已经在监听、客户端 // 可能已经连上来了,而这条错误当时只会进日志。 - tw_control::socket_path_fits(&socket)?; + tw_control::endpoint_usable(&endpoint)?; // 控制面的凭据,同样在起任何东西之前拿到:桌面端从环境变量交过来, // 手工启动时生成一个写进配置目录。取不到就停在这儿 —— 一个装不上门的 // 控制面不该先起来再说。 @@ -832,7 +833,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> } }; - let sock = socket.clone(); + let at = endpoint.clone(); // **控制面没了就得退,不能只记一行日志。** // // 一个没有控制面的 core 是 UI 完全够不着的:连不上、改不了配置、 @@ -841,10 +842,10 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 太长)只在日志里躺着。退出让那句话有机会走到人眼前。 let (control_died, control_dead) = tokio::sync::oneshot::channel(); tokio::spawn(async move { - let r = tw_control::serve_unix(control, &sock, control_token).await; + let r = tw_control::serve(control, &at, control_token).await; let msg = match r { Err(e) => format!("{e}"), - // serve_unix 正常返回意味着 accept 循环结束了,同样是没了 + // serve 正常返回意味着 accept 循环结束了,同样是没了 Ok(()) => "the control plane ended unexpectedly".to_string(), }; let _ = control_died.send(msg); diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 92b841bd..0c87db18 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -3216,3 +3216,90 @@ mod tests { assert!(s.gateway_addr.is_none()); } } + +/// 控制面在哪儿、拿什么进门。 +/// +/// **这是契约的一部分,不是两边各自的约定。**core 在这儿听,桌面端到这儿连 +/// —— 以前两边各拼一次 `<数据目录>/twcore.sock`,能对上只是因为那一行足够 +/// 短。Windows 上这个答案要分岔(那里没有 unix socket),两份各写一次就是 +/// 两份会漂,而漂掉的表现是「界面连不上一个正在跑的网关」。 +/// +/// **仍然没有 IO**,遵守这个 crate 的规矩(见模块头):这里只有名字和形状, +/// 真正去绑、去读的是各自那一侧。 +pub mod control { + use std::path::{Path, PathBuf}; + + /// unix socket 文件,在数据目录下。 + pub const SOCKET_FILE: &str = "twcore.sock"; + /// Windows 上控制面绑到哪个端口,由 core 写、由客户端读。 + pub const PORT_FILE: &str = "control.port"; + /// 手工启动 core 时凭据落在哪。 + pub const TOKEN_FILE: &str = "control.token"; + /// 父进程把凭据交过来的环境变量。**走环境不走 argv** —— Windows 上任意 + /// 同用户进程都看得见别人的命令行。 + pub const TOKEN_ENV: &str = "TW_CONTROL_TOKEN"; + + /// 控制面听在哪。 + #[derive(Debug, Clone, PartialEq, Eq)] + pub enum Endpoint { + /// 一个 `0700` 的 unix socket 文件。**权限是文件系统给的**,所以这 + /// 一档天然只有当前用户连得上。 + Socket(PathBuf), + /// 回环上的一个端口。Windows 只有这一档。 + /// + /// **端口不固定**:固定端口会和别的软件撞,也省了想连进来的人一步。 + /// core 绑到一个系统给的空闲端口,再把号码写进这个文件。 + /// + /// 回环端口挡不住同机的任何进程,也问不出对端是谁(unix socket 问 + /// 得出,`SO_PEERCRED`)—— 那一档的门**全靠凭据**。 + Loopback { port_file: PathBuf }, + } + + impl Endpoint { + /// 这个平台默认听在数据目录的什么位置。 + pub fn in_dir(dir: &Path) -> Self { + #[cfg(unix)] + { + Endpoint::Socket(dir.join(SOCKET_FILE)) + } + #[cfg(not(unix))] + { + Endpoint::Loopback { + port_file: dir.join(PORT_FILE), + } + } + } + } + + /// 凭据文件在哪。 + pub fn token_file(dir: &Path) -> PathBuf { + dir.join(TOKEN_FILE) + } + + #[cfg(test)] + mod tests { + use super::*; + + /// 两个仓库拼出来的必须是同一个位置 —— 这个函数存在的全部理由。 + #[test] + fn the_endpoint_lands_in_the_data_directory() { + let d = Path::new("/data"); + match Endpoint::in_dir(d) { + Endpoint::Socket(p) => assert_eq!(p, d.join(SOCKET_FILE)), + Endpoint::Loopback { port_file } => assert_eq!(port_file, d.join(PORT_FILE)), + } + assert_eq!(token_file(d), d.join(TOKEN_FILE)); + } + + /// 平台决定用哪一档,不是调用方挑。 + #[test] + fn each_platform_gets_the_only_transport_it_has() { + let got = Endpoint::in_dir(Path::new("/data")); + if cfg!(unix) { + assert!(matches!(got, Endpoint::Socket(_))); + } else { + assert!(matches!(got, Endpoint::Loopback { .. })); + } + } + } +} diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 55cb55ff..c3e39ebc 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1448,6 +1448,20 @@ pub enum ControlError { len: usize, max: usize, }, + /// 端口号写不进去。**这不是小事**:写不进去,客户端就找不到控制面, + /// 而网关本身照常在转发 —— 一个「跑着但够不着」的 core。 + #[error("the control-plane port could not be written to {path}: {source}")] + PortFile { + path: PathBuf, + source: std::io::Error, + }, + /// 这个平台上没有 unix socket。 + /// + /// `Endpoint::in_dir` 不会给出这一档,所以走到这里说明有人显式指定了它 + /// —— 与其静默换一种传输,不如说清楚。 + #[cfg(not(unix))] + #[error("this platform has no unix sockets, so the control plane cannot listen on {path}")] + NoUnixSockets { path: PathBuf }, } /// `sockaddr_un.sun_path` 的容量。macOS 104、Linux 108,取小的那个 —— @@ -1468,15 +1482,34 @@ pub fn socket_path_fits(path: &Path) -> Result<(), ControlError> { Ok(()) } -/// 在 unix socket 上起控制面。 +/// 起控制面。 /// -/// 陈旧的 socket 文件直接删掉重建 —— 它和 lock 文件不一样,没有「另一个 -/// 实例可能还在用」的歧义:单实例锁已经在上一步挡住了。 -pub async fn serve_unix( +/// 两种传输,**挑哪一种不是调用方的事**:`Endpoint::in_dir` 按平台给出这台 +/// 机器上唯一可用的那一种(见 [`tw_api::control::Endpoint`])。这里只负责把 +/// 它听起来。 +pub async fn serve( state: ControlState, - path: &Path, + at: &tw_api::control::Endpoint, token: token::Token, ) -> Result<(), ControlError> { + use tw_api::control::Endpoint; + // 门装在这儿,不装进 `router()` —— 理由见 `token::guard` + let app = token::guard(router(state), token); + match at { + #[cfg(unix)] + Endpoint::Socket(path) => serve_socket(app, path).await, + #[cfg(not(unix))] + Endpoint::Socket(path) => Err(ControlError::NoUnixSockets { path: path.clone() }), + Endpoint::Loopback { port_file } => serve_loopback(app, port_file).await, + } +} + +/// unix socket 上的控制面。 +/// +/// 陈旧的 socket 文件直接删掉重建 —— 它和 lock 文件不一样,没有「另一个 +/// 实例可能还在用」的歧义:单实例锁已经在上一步挡住了。 +#[cfg(unix)] +async fn serve_socket(app: Router, path: &Path) -> Result<(), ControlError> { socket_path_fits(path)?; if path.exists() { let _ = std::fs::remove_file(path); @@ -1488,7 +1521,6 @@ pub async fn serve_unix( path: path.to_path_buf(), source, })?; - #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; // 0700:只有当前用户能连。凭据那道门在它之外,不是替代它 —— @@ -1496,37 +1528,91 @@ pub async fn serve_unix( let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); } tracing::info!(path = %path.display(), "the control plane is listening"); + loop { + match listener.accept().await { + Ok((stream, _)) => hand_off(stream, app.clone()), + Err(e) => tracing::warn!("the control plane could not accept a connection: {e}"), + } + } +} - let app = token::guard(router(state), token); +/// 回环 TCP 上的控制面。Windows 只有这一档。 +/// +/// **绑 0 号端口**,让系统挑一个空闲的,再把号码写进那个文件。固定端口会和 +/// 别的软件撞,而撞上的表现是 core 起不来;它也省了想连进来的人一步。 +/// +/// 端口文件**先绑后写**:写完才说得出真实的号码,而反过来(先写一个想要的 +/// 号再去绑)会在绑失败时留下一个指向别人的文件。 +/// +/// 这一档**挡不住同机的任何进程**,也问不出对端是谁 —— 门全在凭据上, +/// 见 [`token`]。 +async fn serve_loopback(app: Router, port_file: &Path) -> Result<(), ControlError> { + use std::net::Ipv4Addr; + if let Some(dir) = port_file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .await + .map_err(|source| ControlError::Bind { + path: port_file.to_path_buf(), + source, + })?; + let port = listener + .local_addr() + .map_err(|source| ControlError::Bind { + path: port_file.to_path_buf(), + source, + })? + .port(); + std::fs::write(port_file, port.to_string()).map_err(|source| ControlError::PortFile { + path: port_file.to_path_buf(), + source, + })?; + tracing::info!(port, "the control plane is listening on loopback"); loop { - let (stream, _) = match listener.accept().await { - Ok(x) => x, - Err(e) => { - tracing::warn!("the control plane could not accept a connection: {e}"); - continue; - } - }; - let svc = app.clone(); - tokio::spawn(async move { - let io = hyper_util::rt::TokioIo::new(stream); - let svc = hyper::service::service_fn(move |req| { - use tower::ServiceExt; - svc.clone().oneshot(req) - }); - if let Err(e) = - hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) - .serve_connection(io, svc) - .await - { - tracing::debug!("a control-plane connection ended: {e}"); - } - }); + match listener.accept().await { + Ok((stream, _)) => hand_off(stream, app.clone()), + Err(e) => tracing::warn!("the control plane could not accept a connection: {e}"), + } } } -/// 默认 socket 路径。和配置放一起,这样「一个目录装下全部状态」这条成立。 -pub fn default_socket_path() -> PathBuf { - tw_config::default_dir().join("twcore.sock") +/// 一条连接交给 hyper。 +/// +/// **两种传输共用**:它们的差别只在怎么拿到这个流,拿到之后的每一件事 +/// (协议协商、错误怎么记)都该一模一样 —— 写两遍就是两遍会漂。 +fn hand_off(stream: S, app: Router) +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin + 'static, +{ + tokio::spawn(async move { + let io = hyper_util::rt::TokioIo::new(stream); + let svc = hyper::service::service_fn(move |req| { + use tower::ServiceExt; + app.clone().oneshot(req) + }); + if let Err(e) = + hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()) + .serve_connection(io, svc) + .await + { + tracing::debug!("a control-plane connection ended: {e}"); + } + }); +} + +/// 在起任何东西之前问一句:这个地址听得起来吗。 +/// +/// **不是等到 bind 的那一刻才发现。**那时网关已经在监听、客户端可能已经 +/// 连上来了,而这条错误当时只会进日志。 +pub fn endpoint_usable(at: &tw_api::control::Endpoint) -> Result<(), ControlError> { + use tw_api::control::Endpoint; + match at { + Endpoint::Socket(p) => socket_path_fits(p), + // 回环那一档没有等价的前置条件:端口由系统挑,挑不出来时 bind 自己 + // 会说,而那句话已经够清楚了。 + Endpoint::Loopback { .. } => Ok(()), + } } #[cfg(test)] diff --git a/crates/tw-control/src/token.rs b/crates/tw-control/src/token.rs index 545c285b..a060d08d 100644 --- a/crates/tw-control/src/token.rs +++ b/crates/tw-control/src/token.rs @@ -31,11 +31,9 @@ use axum::response::{IntoResponse, Response}; use std::sync::Arc; use tw_types::msg; -/// 桌面端把 token 交过来的那个环境变量。 -pub const ENV: &str = "TW_CONTROL_TOKEN"; - -/// 手工启动时 token 落在哪(相对配置目录)。 -pub const FILE: &str = "control.token"; +// 名字住在契约层:桌面端要知道环境变量叫什么才能把 token 交过来,而它 +// 依赖的是 tw-api,够不着这个 crate。两边各写一遍字符串就是两边会漂。 +use tw_api::control::{TOKEN_ENV as ENV, token_file}; #[derive(Debug, thiserror::Error)] pub enum TokenError { @@ -84,7 +82,7 @@ impl Token { } fn load_or_create(dir: &Path) -> Result { - let path = dir.join(FILE); + let path = token_file(dir); match std::fs::read_to_string(&path) { Ok(s) if !s.trim().is_empty() => return Ok(Self(s.trim().to_string())), // 空文件:当没有过,重新生成盖掉。理由同 `from_env` 里那条。 @@ -284,7 +282,7 @@ mod tests { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(d.path().join(FILE)) + let mode = std::fs::metadata(token_file(d.path())) .unwrap() .permissions() .mode(); @@ -296,7 +294,7 @@ mod tests { #[test] fn an_empty_file_is_replaced_rather_than_trusted() { let d = tempfile::tempdir().unwrap(); - std::fs::write(d.path().join(FILE), " \n").unwrap(); + std::fs::write(token_file(d.path()), " \n").unwrap(); let t = Token::load_or_create(d.path()).unwrap(); assert_eq!(t.as_str().len(), 64); } @@ -305,7 +303,7 @@ mod tests { #[test] fn surrounding_whitespace_in_the_file_is_not_part_of_the_token() { let d = tempfile::tempdir().unwrap(); - std::fs::write(d.path().join(FILE), " abc123\n").unwrap(); + std::fs::write(token_file(d.path()), " abc123\n").unwrap(); assert!(Token::load_or_create(d.path()).unwrap().matches("abc123")); }