|
| 1 | +/** systemctl execution, user-manager routing, and availability probes. */ |
| 2 | +import * as fsSync from "node:fs"; |
| 3 | +import os from "node:os"; |
| 4 | +import path from "node:path"; |
| 5 | +import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce"; |
| 6 | +import { escapeRegExp } from "../shared/regexp.js"; |
| 7 | +import { execFileUtf8 } from "./exec-file.js"; |
| 8 | +import type { GatewayServiceEnv } from "./service-types.js"; |
| 9 | +import { |
| 10 | + classifySystemdUnavailableDetail, |
| 11 | + isSystemctlMissingDetail, |
| 12 | + isSystemdUserBusUnavailableDetail, |
| 13 | +} from "./systemd-unavailable.js"; |
| 14 | + |
| 15 | +export type SystemdUnitScope = "system" | "user"; |
| 16 | + |
| 17 | +export async function execSystemctl( |
| 18 | + args: string[], |
| 19 | + env?: GatewayServiceEnv, |
| 20 | + timeoutMs?: number, |
| 21 | +): Promise<{ stdout: string; stderr: string; code: number }> { |
| 22 | + return await execFileUtf8("systemctl", args, { |
| 23 | + env: env ? resolveSystemctlProcessEnv(env) : process.env, |
| 24 | + // A wedged systemd socket can leave `systemctl` blocked forever; the timeout |
| 25 | + // kills the child so status reads fail soft instead of hanging the command. |
| 26 | + ...(timeoutMs && timeoutMs > 0 ? { timeout: timeoutMs, killSignal: "SIGKILL" as const } : {}), |
| 27 | + }); |
| 28 | +} |
| 29 | + |
| 30 | +export function readSystemctlDetail(result: { stdout: string; stderr: string }): string { |
| 31 | + // Concatenate both streams so pattern matchers (isSystemdUnitNotEnabled, |
| 32 | + // isSystemctlMissing) can see the unit status from stdout even when |
| 33 | + // execFileUtf8 populates stderr with the Node error message fallback. |
| 34 | + return `${result.stderr} ${result.stdout}`.trim(); |
| 35 | +} |
| 36 | + |
| 37 | +export const isSystemctlMissing = isSystemctlMissingDetail; |
| 38 | + |
| 39 | +export function isSystemdUnitNotEnabled(detail: string): boolean { |
| 40 | + if (!detail) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + const normalized = normalizeLowercaseStringOrEmpty(detail); |
| 44 | + return ( |
| 45 | + normalized.includes("disabled") || |
| 46 | + normalized.includes("static") || |
| 47 | + normalized.includes("indirect") || |
| 48 | + normalized.includes("masked") || |
| 49 | + normalized.includes("not-found") || |
| 50 | + normalized.includes("could not be found") || |
| 51 | + normalized.includes("failed to get unit file state") |
| 52 | + ); |
| 53 | +} |
| 54 | + |
| 55 | +export function isSystemdUnitMissingDetail(detail: string): boolean { |
| 56 | + if (!detail) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + const normalized = normalizeLowercaseStringOrEmpty(detail); |
| 60 | + return ( |
| 61 | + (normalized.includes("unit file") && normalized.includes("does not exist")) || |
| 62 | + normalized.includes("not-found") || |
| 63 | + normalized.includes("could not be found") |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +function isSystemdUnitAlreadyMissingOrInactive(detail: string, unitName: string): boolean { |
| 68 | + const escapedUnitName = escapeRegExp(normalizeLowercaseStringOrEmpty(unitName)); |
| 69 | + return new RegExp( |
| 70 | + `^(?:failed to (?:disable unit|stop\\s+${escapedUnitName}):\\s*)?` + |
| 71 | + `(?:unit file\\s+${escapedUnitName}\\s+does not exist|` + |
| 72 | + `unit\\s+${escapedUnitName}(?:\\s+is)?\\s+` + |
| 73 | + `(?:inactive|not\\s+active|not\\s+loaded|not-found|could not be found))[.!]?$`, |
| 74 | + "u", |
| 75 | + ).test(normalizeLowercaseStringOrEmpty(detail)); |
| 76 | +} |
| 77 | + |
| 78 | +const isSystemctlBusUnavailable = isSystemdUserBusUnavailableDetail; |
| 79 | + |
| 80 | +export function isSystemdUserScopeUnavailable(detail: string): boolean { |
| 81 | + return classifySystemdUnavailableDetail(detail) !== null; |
| 82 | +} |
| 83 | + |
| 84 | +function isGenericSystemctlIsEnabledFailure(detail: string): boolean { |
| 85 | + if (!detail) { |
| 86 | + return false; |
| 87 | + } |
| 88 | + const normalized = normalizeLowercaseStringOrEmpty(detail); |
| 89 | + return ( |
| 90 | + normalized.startsWith("command failed: systemctl") && |
| 91 | + normalized.includes(" is-enabled ") && |
| 92 | + !normalized.includes("permission denied") && |
| 93 | + !normalized.includes("access denied") && |
| 94 | + !normalized.includes("no space left") && |
| 95 | + !normalized.includes("read-only file system") && |
| 96 | + !normalized.includes("out of memory") && |
| 97 | + !normalized.includes("cannot allocate memory") |
| 98 | + ); |
| 99 | +} |
| 100 | + |
| 101 | +export function isNonFatalSystemdInstallProbeError(error: unknown): boolean { |
| 102 | + const detail = error instanceof Error ? error.message : typeof error === "string" ? error : ""; |
| 103 | + if (!detail) { |
| 104 | + return false; |
| 105 | + } |
| 106 | + const normalized = normalizeLowercaseStringOrEmpty(detail); |
| 107 | + return isSystemctlBusUnavailable(normalized) || isGenericSystemctlIsEnabledFailure(normalized); |
| 108 | +} |
| 109 | + |
| 110 | +function resolveSystemctlDirectUserScopeArgs(): string[] { |
| 111 | + return ["--user"]; |
| 112 | +} |
| 113 | + |
| 114 | +function readSystemctlEnvUser(env: GatewayServiceEnv): string | null { |
| 115 | + return env.USER?.trim() || env.LOGNAME?.trim() || null; |
| 116 | +} |
| 117 | + |
| 118 | +function readSystemctlEffectiveUser(): string | null { |
| 119 | + try { |
| 120 | + return os.userInfo().username; |
| 121 | + } catch { |
| 122 | + return null; |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +function readSystemctlEffectiveUid(): number | null { |
| 127 | + if (typeof process.geteuid !== "function") { |
| 128 | + return null; |
| 129 | + } |
| 130 | + try { |
| 131 | + return process.geteuid(); |
| 132 | + } catch { |
| 133 | + return null; |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +function resolveSystemctlProcessEnv(env: GatewayServiceEnv): NodeJS.ProcessEnv { |
| 138 | + const processEnv = { ...process.env, ...env }; |
| 139 | + if (processEnv.XDG_RUNTIME_DIR?.trim() && processEnv.DBUS_SESSION_BUS_ADDRESS?.trim()) { |
| 140 | + return processEnv; |
| 141 | + } |
| 142 | + |
| 143 | + const uid = readSystemctlEffectiveUid(); |
| 144 | + if (uid === null || uid === 0) { |
| 145 | + return processEnv; |
| 146 | + } |
| 147 | + |
| 148 | + const runtimeDir = processEnv.XDG_RUNTIME_DIR?.trim() || `/run/user/${uid}`; |
| 149 | + const busPath = path.posix.join(runtimeDir, "bus"); |
| 150 | + if (!fsSync.existsSync(busPath)) { |
| 151 | + return processEnv; |
| 152 | + } |
| 153 | + |
| 154 | + // In non-login shells the bus socket can exist while DBUS_SESSION_BUS_ADDRESS |
| 155 | + // is missing. Fill it so systemctl --user reaches the right user manager. |
| 156 | + return { |
| 157 | + ...processEnv, |
| 158 | + XDG_RUNTIME_DIR: runtimeDir, |
| 159 | + DBUS_SESSION_BUS_ADDRESS: processEnv.DBUS_SESSION_BUS_ADDRESS?.trim() || `unix:path=${busPath}`, |
| 160 | + }; |
| 161 | +} |
| 162 | + |
| 163 | +function isNonRootUser(user: string | null): user is string { |
| 164 | + return Boolean(user && user !== "root"); |
| 165 | +} |
| 166 | + |
| 167 | +function hasRootUserManagerEnvironment(env: GatewayServiceEnv): boolean { |
| 168 | + const home = env.HOME?.trim(); |
| 169 | + const runtimeDir = env.XDG_RUNTIME_DIR?.trim(); |
| 170 | + const dbusAddress = env.DBUS_SESSION_BUS_ADDRESS?.trim(); |
| 171 | + return ( |
| 172 | + home === "/root" && |
| 173 | + runtimeDir === "/run/user/0" && |
| 174 | + Boolean(dbusAddress?.includes("/run/user/0/bus")) |
| 175 | + ); |
| 176 | +} |
| 177 | + |
| 178 | +function resolveSystemctlUserScope(env: GatewayServiceEnv): { |
| 179 | + machineUser: string | null; |
| 180 | + preferMachineScope: boolean; |
| 181 | +} { |
| 182 | + const sudoUser = env.SUDO_USER?.trim() || null; |
| 183 | + const envUser = readSystemctlEnvUser(env); |
| 184 | + const effectiveUid = readSystemctlEffectiveUid(); |
| 185 | + const effectiveUser = readSystemctlEffectiveUser(); |
| 186 | + const isEffectiveRoot = effectiveUid === null ? effectiveUser === "root" : effectiveUid === 0; |
| 187 | + const hasRootUserManager = isEffectiveRoot && hasRootUserManagerEnvironment(env); |
| 188 | + const isSudoToRoot = isEffectiveRoot && !hasRootUserManager && isNonRootUser(sudoUser); |
| 189 | + const machineUser = hasRootUserManager |
| 190 | + ? null |
| 191 | + : isSudoToRoot |
| 192 | + ? sudoUser |
| 193 | + : isNonRootUser(envUser) |
| 194 | + ? envUser |
| 195 | + : isNonRootUser(sudoUser) |
| 196 | + ? sudoUser |
| 197 | + : effectiveUser || envUser || sudoUser || null; |
| 198 | + return { |
| 199 | + machineUser, |
| 200 | + preferMachineScope: isSudoToRoot, |
| 201 | + }; |
| 202 | +} |
| 203 | + |
| 204 | +/** |
| 205 | + * Resolves the account whose user manager owns the service operation. |
| 206 | + * Keep linger diagnostics on this identity so sudo never checks root while |
| 207 | + * systemctl targets the invoking user's manager. |
| 208 | + */ |
| 209 | +export function resolveSystemdUserServiceAccount(env: GatewayServiceEnv): string | null { |
| 210 | + const { machineUser } = resolveSystemctlUserScope(env); |
| 211 | + return machineUser ?? readSystemctlEffectiveUser() ?? readSystemctlEnvUser(env); |
| 212 | +} |
| 213 | + |
| 214 | +function resolveSystemctlMachineUserScopeArgs(user: string): string[] { |
| 215 | + const trimmedUser = user.trim(); |
| 216 | + if (!trimmedUser) { |
| 217 | + return []; |
| 218 | + } |
| 219 | + return ["--machine", `${trimmedUser}@`, "--user"]; |
| 220 | +} |
| 221 | + |
| 222 | +function shouldFallbackToMachineUserScope(detail: string): boolean { |
| 223 | + if (!isSystemdUserBusUnavailableDetail(detail)) { |
| 224 | + return false; |
| 225 | + } |
| 226 | + // "Permission denied" means the bus socket exists but this process cannot connect to it. |
| 227 | + // The machine-scope approach targets the same bus infrastructure and will also fail, |
| 228 | + // so do not trigger the fallback in this case. |
| 229 | + return !detail.toLowerCase().includes("permission denied"); |
| 230 | +} |
| 231 | + |
| 232 | +export async function execSystemctlUser( |
| 233 | + env: GatewayServiceEnv, |
| 234 | + args: string[], |
| 235 | + timeoutMs?: number, |
| 236 | +): Promise<{ stdout: string; stderr: string; code: number }> { |
| 237 | + const { machineUser, preferMachineScope } = resolveSystemctlUserScope(env); |
| 238 | + |
| 239 | + // Under sudo-to-root, prefer the invoking non-root user's scope directly via machine scope. |
| 240 | + if (preferMachineScope && machineUser) { |
| 241 | + const machineScopeArgs = resolveSystemctlMachineUserScopeArgs(machineUser); |
| 242 | + if (machineScopeArgs.length > 0) { |
| 243 | + // Do not fall through to bare --user: under sudo that can target root's user manager. |
| 244 | + return await execSystemctl([...machineScopeArgs, ...args], env, timeoutMs); |
| 245 | + } |
| 246 | + } |
| 247 | + |
| 248 | + const directResult = await execSystemctl( |
| 249 | + [...resolveSystemctlDirectUserScopeArgs(), ...args], |
| 250 | + env, |
| 251 | + timeoutMs, |
| 252 | + ); |
| 253 | + if (directResult.code === 0) { |
| 254 | + return directResult; |
| 255 | + } |
| 256 | + |
| 257 | + const detail = `${directResult.stderr} ${directResult.stdout}`.trim(); |
| 258 | + if (!machineUser || !shouldFallbackToMachineUserScope(detail)) { |
| 259 | + return directResult; |
| 260 | + } |
| 261 | + |
| 262 | + const machineScopeArgs = resolveSystemctlMachineUserScopeArgs(machineUser); |
| 263 | + if (machineScopeArgs.length === 0) { |
| 264 | + return directResult; |
| 265 | + } |
| 266 | + return await execSystemctl([...machineScopeArgs, ...args], env, timeoutMs); |
| 267 | +} |
| 268 | + |
| 269 | +export async function disableSystemdUserUnitForRemoval( |
| 270 | + env: GatewayServiceEnv, |
| 271 | + unitName: string, |
| 272 | +): Promise<void> { |
| 273 | + const result = await execSystemctlUser(env, ["disable", "--now", unitName]); |
| 274 | + if (result.code === 0) { |
| 275 | + return; |
| 276 | + } |
| 277 | + const detail = readSystemctlDetail(result); |
| 278 | + if (isSystemdUnitAlreadyMissingOrInactive(detail, unitName)) { |
| 279 | + return; |
| 280 | + } |
| 281 | + throw new Error(`systemctl disable failed: ${detail || "unknown error"}`); |
| 282 | +} |
| 283 | + |
| 284 | +export async function reloadSystemdUserManager(env: GatewayServiceEnv): Promise<void> { |
| 285 | + const result = await execSystemctlUser(env, ["daemon-reload"]); |
| 286 | + if (result.code !== 0) { |
| 287 | + throw new Error( |
| 288 | + `systemctl daemon-reload failed: ${readSystemctlDetail(result) || "unknown error"}`, |
| 289 | + ); |
| 290 | + } |
| 291 | +} |
| 292 | + |
| 293 | +export async function isSystemdUserServiceAvailable( |
| 294 | + env: GatewayServiceEnv = process.env as GatewayServiceEnv, |
| 295 | +): Promise<boolean> { |
| 296 | + const res = await execSystemctlUser(env, ["status"]); |
| 297 | + if (res.code === 0) { |
| 298 | + return true; |
| 299 | + } |
| 300 | + const detail = `${res.stderr} ${res.stdout}`.trim(); |
| 301 | + if (!detail) { |
| 302 | + return false; |
| 303 | + } |
| 304 | + return !isSystemdUserScopeUnavailable(detail); |
| 305 | +} |
| 306 | + |
| 307 | +export async function isSystemdUnitActive( |
| 308 | + env: GatewayServiceEnv, |
| 309 | + unitName: string, |
| 310 | + scope: SystemdUnitScope = "user", |
| 311 | +): Promise<boolean> { |
| 312 | + const normalizedUnit = unitName.trim(); |
| 313 | + if (!normalizedUnit) { |
| 314 | + return false; |
| 315 | + } |
| 316 | + const args = ["is-active", "--quiet", normalizedUnit]; |
| 317 | + const res = scope === "system" ? await execSystemctl(args) : await execSystemctlUser(env, args); |
| 318 | + return res.code === 0; |
| 319 | +} |
| 320 | + |
| 321 | +export async function assertSystemdAvailable( |
| 322 | + env: GatewayServiceEnv = process.env as GatewayServiceEnv, |
| 323 | + timeoutMs?: number, |
| 324 | +) { |
| 325 | + const res = await execSystemctlUser(env, ["status"], timeoutMs); |
| 326 | + if (res.code === 0) { |
| 327 | + return; |
| 328 | + } |
| 329 | + const detail = readSystemctlDetail(res); |
| 330 | + if (isSystemctlMissing(detail)) { |
| 331 | + throw new Error("systemctl not available; systemd user services are required on Linux."); |
| 332 | + } |
| 333 | + if (!detail) { |
| 334 | + throw new Error("systemctl --user unavailable: unknown error"); |
| 335 | + } |
| 336 | + if (!isSystemdUserScopeUnavailable(detail)) { |
| 337 | + return; |
| 338 | + } |
| 339 | + throw new Error(`systemctl --user unavailable: ${detail || "unknown error"}`.trim()); |
| 340 | +} |
| 341 | + |
| 342 | +export async function isSystemctlAvailable(env: GatewayServiceEnv): Promise<boolean> { |
| 343 | + const res = await execSystemctlUser(env, ["status"]); |
| 344 | + if (res.code === 0) { |
| 345 | + return true; |
| 346 | + } |
| 347 | + return !isSystemctlMissing(readSystemctlDetail(res)); |
| 348 | +} |
0 commit comments