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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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