467 lines
16 KiB
Rust
467 lines
16 KiB
Rust
//! Local daemon startup, private sockets and process roles.
|
|
|
|
#[cfg(target_os = "linux")]
|
|
pub(crate) mod zygote;
|
|
|
|
use std::{
|
|
fs::{self, DirBuilder, File, OpenOptions},
|
|
io,
|
|
os::{
|
|
fd::AsRawFd,
|
|
unix::{
|
|
ffi::{OsStrExt, OsStringExt},
|
|
fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
|
|
net::UnixStream,
|
|
process::CommandExt,
|
|
},
|
|
},
|
|
path::{Path, PathBuf},
|
|
process::{Child, Command, Stdio},
|
|
thread,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use anyhow::{Context, Result, bail};
|
|
|
|
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_from(&executable_path()?, "--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 mut result = control_stream(stream, command, REQUEST_TIMEOUT);
|
|
if legacy_shutdown {
|
|
// Older versions share the Hello/Shutdown/Closing wire prefix. Permit
|
|
// only explicit shutdown through it, never decoding older grid layouts.
|
|
for version in (1..protocol::VERSION).rev() {
|
|
if !result
|
|
.as_ref()
|
|
.is_err_and(|error| error.to_string().contains("protocol"))
|
|
{
|
|
break;
|
|
}
|
|
let stream = UnixStream::connect(socket)?;
|
|
result =
|
|
control_stream_version(stream, ClientMessage::Shutdown, REQUEST_TIMEOUT, version);
|
|
}
|
|
}
|
|
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}"),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
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
|
|
.arg(role)
|
|
.arg("--socket")
|
|
.arg(socket)
|
|
.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
|
|
// 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());
|
|
}
|
|
#[cfg(target_os = "linux")]
|
|
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(())
|
|
});
|
|
}
|
|
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.
|
|
/// 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)
|
|
}
|
|
|
|
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(())
|
|
}
|
|
|
|
#[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
|
|
// 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());
|
|
}
|
|
Ok(credentials.uid)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
use std::os::unix::{fs::PermissionsExt, net::UnixListener};
|
|
|
|
pub(super) fn test_dir() -> PathBuf {
|
|
let path = std::env::temp_dir().join(format!(
|
|
"pt-{:x}-{:x}",
|
|
std::process::id(),
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_nanos()
|
|
));
|
|
ensure_private_directory(&path).unwrap();
|
|
path
|
|
}
|
|
|
|
#[test]
|
|
fn explicit_shutdown_negotiates_previous_protocol_prefixes() {
|
|
for old_version in 1..protocol::VERSION {
|
|
let root = test_dir();
|
|
let socket = root.join("server.sock");
|
|
let listener = UnixListener::bind(&socket).unwrap();
|
|
let peer = thread::spawn(move || {
|
|
for expected_attempt in (old_version..=protocol::VERSION).rev() {
|
|
let (mut stream, _) = listener.accept().unwrap();
|
|
stream.set_read_timeout(Some(REQUEST_TIMEOUT)).unwrap();
|
|
let hello = protocol::read_message::<ClientMessage>(&mut stream).unwrap();
|
|
assert!(
|
|
matches!(hello, ClientMessage::Hello { version } if version == expected_attempt)
|
|
);
|
|
if expected_attempt != old_version {
|
|
protocol::write_message(
|
|
&mut stream,
|
|
&ServerMessage::Error("protocol mismatch".into()),
|
|
)
|
|
.unwrap();
|
|
continue;
|
|
}
|
|
protocol::write_message(
|
|
&mut stream,
|
|
&ServerMessage::Hello {
|
|
version: old_version,
|
|
server_pid: std::process::id(),
|
|
},
|
|
)
|
|
.unwrap();
|
|
assert!(matches!(
|
|
protocol::read_message::<ClientMessage>(&mut stream).unwrap(),
|
|
ClientMessage::Shutdown
|
|
));
|
|
protocol::write_message(&mut stream, &ServerMessage::Closing).unwrap();
|
|
}
|
|
});
|
|
assert!(matches!(
|
|
control(&socket, ClientMessage::Shutdown).unwrap(),
|
|
ServerMessage::Closing
|
|
));
|
|
peer.join().unwrap();
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
}
|
|
|
|
#[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 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();
|
|
}
|
|
}
|