Port psyTerm to macOS and package a native app bundle
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user