diff --git a/AGENTS.md b/AGENTS.md index a9c66cc5..8058affa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,10 +21,11 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `include/webfront/weblink/`: bridge message encoding and routing. - `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together). - `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters. -- `examples/`: only Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). +- `examples/`: the default build includes Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). The standalone [PTY example](docs/PTY.md) has its own CMake entry point. - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. - `js/developer/starters/`: the sources of the `app` starter and `agent-guide.md`, the `AGENTS.md` that `wf create` puts beside a starter and that `webfront_write_agent_guide()` (`cmake/WebFrontAgentGuide.cmake`) writes in a consuming project. - `js/services/`: optional `@webfront/services` package, the browser side of the system services (ADR-020; a skeleton so far), built like `@webfront/react` by `wf run services-package`; outside the core's embedded resource list. +- `js/pty/`: optional `@webfront/pty` adapter for native pseudoterminals. `wf run pty-package` assembles the archive used by the browser tests. See `docs/PTY.md`. - `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list. - `test/fixtures/`, `test/web/fixtures/`: retained regression fixtures, not public example applications. - `test/unit/`: C++ unit tests, written with `test/unit/Bdd.hpp` (a single-header BDD framework); `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. @@ -116,7 +117,7 @@ Exception: a purely C++ change that reuses an existing encoding, introduces no n ## Coding and testing conventions - Use C++23, four-space indentation, the `.clang-format` of the directory (`include/webfront/`, `test/`, `examples/`), and the naming rules in `.github/CONTRIBUTING.md`. -- Keep production implementation header-only under `include/`; `examples/` contains the three public examples; browser resources live in `js/`. +- Keep production implementation header-only under `include/`; browser resources live in `js/`. - Prefer standard-library facilities and explicit ownership. Keep public headers ODR-safe (`inline`/templates as appropriate). - Unit tests are named `const Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check` (`test/unit/Bdd.hpp`), and use deterministic mocks. - Jasmine specs are the project `test/web/suite/`, built by esbuild-wasm and run by `wf test` under the locked `jasmine-core` (installed from the local registry by `WebSuiteInstall`); `webtest` is the `webfront-wf` driver plus the C++ callbacks of the specs. The specs tell C++ they are done (`specsFinished`), the process status is that of `wf test` (or 1 when C++ did not observe every call), and the CTest case has a timeout. The registry the suite installs from is built by `wf run test-registry` (the `TestRegistry` case), from the packages that configure downloaded. diff --git a/README.fr.md b/README.fr.md index a79202f7..71fe0b4c 100644 --- a/README.fr.md +++ b/README.fr.md @@ -456,6 +456,7 @@ L'installation de CMake elle-même ne demande pas de droits root. Répétez l'ex - Les appels JavaScript vers C++ renvoient toujours des Promises. En C++, `ui.jsFunction(name)(...)` est sans retour ; `ui.jsFunction(name)(...)` renvoie un `std::future`. Fonction absente, exception, réponse mal formée et déconnexion font échouer l'appel typé. Les futures et Promises n'exposent pas d'annulation ; les senders typés proposent une annulation locale. - Le pont transporte scalaires, chaînes, tuples, tableaux numériques typés, bitsets et listes homogènes de valeurs composées prises en charge. Il ne transporte pas d'objets arbitraires. Chaînes et messages sont bornés par la politique de taille (64 Mio par défaut) ; à partir de 65 536 octets, les chaînes utilisent l'encodage long. - L'environnement de développement et l'accès aux fichiers du projet sont destinés au code local de confiance, sans sandbox. Seuls les paquets compatibles navigateur sont pris en charge ; ni scripts d'installation ni extensions natives ne sont exécutés. `wf check` vérifie les types séparément de la compilation. +- Le [pseudo-terminal natif](docs/PTY.md) relie un programme choisi par l’application à xterm.js sous Linux, macOS et Windows, après activation explicite. - L'adaptateur optionnel [`@webfront/react`](docs/REACT.md) apporte stores C++ avec regroupement des mises à jour et îlots React. `WebFrontLifeReact` montre un panneau C++ dans React ; son archive est préparée localement pour publication au registre. - Linux embarqué dispose d'une CI ARM64 et de preuves sur Orin Nano. Les autres cartes, cibles sans OS et microcontrôleurs ne sont pas qualifiés globalement. Le transport local ne fournit ni TLS ni authentification client ; un accès distant demande une conception de sécurité propre à l'application. - Packaging, accessibilité et déploiement des moteurs natifs restent propres au produit. L'[état du projet](docs/PROJECT_STATUS.md) fait référence pour les validations et limites ; l'[historique](docs/CHANGELOG.md) décrit les migrations et ruptures de compatibilité. diff --git a/README.md b/README.md index fea5ac0f..33bbc334 100644 --- a/README.md +++ b/README.md @@ -524,6 +524,7 @@ CI exercises C++ and native-browser paths on Windows, macOS and Linux. Extended - JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction(name)(...)` returns `std::future`. Missing functions, exceptions, malformed replies and disconnects fail the typed call. - The binary bridge supports scalars, strings, tuples, numeric typed arrays, packed bitsets and homogeneous lists of supported compound values. Arbitrary objects do not cross it. Strings and messages are bounded by the message-size policy (64 MiB by default); strings of 65,536 bytes or more use the long-string encoding. See [the bridge contract](docs/adr/ADR-003-protocole-binaire-et-bornes.md). - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. +- An opt-in [native pseudoterminal](docs/PTY.md) connects an application-selected program to xterm.js on Linux, macOS and Windows. - The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication. - Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. The default local transport supplies neither TLS nor client authentication; remote deployment needs an application-specific security design. - Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c5f00b09..d8f02c04 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,7 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased ### Added +- Run application-selected programs in a native pseudoterminal with an optional xterm.js page adapter and replay across reloads (#613, `docs/PTY.md`). - Skip GStreamer's initialization, and its plugin scan, in WebKitGTK for an application whose pages never use audio or video, with `WindowOptions::media = false`; the default keeps media (#611, `docs/WEBKITGTK.md`). - WKWebView supports `WindowOptions::background`, translucent colours included, and `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WKWEBVIEW.md`). - WebView2 supports `WindowOptions::background` and `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBVIEW2.md`). diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 67a3a880..53821250 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -27,6 +27,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer system browser, `app.requestClose()` from another thread, or `webfront::UIThread` where the frontend accepts a secondary thread (WebView2); a host loop cannot share the main thread with an embedded window. See [host integration](HOST_INTEGRATION.md). +- **Native pseudoterminals (opt-in).** `webfront::Pty` uses a Unix PTY on Linux and macOS or ConPTY on Windows 10 version 1809 and later. The page adapter requires a loopback bind and the application’s own browser origin. See the [PTY guide and standalone example](PTY.md). - **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `why`, `info` and `help`, beside the terminal's own read-only `ls`, `cat`, `tree` and `mounts` (ADR-023). The manifest and lock describe @@ -40,7 +41,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer Native-engine deployment remains application work. The [README walkthrough](../README.md) covers the console, developer and embedded Game of Life stages; Hello World and the host loop (`examples/host-loop/`, a Boing Ball ray-traced by the host on the CPU or with optional CUDA; see - [the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are the other public examples. + [the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are also in the default build. - **Developer automation (opt-in).** `webfront-agent` provides local stdio MCP and a JSON CLI for an explicitly launched developer window. Native grants select check/build/test/preview, bounded inspection and semantic actions. [Automation](AUTOMATION.md) documents provisioning, diff --git a/docs/PTY.md b/docs/PTY.md new file mode 100644 index 00000000..5a6a8adb --- /dev/null +++ b/docs/PTY.md @@ -0,0 +1,46 @@ +# Native pseudoterminals + +Include `` to run a program in a native terminal from C++. The child receives the requested argument vector, working directory, environment and initial terminal dimensions. Linux and macOS use a Unix PTY. Windows uses ConPTY, available since Windows 10 version 1809 and Windows Server 2019. [Microsoft's ConPTY documentation](https://learn.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session) + +```cpp +webfront::Pty terminal({ + .argv = {"sh", "-i"}, + .directory = "/path/to/project", + .environment = {{"PATH", "/usr/bin:/bin"}}, + .size = {100, 32} +}); +``` + +Use UTF-8 strings for arguments and environment entries. The environment comes from `PtyOptions::environment`, with defaults for `TERM` (`xterm-256color`), `COLORTERM` (`truecolor`) and Windows `SystemRoot`. Supply any other variables the program needs, such as `HOME`, `USERPROFILE` or `PATH`. Relative paths are resolved against the child's directory. Bare executable names are searched in the supplied `PATH` or, when it is absent, in `/usr/bin:/bin` on Unix and the system directory on Windows. Windows also resolves `.cmd` and `.bat` shims and runs them through the system `cmd.exe`. Paths and arguments passed to batch scripts must omit double quotes, percent signs and line breaks. + +- `write(bytes)` queues a whole chunk if there is room. It returns `false` immediately when the 64 KiB queue is full, the chunk exceeds capacity or the terminal is closing. +- `read(cursor, stopToken)` waits for data, exit, cancellation or hangup. `tryRead(cursor)` takes a snapshot without waiting for terminal I/O. Start at cursor zero and use the returned `next` for the following read. Each snapshot contains at most 16 KiB. `truncated` means the cursor fell behind the latest 1 MiB of retained output. The final snapshot carries the exit code. +- `resize({columns, rows})` schedules a resize on the terminal worker. Consecutive requests may be coalesced. +- `hangUp()` wakes readers and requests cleanup. `exitCode()` becomes available after cleanup. Destruction joins the worker. On Unix, cleanup signals the child and the foreground process group with SIGHUP and then escalates to SIGKILL. The host must leave the PTY child available for WebFront to reap. Cleanup also looks for remaining processes in the same session, including after the session leader exits. A process that creates a separate session may outlive it. On Linux with pidfds, cleanup uses a stable reference when signalling a member of a secondary group. Other Unix configurations check session and process group membership immediately before signalling by PID. On Windows, a job object terminates the entire process tree and ConPTY is closed. Ctrl+C follows the child console mode and the Windows control-handler policy. If the host was launched with Ctrl+C ignored, a child can inherit that setting. The example enables normal processing for its own process with `SetConsoleCtrlHandler(nullptr, FALSE)` before launch. + +After natural exit, the worker drains terminal output to EOF or until a three-second deadline when another process holds the terminal open. Unix waits on the terminal and a wake pipe, with a 250 ms backstop for child exit. Windows checks its output pipe every 40 ms while idle and every 10 ms when input is pending or final output is draining. ConPTY keeps accepting output from descendants until its job empties or the drainage deadline expires. The launch pipe closes on exec. On Unix, coordinate host forks that retain inherited descriptors with PTY startup. A concurrent child that keeps the writer open can cause the PTY launch to fail at the ten-second startup deadline. + +## Connect a browser page + +Set `WebFrontConfig::allowPtyPages = true` and call `webfront::registerPtyPage(app, options)` from `` before starting the server. Use a literal IPv4 loopback address or `::1` and set `contentPolicy.allowMissingOrigin = false`. Leave `allowAnyBridgeOrigin` disabled and `bridgeAllowedOrigins` empty. WebFront rejects incompatible configurations before binding. The application configures the executable, directory and environment. A dedicated worker starts the native process, so its startup wait leaves the server available. A page can open the configured session, send terminal input, resize, read output or hang up. + +Every page of that origin shares access to the registered terminal. Serve trusted content and keep the loopback port private to the local application. A local native client can supply its own `Origin` header, and forwarding the port can extend access beyond the local machine. The terminal runs with the host application's privileges. + +Bundle [the adapter](../js/pty/index.mjs) from the `@webfront/pty` package with your page and call `mount(element, {terminal, fit})` with your xterm.js `Terminal` and `FitAddon`. The adapter writes byte chunks to xterm so UTF-8 sequences can span reads. It forwards input and resizes the PTY when the container changes size. `onError` reports a rejected input or bridge failure, `onExit` receives the process status and `onTruncated` reports when some history has expired. The adapter rejects paste events that exceed the 64 KiB browser input queue, measured in UTF-8 bytes and reduced by pending input. If the native queue fills, the adapter reports the rejection and discards unsent input. The child may already have received earlier chunks. + +Each registration owns one session, opened on first attach and retained across page reloads, including after the child exits. Pass `restart: true` to `mount` to start a fresh session after the old process has finished. The old replay is discarded and pending calls for the old session are refused. A different callback name selects another application-configured session. Call `dispose()` when unmounting the adapter to stop its output requests and listeners. Call `hangUp()` to close the process. Application shutdown also closes the process. The adapter keeps one output request pending, for up to one second while idle. The server checks for output every 40 ms during that wait, in addition to the native worker and bridge latency. Reattachment replays the retained bytes, so after truncation a full-screen program may need to redraw. + +Prepare a publishable `@webfront/pty` archive with `wf run pty-package` from the repository developer project. The example below uses the same adapter source directly. + +## Run the example + +The [standalone example](../examples/pty/) opens the system shell in the application's working directory. Run the following commands from the repository root in a POSIX shell with the WebFront developer environment available for the `wf` commands. + +```sh +cmake -S examples/pty -B build-pty-example -DWEBFRONT_AUTODETECT_NATIVE=OFF +cmake --build build-pty-example +(cd build-pty-example/page && wf restore && wf build) +./build-pty-example/WebFrontPtyExample build-pty-example/page/.webfront/developer/build +``` + +CMake stages the browser sources, pinned packages and adapter in `build-pty-example/page`. On Windows, pass the same build output directory to `WebFrontPtyExample.exe` in the chosen CMake configuration's output directory. diff --git a/docs/adr/ADR-010-composants-et-outils-optionnels.md b/docs/adr/ADR-010-composants-et-outils-optionnels.md index 5e1b79a0..796e2ad8 100644 --- a/docs/adr/ADR-010-composants-et-outils-optionnels.md +++ b/docs/adr/ADR-010-composants-et-outils-optionnels.md @@ -88,7 +88,8 @@ personnalisés des services ([ADR-020](ADR-020-services-systeme.md)) s'y ajouter `wf run services-package` écrivent une archive déterministe (`js/developer/scripts/package-archive.mjs`) et son SHA-512 ; le registre de test sert ces mêmes octets, et la suite installe puis importe l'archive. Aucun de ces paquets n'entre dans les ressources du cœur (`MinimalCoreAssets` inchangé) ; la publication reste une action de -mainteneur distincte. +mainteneur distincte. `@webfront/pty` (#613) suit le même modèle avec `wf run pty-package`. +Son adaptateur reçoit les instances de xterm.js et de FitAddon de l’application. ## Prescriptions d’implémentation et de génération de code diff --git a/examples/pty/.gitignore b/examples/pty/.gitignore new file mode 100644 index 00000000..c8b34ef7 --- /dev/null +++ b/examples/pty/.gitignore @@ -0,0 +1 @@ +/terminal.mjs diff --git a/examples/pty/CMakeLists.txt b/examples/pty/CMakeLists.txt new file mode 100644 index 00000000..a330a639 --- /dev/null +++ b/examples/pty/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.31) +project(WebFrontPtyExample LANGUAGES CXX) + +add_subdirectory(../.. webfront) +add_executable(WebFrontPtyExample main.cpp) +target_link_libraries(WebFrontPtyExample PRIVATE WebFront::WebFront) + +# Stage a complete wf project in the build tree, with the maintained adapter. +foreach(file IN ITEMS main.mjs webfront.project.json webfront-packages.lock.json) + configure_file("${file}" "page/${file}" COPYONLY) +endforeach() +configure_file("../../js/pty/index.mjs" "page/terminal.mjs" COPYONLY) diff --git a/examples/pty/main.cpp b/examples/pty/main.cpp new file mode 100644 index 00000000..b27495c9 --- /dev/null +++ b/examples/pty/main.cpp @@ -0,0 +1,39 @@ +#include +#include +#ifdef _WIN32 + #include +#endif + +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "Usage: WebFrontPtyExample \n"; + return 1; + } + +#ifdef _WIN32 + // This executable opts its shell children into the Windows console's Ctrl+C processing. + ::SetConsoleCtrlHandler(nullptr, FALSE); +#endif + webfront::PtyOptions shell{ + .argv = + { +#ifdef _WIN32 + "cmd.exe", "/d" +#else + "/bin/sh", + "-i" +#endif + }, + .directory = std::filesystem::current_path(), + .environment = {}, + .size = {} + }; + if (const char* path = std::getenv("PATH")) + shell.environment.emplace("PATH", path); + webfront::WebFront app({.documentRoot = argv[1], .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true}); + webfront::registerPtyPage(app, std::move(shell)); + app.show(); +} diff --git a/examples/pty/main.mjs b/examples/pty/main.mjs new file mode 100644 index 00000000..0c350e26 --- /dev/null +++ b/examples/pty/main.mjs @@ -0,0 +1,47 @@ +import { Terminal } from '@xterm/xterm'; +import { FitAddon } from '@xterm/addon-fit'; +import '@xterm/xterm/css/xterm.css'; +import { mount } from './terminal.mjs'; + +document.body.style.margin = '0'; +const element = document.createElement('main'); +element.style.height = 'calc(100dvh - 2rem)'; +const close = document.createElement('button'); +close.textContent = 'Hang up'; +const status = document.createElement('output'); +status.setAttribute('aria-live', 'polite'); +document.body.replaceChildren(element, close, status); +close.disabled = true; + +let terminal; +async function start(restart = false) { + close.disabled = true; + close.textContent = 'Hang up'; + status.textContent = ''; + terminal?.dispose(); + try { + terminal = new Terminal({ cursorBlink: true }); + const session = await mount(element, { + terminal, fit: new FitAddon(), restart, + onError: error => { status.textContent = error.message; }, + onExit: code => { + close.disabled = false; + close.textContent = 'Start again'; + close.onclick = () => { void start(true); }; + status.textContent = ` Process exited (${code})`; + }, + onTruncated: () => { status.textContent = ' Showing the latest terminal output'; }, + }); + close.disabled = false; + close.onclick = async () => { + close.disabled = true; + try { await session.hangUp(); } + catch (error) { status.textContent = error.message; } + }; + terminal.focus(); + } catch (error) { + status.textContent = error.message; + } +} + +void start(); diff --git a/examples/pty/webfront-packages.lock.json b/examples/pty/webfront-packages.lock.json new file mode 100644 index 00000000..a864c46d --- /dev/null +++ b/examples/pty/webfront-packages.lock.json @@ -0,0 +1,342 @@ +{ + "format": 1, + "manifestDigest": "bc5ef6827171f5e135ef392a20348607f17771b484d0fb593fd5544bac567fa8", + "registry": "https://registry.npmjs.org/", + "roots": { + "@xterm/addon-fit": { + "requested": "0.11.0", + "id": "@xterm+addon-fit@0.11.0" + }, + "@xterm/xterm": { + "requested": "6.0.0", + "id": "@xterm+xterm@6.0.0" + } + }, + "packages": { + "@xterm+addon-fit@0.11.0": { + "name": "@xterm/addon-fit", + "version": "0.11.0", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "key": "@xterm+addon-fit@0.11.0-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo-vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g", + "manifest": { + "name": "@xterm/addon-fit", + "version": "0.11.0", + "author": { + "name": "The xterm.js authors", + "url": "https://xtermjs.org/" + }, + "main": "lib/addon-fit.js", + "module": "lib/addon-fit.mjs", + "types": "typings/addon-fit.d.ts", + "repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit", + "license": "MIT", + "keywords": [ + "terminal", + "xterm", + "xterm.js" + ], + "scripts": { + "build": "../../node_modules/.bin/tsc -p .", + "prepackage": "npm run build", + "package": "../../node_modules/.bin/webpack", + "prepublishOnly": "npm run package", + "start": "node ../../demo/start" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" + }, + "files": [ + "LICENSE", + "README.md", + "lib/addon-fit.js", + "lib/addon-fit.js.map", + "lib/addon-fit.mjs", + "lib/addon-fit.mjs.map", + "package.json", + "src/FitAddon.ts", + "typings/addon-fit.d.ts" + ], + "dependencies": {} + }, + "@xterm+xterm@6.0.0": { + "name": "@xterm/xterm", + "version": "6.0.0", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "key": "@xterm+xterm@6.0.0-TQwDdQGtwwDt-2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc_Zgc5kq5omJ-V0a8_kIM2WD3sMOYg", + "manifest": { + "name": "@xterm/xterm", + "description": "Full xterm terminal, in your browser", + "version": "6.0.0", + "main": "lib/xterm.js", + "module": "lib/xterm.mjs", + "style": "css/xterm.css", + "types": "typings/xterm.d.ts", + "repository": "https://github.com/xtermjs/xterm.js", + "license": "MIT", + "workspaces": [ + "addons/*" + ], + "keywords": [ + "cli", + "command-line", + "console", + "pty", + "shell", + "ssh", + "styles", + "terminal-emulator", + "terminal", + "tty", + "vt100", + "webgl", + "xterm" + ], + "scripts": { + "setup": "npm run build", + "start": "node demo/start", + "build": "npm run tsc", + "watch": "npm run tsc-watch", + "tsc": "tsc -b ./tsconfig.all.json", + "tsc-watch": "tsc -b -w ./tsconfig.all.json --preserveWatchOutput", + "esbuild": "node bin/esbuild_all.mjs", + "esbuild-watch": "node bin/esbuild_all.mjs --watch", + "esbuild-package": "node bin/esbuild_all.mjs --prod", + "esbuild-package-watch": "node bin/esbuild_all.mjs --prod --watch", + "esbuild-package-headless-only": "node bin/esbuild.mjs --prod --headless", + "esbuild-demo": "node bin/esbuild.mjs --demo-client", + "esbuild-demo-watch": "node bin/esbuild.mjs --demo-client --watch", + "test": "npm run test-unit", + "posttest": "npm run lint", + "lint": "eslint -c .eslintrc.json --max-warnings 0 --ext .ts src/ addons/", + "lint-fix": "eslint -c .eslintrc.json --fix --ext .ts src/ addons/", + "lint-api": "eslint --no-eslintrc -c .eslintrc.json.typings --max-warnings 0 --no-ignore --ext .d.ts typings/", + "test-unit": "node ./bin/test_unit.js", + "test-unit-coverage": "node ./bin/test_unit.js --coverage", + "test-unit-dev": "cross-env NODE_PATH='./out' mocha", + "test-integration": "node ./bin/test_integration.js --workers=75%", + "test-integration-chromium": "node ./bin/test_integration.js --workers=75% \"--project=ChromeStable\"", + "test-integration-firefox": "node ./bin/test_integration.js --workers=75% \"--project=FirefoxStable\"", + "test-integration-webkit": "node ./bin/test_integration.js --workers=75% \"--project=WebKit\"", + "test-integration-debug": "node ./bin/test_integration.js --workers=1 --headed --timeout=30000", + "benchmark": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json", + "benchmark-baseline": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --baseline out-test/benchmark/*benchmark.js", + "benchmark-eval": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --eval out-test/benchmark/*benchmark.js", + "clean": "rm -rf lib out addons/*/lib addons/*/out", + "vtfeatures": "node bin/extract_vtfeatures.js src/**/*.ts src/*.ts", + "prepackage": "npm run build", + "package": "webpack", + "postpackage": "npm run esbuild-package", + "prepackage-headless": "npm run esbuild-package-headless-only", + "package-headless": "webpack --config ./webpack.config.headless.js", + "postpackage-headless": "node ./bin/package_headless.js", + "prepublishOnly": "npm run package" + }, + "devDependencies": { + "@lunapaint/png-codec": "^0.2.0", + "@playwright/test": "^1.37.1", + "@stylistic/eslint-plugin": "^2.3.0", + "@types/chai": "^4.2.22", + "@types/debug": "^4.1.7", + "@types/deep-equal": "^1.0.1", + "@types/express": "4", + "@types/express-ws": "^3.0.1", + "@types/jsdom": "^16.2.13", + "@types/mocha": "^9.0.0", + "@types/node": "^18.16.0", + "@types/trusted-types": "^1.0.6", + "@types/utf8": "^3.0.0", + "@types/webpack": "^5.28.0", + "@types/ws": "^8.2.0", + "@typescript-eslint/eslint-plugin": "^6.2.00", + "@typescript-eslint/parser": "^6.2.00", + "chai": "^4.3.4", + "cross-env": "^7.0.3", + "deep-equal": "^2.0.5", + "esbuild": "~0.25.2", + "eslint": "^8.56.0", + "eslint-plugin-jsdoc": "^46.9.1", + "express": "^4.19.2", + "express-ws": "^5.0.2", + "jsdom": "^18.0.1", + "mocha": "^10.1.0", + "mustache": "^4.2.0", + "node-pty": "1.1.0-beta19", + "nyc": "^15.1.0", + "source-map-loader": "^3.0.0", + "source-map-support": "^0.5.20", + "ts-loader": "^9.3.1", + "typescript": "5.5", + "utf8": "^3.0.0", + "webpack": "^5.61.0", + "webpack-cli": "^4.9.1", + "ws": "^8.2.3", + "xterm-benchmark": "^0.3.1" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" + }, + "files": [ + "LICENSE", + "README.md", + "css/xterm.css", + "lib/xterm.js", + "lib/xterm.js.map", + "lib/xterm.mjs", + "lib/xterm.mjs.map", + "package.json", + "src/browser/AccessibilityManager.ts", + "src/browser/Clipboard.ts", + "src/browser/ColorContrastCache.ts", + "src/browser/CoreBrowserTerminal.ts", + "src/browser/Linkifier.ts", + "src/browser/LocalizableStrings.ts", + "src/browser/OscLinkProvider.ts", + "src/browser/RenderDebouncer.ts", + "src/browser/TimeBasedDebouncer.ts", + "src/browser/Types.ts", + "src/browser/Viewport.ts", + "src/browser/decorations/BufferDecorationRenderer.ts", + "src/browser/decorations/ColorZoneStore.ts", + "src/browser/decorations/OverviewRulerRenderer.ts", + "src/browser/input/CompositionHelper.ts", + "src/browser/input/Mouse.ts", + "src/browser/input/MoveToCell.ts", + "src/browser/public/Terminal.ts", + "src/browser/renderer/dom/DomRenderer.ts", + "src/browser/renderer/dom/DomRendererRowFactory.ts", + "src/browser/renderer/dom/WidthCache.ts", + "src/browser/renderer/shared/Constants.ts", + "src/browser/renderer/shared/RendererUtils.ts", + "src/browser/renderer/shared/SelectionRenderModel.ts", + "src/browser/renderer/shared/Types.ts", + "src/browser/selection/SelectionModel.ts", + "src/browser/selection/Types.ts", + "src/browser/services/CharSizeService.ts", + "src/browser/services/CharacterJoinerService.ts", + "src/browser/services/CoreBrowserService.ts", + "src/browser/services/LinkProviderService.ts", + "src/browser/services/MouseService.ts", + "src/browser/services/RenderService.ts", + "src/browser/services/SelectionService.ts", + "src/browser/services/Services.ts", + "src/browser/services/ThemeService.ts", + "src/browser/shared/Constants.ts", + "src/common/CircularList.ts", + "src/common/Clone.ts", + "src/common/Color.ts", + "src/common/CoreTerminal.ts", + "src/common/InputHandler.ts", + "src/common/MultiKeyMap.ts", + "src/common/Platform.ts", + "src/common/SortedList.ts", + "src/common/TaskQueue.ts", + "src/common/TypedArrayUtils.ts", + "src/common/Types.ts", + "src/common/WindowsMode.ts", + "src/common/buffer/AttributeData.ts", + "src/common/buffer/Buffer.ts", + "src/common/buffer/BufferLine.ts", + "src/common/buffer/BufferRange.ts", + "src/common/buffer/BufferReflow.ts", + "src/common/buffer/BufferSet.ts", + "src/common/buffer/CellData.ts", + "src/common/buffer/Constants.ts", + "src/common/buffer/Marker.ts", + "src/common/buffer/Types.ts", + "src/common/data/Charsets.ts", + "src/common/data/EscapeSequences.ts", + "src/common/input/Keyboard.ts", + "src/common/input/TextDecoder.ts", + "src/common/input/UnicodeV6.ts", + "src/common/input/WriteBuffer.ts", + "src/common/input/XParseColor.ts", + "src/common/parser/Constants.ts", + "src/common/parser/DcsParser.ts", + "src/common/parser/EscapeSequenceParser.ts", + "src/common/parser/OscParser.ts", + "src/common/parser/Params.ts", + "src/common/parser/Types.ts", + "src/common/public/AddonManager.ts", + "src/common/public/BufferApiView.ts", + "src/common/public/BufferLineApiView.ts", + "src/common/public/BufferNamespaceApi.ts", + "src/common/public/ParserApi.ts", + "src/common/public/UnicodeApi.ts", + "src/common/services/BufferService.ts", + "src/common/services/CharsetService.ts", + "src/common/services/CoreMouseService.ts", + "src/common/services/CoreService.ts", + "src/common/services/DecorationService.ts", + "src/common/services/InstantiationService.ts", + "src/common/services/LogService.ts", + "src/common/services/OptionsService.ts", + "src/common/services/OscLinkService.ts", + "src/common/services/ServiceRegistry.ts", + "src/common/services/Services.ts", + "src/common/services/UnicodeService.ts", + "src/vs/base/browser/browser.ts", + "src/vs/base/browser/canIUse.ts", + "src/vs/base/browser/dom.ts", + "src/vs/base/browser/fastDomNode.ts", + "src/vs/base/browser/globalPointerMoveMonitor.ts", + "src/vs/base/browser/iframe.ts", + "src/vs/base/browser/keyboardEvent.ts", + "src/vs/base/browser/mouseEvent.ts", + "src/vs/base/browser/touch.ts", + "src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts", + "src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts", + "src/vs/base/browser/ui/scrollbar/scrollableElement.ts", + "src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarState.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts", + "src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts", + "src/vs/base/browser/ui/widget.ts", + "src/vs/base/browser/window.ts", + "src/vs/base/common/arrays.ts", + "src/vs/base/common/arraysFind.ts", + "src/vs/base/common/assert.ts", + "src/vs/base/common/async.ts", + "src/vs/base/common/cancellation.ts", + "src/vs/base/common/charCode.ts", + "src/vs/base/common/collections.ts", + "src/vs/base/common/decorators.ts", + "src/vs/base/common/equals.ts", + "src/vs/base/common/errors.ts", + "src/vs/base/common/event.ts", + "src/vs/base/common/functional.ts", + "src/vs/base/common/hash.ts", + "src/vs/base/common/iterator.ts", + "src/vs/base/common/keyCodes.ts", + "src/vs/base/common/keybindings.ts", + "src/vs/base/common/lazy.ts", + "src/vs/base/common/lifecycle.ts", + "src/vs/base/common/linkedList.ts", + "src/vs/base/common/map.ts", + "src/vs/base/common/numbers.ts", + "src/vs/base/common/observable.ts", + "src/vs/base/common/observableInternal/api.ts", + "src/vs/base/common/observableInternal/autorun.ts", + "src/vs/base/common/observableInternal/base.ts", + "src/vs/base/common/observableInternal/debugName.ts", + "src/vs/base/common/observableInternal/derived.ts", + "src/vs/base/common/observableInternal/lazyObservableValue.ts", + "src/vs/base/common/observableInternal/logging.ts", + "src/vs/base/common/observableInternal/promise.ts", + "src/vs/base/common/observableInternal/utils.ts", + "src/vs/base/common/platform.ts", + "src/vs/base/common/scrollable.ts", + "src/vs/base/common/sequence.ts", + "src/vs/base/common/stopwatch.ts", + "src/vs/base/common/strings.ts", + "src/vs/base/common/symbols.ts", + "src/vs/base/common/uint.ts", + "src/vs/patches/nls.ts", + "src/vs/typings/base-common.d.ts", + "src/vs/typings/require.d.ts", + "src/vs/typings/vscode-globals-nls.d.ts", + "src/vs/typings/vscode-globals-product.d.ts", + "typings/xterm.d.ts" + ], + "dependencies": {} + } + } +} diff --git a/examples/pty/webfront.project.json b/examples/pty/webfront.project.json new file mode 100644 index 00000000..6c52ca3a --- /dev/null +++ b/examples/pty/webfront.project.json @@ -0,0 +1,10 @@ +{ + "format": 1, + "name": "webfront-pty-example", + "version": "0.1.0", + "dependencies": { + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0" + }, + "entries": {"main": "main.mjs"} +} diff --git a/include/webfront/Pty.hpp b/include/webfront/Pty.hpp new file mode 100644 index 00000000..4ee2b3b6 --- /dev/null +++ b/include/webfront/Pty.hpp @@ -0,0 +1,263 @@ +/// @brief Optional native pseudoterminal for an application-selected program. +#pragma once + +#ifdef _WIN32 + #include "components/pty/Windows.hpp" +#else + #include "components/pty/Unix.hpp" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::pty::detail { + +class ByteRing { +public: + explicit ByteRing(std::size_t capacity) : storage(capacity) {} + + std::size_t size() const { + return used; + } + std::size_t capacity() const { + return storage.size(); + } + + void append(std::span bytes) { + const auto tail = (head + used) % capacity(); + const auto first = std::min(bytes.size(), capacity() - tail); + std::ranges::copy(bytes.first(first), storage.begin() + static_cast(tail)); + std::ranges::copy(bytes.subspan(first), storage.begin()); + used += bytes.size(); + } + + void copy(std::size_t offset, std::span bytes) const { + const auto start = (head + offset) % capacity(); + const auto first = std::min(bytes.size(), capacity() - start); + auto source = std::span{storage}; + std::ranges::copy(source.subspan(start, first), bytes.begin()); + std::ranges::copy(source.first(bytes.size() - first), bytes.subspan(first).begin()); + } + + void consume(std::size_t count) { + head = (head + count) % capacity(); + used -= count; + } + +private: + std::vector storage; + std::size_t head = 0; + std::size_t used = 0; +}; +} // namespace webfront::pty::detail + +namespace webfront { + +class Pty { +public: + static constexpr std::size_t inputCapacity = 64 * 1024; + static constexpr std::size_t replayCapacity = 1024 * 1024; + static constexpr std::size_t readChunk = 16 * 1024; + + struct Output { + std::uint64_t next = 0; + std::vector bytes; + bool truncated = false; + std::optional exitCode; + }; + + explicit Pty(PtyOptions options) + : native(pty::detail::prepare(std::move(options))), worker([this] { + run(); + }) {} + + ~Pty() { + hangUp(); + } + + Pty(const Pty&) = delete; + Pty& operator=(const Pty&) = delete; + + /// Enqueues the complete chunk or returns false. Never waits for the child to read. + [[nodiscard]] bool write(std::span bytes) { + if (bytes.size() > inputCapacity) + return false; + std::scoped_lock lock(mutex); + if (closing || inputClosed || bytes.size() > inputCapacity - input.size()) + return false; + input.append(bytes); + wakeWorker(); + return true; + } + + /// Requests a size change on the worker. Rapid requests are coalesced. + void resize(PtySize size) { + pty::detail::validateSize(size); + std::scoped_lock lock(mutex); + if (closing || inputClosed) + return; + requestedSize = size; + wakeWorker(); + } + + /// Interrupts pending reads and starts cleanup. Destruction joins the worker. + void hangUp() { + std::scoped_lock lock(mutex); + if (closing || status) + return; + closing = true; + wakeWorker(); + changed.notify_all(); + } + + [[nodiscard]] std::optional exitCode() const { + std::scoped_lock lock(mutex); + return status; + } + + /// The cursor is a byte offset, initially zero. Multiple readers can replay independently. + [[nodiscard]] Output tryRead(std::uint64_t cursor) const { + std::scoped_lock lock(mutex); + return snapshot(cursor); + } + + /// Waits for output or exit. A stop request or hangUp also wakes the wait. + [[nodiscard]] Output read(std::uint64_t cursor, std::stop_token stop = {}) const { + std::unique_lock lock(mutex); + changed.wait(lock, stop, [&] { + return cursor != end || status || closing; + }); + return snapshot(cursor); + } + +private: + mutable std::mutex mutex; + mutable std::condition_variable_any changed; + pty::detail::ByteRing input{inputCapacity}; + pty::detail::ByteRing replay{replayCapacity}; + std::uint64_t end = 0; + bool closing = false; + bool inputClosed = false; + std::optional requestedSize; + std::optional status; + std::exception_ptr failure; + pty::detail::NativePty native; +#ifdef _WIN32 + std::condition_variable workerChanged; +#endif + std::jthread worker; + + Output snapshot(std::uint64_t cursor) const { + if (cursor > end) + throw std::invalid_argument("PTY cursor is ahead of its output"); + const auto oldest = end - replay.size(); + const auto start = std::max(cursor, oldest); + const auto count = static_cast(std::min(end - start, readChunk)); + Output result{start + count, std::vector(count), cursor < oldest, {}}; + if (count) + replay.copy(static_cast(start - oldest), result.bytes); + if (!count && failure) + std::rethrow_exception(failure); + if (result.next == end && !failure) + result.exitCode = status; + return result; + } + + void publish(std::span bytes) { + if (bytes.empty()) + return; + std::scoped_lock lock(mutex); + const auto required = replay.size() + bytes.size(); + if (required > replay.capacity()) + replay.consume(required - replay.capacity()); + replay.append(bytes); + end += bytes.size(); + changed.notify_all(); + } + + void wakeWorker() { +#ifdef _WIN32 + workerChanged.notify_one(); +#else + native.wake(); +#endif + } + + void run() { + using namespace std::chrono_literals; + std::exception_ptr error; + std::array output{}; + std::array incoming{}; + try { + std::optional drainDeadline; + for (;;) { + if (!drainDeadline && native.exited()) { + { + std::scoped_lock lock(mutex); + inputClosed = true; + } + native.beginDrain(); + drainDeadline = std::chrono::steady_clock::now() + 3s; + } + const auto received = native.read(output); + publish(std::span{output}.first(received)); + if (drainDeadline && (native.atEnd() || std::chrono::steady_clock::now() >= *drainDeadline)) + break; + + std::optional size; + std::size_t count = 0; + { + std::scoped_lock lock(mutex); + if (closing) + break; + if (!drainDeadline) { + size = std::exchange(requestedSize, std::nullopt); + count = std::min(input.size(), incoming.size()); + if (count) + input.copy(0, std::span{incoming}.first(count)); + } + } + if (size) + native.resize(*size); + const auto sent = count ? native.write(std::span{incoming}.first(count)) : 0; + { + std::scoped_lock lock(mutex); + input.consume(sent); + } + if (!received && !sent) { +#ifdef _WIN32 + std::unique_lock lock(mutex); + if (!closing && (drainDeadline || (!requestedSize && (count != 0 || input.size() == 0)))) + workerChanged.wait_for(lock, drainDeadline || count ? 10ms : 40ms); +#else + native.wait(count != 0, drainDeadline.has_value()); +#endif + } + } + } catch (...) { + error = std::current_exception(); + } + { + std::scoped_lock lock(mutex); + inputClosed = true; + } + const int code = native.finish(); + std::scoped_lock lock(mutex); +#ifndef _WIN32 + native.closeWakePipe(); +#endif + status = code; + failure = error; + changed.notify_all(); + } +}; +} // namespace webfront diff --git a/include/webfront/PtyPage.hpp b/include/webfront/PtyPage.hpp new file mode 100644 index 00000000..fbc1a23c --- /dev/null +++ b/include/webfront/PtyPage.hpp @@ -0,0 +1,125 @@ +/// @brief Registers an application-chosen PTY for the optional xterm.js adapter. +#pragma once + +#include "http/Encodings.hpp" +#include "Pty.hpp" +#include "Task.hpp" + +#include +#include +#include +#include + +namespace webfront { + +namespace pty::detail { +struct PageRegistration { + template + static void addCleanup(App& app, Cleanup&& cleanup) { + app.ptyPageCleanups.emplace_back(std::forward(cleanup)); + } +}; +} // namespace pty::detail + +/// Call during application setup. Each name owns one session, retained across page reloads. +template +void registerPtyPage(App& app, PtyOptions options, std::string name = "webfront.pty") { + if (!app.allowsPtyPages()) + throw std::logic_error("PTY pages need WebFrontConfig::allowPtyPages"); + if (name.empty()) + throw std::invalid_argument("PTY page name cannot be empty"); + for (const auto* operation : {".open", ".read", ".write", ".resize", ".hangUp"}) + if (app.hasCppFunction(name + operation)) + throw std::invalid_argument("PTY page callback already registered: " + name + operation); + + struct Launch { + std::shared_future> terminal; + std::uint32_t generation; + }; + + struct Session { + PtyOptions options; + std::shared_ptr terminal{}; + std::shared_ptr launching{}; + std::uint32_t generation = 0; + Pty& get(std::uint32_t expected) { + if (!terminal || generation != expected) + throw std::logic_error("PTY page session is stale or closed"); + return *terminal; + } + }; + auto state = std::make_shared(Session{std::move(options)}); + pty::detail::PageRegistration::addCleanup(app, [state] { + state->launching.reset(); // A launch outlives disconnects and is joined at application shutdown. + state->terminal.reset(); + }); + app.cppFunction(name + ".open", [state](typename App::UI ui, bool restart) -> ResultTask { + if (restart && (state->launching || (state->terminal && !state->terminal->exitCode()))) + throw std::logic_error("PTY page session is still running or launching"); + if (!state->launching) { + if (state->terminal && !restart) + co_return state->generation; + if (state->generation == UINT32_MAX) + throw std::overflow_error("PTY page generation exhausted"); + + // Only the constructor runs off the server thread. Concurrent attachments share its result. + auto launch = std::make_shared(); + launch->generation = state->generation + 1; + launch->terminal = std::async(std::launch::async, [options = state->options]() mutable { + return std::make_shared(std::move(options)); + }).share(); + state->launching = std::move(launch); + } + auto launch = state->launching; + using namespace std::chrono_literals; + while (launch->terminal.wait_for(0ms) != std::future_status::ready) + co_await ui.resumeAfter(10ms); + + try { + auto terminal = launch->terminal.get(); + if (state->launching == launch) { + state->terminal = std::move(terminal); + state->generation = launch->generation; + state->launching.reset(); + } + } catch (...) { + if (state->launching == launch) + state->launching.reset(); + throw; + } + co_return launch->generation; + }); + using ReadResult = std::tuple; + app.cppFunction(name + ".read", [state](typename App::UI ui, std::uint32_t generation, double cursor) -> ResultTask { + if (!std::isfinite(cursor) || cursor < 0 || cursor > 9007199254740991.0 || std::trunc(cursor) != cursor) + throw std::invalid_argument("Invalid PTY page cursor"); + using namespace std::chrono_literals; + const auto deadline = std::chrono::steady_clock::now() + 1s; + for (;;) { + auto output = state->get(generation).tryRead(static_cast(cursor)); + if (!output.bytes.empty() || output.exitCode || std::chrono::steady_clock::now() >= deadline) + co_return ReadResult{static_cast(output.next), + base64::encode(std::move(output.bytes)), + output.truncated, + output.exitCode.has_value(), + output.exitCode.value_or(0)}; + // Connection-owned timer. A browser reload stops this wait without blocking the server. + co_await ui.resumeAfter(40ms); + } + }); + app.cppFunction(name + ".write", [state](std::uint32_t generation, const std::vector& bytes) { + return state->get(generation).write(bytes); + }); + app.cppFunction(name + ".resize", [state](std::uint32_t generation, double columns, double rows) { + const auto dimension = [](double value) { + if (!(value >= 1 && value <= 32767) || std::trunc(value) != value) + throw std::invalid_argument("Invalid PTY page dimension"); + return static_cast(value); + }; + state->get(generation).resize({dimension(columns), dimension(rows)}); + }); + app.cppFunction(name + ".hangUp", [state](std::uint32_t generation) { + state->get(generation).hangUp(); + }); +} +} // namespace webfront diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 558c71e0..424336bc 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -46,6 +46,10 @@ namespace webfront { +namespace pty::detail { +struct PageRegistration; +} // namespace pty::detail + inline constexpr std::string_view version = "1.0.0"; namespace testing { @@ -509,6 +513,8 @@ struct WebFrontConfig { /// from an address or a `Forwarded` header. `loopbackAttested` is refused at construction unless `address` is a /// loopback address; the other declarations are the integrator's word, which WebFront does not verify. RemoteFileTransport remoteFileTransport = RemoteFileTransport::refused; + /// Allows the optional PtyPage component. Requires a literal loopback bind and a bridge policy limited to the application's Origin. + bool allowPtyPages = false; }; namespace detail { @@ -601,6 +607,16 @@ inline const std::string& checkedAddress(const WebFrontConfig& config) { return config.address; } +inline WebFrontConfig checkedPtyPageConfig(WebFrontConfig config) { + if (config.allowPtyPages) { + if (!isLoopbackName(config.address) || (config.address.contains(':') && config.address != "::1")) + throw std::invalid_argument("PTY pages require a literal loopback listening address (127.x.y.z or ::1)"); + if (config.contentPolicy.allowMissingOrigin || config.contentPolicy.allowAnyBridgeOrigin || !config.contentPolicy.bridgeAllowedOrigins.empty()) + throw std::invalid_argument("PTY pages require a bridge policy limited to the application's own Origin"); + } + return config; +} + /// The read binding of a configuration, which is refused here, before anything is bound, if its declaration is false. inline std::shared_ptr makeReadBinding(const WebFrontConfig& config) { checkedAddress(config); @@ -620,7 +636,11 @@ class BasicWF { // Newcomer-friendly defaults: loopback address, port 9002, no local document root. BasicWF() : BasicWF(WebFrontConfig{}) {} - explicit BasicWF(WebFrontConfig config) + explicit BasicWF(WebFrontConfig config) : BasicWF(detail::checkedPtyPageConfig(std::move(config)), CheckedConfig{}) {} + +private: + struct CheckedConfig {}; + BasicWF(WebFrontConfig config, CheckedConfig) : readBinding(detail::makeReadBinding(config)), httpServer((detail::ensureFrontendInitialized(), config.address), config.port, config.documentRoot, config.contentPolicy), httpAddress(config.address), @@ -629,6 +649,7 @@ class BasicWF { contentPolicy(std::move(config.contentPolicy)), windowOptions(std::move(config.window)), trustLoopbackClients(config.trustLoopbackClients), + ptyPagesAllowed(config.allowPtyPages), idsCounter(0) { // Links are created on the server thread, outside the lock: identifiers are only assigned here. httpServer.onUpgrade([this](typename Net::Socket&& socket) { @@ -663,6 +684,9 @@ class BasicWF { bindRoute = httpServer.addRoute(std::string(ReadBinding::bindPath), readBinding->exchangeHandler(), true); } +public: + [[nodiscard]] bool allowsPtyPages() const noexcept { return ptyPagesAllowed; } + // Preserved for source compatibility; binds all interfaces like it always has, unlike the // loopback-by-default WebFrontConfig constructor above. explicit BasicWF(std::string_view port, std::filesystem::path docRoot = ".") @@ -680,6 +704,7 @@ class BasicWF { // Coroutine cleanup may use its UI, so links stay alive through the join. httpServer.drainUntilJoined(); releaseLinks(); + closePtyPages(); } /** @brief Stops and joins owned work before returning. Call outside server callbacks, @@ -690,6 +715,7 @@ class BasicWF { // Application coroutine cleanup may still use its UI: retain links until join. httpServer.drain(); releaseLinks(); + closePtyPages(); } /** @brief Thread-safe while the application lives. Starts on the server thread. @@ -1207,6 +1233,15 @@ class BasicWF { } } + friend struct pty::detail::PageRegistration; + std::vector> ptyPageCleanups; + + void closePtyPages() { + for (const auto& cleanup : ptyPageCleanups) + cleanup(); + ptyPageCleanups.clear(); + } + void stopAndJoinServer() { stop(); if (serverThread.joinable()) @@ -1383,6 +1418,7 @@ class BasicWF { WindowOptions windowOptions; const std::string viewSecret = detail::newViewSecret(); // this launch's proof of an embedded view const bool trustLoopbackClients; + const bool ptyPagesAllowed; bool developerEnvironment = false; std::atomic launched{false}; // start() was called std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any diff --git a/include/webfront/components/pty/Options.hpp b/include/webfront/components/pty/Options.hpp new file mode 100644 index 00000000..793e1590 --- /dev/null +++ b/include/webfront/components/pty/Options.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace webfront { + +struct PtySize { + std::uint16_t columns = 80; + std::uint16_t rows = 24; +}; + +struct PtyOptions { + std::vector argv; + std::filesystem::path directory; + /// Complete child environment, with terminal defaults supplied by Pty. + std::map environment; + PtySize size; +}; + +namespace pty::detail { +inline void validateSize(PtySize size) { + if (!size.columns || !size.rows || size.columns > 32767 || size.rows > 32767) + throw std::invalid_argument("PTY dimensions must be between 1 and 32767"); +} + +inline PtyOptions prepare(PtyOptions options) { + validateSize(options.size); + if (options.argv.empty() || options.argv.front().empty()) + throw std::invalid_argument("PTY requires an executable"); + for (const auto& arg : options.argv) + if (arg.contains('\0')) + throw std::invalid_argument("PTY arguments cannot contain NUL"); + for (const auto& [key, value] : options.environment) + if (key.empty() || key.contains('=') || key.contains('\0') || value.contains('\0')) + throw std::invalid_argument("Invalid PTY environment entry"); + options.directory = std::filesystem::absolute(options.directory.empty() ? std::filesystem::current_path() : options.directory); + if (options.directory.native().contains(std::filesystem::path::value_type{})) + throw std::invalid_argument("PTY directory cannot contain NUL"); + options.environment.try_emplace("TERM", "xterm-256color"); + options.environment.try_emplace("COLORTERM", "truecolor"); + return options; +} +} // namespace pty::detail +} // namespace webfront diff --git a/include/webfront/components/pty/Unix.hpp b/include/webfront/components/pty/Unix.hpp new file mode 100644 index 00000000..fbed060a --- /dev/null +++ b/include/webfront/components/pty/Unix.hpp @@ -0,0 +1,473 @@ +#pragma once + +#if !defined(__linux__) && !defined(__APPLE__) + #error "WebFront Unix PTYs support Linux and macOS" +#endif + +#include "Options.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__APPLE__) + #include + #include +#else + #include +#endif + +namespace webfront::pty::detail { + +class PtyFd { +public: + explicit PtyFd(int descriptor = -1) : fd(descriptor) {} + ~PtyFd() { + reset(); + } + PtyFd(const PtyFd&) = delete; + PtyFd& operator=(const PtyFd&) = delete; + + int get() const { + return fd; + } + void reset(int replacement = -1) { + if (fd >= 0) + ::close(fd); + fd = replacement; + } + +private: + int fd; +}; + +class NativePty { +public: + explicit NativePty(const PtyOptions& options) { + const auto executable = resolve(options); + std::vector environment; + for (const auto& [key, value] : options.environment) + environment.push_back(key + "=" + value); + const auto args = pointers(options.argv); + const auto env = pointers(environment); + const auto maximumFd = descriptorLimit(); + makePipe(wakeRead, wakeWrite, true); + auto dimensions = window(options.size); + + master.reset(::posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC)); + if (master.get() < 0 || ::fcntl(master.get(), F_SETFL, O_NONBLOCK) < 0 || ::grantpt(master.get()) < 0 || ::unlockpt(master.get()) < 0) + fail("open PTY master"); + std::array slaveName{}; + if (const auto error = ::ptsname_r(master.get(), slaveName.data(), slaveName.size()); error) + throw std::system_error(error > 0 ? error : errno, std::generic_category(), "resolve PTY slave"); + PtyFd slave{::open(slaveName.data(), O_RDWR | O_NOCTTY | O_CLOEXEC)}; + if (slave.get() < 0 || ::ioctl(slave.get(), TIOCSWINSZ, &dimensions) < 0) + fail("open and size PTY slave"); + + // The close-on-exec pipe delivers setup errors and synchronizes with setsid/TIOCSCTTY. + PtyFd reportRead, reportWrite; + makePipe(reportRead, reportWrite, false); + // Keep the error channel above stderr even when the host has closed some standard descriptors. + const int report = ::fcntl(reportWrite.get(), F_DUPFD_CLOEXEC, 3); + if (report < 0) + fail("duplicate PTY launch descriptor"); + reportWrite.reset(report); + const auto* program = executable.c_str(); + const auto* directory = options.directory.c_str(); + struct sigaction childAction{}; + if (::sigaction(SIGCHLD, nullptr, &childAction) < 0) + fail("query SIGCHLD disposition"); + if (childAction.sa_handler == SIG_IGN || (childAction.sa_flags & SA_NOCLDWAIT)) + throw std::logic_error("PTY needs the host to leave its child exit status waitable"); + + // Prevent a host signal handler from running in the post-fork child. + sigset_t blocked{}, previous{}; + (void)sigfillset(&blocked); + if (const int error = ::pthread_sigmask(SIG_SETMASK, &blocked, &previous); error) + throw std::system_error(error, std::generic_category(), "block signals before PTY fork"); + child = ::fork(); + if (child == 0) + launch(program, directory, args.data(), env.data(), slave.get(), report, maximumFd); + const int forkError = errno; + ::pthread_sigmask(SIG_SETMASK, &previous, nullptr); + if (child < 0) + throw std::system_error(forkError, std::generic_category(), "fork PTY child"); + reportWrite.reset(); + slave.reset(); + + int error = 0; + ssize_t count; + // Even a close-on-exec descriptor can be kept by a concurrent child that forks + // without exec. Bound the wait even if that process holds the writer. + pollfd reportReady{reportRead.get(), POLLIN, 0}; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + do { + count = ::poll(&reportReady, 1, 100); + } while ((count == 0 || (count < 0 && errno == EINTR)) && std::chrono::steady_clock::now() < deadline); + if (count > 0) { + do { + count = ::read(reportRead.get(), &error, sizeof(error)); + } while (count < 0 && errno == EINTR); + } else if (count == 0) { + count = -1; + errno = ETIMEDOUT; + } + if (count != 0) { + if (count < 0) + error = errno; + ::kill(child, SIGKILL); + finish(); + throw std::system_error(error, std::generic_category(), "start PTY child"); + } + } + + ~NativePty() { + finish(); + } + + // All I/O after construction belongs to the worker thread. + std::size_t read(std::span bytes) { + const auto count = ::read(master.get(), bytes.data(), bytes.size()); + // EIO means no slave is open now. A live program can reopen it. + if (count < 0 && errno != EIO && errno != EAGAIN && errno != EINTR) + fail("read PTY output"); + if (count >= 0 || errno != EINTR) + eof = count == 0 || (count < 0 && errno == EIO); + return count > 0 ? static_cast(count) : 0; + } + + bool atEnd() const { + return eof; + } + void beginDrain() const {} + + void wake() const { + const char byte = 0; + while (::write(wakeWrite.get(), &byte, 1) < 0 && errno == EINTR) {} + } + + // The owner excludes concurrent wake() calls before retiring these descriptors. + void closeWakePipe() { + wakeWrite.reset(); + wakeRead.reset(); + } + + void wait(bool writing, bool draining) const { + const short events = writing ? POLLIN | POLLOUT : POLLIN; + // A closed slave leaves POLLHUP continuously set. Retry periodically until it reopens + // or the leader exits. The timeout also detects exit while a descendant holds the slave. + pollfd fds[] = { + { wakeRead.get(), POLLIN, 0}, + {eof ? -1 : master.get(), events, 0} + }; + const int ready = ::poll(fds, 2, eof || draining ? 50 : 250); + if (ready < 0 && errno != EINTR) + fail("wait for PTY activity"); + if (ready > 0 && (fds[0].revents & POLLIN)) { + std::array bytes{}; + // Bound each drain so concurrent writers cannot starve terminal I/O. + if (::read(wakeRead.get(), bytes.data(), bytes.size()) < 0 && errno != EINTR && errno != EAGAIN) + fail("read PTY wake pipe"); + } + } + + std::size_t write(std::span bytes) { + const auto count = ::write(master.get(), bytes.data(), bytes.size()); + return count > 0 ? static_cast(count) : 0; + } + + void resize(PtySize size) { + auto dimensions = window(size); + if (::ioctl(master.get(), TIOCSWINSZ, &dimensions) < 0) + fail("resize PTY"); + } + + bool exited() const { + siginfo_t info{}; + const auto result = ::waitid(P_PID, static_cast(child), &info, WEXITED | WNOHANG | WNOWAIT); + if (result == 0) + return info.si_pid != 0; + if (errno == EINTR) + return false; + fail("wait for PTY child"); + } + + int finish() { + if (child <= 0) + return exitCode; + + // Stop if an external reaper has already collected our child and released its PID. + siginfo_t info{}; + int result; + do { + result = ::waitid(P_PID, static_cast(child), &info, WEXITED | WNOHANG | WNOWAIT); + } while (result < 0 && errno == EINTR); + if (result == 0) { + const auto foreground = foregroundGroup(); + const bool hasMembers = signalSession(foreground, SIGHUP); + if (!info.si_pid || hasMembers) { + signalSession(foreground, SIGCONT); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + // The waitable leader reserves the session ID even if the tty has forgotten its group. + signalSession(foregroundGroup(), SIGKILL); + } + reap(); + } + child = -1; + master.reset(); + return exitCode; + } + +private: + PtyFd master, wakeRead, wakeWrite; + pid_t child = -1; + bool eof = false; + int exitCode = 255; + + [[noreturn]] static void fail(const char* action) { + throw std::system_error(errno, std::generic_category(), action); + } + + static winsize window(PtySize size) { + return {size.rows, size.columns, 0, 0}; + } + + static std::vector pointers(const std::vector& strings) { + std::vector result; + for (const auto& string : strings) + result.push_back(const_cast(string.c_str())); + result.push_back(nullptr); + return result; + } + + static std::filesystem::path resolve(const PtyOptions& options) { + const auto& name = options.argv.front(); + if (name.contains('/')) + return options.directory / name; + const auto entry = options.environment.find("PATH"); + std::string_view path = entry == options.environment.end() ? std::string_view("/usr/bin:/bin") : std::string_view(entry->second); + for (;;) { + const auto end = path.find(':'); + auto candidate = options.directory / std::filesystem::path(path.substr(0, end)) / name; + struct stat status{}; + if (::stat(candidate.c_str(), &status) == 0 && S_ISREG(status.st_mode) && ::access(candidate.c_str(), X_OK) == 0) + return candidate; + if (end == std::string_view::npos) + break; + path.remove_prefix(end + 1); + } + throw std::system_error(ENOENT, std::generic_category(), "resolve PTY executable: " + name); + } + + static void makePipe(PtyFd& readEnd, PtyFd& writeEnd, bool nonblocking) { + std::array fds{}; +#if defined(__linux__) + if (::pipe2(fds.data(), O_CLOEXEC | (nonblocking ? O_NONBLOCK : 0)) < 0) +#else + if (::pipe(fds.data()) < 0) +#endif + fail("create PTY pipe"); + readEnd.reset(fds[0]); + writeEnd.reset(fds[1]); +#if !defined(__linux__) + for (auto fd : fds) + if (::fcntl(fd, F_SETFD, FD_CLOEXEC) < 0 || (nonblocking && ::fcntl(fd, F_SETFL, O_NONBLOCK) < 0)) + fail("configure PTY pipe"); +#endif + } + + static int descriptorLimit() { +#if defined(__APPLE__) + int maximum = 0; + std::size_t size = sizeof(maximum); + if (::sysctlbyname("kern.maxfilesperproc", &maximum, &size, nullptr, 0) < 0) + fail("query macOS descriptor limit"); + rlimit limit{}; + if (::getrlimit(RLIMIT_NOFILE, &limit) < 0) + fail("query descriptor limit"); + if ((limit.rlim_max < INT_MAX) && (static_cast(limit.rlim_max) > maximum)) + maximum = static_cast(limit.rlim_max); + return maximum; +#else + return 0; +#endif + } + + static bool closeDescriptors(int report, [[maybe_unused]] int maximumFd) { +#if defined(__linux__) + #if defined(SYS_close_range) + if ((report == 3 || ::syscall(SYS_close_range, 3u, static_cast(report - 1), 0u) == 0) + && ::syscall(SYS_close_range, static_cast(report + 1), UINT_MAX, 0u) == 0) + return true; + #endif + // Use the kernel directory API directly. libc directory iteration can allocate after fork. + const int directory = ::open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (directory < 0) + return false; + // linux_dirent64: u64 inode, s64 offset, u16 length, u8 type, then the name. + std::array entries{}; + for (;;) { + const long size = ::syscall(SYS_getdents64, directory, entries.data(), entries.size()); + if (size < 0 && errno == EINTR) + continue; + if (size <= 0) { + const int error = errno; + ::close(directory); + errno = error; + return size == 0; + } + for (long offset = 0; offset < size;) { + const char* entry = entries.data() + offset; + std::uint16_t length = 0; + std::memcpy(&length, entry + 16, sizeof(length)); + int fd = 0; + const auto* name = entry + 19; + while (*name >= '0' && *name <= '9') + fd = fd * 10 + *name++ - '0'; + if (fd >= 3 && fd != report && fd != directory) + ::close(fd); + offset += length; + } + } +#else + for (int fd = 3; fd < maximumFd; ++fd) + if (fd != report) + ::close(fd); + return true; +#endif + } + + // Child branch: only system operations and preallocated data between fork and exec. + [[noreturn]] static void launch(const char* program, const char* directory, char* const* args, char* const* env, int slave, int report, int maximumFd) { + if (::setsid() >= 0 && ::ioctl(slave, TIOCSCTTY, 0) >= 0 && ::dup2(slave, STDIN_FILENO) >= 0 && ::dup2(slave, STDOUT_FILENO) >= 0 + && ::dup2(slave, STDERR_FILENO) >= 0 && ::chdir(directory) == 0) { + for (int fd = 0; fd <= STDERR_FILENO; ++fd) + ::fcntl(fd, F_SETFD, 0); + + if (closeDescriptors(report, maximumFd)) { + struct sigaction action{}; + action.sa_handler = SIG_DFL; + (void)sigemptyset(&action.sa_mask); + for (int signal = 1; signal < NSIG; ++signal) + if (signal != SIGKILL && signal != SIGSTOP) + ::sigaction(signal, &action, nullptr); + ::sigprocmask(SIG_SETMASK, &action.sa_mask, nullptr); + ::execve(program, args, env); + } + } + const auto error = errno; + ssize_t count; + do { + count = ::write(report, &error, sizeof(error)); + } while (count < 0 && errno == EINTR); + ::_exit(127); + } + + pid_t foregroundGroup() const { + const auto group = ::tcgetpgrp(master.get()); +#if defined(__APPLE__) + // Darwin can require the calling process to control the tty for TIOCGPGRP. + if (group <= 0) { + int request[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, child}; + kinfo_proc process{}; + std::size_t bytes = sizeof(process); + if (::sysctl(request, 4, &process, &bytes, nullptr, 0) == 0 && bytes == sizeof(process)) + return process.kp_eproc.e_tpgid; + } +#endif + return group; + } + + bool signalSession(pid_t foreground, int signal) const { + bool hasMembers = false; + if (foreground > 0 && foreground != child) + hasMembers = ::kill(-foreground, signal) == 0 || errno != ESRCH; + ::kill(-child, signal); + auto signalMember = [&](pid_t pid) { + if (pid <= 0 || pid == child || ::getsid(pid) != child) + return; +#if defined(__linux__) && defined(SYS_pidfd_open) && defined(SYS_pidfd_send_signal) + PtyFd reference{static_cast(::syscall(SYS_pidfd_open, pid, 0u))}; + const bool pidfdUnavailable = reference.get() < 0 && (errno == ENOSYS || errno == EINVAL); +#endif + if (::getsid(pid) != child) + return; + hasMembers = true; + const auto group = ::getpgid(pid); + if (group <= 0 || group == child || group == foreground) + return; +#if defined(__linux__) && defined(SYS_pidfd_open) && defined(SYS_pidfd_send_signal) + if (reference.get() >= 0) { + ::syscall(SYS_pidfd_send_signal, reference.get(), signal, nullptr, 0u); + return; + } + if (!pidfdUnavailable) + return; +#endif + // Platforms without pidfds can only recheck the process identity immediately before signalling. + if (::getsid(pid) == child && ::getpgid(pid) == group) + ::kill(pid, signal); + }; +#if defined(__APPLE__) + // Listing is best-effort if the OS cannot provide a process snapshot. + try { + const auto needed = ::proc_listpids(PROC_ALL_PIDS, 0, nullptr, 0); + if (needed <= 0) + return true; + std::vector pids(static_cast(needed) / sizeof(pid_t) + 64); + const auto bytes = ::proc_listpids(PROC_ALL_PIDS, 0, pids.data(), static_cast(pids.size() * sizeof(pid_t))); + if (bytes <= 0 || static_cast(bytes) == pids.size() * sizeof(pid_t)) + hasMembers = true; + for (int i = 0; i < bytes / static_cast(sizeof(pid_t)); ++i) + signalMember(pids[static_cast(i)]); + } catch (const std::bad_alloc&) { + return true; + } +#else + if (auto* processes = ::opendir("/proc")) { + while (auto* entry = ::readdir(processes)) { + pid_t pid = 0; + const auto [end, error] = std::from_chars(entry->d_name, entry->d_name + std::strlen(entry->d_name), pid); + if (error == std::errc{} && *end == 0) + signalMember(pid); + } + ::closedir(processes); + } else { + return true; + } +#endif + return hasMembers; + } + + void reap() { + int status = 0; + pid_t result; + do { + result = ::waitpid(child, &status, 0); + } while (result < 0 && errno == EINTR); + if (result == child) + exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status); + child = -1; + } +}; +} // namespace webfront::pty::detail diff --git a/include/webfront/components/pty/Windows.hpp b/include/webfront/components/pty/Windows.hpp new file mode 100644 index 00000000..3f46ea7f --- /dev/null +++ b/include/webfront/components/pty/Windows.hpp @@ -0,0 +1,382 @@ +#pragma once + +#include "../../automation/Credentials.hpp" +#include "../../system/WindowsArguments.hpp" +#include "../../system/WindowsCompat.hpp" +#include "Options.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::pty::detail { + +class PtyHandle { +public: + ~PtyHandle() { + reset(); + } + PtyHandle() = default; + PtyHandle(const PtyHandle&) = delete; + PtyHandle& operator=(const PtyHandle&) = delete; + + HANDLE value = nullptr; + + explicit operator bool() const { + return value && value != INVALID_HANDLE_VALUE; + } + void reset() { + if (*this) + ::CloseHandle(value); + value = nullptr; + } +}; + +class NativePty { +public: + explicit NativePty(const PtyOptions& options) { + // Resolve at runtime so a program that only conditionally offers PTYs can still load on older Windows. + const auto kernel = ::GetModuleHandleW(L"kernel32.dll"); + const auto createConsole = load(kernel, "CreatePseudoConsole"); + resizeConsole = load(kernel, "ResizePseudoConsole"); + closeConsole = load(kernel, "ClosePseudoConsole"); + + auto [program, command] = commandLine(options); + auto environment = environmentBlock(options); + PtyHandle consoleInput, consoleOutput; + createInputPipe(consoleInput); + if (!::CreatePipe(&output.value, &consoleOutput.value, nullptr, 0)) + fail("create ConPTY output pipe"); + writeEvent.value = ::CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!writeEvent) + fail("create ConPTY write event"); + pending.hEvent = writeEvent.value; + job.value = ::CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (!job || !::SetInformationJobObject(job.value, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) + fail("create ConPTY job"); + + try { + check(createConsole(dimensions(options.size), consoleInput.value, consoleOutput.value, 0, &console), "create ConPTY"); + consoleInput.reset(); + consoleOutput.reset(); + + SIZE_T size = 0; + ::InitializeProcThreadAttributeList(nullptr, 1, 0, &size); + std::vector storage((size + sizeof(std::max_align_t) - 1) / sizeof(std::max_align_t)); + STARTUPINFOEXW startup{}; + startup.StartupInfo.cb = sizeof(startup); + // Null standard handles let ConPTY install its own console handles even if the host is redirected. + startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + startup.lpAttributeList = reinterpret_cast(storage.data()); + if (!::InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &size)) + fail("initialize ConPTY process attributes"); + struct DeleteAttributes { + LPPROC_THREAD_ATTRIBUTE_LIST attributes; + ~DeleteAttributes() { + ::DeleteProcThreadAttributeList(attributes); + } + } cleanup{startup.lpAttributeList}; + + // ProcThreadAttributeValue(22, FALSE, TRUE, FALSE), also with older SDK headers. + constexpr DWORD_PTR pseudoConsoleAttribute = 0x00020016; + if (!::UpdateProcThreadAttribute(startup.lpAttributeList, 0, pseudoConsoleAttribute, console, sizeof(console), nullptr, nullptr)) + fail("attach ConPTY process attributes"); + + PROCESS_INFORMATION info{}; + if (!::CreateProcessW(program.c_str(), + command.data(), + nullptr, + nullptr, + FALSE, + EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, + environment.data(), + options.directory.c_str(), + &startup.StartupInfo, + &info)) + fail("start ConPTY child"); + process.value = info.hProcess; + PtyHandle thread; + thread.value = info.hThread; + if (!::AssignProcessToJobObject(job.value, process.value) || ::ResumeThread(thread.value) == static_cast(-1)) + fail("start ConPTY child in its job"); + } catch (...) { + consoleInput.reset(); + consoleOutput.reset(); + finish(); + throw; + } + } + + ~NativePty() { + finish(); + } + + std::size_t read(std::span bytes) { + if (draining && console) + closeWhenJobIsEmpty(); + DWORD available = 0; + DWORD count = 0; + if (!::PeekNamedPipe(output.value, nullptr, 0, nullptr, &available, nullptr)) { + if (!outputPipeClosed(::GetLastError())) + fail("read ConPTY output"); + outputClosed = true; + } else if (available && !::ReadFile(output.value, bytes.data(), std::min(available, static_cast(bytes.size())), &count, nullptr)) { + if (!outputPipeClosed(::GetLastError())) + fail("read ConPTY output"); + outputClosed = true; + } + return count; + } + + bool atEnd() const { + return outputClosed; + } + + void beginDrain() { + draining = true; + } + + // The overlapped operation borrows the backend's own buffer, including across worker iterations. + std::size_t write(std::span bytes) { + if (writing) { + DWORD count = 0; + if (!::GetOverlappedResult(input.value, &pending, &count, FALSE)) { + if (::GetLastError() == ERROR_IO_INCOMPLETE) + return 0; + writing = false; + input.reset(); + return 0; + } + writing = false; + return count; + } + if (!input) + return 0; + const auto size = std::min(bytes.size(), writeBuffer.size()); + std::copy_n(bytes.data(), size, writeBuffer.data()); + DWORD count = 0; + ::ResetEvent(writeEvent.value); + if (::WriteFile(input.value, writeBuffer.data(), static_cast(size), &count, &pending)) + return count; + writing = ::GetLastError() == ERROR_IO_PENDING; + if (!writing) + input.reset(); + return 0; + } + + void resize(PtySize size) { + check(resizeConsole(console, dimensions(size)), "resize ConPTY"); + } + + bool exited() const { + return ::WaitForSingleObject(process.value, 0) == WAIT_OBJECT_0; + } + + int finish() { + if (input && writing) { + ::CancelIoEx(input.value, &pending); + DWORD count = 0; + ::GetOverlappedResult(input.value, &pending, &count, TRUE); + } + input.reset(); + writeEvent.reset(); + if (job) + ::TerminateJobObject(job.value, 1); + if (process) { + // Covers constructor failure before the suspended process was assigned to the job. + if (!exited()) + ::TerminateProcess(process.value, 1); + ::WaitForSingleObject(process.value, INFINITE); + DWORD status = 0; + if (::GetExitCodeProcess(process.value, &status)) + exitCode = static_cast(status); + process.reset(); + } + // Older versions of ConPTY wait for their final output during ClosePseudoConsole. + output.reset(); + if (closer.joinable()) + closer.join(); + if (console) + closeConsole(console); + console = nullptr; + job.reset(); + return exitCode; + } + +private: + PtyHandle input, output, job, process, writeEvent; + std::jthread closer; + bool draining = false; + bool outputClosed = false; + HANDLE console = nullptr; + HRESULT(WINAPI* resizeConsole)(HANDLE, COORD) = nullptr; + void(WINAPI* closeConsole)(HANDLE) = nullptr; + OVERLAPPED pending{}; + std::array writeBuffer{}; + bool writing = false; + int exitCode = 255; + + [[noreturn]] static void fail(const char* action) { + throw std::system_error(static_cast(::GetLastError()), std::system_category(), action); + } + + static void check(HRESULT result, const char* action) { + if (FAILED(result)) + throw std::system_error(static_cast(result), std::system_category(), action); + } + + template + static Function load(HMODULE module, const char* name) { + const auto address = ::GetProcAddress(module, name); + if (!address) + fail(name); + Function function = nullptr; + static_assert(sizeof(function) == sizeof(address)); + std::memcpy(&function, &address, sizeof(function)); + return function; + } + + void closeWhenJobIsEmpty() { + JOBOBJECT_BASIC_ACCOUNTING_INFORMATION accounting{}; + if (!::QueryInformationJobObject(job.value, JobObjectBasicAccountingInformation, &accounting, sizeof(accounting), nullptr)) + fail("query ConPTY job"); + if (accounting.ActiveProcesses) + return; + // Older versions can block in ClosePseudoConsole while the output pipe still has bytes. + closer = std::jthread([close = closeConsole, handle = console] { + close(handle); + }); + console = nullptr; + } + + static bool outputPipeClosed(DWORD error) { + return error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED || error == ERROR_NO_DATA; + } + + static COORD dimensions(PtySize size) { + return {static_cast(size.columns), static_cast(size.rows)}; + } + + void createInputPipe(PtyHandle& reader) { + const auto name = L"\\\\.\\pipe\\webfront-pty-" + system::detail::toWide(automation::channel::nonce()); + input.value = ::CreateNamedPipeW(name.c_str(), + PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + 1, + 4096, + 0, + 0, + nullptr); + if (!input) + fail("create ConPTY input pipe"); + reader.value = ::CreateFileW(name.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr); + if (!reader) + fail("open ConPTY input pipe"); + ULONG peer = 0; + if (!::GetNamedPipeClientProcessId(input.value, &peer)) + fail("identify ConPTY input peer"); + if (peer != ::GetCurrentProcessId()) + throw std::runtime_error("Unexpected ConPTY input pipe peer"); + } + + static std::filesystem::path systemDirectory() { + std::array directory{}; + const auto count = ::GetSystemDirectoryW(directory.data(), static_cast(directory.size())); + if (!count || count >= directory.size()) + fail("resolve Windows system directory"); + return directory.data(); + } + + using WindowsEnvironment = std::map; + + static WindowsEnvironment variables(const PtyOptions& options) { + WindowsEnvironment result; + for (const auto& [key, value] : options.environment) + result[system::detail::toWide(key)] = system::detail::toWide(value); + return result; + } + + static std::wstring environmentBlock(const PtyOptions& options) { + auto entries = variables(options); + entries.try_emplace(L"SystemRoot", systemDirectory().parent_path().native()); + std::wstring block; + for (const auto& [key, value] : entries) + block += key + L'=' + value + L'\0'; + return block + L'\0'; + } + + static std::filesystem::path resolve(const PtyOptions& options) { + const std::filesystem::path name = system::detail::toWide(options.argv.front()); + std::vector directories; + if (name.has_parent_path() || name.has_root_path()) { + directories.emplace_back(); + } else { + const auto entries = variables(options); + const auto path = entries.find(L"PATH"); + if (path == entries.end()) { + directories.push_back(systemDirectory()); + } else { + std::wstring_view remaining = path->second; + for (;;) { + const auto separator = remaining.find(L';'); + directories.emplace_back(remaining.substr(0, separator)); + if (separator == std::wstring_view::npos) + break; + remaining.remove_prefix(separator + 1); + } + } + } + for (const auto& directory : directories) { + auto candidate = options.directory / directory / name; + if (!candidate.is_absolute()) + candidate = std::filesystem::absolute(candidate); + std::error_code error; + if (name.has_extension()) { + if (std::filesystem::is_regular_file(candidate, error)) + return candidate; + } else { + for (const auto* extension : {L".exe", L".com", L".cmd", L".bat"}) + if (std::filesystem::is_regular_file(candidate.native() + extension, error)) + return candidate.native() + extension; + } + } + throw std::system_error(ERROR_FILE_NOT_FOUND, std::system_category(), "resolve ConPTY executable: " + options.argv.front()); + } + + static std::pair commandLine(const PtyOptions& options) { + auto program = resolve(options); + const auto extension = program.extension().native(); + const bool batch = ::CompareStringOrdinal(extension.c_str(), -1, L".cmd", -1, TRUE) == CSTR_EQUAL + || ::CompareStringOrdinal(extension.c_str(), -1, L".bat", -1, TRUE) == CSTR_EQUAL; + if (batch) { + // cmd.exe expands percent references even inside quotes. Keep its arguments in a literal subset. + const auto literal = [](const std::wstring& argument) { + if (argument.find_first_of(L"\"%\r\n") != std::wstring::npos) + throw std::invalid_argument("Unsupported character in ConPTY batch argument"); + return L'"' + argument + L'"'; + }; + auto interpreter = systemDirectory() / L"cmd.exe"; + auto command = system::detail::quoteWindowsArgument(interpreter.native()) + L" /d /v:off /s /c \"" + literal(program.native()); + for (std::size_t i = 1; i < options.argv.size(); ++i) + command += L' ' + literal(system::detail::toWide(options.argv[i])); + return {interpreter, command + L'"'}; + } + auto command = system::detail::quoteWindowsArgument(program.native()); + for (std::size_t i = 1; i < options.argv.size(); ++i) + command += L' ' + system::detail::quoteWindowsArgument(system::detail::toWide(options.argv[i])); + return {program, command}; + } +}; +} // namespace webfront::pty::detail diff --git a/include/webfront/http/Encodings.hpp b/include/webfront/http/Encodings.hpp index 13ff2350..fee09edc 100644 --- a/include/webfront/http/Encodings.hpp +++ b/include/webfront/http/Encodings.hpp @@ -127,10 +127,10 @@ namespace detail { 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; - std::string output((4 * (size + 2) / 3), '\0'); + std::string output(4 * ((size + 2) / 3), '\0'); auto coded = output.begin(); size_t i = 0; - for (; i < size - 2; i += 3) { + for (; size - i >= 3; i += 3) { *coded++ = code[(input[i] >> 2) & 0x3Fu]; *coded++ = code[((input[i] & 0x3u) << 4) | ((input[i + 1] & 0xF0u) >> 4)]; *coded++ = code[((input[i + 1] & 0xFu) << 2) | ((input[i + 2] & 0xC0u) >> 6)]; @@ -148,8 +148,6 @@ namespace detail { } *coded++ = '='; } - if (coded != output.end()) output.erase(coded); - return output; } } // namespace detail diff --git a/include/webfront/system/WindowsArguments.hpp b/include/webfront/system/WindowsArguments.hpp new file mode 100644 index 00000000..37536503 --- /dev/null +++ b/include/webfront/system/WindowsArguments.hpp @@ -0,0 +1,46 @@ +#pragma once + +#ifdef _WIN32 + #include "WindowsCompat.hpp" + + #include + #include + +namespace webfront::system::detail { +inline std::wstring toWide(const std::string& text) { + if (text.empty()) + return {}; + const int size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), nullptr, 0); + if (size <= 0) + throw std::invalid_argument("Text is not valid UTF-8"); + std::wstring wide(static_cast(size), L'\0'); + ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), wide.data(), size); + return wide; +} + +/// The CommandLineToArgvW / MSVCRT quoting: the program receives exactly the argument. +inline std::wstring quoteWindowsArgument(const std::wstring& argument) { + if (!argument.empty() && argument.find_first_of(L" \t\n\v\"") == std::wstring::npos) + return argument; + std::wstring quoted = L"\""; + for (auto it = argument.begin();; ++it) { + std::size_t backslashes = 0; + while (it != argument.end() && *it == L'\\') { + ++it; + ++backslashes; + } + if (it == argument.end()) { + quoted.append(backslashes * 2, L'\\'); + break; + } + if (*it == L'"') + quoted.append(backslashes * 2 + 1, L'\\'); + else + quoted.append(backslashes, L'\\'); + quoted.push_back(*it); + } + return quoted + L'"'; +} + +} // namespace webfront::system::detail +#endif diff --git a/include/webfront/testing/Process.hpp b/include/webfront/testing/Process.hpp index 56edd0df..13cbffda 100644 --- a/include/webfront/testing/Process.hpp +++ b/include/webfront/testing/Process.hpp @@ -22,6 +22,7 @@ #include #include + #include "../system/WindowsArguments.hpp" #else #include #include @@ -117,40 +118,8 @@ inline void appendBounded(std::string& into, const char* data, std::size_t size, #ifdef _WIN32 -inline std::wstring toWide(const std::string& text) { - if (text.empty()) - return {}; - const int size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), nullptr, 0); - if (size <= 0) - throw std::invalid_argument("Text is not valid UTF-8"); - std::wstring wide(static_cast(size), L'\0'); - ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), wide.data(), size); - return wide; -} - -/// The CommandLineToArgvW / MSVCRT quoting: the program receives exactly the argument. -inline std::wstring quoteWindowsArgument(const std::wstring& argument) { - if (!argument.empty() && argument.find_first_of(L" \t\n\v\"") == std::wstring::npos) - return argument; - std::wstring quoted = L"\""; - for (auto it = argument.begin();; ++it) { - std::size_t backslashes = 0; - while (it != argument.end() && *it == L'\\') { - ++it; - ++backslashes; - } - if (it == argument.end()) { - quoted.append(backslashes * 2, L'\\'); - break; - } - if (*it == L'"') - quoted.append(backslashes * 2 + 1, L'\\'); - else - quoted.append(backslashes, L'\\'); - quoted.push_back(*it); - } - return quoted + L'"'; -} +using webfront::system::detail::quoteWindowsArgument; +using webfront::system::detail::toWide; struct WindowsHandle { HANDLE handle = nullptr; diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 1e1c292e..26592f3f 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -49,7 +49,7 @@ "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a577f4396ab867096bc6fe6876e16e5220121ec8e8dd234fa1e4819d0a1173e1", - "js/developer/webfront.project.json": "a31b7313bedc47bd437fe68decb23e0788dcaa9903c4c5c2a31841b296a40776", + "js/developer/webfront.project.json": "0fdbffbec76da90b1e3169debb1e61389986f72141cadfa2420b75be39262e51", "js/core/bootstrap/bootstrap.bundle.mjs": "65af2f899f7ff4752400148933284e702b0bcb3285a7bd89f2db31da99080698", "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", "include/webfront/system/DeveloperReleaseData.hpp": "572c8e5372ece66eae4a6dbcecc7de9307d92aec342853acd24025a0c0961e37" diff --git a/js/developer/scripts/package-archive.mjs b/js/developer/scripts/package-archive.mjs index 671ccb3b..d80b5fe4 100644 --- a/js/developer/scripts/package-archive.mjs +++ b/js/developer/scripts/package-archive.mjs @@ -1,5 +1,5 @@ // The deterministic npm archive of a package kept in js/: its package.json and the files it declares. Shared by -// wf run react-package, wf run services-package and the test registry, so that all of them write the same bytes. +// the optional package scripts and the test registry, so that all of them write the same bytes. import {tar, storedGzip} from '../tools/archive.mjs'; import {sriOf} from '../tools/distribution.mjs'; diff --git a/js/developer/scripts/pty-package.mjs b/js/developer/scripts/pty-package.mjs new file mode 100644 index 00000000..266541dc --- /dev/null +++ b/js/developer/scripts/pty-package.mjs @@ -0,0 +1,6 @@ +// wf run pty-package: prepare a publishable npm archive of @webfront/pty. +import {packageArchive, writePackage} from './package-archive.mjs'; + +export const ptyPackage = project => packageArchive(project, 'pty', 'pty'); + +export default context => writePackage(context, 'pty', 'pty', 'PTY package'); diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index 5fb3e72d..df958a91 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -17,6 +17,7 @@ "site": "js/developer/scripts/site.mjs", "pin": "js/developer/scripts/pin.mjs", "react-package": "js/developer/scripts/react-package.mjs", + "pty-package": "js/developer/scripts/pty-package.mjs", "services-package": "js/developer/scripts/services-package.mjs", "test-registry": "test/web/registry/build.mjs" }, @@ -43,6 +44,7 @@ "js/developer/webfront-packages.lock.json", ".webfront/developer/packages", "js/core", + "js/pty", "js/react", "js/services", "js/developer/environment", @@ -61,6 +63,7 @@ "build-developer-environment", "build-site", "build-registry", + "build-pty-package", "build-react-package", "build-services-package", "js/core/bootstrap/bootstrap.bundle.mjs", diff --git a/js/pty/LICENSE b/js/pty/LICENSE new file mode 100644 index 00000000..782734cb --- /dev/null +++ b/js/pty/LICENSE @@ -0,0 +1,1276 @@ +WebFront +Copyright (c) 2013-2026 Ambroise Leclerc and WebFront contributors + +SPDX-License-Identifier: Apache-2.0 OR CECILL-B + +Unless otherwise stated, WebFront's original source code, examples and +accompanying documentation are available under either the Apache License, +Version 2.0, or the CeCILL-B Free Software License Agreement, Version 1, +at your option. You may choose either license; you do not need to comply +with both licenses simultaneously. + +The full license texts follow. The French and English versions of CeCILL-B +are equally authentic. The English text of Apache License 2.0 is authoritative. + +Third-party components retain their own licenses and copyright notices. +This choice of licenses does not relicense dependencies, bundled third-party +code or other material carrying a separate license notice. In particular, +see js/developer/environment/PACKAGES-LICENSE.txt for the bundled package +notice and LICENSES.txt in developer-environment distributions for their +component notices. + +License text sources: +https://www.apache.org/licenses/LICENSE-2.0.txt +https://cecill.info/licences/Licence_CeCILL-B_V1-en.txt +https://cecill.info/licences/Licence_CeCILL-B_V1-fr.txt + +======================================================================== +Apache License, Version 2.0 +======================================================================== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +======================================================================== +CeCILL-B, Version 1 (English) +======================================================================== + + +CeCILL-B FREE SOFTWARE LICENSE AGREEMENT + + + Notice + +This Agreement is a Free Software license agreement that is the result +of discussions between its authors in order to ensure compliance with +the two main principles guiding its drafting: + + * firstly, compliance with the principles governing the distribution + of Free Software: access to source code, broad rights granted to + users, + * secondly, the election of a governing law, French law, with which + it is conformant, both as regards the law of torts and + intellectual property law, and the protection that it offers to + both authors and holders of the economic rights over software. + +The authors of the CeCILL-B (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) +license are: + +Commissariat à l'Energie Atomique - CEA, a public scientific, technical +and industrial research establishment, having its principal place of +business at 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris, France. + +Centre National de la Recherche Scientifique - CNRS, a public scientific +and technological establishment, having its principal place of business +at 3 rue Michel-Ange, 75794 Paris cedex 16, France. + +Institut National de Recherche en Informatique et en Automatique - +INRIA, a public scientific and technological establishment, having its +principal place of business at Domaine de Voluceau, Rocquencourt, BP +105, 78153 Le Chesnay cedex, France. + + + Preamble + +This Agreement is an open source software license intended to give users +significant freedom to modify and redistribute the software licensed +hereunder. + +The exercising of this freedom is conditional upon a strong obligation +of giving credits for everybody that distributes a software +incorporating a software ruled by the current license so as all +contributions to be properly identified and acknowledged. + +In consideration of access to the source code and the rights to copy, +modify and redistribute granted by the license, users are provided only +with a limited warranty and the software's author, the holder of the +economic rights, and the successive licensors only have limited liability. + +In this respect, the risks associated with loading, using, modifying +and/or developing or reproducing the software by the user are brought to +the user's attention, given its Free Software status, which may make it +complicated to use, with the result that its use is reserved for +developers and experienced professionals having in-depth computer +knowledge. Users are therefore encouraged to load and test the +suitability of the software as regards their requirements in conditions +enabling the security of their systems and/or data to be ensured and, +more generally, to use and operate it in the same conditions of +security. This Agreement may be freely reproduced and published, +provided it is not altered, and that no provisions are either added or +removed herefrom. + +This Agreement may apply to any or all software for which the holder of +the economic rights decides to submit the use thereof to its provisions. + + + Article 1 - DEFINITIONS + +For the purpose of this Agreement, when the following expressions +commence with a capital letter, they shall have the following meaning: + +Agreement: means this license agreement, and its possible subsequent +versions and annexes. + +Software: means the software in its Object Code and/or Source Code form +and, where applicable, its documentation, "as is" when the Licensee +accepts the Agreement. + +Initial Software: means the Software in its Source Code and possibly its +Object Code form and, where applicable, its documentation, "as is" when +it is first distributed under the terms and conditions of the Agreement. + +Modified Software: means the Software modified by at least one +Contribution. + +Source Code: means all the Software's instructions and program lines to +which access is required so as to modify the Software. + +Object Code: means the binary files originating from the compilation of +the Source Code. + +Holder: means the holder(s) of the economic rights over the Initial +Software. + +Licensee: means the Software user(s) having accepted the Agreement. + +Contributor: means a Licensee having made at least one Contribution. + +Licensor: means the Holder, or any other individual or legal entity, who +distributes the Software under the Agreement. + +Contribution: means any or all modifications, corrections, translations, +adaptations and/or new functions integrated into the Software by any or +all Contributors, as well as any or all Internal Modules. + +Module: means a set of sources files including their documentation that +enables supplementary functions or services in addition to those offered +by the Software. + +External Module: means any or all Modules, not derived from the +Software, so that this Module and the Software run in separate address +spaces, with one calling the other when they are run. + +Internal Module: means any or all Module, connected to the Software so +that they both execute in the same address space. + +Parties: mean both the Licensee and the Licensor. + +These expressions may be used both in singular and plural form. + + + Article 2 - PURPOSE + +The purpose of the Agreement is the grant by the Licensor to the +Licensee of a non-exclusive, transferable and worldwide license for the +Software as set forth in Article 5 hereinafter for the whole term of the +protection granted by the rights over said Software. + + + Article 3 - ACCEPTANCE + +3.1 The Licensee shall be deemed as having accepted the terms and +conditions of this Agreement upon the occurrence of the first of the +following events: + + * (i) loading the Software by any or all means, notably, by + downloading from a remote server, or by loading from a physical + medium; + * (ii) the first time the Licensee exercises any of the rights + granted hereunder. + +3.2 One copy of the Agreement, containing a notice relating to the +characteristics of the Software, to the limited warranty, and to the +fact that its use is restricted to experienced users has been provided +to the Licensee prior to its acceptance as set forth in Article 3.1 +hereinabove, and the Licensee hereby acknowledges that it has read and +understood it. + + + Article 4 - EFFECTIVE DATE AND TERM + + + 4.1 EFFECTIVE DATE + +The Agreement shall become effective on the date when it is accepted by +the Licensee as set forth in Article 3.1. + + + 4.2 TERM + +The Agreement shall remain in force for the entire legal term of +protection of the economic rights over the Software. + + + Article 5 - SCOPE OF RIGHTS GRANTED + +The Licensor hereby grants to the Licensee, who accepts, the following +rights over the Software for any or all use, and for the term of the +Agreement, on the basis of the terms and conditions set forth hereinafter. + +Besides, if the Licensor owns or comes to own one or more patents +protecting all or part of the functions of the Software or of its +components, the Licensor undertakes not to enforce the rights granted by +these patents against successive Licensees using, exploiting or +modifying the Software. If these patents are transferred, the Licensor +undertakes to have the transferees subscribe to the obligations set +forth in this paragraph. + + + 5.1 RIGHT OF USE + +The Licensee is authorized to use the Software, without any limitation +as to its fields of application, with it being hereinafter specified +that this comprises: + + 1. permanent or temporary reproduction of all or part of the Software + by any or all means and in any or all form. + + 2. loading, displaying, running, or storing the Software on any or + all medium. + + 3. entitlement to observe, study or test its operation so as to + determine the ideas and principles behind any or all constituent + elements of said Software. This shall apply when the Licensee + carries out any or all loading, displaying, running, transmission + or storage operation as regards the Software, that it is entitled + to carry out hereunder. + + + 5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS + +The right to make Contributions includes the right to translate, adapt, +arrange, or make any or all modifications to the Software, and the right +to reproduce the resulting software. + +The Licensee is authorized to make any or all Contributions to the +Software provided that it includes an explicit notice that it is the +author of said Contribution and indicates the date of the creation thereof. + + + 5.3 RIGHT OF DISTRIBUTION + +In particular, the right of distribution includes the right to publish, +transmit and communicate the Software to the general public on any or +all medium, and by any or all means, and the right to market, either in +consideration of a fee, or free of charge, one or more copies of the +Software by any means. + +The Licensee is further authorized to distribute copies of the modified +or unmodified Software to third parties according to the terms and +conditions set forth hereinafter. + + + 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION + +The Licensee is authorized to distribute true copies of the Software in +Source Code or Object Code form, provided that said distribution +complies with all the provisions of the Agreement and is accompanied by: + + 1. a copy of the Agreement, + + 2. a notice relating to the limitation of both the Licensor's + warranty and liability as set forth in Articles 8 and 9, + +and that, in the event that only the Object Code of the Software is +redistributed, the Licensee allows effective access to the full Source +Code of the Software at a minimum during the entire period of its +distribution of the Software, it being understood that the additional +cost of acquiring the Source Code shall not exceed the cost of +transferring the data. + + + 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE + +If the Licensee makes any Contribution to the Software, the resulting +Modified Software may be distributed under a license agreement other +than this Agreement subject to compliance with the provisions of Article +5.3.4. + + + 5.3.3 DISTRIBUTION OF EXTERNAL MODULES + +When the Licensee has developed an External Module, the terms and +conditions of this Agreement do not apply to said External Module, that +may be distributed under a separate license agreement. + + + 5.3.4 CREDITS + +Any Licensee who may distribute a Modified Software hereby expressly +agrees to: + + 1. indicate in the related documentation that it is based on the + Software licensed hereunder, and reproduce the intellectual + property notice for the Software, + + 2. ensure that written indications of the Software intended use, + intellectual property notice and license hereunder are included in + easily accessible format from the Modified Software interface, + + 3. mention, on a freely accessible website describing the Modified + Software, at least throughout the distribution term thereof, that + it is based on the Software licensed hereunder, and reproduce the + Software intellectual property notice, + + 4. where it is distributed to a third party that may distribute a + Modified Software without having to make its source code + available, make its best efforts to ensure that said third party + agrees to comply with the obligations set forth in this Article . + +If the Software, whether or not modified, is distributed with an +External Module designed for use in connection with the Software, the +Licensee shall submit said External Module to the foregoing obligations. + + + 5.3.5 COMPATIBILITY WITH THE CeCILL AND CeCILL-C LICENSES + +Where a Modified Software contains a Contribution subject to the CeCILL +license, the provisions set forth in Article 5.3.4 shall be optional. + +A Modified Software may be distributed under the CeCILL-C license. In +such a case the provisions set forth in Article 5.3.4 shall be optional. + + + Article 6 - INTELLECTUAL PROPERTY + + + 6.1 OVER THE INITIAL SOFTWARE + +The Holder owns the economic rights over the Initial Software. Any or +all use of the Initial Software is subject to compliance with the terms +and conditions under which the Holder has elected to distribute its work +and no one shall be entitled to modify the terms and conditions for the +distribution of said Initial Software. + +The Holder undertakes that the Initial Software will remain ruled at +least by this Agreement, for the duration set forth in Article 4.2. + + + 6.2 OVER THE CONTRIBUTIONS + +The Licensee who develops a Contribution is the owner of the +intellectual property rights over this Contribution as defined by +applicable law. + + + 6.3 OVER THE EXTERNAL MODULES + +The Licensee who develops an External Module is the owner of the +intellectual property rights over this External Module as defined by +applicable law and is free to choose the type of agreement that shall +govern its distribution. + + + 6.4 JOINT PROVISIONS + +The Licensee expressly undertakes: + + 1. not to remove, or modify, in any manner, the intellectual property + notices attached to the Software; + + 2. to reproduce said notices, in an identical manner, in the copies + of the Software modified or not. + +The Licensee undertakes not to directly or indirectly infringe the +intellectual property rights of the Holder and/or Contributors on the +Software and to take, where applicable, vis-à-vis its staff, any and all +measures required to ensure respect of said intellectual property rights +of the Holder and/or Contributors. + + + Article 7 - RELATED SERVICES + +7.1 Under no circumstances shall the Agreement oblige the Licensor to +provide technical assistance or maintenance services for the Software. + +However, the Licensor is entitled to offer this type of services. The +terms and conditions of such technical assistance, and/or such +maintenance, shall be set forth in a separate instrument. Only the +Licensor offering said maintenance and/or technical assistance services +shall incur liability therefor. + +7.2 Similarly, any Licensor is entitled to offer to its licensees, under +its sole responsibility, a warranty, that shall only be binding upon +itself, for the redistribution of the Software and/or the Modified +Software, under terms and conditions that it is free to decide. Said +warranty, and the financial terms and conditions of its application, +shall be subject of a separate instrument executed between the Licensor +and the Licensee. + + + Article 8 - LIABILITY + +8.1 Subject to the provisions of Article 8.2, the Licensee shall be +entitled to claim compensation for any direct loss it may have suffered +from the Software as a result of a fault on the part of the relevant +Licensor, subject to providing evidence thereof. + +8.2 The Licensor's liability is limited to the commitments made under +this Agreement and shall not be incurred as a result of in particular: +(i) loss due the Licensee's total or partial failure to fulfill its +obligations, (ii) direct or consequential loss that is suffered by the +Licensee due to the use or performance of the Software, and (iii) more +generally, any consequential loss. In particular the Parties expressly +agree that any or all pecuniary or business loss (i.e. loss of data, +loss of profits, operating loss, loss of customers or orders, +opportunity cost, any disturbance to business activities) or any or all +legal proceedings instituted against the Licensee by a third party, +shall constitute consequential loss and shall not provide entitlement to +any or all compensation from the Licensor. + + + Article 9 - WARRANTY + +9.1 The Licensee acknowledges that the scientific and technical +state-of-the-art when the Software was distributed did not enable all +possible uses to be tested and verified, nor for the presence of +possible defects to be detected. In this respect, the Licensee's +attention has been drawn to the risks associated with loading, using, +modifying and/or developing and reproducing the Software which are +reserved for experienced users. + +The Licensee shall be responsible for verifying, by any or all means, +the suitability of the product for its requirements, its good working +order, and for ensuring that it shall not cause damage to either persons +or properties. + +9.2 The Licensor hereby represents, in good faith, that it is entitled +to grant all the rights over the Software (including in particular the +rights set forth in Article 5). + +9.3 The Licensee acknowledges that the Software is supplied "as is" by +the Licensor without any other express or tacit warranty, other than +that provided for in Article 9.2 and, in particular, without any warranty +as to its commercial value, its secured, safe, innovative or relevant +nature. + +Specifically, the Licensor does not warrant that the Software is free +from any error, that it will operate without interruption, that it will +be compatible with the Licensee's own equipment and software +configuration, nor that it will meet the Licensee's requirements. + +9.4 The Licensor does not either expressly or tacitly warrant that the +Software does not infringe any third party intellectual property right +relating to a patent, software or any other property right. Therefore, +the Licensor disclaims any and all liability towards the Licensee +arising out of any or all proceedings for infringement that may be +instituted in respect of the use, modification and redistribution of the +Software. Nevertheless, should such proceedings be instituted against +the Licensee, the Licensor shall provide it with technical and legal +assistance for its defense. Such technical and legal assistance shall be +decided on a case-by-case basis between the relevant Licensor and the +Licensee pursuant to a memorandum of understanding. The Licensor +disclaims any and all liability as regards the Licensee's use of the +name of the Software. No warranty is given as regards the existence of +prior rights over the name of the Software or as regards the existence +of a trademark. + + + Article 10 - TERMINATION + +10.1 In the event of a breach by the Licensee of its obligations +hereunder, the Licensor may automatically terminate this Agreement +thirty (30) days after notice has been sent to the Licensee and has +remained ineffective. + +10.2 A Licensee whose Agreement is terminated shall no longer be +authorized to use, modify or distribute the Software. However, any +licenses that it may have granted prior to termination of the Agreement +shall remain valid subject to their having been granted in compliance +with the terms and conditions hereof. + + + Article 11 - MISCELLANEOUS + + + 11.1 EXCUSABLE EVENTS + +Neither Party shall be liable for any or all delay, or failure to +perform the Agreement, that may be attributable to an event of force +majeure, an act of God or an outside cause, such as defective +functioning or interruptions of the electricity or telecommunications +networks, network paralysis following a virus attack, intervention by +government authorities, natural disasters, water damage, earthquakes, +fire, explosions, strikes and labor unrest, war, etc. + +11.2 Any failure by either Party, on one or more occasions, to invoke +one or more of the provisions hereof, shall under no circumstances be +interpreted as being a waiver by the interested Party of its right to +invoke said provision(s) subsequently. + +11.3 The Agreement cancels and replaces any or all previous agreements, +whether written or oral, between the Parties and having the same +purpose, and constitutes the entirety of the agreement between said +Parties concerning said purpose. No supplement or modification to the +terms and conditions hereof shall be effective as between the Parties +unless it is made in writing and signed by their duly authorized +representatives. + +11.4 In the event that one or more of the provisions hereof were to +conflict with a current or future applicable act or legislative text, +said act or legislative text shall prevail, and the Parties shall make +the necessary amendments so as to comply with said act or legislative +text. All other provisions shall remain effective. Similarly, invalidity +of a provision of the Agreement, for any reason whatsoever, shall not +cause the Agreement as a whole to be invalid. + + + 11.5 LANGUAGE + +The Agreement is drafted in both French and English and both versions +are deemed authentic. + + + Article 12 - NEW VERSIONS OF THE AGREEMENT + +12.1 Any person is authorized to duplicate and distribute copies of this +Agreement. + +12.2 So as to ensure coherence, the wording of this Agreement is +protected and may only be modified by the authors of the License, who +reserve the right to periodically publish updates or new versions of the +Agreement, each with a separate number. These subsequent versions may +address new issues encountered by Free Software. + +12.3 Any Software distributed under a given version of the Agreement may +only be subsequently distributed under the same version of the Agreement +or a subsequent version. + + + Article 13 - GOVERNING LAW AND JURISDICTION + +13.1 The Agreement is governed by French law. The Parties agree to +endeavor to seek an amicable solution to any disagreements or disputes +that may arise during the performance of the Agreement. + +13.2 Failing an amicable solution within two (2) months as from their +occurrence, and unless emergency proceedings are necessary, the +disagreements or disputes shall be referred to the Paris Courts having +jurisdiction, by the more diligent Party. + + +Version 1.0 dated 2006-09-05. + +======================================================================== +CeCILL-B, version 1 (français) +======================================================================== + + +CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B + + + Avertissement + +Ce contrat est une licence de logiciel libre issue d'une concertation +entre ses auteurs afin que le respect de deux grands principes préside à +sa rédaction: + + * d'une part, le respect des principes de diffusion des logiciels + libres: accès au code source, droits étendus conférés aux + utilisateurs, + * d'autre part, la désignation d'un droit applicable, le droit + français, auquel elle est conforme, tant au regard du droit de la + responsabilité civile que du droit de la propriété intellectuelle + et de la protection qu'il offre aux auteurs et titulaires des + droits patrimoniaux sur un logiciel. + +Les auteurs de la licence CeCILL-B (pour Ce[a] C[nrs] I[nria] L[ogiciel] +L[ibre]) sont: + +Commissariat à l'Energie Atomique - CEA, établissement public de +recherche à caractère scientifique, technique et industriel, dont le +siège est situé 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris. + +Centre National de la Recherche Scientifique - CNRS, établissement +public à caractère scientifique et technologique, dont le siège est +situé 3 rue Michel-Ange, 75794 Paris cedex 16. + +Institut National de Recherche en Informatique et en Automatique - +INRIA, établissement public à caractère scientifique et technologique, +dont le siège est situé Domaine de Voluceau, Rocquencourt, BP 105, 78153 +Le Chesnay cedex. + + + Préambule + +Ce contrat est une licence de logiciel libre dont l'objectif est de +conférer aux utilisateurs une très large liberté de modification et de +redistribution du logiciel régi par cette licence. + +L'exercice de cette liberté est assorti d'une obligation forte de +citation à la charge de ceux qui distribueraient un logiciel incorporant +un logiciel régi par la présente licence afin d'assurer que les +contributions de tous soient correctement identifiées et reconnues. + +L'accessibilité au code source et les droits de copie, de modification +et de redistribution qui découlent de ce contrat ont pour contrepartie +de n'offrir aux utilisateurs qu'une garantie limitée et de ne faire +peser sur l'auteur du logiciel, le titulaire des droits patrimoniaux et +les concédants successifs qu'une responsabilité restreinte. + +A cet égard l'attention de l'utilisateur est attirée sur les risques +associés au chargement, à l'utilisation, à la modification et/ou au +développement et à la reproduction du logiciel par l'utilisateur étant +donné sa spécificité de logiciel libre, qui peut le rendre complexe à +manipuler et qui le réserve donc à des développeurs ou des +professionnels avertis possédant des connaissances informatiques +approfondies. Les utilisateurs sont donc invités à charger et tester +l'adéquation du logiciel à leurs besoins dans des conditions permettant +d'assurer la sécurité de leurs systèmes et/ou de leurs données et, plus +généralement, à l'utiliser et l'exploiter dans les mêmes conditions de +sécurité. Ce contrat peut être reproduit et diffusé librement, sous +réserve de le conserver en l'état, sans ajout ni suppression de clauses. + +Ce contrat est susceptible de s'appliquer à tout logiciel dont le +titulaire des droits patrimoniaux décide de soumettre l'exploitation aux +dispositions qu'il contient. + + + Article 1 - DEFINITIONS + +Dans ce contrat, les termes suivants, lorsqu'ils seront écrits avec une +lettre capitale, auront la signification suivante: + +Contrat: désigne le présent contrat de licence, ses éventuelles versions +postérieures et annexes. + +Logiciel: désigne le logiciel sous sa forme de Code Objet et/ou de Code +Source et le cas échéant sa documentation, dans leur état au moment de +l'acceptation du Contrat par le Licencié. + +Logiciel Initial: désigne le Logiciel sous sa forme de Code Source et +éventuellement de Code Objet et le cas échéant sa documentation, dans +leur état au moment de leur première diffusion sous les termes du Contrat. + +Logiciel Modifié: désigne le Logiciel modifié par au moins une +Contribution. + +Code Source: désigne l'ensemble des instructions et des lignes de +programme du Logiciel et auquel l'accès est nécessaire en vue de +modifier le Logiciel. + +Code Objet: désigne les fichiers binaires issus de la compilation du +Code Source. + +Titulaire: désigne le ou les détenteurs des droits patrimoniaux d'auteur +sur le Logiciel Initial. + +Licencié: désigne le ou les utilisateurs du Logiciel ayant accepté le +Contrat. + +Contributeur: désigne le Licencié auteur d'au moins une Contribution. + +Concédant: désigne le Titulaire ou toute personne physique ou morale +distribuant le Logiciel sous le Contrat. + +Contribution: désigne l'ensemble des modifications, corrections, +traductions, adaptations et/ou nouvelles fonctionnalités intégrées dans +le Logiciel par tout Contributeur, ainsi que tout Module Interne. + +Module: désigne un ensemble de fichiers sources y compris leur +documentation qui permet de réaliser des fonctionnalités ou services +supplémentaires à ceux fournis par le Logiciel. + +Module Externe: désigne tout Module, non dérivé du Logiciel, tel que ce +Module et le Logiciel s'exécutent dans des espaces d'adressage +différents, l'un appelant l'autre au moment de leur exécution. + +Module Interne: désigne tout Module lié au Logiciel de telle sorte +qu'ils s'exécutent dans le même espace d'adressage. + +Parties: désigne collectivement le Licencié et le Concédant. + +Ces termes s'entendent au singulier comme au pluriel. + + + Article 2 - OBJET + +Le Contrat a pour objet la concession par le Concédant au Licencié d'une +licence non exclusive, cessible et mondiale du Logiciel telle que +définie ci-après à l'article 5 pour toute la durée de protection des droits +portant sur ce Logiciel. + + + Article 3 - ACCEPTATION + +3.1 L'acceptation par le Licencié des termes du Contrat est réputée +acquise du fait du premier des faits suivants: + + * (i) le chargement du Logiciel par tout moyen notamment par + téléchargement à partir d'un serveur distant ou par chargement à + partir d'un support physique; + * (ii) le premier exercice par le Licencié de l'un quelconque des + droits concédés par le Contrat. + +3.2 Un exemplaire du Contrat, contenant notamment un avertissement +relatif aux spécificités du Logiciel, à la restriction de garantie et à +la limitation à un usage par des utilisateurs expérimentés a été mis à +disposition du Licencié préalablement à son acceptation telle que +définie à l'article 3.1 ci dessus et le Licencié reconnaît en avoir pris +connaissance. + + + Article 4 - ENTREE EN VIGUEUR ET DUREE + + + 4.1 ENTREE EN VIGUEUR + +Le Contrat entre en vigueur à la date de son acceptation par le Licencié +telle que définie en 3.1. + + + 4.2 DUREE + +Le Contrat produira ses effets pendant toute la durée légale de +protection des droits patrimoniaux portant sur le Logiciel. + + + Article 5 - ETENDUE DES DROITS CONCEDES + +Le Concédant concède au Licencié, qui accepte, les droits suivants sur +le Logiciel pour toutes destinations et pour la durée du Contrat dans +les conditions ci-après détaillées. + +Par ailleurs, si le Concédant détient ou venait à détenir un ou +plusieurs brevets d'invention protégeant tout ou partie des +fonctionnalités du Logiciel ou de ses composants, il s'engage à ne pas +opposer les éventuels droits conférés par ces brevets aux Licenciés +successifs qui utiliseraient, exploiteraient ou modifieraient le +Logiciel. En cas de cession de ces brevets, le Concédant s'engage à +faire reprendre les obligations du présent alinéa aux cessionnaires. + + + 5.1 DROIT D'UTILISATION + +Le Licencié est autorisé à utiliser le Logiciel, sans restriction quant +aux domaines d'application, étant ci-après précisé que cela comporte: + + 1. la reproduction permanente ou provisoire du Logiciel en tout ou + partie par tout moyen et sous toute forme. + + 2. le chargement, l'affichage, l'exécution, ou le stockage du + Logiciel sur tout support. + + 3. la possibilité d'en observer, d'en étudier, ou d'en tester le + fonctionnement afin de déterminer les idées et principes qui sont + à la base de n'importe quel élément de ce Logiciel; et ceci, + lorsque le Licencié effectue toute opération de chargement, + d'affichage, d'exécution, de transmission ou de stockage du + Logiciel qu'il est en droit d'effectuer en vertu du Contrat. + + + 5.2 DROIT D'APPORTER DES CONTRIBUTIONS + +Le droit d'apporter des Contributions comporte le droit de traduire, +d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel +et le droit de reproduire le logiciel en résultant. + +Le Licencié est autorisé à apporter toute Contribution au Logiciel sous +réserve de mentionner, de façon explicite, son nom en tant qu'auteur de +cette Contribution et la date de création de celle-ci. + + + 5.3 DROIT DE DISTRIBUTION + +Le droit de distribution comporte notamment le droit de diffuser, de +transmettre et de communiquer le Logiciel au public sur tout support et +par tout moyen ainsi que le droit de mettre sur le marché à titre +onéreux ou gratuit, un ou des exemplaires du Logiciel par tout procédé. + +Le Licencié est autorisé à distribuer des copies du Logiciel, modifié ou +non, à des tiers dans les conditions ci-après détaillées. + + + 5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION + +Le Licencié est autorisé à distribuer des copies conformes du Logiciel, +sous forme de Code Source ou de Code Objet, à condition que cette +distribution respecte les dispositions du Contrat dans leur totalité et +soit accompagnée: + + 1. d'un exemplaire du Contrat, + + 2. d'un avertissement relatif à la restriction de garantie et de + responsabilité du Concédant telle que prévue aux articles 8 + et 9, + +et que, dans le cas où seul le Code Objet du Logiciel est redistribué, +le Licencié permette un accès effectif au Code Source complet du +Logiciel pendant au moins toute la durée de sa distribution du Logiciel, +étant entendu que le coût additionnel d'acquisition du Code Source ne +devra pas excéder le simple coût de transfert des données. + + + 5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE + +Lorsque le Licencié apporte une Contribution au Logiciel, le Logiciel +Modifié peut être distribué sous un contrat de licence autre que le +présent Contrat sous réserve du respect des dispositions de l'article +5.3.4. + + + 5.3.3 DISTRIBUTION DES MODULES EXTERNES + +Lorsque le Licencié a développé un Module Externe les conditions du +Contrat ne s'appliquent pas à ce Module Externe, qui peut être distribué +sous un contrat de licence différent. + + + 5.3.4 CITATIONS + +Le Licencié qui distribue un Logiciel Modifié s'engage expressément: + + 1. à indiquer dans sa documentation qu'il a été réalisé à partir du + Logiciel régi par le Contrat, en reproduisant les mentions de + propriété intellectuelle du Logiciel, + + 2. à faire en sorte que l'utilisation du Logiciel, ses mentions de + propriété intellectuelle et le fait qu'il est régi par le Contrat + soient indiqués dans un texte facilement accessible depuis + l'interface du Logiciel Modifié, + + 3. à mentionner, sur un site Web librement accessible décrivant le + Logiciel Modifié, et pendant au moins toute la durée de sa + distribution, qu'il a été réalisé à partir du Logiciel régi par le + Contrat, en reproduisant les mentions de propriété intellectuelle + du Logiciel, + + 4. lorsqu'il le distribue à un tiers susceptible de distribuer + lui-même un Logiciel Modifié, sans avoir à en distribuer le code + source, à faire ses meilleurs efforts pour que les obligations du + présent article 5.3.4 soient reprises par le dit tiers. + +Lorsque le Logiciel modifié ou non est distribué avec un Module Externe +qui a été conçu pour l'utiliser, le Licencié doit soumettre le dit +Module Externe aux obligations précédentes. + + + 5.3.5 COMPATIBILITE AVEC LES LICENCES CeCILL et CeCILL-C + +Lorsqu'un Logiciel Modifié contient une Contribution soumise au contrat +de licence CeCILL, les stipulations prévues à l'article 5.3.4 sont +facultatives. + +Un Logiciel Modifié peut être distribué sous le contrat de licence +CeCILL-C. Les stipulations prévues à l'article 5.3.4 sont alors +facultatives. + + + Article 6 - PROPRIETE INTELLECTUELLE + + + 6.1 SUR LE LOGICIEL INITIAL + +Le Titulaire est détenteur des droits patrimoniaux sur le Logiciel +Initial. Toute utilisation du Logiciel Initial est soumise au respect +des conditions dans lesquelles le Titulaire a choisi de diffuser son +oeuvre et nul autre n'a la faculté de modifier les conditions de +diffusion de ce Logiciel Initial. + +Le Titulaire s'engage à ce que le Logiciel Initial reste au moins régi +par le Contrat et ce, pour la durée visée à l'article 4.2. + + + 6.2 SUR LES CONTRIBUTIONS + +Le Licencié qui a développé une Contribution est titulaire sur celle-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable. + + + 6.3 SUR LES MODULES EXTERNES + +Le Licencié qui a développé un Module Externe est titulaire sur celui-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable et reste libre du choix du contrat régissant +sa diffusion. + + + 6.4 DISPOSITIONS COMMUNES + +Le Licencié s'engage expressément: + + 1. à ne pas supprimer ou modifier de quelque manière que ce soit les + mentions de propriété intellectuelle apposées sur le Logiciel; + + 2. à reproduire à l'identique lesdites mentions de propriété + intellectuelle sur les copies du Logiciel modifié ou non. + +Le Licencié s'engage à ne pas porter atteinte, directement ou +indirectement, aux droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs sur le Logiciel et à prendre, le cas échéant, à +l'égard de son personnel toutes les mesures nécessaires pour assurer le +respect des dits droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs. + + + Article 7 - SERVICES ASSOCIES + +7.1 Le Contrat n'oblige en aucun cas le Concédant à la réalisation de +prestations d'assistance technique ou de maintenance du Logiciel. + +Cependant le Concédant reste libre de proposer ce type de services. Les +termes et conditions d'une telle assistance technique et/ou d'une telle +maintenance seront alors déterminés dans un acte séparé. Ces actes de +maintenance et/ou assistance technique n'engageront que la seule +responsabilité du Concédant qui les propose. + +7.2 De même, tout Concédant est libre de proposer, sous sa seule +responsabilité, à ses licenciés une garantie, qui n'engagera que lui, +lors de la redistribution du Logiciel et/ou du Logiciel Modifié et ce, +dans les conditions qu'il souhaite. Cette garantie et les modalités +financières de son application feront l'objet d'un acte séparé entre le +Concédant et le Licencié. + + + Article 8 - RESPONSABILITE + +8.1 Sous réserve des dispositions de l'article 8.2, le Licencié a la +faculté, sous réserve de prouver la faute du Concédant concerné, de +solliciter la réparation du préjudice direct qu'il subirait du fait du +Logiciel et dont il apportera la preuve. + +8.2 La responsabilité du Concédant est limitée aux engagements pris en +application du Contrat et ne saurait être engagée en raison notamment: +(i) des dommages dus à l'inexécution, totale ou partielle, de ses +obligations par le Licencié, (ii) des dommages directs ou indirects +découlant de l'utilisation ou des performances du Logiciel subis par le +Licencié et (iii) plus généralement d'un quelconque dommage indirect. En +particulier, les Parties conviennent expressément que tout préjudice +financier ou commercial (par exemple perte de données, perte de +bénéfices, perte d'exploitation, perte de clientèle ou de commandes, +manque à gagner, trouble commercial quelconque) ou toute action dirigée +contre le Licencié par un tiers, constitue un dommage indirect et +n'ouvre pas droit à réparation par le Concédant. + + + Article 9 - GARANTIE + +9.1 Le Licencié reconnaît que l'état actuel des connaissances +scientifiques et techniques au moment de la mise en circulation du +Logiciel ne permet pas d'en tester et d'en vérifier toutes les +utilisations ni de détecter l'existence d'éventuels défauts. L'attention +du Licencié a été attirée sur ce point sur les risques associés au +chargement, à l'utilisation, la modification et/ou au développement et à +la reproduction du Logiciel qui sont réservés à des utilisateurs avertis. + +Il relève de la responsabilité du Licencié de contrôler, par tous +moyens, l'adéquation du produit à ses besoins, son bon fonctionnement et +de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens. + +9.2 Le Concédant déclare de bonne foi être en droit de concéder +l'ensemble des droits attachés au Logiciel (comprenant notamment les +droits visés à l'article 5). + +9.3 Le Licencié reconnaît que le Logiciel est fourni "en l'état" par le +Concédant sans autre garantie, expresse ou tacite, que celle prévue à +l'article 9.2 et notamment sans aucune garantie sur sa valeur commerciale, +son caractère sécurisé, innovant ou pertinent. + +En particulier, le Concédant ne garantit pas que le Logiciel est exempt +d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible +avec l'équipement du Licencié et sa configuration logicielle ni qu'il +remplira les besoins du Licencié. + +9.4 Le Concédant ne garantit pas, de manière expresse ou tacite, que le +Logiciel ne porte pas atteinte à un quelconque droit de propriété +intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout +autre droit de propriété. Ainsi, le Concédant exclut toute garantie au +profit du Licencié contre les actions en contrefaçon qui pourraient être +diligentées au titre de l'utilisation, de la modification, et de la +redistribution du Logiciel. Néanmoins, si de telles actions sont +exercées contre le Licencié, le Concédant lui apportera son aide +technique et juridique pour sa défense. Cette aide technique et +juridique est déterminée au cas par cas entre le Concédant concerné et +le Licencié dans le cadre d'un protocole d'accord. Le Concédant dégage +toute responsabilité quant à l'utilisation de la dénomination du +Logiciel par le Licencié. Aucune garantie n'est apportée quant à +l'existence de droits antérieurs sur le nom du Logiciel et sur +l'existence d'une marque. + + + Article 10 - RESILIATION + +10.1 En cas de manquement par le Licencié aux obligations mises à sa +charge par le Contrat, le Concédant pourra résilier de plein droit le +Contrat trente (30) jours après notification adressée au Licencié et +restée sans effet. + +10.2 Le Licencié dont le Contrat est résilié n'est plus autorisé à +utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les +licences qu'il aura concédées antérieurement à la résiliation du Contrat +resteront valides sous réserve qu'elles aient été effectuées en +conformité avec le Contrat. + + + Article 11 - DISPOSITIONS DIVERSES + + + 11.1 CAUSE EXTERIEURE + +Aucune des Parties ne sera responsable d'un retard ou d'une défaillance +d'exécution du Contrat qui serait dû à un cas de force majeure, un cas +fortuit ou une cause extérieure, telle que, notamment, le mauvais +fonctionnement ou les interruptions du réseau électrique ou de +télécommunication, la paralysie du réseau liée à une attaque +informatique, l'intervention des autorités gouvernementales, les +catastrophes naturelles, les dégâts des eaux, les tremblements de terre, +le feu, les explosions, les grèves et les conflits sociaux, l'état de +guerre... + +11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou +plusieurs occasions de se prévaloir d'une ou plusieurs dispositions du +Contrat, ne pourra en aucun cas impliquer renonciation par la Partie +intéressée à s'en prévaloir ultérieurement. + +11.3 Le Contrat annule et remplace toute convention antérieure, écrite +ou orale, entre les Parties sur le même objet et constitue l'accord +entier entre les Parties sur cet objet. Aucune addition ou modification +aux termes du Contrat n'aura d'effet à l'égard des Parties à moins +d'être faite par écrit et signée par leurs représentants dûment habilités. + +11.4 Dans l'hypothèse où une ou plusieurs des dispositions du Contrat +s'avèrerait contraire à une loi ou à un texte applicable, existants ou +futurs, cette loi ou ce texte prévaudrait, et les Parties feraient les +amendements nécessaires pour se conformer à cette loi ou à ce texte. +Toutes les autres dispositions resteront en vigueur. De même, la +nullité, pour quelque raison que ce soit, d'une des dispositions du +Contrat ne saurait entraîner la nullité de l'ensemble du Contrat. + + + 11.5 LANGUE + +Le Contrat est rédigé en langue française et en langue anglaise, ces +deux versions faisant également foi. + + + Article 12 - NOUVELLES VERSIONS DU CONTRAT + +12.1 Toute personne est autorisée à copier et distribuer des copies de +ce Contrat. + +12.2 Afin d'en préserver la cohérence, le texte du Contrat est protégé +et ne peut être modifié que par les auteurs de la licence, lesquels se +réservent le droit de publier périodiquement des mises à jour ou de +nouvelles versions du Contrat, qui posséderont chacune un numéro +distinct. Ces versions ultérieures seront susceptibles de prendre en +compte de nouvelles problématiques rencontrées par les logiciels libres. + +12.3 Tout Logiciel diffusé sous une version donnée du Contrat ne pourra +faire l'objet d'une diffusion ultérieure que sous la même version du +Contrat ou une version postérieure. + + + Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE + +13.1 Le Contrat est régi par la loi française. Les Parties conviennent +de tenter de régler à l'amiable les différends ou litiges qui +viendraient à se produire par suite ou à l'occasion du Contrat. + +13.2 A défaut d'accord amiable dans un délai de deux (2) mois à compter +de leur survenance et sauf situation relevant d'une procédure d'urgence, +les différends ou litiges seront portés par la Partie la plus diligente +devant les Tribunaux compétents de Paris. + + +Version 1.0 du 2006-09-05. diff --git a/js/pty/README.md b/js/pty/README.md new file mode 100644 index 00000000..3f526c30 --- /dev/null +++ b/js/pty/README.md @@ -0,0 +1,14 @@ +# @webfront/pty + +Connect xterm.js to a pseudoterminal registered by a WebFront C++ application. Pass an xterm.js `Terminal` and a `FitAddon` to `mount(element, options)`. The adapter uses the installed WebFront bridge by default. + +```js +import { mount } from '@webfront/pty'; +import { Terminal } from '@xterm/xterm'; +import { FitAddon } from '@xterm/addon-fit'; +import '@xterm/xterm/css/xterm.css'; + +const session = await mount(element, {terminal: new Terminal(), fit: new FitAddon()}); +``` + +Unmount with `session.dispose()`. The app retains the PTY and its recent output across page reloads. Call `await session.hangUp()` to terminate the process. Mount with `restart: true` after exit to start a fresh session. The host must explicitly opt in and register the program it wants the terminal to run. See the [WebFront PTY guide](https://github.com/ambroise-leclerc/WebFront/blob/develop/docs/PTY.md). diff --git a/js/pty/index.d.ts b/js/pty/index.d.ts new file mode 100644 index 00000000..6eacf23f --- /dev/null +++ b/js/pty/index.d.ts @@ -0,0 +1,23 @@ +import type { Terminal } from '@xterm/xterm'; +import type { FitAddon } from '@xterm/addon-fit'; + +export interface PtyPageOptions { + terminal: Terminal; + fit: FitAddon; + name?: string; + restart?: boolean; + webFront?: { + ready: Promise; + cppFunction(name: string): (...args: (boolean | number | Uint8Array)[]) => Promise; + }; + onExit?(code: number): void; + onError?(error: unknown): void; + onTruncated?(): void; +} + +export interface PtyPage { + dispose(): void; + hangUp(): Promise; +} + +export declare function mount(element: HTMLElement, options: PtyPageOptions): Promise; diff --git a/js/pty/index.mjs b/js/pty/index.mjs new file mode 100644 index 00000000..c344ea36 --- /dev/null +++ b/js/pty/index.mjs @@ -0,0 +1,128 @@ +// Optional xterm.js adapter. The application supplies its own Terminal and FitAddon instances. +export async function mount(element, { + terminal, fit, webFront = globalThis.webFront, name = 'webfront.pty', restart = false, + onExit = () => {}, onError = error => console.error(error), onTruncated = () => {}, +}) { + await webFront.ready; + const generation = await webFront.cppFunction(name + '.open')(restart); + const call = operation => (...args) => webFront.cppFunction(name + '.' + operation)(generation, ...args); + const read = call('read'); + const write = call('write'); + const resize = call('resize'); + const hangUp = call('hangUp'); + + const limit = 64 * 1024; + const encoder = new TextEncoder(); + const input = []; + let pending = 0; + let writing = false; + let sizing = false; + let sentSize; + let disposed = false; + let cursor = 0; + + const sendInput = async () => { + writing = true; + try { + while (!disposed && input.length) { + const bytes = input[0]; + for (let offset = 0; offset < bytes.length && !disposed; offset += 4096) { + if (!await write(bytes.subarray(offset, offset + 4096))) + throw new Error('PTY input queue is full or closed'); + } + if (!disposed) { + input.shift(); + pending -= bytes.length; + } + } + } catch (error) { + input.length = 0; + pending = 0; + if (!disposed) onError(error); + } finally { + writing = false; + } + }; + + const enqueue = (text, encode) => { + if (disposed || !text.length) return; + if (text.length <= limit - pending) { + const bytes = encode(text); + if (bytes.length <= limit - pending) { + input.push(bytes); + pending += bytes.length; + if (!writing) void sendInput(); + return; + } + } + onError(new Error('PTY input exceeds the browser queue capacity')); + }; + + const fitting = async () => { + if (disposed || sizing) return; + sizing = true; + try { + for (;;) { + fit.fit(); + const {cols, rows} = terminal; + if (sentSize?.cols === cols && sentSize?.rows === rows) break; + if (!cols || !rows) break; + await resize(cols, rows); + if (disposed) break; + sentSize = {cols, rows}; + // Recheck in case a ResizeObserver callback arrived while awaiting the bridge. + } + } catch (error) { + if (!disposed) onError(error); + } finally { + sizing = false; + } + }; + + const poll = async () => { + try { + const [next, base64, truncated, exited, code] = await read(cursor); + if (disposed) return; + cursor = next; + if (truncated) { + terminal.reset(); + onTruncated(); + } + if (base64) { + const bytes = Uint8Array.from(atob(base64), character => character.charCodeAt(0)); + // xterm decodes UTF-8 incrementally and acknowledges consumption before the next read. + await new Promise(resolve => terminal.write(bytes, resolve)); + } + if (disposed) return; + if (exited) { + dispose(); + onExit(code); + } else { + void poll(); + } + } catch (error) { + if (disposed) return; + dispose(); + onError(error); + } + }; + + const dispose = () => { + if (disposed) return; + disposed = true; + observer.disconnect(); + data.dispose(); + binary.dispose(); + input.length = 0; + }; + + terminal.loadAddon(fit); + terminal.open(element); + const data = terminal.onData(text => enqueue(text, value => encoder.encode(value))); + const binary = terminal.onBinary(text => enqueue(text, value => Uint8Array.from(value, ch => ch.charCodeAt(0)))); + const observer = new ResizeObserver(() => { void fitting(); }); + observer.observe(element); + void fitting(); + void poll(); + return { dispose, hangUp: () => hangUp() }; +} diff --git a/js/pty/package.json b/js/pty/package.json new file mode 100644 index 00000000..c80e0dbe --- /dev/null +++ b/js/pty/package.json @@ -0,0 +1,20 @@ +{ + "name": "@webfront/pty", + "version": "0.1.0", + "type": "module", + "main": "index.mjs", + "types": "index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "default": "./index.mjs" + } + }, + "peerDependencies": { + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0" + }, + "license": "(Apache-2.0 OR CECILL-B)", + "files": ["index.mjs", "index.d.ts", "README.md", "LICENSE"] +} diff --git a/test/cmake/NodeGuardExceptions.cmake b/test/cmake/NodeGuardExceptions.cmake index 9baa902c..f839954b 100644 --- a/test/cmake/NodeGuardExceptions.cmake +++ b/test/cmake/NodeGuardExceptions.cmake @@ -31,6 +31,9 @@ set(NODE_GUARD_EXCEPTIONS "test/cmake/CheckRepositoryLayoutNegative.cmake|node-config|tracks such a directory in a scratch repository to prove that the layout guard rejects it" "docs/DEVELOPER_ENVIRONMENT.md|node-config|states which directories wf check never lists, the TypeScript layout among them" # Data of dependencies. + "examples/pty/webfront-packages.lock.json|node-command|the lock records xterm package metadata verbatim and no package scripts are run" + "examples/pty/webfront-packages.lock.json|npm-command|the lock records xterm package metadata verbatim and no package scripts are run" + "examples/pty/webfront-packages.lock.json|node-config|the lock records xterm package metadata verbatim and no package scripts are run" "js/developer/webfront-packages.lock.json|node-command|the lock records the package.json scripts of its dependencies verbatim, and nothing runs them" "js/developer/webfront-packages.lock.json|npm-command|the lock records the package.json scripts of its dependencies verbatim, and nothing runs them" "js/developer/webfront-packages.lock.json|node-config|the lock records the file lists of its dependencies verbatim" diff --git a/test/cmake/PrepareSelfBuildProject.cmake b/test/cmake/PrepareSelfBuildProject.cmake index 7ad85246..1877b450 100644 --- a/test/cmake/PrepareSelfBuildProject.cmake +++ b/test/cmake/PrepareSelfBuildProject.cmake @@ -7,6 +7,7 @@ file(REMOVE_RECURSE "${PROJECT}") file(MAKE_DIRECTORY "${PROJECT}" "${PROJECT}/include/webfront/system" "${PROJECT}/js/developer") file(COPY "${SOURCE}/LICENSE" DESTINATION "${PROJECT}") +file(COPY "${SOURCE}/js/pty" DESTINATION "${PROJECT}/js") file(COPY "${SOURCE}/js/react" DESTINATION "${PROJECT}/js") file(COPY "${SOURCE}/js/services" DESTINATION "${PROJECT}/js") file(COPY "${SOURCE}/js/core" DESTINATION "${PROJECT}/js") diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index bb1f73a3..991c03e5 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -415,7 +415,10 @@ int run(const Options& options, Setup&& setup = {}) { }; DriverDeadline deadlines{options.timeout}; Outcome outcome; - App app{options.project, {.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested}}; // 127.0.0.1: the test pages are not the embedded view + webfront::WebFrontConfig config{.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested}; + if constexpr (requires { setup.configureApplication(config); }) + setup.configureApplication(config); + App app{options.project, std::move(config)}; bool commandStarted = false; app.cppFunction("wf.commandStarted", [&] { if (std::exchange(commandStarted, true)) diff --git a/test/fixtures/pty/Probe.cpp b/test/fixtures/pty/Probe.cpp new file mode 100644 index 00000000..4c5fdcdf --- /dev/null +++ b/test/fixtures/pty/Probe.cpp @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include +#else + #include + + #include + #include + #include +#endif + +int main(int argc, char** argv) { + using namespace std::chrono_literals; + const std::string_view mode = argc > 1 ? argv[1] : ""; + if (mode == "stall") { +#ifdef _WIN32 + const auto pid = ::GetCurrentProcessId(); +#else + const auto pid = ::getpid(); + std::signal(SIGHUP, SIG_IGN); + termios settings{}; + if (::tcgetattr(STDIN_FILENO, &settings) != 0) + return 1; + ::cfmakeraw(&settings); + if (::tcsetattr(STDIN_FILENO, TCSANOW, &settings) != 0) + return 1; +#endif + std::cout << "STALLED:" << pid << ":END\n" << std::flush; + std::this_thread::sleep_for(30s); + return 2; + } + if (mode == "size") { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO info{}; + if (!::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE), &info)) + return 1; + std::cout << "SIZE:" << info.srWindow.Right - info.srWindow.Left + 1 << 'x' << info.srWindow.Bottom - info.srWindow.Top + 1 << '\n'; +#else + return 1; // Unix coverage uses stty. +#endif + return 0; + } +#ifdef _WIN32 + if (mode == "delayed-output") { + std::this_thread::sleep_for(300ms); + std::cout << "DESCENDANT_OUTPUT\n" << std::flush; + return 0; + } + if (mode == "leave-child") { + std::array executable{}; + const auto count = ::GetModuleFileNameW(nullptr, executable.data(), static_cast(executable.size())); + if (!count || count >= executable.size()) + return 1; + auto command = L'"' + std::wstring(executable.data(), count) + L'"' + L" delayed-output"; + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION child{}; + if (!::CreateProcessW(executable.data(), command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &child)) + return 2; + ::CloseHandle(child.hThread); + ::CloseHandle(child.hProcess); + return 42; + } +#endif + if (mode == "interrupt") { +#ifdef _WIN32 + // A runner can inherit the process-wide Ctrl+C ignore flag from its own launcher. + const auto input = ::GetStdHandle(STD_INPUT_HANDLE); + DWORD modeFlags = 0; + if (!::SetConsoleCtrlHandler(nullptr, FALSE) || !::GetConsoleMode(input, &modeFlags) || !::SetConsoleMode(input, modeFlags | ENABLE_PROCESSED_INPUT)) + return 5; +#endif + std::cout << "INTERRUPT_READY\n" << std::flush; + std::this_thread::sleep_for(30s); + return 2; + } +#ifndef _WIN32 + if (mode == "fd" && argc == 3) { + const auto fd = std::atoi(argv[2]); + return ::fcntl(fd, F_GETFD) < 0 && errno == EBADF ? 0 : 1; + } + if (mode == "flood") { + termios settings{}; + if (::tcgetattr(STDOUT_FILENO, &settings) != 0) + return 1; + ::cfmakeraw(&settings); + if (::tcsetattr(STDOUT_FILENO, TCSANOW, &settings) != 0) + return 2; + const auto* environment = std::getenv("WF_TEST_ENVIRONMENT"); + if (::access("marker", F_OK) != 0 || !environment || std::string_view(environment) != "explicit") + return 3; + std::array bytes{}; + for (std::size_t left = 1200000; left;) { + const auto count = ::write(STDOUT_FILENO, bytes.data(), left < bytes.size() ? left : bytes.size()); + if (count <= 0) + return 4; + left -= static_cast(count); + } + return ::write(STDOUT_FILENO, "COMPLETE", 8) == 8 ? 0 : 5; + } + if (mode == "reopen") { + const char* name = ::ttyname(STDIN_FILENO); + if (!name) + return 1; + const std::string path(name); + ::close(STDIN_FILENO); + ::close(STDOUT_FILENO); + ::close(STDERR_FILENO); + std::this_thread::sleep_for(250ms); + const auto slave = ::open(path.c_str(), O_WRONLY | O_NOCTTY); + return slave >= 0 && ::write(slave, "REOPENED", 8) == 8 ? 0 : 2; + } + if (mode == "orphan") { + int ready[2]{}; + if (::pipe(ready) < 0) + return 1; + const auto child = ::fork(); + if (child == 0) { + ::close(ready[0]); + if (::setpgid(0, 0) < 0) + ::_exit(2); + std::signal(SIGHUP, SIG_IGN); + if (::write(ready[1], "!", 1) != 1) + ::_exit(3); + ::close(ready[1]); + ::sleep(30); + ::_exit(4); + } + ::close(ready[1]); + char byte = 0; + if (child < 0 || ::read(ready[0], &byte, 1) != 1 || ::tcsetpgrp(STDIN_FILENO, child) < 0) + return 5; + std::cout << "STALLED:" << child << ":END" << std::flush; + return 0; + } +#endif + return 3; +} diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 131ece6d..0aaa3739 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -410,13 +410,20 @@ def consumer(args): assert owner.poll() is None, (root / "consumer.log").read_text() assert time.monotonic() < deadline, "The application never published its endpoint" time.sleep(0.05) - # Discoverable by an agent that was told nothing, without the capability. - listed = subprocess.run([args.agent, "--list", "--sessions-dir", str(sessions)], - capture_output=True, text=True, timeout=10) - assert listed.returncode == 0, listed.stderr + # The endpoint is published before the discovery record. Wait for the + # record as well, polling without the private attachment capability. token = json.loads((endpoint / "endpoint.json").read_text())["token"] - assert token not in listed.stdout + listed.stderr - entries = json.loads(listed.stdout)["sessions"] + while True: + listed = subprocess.run([args.agent, "--list", "--sessions-dir", str(sessions)], + capture_output=True, text=True, timeout=10) + assert listed.returncode == 0, listed.stderr + assert token not in listed.stdout + listed.stderr + entries = json.loads(listed.stdout)["sessions"] + if entries: + break + assert owner.poll() is None, (root / "consumer.log").read_text() + assert time.monotonic() < deadline, f"The application never registered its session: {listed.stdout}" + time.sleep(0.05) assert len(entries) == 1 and entries[0]["state"] == "running", listed.stdout assert sorted(entries[0]["allow"]) == sorted(["check", "build", "preview", "inspect", "interact", "call"]), entries assert entries[0]["callbacks"] == ["consumer.render"], entries diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 177344a1..448a4042 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -42,7 +42,7 @@ set_tests_properties(BddSelfTest BddDiscovery PROPERTIES TIMEOUT 30 LABELS fast) set(TESTS_LIST) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp HTTPRangeTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) -list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp) +list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp AutomationDiscoveryTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) @@ -72,6 +72,11 @@ target_link_libraries(host_probe PRIVATE WebFront_test_hardening WebFront_warnin add_dependencies(tests host_probe) target_compile_definitions(tests PRIVATE WEBFRONT_HOST_PROBE="$") +add_executable(pty_probe ../fixtures/pty/Probe.cpp) +target_link_libraries(pty_probe PRIVATE WebFront WebFront_test_hardening WebFront_warnings) +add_dependencies(tests pty_probe) +target_compile_definitions(tests PRIVATE WEBFRONT_PTY_PROBE="$") + # The heavy units instantiate a full application, and compile four to a file in about half the time of four apart # (docs/BUILD_TIME_STUDY.md): that is the default. 0 keeps one object per test file, which the portability and # sanitizer jobs ask for. The light units stay apart: grouping every unit does not compile, as their diff --git a/test/unit/DomDocumentTests.cpp b/test/unit/DomDocumentTests.cpp index 360e809b..46590127 100644 --- a/test/unit/DomDocumentTests.cpp +++ b/test/unit/DomDocumentTests.cpp @@ -644,7 +644,20 @@ const Scenario coroutineState{"A coroutine is the state machine of a sequential {back, "2"}, {next, "3"} }; +#if defined(_MSC_VER) && _MSC_VER >= 1952 + // MSVC 19.52 rejects stdexec's when_all with two coroutine task senders. + // Exercise both coroutines on the server's shared scheduler instead. + ::stdnet::io_context context; + networking::TaskScope scope; + const auto scheduler = context.get_scheduler(); + const bool wizardStarted = networking::Spawn(scope, scheduler, wizard(next, back, steps)); + const bool clicksStarted = networking::Spawn(scope, scheduler, clicks(document.state, std::move(sequence))); + context.run(); + scope.drain(context); + require(wizardStarted && clicksStarted); +#else ex::sync_wait(ex::when_all(wizard(next, back, steps), clicks(document.state, std::move(sequence)))); +#endif require(steps == std::vector{"name: 1", "back: 2", "done: 3"}); require(document.state->waiters.empty()); }}; diff --git a/test/unit/EncodingsTests.cpp b/test/unit/EncodingsTests.cpp index 585306bd..492cef8c 100644 --- a/test/unit/EncodingsTests.cpp +++ b/test/unit/EncodingsTests.cpp @@ -140,6 +140,10 @@ const Scenario webSocketSec{"WebSocket Sec Key coding", [] { }}; const Scenario base64Encoding{"Base64 encoding", [] { + require(base64::encode(std::string{}) == ""); + require(base64::encode(std::string{"f"}) == "Zg=="); + require(base64::encode(std::string{"fo"}) == "Zm8="); + require(base64::encode(std::string{"foo"}) == "Zm9v"); require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy dog")) == "L9ThxnotKPzthJ7hu3bnORuT6xI="); require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy cog")) == diff --git a/test/unit/PtyTests.cpp b/test/unit/PtyTests.cpp new file mode 100644 index 00000000..61fba390 --- /dev/null +++ b/test/unit/PtyTests.cpp @@ -0,0 +1,328 @@ +#include "Bdd.hpp" +#include "TemporaryDirectory.hpp" +#include + +#include +#include +#include +#include + +#ifndef _WIN32 + #include + #include +#endif + +namespace { +using namespace std::chrono_literals; +using namespace webfront; +using namespace webfront::bdd; + +std::string probe() { + const auto path = std::filesystem::path(WEBFRONT_PTY_PROBE).u8string(); + return {reinterpret_cast(path.data()), path.size()}; +} + +PtyOptions shell() { +#ifdef _WIN32 + return { + .argv = {"cmd.exe", "/d", "/q"}, + .directory = {}, + .environment = {}, + .size = {87, 26} + }; +#else + return { + .argv = {"sh", "-i"}, + .directory = {}, + .environment = {}, + .size = {87, 26} + }; +#endif +} + +void send(Pty& terminal, std::string_view text) { + require(terminal.write({reinterpret_cast(text.data()), text.size()})); +} + +struct Transcript { + std::uint64_t cursor = 0; + std::string text; + std::optional exit; + + void until(Pty& terminal, std::string_view marker) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration(8s * impl::timeoutFactor()); + do { + auto part = terminal.tryRead(cursor); + cursor = part.next; + if (!part.bytes.empty()) + text.append(reinterpret_cast(part.bytes.data()), part.bytes.size()); + exit = part.exitCode; + if (marker.empty() ? exit.has_value() : text.contains(marker)) + return; + std::this_thread::sleep_for(10ms); + } while (!exit && std::chrono::steady_clock::now() < deadline); + auto context = info("waiting for " + std::string(marker) + ", exit=" + (exit ? std::to_string(*exit) : "running") + ", output=" + text); + require(false); + } +}; + +unsigned stallPid(std::string_view text) { + const auto start = text.find("STALLED:") + std::string_view("STALLED:").size(); + unsigned pid = 0; + const auto [end, error] = std::from_chars(text.data() + start, text.data() + text.size(), pid); + require(error == std::errc{}); + require(end < text.data() + text.size() && *end == ':'); + return pid; +} + +bool running(unsigned pid) { +#ifdef _WIN32 + const HANDLE process = ::OpenProcess(SYNCHRONIZE, FALSE, static_cast(pid)); + if (!process) + return false; + const bool active = ::WaitForSingleObject(process, 0) == WAIT_TIMEOUT; + ::CloseHandle(process); + return active; +#else + if (::kill(static_cast(pid), 0) < 0) + return false; + #ifdef __linux__ + // The orphan can remain a zombie briefly (or indefinitely under a container PID 1). + std::ifstream status("/proc/" + std::to_string(pid) + "/stat"); + std::string line; + if (std::getline(status, line) && line.substr(line.rfind(')') + 2, 1) == "Z") + return false; + #endif + return true; +#endif +} + +const Scenario ptyShell{"PTY exchanges bytes with an interactive shell and resizes and interrupts its foreground", [] { + given("a native shell", [] { + Pty terminal(shell()); + Transcript output; +#ifdef _WIN32 + send(terminal, "\"" + probe() + "\" size\r"); + output.until(terminal, "SIZE:87x26"); +#else + send(terminal, "stty size; printf 'term=%s\\n' \"$TERM\"\n"); + output.until(terminal, "26 87"); + output.until(terminal, "term=xterm-256color"); +#endif + when("the application changes the terminal size", [&] { + terminal.resize({101, 33}); +#ifdef _WIN32 + send(terminal, "\"" + probe() + "\" size\r"); + output.until(terminal, "SIZE:101x33"); +#else + send(terminal, "stty size\n"); + output.until(terminal, "33 101"); +#endif + }); + then("the foreground command is interrupted and the shell exits with its own status", [&] { +#ifdef _WIN32 + // The console control event can also affect cmd itself. Exercise it with a directly hosted probe. + Pty foreground({ + .argv = {probe(), "interrupt"}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript interrupted; + interrupted.until(foreground, "INTERRUPT_READY"); + send(foreground, "\x03"); + interrupted.until(foreground, ""); + require(interrupted.exit == static_cast(0xc000013au)); + send(terminal, "echo HELLO_&echo _PTY\rexit 42\r"); + output.until(terminal, "_PTY"); +#else + send(terminal, "\"" + probe() + "\" interrupt\n"); + output.until(terminal, "INTERRUPT_READY"); + send(terminal, "\x03"); + send(terminal, "exit 42\n"); +#endif + output.until(terminal, ""); + require(output.exit == 42); + auto replay = terminal.tryRead(0); + require(!replay.bytes.empty()); + require(!replay.truncated); + }); + }); + }}; + +const Scenario ptyHangUp{"PTY refuses oversized input promptly and terminates a stalled foreground descendant", [] { + Pty terminal(shell()); + Transcript output; +#ifdef _WIN32 + send(terminal, "\"" + probe() + "\" stall\r"); +#else + send(terminal, "\"" + probe() + "\" stall\n"); +#endif + output.until(terminal, ":END"); + const auto pid = stallPid(output.text); + require(running(pid)); + const std::vector paste(4 * 1024 * 1024, 'x'); + then("large input is refused and the pending queue has a fixed limit", [&] { + const auto start = std::chrono::steady_clock::now(); + require(!terminal.write(paste)); + const auto packet = std::span{paste}.first(Pty::inputCapacity); + bool full = false; + for (int i = 0; i < 20 && !full; ++i) + full = !terminal.write(packet); + require(full); + require(std::chrono::steady_clock::now() - start < 1s); + }); + then("hangUp terminates the foreground descendant and publishes the shell status", [&] { + terminal.hangUp(); + output.until(terminal, ""); + const auto deadline = std::chrono::steady_clock::now() + 2s; + while (running(pid) && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(10ms); + require(!running(pid)); + require(!terminal.write({})); + }); + }}; + +const Scenario ptyInterruptRead{"PTY blocking reads observe a stop request", [] { + Pty terminal({ + .argv = {probe(), "stall"}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript output; + output.until(terminal, ":END"); + std::stop_source stop; + auto result = std::async(std::launch::async, [&] { + return terminal.read(output.cursor, stop.get_token()); + }); + require(result.wait_for(50ms) == std::future_status::timeout); + stop.request_stop(); + const auto ready = result.wait_for(1s); + if (ready != std::future_status::ready) + terminal.hangUp(); + require(ready == std::future_status::ready); + const auto cancelled = result.get(); + require(cancelled.bytes.empty()); + require(cancelled.next == output.cursor); + require(!cancelled.exitCode); + }}; + +#ifdef _WIN32 +const Scenario ptyDescendantOutput{"ConPTY drains a descendant's output after the leader exits", [] { + Pty terminal({ + .argv = {probe(), "leave-child"}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript output; + output.until(terminal, "DESCENDANT_OUTPUT"); + output.until(terminal, ""); + require(output.exit == 42); + }}; + +const Scenario ptyBatchShim{"PTY resolves Windows npm-style batch shims from the explicit PATH", [] { + webfront::test::TemporaryDirectory directory; + const auto root = directory.path(); + { + std::ofstream script(root / "pty test.cmd"); + script << "@echo off\r\necho [\"%~1\"]\r\nexit /b 42\r\n"; + } + const auto path = root.u8string(); + Pty terminal({ + .argv = {"pty test", "a & b"}, + .directory = root, + .environment = {{"Path", {reinterpret_cast(path.data()), path.size()}}}, + .size = {} + }); + Transcript output; + output.until(terminal, "[\"a & b\"]"); + output.until(terminal, ""); + require(output.exit == 42); + }}; +#endif + +#ifndef _WIN32 +const Scenario ptyReplay{"PTY resolves PATH in the child directory and bounds its output history", [] { + webfront::test::TemporaryDirectory directory; + const auto root = directory.path(); + std::ofstream(root / "marker").put('!'); + std::filesystem::create_symlink(std::filesystem::path(WEBFRONT_PTY_PROBE), root / "terminal-flood"); + Pty terminal({ + .argv = {"terminal-flood", "flood"}, + .directory = root, + .environment = {{"PATH", ".:/usr/bin:/bin"}, {"WF_TEST_ENVIRONMENT", "explicit"}}, + .size = {} + }); + requireEventually( + [&] { + return terminal.exitCode().has_value(); + }, + 15s); + auto context = info("child exit: " + std::to_string(terminal.exitCode().value())); + require(terminal.exitCode() == 0); + auto part = terminal.tryRead(0); + require(part.truncated); + require(part.bytes.size() == Pty::readChunk); + require(part.next - part.bytes.size() == 1200008 - Pty::replayCapacity); + std::uint64_t cursor = part.next; + while (!part.exitCode) { + part = terminal.tryRead(cursor); + cursor = part.next; + } + const std::string tail(reinterpret_cast(part.bytes.data()), part.bytes.size()); + require(tail.ends_with("COMPLETE")); + }}; + +const Scenario ptyReopen{"PTY resumes output when the live child reopens its slave", [] { + Pty terminal({ + .argv = {probe(), "reopen"}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript output; + output.until(terminal, "REOPENED"); + output.until(terminal, ""); + require(output.exit == 0); + }}; + +const Scenario ptyOrphan{"PTY cleans up a foreground group that ignores SIGHUP after the session leader exits", [] { + Pty terminal({ + .argv = {probe(), "orphan"}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript output; + output.until(terminal, ":END"); + const auto pid = stallPid(output.text); + output.until(terminal, ""); + require(output.exit == 0); + requireEventually( + [&] { + return !running(pid); + }, + 3s); + }}; + +const Scenario ptyDescriptors{"PTY child does not inherit an application descriptor", [] { + pty::detail::PtyFd socket{::socket(AF_INET, SOCK_STREAM, 0)}; + require(socket.get() >= 0); + // Reserve a number the loader won't normally use for its own files. + pty::detail::PtyFd descriptor{::fcntl(socket.get(), F_DUPFD, 100)}; + require(descriptor.get() >= 3); + require(::fcntl(descriptor.get(), F_GETFD) == 0); + Pty terminal({ + .argv = {probe(), "fd", std::to_string(descriptor.get())}, + .directory = {}, + .environment = {}, + .size = {} + }); + Transcript output; + output.until(terminal, ""); + require(output.exit == 0); + }}; +#endif +} // namespace diff --git a/test/unit/WebFrontTests.cpp b/test/unit/WebFrontTests.cpp index 72f75932..d7297ac9 100644 --- a/test/unit/WebFrontTests.cpp +++ b/test/unit/WebFrontTests.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -42,6 +43,52 @@ const Scenario publicVersion{"The public version matches the version detected by }); }}; +const Scenario ptyPageAuthorization{"PTY page requires explicit opt-in, a loopback bind and the application Origin", [] { + then("registration is refused by default and opt-in rejects wildcard and non-loopback binds", [] { + WebFront app{WebFrontConfig{.port = "0"}}; + requireThrows([&] { registerPtyPage(app, {}); }); + require(!app.hasCppFunction("webfront.pty.open")); + for (const auto* address : {"0.0.0.0", "::", "192.0.2.1", "localhost", "0:0:0:0:0:0:0:1"}) { + requireThrows([&] { + WebFront rejected{WebFrontConfig{.address = address, .port = "0", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true}}; + }); + } + }); + then("configuration rejects a bridge policy that would allow missing or foreign origins", [] { + for (const auto& policy : {ContentPolicy{}, ContentPolicy{.allowAnyBridgeOrigin = true, .allowMissingOrigin = false}, + ContentPolicy{.bridgeAllowedOrigins = {"http://foreign.example"}, .allowMissingOrigin = false}}) { + requireThrows([&] { + WebFront app{WebFrontConfig{.port = "0", .contentPolicy = policy, .allowPtyPages = true}}; + }); + } + }); + then("the upgrade handler accepts the application's own Origin and refuses missing or foreign Origin", [] { + using namespace webfront::http; + const auto config = webfront::detail::checkedPtyPageConfig({ + .contentPolicy = {.allowMissingOrigin = false}, + .allowPtyPages = true + }); + RequestHandler> handler{ + ".", webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002/", config.contentPolicy} + }; + const auto upgrade = [&](std::string_view origin) { + std::string input = "GET / HTTP/1.1\r\nHost: 127.0.0.1:9002\r\nUpgrade: websocket\r\n" + "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"; + input += origin; + input += "\r\n"; + Request request; + require(request.parseSomeData(input.begin(), input.end())); + return handler.handleRequest(request).statusCode; + }; + require(upgrade("") == Response::forbidden); + require(upgrade("Origin: http://foreign.example\r\n") == Response::forbidden); + require(upgrade("Origin: http://127.0.0.1:9002\r\n") == Response::switchingProtocols); + require(webfront::detail::checkedPtyPageConfig({ + .address = "::1", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true + }).address == "::1"); + }); +}}; + namespace { using TestFilesystem = MockFileSystem<>; diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index bf8716be..5f691756 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -527,9 +527,8 @@ if(_browser_tests_available) REQUIRES SelfBuildProject TestRegistry PROVIDES SelfBuildInstalled) webfront_add_self_build_test(SelfBuild 0 "run|build|build-distribution" OUTPUT "Script build completed" REQUIRES SelfBuildInstalled PROVIDES SelfBuilt) - # The optional packages, @webfront/react and @webfront/services (#461): from their own sources to the exact archive that - # the registry serves. - foreach(_package "ReactAdapter|react|React|React adapter:" "Services|services|Services|Services package:") + # The registry serves the same bytes as each optional package script. + foreach(_package "ReactAdapter|react|React|React adapter:" "Services|services|Services|Services package:" "Pty|pty|PTY|PTY package:") string(REPLACE "|" ";" _package "${_package}") list(GET _package 0 _name) list(GET _package 1 _directory) diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 83c39a81..7fddb14e 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "../driver/WfDriver.hpp" @@ -113,6 +114,11 @@ class BrowserIntegrationTest { if (!mediaFile.empty()) filesystem::remove(mediaFile, ignored); } + void configureApplication(WebFrontConfig& config) { + config.contentPolicy.allowMissingOrigin = false; + config.allowPtyPages = true; + } + /// Registers the callbacks of the specs before the page opens; the rejecting WebSocket server starts after the CEF /// subprocesses have dispatched (driver main), in the browser process. void configure(TestWF& app) { @@ -120,6 +126,14 @@ class BrowserIntegrationTest { webFront = &app; rejectedWebSocket.emplace(); registerCallbacks(); + registerPtyPage(app, { +#ifdef _WIN32 + .argv = {"cmd.exe", "/d", "/q"}, +#else + .argv = {"sh", "-i"}, +#endif + .directory = {}, .environment = {{"WF_PTY_MARKER", "WEBFRONT_PTY_OK"}}, .size = {} + }); registerBitsetCallbacks(); registerListCallbacks(); lifeReactSubscription = demo::installLifeReact(app); diff --git a/test/web/registry/build.mjs b/test/web/registry/build.mjs index 0991d7cc..efb2a9be 100644 --- a/test/web/registry/build.mjs +++ b/test/web/registry/build.mjs @@ -6,6 +6,7 @@ // test/web/registry-packages.json), kept byte for byte; the synthetic ones are generated. The registry's files go to // build-registry/, next to an integrities.json of every package. import {realPackage, syntheticPackages, registryFiles} from './fixture.mjs'; +import {ptyPackage} from '../../../js/developer/scripts/pty-package.mjs'; import {reactPackage} from '../../../js/developer/scripts/react-package.mjs'; import {servicesPackage} from '../../../js/developer/scripts/services-package.mjs'; @@ -16,7 +17,8 @@ export default async function (context) { if (!archives.length) throw new Error('registry-archives holds no archive'); const packages = []; for (const name of archives) packages.push(await realPackage(await project.read(`registry-archives/${name}`))); - // Preserve exactly the same archive bytes that `wf run react-package` and `wf run services-package` write. + // Preserve exactly the same archive bytes that the optional package scripts write. + packages.push(await ptyPackage(project)); packages.push(await reactPackage(project)); packages.push(await servicesPackage(project)); const {files, integrities} = await registryFiles([...packages, ...syntheticPackages()]); diff --git a/test/web/suite/specs/pty-specs.mjs b/test/web/suite/specs/pty-specs.mjs new file mode 100644 index 00000000..e9f2ce55 --- /dev/null +++ b/test/web/suite/specs/pty-specs.mjs @@ -0,0 +1,97 @@ +import { mount } from '@webfront/pty'; + +describe('Native PTY page adapter', () => { + const call = operation => webFront.cppFunction('webfront.pty.' + operation); + + function completion() { + let resolve, reject; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return {promise, resolve, reject}; + } + + function xtermProbe() { + const decoder = new TextDecoder(); + return { + text: '', + cols: 87, + rows: 29, + loadAddon() {}, + open() {}, + onData(callback) { + this.send = callback; + return {dispose: () => { this.send = undefined; }}; + }, + onBinary() { return {dispose() {}}; }, + reset() { this.text = ''; }, + write(bytes, done) { + this.text += decoder.decode(bytes, {stream: true}); + done(); + }, + }; + } + + it('reads one terminal byte stream across split UTF-8 sequences', async () => { + const terminal = xtermProbe(); + const bridge = { + ready: Promise.resolve(), + cppFunction(name) { + if (!name.endsWith('.read')) return async () => {}; + return async (_generation, offset) => [ + [1, '4g==', false, false, 0], + [2, 'gg==', false, false, 0], + [3, 'rA==', false, true, 42], + ][offset]; + }, + }; + const element = document.createElement('div'); + const exit = completion(); + const session = await mount(element, {terminal, fit: {fit() {}}, webFront: bridge, onExit: exit.resolve, onError: exit.reject}); + try { + expect(await exit.promise).toBe(42); + expect(terminal.text).toBe('€'); + } finally { + session.dispose(); + } + }); + + it('drives a native shell, rejects an oversized input and replays after reattachment', async () => { + const [generation, otherAttachment, reply] = await Promise.all([ + call('open')(false), + call('open')(false), + webFront.cppFunction('returnFromCpp')('pty startup'), + ]); + expect(otherAttachment).toBe(generation); + expect(reply).toBe('cpp-result:pty startup'); + expect(await call('write')(generation, new Uint8Array(4 * 1024 * 1024))).toBeFalse(); + await expectAsync(call('open')(true)).toBeRejected(); + expect(await webFront.cppFunction('returnFromCpp')('pty')).toBe('cpp-result:pty'); + const element = document.createElement('div'); + const terminal = xtermProbe(); + const exit = completion(); + const session = await mount(element, {terminal, fit: {fit() {}}, onExit: exit.resolve, onError: exit.reject}); + try { + // cmd expands the percent form and sh expands the dollar form. Neither + // input echo contains the value, and the PTY may paint it with cursor moves. + terminal.send('echo $WF_PTY_MARKER%WF_PTY_MARKER%\r'); + terminal.send('exit 42\r'); + expect(await exit.promise).toBe(42); + expect(terminal.text).toContain('WEBFRONT_PTY_OK'); + } finally { + session.dispose(); + } + + const replay = xtermProbe(); + const replayExit = completion(); + const reattached = await mount(element, {terminal: replay, fit: {fit() {}}, onExit: replayExit.resolve, onError: replayExit.reject}); + try { + expect(await replayExit.promise).toBe(42); + expect(replay.text).toBe(terminal.text); + const restarted = await call('open')(true); + expect(restarted).not.toBe(generation); + await expectAsync(call('write')(generation, new Uint8Array([3]))).toBeRejected(); + await call('hangUp')(restarted); + } finally { + reattached.dispose(); + } + }); +}); diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index c9c6bd8d..135645f8 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -1,4 +1,5 @@ import './react-specs.mjs'; +import './pty-specs.mjs'; import './host-loop-specs.mjs'; import './services-specs.mjs'; import './fallback-specs.mjs'; diff --git a/test/web/suite/tsconfig.json b/test/web/suite/tsconfig.json index 08d5636a..9266ab89 100644 --- a/test/web/suite/tsconfig.json +++ b/test/web/suite/tsconfig.json @@ -16,6 +16,7 @@ "files": [ "types/react.tsx", "types/services.ts", + "types/pty.ts", "pages/life-react.tsx" ] } diff --git a/test/web/suite/types/pty.ts b/test/web/suite/types/pty.ts new file mode 100644 index 00000000..f1144dd8 --- /dev/null +++ b/test/web/suite/types/pty.ts @@ -0,0 +1,13 @@ +import { mount } from '@webfront/pty'; +import { Terminal } from '@xterm/xterm'; +import { FitAddon } from '@xterm/addon-fit'; + +export async function attach(element: HTMLElement): Promise { + const page = await mount(element, { + terminal: new Terminal(), + fit: new FitAddon(), + onExit: code => { element.dataset.exitCode = code.toString(); }, + }); + await page.hangUp(); + page.dispose(); +} diff --git a/test/web/suite/webfront.project.json b/test/web/suite/webfront.project.json index d0f73ead..f51d2081 100644 --- a/test/web/suite/webfront.project.json +++ b/test/web/suite/webfront.project.json @@ -6,6 +6,9 @@ "jasmine-core": "7.0.2", "react": "19.3.1", "react-dom": "19.3.1", + "@webfront/pty": "0.1.0", + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0", "@webfront/react": "0.1.0", "@webfront/services": "0.1.0", "typescript": "5.9.3",