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