Port psyTerm to macOS and package a native app bundle
This commit is contained in:
Generated
+33
-32
@@ -130,9 +130,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "ar_archive_writer"
|
||||
version = "0.5.5"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
|
||||
checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
|
||||
dependencies = [
|
||||
"object",
|
||||
]
|
||||
@@ -743,9 +743,9 @@ checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.4"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
@@ -840,9 +840,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.2"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
|
||||
checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
@@ -1002,7 +1002,7 @@ version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b60b5124979fccd9addd89d8b97a1d6eebb4950694520c75ddd722535ea443f"
|
||||
dependencies = [
|
||||
"nix 0.31.4",
|
||||
"nix 0.31.3",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -1591,9 +1591,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1703,9 +1703,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.30"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
@@ -2875,9 +2875,9 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "0.2.46"
|
||||
version = "0.2.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f"
|
||||
checksum = "fefca06093eeaed707a905795e68206da0edca4edef23d2a3997a3ddbee462aa"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"jiff-static",
|
||||
@@ -2889,18 +2889,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff-core"
|
||||
version = "0.1.8"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b"
|
||||
checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.46"
|
||||
version = "0.2.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba"
|
||||
checksum = "41d3213549742662eea1a18e6c5af9be5dfbabeb7611ab71356a54928ec398f0"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"proc-macro2",
|
||||
@@ -3258,9 +3258,9 @@ checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff"
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.5"
|
||||
version = "1.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
@@ -3368,9 +3368,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.31.4"
|
||||
version = "0.31.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7"
|
||||
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
@@ -4027,6 +4027,7 @@ dependencies = [
|
||||
"gpui",
|
||||
"libc",
|
||||
"log",
|
||||
"nix 0.29.0",
|
||||
"serde",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
@@ -4090,7 +4091,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand 0.10.4",
|
||||
"rand 0.10.3",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash 2.1.3",
|
||||
@@ -4161,9 +4162,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.4"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
@@ -4451,9 +4452,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||
|
||||
[[package]]
|
||||
name = "rust-embed"
|
||||
version = "8.14.0"
|
||||
version = "8.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e98f580cf7a2863aeb6827800283f52cbe6fb3f3bb7c1843783f903c16dcb8ad"
|
||||
checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23"
|
||||
dependencies = [
|
||||
"rust-embed-impl",
|
||||
"rust-embed-utils",
|
||||
@@ -4462,9 +4463,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rust-embed-impl"
|
||||
version = "8.14.0"
|
||||
version = "8.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a93e2f69cf224a6c7df7509aa5ba4a23f56828ee41b040e92ac8762371eb9ba7"
|
||||
checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053"
|
||||
dependencies = [
|
||||
"mime_guess",
|
||||
"proc-macro2",
|
||||
@@ -4476,9 +4477,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rust-embed-utils"
|
||||
version = "8.14.0"
|
||||
version = "8.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"
|
||||
checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"sha2 0.11.1",
|
||||
@@ -5889,9 +5890,9 @@ checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.29.3"
|
||||
version = "1.29.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
|
||||
checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
|
||||
+21
-2
@@ -4,20 +4,39 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[package.metadata.bundle]
|
||||
name = "psyTerm"
|
||||
identifier = "dev.buzzert.psyterm"
|
||||
category = "Developer Tool"
|
||||
icon = ["assets/psyTerm.icns"]
|
||||
resources = [
|
||||
"THIRD_PARTY_NOTICES.md",
|
||||
"licenses",
|
||||
"vendor/gpui/LICENSE-APACHE",
|
||||
"vendor/gpui/PATCH.md",
|
||||
"vendor/xattr/LICENSE-*",
|
||||
]
|
||||
short_description = "Terminal emulator and multiplexer"
|
||||
|
||||
[dependencies]
|
||||
alacritty_terminal = "=0.26.0"
|
||||
anyhow = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
bincode = "1.3"
|
||||
async-channel = "2"
|
||||
gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] }
|
||||
log = "0.4"
|
||||
env_logger = "0.11"
|
||||
futures-lite = "2"
|
||||
unicode-segmentation = "1"
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
libc = "0.2"
|
||||
gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Embed Metal source so building the app needs only the Xcode command line tools.
|
||||
gpui = { version = "=0.2.2", default-features = false, features = ["font-kit", "runtime_shaders"] }
|
||||
nix = { version = "0.29", features = ["event", "poll", "signal", "user"] }
|
||||
|
||||
[patch.crates-io]
|
||||
# GPUI's zed-async-tar uses xattr 0.2.3, whose Linux ENOATTR alias was removed
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# psyTerm
|
||||
|
||||
A Wayland terminal and multiplexer built with [GPUI 0.2.2](https://gpui.rs/)
|
||||
A terminal and multiplexer for macOS and Linux (Wayland), built with [GPUI 0.2.2](https://gpui.rs/)
|
||||
and [alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/).
|
||||
A separate server owns terminal emulation, shells, tabs, panes, and scrollback.
|
||||
GUI processes display its snapshots and send input commands. Closing a window
|
||||
@@ -8,8 +8,41 @@ detaches it; the shells keep running for the next local or remote connection.
|
||||
|
||||
## Build and run
|
||||
|
||||
Use recent stable Rust (development uses 1.96) and Linux 5.3 or newer. GUI
|
||||
processes require a running Wayland desktop and a working Vulkan driver.
|
||||
Use recent stable Rust and build with `--locked` to use the dependency versions
|
||||
in `Cargo.lock`.
|
||||
|
||||
### macOS
|
||||
|
||||
Install Xcode or its Command Line Tools (`xcode-select --install`). GPUI embeds
|
||||
its Metal shader source and compiles it when the GUI opens. To launch from a
|
||||
checkout, run `cargo run --locked`.
|
||||
|
||||
Install cargo-bundle once to build the Finder-launchable app. This is the
|
||||
version used by [Zed](https://github.com/zed-industries/zed/blob/main/script/bundle-mac).
|
||||
|
||||
```sh
|
||||
cargo install --locked --git https://github.com/zed-industries/cargo-bundle \
|
||||
--rev 2be2669972dff3ddd4daf89a2cb29d2d06cad7c7 cargo-bundle
|
||||
```
|
||||
|
||||
Build the release executable, package it, and sign the bundle locally.
|
||||
|
||||
```sh
|
||||
cargo build --locked --release
|
||||
CARGO_BUNDLE_SKIP_BUILD=true cargo bundle --release --format osx --select-workspace-root
|
||||
codesign --force --sign - target/release/bundle/osx/psyTerm.app
|
||||
open target/release/bundle/osx/psyTerm.app
|
||||
```
|
||||
|
||||
You can copy `psyTerm.app` to Applications. The bundle and CLI both open a GUI
|
||||
in the launching process and connect to the same local server. Use `open -n`
|
||||
with the app path for another window. The bundle's
|
||||
`Contents/MacOS/psyterm` executable also accepts the CLI commands below.
|
||||
|
||||
### Linux
|
||||
|
||||
Use Linux 5.3 or newer. GUI processes require a running Wayland desktop and
|
||||
a working Vulkan driver.
|
||||
The server and SSH bridge do not initialize GPUI, Wayland, or Vulkan, although
|
||||
the shared executable still needs its dynamically linked libraries installed.
|
||||
|
||||
@@ -44,13 +77,18 @@ cargo build --locked --release
|
||||
|
||||
The default command starts or reuses a local server, asks its zygote to fork a
|
||||
GUI, and returns. Running it again opens another view of the same workspace.
|
||||
The first attachment to an empty server creates a shell. Shells use the
|
||||
server's `$SHELL` (falling back to `/bin/sh`), environment, and startup directory;
|
||||
they receive `TERM=xterm-256color` and `COLORTERM=truecolor`.
|
||||
|
||||
The server retains its startup environment. Set shell or GUI environment
|
||||
preferences before starting that server, or use `--gui` to launch a diagnostic
|
||||
GUI directly from the current environment. After rebuilding, the server refreshes
|
||||
### Shells and sessions
|
||||
|
||||
The first attachment to an empty server creates a shell in the server's startup
|
||||
directory. Shells inherit the server's environment and receive
|
||||
`TERM=xterm-256color` and `COLORTERM=truecolor`. The server uses `$SHELL`
|
||||
when set. On macOS it starts a login shell and falls back to the shell in
|
||||
your account settings. On Linux the fallback is `/bin/sh`.
|
||||
|
||||
The server retains its startup environment. Set shell preferences before
|
||||
starting the server. On Linux, use `--gui` to launch a diagnostic GUI directly
|
||||
from the current environment. After rebuilding on Linux, the server refreshes
|
||||
its zygote for new GUI windows, preserving existing windows and shells. Changes
|
||||
to server logic or the protocol still require restarting the server;
|
||||
`--shutdown` also ends its shell sessions.
|
||||
@@ -64,9 +102,9 @@ Finish any running work first, since shutdown ends its sessions, then launch
|
||||
|
||||
| Command | Behavior |
|
||||
| --- | --- |
|
||||
| `psyterm` | Open a local window through the server's zygote |
|
||||
| `psyterm` | Open a local window attached to the server |
|
||||
| `psyterm --remote user@host` | Open a local GUI connected to the remote server over SSH |
|
||||
| `psyterm --gui` | Launch a GUI directly, bypassing the zygote |
|
||||
| `psyterm --gui` | Run the GUI in the current process |
|
||||
| `psyterm --list` | Inspect tabs and panes in the running local server |
|
||||
| `psyterm --shutdown` | Stop the local server and end its sessions |
|
||||
| `psyterm --server` | Run the terminal server in the foreground |
|
||||
@@ -75,16 +113,17 @@ Finish any running work first, since shutdown ends its sessions, then launch
|
||||
|
||||
By default the socket is `$XDG_RUNTIME_DIR/psyterm/server.sock`, with a private
|
||||
per-user temporary directory as fallback. A custom socket must have a real,
|
||||
user-owned parent directory with mode `0700`:
|
||||
user-owned parent directory with mode `0700`.
|
||||
|
||||
```sh
|
||||
mkdir -m 700 "$XDG_RUNTIME_DIR/psyterm-dev"
|
||||
cargo run --locked -- --socket "$XDG_RUNTIME_DIR/psyterm-dev/server.sock"
|
||||
socket_dir=$(mktemp -d /tmp/psyterm.XXXXXXXX)
|
||||
cargo run --locked -- --socket "$socket_dir/server.sock"
|
||||
```
|
||||
|
||||
Sockets and log files are private to the current UID; peers are checked with
|
||||
Linux credentials. Server and zygote logs are beside the socket as
|
||||
`server.sock.log` and `server.sock.zygote.log`.
|
||||
Sockets and log files are private to the current UID. psyTerm checks the peer's
|
||||
UID using `getpeereid` on macOS and `SO_PEERCRED` on Linux. The server logs
|
||||
to `server.sock.log` beside the socket. The Linux zygote logs to
|
||||
`server.sock.zygote.log`.
|
||||
|
||||
SSH uses `BatchMode=yes`: configure key/agent authentication and known-host trust
|
||||
before connecting. The remote host needs a compatible `psyterm` executable in
|
||||
@@ -210,7 +249,7 @@ scrollback by default.
|
||||
| --- | --- |
|
||||
| `server.rs`, `session.rs` | Authoritative workspace, PTYs, child processes, parser, terminal grids, selection, scrolling, and resize |
|
||||
| `protocol.rs`, `client.rs` | Versioned bounded messages, local socket / SSH transport, snapshot delivery |
|
||||
| `launcher.rs` | Server startup, private paths, lifecycle locks, and the server-owned GUI zygote |
|
||||
| `launcher.rs` | Server startup, private paths, lifecycle locks, and platform-specific GUI launch |
|
||||
| `terminal.rs` | Snapshot-only GUI workspace and panes, command dispatch, focus, and animation scheduling |
|
||||
| `commands.rs`, `bindings.rs`, `palette.rs` | Extensible command metadata, optional shortcuts, searchable nested menus |
|
||||
| `pane_name.rs`, `label.rs` | Pane name editor, Unicode composition, and middle-truncated labels |
|
||||
@@ -218,7 +257,7 @@ scrollback by default.
|
||||
| `chrome.rs`, `colors.rs`, `fonts.rs` | Window chrome, terminal colors, font selection |
|
||||
| `input.rs`, `main.rs` | Key/paste encoding and CLI/process-role dispatch |
|
||||
|
||||
The server starts the zygote on demand and manages its lifetime. The zygote
|
||||
On Linux, the server starts the zygote on demand and manages its lifetime. The zygote
|
||||
checks that it is single-threaded and forks GUI children **before** GPUI,
|
||||
Wayland, Vulkan, font discovery, or executors initialize. Children inherit the
|
||||
loaded executable mappings and avoid another `exec`; graphics and font setup
|
||||
@@ -289,10 +328,8 @@ executable refreshed its zygote while the original GUI and shell stayed alive.
|
||||
New live checks cover palette search/submenus and input isolation, Zellij
|
||||
navigation bindings, stack insertion in both directions, collapsed-pane focus,
|
||||
exit cleanup, and stack reattachment. A second client's focus changes preserve
|
||||
palette input. These are Linux checks; remote-network latency and macOS remain
|
||||
unverified.
|
||||
palette input. These checks cover Linux Wayland.
|
||||
|
||||
Linux Wayland is the implemented platform; macOS is a future target. Current
|
||||
limits include no arbitrary split trees or floating panes, shared per-server
|
||||
Current limits include no arbitrary split trees or floating panes, shared per-server
|
||||
viewport state, no disk-restored sessions, no configuration files, no application mouse reporting,
|
||||
no Kitty keyboard protocol, no OSC 52 clipboard access, and no clickable links.
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||
<defs>
|
||||
<linearGradient id="panel" x2=".7" y2="1" gradientUnits="objectBoundingBox">
|
||||
<stop stop-color="#302447"/>
|
||||
<stop offset="1" stop-color="#080917"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="phosphor" x2="0" y2="1">
|
||||
<stop stop-color="#dac0ff"/>
|
||||
<stop offset="1" stop-color="#9858f9"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="18" y="19" width="220" height="220" rx="49" fill="url(#panel)" stroke="#382f4f" stroke-width="2"/>
|
||||
<path d="M63 90v23c0 19 14 32 36 32s36-13 36-32V90 M99 78v99"
|
||||
fill="none" stroke="url(#phosphor)" stroke-width="15" stroke-linecap="round"/>
|
||||
<path d="M143 169h50" stroke="#4bdbf1" stroke-width="14" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 795 B |
+56
-394
@@ -1,7 +1,8 @@
|
||||
//! Local daemon startup and the server-owned, single-threaded GUI zygote.
|
||||
//!
|
||||
//! GPUI, fonts, Wayland, Vulkan, and executors are initialized only in forked GUI
|
||||
//! children. Forking a process after any of those start threads is unsupported.
|
||||
//! Local daemon startup, private sockets and process roles.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod zygote;
|
||||
|
||||
use std::{
|
||||
fs::{self, DirBuilder, File, OpenOptions},
|
||||
io,
|
||||
@@ -9,8 +10,8 @@ use std::{
|
||||
fd::AsRawFd,
|
||||
unix::{
|
||||
ffi::{OsStrExt, OsStringExt},
|
||||
fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
net::{UnixListener, UnixStream},
|
||||
fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
|
||||
net::UnixStream,
|
||||
process::CommandExt,
|
||||
},
|
||||
},
|
||||
@@ -21,7 +22,6 @@ use std::{
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::protocol::{self, ClientMessage, ServerMessage};
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn ensure_server(socket: &Path) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
let log_path = suffixed(socket, ".log");
|
||||
let mut child = spawn_role("--server", socket, &log_path)?;
|
||||
let mut child = spawn_role_from(&executable_path()?, "--server", socket, &log_path)?;
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
if probe_server(socket)? {
|
||||
@@ -170,291 +170,13 @@ fn control_stream_version(
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned by the terminal server. Its GUI children are independent clients and
|
||||
/// keep running when this helper is stopped; stopping the helper never kills them.
|
||||
pub struct Zygote {
|
||||
server_socket: PathBuf,
|
||||
socket: PathBuf,
|
||||
child: Child,
|
||||
ready: bool,
|
||||
executable: PathBuf,
|
||||
executable_identity: ExecutableIdentity,
|
||||
}
|
||||
|
||||
impl Zygote {
|
||||
pub fn start(server_socket: &Path) -> Result<Self> {
|
||||
ensure_socket_parent(server_socket)?;
|
||||
let socket = suffixed(server_socket, ".zygote.sock");
|
||||
let log_path = suffixed(server_socket, ".zygote.log");
|
||||
let executable = executable_path()?;
|
||||
let executable_identity = ExecutableIdentity::read(&executable)?;
|
||||
let child = spawn_role_from(&executable, "--zygote", &socket, &log_path)?;
|
||||
let mut zygote = Self {
|
||||
server_socket: server_socket.to_owned(),
|
||||
socket,
|
||||
child,
|
||||
ready: false,
|
||||
executable,
|
||||
executable_identity,
|
||||
};
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
if let Ok(LaunchResponse::Ready { pid }) = zygote.request(&LaunchRequest::Ping) {
|
||||
if pid != zygote.child.id() {
|
||||
bail!(
|
||||
"a different GUI zygote is already listening at {}",
|
||||
zygote.socket.display()
|
||||
);
|
||||
}
|
||||
zygote.ready = true;
|
||||
return Ok(zygote);
|
||||
}
|
||||
if let Some(status) = zygote.child.try_wait()? {
|
||||
bail!(
|
||||
"psyTerm zygote exited ({status}); see {}",
|
||||
log_path.display()
|
||||
);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"psyTerm zygote startup timed out; see {}",
|
||||
log_path.display()
|
||||
);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_window(&mut self, remote: Option<String>) -> Result<()> {
|
||||
let executable = executable_path()?;
|
||||
let identity = ExecutableIdentity::read(&executable)?;
|
||||
let helper_exited = self.child.try_wait()?.is_some();
|
||||
if helper_exited || executable != self.executable || identity != self.executable_identity {
|
||||
log::info!("Refreshing GUI zygote after executable replacement or helper exit");
|
||||
self.stop();
|
||||
// Assignment drops the stopped helper only after a replacement is
|
||||
// ready. If startup fails, a later launch can retry this stopped one.
|
||||
*self = Self::start(&self.server_socket)?;
|
||||
}
|
||||
match self.request(&LaunchRequest::Launch {
|
||||
server_socket: self.server_socket.clone(),
|
||||
remote,
|
||||
})? {
|
||||
LaunchResponse::Launched { pid } => {
|
||||
log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id());
|
||||
Ok(())
|
||||
}
|
||||
LaunchResponse::Error(error) => bail!("{error}"),
|
||||
_ => bail!("unexpected GUI zygote reply"),
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&self, request: &LaunchRequest) -> Result<LaunchResponse> {
|
||||
let mut stream = UnixStream::connect(&self.socket)?;
|
||||
verify_peer(&stream)?;
|
||||
stream.set_read_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
protocol::write_message(&mut stream, request)?;
|
||||
protocol::read_message(&mut stream)
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
if matches!(self.child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
if self.ready {
|
||||
let _ = self.request(&LaunchRequest::Shutdown);
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_millis(500);
|
||||
while Instant::now() < deadline {
|
||||
if matches!(self.child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
self.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Zygote {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ExecutableIdentity {
|
||||
device: u64,
|
||||
inode: u64,
|
||||
bytes: u64,
|
||||
modified: std::time::SystemTime,
|
||||
}
|
||||
|
||||
impl ExecutableIdentity {
|
||||
fn read(path: &Path) -> Result<Self> {
|
||||
let metadata =
|
||||
fs::metadata(path).with_context(|| format!("inspect executable {}", path.display()))?;
|
||||
if !metadata.is_file() {
|
||||
bail!("{} is not an executable file", path.display());
|
||||
}
|
||||
Ok(Self {
|
||||
device: metadata.dev(),
|
||||
inode: metadata.ino(),
|
||||
bytes: metadata.len(),
|
||||
modified: metadata.modified()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
enum LaunchRequest {
|
||||
Ping,
|
||||
Launch {
|
||||
server_socket: PathBuf,
|
||||
remote: Option<String>,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
enum LaunchResponse {
|
||||
Ready { pid: u32 },
|
||||
Launched { pid: u32 },
|
||||
Error(String),
|
||||
Stopped,
|
||||
}
|
||||
|
||||
pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
ensure_single_threaded()?;
|
||||
// SAFETY: the fixed NUL-terminated name fits Linux's 16-byte comm field.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-zygote".as_ptr());
|
||||
}
|
||||
ensure_socket_parent(socket)?;
|
||||
remove_stale_socket(socket)?;
|
||||
let listener = UnixListener::bind(socket).context("bind GUI zygote socket")?;
|
||||
fs::set_permissions(socket, fs::Permissions::from_mode(0o600))?;
|
||||
let _socket_guard = SocketGuard::new(socket)?;
|
||||
set_child_reaping(true)?;
|
||||
log::info!("Single-threaded GUI zygote {} ready", std::process::id());
|
||||
loop {
|
||||
let (mut stream, _) = match listener.accept() {
|
||||
Ok(connection) => connection,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error).context("accept GUI launch request"),
|
||||
};
|
||||
if let Err(error) = verify_peer(&stream) {
|
||||
log::warn!("Rejected GUI launch peer: {error}");
|
||||
continue;
|
||||
}
|
||||
stream.set_read_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
let request = match protocol::read_message::<LaunchRequest>(&mut stream) {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
log::debug!("Incomplete GUI launch request: {error}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match request {
|
||||
LaunchRequest::Ping => protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Ready {
|
||||
pid: std::process::id(),
|
||||
},
|
||||
)?,
|
||||
LaunchRequest::Shutdown => {
|
||||
protocol::write_message(&mut stream, &LaunchResponse::Stopped)?;
|
||||
return Ok(());
|
||||
}
|
||||
LaunchRequest::Launch {
|
||||
server_socket,
|
||||
remote,
|
||||
} => {
|
||||
if let Err(error) = ensure_single_threaded() {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(error.to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
// SAFETY: this process is single-threaded (checked above) and
|
||||
// has never initialized GPUI/Wayland/Vulkan or an executor. All
|
||||
// Rust allocator/logger locks can only have belonged to this
|
||||
// thread and are unlocked here. The child closes inherited IPC
|
||||
// descriptors, resets SIGCHLD, and owns its fresh GUI runtime.
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid == -1 {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(io::Error::last_os_error().to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if pid == 0 {
|
||||
// SAFETY: this only labels our forked GUI process for tools.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-gui".as_ptr());
|
||||
}
|
||||
drop(stream);
|
||||
drop(listener);
|
||||
let result = set_child_reaping(false)
|
||||
.and_then(|()| crate::run_gui(server_socket, remote));
|
||||
let code = if let Err(error) = result {
|
||||
log::error!("GUI startup failed: {error:#}");
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// SAFETY: this fork child must not run parent scope cleanup
|
||||
// (particularly the shared listening socket's unlink guard).
|
||||
unsafe { libc::_exit(code) };
|
||||
}
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Launched { pid: pid as u32 },
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_child_reaping(auto_reap: bool) -> Result<()> {
|
||||
// SAFETY: sigaction is initialized before use, uses SIG_DFL (no callback),
|
||||
// and points only to stack storage for the duration of these calls.
|
||||
unsafe {
|
||||
let mut action: libc::sigaction = std::mem::zeroed();
|
||||
action.sa_sigaction = libc::SIG_DFL;
|
||||
libc::sigemptyset(&mut action.sa_mask);
|
||||
action.sa_flags = if auto_reap {
|
||||
libc::SA_NOCLDWAIT | libc::SA_RESTART
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if libc::sigaction(libc::SIGCHLD, &action, std::ptr::null_mut()) == -1 {
|
||||
return Err(io::Error::last_os_error()).context("configure child reaping");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_single_threaded() -> Result<()> {
|
||||
let count = fs::read_dir("/proc/self/task")
|
||||
.context("verify zygote thread count")?
|
||||
.count();
|
||||
if count != 1 {
|
||||
bail!("refusing to fork GUI zygote with {count} threads; initialize GPUI only after fork");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_role(role: &str, socket: &Path, log_path: &Path) -> Result<Child> {
|
||||
spawn_role_from(&executable_path()?, role, socket, log_path)
|
||||
}
|
||||
|
||||
fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path) -> Result<Child> {
|
||||
role_command(executable, role, socket, log_path)?
|
||||
.spawn()
|
||||
.with_context(|| format!("launch psyTerm {role}"))
|
||||
}
|
||||
|
||||
fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) -> Result<Command> {
|
||||
let log = private_file(log_path)?;
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
@@ -464,7 +186,9 @@ fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log));
|
||||
#[cfg(target_os = "linux")]
|
||||
let managed_helper = role == "--zygote";
|
||||
#[cfg(target_os = "linux")]
|
||||
let parent_pid = std::process::id() as libc::pid_t;
|
||||
// SAFETY: the closure calls only libc syscalls and performs no allocation or
|
||||
// synchronization between Command's fork and exec. A zygote follows its
|
||||
@@ -474,6 +198,7 @@ fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path
|
||||
if libc::setsid() == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
if managed_helper {
|
||||
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
@@ -485,9 +210,24 @@ fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
command
|
||||
.spawn()
|
||||
.with_context(|| format!("launch psyTerm {role}"))
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
// AppKit needs a fresh process for a server-requested window on macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn open_window(socket: &Path, remote: Option<String>) -> Result<()> {
|
||||
let mut command = role_command(
|
||||
&executable_path()?,
|
||||
"--gui",
|
||||
socket,
|
||||
&suffixed(socket, ".gui.log"),
|
||||
)?;
|
||||
if let Some(host) = remote {
|
||||
command.arg("--remote").arg(host);
|
||||
}
|
||||
let mut child = command.spawn().context("launch psyTerm GUI")?;
|
||||
thread::spawn(move || child.wait());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Linux marks `/proc/self/exe` with " (deleted)" after atomic replacement.
|
||||
@@ -584,33 +324,25 @@ fn private_file(path: &Path) -> Result<File> {
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn remove_stale_socket(path: &Path) -> Result<()> {
|
||||
match UnixStream::connect(path) {
|
||||
Ok(_) => bail!("GUI zygote is already listening at {}", path.display()),
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
|
||||
) => {}
|
||||
Err(error) => return Err(error).context("inspect previous zygote listener"),
|
||||
}
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.file_type().is_socket() || metadata.uid() != uid() {
|
||||
bail!(
|
||||
"refusing to remove non-owned/non-socket path {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
fs::remove_file(path).context("remove stale zygote socket")?;
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("inspect stale zygote socket"),
|
||||
pub(crate) fn verify_peer(stream: &UnixStream) -> Result<()> {
|
||||
if peer_uid(stream).context("read socket peer credentials")? != uid() {
|
||||
bail!("socket peer belongs to another UID");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn verify_peer(stream: &UnixStream) -> Result<()> {
|
||||
#[cfg(target_os = "macos")]
|
||||
fn peer_uid(stream: &UnixStream) -> io::Result<libc::uid_t> {
|
||||
let (mut euid, mut egid) = (0, 0);
|
||||
// SAFETY: both outputs are writable for the duration of getpeereid.
|
||||
if unsafe { libc::getpeereid(stream.as_raw_fd(), &mut euid, &mut egid) } == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(euid)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn peer_uid(stream: &UnixStream) -> io::Result<libc::uid_t> {
|
||||
let mut credentials: libc::ucred = unsafe { std::mem::zeroed() };
|
||||
let mut size = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
||||
// SAFETY: credentials and size are valid initialized buffers of the stated
|
||||
@@ -625,47 +357,20 @@ pub(crate) fn verify_peer(stream: &UnixStream) -> Result<()> {
|
||||
)
|
||||
};
|
||||
if result == -1 {
|
||||
return Err(io::Error::last_os_error()).context("read socket peer credentials");
|
||||
}
|
||||
if credentials.uid != uid() {
|
||||
bail!("socket peer belongs to another UID");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SocketGuard {
|
||||
path: PathBuf,
|
||||
device: u64,
|
||||
inode: u64,
|
||||
}
|
||||
impl SocketGuard {
|
||||
fn new(path: &Path) -> Result<Self> {
|
||||
let metadata = fs::symlink_metadata(path)?;
|
||||
Ok(Self {
|
||||
path: path.to_owned(),
|
||||
device: metadata.dev(),
|
||||
inode: metadata.ino(),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Drop for SocketGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(metadata) = fs::symlink_metadata(&self.path)
|
||||
&& metadata.dev() == self.device
|
||||
&& metadata.ino() == self.inode
|
||||
{
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(credentials.uid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_dir() -> PathBuf {
|
||||
use std::os::unix::{fs::PermissionsExt, net::UnixListener};
|
||||
|
||||
pub(super) fn test_dir() -> PathBuf {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"psyterm-launcher-test-{}-{}",
|
||||
"pt-{:x}-{:x}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -740,36 +445,6 @@ mod tests {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_socket_cleanup_never_removes_regular_files() {
|
||||
let root = test_dir();
|
||||
let path = root.join("zygote.sock");
|
||||
fs::write(&path, b"keep me").unwrap();
|
||||
assert!(remove_stale_socket(&path).is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), b"keep me");
|
||||
fs::remove_file(&path).unwrap();
|
||||
let listener = UnixListener::bind(&path).unwrap();
|
||||
assert!(remove_stale_socket(&path).is_err());
|
||||
drop(listener);
|
||||
remove_stale_socket(&path).unwrap();
|
||||
assert!(!path.exists());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_request_round_trip_preserves_remote_without_shell_parsing() {
|
||||
let request = LaunchRequest::Launch {
|
||||
server_socket: PathBuf::from("/private/psyterm.sock"),
|
||||
remote: Some("work-host".into()),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
protocol::write_message(&mut bytes, &request).unwrap();
|
||||
let decoded: LaunchRequest = protocol::read_message(&mut bytes.as_slice()).unwrap();
|
||||
assert!(
|
||||
matches!(decoded, LaunchRequest::Launch { remote: Some(host), .. } if host == "work-host")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_peer_credentials_match_current_user() {
|
||||
let (left, _right) = UnixStream::pair().unwrap();
|
||||
@@ -788,17 +463,4 @@ mod tests {
|
||||
assert!(resolve_executable_path(root.join("missing")).is_err());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_executable_changes_identity_even_with_same_contents() {
|
||||
let root = test_dir();
|
||||
let original = root.join("psyterm");
|
||||
fs::write(&original, b"binary").unwrap();
|
||||
let before = ExecutableIdentity::read(&original).unwrap();
|
||||
let replacement = root.join("psyterm-new");
|
||||
fs::write(&replacement, b"binary").unwrap();
|
||||
fs::rename(replacement, &original).unwrap();
|
||||
assert_ne!(ExecutableIdentity::read(&original).unwrap(), before);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Linux GUI prefork helper. Only the single-threaded helper forks without exec.
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::{
|
||||
fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
||||
net::{UnixListener, UnixStream},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
process::Child,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
REQUEST_TIMEOUT, START_TIMEOUT, ensure_socket_parent, executable_path, spawn_role_from,
|
||||
suffixed, uid, verify_peer,
|
||||
};
|
||||
use crate::protocol;
|
||||
|
||||
/// Owned by the terminal server. Its GUI children are independent clients and
|
||||
/// keep running when this helper is stopped; stopping the helper never kills them.
|
||||
pub struct Zygote {
|
||||
server_socket: PathBuf,
|
||||
socket: PathBuf,
|
||||
child: Child,
|
||||
ready: bool,
|
||||
executable: PathBuf,
|
||||
executable_identity: ExecutableIdentity,
|
||||
}
|
||||
|
||||
impl Zygote {
|
||||
pub fn start(server_socket: &Path) -> Result<Self> {
|
||||
ensure_socket_parent(server_socket)?;
|
||||
let socket = suffixed(server_socket, ".zygote.sock");
|
||||
let log_path = suffixed(server_socket, ".zygote.log");
|
||||
let executable = executable_path()?;
|
||||
let executable_identity = ExecutableIdentity::read(&executable)?;
|
||||
let child = spawn_role_from(&executable, "--zygote", &socket, &log_path)?;
|
||||
let mut zygote = Self {
|
||||
server_socket: server_socket.to_owned(),
|
||||
socket,
|
||||
child,
|
||||
ready: false,
|
||||
executable,
|
||||
executable_identity,
|
||||
};
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
if let Ok(LaunchResponse::Ready { pid }) = zygote.request(&LaunchRequest::Ping) {
|
||||
if pid != zygote.child.id() {
|
||||
bail!(
|
||||
"a different GUI zygote is already listening at {}",
|
||||
zygote.socket.display()
|
||||
);
|
||||
}
|
||||
zygote.ready = true;
|
||||
return Ok(zygote);
|
||||
}
|
||||
if let Some(status) = zygote.child.try_wait()? {
|
||||
bail!(
|
||||
"psyTerm zygote exited ({status}); see {}",
|
||||
log_path.display()
|
||||
);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"psyTerm zygote startup timed out; see {}",
|
||||
log_path.display()
|
||||
);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_window(&mut self, remote: Option<String>) -> Result<()> {
|
||||
let executable = executable_path()?;
|
||||
let identity = ExecutableIdentity::read(&executable)?;
|
||||
let helper_exited = self.child.try_wait()?.is_some();
|
||||
if helper_exited || executable != self.executable || identity != self.executable_identity {
|
||||
log::info!("Refreshing GUI zygote after executable replacement or helper exit");
|
||||
self.stop();
|
||||
// Assignment drops the stopped helper only after a replacement is
|
||||
// ready. If startup fails, a later launch can retry this stopped one.
|
||||
*self = Self::start(&self.server_socket)?;
|
||||
}
|
||||
match self.request(&LaunchRequest::Launch {
|
||||
server_socket: self.server_socket.clone(),
|
||||
remote,
|
||||
})? {
|
||||
LaunchResponse::Launched { pid } => {
|
||||
log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id());
|
||||
Ok(())
|
||||
}
|
||||
LaunchResponse::Error(error) => bail!("{error}"),
|
||||
_ => bail!("unexpected GUI zygote reply"),
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&self, request: &LaunchRequest) -> Result<LaunchResponse> {
|
||||
let mut stream = UnixStream::connect(&self.socket)?;
|
||||
verify_peer(&stream)?;
|
||||
stream.set_read_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
protocol::write_message(&mut stream, request)?;
|
||||
protocol::read_message(&mut stream)
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
if matches!(self.child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
if self.ready {
|
||||
let _ = self.request(&LaunchRequest::Shutdown);
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_millis(500);
|
||||
while Instant::now() < deadline {
|
||||
if matches!(self.child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
self.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Zygote {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ExecutableIdentity {
|
||||
device: u64,
|
||||
inode: u64,
|
||||
bytes: u64,
|
||||
modified: std::time::SystemTime,
|
||||
}
|
||||
|
||||
impl ExecutableIdentity {
|
||||
fn read(path: &Path) -> Result<Self> {
|
||||
let metadata =
|
||||
fs::metadata(path).with_context(|| format!("inspect executable {}", path.display()))?;
|
||||
if !metadata.is_file() {
|
||||
bail!("{} is not an executable file", path.display());
|
||||
}
|
||||
Ok(Self {
|
||||
device: metadata.dev(),
|
||||
inode: metadata.ino(),
|
||||
bytes: metadata.len(),
|
||||
modified: metadata.modified()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
enum LaunchRequest {
|
||||
Ping,
|
||||
Launch {
|
||||
server_socket: PathBuf,
|
||||
remote: Option<String>,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
enum LaunchResponse {
|
||||
Ready { pid: u32 },
|
||||
Launched { pid: u32 },
|
||||
Error(String),
|
||||
Stopped,
|
||||
}
|
||||
|
||||
pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
ensure_single_threaded()?;
|
||||
// SAFETY: the fixed NUL-terminated name fits Linux's 16-byte comm field.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-zygote".as_ptr());
|
||||
}
|
||||
ensure_socket_parent(socket)?;
|
||||
remove_stale_socket(socket)?;
|
||||
let listener = UnixListener::bind(socket).context("bind GUI zygote socket")?;
|
||||
fs::set_permissions(socket, fs::Permissions::from_mode(0o600))?;
|
||||
let _socket_guard = SocketGuard::new(socket)?;
|
||||
set_child_reaping(true)?;
|
||||
log::info!("Single-threaded GUI zygote {} ready", std::process::id());
|
||||
loop {
|
||||
let (mut stream, _) = match listener.accept() {
|
||||
Ok(connection) => connection,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error).context("accept GUI launch request"),
|
||||
};
|
||||
if let Err(error) = verify_peer(&stream) {
|
||||
log::warn!("Rejected GUI launch peer: {error}");
|
||||
continue;
|
||||
}
|
||||
stream.set_read_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(REQUEST_TIMEOUT))?;
|
||||
let request = match protocol::read_message::<LaunchRequest>(&mut stream) {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
log::debug!("Incomplete GUI launch request: {error}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match request {
|
||||
LaunchRequest::Ping => protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Ready {
|
||||
pid: std::process::id(),
|
||||
},
|
||||
)?,
|
||||
LaunchRequest::Shutdown => {
|
||||
protocol::write_message(&mut stream, &LaunchResponse::Stopped)?;
|
||||
return Ok(());
|
||||
}
|
||||
LaunchRequest::Launch {
|
||||
server_socket,
|
||||
remote,
|
||||
} => {
|
||||
if let Err(error) = ensure_single_threaded() {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(error.to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
// SAFETY: this process is single-threaded (checked above) and
|
||||
// has never initialized GPUI/Wayland/Vulkan or an executor. All
|
||||
// Rust allocator/logger locks can only have belonged to this
|
||||
// thread and are unlocked here. The child closes inherited IPC
|
||||
// descriptors, resets SIGCHLD, and owns its fresh GUI runtime.
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid == -1 {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(io::Error::last_os_error().to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if pid == 0 {
|
||||
// SAFETY: this only labels our forked GUI process for tools.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-gui".as_ptr());
|
||||
}
|
||||
drop(stream);
|
||||
drop(listener);
|
||||
let result = set_child_reaping(false)
|
||||
.and_then(|()| crate::run_gui(server_socket, remote));
|
||||
let code = if let Err(error) = result {
|
||||
log::error!("GUI startup failed: {error:#}");
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// SAFETY: this fork child must not run parent scope cleanup
|
||||
// (particularly the shared listening socket's unlink guard).
|
||||
unsafe { libc::_exit(code) };
|
||||
}
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Launched { pid: pid as u32 },
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_child_reaping(auto_reap: bool) -> Result<()> {
|
||||
// SAFETY: sigaction is initialized before use, uses SIG_DFL (no callback),
|
||||
// and points only to stack storage for the duration of these calls.
|
||||
unsafe {
|
||||
let mut action: libc::sigaction = std::mem::zeroed();
|
||||
action.sa_sigaction = libc::SIG_DFL;
|
||||
libc::sigemptyset(&mut action.sa_mask);
|
||||
action.sa_flags = if auto_reap {
|
||||
libc::SA_NOCLDWAIT | libc::SA_RESTART
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if libc::sigaction(libc::SIGCHLD, &action, std::ptr::null_mut()) == -1 {
|
||||
return Err(io::Error::last_os_error()).context("configure child reaping");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_single_threaded() -> Result<()> {
|
||||
let count = fs::read_dir("/proc/self/task")
|
||||
.context("verify zygote thread count")?
|
||||
.count();
|
||||
if count != 1 {
|
||||
bail!("refusing to fork GUI zygote with {count} threads; initialize GPUI only after fork");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_stale_socket(path: &Path) -> Result<()> {
|
||||
match UnixStream::connect(path) {
|
||||
Ok(_) => bail!("GUI zygote is already listening at {}", path.display()),
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
|
||||
) => {}
|
||||
Err(error) => return Err(error).context("inspect previous zygote listener"),
|
||||
}
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.file_type().is_socket() || metadata.uid() != uid() {
|
||||
bail!(
|
||||
"refusing to remove non-owned/non-socket path {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
fs::remove_file(path).context("remove stale zygote socket")?;
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("inspect stale zygote socket"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SocketGuard {
|
||||
path: PathBuf,
|
||||
device: u64,
|
||||
inode: u64,
|
||||
}
|
||||
impl SocketGuard {
|
||||
fn new(path: &Path) -> Result<Self> {
|
||||
let metadata = fs::symlink_metadata(path)?;
|
||||
Ok(Self {
|
||||
path: path.to_owned(),
|
||||
device: metadata.dev(),
|
||||
inode: metadata.ino(),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Drop for SocketGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(metadata) = fs::symlink_metadata(&self.path)
|
||||
&& metadata.dev() == self.device
|
||||
&& metadata.ino() == self.inode
|
||||
{
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::launcher::tests::test_dir;
|
||||
|
||||
#[test]
|
||||
fn stale_socket_cleanup_never_removes_regular_files() {
|
||||
let root = test_dir();
|
||||
let path = root.join("zygote.sock");
|
||||
fs::write(&path, b"keep me").unwrap();
|
||||
assert!(remove_stale_socket(&path).is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), b"keep me");
|
||||
fs::remove_file(&path).unwrap();
|
||||
let listener = UnixListener::bind(&path).unwrap();
|
||||
assert!(remove_stale_socket(&path).is_err());
|
||||
drop(listener);
|
||||
remove_stale_socket(&path).unwrap();
|
||||
assert!(!path.exists());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_request_round_trip_preserves_remote_without_shell_parsing() {
|
||||
let request = LaunchRequest::Launch {
|
||||
server_socket: PathBuf::from("/private/psyterm.sock"),
|
||||
remote: Some("work-host".into()),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
protocol::write_message(&mut bytes, &request).unwrap();
|
||||
let decoded: LaunchRequest = protocol::read_message(&mut bytes.as_slice()).unwrap();
|
||||
assert!(
|
||||
matches!(decoded, LaunchRequest::Launch { remote: Some(host), .. } if host == "work-host")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_executable_changes_identity_even_with_same_contents() {
|
||||
let root = test_dir();
|
||||
let original = root.join("psyterm");
|
||||
fs::write(&original, b"binary").unwrap();
|
||||
let before = ExecutableIdentity::read(&original).unwrap();
|
||||
let replacement = root.join("psyterm-new");
|
||||
fs::write(&replacement, b"binary").unwrap();
|
||||
fs::rename(replacement, &original).unwrap();
|
||||
assert_ne!(ExecutableIdentity::read(&original).unwrap(), before);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
+41
-7
@@ -21,15 +21,24 @@ use anyhow::{Result, bail};
|
||||
use gpui::{prelude::*, *};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
gpui::actions!(psyterm, [Quit]);
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::init();
|
||||
let mut role = "launch";
|
||||
// AppKit runs in the process that LaunchServices opens. Linux uses a prefork helper.
|
||||
let mut role = if cfg!(target_os = "macos") {
|
||||
"gui"
|
||||
} else {
|
||||
"launch"
|
||||
};
|
||||
let mut socket = None;
|
||||
let mut remote = None;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--server" => role = "server",
|
||||
#[cfg(target_os = "linux")]
|
||||
"--zygote" => role = "zygote",
|
||||
"--gui" => role = "gui",
|
||||
"--bridge" => role = "bridge",
|
||||
@@ -49,7 +58,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a window via the local server's zygote\n psyterm --remote user@host Connect a local GUI to a server over SSH\n psyterm --list List server-owned tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Direct GUI launch (diagnostics; bypass zygote)\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n"
|
||||
"psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a local terminal window\n psyterm --remote user@host Connect a local GUI to a server over SSH\n psyterm --list List server-owned tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Run the GUI in the current process\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -58,18 +67,34 @@ fn main() -> Result<()> {
|
||||
}
|
||||
let socket = socket.map(Ok).unwrap_or_else(launcher::default_socket)?;
|
||||
match role {
|
||||
#[cfg(target_os = "macos")]
|
||||
"server" => server::run(&socket, |remote| launcher::open_window(&socket, remote)),
|
||||
#[cfg(target_os = "linux")]
|
||||
"server" => {
|
||||
let zygote_socket = socket.clone();
|
||||
let mut zygote: Option<launcher::Zygote> = None;
|
||||
let mut zygote: Option<launcher::zygote::Zygote> = None;
|
||||
server::run(&socket, move |remote| {
|
||||
if zygote.is_none() {
|
||||
zygote = Some(launcher::Zygote::start(&zygote_socket)?);
|
||||
zygote = Some(launcher::zygote::Zygote::start(&zygote_socket)?);
|
||||
}
|
||||
zygote.as_mut().unwrap().open_window(remote)
|
||||
})
|
||||
}
|
||||
"zygote" => launcher::run_zygote(&socket),
|
||||
#[cfg(target_os = "linux")]
|
||||
"zygote" => launcher::zygote::run_zygote(&socket),
|
||||
"gui" => {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// LaunchServices starts Finder-launched apps in / with launchd as parent.
|
||||
// Give that first shell a useful directory while preserving CLI launch paths.
|
||||
// SAFETY: getppid has no preconditions.
|
||||
if unsafe { libc::getppid() } == 1
|
||||
&& std::env::current_dir()? == std::path::Path::new("/")
|
||||
&& let Some(home) = std::env::home_dir()
|
||||
{
|
||||
std::env::set_current_dir(home)?;
|
||||
}
|
||||
}
|
||||
launcher::ensure_server(&socket)?;
|
||||
run_gui(socket, remote)
|
||||
}
|
||||
@@ -92,6 +117,7 @@ fn main() -> Result<()> {
|
||||
|
||||
fn list_sessions(socket: &std::path::Path) -> Result<()> {
|
||||
let mut stream = std::os::unix::net::UnixStream::connect(socket)?;
|
||||
launcher::verify_peer(&stream)?;
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
@@ -125,8 +151,7 @@ fn list_sessions(socket: &std::path::Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called directly in a fresh fork of the single-threaded zygote. All GPUI,
|
||||
/// graphics, font discovery and client I/O initialization happens after fork.
|
||||
/// Initialize GPUI on the main thread of the GUI process.
|
||||
pub(crate) fn run_gui(socket: PathBuf, remote: Option<String>) -> Result<()> {
|
||||
let (client, updates) = client::Client::connect(&socket, remote.as_deref())?;
|
||||
let connection: SharedString = remote
|
||||
@@ -134,6 +159,15 @@ pub(crate) fn run_gui(socket: PathBuf, remote: Option<String>) -> Result<()> {
|
||||
.unwrap_or_else(|| "Local".into())
|
||||
.into();
|
||||
Application::new().run(move |cx: &mut App| {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
cx.on_action(|_: &Quit, cx| cx.quit());
|
||||
cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]);
|
||||
cx.set_menus(vec![Menu {
|
||||
name: "psyTerm".into(),
|
||||
items: vec![MenuItem::action("Quit psyTerm", Quit)],
|
||||
}]);
|
||||
}
|
||||
cx.on_window_closed(|cx| {
|
||||
if cx.windows().is_empty() {
|
||||
cx.quit();
|
||||
|
||||
+9
-35
@@ -175,7 +175,7 @@ impl Outbox {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the headless server. The owner supplies a server-managed GUI zygote callback.
|
||||
/// Run the headless server. The caller handles platform-specific window launches.
|
||||
pub fn run(socket: &Path, open_window: impl FnMut(Option<String>) -> Result<()>) -> Result<()> {
|
||||
run_with_shell(socket, open_window, None)
|
||||
}
|
||||
@@ -200,7 +200,7 @@ fn run_with_shell(
|
||||
break;
|
||||
}
|
||||
};
|
||||
if !same_user(&stream) {
|
||||
if crate::launcher::verify_peer(&stream).is_err() {
|
||||
continue;
|
||||
}
|
||||
let reader = match stream.try_clone() {
|
||||
@@ -346,7 +346,7 @@ impl Server {
|
||||
{
|
||||
client
|
||||
.output
|
||||
.reliable(ServerMessage::Error(error.to_string()));
|
||||
.reliable(ServerMessage::Error(format!("{error:#}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1092,34 +1092,6 @@ fn bind_socket(socket: &Path) -> Result<(SocketGuard, UnixListener)> {
|
||||
))
|
||||
}
|
||||
|
||||
fn same_user(stream: &UnixStream) -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let mut credentials = libc::ucred {
|
||||
pid: 0,
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
};
|
||||
let mut len = std::mem::size_of_val(&credentials) as libc::socklen_t;
|
||||
// SAFETY: arguments point to initialized writable storage of the given length.
|
||||
let result = unsafe {
|
||||
libc::getsockopt(
|
||||
stream.as_raw_fd(),
|
||||
libc::SOL_SOCKET,
|
||||
libc::SO_PEERCRED,
|
||||
(&mut credentials as *mut libc::ucred).cast(),
|
||||
&mut len,
|
||||
)
|
||||
};
|
||||
result == 0 && credentials.uid == unsafe { libc::geteuid() }
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = stream;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1133,7 +1105,7 @@ mod tests {
|
||||
impl TestServer {
|
||||
fn start() -> Self {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"psyterm-server-test-{}-{}",
|
||||
"pt-s-{:x}-{:x}",
|
||||
std::process::id(),
|
||||
NEXT_TEST.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
@@ -1153,7 +1125,7 @@ mod tests {
|
||||
thread: Some(thread),
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !test.socket.exists() {
|
||||
while UnixStream::connect(&test.socket).is_err() {
|
||||
assert!(Instant::now() < deadline);
|
||||
thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
@@ -1865,8 +1837,10 @@ mod tests {
|
||||
#[test]
|
||||
fn cwd_program_and_manual_names_follow_precedence_and_survive_detach() {
|
||||
let server = TestServer::start();
|
||||
let first_dir = server.socket.parent().unwrap().join("first");
|
||||
let second_dir = server.socket.parent().unwrap().join("second");
|
||||
// The OS reports the physical cwd; macOS TMPDIR typically starts with the /var symlink.
|
||||
let parent = fs::canonicalize(server.socket.parent().unwrap()).unwrap();
|
||||
let first_dir = parent.join("first");
|
||||
let second_dir = parent.join("second");
|
||||
fs::create_dir(&first_dir).unwrap();
|
||||
fs::create_dir(&second_dir).unwrap();
|
||||
let mut client = server.client();
|
||||
|
||||
+60
-16
@@ -3,6 +3,11 @@
|
||||
//! A future pane can own a `Session` without owning a window. Alacritty handles
|
||||
//! escape sequences, scrollback, PTY polling, and child-process notifications.
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos::MacProcess;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -73,6 +78,8 @@ pub struct Session {
|
||||
// A pinned proc directory cannot silently resolve to a reused numerical PID.
|
||||
#[cfg(target_os = "linux")]
|
||||
proc_directory: Option<std::fs::File>,
|
||||
#[cfg(target_os = "macos")]
|
||||
process: Option<Arc<MacProcess>>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
@@ -80,11 +87,12 @@ impl Session {
|
||||
pub fn in_directory(
|
||||
directory: Option<std::path::PathBuf>,
|
||||
) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
let program = std::env::var("SHELL")
|
||||
.ok()
|
||||
.filter(|shell| !shell.is_empty())
|
||||
.unwrap_or_else(|| "/bin/sh".into());
|
||||
Self::with_shell_and_directory(Shell::new(program, Vec::new()), directory)
|
||||
let program = std::env::var("SHELL").ok().filter(|s| !s.is_empty());
|
||||
#[cfg(target_os = "macos")]
|
||||
let shell = macos::login_shell(program);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let shell = Shell::new(program.unwrap_or_else(|| "/bin/sh".into()), Vec::new());
|
||||
Self::with_shell_and_directory(shell, directory)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -132,6 +140,15 @@ impl Session {
|
||||
.open(format!("/proc/{}", pty.child().id()))
|
||||
.ok()
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let process = MacProcess::watch(pty.child().id())?.map(Arc::new);
|
||||
#[cfg(target_os = "macos")]
|
||||
let worker_process = process.clone();
|
||||
#[cfg(target_os = "macos")]
|
||||
let master = pty
|
||||
.file()
|
||||
.try_clone()
|
||||
.context("retain shell PTY for shutdown")?;
|
||||
let event_loop = EventLoop::new(term.clone(), proxy.clone(), pty, true, false)
|
||||
.context("Could not initialize PTY polling")?;
|
||||
let sender = event_loop.channel();
|
||||
@@ -141,7 +158,15 @@ impl Session {
|
||||
.name("terminal-session".into())
|
||||
.spawn(move || {
|
||||
match event_loop.spawn().join() {
|
||||
Ok(state) => drop(state),
|
||||
Ok(state) => {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(process) = worker_process
|
||||
&& let Err(error) = process.finish_shutdown(&master)
|
||||
{
|
||||
log::warn!("Could not finish shell shutdown: {error}");
|
||||
}
|
||||
drop(state);
|
||||
}
|
||||
Err(_) => log::error!("The terminal PTY thread panicked"),
|
||||
}
|
||||
// Also close the window on I/O failures that have no Exit event.
|
||||
@@ -155,7 +180,7 @@ impl Session {
|
||||
sender,
|
||||
wakeup_pending,
|
||||
size,
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
process,
|
||||
#[cfg(target_os = "linux")]
|
||||
proc_directory,
|
||||
@@ -185,7 +210,11 @@ impl Session {
|
||||
let directory = self.proc_directory.as_ref()?;
|
||||
std::fs::read_link(format!("/proc/self/fd/{}/cwd", directory.as_raw_fd())).ok()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
self.process.as_ref()?.working_directory()
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -385,19 +414,28 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
fn closing_session_reaps_shell_even_when_sighup_is_ignored() {
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
for ignore_hup in [false, true] {
|
||||
let script = format!(
|
||||
"{}printf '\\033]0;ready\\007'; read value",
|
||||
if ignore_hup { "trap '' HUP; " } else { "" }
|
||||
if ignore_hup {
|
||||
"trap '' HUP; "
|
||||
} else {
|
||||
// Darwin must drain this last output to finish shell exit.
|
||||
"trap 'printf final-output; exit 0' HUP; "
|
||||
}
|
||||
);
|
||||
let (session, events) =
|
||||
Session::with_shell(Shell::new("/bin/sh".into(), vec!["-c".into(), script]))
|
||||
.expect("start shell for shutdown test");
|
||||
#[cfg(target_os = "linux")]
|
||||
let process = session.process.0.try_clone().unwrap();
|
||||
#[cfg(target_os = "macos")]
|
||||
let pid = session.process.as_ref().unwrap().pid();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
match receive_before(&events, deadline) {
|
||||
@@ -407,15 +445,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
drop(session);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(2),
|
||||
"shutdown was not bounded"
|
||||
);
|
||||
let (done, closed) = std::sync::mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
drop(session);
|
||||
let _ = done.send(());
|
||||
});
|
||||
closed
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("shutdown was not bounded");
|
||||
#[cfg(target_os = "linux")]
|
||||
let mut status = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
|
||||
// SAFETY: the cloned pidfd and writable siginfo are valid. WNOHANG
|
||||
// avoids waiting if the process was accidentally left running.
|
||||
#[cfg(target_os = "linux")]
|
||||
let result = unsafe {
|
||||
libc::waitid(
|
||||
libc::P_PIDFD,
|
||||
@@ -424,6 +466,8 @@ mod tests {
|
||||
libc::WEXITED | libc::WNOHANG,
|
||||
)
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let result = unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) };
|
||||
assert_eq!(result, -1, "the shell was left running or unreaped");
|
||||
assert_eq!(
|
||||
std::io::Error::last_os_error().raw_os_error(),
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! macOS shell identity, current directory, and shutdown.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::os::fd::AsFd;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use alacritty_terminal::tty::Shell;
|
||||
use nix::errno::Errno;
|
||||
use nix::poll::{PollFd, PollFlags, poll};
|
||||
use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, Kqueue};
|
||||
use nix::sys::signal::{Signal, kill};
|
||||
use nix::unistd::{Pid, Uid, User};
|
||||
|
||||
pub(super) fn login_shell(program: Option<String>) -> Shell {
|
||||
// Finder may launch the app without SHELL.
|
||||
let program = program.or_else(|| {
|
||||
let user = User::from_uid(Uid::current()).ok()??;
|
||||
user.shell
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
});
|
||||
Shell::new(
|
||||
program.unwrap_or_else(|| "/bin/zsh".into()),
|
||||
vec!["-l".into()],
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) struct MacProcess {
|
||||
pid: Pid,
|
||||
exit_queue: Kqueue,
|
||||
}
|
||||
|
||||
impl MacProcess {
|
||||
pub(super) fn watch(pid: u32) -> nix::Result<Option<Self>> {
|
||||
// Register before the PTY reader can reap the child and release its PID.
|
||||
let exit_queue = Kqueue::new()?;
|
||||
let event = KEvent::new(
|
||||
pid as usize,
|
||||
EventFilter::EVFILT_PROC,
|
||||
EventFlag::EV_ADD,
|
||||
FilterFlag::NOTE_EXIT,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
match exit_queue.kevent(&[event], &mut [], None) {
|
||||
Ok(_) => Ok(Some(Self {
|
||||
pid: Pid::from_raw(pid as libc::pid_t),
|
||||
exit_queue,
|
||||
})),
|
||||
Err(Errno::ESRCH) => Ok(None), // Already exited before registration.
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_exited(&self) -> nix::Result<bool> {
|
||||
let mut fds = [PollFd::new(self.exit_queue.as_fd(), PollFlags::POLLIN)];
|
||||
// Polling leaves the exit notice queued for subsequent checks.
|
||||
loop {
|
||||
match poll(&mut fds, 0u16) {
|
||||
Err(Errno::EINTR) => continue,
|
||||
result => return result.map(|count| count > 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn working_directory(&self) -> Option<PathBuf> {
|
||||
let mut info = std::mem::MaybeUninit::<libc::proc_vnodepathinfo>::uninit();
|
||||
let size = std::mem::size_of::<libc::proc_vnodepathinfo>() as i32;
|
||||
// SAFETY: the output buffer matches PROC_PIDVNODEPATHINFO. Only read a
|
||||
// complete result, and discard it if the shell released its PID.
|
||||
let count = unsafe {
|
||||
libc::proc_pidinfo(
|
||||
self.pid.as_raw(),
|
||||
libc::PROC_PIDVNODEPATHINFO,
|
||||
0,
|
||||
info.as_mut_ptr().cast(),
|
||||
size,
|
||||
)
|
||||
};
|
||||
if count != size || self.has_exited().ok()? {
|
||||
return None;
|
||||
}
|
||||
let path = unsafe { info.assume_init() }.pvi_cdir.vip_path;
|
||||
let bytes = path
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.take_while(|c| *c != 0)
|
||||
.map(|c| c as u8)
|
||||
.collect::<Vec<_>>();
|
||||
(!bytes.is_empty()).then(|| std::ffi::OsString::from_vec(bytes).into())
|
||||
}
|
||||
|
||||
pub(super) fn finish_shutdown(&self, mut master: &File) -> io::Result<()> {
|
||||
// The only reader that can reap this child has joined. If the shell is
|
||||
// still alive, it retains this PID until the worker drops the PTY.
|
||||
if self.has_exited()? {
|
||||
return Ok(());
|
||||
}
|
||||
kill(self.pid, Signal::SIGHUP)?;
|
||||
let mut kill_at = Some(Instant::now() + Duration::from_millis(300));
|
||||
let mut monitor_master = true;
|
||||
let mut output = [0; 8192];
|
||||
loop {
|
||||
if kill_at.is_some_and(|deadline| Instant::now() >= deadline) {
|
||||
kill(self.pid, Signal::SIGKILL)?;
|
||||
kill_at = None;
|
||||
}
|
||||
let timeout =
|
||||
kill_at.map(|t| t.saturating_duration_since(Instant::now()).as_millis() as u16);
|
||||
let mut fds = [
|
||||
PollFd::new(self.exit_queue.as_fd(), PollFlags::POLLIN),
|
||||
PollFd::new(master.as_fd(), PollFlags::POLLIN),
|
||||
];
|
||||
let count = if monitor_master { 2 } else { 1 };
|
||||
match poll(&mut fds[..count], timeout) {
|
||||
Err(Errno::EINTR) | Ok(0) => continue,
|
||||
Err(error) => return Err(error.into()),
|
||||
Ok(_) if fds[0].any() == Some(true) => return Ok(()),
|
||||
Ok(_) => {}
|
||||
}
|
||||
// Darwin waits for queued PTY output to drain while the session
|
||||
// leader exits, even after SIGKILL. No GUI will consume these bytes.
|
||||
match master.read(&mut output) {
|
||||
Ok(0) => monitor_master = false,
|
||||
Ok(_) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
|
||||
) => {}
|
||||
Err(error) if error.raw_os_error() == Some(libc::EIO) => monitor_master = false,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn pid(&self) -> libc::pid_t {
|
||||
self.pid.as_raw()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user