| 1 | //! # Endpoint resolution |
| 2 | //! |
| 3 | //! In precedence order (see [`resolve_socket_path`]): |
| 4 | //! |
| 5 | //! 1. an explicit path (`--socket-path`); |
| 6 | //! 2. `$CODEWHALE_HOME/run/daemon.sock` when `CODEWHALE_HOME` is set — an |
| 7 | //! explicit home is an isolation boundary, so its daemon must not collide |
| 8 | //! with the default one; |
| 9 | //! 3. `$XDG_RUNTIME_DIR/codewhale/daemon.sock`; |
| 10 | //! 4. macOS: `~/Library/Application Support/codewhale/daemon.sock`; |
| 11 | //! 5. `~/.codewhale/run/daemon.sock`. |
| 12 | //! |
| 13 | |
| 14 | #[cfg(unix)] |
| 15 | use std::path::Path; |
| 16 | use std::path::PathBuf; |
| 17 | |
| 18 | /// Basename of the daemon socket inside the Codewhale runtime directory. |
| 19 | pub const DAEMON_SOCKET_FILE_NAME: &str = "daemon.sock"; |
| 20 | |
| 21 | /// Historical reserved endpoint used in unsupported-platform diagnostics. |
| 22 | /// Actual Windows owner endpoints are scoped to the selected home/principal. |
| 23 | pub const WINDOWS_NAMED_PIPE: &str = r"\\.\pipe\codewhale-daemon"; |
| 24 | |
| 25 | /// Longest socket path the kernel accepts (`sun_path` minus the NUL). |
| 26 | pub const MAX_SOCKET_PATH_BYTES: usize = if cfg!(any(target_os = "macos", target_os = "ios")) { |
| 27 | 103 |
| 28 | } else { |
| 29 | 107 |
| 30 | }; |
| 31 | |
| 32 | /// Typed failures of the daemon socket transport. |
| 33 | #[derive(Debug, thiserror::Error)] |
| 34 | #[expect( |
| 35 | missing_docs, |
| 36 | reason = "Preserve the relocated public error variant fields" |
| 37 | )] |
| 38 | pub enum DaemonSocketError { |
| 39 | /// The platform has no daemon socket implementation. Never a silent |
| 40 | /// fallback: the caller must pick another transport explicitly. |
| 41 | #[error( |
| 42 | "the daemon socket transport is not supported on {platform}; the reserved endpoint \ |
| 43 | there is the named pipe {planned_endpoint}, which is not implemented yet" |
| 44 | )] |
| 45 | UnsupportedPlatform { |
| 46 | platform: &'static str, |
| 47 | planned_endpoint: &'static str, |
| 48 | }, |
| 49 | /// No home directory (or runtime directory) to derive a default path from. |
| 50 | #[error( |
| 51 | "cannot resolve the Codewhale runtime directory for the daemon socket: no home directory" |
| 52 | )] |
| 53 | RuntimeDirUnavailable, |
| 54 | /// `CODEWHALE_HOME` is set but not a usable absolute path. |
| 55 | #[error("invalid CODEWHALE_HOME override: {0}")] |
| 56 | InvalidHomeOverride(String), |
| 57 | #[error("cannot use {variable} for the runtime endpoint: {reason}")] |
| 58 | InvalidRuntimeRoot { |
| 59 | variable: &'static str, |
| 60 | reason: &'static str, |
| 61 | }, |
| 62 | /// Unix socket paths are limited to roughly one hundred bytes. |
| 63 | #[error("daemon socket path {} is {len} bytes; this platform allows at most {max}", path.display())] |
| 64 | PathTooLong { |
| 65 | path: PathBuf, |
| 66 | len: usize, |
| 67 | max: usize, |
| 68 | }, |
| 69 | /// Something other than a socket already sits at the path. Refused so a |
| 70 | /// misconfigured path can never delete a user's file. |
| 71 | #[error("{} exists and is not a unix socket; refusing to remove it", path.display())] |
| 72 | NotASocket { path: PathBuf }, |
| 73 | /// A daemon answered on the socket: this one must not replace it. |
| 74 | #[error( |
| 75 | "a live listener already answers on {}; refusing to replace it (another codewhale daemon, or something else bound to this path)", |
| 76 | path.display() |
| 77 | )] |
| 78 | AlreadyRunning { path: PathBuf }, |
| 79 | /// The liveness probe neither connected nor was refused within the |
| 80 | /// budget. Refused rather than clobbered; remove the file by hand if the |
| 81 | /// old daemon is truly gone. |
| 82 | #[error("liveness probe of {} timed out; refusing to replace a socket that may be live", path.display())] |
| 83 | ProbeTimedOut { path: PathBuf }, |
| 84 | /// Filesystem or socket I/O failed. |
| 85 | #[error("{context} ({})", path.display())] |
| 86 | Io { |
| 87 | context: &'static str, |
| 88 | path: PathBuf, |
| 89 | #[source] |
| 90 | source: std::io::Error, |
| 91 | }, |
| 92 | /// The app-server state (config, state store, runtime) failed to build. |
| 93 | /// |
| 94 | /// The source carries the real cause; a caller that prints only this |
| 95 | /// message hides it. `serve --http` on a mount where the endpoint |
| 96 | /// directory cannot be private used to surface here as a bare |
| 97 | /// "failed to build daemon state", which named neither the directory nor |
| 98 | /// the reason — see [`Self::EndpointDirectoryUnsupported`]. |
| 99 | #[error("failed to build daemon state")] |
| 100 | State(#[source] anyhow::Error), |
| 101 | /// The filesystem cannot hold the private directory an endpoint needs. |
| 102 | /// |
| 103 | /// A private endpoint directory must be current-user-owned and closed to |
| 104 | /// group and other. HarmonyOS hmdfs — the 2in1 user directory — reports the |
| 105 | /// logged-in user's uid and a group-writable mode for every object created |
| 106 | /// on it, so `chmod` answers `EPERM` and no directory there can satisfy that |
| 107 | /// check. |
| 108 | /// This is a missing capability, not a refusal: an owner with an HTTP |
| 109 | /// frontend can run without its control socket, and does. |
| 110 | #[error( |
| 111 | "the filesystem cannot hold a private endpoint directory at {}: {reason}", |
| 112 | path.display() |
| 113 | )] |
| 114 | EndpointDirectoryUnsupported { path: PathBuf, reason: String }, |
| 115 | } |
| 116 | |
| 117 | /// Inputs to [`resolve_socket_path`], separated from the environment so the |
| 118 | /// precedence rules can be verified independently of process-wide variables. |
| 119 | #[derive(Debug, Clone, Default)] |
| 120 | pub struct SocketPathInputs { |
| 121 | /// `--socket-path`. |
| 122 | pub explicit: Option<PathBuf>, |
| 123 | /// A valid explicit `CODEWHALE_HOME`. |
| 124 | pub codewhale_home_override: Option<PathBuf>, |
| 125 | /// `$XDG_RUNTIME_DIR`, when set and non-empty. |
| 126 | pub xdg_runtime_dir: Option<PathBuf>, |
| 127 | /// The user's home directory. |
| 128 | pub user_home: Option<PathBuf>, |
| 129 | /// Whether the macOS Application Support layout applies. |
| 130 | pub macos: bool, |
| 131 | } |
| 132 | |
| 133 | impl SocketPathInputs { |
| 134 | /// Capture the live environment. |
| 135 | pub fn from_environment(explicit: Option<PathBuf>) -> Result<Self, DaemonSocketError> { |
| 136 | let codewhale_home_override = crate::codewhale_home_override() |
| 137 | .map_err(|err| DaemonSocketError::InvalidHomeOverride(err.to_string()))?; |
| 138 | let xdg_runtime_dir = std::env::var_os("XDG_RUNTIME_DIR") |
| 139 | .filter(|value| !value.is_empty()) |
| 140 | .map(PathBuf::from); |
| 141 | let user_home = crate::user_home(); |
| 142 | Ok(Self { |
| 143 | explicit, |
| 144 | codewhale_home_override, |
| 145 | xdg_runtime_dir, |
| 146 | user_home, |
| 147 | macos: cfg!(target_os = "macos"), |
| 148 | }) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | fn implicit_endpoint_root( |
| 153 | _variable: &'static str, |
| 154 | root: PathBuf, |
| 155 | ) -> Result<PathBuf, DaemonSocketError> { |
| 156 | #[cfg(unix)] |
| 157 | { |
| 158 | if !root.is_absolute() |
| 159 | || root |
| 160 | .components() |
| 161 | .any(|part| matches!(part, std::path::Component::ParentDir)) |
| 162 | { |
| 163 | return Err(DaemonSocketError::InvalidRuntimeRoot { |
| 164 | variable: _variable, |
| 165 | reason: "expected an absolute directory path without '..' components", |
| 166 | }); |
| 167 | } |
| 168 | let root = crate::resolve_root_owned_ancestors(&root); |
| 169 | for ancestor in root.ancestors() { |
| 170 | match std::fs::symlink_metadata(ancestor) { |
| 171 | Ok(metadata) if metadata.file_type().is_symlink() => { |
| 172 | return Err(DaemonSocketError::InvalidRuntimeRoot { |
| 173 | variable: _variable, |
| 174 | reason: "a non-system symbolic link is not allowed", |
| 175 | }); |
| 176 | } |
| 177 | Err(error) if error.kind() != std::io::ErrorKind::NotFound => { |
| 178 | return Err(DaemonSocketError::Io { |
| 179 | context: "cannot inspect runtime endpoint directory", |
| 180 | path: ancestor.to_path_buf(), |
| 181 | source: error, |
| 182 | }); |
| 183 | } |
| 184 | _ => {} |
| 185 | } |
| 186 | } |
| 187 | Ok(root) |
| 188 | } |
| 189 | #[cfg(not(unix))] |
| 190 | { |
| 191 | Ok(root) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// Apply the precedence rules documented at the module level, shortening only |
| 196 | /// implicit endpoints to leave room for store-specific control sockets. |
| 197 | pub fn resolve_socket_path(inputs: &SocketPathInputs) -> Result<PathBuf, DaemonSocketError> { |
| 198 | let path = if let Some(explicit) = inputs.explicit.clone() { |
| 199 | explicit |
| 200 | } else if let Some(home) = inputs.codewhale_home_override.clone() { |
| 201 | implicit_endpoint_root("CODEWHALE_HOME", home)? |
| 202 | .join("run") |
| 203 | .join(DAEMON_SOCKET_FILE_NAME) |
| 204 | } else if let Some(runtime_dir) = inputs.xdg_runtime_dir.clone() { |
| 205 | implicit_endpoint_root("XDG_RUNTIME_DIR", runtime_dir)? |
| 206 | .join("codewhale") |
| 207 | .join(DAEMON_SOCKET_FILE_NAME) |
| 208 | } else { |
| 209 | let user_home = inputs |
| 210 | .user_home |
| 211 | .clone() |
| 212 | .ok_or(DaemonSocketError::RuntimeDirUnavailable)?; |
| 213 | let user_home = implicit_endpoint_root("HOME", user_home)?; |
| 214 | if inputs.macos { |
| 215 | user_home |
| 216 | .join("Library") |
| 217 | .join("Application Support") |
| 218 | .join("codewhale") |
| 219 | .join(DAEMON_SOCKET_FILE_NAME) |
| 220 | } else { |
| 221 | user_home |
| 222 | .join(crate::CODEWHALE_APP_DIR) |
| 223 | .join("run") |
| 224 | .join(DAEMON_SOCKET_FILE_NAME) |
| 225 | } |
| 226 | }; |
| 227 | #[cfg(unix)] |
| 228 | if inputs.explicit.is_none() { |
| 229 | let store_name = format!("store-{}.sock", "0".repeat(DERIVED_STORE_HASH_BYTES * 2)); |
| 230 | if path.with_file_name(store_name).as_os_str().len() > MAX_SOCKET_PATH_BYTES { |
| 231 | return Ok(short_socket_directory(&path).join(DAEMON_SOCKET_FILE_NAME)); |
| 232 | } |
| 233 | } |
| 234 | let len = path.as_os_str().len(); |
| 235 | if len > MAX_SOCKET_PATH_BYTES { |
| 236 | return Err(DaemonSocketError::PathTooLong { |
| 237 | path, |
| 238 | len, |
| 239 | max: MAX_SOCKET_PATH_BYTES, |
| 240 | }); |
| 241 | } |
| 242 | Ok(path) |
| 243 | } |
| 244 | |
| 245 | #[cfg(unix)] |
| 246 | fn short_socket_directory(scope: &Path) -> PathBuf { |
| 247 | use sha2::Digest as _; |
| 248 | |
| 249 | let mut digest = sha2::Sha256::new(); |
| 250 | digest.update(b"Codewhale/short-socket/v1\0"); |
| 251 | digest.update(scope.as_os_str().as_encoded_bytes()); |
| 252 | let suffix: String = digest.finalize()[..16] |
| 253 | .iter() |
| 254 | .map(|byte| format!("{byte:02x}")) |
| 255 | .collect(); |
| 256 | let root = if cfg!(target_os = "macos") { |
| 257 | "/private/tmp" |
| 258 | } else { |
| 259 | "/tmp" |
| 260 | }; |
| 261 | PathBuf::from(root).join(format!("codewhale-{suffix}")) |
| 262 | } |
| 263 | |
| 264 | /// The socket path this host would use with no explicit override. |
| 265 | #[cfg(unix)] |
| 266 | pub fn default_socket_path() -> Result<PathBuf, DaemonSocketError> { |
| 267 | resolve_socket_path(&SocketPathInputs::from_environment(None)?) |
| 268 | } |
| 269 | |
| 270 | /// Digest bytes that name a derived socket. Six bytes (twelve hex characters, |
| 271 | /// the same digest length the runtime-boundary id uses) make the basename a |
| 272 | /// fixed 23 bytes with the `store-` prefix and the `.sock` suffix, which keeps |
| 273 | /// the hard kernel path limit reachable only for an already-close default |
| 274 | /// endpoint instead of consuming the remaining headroom. |
| 275 | #[cfg(unix)] |
| 276 | const DERIVED_STORE_HASH_BYTES: usize = 6; |
| 277 | |
| 278 | /// The control endpoint for a selected runtime store: the well-known default |
| 279 | /// socket when the store is the default selection, and a private sibling |
| 280 | /// derived from the store root otherwise. |
| 281 | /// |
| 282 | /// One control endpoint per runtime store, as a pure function of the store |
| 283 | /// selection. A client that selects a non-default store (`CODEWHALE_RUNTIME_DIR`, |
| 284 | /// e.g. the VS Code extension's per-workspace store) elects its own owner |
| 285 | /// instead of colliding with the default store's owner on the shared socket; |
| 286 | /// the default store keeps the historical path, so discovery, `doctor` and |
| 287 | /// single-engine setups are unchanged. |
| 288 | /// |
| 289 | /// `store_root` is the canonicalized runtime store root the caller selected; |
| 290 | /// `None` means "the default selection" (no override in effect). |
| 291 | /// |
| 292 | /// Unix only: a Windows owner endpoint is a named pipe. |
| 293 | #[cfg(unix)] |
| 294 | pub fn store_selected_socket_path( |
| 295 | store_root: Option<&Path>, |
| 296 | inputs: &SocketPathInputs, |
| 297 | ) -> Result<PathBuf, DaemonSocketError> { |
| 298 | use anyhow::Context as _; |
| 299 | use sha2::Digest as _; |
| 300 | |
| 301 | let base = resolve_socket_path(inputs)?; |
| 302 | let Some(store_root) = store_root else { |
| 303 | return Ok(base); |
| 304 | }; |
| 305 | let mut digest = sha2::Sha256::new(); |
| 306 | // The tag keeps this name from colliding with any other use of the store |
| 307 | // root's digest in the same directory. |
| 308 | digest.update(b"Codewhale/store-socket/v1\0"); |
| 309 | digest.update(store_root.as_os_str().as_encoded_bytes()); |
| 310 | let suffix: String = digest.finalize()[..DERIVED_STORE_HASH_BYTES] |
| 311 | .iter() |
| 312 | .map(|byte| format!("{byte:02x}")) |
| 313 | .collect(); |
| 314 | let parent = base |
| 315 | .parent() |
| 316 | .context("default daemon socket has no parent directory") |
| 317 | .map_err(DaemonSocketError::State)?; |
| 318 | let derived = parent.join(format!("store-{suffix}.sock")); |
| 319 | let len = derived.as_os_str().len(); |
| 320 | if len > MAX_SOCKET_PATH_BYTES { |
| 321 | return Err(DaemonSocketError::PathTooLong { |
| 322 | path: derived, |
| 323 | len, |
| 324 | max: MAX_SOCKET_PATH_BYTES, |
| 325 | }); |
| 326 | } |
| 327 | Ok(derived) |
| 328 | } |
| 329 |