UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

322 lines (321 loc) • 9.04 kB
import { A as parseStrictPositiveInteger, L as normalizeLowercaseStringOrEmpty } from "./path-guards-quCEQx1i.mjs"; import { n as resolveDiagnosticProcessEnv } from "./process-env-Bx8i77R6.mjs"; import { x as canAccess } from "./redact-BRF0hr6G.mjs"; import { t as runCommandWithTimeout } from "./exec-CUD-gZWW.mjs"; import { a as parseTcpEndpoint, i as buildPortHints, o as parseTcpListenerEndpoint, s as parseWindowsNetstatListeners, t as probePortUsage } from "./ports-probe-BXzZ4if-.mjs"; import { a as getWindowsSystem32ExePath, o as getWindowsWmicExePath, r as getWindowsPowerShellExePath } from "./windows-install-roots-CNvr-0dO.mjs"; import fsSync from "node:fs"; import os from "node:os"; import net from "node:net"; import pMap from "p-map"; //#region src/infra/ports-lsof.ts const LSOF_CANDIDATES = process.platform === "darwin" ? ["/usr/sbin/lsof", "/usr/bin/lsof"] : ["/usr/bin/lsof", "/usr/sbin/lsof"]; async function resolveLsofCommand(e) { for (const t of LSOF_CANDIDATES) { e?.throwIfAborted(); const n = await canAccess(t, fsSync.constants.X_OK); e?.throwIfAborted(); if (n) return t; } return "lsof"; } //#endregion //#region src/infra/ports-inspect.ts const PORT_PROCESS_ENRICHMENT_CONCURRENCY = 20; async function runCommandSafe(e, t) { t?.throwIfAborted(); try { const n = await runCommandWithTimeout(e, { timeoutMs: 5e3, baseEnv: resolveDiagnosticProcessEnv(), ...t ? { signal: t } : {} }); t?.throwIfAborted(); return { stdout: n.stdout, stderr: n.stderr, code: n.code ?? 1 }; } catch (e) { t?.throwIfAborted(); return { stdout: "", stderr: "", code: 1, error: String(e) }; } } function parseLsofListenerRecordsByPort(e) { const t = /* @__PURE__ */ new Map(); let n = {}; for (const r of e.split(/\r?\n/)) { const e = r.trim(); if (!e) continue; if (e.startsWith("p")) { const t = parseStrictPositiveInteger(e.slice(1)); n = t !== void 0 ? { pid: t } : {}; continue; } if (e.startsWith("c")) { n.command = e.slice(1); continue; } if (e.startsWith("n")) { const r = { ...n, address: e.slice(1) }; const i = r.address.replace(/^tcp\s+/i, "").replace(/\s*\([^)]*\)\s*$/i, "").trim(); const a = i && !i.includes("->") ? parseTcpEndpoint(i)?.port ?? null : null; if (a !== null) { const e = t.get(a) ?? []; e.push(r); t.set(a, e); } } } return t; } function* parseSsRows(e) { for (const t of e.split(/\r?\n/)) { const e = t.trim(); const n = e.indexOf("users:"); const r = (n < 0 ? e : e.slice(0, n)).trim().split(/\s+/); const [i, a] = r.slice(-2); if (!i || !a) continue; const o = n < 0 ? "" : e.slice(n); const s = Number.parseInt(o.match(/pid=(\d+)/)?.[1] ?? "", 10); const c = o.match(/users:\(\("([^"]+)"/)?.[1]; yield { local: i, remote: a, listening: r.includes("LISTEN"), process: { ...Number.isFinite(s) ? { pid: s } : {}, ...c ? { command: c } : {} } }; } } async function enrichListenerProcessInfo(e, t) { const n = [...new Set(e.flatMap(({ pid: e }) => e ? [e] : []))]; const r = new Map(await pMap(n, async (e) => [e, await resolveProcessInfo(e, t)], { concurrency: PORT_PROCESS_ENRICHMENT_CONCURRENCY, signal: t })); for (const t of e) if (t.pid) Object.assign(t, r.get(t.pid)); } async function readUnixSocketOutput(e, t) { const n = await runCommandSafe(e, t); if (n.code === 0) return { stdout: n.stdout, errors: [], unavailable: false }; const r = n.stderr.trim(); if (n.code === 1 && !n.error && !r) return { errors: [], unavailable: false }; const i = [r, n.stdout.trim()].filter(Boolean).join("\n"); return { errors: [...n.error ? [n.error] : [], ...i ? [i] : []], unavailable: true }; } async function readUnixSocketEntries(e, t, n, r) { const i = await readUnixSocketOutput(e, n); const a = i.stdout === void 0 ? [] : t(i.stdout); return { entries: a, errors: r && a.length === 0 ? [...r, ...i.errors] : i.errors, ...r ? {} : { unavailable: i.unavailable } }; } async function resolveProcessInfo(e, t) { if (process.platform === "win32") { const [n, r] = await Promise.all([resolveWindowsImageName(e, t), resolveWindowsCommandLine(e, t)]); return { ...n ? { command: n } : {}, ...r ? { commandLine: r } : {} }; } const n = await runCommandSafe([ "ps", "-p", String(e), "-ww", "-o", "ppid=", "-o", "command=" ], t); const r = await runCommandSafe([ "ps", "-p", String(e), "-o", "user=" ], t); const i = n.code === 0 ? /^\s*(\S+)(?:\s+([\s\S]*))?$/.exec(n.stdout) : null; const a = Number.parseInt(i?.[1] ?? "", 10); const o = i?.[2]?.trim(); const s = r.code === 0 ? r.stdout.trim() : ""; return { ...s ? { user: s } : {}, ...o ? { commandLine: o } : {}, ...Number.isFinite(a) && a > 0 ? { ppid: a } : {} }; } function parseSsListeners(e, t) { const n = []; for (const r of parseSsRows(e)) if (r.listening && parseTcpEndpoint(r.local)?.port === t) n.push({ ...r.process, address: r.local }); return n; } async function readUnixListenerSnapshot(e, t) { const n = await readUnixSocketOutput([ await resolveLsofCommand(t), "-nP", e === void 0 ? "-iTCP" : `-iTCP:${e}`, "-sTCP:LISTEN", "-FpFcn" ], t); return { recordsByPort: parseLsofListenerRecordsByPort(n.stdout ?? ""), errors: n.errors, lsofUnavailable: n.unavailable }; } async function readUnixListeners(e, t, n) { const r = t ?? await readUnixListenerSnapshot(e, n); if (!r.lsofUnavailable) { const t = r.recordsByPort.get(e) ?? []; const n = /* @__PURE__ */ new Set(); const i = []; for (const e of t) { const t = `${e.pid ?? ""}\0${e.command ?? ""}\0${e.address ?? ""}`; if (n.has(t)) continue; n.add(t); i.push(e); } return { entries: i, errors: r.errors }; } return await readUnixSocketEntries([ "ss", "-H", "-ltnp", `sport = :${e}` ], (t) => parseSsListeners(t, e), n, r.errors); } async function resolveWindowsImageName(e, t) { t?.throwIfAborted(); const n = await runCommandSafe([ getWindowsSystem32ExePath("tasklist.exe"), "/FI", `PID eq ${e}`, "/FO", "CSV", "/NH" ], t); if (n.code !== 0) return; for (const t of n.stdout.split(/\r?\n/)) { const n = t.trim().match(/^"([^"]+)","(\d+)",/); if (n?.[1] && n[2] === String(e)) return n[1]; } } async function resolveWindowsCommandLine(e, t) { t?.throwIfAborted(); const n = await runCommandSafe([ getWindowsPowerShellExePath(), "-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}" | Select-Object -ExpandProperty CommandLine)` ], t); if (n.code === 0) { const e = n.stdout.trim(); if (e) return e; } const r = await runCommandSafe([ getWindowsWmicExePath(), "process", "where", `ProcessId=${e}`, "get", "CommandLine", "/value" ], t); if (r.code !== 0) return; for (const e of r.stdout.split(/\r?\n/)) { const t = e.trim(); if (!normalizeLowercaseStringOrEmpty(t).startsWith("commandline=")) continue; return t.slice(12).trim() || void 0; } } async function readWindowsNetstatEntries(e, t, n) { n?.throwIfAborted(); const r = []; const i = await runCommandSafe([getWindowsSystem32ExePath("netstat.exe"), "-ano"], n); if (i.code !== 0) { if (i.error) r.push(i.error); const t = [i.stderr.trim(), i.stdout.trim()].filter(Boolean).join("\n"); if (t) r.push(t); return e.map(() => ({ entries: [], errors: r })); } return e.map((e) => ({ entries: t(i.stdout, e), errors: r })); } async function inspectPortUsage(e, t) { const n = t?.signal; n?.throwIfAborted(); const r = process.platform === "win32" ? (await readWindowsNetstatEntries([e], parseWindowsNetstatListeners, n))[0] : await readUnixListeners(e, void 0, n); await enrichListenerProcessInfo(r.entries, n); return buildPortUsage(e, r, t?.probeHosts, n, t?.deadlineMs); } async function buildPortUsage(e, t, n, r, i) { r?.throwIfAborted(); let a = t.entries; const o = n ? await probePortUsage(e, n, r, i) : a.length > 0 ? "busy" : await probePortUsage(e, void 0, r, i); r?.throwIfAborted(); if (o !== "busy") a = []; else if (n) a = a.filter((t) => { const r = parseTcpListenerEndpoint(t.address); if (!r || r.port !== e) return false; return n.some((e) => { const t = normalizeLowercaseStringOrEmpty(e); if (isWildcardTcpHost(r.host)) return isSameTcpAddressFamily(r.host, t); if (isWildcardTcpHost(t)) return isSameTcpAddressFamily(t, r.host); return t === r.host; }); }); const s = buildPortHints(a, e); if (o === "busy" && a.length === 0) s.push("Port is in use but process details are unavailable (install lsof or run as an admin user)."); return { port: e, status: o, listeners: a, hints: s, errors: t.errors.length > 0 ? [...t.errors] : void 0 }; } function isWildcardTcpHost(e) { return e === "0.0.0.0" || e === "::" || e === "*"; } function isSameTcpAddressFamily(e, t) { const n = net.isIP(e); const r = net.isIP(t); return n === 0 || r === 0 || n === r; } //#endregion export { inspectPortUsage };