diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index 9136902..8dff691 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -136,6 +136,12 @@ async function main() { } try { + if (process.platform === 'win32') { + await electronApp.evaluate(({ shell }) => { + global.__launcherOpened = []; + shell.openExternal = async (url) => { global.__launcherOpened.push(url); }; + }); + } const page = await electronApp.firstWindow(); const readyDeadline = Date.now() + 60000; let clicked = ''; @@ -225,6 +231,14 @@ async function main() { executablePath: electronPath, cwd: root, args, env, timeout: 120000, }); } + if (process.platform === 'win32') { + const opened = await electronApp.evaluate(() => global.__launcherOpened); + if (!Array.isArray(opened) || opened.length !== 0) { + throw new Error(`Install opened a browser tab after Start: ${JSON.stringify(opened)}`); + } + console.log('PASS install did not open a second browser tab'); + electronApp = await require('./windows-lifecycle-e2e')(electronApp, page, home); + } return; } if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) { diff --git a/scripts/windows-lifecycle-e2e.js b/scripts/windows-lifecycle-e2e.js new file mode 100644 index 0000000..00b6b2f --- /dev/null +++ b/scripts/windows-lifecycle-e2e.js @@ -0,0 +1,195 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); +const { runtimeDataDir, runtimeUpdateCheckPath } = require('../dist/main/targets/runtimePaths'); + +async function health(wanted) { + const deadline = Date.now() + 180000; + while (Date.now() < deadline) { + if (isHealthOk(await probeGatewayHealth()) === wanted) return; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(`Home health did not become ${wanted}`); +} + +async function waitFor(check, timeoutMs, message) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(message); +} + +async function status(page, wanted) { + await waitFor(async () => await page.evaluate(() => window.elastos.getStatus()) === wanted, + 180000, `Launcher status did not become ${wanted}`); + await waitFor(async () => (await page.locator('#status-text').innerText()).toLowerCase() === wanted, + 10000, `Window status did not become ${wanted}`); +} + +function proveLiveController() { + const script = [ + 'import json, os, stat', + 'LIMIT = 16384', + 'ROOT = "/root/.local/share/elastos"', + 'LOCK = ROOT + "/host-process.lock"', + 'DIRECTORY = ROOT + "/update-controller"', + 'STATUS = DIRECTORY + "/status.json"', + 'REQUEST = DIRECTORY + "/request.json"', + 'ACTIVE = DIRECTORY + "/active-request.json"', + 'def read_text(path):', + ' current = ""', + ' parts = path.strip("/").split("/")', + ' info = None', + ' for index, part in enumerate(parts):', + ' current = current + "/" + part', + ' info = os.lstat(current)', + ' if stat.S_ISLNK(info.st_mode):', + ' raise SystemExit("refusing a link at " + current)', + ' if index == len(parts) - 1:', + ' if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT:', + ' raise SystemExit("refusing " + path)', + ' fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)', + ' try:', + ' data = os.read(fd, LIMIT + 1)', + ' finally:', + ' os.close(fd)', + ' if len(data) > LIMIT:', + ' raise SystemExit("refusing " + path)', + ' return data.decode("utf-8", "replace")', + 'def start_id(pid):', + ' raw = read_text("/proc/%d/stat" % pid)', + ' tail = raw.rsplit(")", 1)[1].split()', + ' start = tail[19]', + ' boot = read_text("/proc/sys/kernel/random/boot_id").strip()', + ' if boot:', + ' return "linux:%s:%s" % (boot, start)', + ' return "linux:%s" % start', + 'def ppid_of(pid):', + ' for line in read_text("/proc/%d/status" % pid).splitlines():', + ' if line.startswith("PPid:"):', + ' return int(line.split()[1])', + ' raise SystemExit("no parent")', + 'def command_of(pid):', + ' fd = os.open("/proc/%d/cmdline" % pid, os.O_RDONLY | os.O_NOFOLLOW)', + ' try:', + ' data = os.read(fd, LIMIT)', + ' finally:', + ' os.close(fd)', + ' return data.replace(b"\\x00", b" ").decode("utf-8", "replace")', + 'status = json.loads(read_text(STATUS))', + 'lock = json.loads(read_text(LOCK))', + 'phase = status.get("phase")', + 'if phase not in ("ready", "updated", "restored", "failed"):', + ' raise SystemExit("phase " + str(phase))', + 'controller = status.get("controller_pid")', + 'host = status.get("host_pid")', + 'if type(controller) is not int or type(host) is not int or controller <= 1 or host <= 1:', + ' raise SystemExit("pid")', + 'if lock.get("pid") != host or lock.get("addr") != "localhost:8090":', + ' raise SystemExit("lock")', + 'if not status.get("generation") or lock.get("generation") != status.get("generation"):', + ' raise SystemExit("generation")', + 'if start_id(controller) != status.get("controller_start"):', + ' raise SystemExit("controller is not the live process")', + 'if ppid_of(host) != controller:', + ' raise SystemExit("host parent")', + 'controller_command = command_of(controller)', + 'host_command = command_of(host)', + 'if "update-controller/runtime" not in controller_command or "__update-controller" not in controller_command:', + ' raise SystemExit("controller command")', + 'if "home" not in host_command or "--browser" not in host_command:', + ' raise SystemExit("host command")', + 'if os.path.lexists(REQUEST) or os.path.lexists(ACTIVE):', + ' raise SystemExit("queue is not empty")', + 'print(json.dumps({"phase": phase, "queue": "empty", "controller": controller, "host": host}))', + ].join('\n'); + const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'python3', '-'], { + input: script, + encoding: 'utf8', + timeout: 60000, + windowsHide: true, + }); + if (result.status !== 0) { + throw new Error((result.stderr || result.stdout || 'The update controller was not proved.').trim()); + } + const proof = JSON.parse(result.stdout); + assert.equal(proof.queue, 'empty'); + assert.equal(['ready', 'updated', 'restored', 'failed'].includes(proof.phase), true); + console.log(`PASS controller phase ${proof.phase} is live and the update queue is empty (controller ${proof.controller}, host ${proof.host})`); + console.log('NOT RUN: a System update apply. No newer signed release exists, and apply needs an owner step-up token.'); +} + +function distroUpdateCheck() { + const file = runtimeUpdateCheckPath(runtimeDataDir('linux', '/root', {})); + const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'cat', file], { + encoding: 'utf8', + timeout: 60000, + windowsHide: true, + }); + if (result.status !== 0) { + const detail = `${result.stderr || ''} ${result.stdout || ''}`; + if (!/No such file or directory/.test(detail)) { + throw new Error(detail.trim() || 'The update check file could not be read.'); + } + return null; + } + return JSON.parse(result.stdout); +} + +function launcherUpdateCheck(home) { + const file = path.join(home, '.elastos-launcher', 'update-check.json'); + if (!fs.existsSync(file)) return null; + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +module.exports = async function (app, page, home) { + await app.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async (url) => { global.__openedHome.push(url); }; + }); + await page.click('#open-btn'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + const response = await fetch('http://localhost:8090/home/'); + assert.equal(response.status, 200); + console.log('PASS Open Home invokes the browser with localhost:8090/home/ and Home returns HTTP 200'); + + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close()); + await new Promise((resolve) => setTimeout(resolve, 2500)); + assert.equal(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isVisible()), false); + await health(true); + console.log('PASS closing the window keeps Home running'); + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].show()); + + await page.click('#power-btn'); + await status(page, 'stopped'); + await health(false); + console.log('PASS Stop Home closes the listener'); + await page.click('#open-btn'); + await status(page, 'running'); + await health(true); + console.log('PASS Start Home becomes healthy'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + const logs = await page.locator('#logs-content').innerText(); + assert.equal(logs.includes('Keep this terminal open. Press Ctrl+C to stop Home.'), false); + proveLiveController(); + + const checked = await page.evaluate(() => window.elastos.checkForUpdate()); + assert.equal(checked.updateAvailable, false); + const runtime = distroUpdateCheck(); + if (runtime) { + assert.equal(runtime.outcome, 'up_to_date'); + assert.equal(runtime.offered, false); + console.log('PASS elastos update --check keeps the Runtime up_to_date record'); + } else { + const launcher = launcherUpdateCheck(home); + assert.ok(launcher); + assert.equal(launcher.outcome, 'up_to_date'); + assert.equal(launcher.offered, false); + console.log('PASS elastos update --check stores up_to_date in the launcher record'); + } + return app; +}; diff --git a/src/main/launchController.ts b/src/main/launchController.ts index 9f11b30..49852ed 100644 --- a/src/main/launchController.ts +++ b/src/main/launchController.ts @@ -126,6 +126,8 @@ export interface LaunchInfo { browserNote: string | null; /** Windows: Uninstall saves the whole Linux environment as one file, then removes it. */ uninstallRemovesLinux: boolean; + /** `home --browser` opens one tab. The launcher does not open a second one after Start. */ + runtimeOpensBrowser: boolean; preflight: PreflightReport; openAtLogin: boolean; canRollback: boolean; @@ -286,6 +288,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L error: status === 'error' ? lastError : null, platformNote: platform?.message ?? null, browserNote: browserNote(process.platform), + runtimeOpensBrowser: process.platform === 'darwin' || process.platform === 'win32', uninstallRemovesLinux: process.platform === 'win32', preflight, openAtLogin: readOpenAtLogin(), diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 09ef064..46b633a 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -57,6 +57,8 @@ export interface GatewayProcess { onExit(listener: (code: number | null) => void): void; signal(signal: NodeJS.Signals): void; hasExited(): boolean | Promise; + /** Drop a stop helper. A process that has none does not implement this. */ + dispose?(): void; } /** @@ -318,12 +320,16 @@ export function isHealthOk(result: HealthResult | null): boolean { return Boolean(result && result.status === 200 && result.body.trim() === 'OK'); } +/** The controller prints this on its own stdout. The launcher log does not show it. */ +export const HOME_TERMINAL_LINE = 'Keep this terminal open. Press Ctrl+C to stop Home.'; + /** Drop lines that can carry attach_secret. The coords files stay on disk, out of the log. */ export function scrubRuntimeLog(chunk: string): string { if (/attach_secret|runtime-coords\.json|gateway-runtime-coords|home-runtime-coords/i.test(chunk)) { return '[elastos] omitted a line that can contain a local secret\n'; } - return chunk; + if (!chunk.includes(HOME_TERMINAL_LINE)) return chunk; + return chunk.split(HOME_TERMINAL_LINE).join(''); } export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySupervisor { @@ -357,8 +363,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup : `ElastOS stopped (exit ${code}). Click Start to try again.`); } - function ownAdopted(proc: GatewayProcess | null): void { + function replaceOwned(proc: GatewayProcess | null): void { + if (owned && owned !== proc) owned.dispose?.(); owned = proc; + } + + function ownAdopted(proc: GatewayProcess | null): void { + replaceOwned(proc); proc?.onExit((code) => recordExit(proc, code)); } @@ -379,7 +390,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup intentionalStop = false; foreign = false; const proc = deps.spawn(deps.binary, deps.args ?? GATEWAY_ARGS); - owned = proc; + replaceOwned(proc); let output = ''; let exited = false; let exitCode: number | null = null; @@ -491,20 +502,27 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup async function stopProcess(proc: GatewayProcess): Promise { intentionalStop = true; current = 'stopping'; - proc.signal('SIGTERM'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; - } - proc.signal('SIGKILL'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; + try { + proc.signal('SIGTERM'); + if (await confirmedStopped(proc, graceMs)) { + proc.dispose?.(); + owned = null; + current = 'stopped'; + return; + } + proc.signal('SIGKILL'); + if (await confirmedStopped(proc, graceMs)) { + proc.dispose?.(); + owned = null; + current = 'stopped'; + return; + } + current = 'error'; + throw new Error('ElastOS is still running.'); + } catch (err) { + proc.dispose?.(); + throw err; } - current = 'error'; - throw new Error('ElastOS is still running.'); } const supervisor: GatewaySupervisor = { @@ -591,11 +609,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup }, forceKill() { if (!owned) return; + const failed = current === 'error'; try { owned.signal('SIGKILL'); } catch { // Quit still closes. The error from stop() is logged by the caller. } + if (failed) owned.dispose?.(); }, openHome() { deps.openUrl(HOME_URL); diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index 3f1f9e3..4865eb2 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -66,7 +66,7 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform } function changeRuntime(action: () => Promise): Promise { - if (platform !== 'darwin') return serialize(action); + if (platform !== 'darwin' && platform !== 'win32') return serialize(action); if (updating) return Promise.reject(new Error('An ElastOS update is already running.')); updating = true; requestedRunning = true; @@ -113,13 +113,20 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform if (supervisor) { const phase = observedPhase; if (phase === 'starting' || phase === 'stopping' || phase === 'error' - || (phase === 'running' && platform !== 'darwin')) { + || (phase === 'running' && platform !== 'darwin' && platform !== 'win32')) { return phase; } } if (platform === 'win32') { if (!distroIsInstalled()) return 'not-installed'; - if (isHealthOk(await readHealth())) return 'running'; + if (isHealthOk(await readHealth())) { + // A live controller keeps Home up after the child pid changes. Health + // and the distro facts are the status, not the supervisor's old phase. + if (!(await confirmInstalledGateway())) { + throw new Error('Another program is answering on port 8090. Home was not adopted.'); + } + return 'running'; + } return 'stopped'; } if (runtimeInstallBlock(platform, arch)) return 'not-installed'; diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 57fb50f..311d9df 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -1,4 +1,4 @@ -import { spawn, spawnSync } from 'child_process'; +import { ChildProcess, spawn, spawnSync } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -13,7 +13,6 @@ import { WINDOWS_NATIVE_MESSAGE } from './runtimeSupport'; import { createGatewaySupervisor, emitRuntimeLog, - GATEWAY_ARGS, GatewayProcess, InstalledGatewayKind, installedGatewayKind, @@ -38,9 +37,10 @@ export const DISTRO_INSTALL_DIR = 'C:\\ElastOS\\distro'; export const DISTRO_IMPORT_FAILED = 'ElastOS could not add its Linux environment. Click Install to try again.'; export const DISTRO_SETUP_FAILED = 'ElastOS could not finish setting up its Linux environment. Click Install to try again.'; export const DISTRO_INSTALL_FAILED = 'ElastOS could not be installed. Click Install to try again.'; +export const HOME_UNCONFIRMED_MESSAGE = 'Home could not be confirmed'; const FILE_HELPER = ` -import base64, sys, pathlib +import base64, os, stat, sys, pathlib op, raw = sys.argv[1], sys.argv[2] root = pathlib.PurePosixPath('/root') target = pathlib.PurePosixPath(raw) @@ -54,23 +54,322 @@ elif op == 'write': path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) elif op == 'read': - sys.stdout.write(base64.b64encode(path.read_bytes()).decode('ascii')) + limit = int(sys.argv[3]) if len(sys.argv) > 3 else None + if limit is not None: + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > limit: + raise SystemExit(2) + fd = os.open(raw, os.O_RDONLY | os.O_NOFOLLOW) + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + raise SystemExit(2) + else: + data = path.read_bytes() + sys.stdout.write(base64.b64encode(data).decode('ascii')) elif op == 'exists': raise SystemExit(0 if path.is_file() else 1) else: raise SystemExit(2) `.trim(); -const STOP_HELPER = ` -import os, signal, sys -name = sys.argv[1] -raw = sys.argv[2] -if type(raw) is not str or not raw.isdigit(): - raise SystemExit(1) -pid = int(raw) -if type(pid) is not int or pid <= 1: +export const STOP_HELPER = ` +import errno, json, os, signal, stat, sys, time +MESSAGE = 'Home could not be confirmed' +RECORD_MAX = 16384 +STAT_MAX = 4096 +LINK_MAX = 4096 +BOOT_MAX = 128 +CMD_MAX = 64 +DATA = '/root/.local/share/elastos' +LOCK = DATA + '/host-process.lock' +STATUS = DATA + '/update-controller/status.json' +RUNTIME = DATA + '/update-controller/runtime' +BINARY = '/root/.local/bin/elastos' + +def located(root, suffix): + if root == '/': + return suffix + return root.rstrip('/') + suffix + +def publish(channel, seq, text): + final = os.path.join(channel, 'reply-%d' % seq) + tmp = final + '.tmp' + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + try: + os.write(fd, (text + '\\n').encode('utf-8')) + finally: + os.close(fd) + os.replace(tmp, final) + +def refuse(channel): + try: + publish(channel, 0, MESSAGE) + except Exception: + pass raise SystemExit(1) -os.kill(-pid, signal.SIGKILL if name == 'KILL' else signal.SIGTERM) + +def walk(path): + current = '' + parts = path.strip('/').split('/') + if not parts or parts == ['']: + return None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return False + if index == len(parts) - 1: + return info + return None + +def read_file(path, limit): + info = walk(path) + if info is None or info is False: + return info + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + return False + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return False + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + return False + return data + +def load_json(data): + if data is None or data is False: + return data + try: + parsed = json.loads(data.decode('utf-8')) + except Exception: + return False + if type(parsed) is not dict: + return False + return parsed + +def positive(value): + if type(value) is not int or value <= 1: + return None + return value + +def token(value, limit): + if type(value) is not str or value == '' or len(value) > limit: + return None + if '\\r' in value or '\\n' in value: + return None + return value + +def prove(root): + lock = load_json(read_file(located(root, LOCK), RECORD_MAX)) + status = load_json(read_file(located(root, STATUS), RECORD_MAX)) + if lock is None or lock is False or status is None or status is False: + return None + if lock.get('role') != 'gateway' or lock.get('addr') != 'localhost:8090': + return None + generation = token(lock.get('generation'), 128) + if generation is None or generation != token(status.get('generation'), 128): + return None + start = token(status.get('controller_start'), 200) + host = positive(lock.get('pid')) + if start is None or host is None or positive(status.get('host_pid')) != host: + return None + controller = positive(status.get('controller_pid')) + if controller is None or controller == host: + return None + return controller, start + +def start_ticks(text, pid): + space = text.find(' ') + if space <= 0 or text[:space] != str(pid): + return None + end = text.rfind(')') + if end < 0: + return None + parts = text[end + 1:].split() + if len(parts) <= 19 or not parts[19].isdigit(): + return None + return parts[19] + +def load_boot(root): + data = read_file(located(root, '/proc/sys/kernel/random/boot_id'), BOOT_MAX) + if data is None: + return True, None + if data is False: + return False, None + boot = data.decode('utf-8', 'replace').strip() + if boot == '' or any(ch.isspace() for ch in boot): + return False, None + return True, boot + +def process_identity(text, boot, pid): + ticks = start_ticks(text, pid) + if ticks is None: + return None + if boot is None: + return 'linux:' + ticks + return 'linux:' + boot + ':' + ticks + +def allowed_exes(root): + found = [] + for suffix in (RUNTIME, BINARY): + path = located(root, suffix) + info = walk(path) + if info is None or info is False or not stat.S_ISREG(info.st_mode): + continue + real = os.path.realpath(path) + if real not in found: + found.append(real) + return found + +def controller_exe(root, pid): + path = located(root, '/proc/%d/exe' % pid) + parent = path.rsplit('/', 1)[0] + info = walk(parent) + if info is None or info is False or not stat.S_ISDIR(info.st_mode): + return None + try: + leaf = os.lstat(path) + except OSError: + return None + if not stat.S_ISLNK(leaf.st_mode): + return None + try: + link = os.readlink(path) + except OSError: + return None + if len(link) > LINK_MAX or not link.startswith('/') or link.endswith(' (deleted)'): + return None + if '\\n' in link or '\\r' in link or '\\x00' in link: + return None + return os.path.realpath(link) + +def identity_matches(root, pid, start): + data = read_file(located(root, '/proc/%d/stat' % pid), STAT_MAX) + if data is None or data is False: + return False + ok, boot = load_boot(root) + if not ok: + return False + if process_identity(data.decode('utf-8', 'replace'), boot, pid) != start: + return False + exe = controller_exe(root, pid) + if exe is None: + return False + return exe in allowed_exes(root) + +def channel_open(channel): + try: + info = os.lstat(channel) + except OSError: + return False + return (not stat.S_ISLNK(info.st_mode)) and stat.S_ISDIR(info.st_mode) + +def read_cmd(channel, seq): + path = os.path.join(channel, 'cmd-%d' % seq) + while channel_open(channel): + try: + info = os.lstat(path) + except OSError: + time.sleep(0.02) + continue + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > CMD_MAX: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, CMD_MAX + 1) + finally: + os.close(fd) + if len(data) > CMD_MAX: + return None + if not data.endswith(b'\\n'): + time.sleep(0.02) + continue + return data.decode('utf-8', 'replace').strip() + return None + +def serve(root, channel): + proved = prove(root) + if proved is None: + refuse(channel) + pid, start = proved + opener = getattr(os, 'pidfd_open', None) + sender = getattr(signal, 'pidfd_send_signal', None) + if opener is None or sender is None: + refuse(channel) + try: + pidfd = opener(pid, 0) + except OSError: + refuse(channel) + try: + if not identity_matches(root, pid, start): + refuse(channel) + publish(channel, 0, 'ready') + seq = 1 + while True: + command = read_cmd(channel, seq) + if command is None: + return + if command == 'close': + publish(channel, seq, 'closed') + return + if command == 'TERM': + sig = signal.SIGTERM + elif command == 'KILL': + sig = signal.SIGKILL + else: + publish(channel, seq, MESSAGE) + seq += 1 + continue + try: + sender(pidfd, sig, None, 0) + except OSError as err: + code = errno.errorcode.get(err.errno, '') + if code == 'ESRCH': + publish(channel, seq, 'errno ESRCH') + else: + publish(channel, seq, MESSAGE) + seq += 1 + continue + publish(channel, seq, 'sent') + seq += 1 + finally: + try: + os.close(pidfd) + except OSError: + pass + +def main(): + root = sys.argv[1] if len(sys.argv) > 1 else '/' + channel = sys.argv[2] if len(sys.argv) > 2 else '' + if not root.startswith('/') or not channel.startswith('/'): + raise SystemExit(1) + try: + info = os.lstat(channel) + except OSError: + raise SystemExit(1) + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise SystemExit(1) + try: + serve(root, channel) + except SystemExit: + raise + except Exception: + refuse(channel) + +main() `.trim(); const LOCK_PID_HELPER = ` @@ -98,43 +397,95 @@ except OSError: raise SystemExit(0) `.trim(); -const FACTS_HELPER = ` -import json, os -lock_path = '/root/.local/share/elastos/host-process.lock' +export const FACTS_HELPER = ` +import json, os, stat, sys +RECORD_MAX = 16384 +PROC_MAX = 8 * 1024 * 1024 +FD_MAX = 1024 +LINK_MAX = 4096 +root = sys.argv[1] if len(sys.argv) > 1 else '' +if root and not root.startswith('/'): + raise SystemExit(1) + +def under(suffix): + if root == '' or root == '/': + return suffix + return root.rstrip('/') + suffix + +def walk(path): + current = '' + parts = path.strip('/').split('/') + if not parts or parts == ['']: + return None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return False + if index == len(parts) - 1: + return info + return None + +def read_capped(path, limit): + info = walk(path) + if info is None or info is False: + return None + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + return None + return data + +lock_path = under('/root/.local/share/elastos/host-process.lock') out = {'lock': None, 'command': None, 'tcp': '', 'tcp6': '', 'links': [], 'alive': False} -try: - out['lock'] = open(lock_path).read() -except Exception: - pass +lock_data = read_capped(lock_path, RECORD_MAX) +if lock_data is not None: + out['lock'] = lock_data.decode('utf-8', 'replace') pid = 0 try: pid = json.loads(out['lock'] or '{}').get('pid') or 0 except Exception: pid = 0 if type(pid) is int and pid > 1: - out['alive'] = os.path.exists(f'/proc/{pid}') + proc = under('/proc/%d' % pid) try: - out['command'] = open(f'/proc/{pid}/cmdline', 'rb').read().replace(bytes([0]), b' ').decode() - except Exception: - out['command'] = None - try: - out['tcp'] = open('/proc/net/tcp').read() - except Exception: - out['tcp'] = '' - try: - out['tcp6'] = open('/proc/net/tcp6').read() - except Exception: - out['tcp6'] = '' + info = os.lstat(proc) + out['alive'] = (not stat.S_ISLNK(info.st_mode)) and stat.S_ISDIR(info.st_mode) + except OSError: + out['alive'] = False + command = read_capped(proc + '/cmdline', RECORD_MAX) + if command is not None: + out['command'] = command.replace(bytes([0]), b' ').decode('utf-8', 'replace') + tcp = read_capped(proc + '/net/tcp', PROC_MAX) + out['tcp'] = '' if tcp is None else tcp.decode('utf-8', 'replace') + tcp6 = read_capped(proc + '/net/tcp6', PROC_MAX) + out['tcp6'] = '' if tcp6 is None else tcp6.decode('utf-8', 'replace') links = [] - fd = f'/proc/{pid}/fd' + fd_dir = proc + '/fd' try: - for name in os.listdir(fd): + info = os.lstat(fd_dir) + names = [] if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode) else os.listdir(fd_dir) + except OSError: + names = [] + if len(names) <= FD_MAX: + for name in names: try: - links.append(os.readlink(f'{fd}/{name}')) - except Exception: - pass - except Exception: - links = [] + link = os.readlink(fd_dir + '/' + name) + except OSError: + continue + if len(link) <= LINK_MAX: + links.append(link) out['links'] = links print(json.dumps(out)) `.trim(); @@ -185,10 +536,220 @@ export function distroInstallerArgs( ]; } +/** Runtime 2.0.0 enters the update controller only through this command. */ export function distroGatewayArgs(): string[] { - return [...wslCommandPrefix(), '/root/.local/bin/elastos', ...GATEWAY_ARGS]; + return [...wslCommandPrefix(), '/root/.local/bin/elastos', 'home', '--browser']; +} + +/** + * The controller binary the host lock's parent must be running. + * `queue_update` accepts a request only while that process is the live controller. + */ +export const DISTRO_CONTROLLER_COMMAND = + `${runtimeDataDir('linux', DISTRO_HOME, {})}/update-controller/runtime __update-controller`; + +/** Home's controller can take the runtime's full ready budget (120s) plus margin. Mac uses the same budget. */ +export const DISTRO_HOME_READY_MS = 150_000; + +export function distroHomeSpawnOptions(env: NodeJS.ProcessEnv = wslSpawnEnv()): { + detached: true; + windowsHide: true; + stdio: ['ignore', 'pipe', 'pipe']; + env: NodeJS.ProcessEnv; +} { + return { + detached: true, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + env, + }; +} + +export interface DistroProcFact { + ppid: number | null; + command: string | null; +} + +/** Stop does not signal a pid from this report. */ +export interface DistroStopReport { + lockText: string; + statusText: string | null; + procs: Readonly>; +} + +/** Stop does not signal this value. */ +export function distroStopPid(report: DistroStopReport): number | null { + let lock: { pid?: unknown; generation?: unknown }; + try { + lock = JSON.parse(report.lockText) as { pid?: unknown; generation?: unknown }; + } catch { + return null; + } + const host = lock.pid; + if (typeof host !== 'number' || !Number.isInteger(host) || host <= 1) return null; + if (!report.statusText) return null; + let status: { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + try { + status = JSON.parse(report.statusText) as { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + } catch { + return null; + } + const controller = status.controller_pid; + const proved = status.host_pid === host + && typeof status.generation === 'string' + && status.generation.length > 0 + && status.generation === lock.generation + && typeof controller === 'number' + && Number.isInteger(controller) + && controller > 1 + && controller !== host; + if (!proved) return null; + const controllerFact = report.procs[String(controller)]; + const hostFact = report.procs[String(host)]; + if (!controllerFact || !hostFact) return null; + if (hostFact.ppid !== controller) return null; + if (!controllerFact.command || !controllerFact.command.includes(DISTRO_CONTROLLER_COMMAND)) return null; + return controller; +} + +export function parseDistroStopReport(raw: string): DistroStopReport | null { + let parsed: { lock?: unknown; status?: unknown; procs?: unknown }; + try { + parsed = JSON.parse(raw) as { lock?: unknown; status?: unknown; procs?: unknown }; + } catch { + return null; + } + if (typeof parsed.lock !== 'string') return null; + if (parsed.status !== null && typeof parsed.status !== 'string') return null; + if (!parsed.procs || typeof parsed.procs !== 'object') return null; + const procs: Record = {}; + for (const [key, value] of Object.entries(parsed.procs as Record)) { + if (!/^[1-9]\d*$/.test(key) || !value || typeof value !== 'object') return null; + const fact = value as { ppid?: unknown; command?: unknown }; + if (fact.ppid !== null && (typeof fact.ppid !== 'number' || !Number.isInteger(fact.ppid) || fact.ppid <= 0)) return null; + if (fact.command !== null && typeof fact.command !== 'string') return null; + procs[key] = { + ppid: typeof fact.ppid === 'number' ? fact.ppid : null, + command: typeof fact.command === 'string' ? fact.command : null, + }; + } + return { + lockText: parsed.lock, + statusText: parsed.status, + procs, + }; +} + +export const DISTRO_STOP_READER = ` +import json, os, stat +LIMIT = 16384 +ROOT = '/root/.local/share/elastos' +LOCK = ROOT + '/host-process.lock' +STATUS = ROOT + '/update-controller/status.json' + +def read_text(path, required): + current = '' + parts = path.strip('/').split('/') + info = None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except FileNotFoundError: + if required: + raise SystemExit(1) + return None + if stat.S_ISLNK(info.st_mode): + raise SystemExit(2) + if index == len(parts) - 1: + if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + raise SystemExit(2) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + try: + data = os.read(fd, LIMIT + 1) + finally: + os.close(fd) + if len(data) > LIMIT: + raise SystemExit(2) + return data.decode('utf-8', 'replace') + +def read_proc(path): + try: + info = os.lstat(path) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, LIMIT + 1) + finally: + os.close(fd) + if len(data) > LIMIT: + return None + return data + +def pid_of(text, key): + try: + value = json.loads(text).get(key) + except Exception: + return None + if type(value) is int and value > 1: + return value + return None + +def proc_fact(pid): + base = '/proc/' + str(pid) + try: + info = os.lstat(base) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + return None + status = read_proc(base + '/status') + cmd = read_proc(base + '/cmdline') + ppid = None + if status: + for line in status.decode('utf-8', 'replace').split('\\n'): + if line.startswith('PPid:'): + raw = line[5:].strip() + if raw.isdigit(): + ppid = int(raw) + command = None + if cmd is not None: + command = cmd.replace(b'\\x00', b' ').decode('utf-8', 'replace').strip() + return {'ppid': ppid, 'command': command} + +lock = read_text(LOCK, True) +status = read_text(STATUS, False) +procs = {} +for key, text in (('pid', lock), ('host_pid', status), ('controller_pid', status)): + if not text: + continue + pid = pid_of(text, key) + if pid and str(pid) not in procs: + fact = proc_fact(pid) + if fact: + procs[str(pid)] = fact +print(json.dumps({'lock': lock, 'status': status, 'procs': procs})) +`.trim(); + +export function readDistroStopReport( + run: (args: readonly string[]) => { code: number; stdout: string } = (args) => runWslSync(args, undefined, 8000), +): DistroStopReport | null { + try { + const result = run(['python3', '-c', DISTRO_STOP_READER]); + if (result.code !== 0) return null; + return parseDistroStopReport(result.stdout); + } catch { + return null; + } } + export function distroToolCheckArgs(): readonly string[] { return ['bash', '-lc', 'command -v python3 >/dev/null && command -v curl >/dev/null']; } @@ -201,20 +762,262 @@ export function runDistroRuntimeCommand(args: readonly string[]): Promise /etc/resolv.conf; apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 curl ca-certificates']; } -/** Signal this pid's group. The helper does not read the lock again. Pid 1 is refused. */ -export function distroStopArgs(signal: 'TERM' | 'KILL', pid: number): string[] { - if (!Number.isInteger(pid) || pid <= 1) { - throw new Error('Refusing to signal that process.'); +export function distroStopArgs(root = '/', channel?: string): string[] { + const args = ['python3', '-c', STOP_HELPER, root]; + if (channel) args.push(channel); + return args; +} + +export const WSL_OUTPUT_MAX = 20 * 1024 * 1024; + +export function appendCappedOutput( + chunks: Buffer[], + total: number, + chunk: Buffer, + max = WSL_OUTPUT_MAX, +): number { + if (total >= max || chunk.length === 0) return total; + const room = max - total; + const slice = chunk.length > room ? chunk.subarray(0, room) : chunk; + chunks.push(Buffer.from(slice)); + return total + slice.length; +} + +const STOP_REPLY_MS = 8000; + +export interface DistroStopSession { + signal(name: 'TERM' | 'KILL'): void; + close(): void; + dispose(): void; +} + +function helperGone(pid: number): boolean { + try { + process.kill(pid, 0); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + return code === 'ESRCH'; + } + if (process.platform === 'win32') return false; + const result = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8', timeout: 1000 }); + const state = (result.stdout || '').trim(); + return state === '' || state.startsWith('Z'); +} + +function distroVisiblePath(file: string): string { + const normalized = file.replace(/\\/g, '/'); + const drive = /^([A-Za-z]):\/(.*)$/.exec(normalized); + if (!drive) return normalized; + return `/mnt/${drive[1].toLowerCase()}/${drive[2]}`; +} + +interface CreatedDir { + path: string; + dev: number; + ino: number; +} + +function stopChannelRoot(): string { + return path.resolve(os.tmpdir()); +} + +function createStopChannel(): CreatedDir { + const dir = fs.mkdtempSync(path.join(stopChannelRoot(), 'elastos-stop-')); + fs.chmodSync(dir, 0o700); + const info = fs.lstatSync(dir); + if (info.isSymbolicLink() || !info.isDirectory()) throw new Error(HOME_UNCONFIRMED_MESSAGE); + return { path: dir, dev: info.dev, ino: info.ino }; +} + +function parentsStayReal(dir: string, root: string): boolean { + let current = path.resolve(dir); + const stop = path.resolve(root); + if (current !== stop && !current.startsWith(`${stop}${path.sep}`)) return false; + while (current !== stop) { + let info: fs.Stats; + try { + info = fs.lstatSync(current); + } catch { + return false; + } + if (info.isSymbolicLink() || !info.isDirectory()) return false; + const parent = path.dirname(current); + if (parent === current) return false; + current = parent; + } + try { + const rootInfo = fs.lstatSync(stop); + return !rootInfo.isSymbolicLink() && rootInfo.isDirectory(); + } catch { + return false; + } +} + +function removeStopChannel(dir: CreatedDir): void { + let info: fs.Stats; + try { + info = fs.lstatSync(dir.path); + } catch { + return; + } + if (info.isSymbolicLink() || !info.isDirectory()) return; + if (info.dev !== dir.dev || info.ino !== dir.ino) return; + if (!parentsStayReal(dir.path, stopChannelRoot())) return; + fs.rmSync(dir.path, { recursive: true, force: true }); +} + +function assertStopChannel(dir: CreatedDir): void { + const info = fs.lstatSync(dir.path); + if (info.isSymbolicLink() || !info.isDirectory() || info.dev !== dir.dev || info.ino !== dir.ino) { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } +} + +function readStopReply(dir: CreatedDir, seq: number, childPid: number, timeoutMs: number): string { + assertStopChannel(dir); + const file = path.join(dir.path, `reply-${seq}`); + const deadline = Date.now() + timeoutMs; + const pause = new Int32Array(new SharedArrayBuffer(4)); + while (Date.now() < deadline) { + try { + const text = fs.readFileSync(file, 'utf8'); + if (text.includes('\n') || text.includes('\r')) return text.split(/\r?\n/, 1)[0].trim(); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ENOENT') throw err; + } + if (helperGone(childPid)) throw new Error(HOME_UNCONFIRMED_MESSAGE); + Atomics.wait(pause, 0, 0, 20); + } + throw new Error(HOME_UNCONFIRMED_MESSAGE); +} + +function writeStopCommand(dir: CreatedDir, seq: number, command: string): void { + assertStopChannel(dir); + const finalPath = path.join(dir.path, `cmd-${seq}`); + const tmp = `${finalPath}.tmp`; + fs.writeFileSync(tmp, `${command}\n`, { mode: 0o600 }); + fs.renameSync(tmp, finalPath); +} + +function defaultStopSpawn(args: readonly string[]): ChildProcess { + return spawn('wsl.exe', [...wslCommandPrefix(), ...args], { + windowsHide: true, + env: wslSpawnEnv(), + stdio: 'ignore', + }); +} + +export function createDistroStopSession(deps: { + root?: string; + spawn?: (args: readonly string[]) => ChildProcess; +} = {}): DistroStopSession { + const root = deps.root ?? '/'; + const launch = deps.spawn ?? defaultStopSpawn; + let dir: CreatedDir | null = null; + let child: ChildProcess | null = null; + let ready = false; + let seq = 0; + let closed = false; + let holding = false; + + function stopChild(): void { + if (!child?.pid || helperGone(child.pid)) return; + try { + child.kill('SIGKILL'); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ESRCH') throw err; + } } - return ['python3', '-c', STOP_HELPER, signal, String(pid)]; + + function finish(): void { + if (closed) return; + holding = true; + closed = true; + let closeError: unknown = null; + if (ready && dir && child?.pid && !helperGone(child.pid)) { + try { + seq += 1; + writeStopCommand(dir, seq, 'close'); + readStopReply(dir, seq, child.pid, STOP_REPLY_MS); + } catch (err) { + closeError = err; + } + } + const helperExited = child?.pid != null && helperGone(child.pid); + stopChild(); + if (dir) removeStopChannel(dir); + holding = false; + if (closeError && !helperExited) throw closeError; + } + + return { + signal(name) { + if (closed || (name !== 'TERM' && name !== 'KILL')) throw new Error(HOME_UNCONFIRMED_MESSAGE); + holding = true; + try { + if (!ready) { + dir = createStopChannel(); + const channel = dir.path; + child = launch(distroStopArgs(root, distroVisiblePath(channel))); + child.on('error', () => {}); + child.on('exit', () => { + if (holding) return; + closed = true; + if (dir) removeStopChannel(dir); + }); + child.unref(); + if (!child.pid) { + finish(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + const opened = readStopReply(dir, 0, child.pid, STOP_REPLY_MS); + if (opened !== 'ready') { + finish(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + ready = true; + } + if (!dir || !child?.pid) throw new Error(HOME_UNCONFIRMED_MESSAGE); + seq += 1; + writeStopCommand(dir, seq, name); + const reply = readStopReply(dir, seq, child.pid, STOP_REPLY_MS); + if (reply === 'sent' || reply === 'errno ESRCH') return; + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } finally { + if (!closed) holding = false; + } + }, + close() { finish(); }, + dispose() { + try { + finish(); + } catch { + // finish() already dropped the helper. Stop still reports its own error. + } + }, + }; } function plainSpawnError(err: unknown, fallback: string): Error { @@ -250,6 +1053,8 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro }); const stdout: Buffer[] = []; const stderr: Buffer[] = []; + let stdoutTotal = 0; + let stderrTotal = 0; const timer = setTimeout(() => { child.kill(); reject(new Error(DISTRO_SETUP_FAILED)); @@ -258,8 +1063,12 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro clearTimeout(timer); reject(plainSpawnError(err, DISTRO_SETUP_FAILED)); }); - child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk)); - child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk)); + child.stdout.on('data', (chunk: Buffer) => { + stdoutTotal = appendCappedOutput(stdout, stdoutTotal, chunk); + }); + child.stderr.on('data', (chunk: Buffer) => { + stderrTotal = appendCappedOutput(stderr, stderrTotal, chunk); + }); child.on('exit', (code) => { clearTimeout(timer); resolve({ @@ -273,12 +1082,14 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro }); } -function fileArgs(op: string, file: string): string[] { - return ['python3', '-c', FILE_HELPER, op, assertDistroPath(file)]; +function fileArgs(op: string, file: string, limit?: number): string[] { + const args = ['python3', '-c', FILE_HELPER, op, assertDistroPath(file)]; + if (limit !== undefined) args.push(String(limit)); + return args; } -function readDistroFile(file: string): string { - const result = runWslSync(fileArgs('read', file)); +function readDistroFile(file: string, limit?: number): string { + const result = runWslSync(fileArgs('read', file, limit)); if (result.code !== 0) { throw new Error('ElastOS could not read a file in its Linux environment. Click Install to try again.'); } @@ -315,24 +1126,22 @@ export async function ensureElastosDistro(deps: { lookup: async () => true, listDistros: deps.listDistros, }); + const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); if (!facts.distroReady) { const rootfs = await deps.ensureRootfs(); deps.onProgress('Rootfs SHA-256 matches the pin'); (deps.prepareImportDir ?? prepareImportDir)(DISTRO_INSTALL_DIR); const code = await deps.importDistro(DISTRO_INSTALL_DIR, rootfs); if (code !== 0) throw new Error(DISTRO_IMPORT_FAILED); - // The first command can block while the rootfs finishes its first boot. - // The tool check's 20 seconds is too short for that. deps.onProgress('Starting the Linux environment for the first time'); - const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); - let booted: WslResult; - try { - booted = await run(['true'], DISTRO_FIRST_BOOT_MS); - } catch { - throw new Error(DISTRO_SETUP_FAILED); - } - if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); } + let booted: WslResult; + try { + booted = await run(['true'], DISTRO_FIRST_BOOT_MS); + } catch { + throw new Error(DISTRO_SETUP_FAILED); + } + if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); if (!(await deps.hasTools())) { const code = await deps.installTools(); if (code !== 0) throw new Error(DISTRO_SETUP_FAILED); @@ -416,11 +1225,21 @@ function distroInstallDeps(): RuntimeInstallDeps { export async function installRuntimeInsideDistro( onProgress: (message: string) => void = () => {}, + host: { + lookupWsl?: () => Promise; + listDistros?: () => Promise; + ensureRootfs?: () => Promise; + importDistro?: (installDir: string, rootfs: string) => Promise; + prepareImportDir?: (dir: string) => void; + runInDistro?: (args: readonly string[], timeoutMs: number) => Promise; + continueInstall?: (onProgress: (message: string) => void) => Promise; + } = {}, ): Promise { + const run = host.runInDistro ?? ((args: readonly string[], timeoutMs: number) => runWsl(args, timeoutMs)); await ensureElastosDistro({ - lookupWsl: () => lookupCommand('wsl.exe'), - listDistros, - ensureRootfs: () => ensureElastosRootfs({ + lookupWsl: host.lookupWsl ?? (() => lookupCommand('wsl.exe')), + listDistros: host.listDistros ?? listDistros, + ensureRootfs: host.ensureRootfs ?? (() => ensureElastosRootfs({ dest: path.join(os.homedir(), '.elastos-launcher', 'ubuntu-noble-wsl.rootfs.tar.gz'), exists: (file) => { try { return fs.statSync(file).isFile(); } catch { return false; } @@ -428,12 +1247,18 @@ export async function installRuntimeInsideDistro( download: downloadPinnedRootfs, read: (file) => fs.readFileSync(file), accept: assertPinnedRootfs, - }), - importDistro: (installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000), - hasTools: async () => (await runWsl(distroToolCheckArgs(), 20000)).code === 0, - installTools: async () => (await runWsl(distroPackageArgs(), 10 * 60 * 1000)).code, + })), + importDistro: host.importDistro ?? ((installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000)), + prepareImportDir: host.prepareImportDir, + runInDistro: run, + hasTools: async () => (await run(distroToolCheckArgs(), 20000)).code === 0, + installTools: async () => (await run(distroPackageArgs(), 10 * 60 * 1000)).code, onProgress, }); + if (host.continueInstall) { + await host.continueInstall(onProgress); + return; + } await installRuntime(distroInstallDeps(), onProgress); } @@ -459,53 +1284,47 @@ function runHost(args: readonly string[], timeoutMs: number): Promise { }); } -/** Signal the gateway recorded in the distro host lock. Never uses pid 0 or 1. */ export function signalDistroLock( signal: NodeJS.Signals, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void, ): void { - const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; - stopInside(name); + stopInside(signal === 'SIGKILL' ? 'KILL' : 'TERM'); } export function signalDistroGateway( wslPid: number, signal: NodeJS.Signals, kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void = () => { throw new Error(HOME_UNCONFIRMED_MESSAGE); }, ): void { + let stopError: unknown = null; try { signalDistroLock(signal, stopInside); - } catch { - // The lock may already be gone. - } - if (!Number.isInteger(wslPid) || wslPid <= 0) return; - try { - kill(wslPid, signal); } catch (err) { - const code = err && typeof err === 'object' && 'code' in err - ? String((err as { code?: string }).code) - : ''; - if (code === 'ESRCH') return; - const message = err instanceof Error ? err.message : String(err); - throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + stopError = err; + } + if (signal === 'SIGKILL' && Number.isInteger(wslPid) && wslPid > 0) { + try { + kill(wslPid, signal); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ESRCH' && !stopError) { + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } + } + } + if (stopError) { + if (stopError instanceof Error) throw stopError; + throw new Error(HOME_UNCONFIRMED_MESSAGE); } } export function spawnDistroGatewayProcess(): GatewayProcess { - const child = spawn('wsl.exe', distroGatewayArgs(), { - windowsHide: true, - env: wslSpawnEnv(), - stdio: ['ignore', 'pipe', 'pipe'], - }); + const child = spawn('wsl.exe', distroGatewayArgs(), distroHomeSpawnOptions()); + const session = createDistroStopSession(); const outputListeners: Array<(chunk: string) => void> = []; const exitListeners: Array<(code: number | null) => void> = []; let exited = false; @@ -524,13 +1343,23 @@ export function spawnDistroGatewayProcess(): GatewayProcess { onOutput(listener) { outputListeners.push(listener); }, onExit(listener) { exitListeners.push(listener); }, hasExited() { return exited; }, - signal(signal) { signalDistroGateway(child.pid ?? -1, signal); }, + signal(signal) { + try { + signalDistroGateway(child.pid ?? -1, signal, process.kill, (name) => session.signal(name)); + } finally { + if (signal === 'SIGKILL') session.close(); + } + }, + dispose() { + session.dispose(); + }, }; } export function createDistroGatewaySupervisor() { return createGatewaySupervisor({ binary: '/root/.local/bin/elastos', + args: ['home', '--browser'], spawn: () => spawnDistroGatewayProcess(), // Windows forwards localhost to the distro. Probe each address Windows // resolves localhost to, the same way the Windows browser can connect. @@ -539,6 +1368,8 @@ export function createDistroGatewaySupervisor() { now: () => Date.now(), openUrl: openRuntimeHome, log: emitRuntimeLog, + adoptForControls: true, + healthTimeoutMs: DISTRO_HOME_READY_MS, confirmForeign: confirmDistroGateway, foreignIsLegacy: async () => (await distroListenerKind()) === 'legacy', // The Windows side of the forward has no pid this launcher can check. @@ -634,45 +1465,55 @@ export async function distroListenerKind( } /** - * Adopt the installed distro gateway. The signal goes to the pid read from - * the lock, not to whatever the lock says later. hasExited asks the distro - * whether that pid is still there and treats an error as still running. - * A missing pid is not adopted, and pid 0 is never signaled. + * Adopt the installed distro Home. Stop signals only the confirmed controller. + * hasExited asks whether the lock pid is still there and treats an error as + * still running. A missing pid is not adopted. */ export function adoptDistroGatewayProcess(deps: { readPid?: () => number | null; alive?: (pid: number) => boolean | Promise; - signal?: (pid: number, signal: NodeJS.Signals) => void; - runStop?: (args: readonly string[]) => void; + stop?: (name: 'TERM' | 'KILL') => void; + root?: string; + spawn?: (args: readonly string[]) => ChildProcess; } = {}): GatewayProcess | null { const readPid = deps.readPid ?? (() => readDistroLockPid()); const alive = deps.alive ?? ((pid: number) => distroPidAlive(pid)); - const signalInside = deps.signal ?? ((pid: number, signal: NodeJS.Signals) => { - if (!Number.isInteger(pid) || pid <= 1) return; - const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; - const run = deps.runStop ?? ((args: readonly string[]) => { - runWslSync(args, undefined, 5000); - }); - run(distroStopArgs(name, pid)); + let session: DistroStopSession | null = null; + const stop = deps.stop ?? ((name: 'TERM' | 'KILL') => { + if (!session) session = createDistroStopSession({ root: deps.root, spawn: deps.spawn }); + session.signal(name); }); const pid = readPid(); if (pid == null || pid <= 1) return null; + const gone = (): boolean | Promise => { + try { + const result = alive(pid); + if (result && typeof (result as Promise).then === 'function') { + return (result as Promise).then((still) => still === false).catch(() => false); + } + return result === false; + } catch { + return false; + } + }; return { pid, onOutput() {}, onExit() {}, hasExited() { + return gone(); + }, + signal(signal) { + const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; try { - const result = alive(pid); - if (result && typeof (result as Promise).then === 'function') { - return (result as Promise).then((still) => still === false).catch(() => false); - } - return result === false; - } catch { - return false; + stop(name); + } finally { + if (name === 'KILL') session?.close(); } }, - signal(signal) { signalInside(pid, signal); }, + dispose() { + session?.dispose(); + }, }; } @@ -689,7 +1530,9 @@ export async function adoptInstalledDistroGateway(deps: { adopt?: (pid: number) => GatewayProcess | null; } = {}): Promise { const identify = deps.identify ?? (() => distroListenerIdentity()); - const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ readPid: () => pid })); + const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ + readPid: () => pid, + })); let seen: DistroListenerIdentity; try { seen = await identify(); diff --git a/src/preload/index.ts b/src/preload/index.ts index ac01288..01f58b6 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -97,6 +97,7 @@ declare global { status: RuntimeStatus; platformNote: string | null; browserNote: string | null; + runtimeOpensBrowser: boolean; uninstallRemovesLinux: boolean; preflight: { ok: boolean; checks: Array<{ id: string; level: string; message: string }> }; openAtLogin: boolean; diff --git a/src/renderer/app.js b/src/renderer/app.js index 2ff1641..e79c687 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -218,7 +218,10 @@ async function runInstall() { renderSteps('Starting'); await window.elastos.start(); renderSteps('Your computer is ready'); - if (window.elastos.platform !== 'darwin') await window.elastos.openBrowser(); + const started = await window.elastos.getLaunchInfo(); + if (flow.shouldOpenBrowserAfterStart(started)) { + await window.elastos.openBrowser(); + } } catch (err) { showError(err && err.message ? err.message : 'Something went wrong. Try again.'); updateStatus('error'); diff --git a/src/renderer/flow.js b/src/renderer/flow.js index 6d66de9..f43d954 100644 --- a/src/renderer/flow.js +++ b/src/renderer/flow.js @@ -141,6 +141,11 @@ function legacyPc2Copy(items) { }; } +/** False when `home --browser` already opens the tab. */ +function shouldOpenBrowserAfterStart(info) { + return !(info && info.runtimeOpensBrowser === true); +} + /** The info-panel Browser line. The main process sends it on Windows only. */ function browserNoteText(info) { return info && typeof info.browserNote === 'string' ? info.browserNote : ''; @@ -167,6 +172,7 @@ const api = { formatBytes, legacyPc2Copy, browserNoteText, + shouldOpenBrowserAfterStart, urlLabel, launcherLog, }; diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index ca86d18..2621d7e 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -171,6 +171,9 @@ test('Windows shows that its Browser is not available yet, and only Windows', () assert.equal(flow.browserNoteText({ browserNote: WINDOWS_BROWSER_MESSAGE }), WINDOWS_BROWSER_MESSAGE); assert.equal(flow.browserNoteText({ browserNote: null }), ''); assert.equal(flow.browserNoteText(undefined), ''); + assert.equal(flow.shouldOpenBrowserAfterStart({ runtimeOpensBrowser: true }), false); + assert.equal(flow.shouldOpenBrowserAfterStart({ runtimeOpensBrowser: false }), true); + assert.equal(flow.shouldOpenBrowserAfterStart(undefined), true); const html = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'index.html'), 'utf8'); assert.match(html, /