755 lines
26 KiB
Rust
755 lines
26 KiB
Rust
//! 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.
|
||
|
|
use std::{
|
||
|
|
fs::{self, DirBuilder, File, OpenOptions},
|
||
|
|
io,
|
||
|
|
os::{
|
||
|
|
fd::AsRawFd,
|
||
|
|
unix::{
|
||
|
|
ffi::{OsStrExt, OsStringExt},
|
||
|
|
fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||
|
|
net::{UnixListener, UnixStream},
|
||
|
|
process::CommandExt,
|
||
|
|
},
|
||
|
|
},
|
||
|
|
path::{Path, PathBuf},
|
||
|
|
process::{Child, Command, Stdio},
|
||
|
|
thread,
|
||
|
|
time::{Duration, Instant},
|
||
|
|
};
|
||
|
|
|
||
|
|
use anyhow::{Context, Result, bail};
|
||
|
|
use serde::{Deserialize, Serialize};
|
||
|
|
|
||
|
|
use crate::protocol::{self, ClientMessage, ServerMessage};
|
||
|
|
|
||
|
|
const START_TIMEOUT: Duration = Duration::from_secs(10);
|
||
|
|
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||
|
|
|
||
|
|
pub fn default_socket() -> Result<PathBuf> {
|
||
|
|
let root = if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") {
|
||
|
|
let runtime = PathBuf::from(runtime);
|
||
|
|
verify_private_directory(&runtime)?;
|
||
|
|
runtime.join("psyterm")
|
||
|
|
} else {
|
||
|
|
std::env::temp_dir().join(format!("psyterm-{}", uid()))
|
||
|
|
};
|
||
|
|
ensure_private_directory(&root)?;
|
||
|
|
Ok(root.join("server.sock"))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Start exactly one daemon. The daemon has its own lifetime lock; this lock is
|
||
|
|
/// held only while racing launchers agree on which process starts it.
|
||
|
|
pub fn ensure_server(socket: &Path) -> Result<()> {
|
||
|
|
ensure_socket_parent(socket)?;
|
||
|
|
if probe_server(socket)? {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let startup_lock = private_file(&suffixed(socket, ".startup.lock"))?;
|
||
|
|
// SAFETY: flock operates on our live file descriptor and has no pointers.
|
||
|
|
if unsafe { libc::flock(startup_lock.as_raw_fd(), libc::LOCK_EX) } != 0 {
|
||
|
|
return Err(io::Error::last_os_error()).context("lock server startup");
|
||
|
|
}
|
||
|
|
if probe_server(socket)? {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
let log_path = suffixed(socket, ".log");
|
||
|
|
let mut child = spawn_role("--server", socket, &log_path)?;
|
||
|
|
let deadline = Instant::now() + START_TIMEOUT;
|
||
|
|
loop {
|
||
|
|
if probe_server(socket)? {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
if let Some(status) = child.try_wait()? {
|
||
|
|
bail!(
|
||
|
|
"psyTerm server exited ({status}); see {}",
|
||
|
|
log_path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
if Instant::now() >= deadline {
|
||
|
|
// This process is ours and never became available to clients.
|
||
|
|
let _ = child.kill();
|
||
|
|
let _ = child.wait();
|
||
|
|
bail!(
|
||
|
|
"psyTerm server startup timed out; see {}",
|
||
|
|
log_path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
thread::sleep(Duration::from_millis(15));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Send a command without attaching a GUI or creating a terminal session.
|
||
|
|
pub fn control(socket: &Path, command: ClientMessage) -> Result<ServerMessage> {
|
||
|
|
let stream = UnixStream::connect(socket)
|
||
|
|
.with_context(|| format!("connect to psyTerm server at {}", socket.display()))?;
|
||
|
|
let legacy_shutdown = matches!(command, ClientMessage::Shutdown);
|
||
|
|
let result = control_stream(stream, command, REQUEST_TIMEOUT);
|
||
|
|
if legacy_shutdown
|
||
|
|
&& protocol::VERSION > 1
|
||
|
|
&& result
|
||
|
|
.as_ref()
|
||
|
|
.is_err_and(|error| error.to_string().contains("protocol"))
|
||
|
|
{
|
||
|
|
// Version 1 shares the Hello/Shutdown/Closing wire prefix. Permit only
|
||
|
|
// an explicit shutdown through that prefix, never old grid decoding.
|
||
|
|
let stream = UnixStream::connect(socket)?;
|
||
|
|
return control_stream_version(stream, ClientMessage::Shutdown, REQUEST_TIMEOUT, 1);
|
||
|
|
}
|
||
|
|
result
|
||
|
|
}
|
||
|
|
|
||
|
|
fn probe_server(socket: &Path) -> Result<bool> {
|
||
|
|
match UnixStream::connect(socket) {
|
||
|
|
Ok(stream) => {
|
||
|
|
match control_stream(stream, ClientMessage::Ping, Duration::from_millis(500))? {
|
||
|
|
ServerMessage::Pong => Ok(true),
|
||
|
|
_ => bail!("psyTerm server did not acknowledge startup probe"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Err(error)
|
||
|
|
if matches!(
|
||
|
|
error.kind(),
|
||
|
|
io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
|
||
|
|
) =>
|
||
|
|
{
|
||
|
|
Ok(false)
|
||
|
|
}
|
||
|
|
Err(error) => Err(error).with_context(|| format!("probe {}", socket.display())),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn control_stream(
|
||
|
|
stream: UnixStream,
|
||
|
|
command: ClientMessage,
|
||
|
|
timeout: Duration,
|
||
|
|
) -> Result<ServerMessage> {
|
||
|
|
control_stream_version(stream, command, timeout, protocol::VERSION)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn control_stream_version(
|
||
|
|
mut stream: UnixStream,
|
||
|
|
command: ClientMessage,
|
||
|
|
timeout: Duration,
|
||
|
|
expected_version: u32,
|
||
|
|
) -> Result<ServerMessage> {
|
||
|
|
verify_peer(&stream)?;
|
||
|
|
stream.set_read_timeout(Some(timeout))?;
|
||
|
|
stream.set_write_timeout(Some(timeout))?;
|
||
|
|
protocol::write_message(
|
||
|
|
&mut stream,
|
||
|
|
&ClientMessage::Hello {
|
||
|
|
version: expected_version,
|
||
|
|
},
|
||
|
|
)?;
|
||
|
|
match protocol::read_message::<ServerMessage>(&mut stream)? {
|
||
|
|
ServerMessage::Hello { version, .. } if version == expected_version => {}
|
||
|
|
ServerMessage::Hello { version, .. } => bail!(
|
||
|
|
"server protocol {version} does not match client protocol {}",
|
||
|
|
expected_version
|
||
|
|
),
|
||
|
|
ServerMessage::Error(error) => bail!(
|
||
|
|
"{error}. If the server predates this build, end its sessions with psyterm --shutdown and relaunch"
|
||
|
|
),
|
||
|
|
_ => bail!("server did not send a protocol greeting"),
|
||
|
|
}
|
||
|
|
protocol::write_message(&mut stream, &command)?;
|
||
|
|
loop {
|
||
|
|
let message: ServerMessage = protocol::read_message(&mut stream)?;
|
||
|
|
match message {
|
||
|
|
ServerMessage::Pong | ServerMessage::Closing => return Ok(message),
|
||
|
|
ServerMessage::Error(error) => bail!("{error}"),
|
||
|
|
_ => {}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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> {
|
||
|
|
let log = private_file(log_path)?;
|
||
|
|
let mut command = Command::new(executable);
|
||
|
|
command
|
||
|
|
.arg(role)
|
||
|
|
.arg("--socket")
|
||
|
|
.arg(socket)
|
||
|
|
.stdin(Stdio::null())
|
||
|
|
.stdout(Stdio::from(log.try_clone()?))
|
||
|
|
.stderr(Stdio::from(log));
|
||
|
|
let managed_helper = role == "--zygote";
|
||
|
|
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
|
||
|
|
// server's lifetime; the server itself intentionally outlives its launcher.
|
||
|
|
unsafe {
|
||
|
|
command.pre_exec(move || {
|
||
|
|
if libc::setsid() == -1 {
|
||
|
|
return Err(io::Error::last_os_error());
|
||
|
|
}
|
||
|
|
if managed_helper {
|
||
|
|
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
|
||
|
|
return Err(io::Error::last_os_error());
|
||
|
|
}
|
||
|
|
if libc::getppid() != parent_pid {
|
||
|
|
libc::_exit(1);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
});
|
||
|
|
}
|
||
|
|
command
|
||
|
|
.spawn()
|
||
|
|
.with_context(|| format!("launch psyTerm {role}"))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Linux marks `/proc/self/exe` with " (deleted)" after atomic replacement.
|
||
|
|
/// Resolve the new installed path without rewriting a real filename that happens
|
||
|
|
/// to end with those characters. Server logic remains loaded until shutdown;
|
||
|
|
/// only newly forked GUI code is refreshed by `Zygote::open_window`.
|
||
|
|
fn executable_path() -> Result<PathBuf> {
|
||
|
|
resolve_executable_path(std::env::current_exe()?)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn resolve_executable_path(path: PathBuf) -> Result<PathBuf> {
|
||
|
|
match fs::symlink_metadata(&path) {
|
||
|
|
Ok(_) => {
|
||
|
|
if path.is_file() {
|
||
|
|
return Ok(path);
|
||
|
|
}
|
||
|
|
bail!("{} is not an executable file", path.display());
|
||
|
|
}
|
||
|
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||
|
|
Err(error) => return Err(error).context("inspect current executable path"),
|
||
|
|
}
|
||
|
|
if let Some(original) = path.as_os_str().as_bytes().strip_suffix(b" (deleted)") {
|
||
|
|
let original = PathBuf::from(std::ffi::OsString::from_vec(original.to_vec()));
|
||
|
|
if original.is_file() {
|
||
|
|
return Ok(original);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
bail!(
|
||
|
|
"psyTerm executable {} no longer exists; restart the server from its installed location",
|
||
|
|
path.display()
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn uid() -> u32 {
|
||
|
|
// SAFETY: geteuid has no arguments or side effects.
|
||
|
|
unsafe { libc::geteuid() }
|
||
|
|
}
|
||
|
|
|
||
|
|
fn suffixed(path: &Path, suffix: &str) -> PathBuf {
|
||
|
|
let mut name = path.as_os_str().to_owned();
|
||
|
|
name.push(suffix);
|
||
|
|
PathBuf::from(name)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_socket_parent(socket: &Path) -> Result<()> {
|
||
|
|
let parent = socket
|
||
|
|
.parent()
|
||
|
|
.filter(|parent| !parent.as_os_str().is_empty())
|
||
|
|
.context("socket path must include a private parent directory")?;
|
||
|
|
ensure_private_directory(parent)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_private_directory(path: &Path) -> Result<()> {
|
||
|
|
match DirBuilder::new().mode(0o700).create(path) {
|
||
|
|
Ok(()) => {}
|
||
|
|
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
|
||
|
|
Err(error) => return Err(error).with_context(|| format!("create {}", path.display())),
|
||
|
|
}
|
||
|
|
verify_private_directory(path)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn verify_private_directory(path: &Path) -> Result<()> {
|
||
|
|
let metadata =
|
||
|
|
fs::symlink_metadata(path).with_context(|| format!("inspect {}", path.display()))?;
|
||
|
|
if !metadata.is_dir() || metadata.uid() != uid() || metadata.mode() & 0o077 != 0 {
|
||
|
|
bail!(
|
||
|
|
"{} must be a real directory owned by your UID with mode 0700",
|
||
|
|
path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
fn private_file(path: &Path) -> Result<File> {
|
||
|
|
let file = OpenOptions::new()
|
||
|
|
.read(true)
|
||
|
|
.append(true)
|
||
|
|
.create(true)
|
||
|
|
.mode(0o600)
|
||
|
|
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||
|
|
.open(path)
|
||
|
|
.with_context(|| format!("open {}", path.display()))?;
|
||
|
|
let metadata = file.metadata()?;
|
||
|
|
if !metadata.is_file()
|
||
|
|
|| metadata.uid() != uid()
|
||
|
|
|| metadata.mode() & 0o077 != 0
|
||
|
|
|| metadata.nlink() != 1
|
||
|
|
{
|
||
|
|
bail!(
|
||
|
|
"{} must be a private regular file owned by your UID",
|
||
|
|
path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
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"),
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub(crate) fn verify_peer(stream: &UnixStream) -> Result<()> {
|
||
|
|
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
|
||
|
|
// lengths; getsockopt writes only the SO_PEERCRED structure.
|
||
|
|
let result = unsafe {
|
||
|
|
libc::getsockopt(
|
||
|
|
stream.as_raw_fd(),
|
||
|
|
libc::SOL_SOCKET,
|
||
|
|
libc::SO_PEERCRED,
|
||
|
|
(&mut credentials as *mut libc::ucred).cast(),
|
||
|
|
&mut size,
|
||
|
|
)
|
||
|
|
};
|
||
|
|
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);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
|
||
|
|
fn test_dir() -> PathBuf {
|
||
|
|
let path = std::env::temp_dir().join(format!(
|
||
|
|
"psyterm-launcher-test-{}-{}",
|
||
|
|
std::process::id(),
|
||
|
|
std::time::SystemTime::now()
|
||
|
|
.duration_since(std::time::UNIX_EPOCH)
|
||
|
|
.unwrap()
|
||
|
|
.as_nanos()
|
||
|
|
));
|
||
|
|
ensure_private_directory(&path).unwrap();
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn private_paths_reject_symlinks_and_shared_directories() {
|
||
|
|
let root = test_dir();
|
||
|
|
let private = root.join("private");
|
||
|
|
ensure_private_directory(&private).unwrap();
|
||
|
|
let alias = root.join("alias");
|
||
|
|
std::os::unix::fs::symlink(&private, &alias).unwrap();
|
||
|
|
assert!(ensure_private_directory(&alias).is_err());
|
||
|
|
fs::set_permissions(&private, fs::Permissions::from_mode(0o755)).unwrap();
|
||
|
|
assert!(verify_private_directory(&private).is_err());
|
||
|
|
let file = root.join("log");
|
||
|
|
private_file(&file).unwrap();
|
||
|
|
let alias_file = root.join("alias-file");
|
||
|
|
std::os::unix::fs::symlink(&file, &alias_file).unwrap();
|
||
|
|
assert!(private_file(&alias_file).is_err());
|
||
|
|
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();
|
||
|
|
verify_peer(&left).unwrap();
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn deleted_executable_suffix_resolves_only_when_original_name_is_absent() {
|
||
|
|
let root = test_dir();
|
||
|
|
let original = root.join("psyterm");
|
||
|
|
let deleted = root.join("psyterm (deleted)");
|
||
|
|
fs::write(&original, b"new executable").unwrap();
|
||
|
|
assert_eq!(resolve_executable_path(deleted.clone()).unwrap(), original);
|
||
|
|
fs::write(&deleted, b"real literal filename").unwrap();
|
||
|
|
assert_eq!(resolve_executable_path(deleted.clone()).unwrap(), deleted);
|
||
|
|
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();
|
||
|
|
}
|
||
|
|
}
|