diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 22d609e..00945a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -109,8 +109,12 @@ jobs: dist-electron/*.deb if-no-files-found: error + linux-arm64: + if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/linux-arm64.yml + release: - needs: build + needs: [build, linux-arm64] runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') diff --git a/.github/workflows/linux-arm64.yml b/.github/workflows/linux-arm64.yml new file mode 100644 index 0000000..d1a87d8 --- /dev/null +++ b/.github/workflows/linux-arm64.yml @@ -0,0 +1,46 @@ +name: Linux ARM64 package + +# Ubuntu 22.04 matches the Jetson glibc (2.35). +on: + pull_request: + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + package: + runs-on: ubuntu-22.04-arm + timeout-minutes: 90 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Build the arm64 AppImage and deb + run: npm run build:linux -- --arm64 --publish never + + - name: Record checksums + run: | + set -euo pipefail + sha256sum dist-electron/*.AppImage dist-electron/*.deb + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.AppImage' -print)" + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.deb' -print)" + + - name: Upload the arm64 packages + uses: actions/upload-artifact@v4 + with: + name: ElastOS-linux-arm64 + path: | + dist-electron/*.AppImage + dist-electron/*.deb + if-no-files-found: error diff --git a/.github/workflows/runtime-smoke.yml b/.github/workflows/runtime-smoke.yml index 998ef09..e1f7e1a 100644 --- a/.github/workflows/runtime-smoke.yml +++ b/.github/workflows/runtime-smoke.yml @@ -1,6 +1,5 @@ name: Runtime smoke -# Linux x64, macOS arm64, and the ElastOS WSL2 distro are required. # A red run fails the pull request. Each job verifies the selected channel # against the maintainer DID and rollback floor. Failed verification means # install stops. The job then checks gateway /healthz and @@ -21,6 +20,8 @@ jobs: platform: linux-x64 - os: macos-latest platform: darwin-arm64 + - os: ubuntu-22.04-arm + platform: linux-arm64 runs-on: ${{ matrix.os }} steps: - name: Checkout code @@ -47,15 +48,20 @@ jobs: electron-e2e: name: e2e (${{ matrix.platform }}) - timeout-minutes: 40 + timeout-minutes: 50 strategy: fail-fast: false matrix: include: - os: ubuntu-24.04 platform: linux-x64 + packages: xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1 + - os: ubuntu-22.04-arm + platform: linux-arm64 + packages: xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2 libgtk-3-0 libxss1 libayatana-appindicator3-1 - os: macos-latest platform: darwin-arm64 + packages: "" runs-on: ${{ matrix.os }} steps: - name: Checkout code @@ -75,7 +81,7 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1 + sudo apt-get install -y ${{ matrix.packages }} - name: Install dependencies env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7fd0d0..f8f126f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ A wrong signature or channel, version below the floor, changed metadata snapshot - Home is `http://localhost:8090/home/`. - Update offers require signed metadata. Runtime 2.0.0 needs a compatibility `update-check.json` record after a successful CLI check. Human-readable stdout never determines the offer. A 2.0.0 source with an unknown head uses the stored signed install record and matching binary version for rollback identity. - A foreign listener on 8090 keeps running and its specific error reaches the window. A status probe that overlaps Start, Stop, or Update must honor the newer control phase. -- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. Other platforms signal the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. +- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. On Linux, Stop and Quit signal the update controller only, and only after a fresh read of its `/proc` start time, its exe, and the host lock generation. A mismatch sends no signal. A gateway on `127.0.0.1:8090` stays running and has no Stop control. A process the launcher spawned is signaled through its own process handle. Windows signals the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. - Reset and uninstall remove only the ElastOS program, its data directory, and the launcher stage file. Other home directories stay on disk. - IPC channel names are `elastos:*`. The preload object is `window.elastos`. - `src/main/index.ts` does not import `./targets`. diff --git a/docs/RUNTIME_MIGRATION.md b/docs/RUNTIME_MIGRATION.md index 4eac512..4a2d074 100644 --- a/docs/RUNTIME_MIGRATION.md +++ b/docs/RUNTIME_MIGRATION.md @@ -68,7 +68,7 @@ Uninstall on Windows removes the whole ElastOS WSL2 Linux environment with `wsl. Remove PC2 is a separate action in `src/main/legacyPc2Removal.ts`. The button stays hidden until a legacy install is on disk: `~/.pc2`, `~/.elastos/node` when it is the old bundled Node 22.13.1 tree, a PC2 launch agent or autostart file, a sudoers file whose text matches the rules the old installer wrote (`/etc/sudoers.d/wireguard` with `wg-quick`, or `/etc/sudoers.d/amneziawg` with `NOPASSWD:SETENV`, `amneziawg-go`, and `/var/run/amneziawg/`) together with one of those installs, a `~/.pc2` folder inside another Windows Linux distro, or a Windows distro named `pc2` or `pc2-wsl` that itself contains that folder or Node tree. The old installer never wrote `/etc/sudoers.d/elastos` or `/etc/sudoers.d/pc2-wireguard`. This repo has no hash for the VPN programs it compiled, so those programs are not deleted by name. The ElastOS distro is never unregistered. The confirm dialog lists each path and its size. Removal deletes only the paths from that list. “Back up my PC2 data first” must write a backup before anything is deleted, including a Windows Linux folder or distro; if that backup cannot be saved, nothing is removed. One privileged prompt covers a matching sudoers rule. That prompt is pkexec. Cancelling it (exit 126), a missing authorization or a missing prompt (exit 127), and a missing pkexec program each have their own sentence. pkexec is not replaced with sudo. An exit after the prompt has started is the removal command's own result. The list of files still there is what that privileged script can see, including a sudoers file the app itself cannot stat. A failure says what is still there and saves a support bundle. -On Mac, Stop and Quit re-read the installed Home generation and signal its verified controller when present. The controller drains its children. Linux and Windows retain gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. +On Mac and Linux, Stop and Quit re-read the installed Home and signal its verified controller when the host lock and the update-controller status agree. Linux reads the controller start time from /proc, the controller exe, and the host lock generation immediately before every signal. A reused pid, a stale status file, a wrong exe, or a generation mismatch is left running, and the window says to stop that Home with Ctrl+C. Linux does not signal a host pid, a process group, or a descendant, and it does not adopt a gateway on 127.0.0.1:8090. That gateway is shown as another ElastOS Home with no Stop control. A process the launcher spawned is signaled through its own process handle. The controller drains its children. Windows retains gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. The support bundle redacts labeled secrets (`password`, `token`, `api_key`, `attach_secret`, `cookie`, `authorization`, `seed`, `mnemonic`, `private_key`, `secret`, bearer tokens, and JWTs), the rest of a `seed`, `mnemonic`, `private_key`, or `secret` line, a run of 12 or more BIP39 words in any case, split by spaces, line breaks, commas, hyphens, quotes, or numbering such as `1.` or `2:`, known secret prefixes (AWS access key ids, `ghp_` tokens, and `sk-` keys), hex of 32 or more characters with or without `0x`, including a 64-character hex string unless that line is labelled sha256 or hash, hex wrapped over two or more lines that holds 32 or more characters together (a list of whole 40- or 64-character hashes stays), an unlabeled uppercase token of 16 or more characters that contains a digit and no underscore, a lowercase token of 32 or more characters with high entropy, and an unlabeled mixed-case token of 20 or more characters with high entropy. It keeps paths, a 40-character hex hash on its own line or beside a hash, cid, commit, or installer label, a 64-character hex string on a sha256 or hash line, CIDv0 and CIDv1, `did:key` values, versions, UUIDs, and `UPPER_SNAKE` names. An unlabeled secret shorter than that, or with low entropy, is not redacted. `secret-line` is a short phrase that stays. @@ -95,6 +95,6 @@ Check these before the runtime on `main` is marketed as a live product and this - [ ] No phone-home telemetry. - [x] Uninstall and Reset remove only the exact runtime paths: `~/.local/bin/elastos`, `~/.local/share/elastos`, `~/Library/Application Support/elastos`, `~/.elastos-launcher/install-stage.json`, and `~/.elastos-launcher/resume-install.json`. Reset also removes `~/.elastos-launcher/resume-install.json.lock`. An XDG data directory under this home is included when it is empty or holds only the partial-install files, or when every entry is a runtime name and the signed install record verifies. A user file is refused by name even beside that record. Other folders stay on disk. - [x] Remove PC2 is separate from Reset and Uninstall. It is shown only when a legacy install is detected, lists those known paths and their sizes, and refuses runtime paths, symlink escapes, and any other path. -- A foreign listener is left running. On Mac, Start, Stop, Restart and Quit can adopt the verified installed Home. Controller shutdown drains its child processes. Other platforms retain their existing gateway supervision path. +- A foreign listener is left running. On Mac and Linux, Start, Stop, Restart and Quit can adopt the verified installed Home. Controller shutdown drains its child processes. Windows retains its gateway supervision path. - [ ] Diagnostics and the log panel do not contain `attach_secret` or the coordinate JSON files. Labeled secrets, AWS key ids, `ghp_` tokens, `sk-` keys, a run of 12 or more BIP39 words in any layout, wrapped hex, and hex that is not a 40-character hash or a 64-character hex string on a sha256 or hash line are redacted. An unlabeled short or low-entropy phrase is not. - Live rollback of historical alpha releases is no longer a CI job. Stable 2.0.0's linked predecessor is Canary 2.0.0-rc.2; Runtime correctly refuses that channel change, and there is no prior Stable release within the 2.0.0 floor to exercise. Current signed install and health checks remain in smoke. Unit tests exercise the launcher's verified rollback CID and refusal paths. A future live rollback fixture must use releases on the subscribed channel and within the install floor. diff --git a/package.json b/package.json index 9eaf03c..355ab83 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "license": "AGPL-3.0", "scripts": { "dev": "electron .", - "build:ts": "node scripts/build-mac-process-info.js && tsc", + "build:ts": "node scripts/build-mac-process-info.js && node scripts/build-linux-pidfd.js && tsc", "build": "npm run build:ts && electron-builder", "build:mac": "npm run build:ts && electron-builder --mac", "build:win": "npm run build:ts && electron-builder --win", @@ -70,7 +70,21 @@ ], "category": "Utility" }, - "asarUnpack": ["dist/native/mac-process-info"], + "deb": { + "depends": [ + "libgtk-3-0", + "libnotify4", + "libnss3", + "libxss1", + "libxtst6", + "xdg-utils", + "libatspi2.0-0", + "libuuid1", + "libsecret-1-0", + "libayatana-appindicator3-1" + ] + }, + "asarUnpack": ["dist/native/mac-process-info", "dist/native/linux-pidfd"], "afterAllArtifactBuild": "scripts/notarize.js", "extraResources": [ { diff --git a/scripts/build-linux-pidfd.js b/scripts/build-linux-pidfd.js new file mode 100644 index 0000000..95a0057 --- /dev/null +++ b/scripts/build-linux-pidfd.js @@ -0,0 +1,13 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +if (process.platform !== 'linux') process.exit(0); +const output = path.join(__dirname, '../dist/native/linux-pidfd'); +fs.mkdirSync(path.dirname(output), { recursive: true }); +const result = spawnSync('cc', [ + '-Wall', '-Wextra', '-Werror', '-O2', + path.join(__dirname, '../src/native/linux-pidfd.c'), '-o', output, +], { stdio: 'inherit', timeout: 30000 }); +if (result.error) throw result.error; +process.exit(result.status ?? 1); diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index 9136902..7692dc9 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -225,6 +225,11 @@ async function main() { executablePath: electronPath, cwd: root, args, env, timeout: 120000, }); } + if (process.platform === 'linux') { + await require('./linux-lifecycle-e2e')(electronApp, page, home, { + executablePath: electronPath, cwd: root, args, env, timeout: 120000, + }); + } return; } if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) { @@ -299,7 +304,7 @@ async function main() { } } -const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : 35 * 60 * 1000; +const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : process.platform === 'linux' ? 45 * 60 * 1000 : 35 * 60 * 1000; setTimeout(() => { console.error(`e2e did not finish within ${capMs / 60000} minutes`); process.exit(1); diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js new file mode 100644 index 0000000..942578f --- /dev/null +++ b/scripts/linux-lifecycle-e2e.js @@ -0,0 +1,159 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); + +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}`); +} + +async function liveController(data) { + const statusPath = path.join(data, 'update-controller', 'status.json'); + const deadline = Date.now() + 180000; + let last = 'absent'; + while (Date.now() < deadline) { + try { + const record = JSON.parse(fs.readFileSync(statusPath, 'utf8')); + const pid = record.controller_pid; + if (record.phase === 'ready' && Number.isInteger(pid) && pid > 0) { + const command = Buffer.alloc(4096); + const fd = fs.openSync(`/proc/${pid}/cmdline`, 'r'); + let bytes = 0; + try { + bytes = fs.readSync(fd, command, 0, command.length, 0); + } finally { + fs.closeSync(fd); + } + if (command.subarray(0, bytes).includes('__update-controller')) return record; + last = `pid ${pid} is not the update controller`; + } else { + last = `phase ${record.phase}`; + } + } catch (err) { + last = err && err.code ? err.code : 'unread'; + } + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(`Home system update check did not reach a live controller (${last})`); +} + +async function clickTray(app, id) { + const exit = new Promise((resolve) => app.process().once('exit', resolve)); + const clicked = app.evaluate((_electron, itemId) => { + const menu = global.__elastosTrayMenu; + const item = menu && menu.getMenuItemById(itemId); + if (!item || !item.enabled) return false; + item.click(); + return true; + }, id).catch(() => false); + const ok = await Promise.race([ + clicked, + exit.then(() => true), + ]); + assert.equal(ok, true, id); + await exit; +} + +function portClosed(port, host) { + const net = require('node:net'); + return new Promise((resolve) => { + const socket = net.connect({ port, host }); + const finish = (closed) => { + socket.removeAllListeners(); + socket.destroy(); + resolve(closed); + }; + socket.once('connect', () => finish(false)); + socket.once('error', () => finish(true)); + }); +} + +module.exports = async function (app, page, home, launch) { + assert.equal(await app.evaluate(() => global.__elastosTray), true); + console.log('PASS the tray icon is ready'); + + 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'); + + const data = path.join(home, '.local', 'share', 'elastos'); + const controller = await liveController(data); + assert.equal(controller.phase, 'ready'); + console.log('PASS Home system update check reaches the live controller'); + console.log('NOT EXERCISED a full System update because no newer signed release exists'); + console.log('NOT EXERCISED the owner System summary because that route needs a wallet token'); + + const checked = await page.evaluate(() => window.elastos.checkForUpdate()); + assert.equal(checked.updateAvailable, false); + const nativeUpdate = path.join(data, 'update-check.json'); + const update = JSON.parse(fs.readFileSync(fs.existsSync(nativeUpdate) ? nativeUpdate + : path.join(home, '.elastos-launcher', 'update-check.json'), 'utf8')); + assert.equal(update.outcome, 'up_to_date'); + console.log('PASS elastos update --check writes up_to_date'); + + const keptPid = controller.controller_pid; + await clickTray(app, 'quit-keep-home'); + await health(true); + assert.equal(fs.existsSync(`/proc/${keptPid}`), true); + console.log('PASS Quit and keep Home leaves the controller running'); + + const { _electron: electron } = require('playwright'); + const reopened = await electron.launch(launch); + try { + const again = await reopened.firstWindow(); + await status(again, 'running'); + assert.equal(await again.locator('#open-label').innerText(), 'Open my computer'); + console.log('PASS a reopened launcher sees the retained Home'); + await clickTray(reopened, 'quit-stop-home'); + } finally { + await reopened.close().catch(() => {}); + } + await health(false); + assert.equal(await portClosed(8090, '127.0.0.1'), true); + assert.equal(await portClosed(8090, '::1'), true); + assert.equal(fs.existsSync(`/proc/${keptPid}`), false); + console.log('PASS Quit and stop Home after reopen stops the retained Home'); +}; diff --git a/src/main/index.ts b/src/main/index.ts index 6e4d69e..230c5c0 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -3,7 +3,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import log from 'electron-log'; -import { createDefaultLaunchController, finishQuitAfterGatewayStop, TargetStatus } from './launchController'; +import { createDefaultLaunchController, finishQuitAfterGatewayStop, homeLaunchForPlatform, TargetStatus } from './launchController'; import { describeLegacyPc2OnThisComputer, removeLegacyPc2OnThisComputer, withSupportBundle } from './legacyPc2Removal'; // Chromium must never share the Runtime Home, including on case-insensitive Macs. @@ -37,6 +37,7 @@ if (process.platform === 'darwin') { let mainWindow: BrowserWindow | null = null; let tray: Tray | null = null; let isQuitting = false; +let stopHomeOnQuit = true; const quitGate = { started: false, ready: false }; let currentStatus: TargetStatus = 'stopped'; @@ -87,14 +88,12 @@ function createWindow(): void { } function createTray(): void { - // Simple tray icon const iconPath = path.join(__dirname, '../../resources/icon.png'); let icon: Electron.NativeImage; try { icon = nativeImage.createFromPath(iconPath); if (icon.isEmpty()) { - // Fallback to a simple icon icon = nativeImage.createFromDataURL( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAA7AAAAOwBeShxvQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAH5SURBVFiF7Ze/axRBFMc/M7t3yUWjhYVYiI2NjQERbfwPrGxEOwsLsRAsLPwPbGwsxMbKQrCwEWzEQrDQRhALC8FCCYiIRuNdkuzujsXu3e7l7nKXM+D3wzDM8N7MZ+a9NzOQUXAIGAN2s+0CtXBkCfgD/AJ+ArPAT2ANWBdRFXgEZuUmcAEodshrA5yECcBTcBB4BZwGfOAZ8ETESv+X+i5wEbiY9H0Z2AmMA/uTvieqGuvpxfMYOJbSrqvOIEACMpAJSAJeAF5S9gM2U2OaAYmqhcAz8BpoBc+BzuuLdEiKZrLMSj0B7JIGFQK1wBM/xhp05QfsBKoNYC8wDzzvFyQJiCeJN8DFaJHXxXJV1tQ68IaYcLrpDyLoJ5APvCOLCRwNVCcJYy2wyQs7KiZlJuoB79oj/wBwtXNOtfYmGIrLWpLK+w5c60UYTANFJOsYcKRPCHPAAWASeMojwChWBxTpFrKu2vQC4BlwyUeFE0KxP0AqYT3JQE+B4SSwH6hnQAFYBO6JqPQKkQZYS5bXgccitP8N/oEKMCGi3C/IEPARuNcvRIb+yO4nngvMAe+Tzr5BkoBBYDfwot9qSOsUyxUNjQ8i6sMggmRoD7nHI/+wHTAGPBNR7hciCRj6LpjCxBpw00d5nyAZGgT2AEv/M/4vmHGRlTWP0ioAAAAASUVORK5CYII=' ); @@ -106,6 +105,7 @@ function createTray(): void { } tray = new Tray(icon.resize({ width: 16, height: 16 })); + (global as typeof globalThis & { __elastosTray?: true }).__elastosTray = true; tray.setToolTip('ElastOS'); updateTrayMenu(); @@ -125,7 +125,8 @@ function updateTrayMenu(): void { 'starting': '🟡 Starting...', 'stopping': '🟡 Stopping...', 'error': '🔴 Error', - 'not-installed': '⚪ Not Installed' + 'not-installed': '⚪ Not Installed', + 'other-home': 'another ElastOS Home is running', }; const contextMenu = Menu.buildFromTemplate([ @@ -138,6 +139,7 @@ function updateTrayMenu(): void { }, { label: 'Stop', + visible: currentStatus !== 'other-home', enabled: currentStatus === 'running', click: () => { void launch.stop(); } }, @@ -149,9 +151,20 @@ function updateTrayMenu(): void { }, { type: 'separator' }, { label: 'Show Window', click: () => mainWindow?.show() }, + ...(homeLaunchForPlatform(process.platform).offerKeepHomeOnQuit ? [{ + id: 'quit-keep-home', + label: 'Quit and keep Home', + click: () => { + stopHomeOnQuit = false; + isQuitting = true; + app.quit(); + }, + }] : []), { + id: 'quit-stop-home', label: 'Quit and stop Home', click: () => { + stopHomeOnQuit = true; isQuitting = true; app.quit(); } @@ -159,6 +172,7 @@ function updateTrayMenu(): void { ]); tray?.setContextMenu(contextMenu); + (global as typeof globalThis & { __elastosTrayMenu?: Menu }).__elastosTrayMenu = contextMenu; } // Set up status change listener @@ -285,7 +299,7 @@ app.whenReady().then(() => { }); app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { + if (homeLaunchForPlatform(process.platform).quitWhenLastWindowCloses) { isQuitting = true; app.quit(); } @@ -301,6 +315,7 @@ app.on('activate', () => { app.on('before-quit', (event) => { isQuitting = true; + if (!stopHomeOnQuit) return; void finishQuitAfterGatewayStop(quitGate, event, () => launch.shutdown(), () => { app.quit(); }, { diff --git a/src/main/launchController.ts b/src/main/launchController.ts index 9f11b30..979aa15 100644 --- a/src/main/launchController.ts +++ b/src/main/launchController.ts @@ -1,7 +1,9 @@ import * as os from 'os'; import { applyOpenAtLogin, readOpenAtLogin } from './targets/openAtLogin'; import { buildDiagnostics, collectPreflight, PreflightReport, saveCollectedSupportBundle } from './targets/preflight'; -import { confirmInstalledGateway, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; +import { confirmInstalledGateway, homeLaunchForPlatform, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; + +export { homeLaunchForPlatform }; import { collectFailureFacts, failureScreen, FailureScreen, fixCollectedFailure, windowsFixResult } from './targets/runtimeRecovery'; import { resolveLaunchTargetId } from './targets/preferences'; import { LAUNCH_TARGET_ENV, retiredPc2Notice } from './targets/registry'; @@ -129,6 +131,7 @@ export interface LaunchInfo { preflight: PreflightReport; openAtLogin: boolean; canRollback: boolean; + openBrowserAfterInstall: boolean; } function messageOf(err: unknown): string { @@ -290,6 +293,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L preflight, openAtLogin: readOpenAtLogin(), canRollback: Boolean(runtimeHeadStore().get()), + openBrowserAfterInstall: homeLaunchForPlatform(process.platform).openBrowserAfterInstall, }; }, getPreflight: () => collectPreflight(), diff --git a/src/main/targets/descriptors.ts b/src/main/targets/descriptors.ts index 80f4a57..cc05b18 100644 --- a/src/main/targets/descriptors.ts +++ b/src/main/targets/descriptors.ts @@ -3,8 +3,8 @@ import { LaunchTargetDescriptor } from './types'; /** * Facts taken from elastos-runtime. - * `elastos gateway` is the supervised entry: `elastos home --browser` - * also opens the system browser itself. + * Darwin and Linux start `home --browser` from homeLaunchForPlatform. + * `startArgs` stays the gateway command for the other platforms. * Health is GET /healthz → "OK" on the gateway. * darwin/x64 is included because a runtime build for Intel Mac is planned. * Native win32 is absent: Windows uses a WSL2 distro. diff --git a/src/main/targets/hostTools.ts b/src/main/targets/hostTools.ts index 8efe06f..f296d19 100644 --- a/src/main/targets/hostTools.ts +++ b/src/main/targets/hostTools.ts @@ -80,8 +80,9 @@ export function detectLinuxLibc( // That directory is not on this computer. } } - if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; + // The glibc loader is the system libc when a leftover musl loader is also present. if (names.some((name) => name.startsWith('ld-linux') || name === 'libc.so.6')) return 'glibc'; + if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; return 'unknown'; } diff --git a/src/main/targets/openAtLogin.ts b/src/main/targets/openAtLogin.ts index 527b2fa..3d1cfce 100644 --- a/src/main/targets/openAtLogin.ts +++ b/src/main/targets/openAtLogin.ts @@ -10,13 +10,33 @@ export function linuxAutostartPath(homeDir: string): string { return path.join(homeDir, '.config', 'autostart', 'elastos.desktop'); } +/** A mounted AppImage reports a temporary exec path. `$APPIMAGE` is the file the user keeps. */ +export function linuxAutostartExecPath(env: NodeJS.ProcessEnv, execPath: string): string { + const image = typeof env.APPIMAGE === 'string' ? env.APPIMAGE.trim() : ''; + return image || execPath; +} + +/** Quote a desktop Exec value when it contains a reserved character. */ +export function desktopExecValue(execPath: string): string { + if (/[\r\n\0]/.test(execPath)) { + throw new Error('The sign-in program path is not valid.'); + } + if (!/[\s"'\\><~|&;$*?#()`]/.test(execPath)) return execPath; + const escaped = execPath + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/`/g, '\\`') + .replace(/\$/g, '\\$'); + return `"${escaped}"`; +} + export function linuxAutostartFile(execPath: string): string { return [ '[Desktop Entry]', 'Type=Application', 'Name=ElastOS', 'Comment=Open your computer', - `Exec=${execPath}`, + `Exec=${desktopExecValue(execPath)}`, 'X-GNOME-Autostart-enabled=true', '', ].join('\n'); @@ -63,7 +83,7 @@ export function syncLinuxAutostart( export function applyOpenAtLogin(enabled: boolean, homeDir: string = os.homedir()): void { writeOpenAtLogin(enabled, homeDir); if (process.platform === 'linux') { - syncLinuxAutostart(enabled, homeDir, process.execPath, { + syncLinuxAutostart(enabled, homeDir, linuxAutostartExecPath(process.env, process.execPath), { mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }), writeFile: (file, contents) => fs.writeFileSync(file, contents), remove: (file) => fs.rmSync(file, { force: true }), diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index 09ef064..fef8fd8 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -1,4 +1,4 @@ -import { execFile, execFileSync, spawn } from 'child_process'; +import { ChildProcess, execFile, execFileSync, spawn, spawnSync } from 'child_process'; import * as dns from 'dns'; import * as fs from 'fs'; import * as http from 'http'; @@ -21,6 +21,31 @@ export { HEALTH_URL, HOME_URL, LEGACY_GATEWAY_ADDR, LOOPBACK_ADDRESSES }; /** Supervised command from the launcher contract. */ export const GATEWAY_ARGS: readonly string[] = ['gateway', '--addr', GATEWAY_ADDR]; +const TERMINAL_KEEP_LINE = 'Keep this terminal open. Press Ctrl+C to stop Home.'; + +export interface HomeLaunch { + args: readonly string[]; + quitWhenLastWindowCloses: boolean; + updateRestartsHome: boolean; + rollbackRestartsHome: boolean; + hideTerminalKeepLine: boolean; + openBrowserAfterInstall: boolean; + offerKeepHomeOnQuit: boolean; +} + +/** Darwin and Linux start the signed Home controller. Windows keeps the gateway command. */ +export function homeLaunchForPlatform(platform: string): HomeLaunch { + const browserHome = platform === 'darwin' || platform === 'linux'; + return { + args: browserHome ? ['home', '--browser'] : GATEWAY_ARGS, + quitWhenLastWindowCloses: platform !== 'darwin' && platform !== 'linux', + updateRestartsHome: browserHome, + rollbackRestartsHome: browserHome, + hideTerminalKeepLine: platform === 'linux', + openBrowserAfterInstall: platform !== 'linux', + offerKeepHomeOnQuit: platform === 'linux', + }; +} export const ALREADY_OWNS_TEXT = 'another ElastOS host already owns'; export const EXIT_BINARY_REPLACED = 75; export const STOP_GRACE_MS = 15_000; @@ -28,6 +53,9 @@ export const FOREIGN_LISTENER_MESSAGE = `Another program is answering at ${GATEWAY_ADDR}, so Home was not opened. Quit that program and click Try again.`; export const LEGACY_STILL_RUNNING_MESSAGE = 'An older ElastOS is still running and could not be stopped. Quit it, then click Start.'; +export const HOME_UNCONFIRMED_MESSAGE = + 'Home could not be confirmed; stop it with Ctrl+C in its terminal'; +export const OTHER_HOME_MESSAGE = 'another ElastOS Home is running'; /** A gateway this window did not start. Callers match the type, not the sentence. */ export class ForeignGatewayError extends Error { @@ -53,10 +81,14 @@ export interface HealthResult { export interface GatewayProcess { readonly pid: number; + /** True only for the ChildProcess this launcher created. Stop keeps that handle. */ + readonly spawnedHere?: boolean; onOutput(listener: (chunk: string) => void): void; onExit(listener: (code: number | null) => void): void; signal(signal: NodeJS.Signals): void; hasExited(): boolean | Promise; + /** Drop a pidfd helper. A spawned process and a Mac process have none. */ + dispose?(): void; } /** @@ -93,7 +125,8 @@ export function signalProcessGroup( /** * `current` is a gateway on `localhost:8090`, the address this launcher * starts. `legacy` is one an earlier launcher started on `127.0.0.1:8090`. - * A legacy gateway is only stopped and started again. Home never opens on it. + * Linux does not signal a legacy gateway. Windows may stop its distro + * gateway and start `localhost:8090`. Home never opens on the legacy one. */ export type InstalledGatewayKind = 'current' | 'legacy'; @@ -148,7 +181,7 @@ export function foreignListenerIsElastos(input: Parameters GatewayProcess; fetchHealth: () => Promise; @@ -156,6 +189,8 @@ export interface GatewaySupervisorDeps { now: () => number; openUrl: (url: string) => void; log: (line: string) => void; + /** Linux drops the runtime's terminal sentence. Exit 75 still reads the raw stream. */ + hideTerminalKeepLine?: boolean; confirmForeign?: () => Promise; /** * True when the running gateway is one an earlier launcher started on @@ -163,6 +198,11 @@ export interface GatewaySupervisorDeps { * starts it again on `localhost:8090`. */ foreignIsLegacy?: () => Promise; + /** + * Linux sets this. A bare gateway on 127.0.0.1:8090 is another Home. + * Start reports that and does not signal it. Windows leaves this unset. + */ + reportLegacyHome?: () => Promise; /** * An OK body counts only when this returns true: the started gateway owns * every `localhost` address that answered. Without it, OK is enough. @@ -174,6 +214,11 @@ export interface GatewaySupervisorDeps { * Returning null leaves a listener that is not that gateway running. */ adoptInstalled?: () => GatewayProcess | null | Promise; + /** + * Linux Stop signals the process this window spawned. Mac Stop adopts the + * proved controller instead, including after that process has exited. + */ + keepSpawnedHandle?: boolean; graceMs?: number; healthTimeoutMs?: number; pollMs?: number; @@ -187,7 +232,7 @@ export interface GatewaySupervisor { * Uninstall, after the person confirmed. Quit, Stop, and Restart omit it. */ stop(options?: { adopt?: boolean }): Promise; - /** SIGKILL the process group this supervisor is stopping. Used when quit runs out of time. */ + /** SIGKILL the process this supervisor is stopping. Used when quit runs out of time. */ forceKill(): void; openHome(): void; getLogs(lines?: number): string; @@ -258,6 +303,468 @@ export function procListenersFor(tcp: string, tcp6: string, fdLinks: readonly st return procNetListeners(tcp, tcp6, port).map((entry) => ({ address: entry.address, owned: owned.has(entry.inode) })); } +export interface ProcProcess { + pid: number; + ppid: number; + fdLinks: readonly string[]; +} + +/** `comm` may contain spaces. The kernel ends the name at the last `)`. */ +export function procStatParent(stat: string): { pid: number; ppid: number } | null { + const end = stat.lastIndexOf(')'); + const space = stat.indexOf(' '); + if (end < 0 || space <= 0 || space > end) return null; + const pid = Number(stat.slice(0, space)); + const ppid = Number(stat.slice(end + 2).split(' ')[1]); + if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0) return null; + return { pid, ppid }; +} + +/** + * Sockets on `port` held by `root` itself. + * Home names the gateway pid in the controller status. A descendant is not that pid. + */ +export function listenersFromProcSnapshot( + tcp: string, + tcp6: string, + root: number, + rows: readonly ProcProcess[], + port = GATEWAY_PORT, +): PortListener[] { + const own = rows.find((row) => row.pid === root); + return procListenersFor(tcp, tcp6, own ? own.fdLinks : [], port); +} + +/** Field 22 of `/proc//stat`, the starttime tick. `comm` may contain spaces. */ +export function linuxStatStartTicks(stat: string): string | null { + const end = stat.lastIndexOf(')'); + if (end < 0) return null; + const ticks = stat.slice(end + 1).trim().split(/\s+/)[19]; + if (!ticks || !/^[0-9]+$/.test(ticks)) return null; + return ticks; +} + +/** + * The same birth string Runtime 2.0.0 stores in `controller_start` + * (`update_controller/child.rs` `process_identity`). + */ +export function linuxProcessIdentity(stat: string | null, bootId: string | null): string | null { + if (!stat) return null; + const ticks = linuxStatStartTicks(stat); + if (!ticks) return null; + const boot = (bootId ?? '').trim(); + if (!boot) return `linux:${ticks}`; + if (/[\r\n]/.test(boot)) return null; + return `linux:${boot}:${ticks}`; +} + +export interface LinuxHomeStatus { + controllerPid: number; + controllerStart: string; + hostPid: number; + generation: string; +} + +export interface HostLockRecord { + pid: number; + role: string; + addr: string; + generation: string; +} + +function positivePid(value: unknown): number | null { + return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null; +} + +/** `update-controller/status.json` from Runtime 2.0.0. A missing field is not a Home. */ +export function parseLinuxHomeStatus(text: string | null): LinuxHomeStatus | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { + controller_pid?: unknown; + controller_start?: unknown; + host_pid?: unknown; + generation?: unknown; + }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const controllerPid = positivePid(parsed.controller_pid); + const hostPid = positivePid(parsed.host_pid); + const controllerStart = typeof parsed.controller_start === 'string' ? parsed.controller_start : ''; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (!controllerPid || !hostPid || !controllerStart || !generation) return null; + if (controllerStart.length > 200 || generation.length > 128) return null; + if (/[\r\n]/.test(controllerStart) || /[\r\n]/.test(generation)) return null; + return { controllerPid, controllerStart, hostPid, generation }; +} + +/** `host-process.lock`. `generation` may be empty for a gateway this controller did not start. */ +export function parseHostLockRecord(text: string | null): HostLockRecord | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { pid?: unknown; role?: unknown; addr?: unknown; generation?: unknown }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const pid = positivePid(parsed.pid); + if (!pid || typeof parsed.role !== 'string' || typeof parsed.addr !== 'string') return null; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (generation.length > 128 || /[\r\n]/.test(generation)) return null; + return { pid, role: parsed.role, addr: parsed.addr, generation }; +} + +/** The controller Runtime 2.0.0 recorded, proved against the host lock and `/proc`. */ +export interface ProvedLinuxHome { + controllerPid: number; + controllerStart: string; + hostPid: number; + hostStart: string; + generation: string; +} + +/** + * Fail closed. The host lock must name this gateway on `localhost:8090`. + * The status file must name that same pid, generation, and controller birth. + * The host birth must be the same value on both sides of the descriptor read. + */ +export function proveLinuxHome(input: { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + hostStatBefore: string | null; + hostFdLinks: readonly string[] | null; + hostStatAfter: string | null; + tcp: string; + tcp6: string; + answered?: readonly string[]; +}): ProvedLinuxHome | null { + const status = parseLinuxHomeStatus(input.statusText); + const lock = parseHostLockRecord(input.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (lock.pid !== status.hostPid || lock.generation !== status.generation) return null; + const controllerNow = linuxProcessIdentity(input.controllerStat, input.bootId); + const controllerParsed = input.controllerStat ? procStatParent(input.controllerStat) : null; + if (controllerNow !== status.controllerStart || !controllerParsed || controllerParsed.pid !== status.controllerPid) { + return null; + } + const before = linuxProcessIdentity(input.hostStatBefore, input.bootId); + const after = linuxProcessIdentity(input.hostStatAfter, input.bootId); + const hostParsed = input.hostStatBefore ? procStatParent(input.hostStatBefore) : null; + if (!before || before !== after || !hostParsed || hostParsed.pid !== status.hostPid) return null; + if (!input.hostFdLinks) return null; + const listeners = procListenersFor(input.tcp, input.tcp6, input.hostFdLinks); + if (listenerOwnership(listeners, LOOPBACK_ADDRESSES, input.answered ?? []) !== 'owned') return null; + return { + controllerPid: status.controllerPid, + controllerStart: status.controllerStart, + hostPid: status.hostPid, + hostStart: before, + generation: status.generation, + }; +} + +/** The pid to signal, or null when its birth no longer matches the proof. */ +export function linuxControllerSignalPid(proved: ProvedLinuxHome, identityNow: string | null): number | null { + if (!identityNow || identityNow !== proved.controllerStart) return null; + return proved.controllerPid; +} + +/** One fresh read of the controller record, the lock, and `/proc`. */ +export interface ControllerObservation { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + exePath: string | null; + allowedExes: readonly string[]; +} + +export type ControllerRecord = Pick; + +export type ControllerProcView = Pick; + +/** A pidfd for one process. `send` cannot target a later occupant of the same pid number. */ +export interface Pidfd { + send(signal: NodeJS.Signals): void; + close(): void; +} + +/** + * The update controller pid, or null. The start time, the exe, and the host + * lock generation must all match this read. A host pid is not a target. + */ +export function confirmedControllerPid(observed: ControllerObservation): number | null { + const status = parseLinuxHomeStatus(observed.statusText); + const lock = parseHostLockRecord(observed.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (!status.generation || lock.generation !== status.generation) return null; + const identity = linuxProcessIdentity(observed.controllerStat, observed.bootId); + const parsed = observed.controllerStat ? procStatParent(observed.controllerStat) : null; + if (identity !== status.controllerStart || !parsed || parsed.pid !== status.controllerPid) return null; + const exe = observed.exePath; + if (!exe || exe.endsWith(' (deleted)')) return null; + if (!observed.allowedExes.includes(exe)) return null; + return status.controllerPid; +} + +export function signalRecordedController( + signal: NodeJS.Signals, + io: { + readRecord: () => ControllerRecord; + readProc: (pid: number) => ControllerProcView; + openPidfd: (pid: number) => Pidfd; + }, + held: { pidfd: Pidfd | null }, +): void { + if (!held.pidfd) { + const record = io.readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + const lock = parseHostLockRecord(record.lockText); + if (!status || !lock || lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR + || !status.generation || lock.generation !== status.generation) { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let pidfd: Pidfd; + try { + pidfd = io.openPidfd(status.controllerPid); + } catch { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let proc: ControllerProcView; + try { + proc = io.readProc(status.controllerPid); + } catch { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + const confirmed = confirmedControllerPid({ + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }); + if (confirmed !== status.controllerPid) { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + held.pidfd = pidfd; + } + try { + held.pidfd.send(signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } +} + +export function controllerGateway( + readRecord: () => ControllerRecord, + readProc: (pid: number) => ControllerProcView, + openPidfd: (pid: number) => Pidfd, +): GatewayProcess { + const held: { pidfd: Pidfd | null } = { pidfd: null }; + function observation(): ControllerObservation | null { + const record = readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + if (!status) return null; + const proc = readProc(status.controllerPid); + return { + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }; + } + return { + pid: -1, + onOutput() {}, + onExit() {}, + hasExited() { + let gone = false; + try { + const observed = observation(); + gone = observed === null || confirmedControllerPid(observed) === null; + } catch { + return false; + } + if (gone && held.pidfd) { + held.pidfd.close(); + held.pidfd = null; + } + return gone; + }, + signal(signal) { + signalRecordedController(signal, { readRecord, readProc, openPidfd }, held); + }, + dispose() { + const pidfd = held.pidfd; + held.pidfd = null; + if (!pidfd) return; + try { + pidfd.close(); + } catch { + // Stop still reports its own error. close() has already dropped the helper. + } + }, + }; +} + +function throwSignalCode(code: string, message: string): never { + throw Object.assign(new Error(message), { code }); +} + +function linuxPidfdHelperPath(): string { + return path.join(__dirname, '../../native/linux-pidfd') + .replace(`${path.sep}app.asar${path.sep}`, `${path.sep}app.asar.unpacked${path.sep}`); +} + +function makeFifo(file: string): void { + const result = spawnSync('mkfifo', ['-m', '600', file], { timeout: 1000 }); + if (result.error || result.status !== 0) throwSignalCode('ENOSYS', 'pidfd is unavailable'); +} + +function waitBriefly(): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); +} + +function readPidfdLine(fd: number, deadline: number): string { + const buf = Buffer.alloc(64); + let text = ''; + while (!text.includes('\n')) { + if (text.length > 64) throwSignalCode('EIO', 'pidfd reply is too long'); + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n === 0) { + waitBriefly(); + continue; + } + text += buf.toString('utf8', 0, n); + } catch (err) { + const code = signalErrorCode(err); + if (code === 'EAGAIN' || code === 'EWOULDBLOCK') { + waitBriefly(); + continue; + } + throw err; + } + } + return text.slice(0, text.indexOf('\n')); +} + +function openFifoWrite(file: string, deadline: number): number { + const flags = fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + for (;;) { + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + return fs.openSync(file, flags); + } catch (err) { + if (signalErrorCode(err) === 'ENXIO') { + waitBriefly(); + continue; + } + throw err; + } + } +} + +export function openLinuxPidfd(pid: number, options?: { helper?: string }): Pidfd { + if (!Number.isInteger(pid) || pid <= 0) throwSignalCode('EINVAL', 'bad pid'); + const helper = options?.helper ?? linuxPidfdHelperPath(); + if (!options?.helper && process.platform !== 'linux') throwSignalCode('ENOSYS', 'pidfd is unavailable'); + if (!fs.existsSync(helper)) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'elastos-pidfd-')); + fs.chmodSync(dir, 0o700); + const replyPath = path.join(dir, 'reply'); + const cmdPath = path.join(dir, 'cmd'); + let child: ChildProcess | null = null; + let replyFd: number | null = null; + let cmdFd: number | null = null; + let settled = false; + const cleanup = (): void => { + if (settled) return; + settled = true; + if (cmdFd === null) { + try { + cmdFd = fs.openSync(cmdPath, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'ENXIO' && code !== 'ENOENT') throw err; + } + } + const command = cmdFd; + const reply = replyFd; + cmdFd = null; + replyFd = null; + let closeError: unknown = null; + if (command !== null) { + try { fs.closeSync(command); } catch (err) { closeError = err; } + } + if (reply !== null) { + try { fs.closeSync(reply); } catch (err) { if (!closeError) closeError = err; } + } + child?.unref(); + fs.rmSync(dir, { recursive: true, force: true }); + if (closeError) throw closeError; + }; + try { + makeFifo(replyPath); + makeFifo(cmdPath); + child = spawn(helper, [String(pid), replyPath, cmdPath], { stdio: 'ignore' }); + // Node crashes when the spawn error event has no listener. + child.on('error', () => {}); + if (!child.pid) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const replyFlags = fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + replyFd = fs.openSync(replyPath, replyFlags); + const ready = readPidfdLine(replyFd, Date.now() + 2000); + if (ready.startsWith('errno ')) throwSignalCode(ready.slice('errno '.length), ready); + if (ready !== 'ready') throwSignalCode('EIO', 'pidfd helper did not become ready'); + cmdFd = openFifoWrite(cmdPath, Date.now() + 2000); + const reply = replyFd; + const cmd = cmdFd; + let closed = false; + return { + send(signal: NodeJS.Signals): void { + if (closed) throwSignalCode('EBADF', 'pidfd is closed'); + if (signal !== 'SIGTERM' && signal !== 'SIGKILL') throwSignalCode('EINVAL', 'unsupported signal'); + fs.writeSync(cmd, `${signal}\n`); + const line = readPidfdLine(reply, Date.now() + 2000); + if (line === 'sent') return; + if (line.startsWith('errno ')) throwSignalCode(line.slice('errno '.length), line); + throwSignalCode('EIO', 'pidfd helper reply was not a signal result'); + }, + close(): void { + if (closed) return; + closed = true; + try { + fs.writeSync(cmd, 'close\n'); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'EPIPE' && code !== 'EBADF') { + cleanup(); + throw err; + } + } + cleanup(); + }, + }; + } catch (err) { + cleanup(); + throw err; + } +} + /** * `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` output. `n` names look like * `127.0.0.1:8090`, `[::1]:8090`, or `*:8090`. A socket of another account is @@ -326,6 +833,12 @@ export function scrubRuntimeLog(chunk: string): string { return chunk; } +export function launcherLogText(text: string, hideTerminalKeepLine: boolean): string { + const clean = scrubRuntimeLog(text); + if (!hideTerminalKeepLine) return clean; + return clean.split('\n').filter((line) => !line.includes(TERMINAL_KEEP_LINE)).join('\n'); +} + export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySupervisor { const graceMs = deps.graceMs ?? STOP_GRACE_MS; const healthTimeoutMs = deps.healthTimeoutMs ?? 60_000; @@ -340,7 +853,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup const homeController = deps.args?.[0] === 'home'; const note = (line: string) => { - const clean = scrubRuntimeLog(line).replace(/\s+$/g, ''); + const clean = launcherLogText(line, deps.hideTerminalKeepLine === true).replace(/\s+$/g, ''); if (!clean) return; logs.push(clean); deps.log(clean); @@ -357,8 +870,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 +897,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; @@ -460,7 +978,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup if (output.includes(ALREADY_OWNS_TEXT)) { return 'already'; } - const tail = scrubRuntimeLog(output).trim().split('\n').slice(-3).join(' '); + const tail = launcherLogText(output, deps.hideTerminalKeepLine === true).trim().split('\n').slice(-3).join(' '); current = 'error'; throw new Error( tail @@ -491,20 +1009,25 @@ 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)) { + owned = null; + current = 'stopped'; + return; + } + proc.signal('SIGKILL'); + if (await confirmedStopped(proc, graceMs)) { + 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 = { @@ -519,6 +1042,10 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup const result = await launchOnce(); if (result === 'replaced') continue; if (result === 'already') { + if (deps.reportLegacyHome && await deps.reportLegacyHome()) { + current = 'error'; + throw new Error(OTHER_HOME_MESSAGE); + } if (!legacyStopped && deps.foreignIsLegacy && await deps.foreignIsLegacy()) { // An earlier launcher started it on 127.0.0.1. Passkeys need // localhost, so stop it once and start it again here. @@ -561,7 +1088,11 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup } }, async stop(options?: { adopt?: boolean }) { - if (deps.adoptForControls && isHealthOk(await deps.fetchHealth())) { + const currentProc = owned; + const keepSpawned = deps.keepSpawnedHandle === true + && currentProc !== null && currentProc.spawnedHere === true + && !(await currentProc.hasExited()); + if (!keepSpawned && deps.adoptForControls && isHealthOk(await deps.fetchHealth())) { const installed = await findInstalled(); if (!installed) throw new ForeignGatewayError(); ownAdopted(installed); @@ -591,11 +1122,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); @@ -612,7 +1145,11 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup return supervisor; } -export function spawnGatewayProcess(binary: string, args: readonly string[]): GatewayProcess { +export function spawnGatewayProcess( + binary: string, + args: readonly string[], + platform: string = process.platform, +): GatewayProcess { const child = spawn(binary, [...args], { detached: true, stdio: ['ignore', 'pipe', 'pipe'], @@ -642,8 +1179,19 @@ export function spawnGatewayProcess(binary: string, args: readonly string[]): Ga hasExited() { return exited; }, + spawnedHere: true, signal(signal) { - signalProcessGroup(child.pid ?? -1, signal); + if (platform === 'darwin') { + signalProcessGroup(child.pid ?? -1, signal); + return; + } + try { + child.kill(signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } }, }; } @@ -658,9 +1206,24 @@ export function emitRuntimeLog(line: string): void { logSink(line); } +function withDeadline(work: Promise, timeoutMs: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => { + reject(Object.assign(new Error('localhost lookup timed out'), { code: 'ETIMEDOUT' })); + }, timeoutMs); + }); + return Promise.race([work, timeout]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); +} + /** The addresses `localhost` resolves to on this computer, in resolver order. */ -export async function resolveLocalhost(): Promise { - const found = await dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }); +export async function resolveLocalhost(timeoutMs = 2000): Promise { + const found = await withDeadline( + dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }), + timeoutMs, + ); return [...new Set(found.map((entry) => entry.address))]; } @@ -737,7 +1300,9 @@ export async function probeGatewayHealth(options: { const timeoutMs = options.timeoutMs ?? 2000; let addresses: string[]; try { - addresses = await (options.lookup ?? resolveLocalhost)(); + addresses = options.lookup + ? await withDeadline(options.lookup(), timeoutMs) + : await resolveLocalhost(timeoutMs); } catch { return null; } @@ -747,38 +1312,131 @@ export async function probeGatewayHealth(options: { return combineHealth(results); } -/** LISTEN sockets on the gateway port, marked by whether `pid` holds each. Null when they cannot be read. */ -export async function localListeners(pid: number, platform: string = process.platform): Promise { - if (!Number.isInteger(pid) || pid <= 0) return null; - if (platform === 'linux') { - let tcp: string; +const PROC_STAT_MAX = 4096; +const PROC_TEXT_MAX = 8 * 1024 * 1024; +const HOME_RECORD_MAX = 16 * 1024; + +function fdLinks(pid: number): string[] | null { + const links: string[] = []; + let names: string[]; + try { + names = fs.readdirSync(`/proc/${pid}/fd`); + } catch { + return null; + } + for (const name of names) { try { - tcp = fs.readFileSync('/proc/net/tcp', 'utf8'); + links.push(fs.readlinkSync(`/proc/${pid}/fd/${name}`)); } catch { - return null; + // A descriptor can disappear between readdir and readlink. } - let tcp6 = ''; - try { - tcp6 = fs.readFileSync('/proc/net/tcp6', 'utf8'); - } catch { - // No IPv6 on this kernel. Nothing can listen on ::1. - tcp6 = ''; + } + return links; +} + +/** `undefined` when the path is absent. `null` when the bytes are not a bounded file. */ +function readProcOptional(file: string, max: number): string | null | undefined { + let fd: number | null = null; + try { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const chunks: Buffer[] = []; + let total = 0; + const buf = Buffer.alloc(64 * 1024); + for (;;) { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n <= 0) break; + total += n; + if (total > max) return null; + chunks.push(Buffer.from(buf.subarray(0, n))); } - const links: string[] = []; - try { - const dir = `/proc/${pid}/fd`; - for (const name of fs.readdirSync(dir)) { - try { - links.push(fs.readlinkSync(`${dir}/${name}`)); - } catch { - // A descriptor can disappear between readdir and readlink. - } - } - } catch { - return null; + return Buffer.concat(chunks).toString('utf8'); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; + if (code === 'ENOENT') return undefined; + return null; + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } + } + } +} + +function readRegularText(file: string, max: number): string | null { + let fd: number | null = null; + try { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const info = fs.fstatSync(fd); + if (!info.isFile() || info.size > max) return null; + const buf = Buffer.alloc(info.size); + let offset = 0; + while (offset < info.size) { + const n = fs.readSync(fd, buf, offset, info.size - offset, offset); + if (n <= 0) return null; + offset += n; + } + return buf.toString('utf8'); + } catch { + return null; + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } } - return procListenersFor(tcp, tcp6, links); } +} + +/** Listeners held by `pid` itself. Null when `/proc` cannot prove that. */ +function linuxProcessListeners(pid: number): PortListener[] | null { + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + if (!tcp) return null; + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (tcp6 === null) return null; + const links = fdLinks(pid); + if (!links) return null; + return procListenersFor(tcp, tcp6 ?? '', links); +} + +function readProvedLinuxHome(answered: readonly string[] = []): ProvedLinuxHome | null { + const data = runtimeDataDir('linux', os.homedir(), process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + if (bootId === null) return null; + const status = parseLinuxHomeStatus(statusText); + if (!status) return null; + const hostStatBefore = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const hostFdLinks = fdLinks(status.hostPid); + const hostStatAfter = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const controllerStat = readProcOptional(`/proc/${status.controllerPid}/stat`, PROC_STAT_MAX); + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (!controllerStat || !hostStatBefore || !hostStatAfter || !tcp || tcp6 === null) return null; + return proveLinuxHome({ + statusText, + lockText, + bootId: bootId ?? null, + controllerStat, + hostStatBefore, + hostFdLinks, + hostStatAfter, + tcp, + tcp6: tcp6 ?? '', + answered, + }); +} + +function linuxControllerOwnsListeners(controllerPid: number, health: HealthResult): boolean { + const proved = readProvedLinuxHome(health.addresses ?? []); + if (!proved || proved.controllerPid !== controllerPid) return false; + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + const stat = readProcOptional(`/proc/${proved.controllerPid}/stat`, PROC_STAT_MAX); + if (bootId === null || !stat) return false; + return linuxControllerSignalPid(proved, linuxProcessIdentity(stat, bootId ?? null)) === proved.controllerPid; +} + +/** LISTEN sockets on the gateway port, marked by whether `pid` itself holds each. Null when they cannot be read. */ +export async function localListeners(pid: number, platform: string = process.platform): Promise { + if (!Number.isInteger(pid) || pid <= 0) return null; + if (platform === 'linux') return linuxProcessListeners(pid); if (platform === 'darwin') { return new Promise((resolve) => { execFile('lsof', ['-nP', `-iTCP:${GATEWAY_PORT}`, '-sTCP:LISTEN', '-Fpn'], { @@ -810,24 +1468,39 @@ export async function pidOwnsGatewayPort( return listenerOwnership(listeners, wants, answered) === 'owned'; } +/** Linux and Mac Stop and Quit take the installed Home. Windows does not. */ +export function platformAdoptsInstalledHome(platform: string): boolean { + return platform === 'darwin' || platform === 'linux'; +} + export function createDefaultGatewaySupervisor(binary: string, platform: string = process.platform): GatewaySupervisor { + const launch = homeLaunchForPlatform(platform); return createGatewaySupervisor({ binary, - args: platform === 'darwin' ? ['home', '--browser'] : GATEWAY_ARGS, - adoptForControls: platform === 'darwin', + args: launch.args, + hideTerminalKeepLine: launch.hideTerminalKeepLine, + adoptForControls: platformAdoptsInstalledHome(platform), + keepSpawnedHandle: platform === 'linux', healthTimeoutMs: platform === 'darwin' ? 150000 : 60000, - spawn: spawnGatewayProcess, + spawn: (command, commandArgs) => spawnGatewayProcess(command, commandArgs, platform), fetchHealth: () => probeGatewayHealth(), sleep: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }), now: () => Date.now(), openUrl: openRuntimeHome, log: (line) => logSink(line), confirmForeign: confirmInstalledGateway, - foreignIsLegacy: async () => (await installedGatewayOnThisComputer()) === 'legacy', + foreignIsLegacy: platform === 'darwin' + ? async () => (await installedGatewayOnThisComputer(platform)) === 'legacy' + : undefined, + reportLegacyHome: platform === 'linux' + ? async () => (await installedGatewayOnThisComputer(platform)) === 'legacy' + : undefined, listenerOwned: (pid, health) => platform === 'darwin' - ? confirmInstalledGateway() - : pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), - adoptInstalled: adoptInstalledGatewayProcess, + ? installedGatewayOnThisComputer(platform).then((kind) => kind === 'current') + : platform === 'linux' + ? linuxControllerOwnsListeners(pid, health) + : pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), + adoptInstalled: () => adoptInstalledGatewayProcess(platform), }); } @@ -970,14 +1643,95 @@ export function localPidHasExited( } /** - * The installed gateway from the host lock, so Stop can signal a process this - * window did not spawn. A `127.0.0.1:8090` gateway from an earlier launcher is - * adopted too, so Start, Reset, and Uninstall can stop it. + * Stop can signal one process this window did not spawn: the update controller + * named by status.json. A `127.0.0.1:8090` gateway is not that process. */ +function signalErrorCode(err: unknown): string { + return err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; +} + +function resolvedFile(file: string): string | null { + try { + const real = fs.realpathSync(file); + return real ? real : null; + } catch { + return null; + } +} + +function controllerExeFromProc(pid: number): string | null { + let link: string; + try { + link = fs.readlinkSync(`/proc/${pid}/exe`); + } catch { + return null; + } + if (!link || link.endsWith(' (deleted)')) return null; + return resolvedFile(link); +} + +/** The installed binary, and the controller copy Runtime stores under the data dir. */ +function allowedControllerExes(homeDir: string, dataDir: string): string[] { + const files = [ + runtimeBinaryPath(homeDir), + `${dataDir}/update-controller/runtime`, + ]; + const allowed: string[] = []; + for (const file of files) { + const real = resolvedFile(file); + if (real && !allowed.includes(real)) allowed.push(real); + } + return allowed; +} + +function observeControllerRecord(homeDir: string): ControllerRecord { + const data = runtimeDataDir('linux', homeDir, process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const boot = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + return { + statusText, + lockText, + bootId: boot ?? null, + allowedExes: allowedControllerExes(homeDir, data), + }; +} + +function observeControllerProc(pid: number): ControllerProcView { + if (!Number.isInteger(pid) || pid <= 0) return { controllerStat: null, exePath: null }; + const stat = readProcOptional(`/proc/${pid}/stat`, PROC_STAT_MAX); + return { + controllerStat: stat ?? null, + exePath: controllerExeFromProc(pid), + }; +} + +/** `controller` may be signaled. `other-home` is a legacy gateway and is never signaled. */ +export function linuxControllerAdopt(lockText: string | null): 'controller' | 'other-home' | 'none' { + const lock = parseHostLockRecord(lockText); + if (!lock || lock.role !== 'gateway') return 'none'; + if (lock.addr === LEGACY_GATEWAY_ADDR) return 'other-home'; + if (lock.addr !== GATEWAY_ADDR) return 'none'; + return 'controller'; +} + +/** Linux Home. Signal only the recorded update controller. A legacy gateway is not adopted. */ +async function adoptLinuxGatewayProcess(homeDir: string): Promise { + const data = runtimeDataDir('linux', homeDir, process.env); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + if (linuxControllerAdopt(lockText) !== 'controller') return null; + return controllerGateway( + () => observeControllerRecord(homeDir), + (pid) => observeControllerProc(pid), + openLinuxPidfd, + ); +} + export async function adoptInstalledGatewayProcess( platform: string = process.platform, homeDir: string = os.homedir(), ): Promise { if (platform === 'win32') return null; + if (platform === 'linux') return adoptLinuxGatewayProcess(homeDir); const refused = (reason: string): null => { logSink(`Home ownership check: ${reason}`); return null; @@ -1054,7 +1808,9 @@ export async function adoptInstalledGatewayProcess( throw new Error('ElastOS process identity changed. Refusing to signal a reused PID.'); } process.kill(stopPid, signal); - } else signalProcessGroup(pid, signal); + } else { + signalProcessGroup(pid, signal); + } }, }; } diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index 3f1f9e3..0674014 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -5,8 +5,10 @@ import { RUNTIME_TARGET } from './descriptors'; import { createDefaultGatewaySupervisor, confirmInstalledGateway, + installedGatewayOnThisComputer, ForeignGatewayError, GatewaySupervisor, + homeLaunchForPlatform, isHealthOk, openRuntimeHome, probeGatewayHealth, @@ -102,12 +104,34 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform await supervisor.stop({ adopt }); } + async function runWithHomeRestart(action: () => Promise): Promise { + if (updating) throw new Error('An ElastOS update is already running.'); + updating = true; + try { + await stopGateway(true); + await action(); + } finally { + supervisor = null; + try { + const file = binary(); + if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); + supervisor = createDefaultGatewaySupervisor(file, platform); + await supervisor.start(); + } finally { + updating = false; + } + } + } + return { id: 'runtime', descriptor: RUNTIME_TARGET, isInstalled: () => runtimeIsInstalled(), getStatus: async () => { if (updating) return 'starting'; + if (platform === 'linux' && (await installedGatewayOnThisComputer(platform)) === 'legacy') { + return 'other-home'; + } const observedSupervisor = supervisor; const observedPhase = supervisor?.phase(); if (supervisor) { @@ -156,10 +180,18 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform }); }, install: (onProgress) => runtimeInstall.installRuntimeOnThisComputer(onProgress), - update: (onProgress) => changeRuntime(() => - applyRuntimeUpdate(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress)), - rollback: (onProgress) => changeRuntime(() => - rollbackRuntime(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress)), + update: (onProgress) => { + const action = () => applyRuntimeUpdate(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress); + if (platform === 'darwin') return changeRuntime(action); + if (!homeLaunchForPlatform(platform).updateRestartsHome) return serialize(action); + return serialize(() => runWithHomeRestart(action)); + }, + rollback: (onProgress) => { + const action = () => rollbackRuntime(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress); + if (platform === 'darwin') return changeRuntime(action); + if (!homeLaunchForPlatform(platform).rollbackRestartsHome) return serialize(action); + return serialize(() => runWithHomeRestart(action)); + }, // On Windows the launch controller runs uninstallRuntimeInDistro (windowsUninstall.ts) with the two answers. uninstall: () => { requestedRunning = false; diff --git a/src/main/targets/types.ts b/src/main/targets/types.ts index 467e883..23fa598 100644 --- a/src/main/targets/types.ts +++ b/src/main/targets/types.ts @@ -12,7 +12,8 @@ export type TargetStatus = | 'starting' | 'stopping' | 'error' - | 'not-installed'; + | 'not-installed' + | 'other-home'; export interface TargetPlatform { platform: 'darwin' | 'linux' | 'win32'; diff --git a/src/native/linux-pidfd.c b/src/native/linux-pidfd.c new file mode 100644 index 0000000..f77180e --- /dev/null +++ b/src/native/linux-pidfd.c @@ -0,0 +1,125 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __NR_pidfd_open +#define __NR_pidfd_open 434 +#endif +#ifndef __NR_pidfd_send_signal +#define __NR_pidfd_send_signal 424 +#endif + +static int write_text(int fd, const char *text) { + size_t len = strlen(text); + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, text + off, len - off); + if (n < 0) { + if (errno == EINTR) continue; + return -1; + } + off += (size_t)n; + } + return 0; +} + +static const char *errno_name(int err) { + switch (err) { + case ESRCH: return "ESRCH"; + case ENOSYS: return "ENOSYS"; + case EPERM: return "EPERM"; + case EINVAL: return "EINVAL"; + case EBADF: return "EBADF"; + default: return "EIO"; + } +} + +static void report(int reply, int err) { + char line[32]; + int n = snprintf(line, sizeof line, "errno %s\n", errno_name(err)); + if (n > 0 && (size_t)n < sizeof line) write_text(reply, line); +} + +static int read_line(int fd, char *buf, size_t cap) { + size_t n = 0; + while (n + 1 < cap) { + char c = 0; + ssize_t r = read(fd, &c, 1); + if (r < 0) { + if (errno == EINTR) continue; + return -1; + } + if (r == 0) return -1; + buf[n++] = c; + if (c == '\n') { + buf[n] = '\0'; + return 0; + } + } + return -1; +} + +int main(int argc, char **argv) { + char *end = NULL; + long pid; + int reply; + int fd; + int cmd; + char line[32]; + if (argc != 4) return 2; + prctl(PR_SET_PDEATHSIG, SIGKILL); + if (getppid() == 1) return 2; + alarm(2); + errno = 0; + pid = strtol(argv[1], &end, 10); + if (errno || !argv[1][0] || (end && *end) || pid <= 0 || pid > 0x7fffffff) return 2; + reply = open(argv[2], O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (reply < 0) return 2; + fd = (int)syscall(__NR_pidfd_open, (int)pid, 0); + if (fd < 0) { + report(reply, errno); + close(reply); + return 1; + } + if (write_text(reply, "ready\n") != 0) { + close(fd); + close(reply); + return 1; + } + cmd = open(argv[3], O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + alarm(0); + if (cmd < 0) { + report(reply, errno); + close(fd); + close(reply); + return 1; + } + while (read_line(cmd, line, sizeof line) == 0) { + int sig = 0; + if (strcmp(line, "close\n") == 0) { + close(fd); + close(cmd); + close(reply); + return 0; + } + if (strcmp(line, "SIGTERM\n") == 0) sig = SIGTERM; + else if (strcmp(line, "SIGKILL\n") == 0) sig = SIGKILL; + else { + report(reply, EINVAL); + continue; + } + if (syscall(__NR_pidfd_send_signal, fd, sig, NULL, 0) != 0) report(reply, errno); + else write_text(reply, "sent\n"); + } + close(fd); + close(cmd); + close(reply); + return 0; +} diff --git a/src/preload/index.ts b/src/preload/index.ts index ac01288..76b3ca2 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,6 +1,6 @@ import { contextBridge, ipcRenderer } from 'electron'; -export type RuntimeStatus = 'running' | 'stopped' | 'starting' | 'stopping' | 'error' | 'not-installed'; +export type RuntimeStatus = 'running' | 'stopped' | 'starting' | 'stopping' | 'error' | 'not-installed' | 'other-home'; contextBridge.exposeInMainWorld('elastos', { platform: process.platform, @@ -101,6 +101,8 @@ declare global { preflight: { ok: boolean; checks: Array<{ id: string; level: string; message: string }> }; openAtLogin: boolean; canRollback: boolean; + error: string | null; + openBrowserAfterInstall: boolean; }>; getPreflight: () => Promise<{ ok: boolean; checks: Array<{ id: string; level: string; message: string }> }>; getDiagnostics: () => Promise; diff --git a/src/renderer/app.js b/src/renderer/app.js index 2ff1641..2c313c6 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -69,7 +69,8 @@ const statusLabels = { starting: 'Starting...', stopping: 'Stopping...', error: 'Needs attention', - 'not-installed': 'Not installed' + 'not-installed': 'Not installed', + 'other-home': 'another ElastOS Home is running' }; async function showError(message) { @@ -176,7 +177,8 @@ function updateStatus(status) { openBtn.dataset.action = action.id; powerBtn.className = 'power-button' + (status === 'running' ? ' running' : ''); - powerBtn.disabled = busy || status === 'starting' || status === 'stopping' || status === 'not-installed'; + powerBtn.classList.toggle('hidden', status === 'other-home'); + powerBtn.disabled = busy || status === 'starting' || status === 'stopping' || status === 'not-installed' || status === 'other-home'; const isInstalled = status !== 'not-installed'; uninstallBtn.disabled = !isInstalled || status === 'running' || busy; @@ -218,7 +220,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 (window.elastos.platform !== 'darwin' && started.openBrowserAfterInstall !== false) { + 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..62cec54 100644 --- a/src/renderer/flow.js +++ b/src/renderer/flow.js @@ -28,6 +28,9 @@ function stepStates(message) { function primaryAction(state) { const status = state.status; if (state.busy) return { id: 'busy', label: 'Working…', enabled: false }; + if (status === 'other-home') { + return { id: 'busy', label: 'another ElastOS Home is running', enabled: false }; + } if (status === 'running') { return { id: 'open', diff --git a/test/darwin-kernel-path.test.js b/test/darwin-kernel-path.test.js new file mode 100644 index 0000000..94677c0 --- /dev/null +++ b/test/darwin-kernel-path.test.js @@ -0,0 +1,22 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { installedGatewayKind } = require('../dist/main/targets/runtimeGateway'); + +test('a proved kernel path accepts a gateway whose command does not start with that path', () => { + const kernel = '/Users/example/.local/share/elastos/elastos'; + const facts = { + lockText: JSON.stringify({ pid: 10, addr: 'localhost:8090' }), + verifiedExecutable: kernel, + pidAlive: () => true, + ownsSocket: () => true, + }; + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos gateway --addr localhost:8090', + }), 'current'); + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos serve', + }), null); +}); diff --git a/test/host-tools.test.js b/test/host-tools.test.js index ead6353..4bb4878 100644 --- a/test/host-tools.test.js +++ b/test/host-tools.test.js @@ -13,6 +13,7 @@ const { BASH_MESSAGE, MUSL_MESSAGE, PYTHON_VERIFY_MESSAGE, + detectLinuxLibc, prepareInstallerEnvironment, } = require('../dist/main/targets/hostTools'); const { evaluatePreflight } = require('../dist/main/targets/preflight'); @@ -258,6 +259,11 @@ test('a tampered python archive is refused and nothing is unpacked', async () => assert.equal(fs.existsSync(path.join(home, '.elastos-launcher', 'python', 'python', 'bin', 'python3')), false); }); +test('a glibc computer that also has a musl loader is not musl', () => { + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-aarch64.so.1', 'ld-linux-aarch64.so.1']), 'glibc'); + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-x86_64.so.1']), 'musl'); +}); + test('musl and a missing shell block install, and a bad python hash is refused', async () => { const dir = tempDir(); await assert.rejects( diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index ca86d18..c02fb4f 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -13,7 +13,7 @@ const { publisherHost, publisherOffline, } = require('../dist/main/targets/preflight'); -const { linuxAutostartFile, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); +const { linuxAutostartFile, linuxAutostartExecPath, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); const flow = require('../src/renderer/flow.js'); test('launcher logs omit terminal-only advice and retain replacement diagnostics', () => { @@ -108,7 +108,15 @@ test('sign-in launch writes a desktop file and can remove it', () => { }; const written = syncLinuxAutostart(true, '/home/tester', '/usr/bin/elastos', fs); assert.match(files.get(written), /Name=ElastOS/); + assert.match(files.get(written), /X-GNOME-Autostart-enabled=true/); assert.match(linuxAutostartFile('/usr/bin/elastos'), /Exec=\/usr\/bin\/elastos/); + assert.equal( + linuxAutostartExecPath({ APPIMAGE: '/home/me/ElastOS.AppImage' }, '/tmp/.mount_abc/elastos'), + '/home/me/ElastOS.AppImage', + ); + assert.equal(linuxAutostartExecPath({ APPIMAGE: ' ' }, '/usr/bin/elastos'), '/usr/bin/elastos'); + assert.match(linuxAutostartFile('/home/me/ElastOS App.AppImage'), /Exec="\/home\/me\/ElastOS App\.AppImage"/); + assert.match(linuxAutostartFile('/home/me/ElastOS-$APP.AppImage'), /Exec="\/home\/me\/ElastOS-\\\$APP\.AppImage"/); assert.equal(syncLinuxAutostart(false, '/home/tester', '/usr/bin/elastos', fs), null); assert.equal(files.size, 0); }); @@ -116,6 +124,9 @@ test('sign-in launch writes a desktop file and can remove it', () => { test('the install button is the primary action until the computer is healthy', () => { assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'not-installed', busy: false }).label, 'Install'); assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'running', busy: false }).label, 'Open my computer'); + const otherHome = flow.primaryAction({ targetId: 'runtime', status: 'other-home', busy: false }); + assert.equal(otherHome.enabled, false); + assert.equal(otherHome.label, 'another ElastOS Home is running'); assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'error', busy: false }).id, 'retry'); assert.match(flow.firstRunCopy('runtime', 'not-installed'), /One button/); assert.equal(flow.firstRunCopy('runtime', 'running'), ''); diff --git a/test/linux-arm64.test.js b/test/linux-arm64.test.js new file mode 100644 index 0000000..5595632 --- /dev/null +++ b/test/linux-arm64.test.js @@ -0,0 +1,80 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); + +const root = path.join(__dirname, '..'); + +const DEB_DEPENDS = [ + 'libgtk-3-0', + 'libnotify4', + 'libnss3', + 'libxss1', + 'libxtst6', + 'xdg-utils', + 'libatspi2.0-0', + 'libuuid1', + 'libsecret-1-0', + 'libayatana-appindicator3-1', +]; + +test('the arm64 package job uses the Jetson glibc and the bundled fpm', () => { + const workflow = fs.readFileSync(path.join(root, '.github/workflows/linux-arm64.yml'), 'utf8'); + const build = fs.readFileSync(path.join(root, '.github/workflows/build.yml'), 'utf8'); + assert.match(workflow, /pull_request:/); + assert.match(workflow, /runs-on: ubuntu-22\.04-arm/); + assert.match(workflow, /--arm64/); + assert.equal(workflow.includes('USE_SYSTEM_FPM'), false); + assert.equal(workflow.includes('APPIMAGE_EXTRACT_AND_RUN'), false); + assert.equal(workflow.includes('gem install fpm'), false); + assert.match(build, /uses: \.\/\.github\/workflows\/linux-arm64\.yml/); + assert.match(build, /needs: \[build, linux-arm64\]/); +}); + +test('runtime smoke and electron e2e have a linux-arm64 row on Ubuntu 22.04', () => { + const workflow = fs.readFileSync(path.join(root, '.github/workflows/runtime-smoke.yml'), 'utf8'); + assert.match(workflow, /ubuntu-24\.04/); + assert.match(workflow, /libasound2t64 libgtk-3-0t64/); + const armRows = workflow.match(/os: ubuntu-22\.04-arm\n\s+platform: linux-arm64/g) || []; + assert.equal(armRows.length, 2); + const armPackages = workflow.match(/os: ubuntu-22\.04-arm\n\s+platform: linux-arm64\n\s+packages: (.*)/); + assert.ok(armPackages, 'linux-arm64 e2e package list'); + assert.equal(armPackages[1].includes('t64'), false); + assert.match(armPackages[1], /libasound2 libgtk-3-0 libxss1 libayatana-appindicator3-1/); +}); + +test('the deb depends keep the electron-builder defaults and add the tray library', () => { + const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + assert.deepEqual(pkg.build.deb.depends, DEB_DEPENDS); +}); + +test('linux e2e runs the linux lifecycle and leaves the mac lifecycle on darwin', () => { + const e2e = fs.readFileSync(path.join(root, 'scripts/electron-e2e.js'), 'utf8'); + const life = fs.readFileSync(path.join(root, 'scripts/linux-lifecycle-e2e.js'), 'utf8'); + assert.match(e2e, /process\.platform === 'darwin'/); + assert.match(e2e, /mac-lifecycle-e2e/); + assert.match(e2e, /process\.platform === 'linux'/); + assert.match(e2e, /linux-lifecycle-e2e/); + assert.match(life, /PASS Open Home/); + assert.match(life, /PASS closing the window keeps Home running/); + assert.match(life, /PASS Stop Home closes the listener/); + assert.match(life, /PASS Start Home becomes healthy/); + assert.match(life, /PASS Home system update check reaches the live controller/); + assert.match(life, /NOT EXERCISED a full System update because no newer signed release exists/); + assert.match(life, /NOT EXERCISED the owner System summary because that route needs a wallet token/); + assert.match(life, /update-controller', 'status.json'/); + assert.match(life, /__update-controller/); + assert.match(life, /PASS elastos update --check writes up_to_date/); + assert.match(life, /\.elastos-launcher', 'update-check.json'/); + assert.match(life, /PASS the tray icon is ready/); + assert.match(life, /__elastosTray/); + assert.match(life, /quit-keep-home/); + assert.match(life, /quit-stop-home/); + assert.match(life, /PASS Quit and keep Home leaves the controller running/); + assert.match(life, /PASS Quit and stop Home after reopen stops the retained Home/); + assert.equal(life.includes('waitForFunction'), false); + assert.equal(life.includes('command ${'), false); + assert.equal(life.includes('Application Support'), false); + assert.equal(life.includes('home --browser'), false); + assert.match(life, /\.local', 'share', 'elastos'/); +}); diff --git a/test/native/include/sys/prctl.h b/test/native/include/sys/prctl.h new file mode 100644 index 0000000..67612e9 --- /dev/null +++ b/test/native/include/sys/prctl.h @@ -0,0 +1,8 @@ +#ifndef PIDFD_TEST_PRCTL_H +#define PIDFD_TEST_PRCTL_H + +#define PR_SET_PDEATHSIG 1 + +int prctl(int option, unsigned long arg); + +#endif diff --git a/test/native/pidfd_obs.c b/test/native/pidfd_obs.c new file mode 100644 index 0000000..56acb4f --- /dev/null +++ b/test/native/pidfd_obs.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include +#include +#include + +#ifndef PIDFD_ALARM_LOG +#error PIDFD_ALARM_LOG is required +#endif +#ifndef PIDFD_SIGNAL_LOG +#error PIDFD_SIGNAL_LOG is required +#endif +#ifndef PIDFD_PRCTL_LOG +#error PIDFD_PRCTL_LOG is required +#endif +#ifndef PIDFD_PID_LOG +#error PIDFD_PID_LOG is required +#endif + +static void pidfd_record(const char *path, const char *line) { + FILE *file = fopen(path, "a"); + if (!file) return; + fputs(line, file); + fclose(file); +} + +static void pidfd_note_self(void) { + char line[32]; + int n = snprintf(line, sizeof line, "%ld\n", (long)getpid()); + if (n > 0) pidfd_record(PIDFD_PID_LOG, line); +} + +unsigned int pidfd_test_alarm(unsigned int seconds) { + char line[32]; + int n = snprintf(line, sizeof line, "%u\n", seconds); + if (n > 0) pidfd_record(PIDFD_ALARM_LOG, line); +#ifdef PIDFD_PASSTHROUGH_ALARM + return alarm(seconds); +#else + { + struct itimerval value; + if (seconds >= 60) seconds = 1; + memset(&value, 0, sizeof value); + value.it_value.tv_sec = seconds; + setitimer(ITIMER_REAL, &value, NULL); + } + return 0; +#endif +} + +int pidfd_test_prctl(int option, unsigned long arg) { + char line[64]; + int n = snprintf(line, sizeof line, "%d %lu\n", option, arg); + pidfd_note_self(); + if (n > 0) pidfd_record(PIDFD_PRCTL_LOG, line); + return 0; +} + +int pidfd_test_syscall(int number, ...) { + va_list args; + char line[32]; + int sig; + int n; + va_start(args, number); + if (number == 434) { + (void)va_arg(args, int); + (void)va_arg(args, int); + va_end(args); + return open("/dev/null", O_RDONLY | O_CLOEXEC); + } + if (number == 424) { + (void)va_arg(args, int); + sig = va_arg(args, int); + va_end(args); + n = snprintf(line, sizeof line, "%d\n", sig); + if (n > 0) pidfd_record(PIDFD_SIGNAL_LOG, line); + return 0; + } + va_end(args); + errno = ENOSYS; + return -1; +} diff --git a/test/runtime-gateway.test.js b/test/runtime-gateway.test.js index d471808..8b18a7c 100644 --- a/test/runtime-gateway.test.js +++ b/test/runtime-gateway.test.js @@ -1,19 +1,29 @@ const assert = require('node:assert/strict'); +const { spawn } = require('node:child_process'); const test = require('node:test'); -const { spawn } = require('node:child_process'); const { HOME_URL, binaryReplacement, createGatewaySupervisor, + controllerGateway, + confirmedControllerPid, + signalRecordedController, + openLinuxPidfd, + signalProcessGroup, isHealthOk, scrubRuntimeLog, - signalProcessGroup, + launcherLogText, + homeLaunchForPlatform, + spawnGatewayProcess, ForeignGatewayError, foreignListenerIsElastos, installedGatewayKind, FOREIGN_LISTENER_MESSAGE, LEGACY_STILL_RUNNING_MESSAGE, + HOME_UNCONFIRMED_MESSAGE, + OTHER_HOME_MESSAGE, + linuxControllerAdopt, combineHealth, listenerOwnership, localhostIsLoopback, @@ -23,6 +33,13 @@ const { procListenersFor, procNetAddress, procNetListeners, + procStatParent, + listenersFromProcSnapshot, + linuxProcessIdentity, + linuxStatStartTicks, + proveLinuxHome, + linuxControllerSignalPid, + platformAdoptsInstalledHome, } = require('../dist/main/targets/runtimeGateway'); const { uninstallRuntime } = require('../dist/main/targets/runtimeUninstall'); @@ -223,6 +240,118 @@ test('the gateway must own every localhost listener, on 127.0.0.1 and on ::1', ( assert.equal(listenerOwnership(procListenersFor(tcp, tcp6, ['socket:[4242]', 'socket:[4343]']), wants, ['::1']), 'owned'); }); +function procStat(pid, ppid, start) { + const fields = ['S', String(ppid), ...Array(17).fill('0'), String(start)]; + return `${pid} (elastos) ${fields.join(' ')}`; +} + +test('a Home controller does not own a descendant socket', () => { + const tcp = [TCP_HEADER, tcpRow('0100007F', 4242)].join('\n'); + const tcp6 = [TCP_HEADER, tcpRow(V6_LOOPBACK, 4343)].join('\n'); + const wants = ['127.0.0.1', '::1']; + assert.deepEqual(procStatParent('20 (elastos home) S 10 9'), { pid: 20, ppid: 10 }); + assert.equal(procStatParent('no-paren'), null); + assert.equal(linuxStatStartTicks(procStat(20, 10, 200)), '200'); + assert.equal(linuxStatStartTicks('20 (elastos home) S 10'), null); + assert.equal(linuxProcessIdentity(procStat(10, 1, 100), 'boot-1'), 'linux:boot-1:100'); + const child = [ + { pid: 10, ppid: 1, fdLinks: ['pipe:[1]'] }, + { pid: 20, ppid: 10, fdLinks: ['socket:[4242]', 'socket:[4343]'] }, + ]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, child), wants), 'foreign'); + const host = [{ pid: 20, ppid: 10, fdLinks: ['socket:[4242]', 'socket:[4343]'] }]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 20, host), wants), 'owned'); + const stranger = [ + { pid: 10, ppid: 1, fdLinks: [] }, + { pid: 20, ppid: 10, fdLinks: ['socket:[4242]'] }, + { pid: 30, ppid: 1, fdLinks: ['socket:[4343]'] }, + ]; + assert.equal(listenerOwnership(listenersFromProcSnapshot(tcp, tcp6, 10, stranger), wants), 'foreign'); +}); + +test('Linux Home ownership follows the controller record, not a descendant or a reused pid', () => { + const tcp = [TCP_HEADER, tcpRow('0100007F', 4242)].join('\n'); + const tcp6 = [TCP_HEADER, tcpRow(V6_LOOPBACK, 4343)].join('\n'); + const bootId = 'boot-1'; + const statusText = JSON.stringify({ + phase: 'ready', + controller_pid: 10, + controller_start: 'linux:boot-1:100', + host_pid: 20, + generation: 'abc', + }); + const lockText = JSON.stringify({ + pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + }); + const proved = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(proved && proved.controllerPid, 10); + assert.equal(linuxControllerSignalPid(proved, 'linux:boot-1:100'), 10); + assert.equal(linuxControllerSignalPid(proved, 'linux:boot-1:999'), null); + assert.equal(linuxControllerSignalPid(proved, null), null); + + const descendant = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['pipe:[1]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(descendant, null); + + const reused = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 300), + tcp, + tcp6, + }); + assert.equal(reused, null); + + const stale = proveLinuxHome({ + statusText, + lockText, + bootId, + controllerStat: procStat(10, 1, 50), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(stale, null); + + const wrongRole = proveLinuxHome({ + statusText, + lockText: JSON.stringify({ pid: 20, role: 'serve', addr: 'localhost:8090', generation: 'abc' }), + bootId, + controllerStat: procStat(10, 1, 100), + hostStatBefore: procStat(20, 10, 200), + hostFdLinks: ['socket:[4242]', 'socket:[4343]'], + hostStatAfter: procStat(20, 10, 200), + tcp, + tcp6, + }); + assert.equal(wrongRole, null); +}); + test('lsof listeners name the owner pid for IPv4, [::1], and *', () => { const out = ['p41', 'f7', 'n127.0.0.1:8090', 'f8', 'n[::1]:8090', 'p99', 'f3', 'n*:8090', 'p100', 'n127.0.0.1:9000'].join('\n'); assert.deepEqual(parseLsofListeners(out, 41), [ @@ -290,6 +419,14 @@ test('pidOwnsGatewayPort refuses when the listeners cannot be read', async () => assert.equal(await pidOwnsGatewayPort(7, ['127.0.0.1', '::1'], [], async () => [{ address: '::1', owned: true }]), true); }); +test('the health probe returns when localhost lookup does not answer', { timeout: 2000 }, async () => { + const health = await probeGatewayHealth({ + timeoutMs: 200, + lookup: () => new Promise(() => {}), + }); + assert.equal(health, null); +}); + test('the health probe asks every address localhost resolves to', async () => { const asked = []; const ok = { status: 200, body: 'OK' }; @@ -354,6 +491,57 @@ test('an OK that the started gateway does not own never opens Home', async () => assert.equal(await ready.start(), 'started'); }); +test('a gateway on 127.0.0.1:8090 is another Home and receives no signal', async () => { + const legacyLock = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090' }); + const legacyFacts = { + lockText: legacyLock, + command: '/home/user/.local/bin/elastos gateway --addr 127.0.0.1:8090', + pidAlive: () => true, + ownsSocket: (_pid, wants) => wants.length === 1 && wants[0] === '127.0.0.1', + }; + assert.equal(installedGatewayKind(legacyFacts), 'legacy'); + assert.equal(foreignListenerIsElastos(legacyFacts), false); + assert.equal(installedGatewayKind({ ...legacyFacts, lockText: JSON.stringify({ pid: 7, addr: '0.0.0.0:8090' }) }), null); + assert.equal(installedGatewayKind({ ...legacyFacts, ownsSocket: () => false }), null); + + const spawned = []; + const opened = []; + const signals = []; + const sup = createGatewaySupervisor({ + binary: '/bin/elastos', + spawn(_binary, args) { + spawned.push([...args]); + const proc = fakeProcess(50); + queueMicrotask(() => { + proc.emit('another ElastOS host already owns this data directory\n'); + proc.exit(1); + }); + return proc; + }, + fetchHealth: async () => ({ status: 200, body: 'OK', addresses: ['127.0.0.1'] }), + sleep: async () => {}, + now: () => 0, + openUrl: (url) => opened.push(url), + log: () => {}, + confirmForeign: async () => foreignListenerIsElastos(legacyFacts), + reportLegacyHome: async () => installedGatewayKind(legacyFacts) === 'legacy', + adoptInstalled: () => { + signals.push('adopt'); + return { + pid: 7, + onOutput() {}, + onExit() {}, + hasExited: () => false, + signal(sig) { signals.push(sig); }, + }; + }, + }); + await assert.rejects(() => sup.start(), (err) => err.message === OTHER_HOME_MESSAGE); + assert.deepEqual(signals, []); + assert.deepEqual(opened, []); + assert.deepEqual(spawned, [['gateway', '--addr', 'localhost:8090']]); +}); + test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and started on localhost', async () => { const legacyLock = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090' }); const legacyFacts = { @@ -363,7 +551,6 @@ test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and ownsSocket: (_pid, wants) => wants.length === 1 && wants[0] === '127.0.0.1', }; assert.equal(installedGatewayKind(legacyFacts), 'legacy'); - // Home never opens on the legacy gateway. assert.equal(foreignListenerIsElastos(legacyFacts), false); assert.equal(installedGatewayKind({ ...legacyFacts, lockText: JSON.stringify({ pid: 7, addr: '0.0.0.0:8090' }) }), null); assert.equal(installedGatewayKind({ ...legacyFacts, ownsSocket: () => false }), null); @@ -383,7 +570,7 @@ test('upgrade: a gateway an earlier launcher started on 127.0.0.1 is stopped and let mine = null; const sup = createGatewaySupervisor({ binary: '/bin/elastos', - spawn(binary, args) { + spawn(_binary, args) { spawned.push([...args]); const proc = fakeProcess(50 + spawned.length); if (legacyRunning) { @@ -596,37 +783,19 @@ test('one failed health poll while the process is alive is not a stop', async () assert.deepEqual(world.signals, ['SIGTERM', 'SIGKILL']); }); -test('signalProcessGroup uses the negative pid and surfaces a failed kill', () => { - const seen = []; - signalProcessGroup(42, 'SIGTERM', (pid, signal) => { seen.push([pid, signal]); }); - assert.deepEqual(seen, [[-42, 'SIGTERM']]); - signalProcessGroup(0, 'SIGTERM', () => { throw new Error('pid 0 must not be signaled'); }); - signalProcessGroup(-5, 'SIGTERM', () => { throw new Error('a negative pid must not be signaled'); }); - signalProcessGroup(42, 'SIGTERM', () => { - const err = new Error('gone'); - err.code = 'ESRCH'; - throw err; - }); - assert.throws( - () => signalProcessGroup(42, 'SIGKILL', () => { - const err = new Error('operation not permitted'); - err.code = 'EPERM'; - throw err; - }), - /Could not signal ElastOS \(SIGKILL\): operation not permitted/, - ); -}); - -test('signalProcessGroup kills the leader and a child in that group', async () => { - const child = spawn('bash', ['-c', 'sleep 30 & echo $!; wait'], { - detached: true, - stdio: ['ignore', 'pipe', 'pipe'], - }); +test('a process this launcher spawned is signaled through its own handle', async () => { + const proc = spawnGatewayProcess(process.execPath, ['-e', ` + const { spawn } = require('child_process'); + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); + process.stdout.write(String(child.pid)); + setInterval(() => {}, 1000); + `], 'linux'); + let grandchild = 0; try { - const grandchild = await new Promise((resolve, reject) => { + grandchild = await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('grandchild pid was not printed')), 3000); let buf = ''; - child.stdout.on('data', (chunk) => { + proc.onOutput((chunk) => { buf += chunk.toString(); const line = buf.trim(); if (/^\d+$/.test(line)) { @@ -635,33 +804,456 @@ test('signalProcessGroup kills the leader and a child in that group', async () = } }); }); - signalProcessGroup(child.pid, 'SIGTERM'); - await new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error('leader did not exit')), 3000); - child.once('exit', () => { + proc.signal('SIGTERM'); + const leaderGone = await new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), 3000); + proc.onExit(() => { clearTimeout(timer); - resolve(); + resolve(true); }); }); - // The orphaned child is reaped by init, which can take longer than a - // fixed wait on a busy machine. Poll instead of sleeping once. - const gone = () => { + assert.equal(leaderGone, true); + process.kill(grandchild, 0); + } finally { + try { if (grandchild) process.kill(grandchild, 'SIGKILL'); } catch { /* already gone */ } + try { proc.signal('SIGKILL'); } catch { /* already gone */ } + } +}); + +function controllerView(overrides = {}) { + return { + statusText: JSON.stringify({ + phase: 'ready', + controller_pid: 10, + controller_start: 'linux:boot-1:100', + host_pid: 20, + generation: 'abc', + }), + lockText: JSON.stringify({ + pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + }), + bootId: 'boot-1', + controllerStat: procStat(10, 1, 100), + exePath: '/home/user/.local/share/elastos/update-controller/runtime', + allowedExes: [ + '/home/user/.local/bin/elastos', + '/home/user/.local/share/elastos/update-controller/runtime', + ], + ...overrides, + }; +} + +const RUNTIME_EXE = '/home/user/.local/share/elastos/update-controller/runtime'; + +function signalIo(observed, delivered) { + return { + readRecord: () => observed, + readProc: () => ({ controllerStat: observed.controllerStat, exePath: observed.exePath }), + openPidfd(pid) { + return { + send(signal) { delivered.push([pid, signal]); }, + close() {}, + }; + }, + }; +} + +function refusedSignal(observed) { + const delivered = []; + assert.equal(confirmedControllerPid(observed), null); + assert.throws( + () => signalRecordedController('SIGTERM', signalIo(observed, delivered), { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(delivered, []); +} + +function errno(code) { + return Object.assign(new Error(code), { code }); +} + +function controllerKernel(replaceOn) { + let live = { birth: 100, exe: RUNTIME_EXE }; + const delivered = []; + let opens = 0; + const replace = () => { live = { birth: 999, exe: '/usr/bin/foreign' }; }; + return { + delivered, + opens: () => opens, + replace, + readRecord() { + if (replaceOn === 'after-record') replace(); + return controllerView(); + }, + readProc(pid) { + const statBirth = live.birth; + if (replaceOn === 'during-proc') replace(); + const exe = live.exe; + const snap = { controllerStat: procStat(pid, 1, statBirth), exePath: exe }; + if (replaceOn === 'after-proc') replace(); + return snap; + }, + openPidfd(pid) { + opens += 1; + const bound = { pid, birth: live.birth, exe: live.exe }; + return { + send(signal) { + if (bound.birth !== live.birth || bound.exe !== live.exe) throw errno('ESRCH'); + delivered.push({ pid: bound.pid, signal, birth: live.birth, exe: live.exe }); + }, + close() {}, + }; + }, + }; +} + +function boundController(getView, onDelivered) { + return controllerGateway( + () => getView(), + () => { + const view = getView(); + return { controllerStat: view.controllerStat, exePath: view.exePath }; + }, + (pid) => { + const bound = getView().controllerStat; + return { + send(signal) { + if (getView().controllerStat !== bound) throw errno('ESRCH'); + onDelivered(pid, signal); + }, + close() {}, + }; + }, + ); +} + +test('a controller pid reused before the first read is not signaled', () => { + refusedSignal(controllerView({ controllerStat: procStat(10, 1, 999) })); + refusedSignal(controllerView({ statusText: null })); + refusedSignal(controllerView({ statusText: 'x'.repeat((16 * 1024) + 1) })); + refusedSignal(controllerView({ + lockText: JSON.stringify({ pid: 20, role: 'gateway', addr: 'localhost:8090', generation: 'stale' }), + })); + refusedSignal(controllerView({ exePath: '/usr/bin/other' })); + refusedSignal(controllerView({ exePath: '/home/user/.local/bin/elastos (deleted)' })); + const installed = controllerView({ exePath: '/home/user/.local/bin/elastos' }); + assert.equal(confirmedControllerPid(installed), 10); +}); + +test('a controller pid reused between the check and the signal is not signaled', () => { + let observed = controllerView(); + assert.equal(confirmedControllerPid(observed), 10); + observed = controllerView({ controllerStat: procStat(10, 1, 999) }); + const kills = []; + assert.throws( + () => signalRecordedController('SIGKILL', signalIo(observed, kills), { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kills, []); + const host = []; + signalRecordedController('SIGTERM', signalIo(controllerView(), host), { pidfd: null }); + assert.deepEqual(host, [[10, 'SIGTERM']]); + assert.equal(host.some((row) => row[0] === 20 || row[0] < 0), false); +}); + +test('a controller replaced during the proc read is not signaled', () => { + const kernel = controllerKernel('during-proc'); + assert.throws( + () => signalRecordedController('SIGTERM', kernel, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kernel.delivered, []); +}); + +test('a controller replaced after the proc reads and before the signal is not signaled', () => { + const kernel = controllerKernel('after-proc'); + signalRecordedController('SIGTERM', kernel, { pidfd: null }); + assert.deepEqual(kernel.delivered, []); + assert.equal(kernel.opens(), 1); +}); + +test('a pid reused before pidfd_open fails the identity check', () => { + const kernel = controllerKernel('after-record'); + assert.throws( + () => signalRecordedController('SIGTERM', kernel, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(kernel.delivered, []); +}); + +test('escalation sends SIGKILL through the pidfd opened for SIGTERM', () => { + const kernel = controllerKernel(); + const gateway = controllerGateway(kernel.readRecord, kernel.readProc, kernel.openPidfd); + gateway.signal('SIGTERM'); + gateway.signal('SIGKILL'); + assert.equal(kernel.opens(), 1); + assert.deepEqual(kernel.delivered.map((row) => row.signal), ['SIGTERM', 'SIGKILL']); + assert.deepEqual(kernel.delivered.map((row) => row.birth), [100, 100]); + assert.deepEqual(kernel.delivered.map((row) => row.exe), [RUNTIME_EXE, RUNTIME_EXE]); +}); + +test('escalation does not signal a pid reused after SIGTERM', () => { + const kernel = controllerKernel(); + const gateway = controllerGateway(kernel.readRecord, kernel.readProc, kernel.openPidfd); + gateway.signal('SIGTERM'); + kernel.replace(); + gateway.signal('SIGKILL'); + assert.equal(kernel.opens(), 1); + assert.deepEqual(kernel.delivered, [{ pid: 10, signal: 'SIGTERM', birth: 100, exe: RUNTIME_EXE }]); +}); + +test('a missing pidfd does not signal the recorded pid', () => { + const delivered = []; + assert.throws( + () => signalRecordedController('SIGTERM', { + readRecord: () => controllerView(), + readProc: () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + openPidfd() { throw errno('ENOSYS'); }, + }, { pidfd: null }), + { message: HOME_UNCONFIRMED_MESSAGE }, + ); + assert.deepEqual(delivered, []); + if (process.platform !== 'linux') { + assert.throws(() => openLinuxPidfd(10), (err) => err.code === 'ENOSYS'); + } +}); + +test('the linux package unpacks the pidfd helper', () => { + const pkg = require('../package.json'); + assert.equal(pkg.build.asarUnpack.includes('dist/native/linux-pidfd'), true); + assert.equal(pkg.scripts['build:ts'].includes('scripts/build-linux-pidfd.js'), true); +}); + +test('the pidfd helper command is the pid and two fifo paths', { timeout: 5000 }, () => { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-client-')); + const log = path.join(dir, 'log'); + const helper = path.join(dir, 'helper'); + fs.writeFileSync(helper, `#!/bin/sh +printf '%s\\n' "$#" >> '${log}' +printf '%s\\n' "$1" >> '${log}' +exec 3>"$2" +printf '%s\\n' ready >&3 +exec 4<"$3" +while IFS= read -r line <&4; do + printf '%s\\n' "$line" >> '${log}' + case $line in + SIGTERM|SIGKILL) printf '%s\\n' sent >&3 ;; + close) exit 0 ;; + *) printf '%s\\n' 'errno EINVAL' >&3 ;; + esac +done +`, { mode: 0o755 }); + const pidfd = openLinuxPidfd(10, { helper }); + try { + pidfd.send('SIGTERM'); + pidfd.send('SIGKILL'); + } finally { + pidfd.close(); + } + const lines = fs.readFileSync(log, 'utf8').split('\n').filter(Boolean); + assert.deepEqual(lines.filter((line) => line !== 'close'), ['3', '10', 'SIGTERM', 'SIGKILL']); + assert.equal(lines.every((line) => ['3', '10', 'SIGTERM', 'SIGKILL', 'close'].includes(line)), true); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +function pidfdResources(pidFile) { + const fs = require('node:fs'); + const path = require('node:path'); + const text = fs.existsSync(pidFile) ? fs.readFileSync(pidFile, 'utf8') : ''; + const inodes = new Set(); + let helpers = 0; + let dirs = 0; + for (const line of text.split('\n')) { + const [pidText, cmd] = line.split(' '); + const pid = Number(pidText); + if (!pid || !cmd) continue; + try { + process.kill(pid, 0); + helpers += 1; + } catch { + } + const fifoDir = path.dirname(cmd); + if (fs.existsSync(fifoDir)) dirs += 1; + for (const leaf of ['cmd', 'reply']) { try { - process.kill(grandchild, 0); - return false; + const st = fs.statSync(path.join(fifoDir, leaf)); + inodes.add(`${st.dev}:${st.ino}`); } catch { - return true; } - }; - for (let waited = 0; waited < 5000 && !gone(); waited += 50) { - await new Promise((resolve) => setTimeout(resolve, 50)); } - assert.throws(() => process.kill(grandchild, 0)); + } + let fds = 0; + for (const name of fs.readdirSync('/dev/fd')) { + const fd = Number(name); + if (!Number.isInteger(fd)) continue; + try { + const st = fs.fstatSync(fd); + if (inodes.has(`${st.dev}:${st.ino}`)) fds += 1; + } catch { + // The fd closed while this scan was reading /dev/fd. + } + } + return { helpers, dirs, fds }; +} + +function releasePidfdLeak(pidFile, scriptDir) { + const fs = require('node:fs'); + const path = require('node:path'); + const text = fs.existsSync(pidFile) ? fs.readFileSync(pidFile, 'utf8') : ''; + for (const line of text.split('\n')) { + const [pidText, cmd] = line.split(' '); + const pid = Number(pidText); + if (pid) { + try { process.kill(pid, 'SIGKILL'); } catch {} + } + if (!cmd) continue; + fs.rmSync(path.dirname(cmd), { recursive: true, force: true }); + } + fs.rmSync(scriptDir, { recursive: true, force: true }); +} + +function writePidfdHelper(mode) { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-leak-')); + const helper = path.join(dir, 'helper'); + const pidFile = path.join(dir, 'pids'); + const signalArm = mode === 'timeout' + ? 'SIGTERM|SIGKILL) ;;' + : "SIGTERM|SIGKILL) printf '%s\\n' 'errno EPERM' >&3 ;;"; + fs.writeFileSync(helper, `#!/bin/sh +printf '%s %s\\n' "$$" "$3" >> '${pidFile}' +exec 3>"$2" +printf '%s\\n' ready >&3 +exec 4<"$3" +while IFS= read -r line <&4; do + case $line in + close) exit 0 ;; + ${signalArm} + *) printf '%s\\n' 'errno EINVAL' >&3 ;; + esac +done +exit 0 +`, { mode: 0o755 }); + return { helper, pidFile, dir }; +} + +async function failStopTwice(helper, pattern) { + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned'); }, + fetchHealth: async () => ({ status: 200, body: 'OK' }), + adoptInstalled: () => controllerGateway( + () => controllerView(), + () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + (pid) => openLinuxPidfd(pid, { helper }), + ), + now: () => Date.now(), + sleep: async () => {}, + openUrl() {}, + log() {}, + graceMs: 30, + pollMs: 10, + }); + await assert.rejects(() => sup.stop(), pattern); + await assert.rejects(() => sup.stop(), pattern); + assert.equal(sup.phase(), 'error'); +} + +async function waitForPidfdBaseline(pidFile, before) { + const deadline = Date.now() + 1000; + let after = pidfdResources(pidFile); + while (Date.now() < deadline) { + if (after.helpers === before.helpers && after.dirs === before.dirs && after.fds === before.fds) { + return after; + } + await new Promise((resolve) => { setTimeout(resolve, 20); }); + after = pidfdResources(pidFile); + } + return after; +} + +test('repeated Stop after a pidfd send error returns helper resources to baseline', { timeout: 10000 }, async () => { + const { helper, pidFile, dir } = writePidfdHelper('eperm'); + const before = pidfdResources(pidFile); + try { + await failStopTwice(helper, /Could not signal ElastOS \(SIGTERM\): errno EPERM/); + const after = await waitForPidfdBaseline(pidFile, before); + assert.deepEqual(after, before); } finally { - try { process.kill(-(child.pid), 'SIGKILL'); } catch { /* already gone */ } + releasePidfdLeak(pidFile, dir); + } +}); + +test('repeated Stop after a pidfd timeout returns helper resources to baseline', { timeout: 20000 }, async () => { + const { helper, pidFile, dir } = writePidfdHelper('timeout'); + const before = pidfdResources(pidFile); + try { + await failStopTwice(helper, /Could not signal ElastOS \(SIGTERM\): pidfd helper timed out/); + const after = await waitForPidfdBaseline(pidFile, before); + assert.deepEqual(after, before); + } finally { + releasePidfdLeak(pidFile, dir); } }); +test('Quit and stop after a retained Home signals only the confirmed controller', async () => { + let observed = controllerView(); + const kills = []; + const adopted = boundController(() => observed, (pid, signal) => { + kills.push([pid, signal]); + if (signal === 'SIGTERM') observed = controllerView({ controllerStat: null }); + }); + let health = { status: 200, body: 'OK' }; + let clock = 0; + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned again'); }, + fetchHealth: async () => { + if (kills.length > 0) health = null; + return health; + }, + adoptInstalled: async () => adopted, + now: () => clock, + sleep: async () => { clock += 1000; }, + openUrl() {}, + log() {}, + graceMs: 3000, + pollMs: 1000, + }); + await sup.stop(); + assert.deepEqual(kills, [[10, 'SIGTERM']]); + assert.equal(sup.phase(), 'stopped'); + sup.forceKill(); + assert.deepEqual(kills, [[10, 'SIGTERM']]); + + observed = controllerView(); + const later = []; + const again = boundController(() => observed, (pid, signal) => later.push([pid, signal])); + again.signal('SIGTERM'); + observed = controllerView({ controllerStat: procStat(10, 1, 999) }); + again.signal('SIGKILL'); + assert.deepEqual(later, [[10, 'SIGTERM']]); +}); + +test('a legacy 127.0.0.1 gateway is not a controller the launcher can signal', () => { + const legacy = JSON.stringify({ pid: 7, role: 'gateway', addr: '127.0.0.1:8090', generation: 'abc' }); + assert.equal(linuxControllerAdopt(legacy), 'other-home'); + assert.equal(linuxControllerAdopt(JSON.stringify({ + pid: 7, role: 'gateway', addr: 'localhost:8090', generation: 'abc', + })), 'controller'); + assert.equal(linuxControllerAdopt(null), 'none'); + refusedSignal(controllerView({ lockText: legacy })); +}); + test('stop does not kill a gateway this launcher did not start', async () => { const world = supervisor(); world.setHealth({ status: 200, body: 'OK' }); @@ -820,6 +1412,60 @@ test('logs omit attach secrets', async () => { assert.equal(text.includes('sekrit'), false); assert.match(text, /omitted a line/); assert.equal(scrubRuntimeLog('attach_secret=nope').includes('nope'), false); + const keep = 'Keep this terminal open. Press Ctrl+C to stop Home.\nwas replaced on disk\n'; + assert.equal(launcherLogText(keep, true).includes('Keep this terminal open'), false); + assert.match(launcherLogText(keep, true), /was replaced on disk/); + assert.match(launcherLogText(keep, false), /Keep this terminal open/); + assert.deepEqual(homeLaunchForPlatform('linux').args, ['home', '--browser']); + assert.equal(homeLaunchForPlatform('linux').quitWhenLastWindowCloses, false); + assert.equal(homeLaunchForPlatform('linux').updateRestartsHome, true); + assert.equal(homeLaunchForPlatform('linux').rollbackRestartsHome, true); + assert.equal(homeLaunchForPlatform('linux').hideTerminalKeepLine, true); + assert.equal(homeLaunchForPlatform('linux').openBrowserAfterInstall, false); + assert.equal(homeLaunchForPlatform('linux').offerKeepHomeOnQuit, true); + assert.equal(platformAdoptsInstalledHome('linux'), true); + assert.equal(platformAdoptsInstalledHome('darwin'), true); + assert.equal(platformAdoptsInstalledHome('win32'), false); + assert.deepEqual(homeLaunchForPlatform('darwin').args, ['home', '--browser']); + assert.equal(homeLaunchForPlatform('darwin').quitWhenLastWindowCloses, false); + assert.equal(homeLaunchForPlatform('darwin').updateRestartsHome, true); + assert.equal(homeLaunchForPlatform('darwin').rollbackRestartsHome, true); + assert.equal(homeLaunchForPlatform('darwin').hideTerminalKeepLine, false); + assert.equal(homeLaunchForPlatform('darwin').openBrowserAfterInstall, true); + assert.equal(homeLaunchForPlatform('darwin').offerKeepHomeOnQuit, false); + assert.deepEqual(homeLaunchForPlatform('win32').args, ['gateway', '--addr', 'localhost:8090']); + assert.equal(homeLaunchForPlatform('win32').quitWhenLastWindowCloses, true); + assert.equal(homeLaunchForPlatform('win32').updateRestartsHome, false); + assert.equal(homeLaunchForPlatform('win32').openBrowserAfterInstall, true); + assert.equal(homeLaunchForPlatform('win32').offerKeepHomeOnQuit, false); +}); + +test('a Linux supervisor log drops the terminal sentence and keeps the other lines', async () => { + const launch = homeLaunchForPlatform('linux'); + let proc; + const logs = []; + const sup = createGatewaySupervisor({ + binary: '/bin/elastos', + args: launch.args, + hideTerminalKeepLine: launch.hideTerminalKeepLine, + spawn() { + proc = fakeProcess(11); + return proc; + }, + fetchHealth: async () => { + proc.emit('Keep this terminal open. Press Ctrl+C to stop Home.\nHome: http://localhost:8090/home/\n'); + return { status: 200, body: 'OK' }; + }, + sleep: async () => {}, + now: () => 0, + openUrl() {}, + log: (line) => logs.push(line), + listenerOwned: () => true, + }); + await sup.start(); + const text = logs.join('\n'); + assert.equal(text.includes('Keep this terminal open'), false); + assert.match(text, /Home: http:\/\/localhost:8090\/home\//); }); test('uninstall removes only the runtime binary and data dir', async () => { @@ -924,3 +1570,189 @@ test('Mac adoption refuses an unproved listener without sending any signal', asy await assert.rejects(() => sup.stop(), ForeignGatewayError); assert.equal(attempts, 3, 'unknown ownership is retried only a bounded number of times'); }); + +test('signalProcessGroup uses the negative pid and surfaces a failed kill', () => { + const seen = []; + signalProcessGroup(42, 'SIGTERM', (pid, signal) => { seen.push([pid, signal]); }); + assert.deepEqual(seen, [[-42, 'SIGTERM']]); + signalProcessGroup(0, 'SIGTERM', () => { throw new Error('pid 0 must not be signaled'); }); + signalProcessGroup(-5, 'SIGTERM', () => { throw new Error('a negative pid must not be signaled'); }); + signalProcessGroup(42, 'SIGTERM', () => { + const err = new Error('gone'); + err.code = 'ESRCH'; + throw err; + }); + assert.throws( + () => signalProcessGroup(42, 'SIGKILL', () => { + const err = new Error('operation not permitted'); + err.code = 'EPERM'; + throw err; + }), + /Could not signal ElastOS \(SIGKILL\): operation not permitted/, + ); +}); + +function compileObservedPidfd(dir, passthroughAlarm) { + const fs = require('node:fs'); + const path = require('node:path'); + const { spawnSync } = require('node:child_process'); + const helper = path.join(dir, 'linux-pidfd'); + const alarmLog = path.join(dir, 'alarm'); + const signalLog = path.join(dir, 'signals'); + const prctlLog = path.join(dir, 'prctl'); + const pidLog = path.join(dir, 'pid'); + const include = path.join(__dirname, 'native/include'); + const source = path.join(__dirname, '../src/native/linux-pidfd.c'); + const obs = path.join(__dirname, 'native/pidfd_obs.c'); + const quote = (file) => file.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + const compile = (args) => { + const result = spawnSync('cc', args, { encoding: 'utf8' }); + if (result.status !== 0) { + throw new Error(result.stderr || result.stdout || 'cc failed'); + } + }; + compile([ + '-Wall', '-Wextra', '-Werror', '-Wno-deprecated-declarations', '-O2', + '-I', include, + '-Dalarm=pidfd_test_alarm', + '-Dprctl=pidfd_test_prctl', + '-Dsyscall=pidfd_test_syscall', + '-c', source, '-o', path.join(dir, 'helper.o'), + ]); + compile([ + '-Wall', '-Wextra', '-Werror', '-O2', + ...(passthroughAlarm ? ['-DPIDFD_PASSTHROUGH_ALARM'] : []), + `-DPIDFD_ALARM_LOG="${quote(alarmLog)}"`, + `-DPIDFD_SIGNAL_LOG="${quote(signalLog)}"`, + `-DPIDFD_PRCTL_LOG="${quote(prctlLog)}"`, + `-DPIDFD_PID_LOG="${quote(pidLog)}"`, + '-c', obs, '-o', path.join(dir, 'obs.o'), + ]); + compile([path.join(dir, 'helper.o'), path.join(dir, 'obs.o'), '-o', helper]); + return { helper, alarmLog, signalLog, prctlLog, pidLog }; +} + +function releaseObservedPidfd(dir, pidLog) { + const fs = require('node:fs'); + const text = pidLog && fs.existsSync(pidLog) ? fs.readFileSync(pidLog, 'utf8') : ''; + for (const line of text.split('\n')) { + const pid = Number(line); + if (pid) { + try { process.kill(pid, 'SIGKILL'); } catch {} + } + } + fs.rmSync(dir, { recursive: true, force: true }); +} + +test('Stop still sends SIGKILL on the same pidfd when health outlasts the idle alarm', { timeout: 10000 }, async () => { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'pidfd-idle-')); + let built = null; + let phase = 'adopt'; + let waited = false; + let err = null; + try { + built = compileObservedPidfd(dir, false); + const sup = createGatewaySupervisor({ + binary: '/home/tester/.local/bin/elastos', + args: ['home', '--browser'], + adoptForControls: true, + spawn() { throw new Error('a retained Home is not spawned'); }, + fetchHealth: async () => { + if (phase === 'wait' && !waited) { + waited = true; + await new Promise((resolve) => setTimeout(resolve, 2000)); + } + return { status: 200, body: 'OK' }; + }, + adoptInstalled: () => controllerGateway( + () => controllerView(), + () => ({ controllerStat: procStat(10, 1, 100), exePath: RUNTIME_EXE }), + (pid) => { + const pidfd = openLinuxPidfd(pid, { helper: built.helper }); + return { + send(signal) { + pidfd.send(signal); + if (signal === 'SIGTERM') phase = 'wait'; + }, + close() { pidfd.close(); }, + }; + }, + ), + now: () => Date.now(), + sleep: async () => {}, + openUrl() {}, + log() {}, + graceMs: 30, + pollMs: 1, + }); + try { + await sup.stop(); + } catch (caught) { + err = caught; + } + assert.equal(fs.readFileSync(built.signalLog, 'utf8'), '15\n9\n'); + assert.equal(fs.readFileSync(built.alarmLog, 'utf8'), '2\n0\n'); + assert.equal(fs.readFileSync(built.prctlLog, 'utf8'), '1 9\n'); + assert.match(String(err && err.message), /still running/); + const helperPid = Number(fs.readFileSync(built.pidLog, 'utf8')); + let helperGone = false; + for (let i = 0; i < 50; i += 1) { + try { + process.kill(helperPid, 0); + } catch { + helperGone = true; + break; + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert.equal(helperGone, true); + } finally { + releaseObservedPidfd(dir, built && built.pidLog); + } +}); + +test('signalProcessGroup kills the leader and a child in that group', async () => { + const child = spawn('bash', ['-c', 'sleep 30 & echo $!; wait'], { + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + }); + try { + const grandchild = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('grandchild pid was not printed')), 3000); + let buf = ''; + child.stdout.on('data', (chunk) => { + buf += chunk.toString(); + const line = buf.trim(); + if (/^\d+$/.test(line)) { + clearTimeout(timer); + resolve(Number(line)); + } + }); + }); + signalProcessGroup(child.pid, 'SIGTERM'); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('leader did not exit')), 3000); + child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + const gone = () => { + try { + process.kill(grandchild, 0); + return false; + } catch { + return true; + } + }; + for (let waited = 0; waited < 5000 && !gone(); waited += 50) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } + assert.throws(() => process.kill(grandchild, 0)); + } finally { + try { process.kill(-(child.pid), 'SIGKILL'); } catch { /* already gone */ } + } +}); diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index 397ceed..e959ee1 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -197,6 +197,75 @@ test('Mac Update stops Home, runs the update and starts the current binary even assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); }); +test('Linux Update stops Home, runs the update, and starts the current binary even after failure', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const probe = require('../dist/main/targets/runtimeProbe'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(probe, 'findRuntimeBinary', () => '/installed/elastos'); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, start: async () => { calls.push('start-current-binary'); }, + })); + let fail = false; + t.mock.method(updates, 'applyRuntimeUpdate', async () => { + calls.push('update'); + if (fail) throw new Error('update failed'); + }); + const target = createRuntimeTarget('linux'); + await target.update(); + assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); + calls.length = 0; + fail = true; + await assert.rejects(() => target.update(), /update failed/); + assert.deepEqual(calls, ['stop', 'update', 'start-current-binary']); +}); + +test('Linux Undo stops Home, restores the release, and starts Home again', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const probe = require('../dist/main/targets/runtimeProbe'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(probe, 'findRuntimeBinary', () => '/installed/elastos'); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, + start: async () => { calls.push('start-current-binary'); }, + })); + t.mock.method(updates, 'rollbackRuntime', async () => { calls.push('rollback'); }); + await createRuntimeTarget('linux').rollback(() => {}); + assert.deepEqual(calls, ['stop', 'rollback', 'start-current-binary']); +}); + +test('Mac Undo stops Home, restores the release, and starts Home again', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const probe = require('../dist/main/targets/runtimeProbe'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(probe, 'findRuntimeBinary', () => '/installed/elastos'); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, + start: async () => { calls.push('start-current-binary'); }, + })); + t.mock.method(updates, 'rollbackRuntime', async () => { calls.push('rollback'); }); + await createRuntimeTarget('darwin', 'arm64').rollback(() => {}); + assert.deepEqual(calls, ['stop', 'rollback', 'start-current-binary']); +}); + +test('Windows Update does not stop or start Home around the command', async (t) => { + const gateway = require('../dist/main/targets/runtimeGateway'); + const updates = require('../dist/main/targets/runtimeUpdate'); + const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + const calls = []; + t.mock.method(gateway, 'createDefaultGatewaySupervisor', () => ({ + stop: async () => { calls.push('stop'); }, start: async () => { calls.push('start'); }, + })); + t.mock.method(updates, 'applyRuntimeUpdate', async () => { calls.push('update'); }); + await createRuntimeTarget('win32').update(); + assert.deepEqual(calls, ['update']); +}); + test('Runtime 2.0.0 gets the #61 status record only after a successful check and signed head verification', async () => { const fixture = require('./helpers/signed-release'); const { writeSignedUpdateCheck } = require('../dist/main/targets/runtimeUpdate');