#[cfg(unix)]
use std::io::ErrorKind;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use shep_core::paths::ShepPaths;
use shep_core::transport::Listener;
use super::BootError;
use super::pidfile::read_pidfile;
#[must_use]
pub(crate) fn socket_path(paths: &ShepPaths, override_path: Option<&Path>) -> PathBuf {
match override_path {
Some(path) => path.to_path_buf(),
None => paths.socket.clone(),
}
}
#[cfg(unix)]
fn warn_if_socket_dir_is_loose(socket: &Path) {
let Some(parent) = socket.parent() else {
return;
};
let Ok(metadata) = std::fs::metadata(parent) else {
return;
};
if metadata.permissions().mode() & 0o022 != 0 {
tracing::warn!(
path = %parent.display(),
"control-socket directory is group- or world-writable; \
the 0700 guarantee only covers the default $SHEP_HOME/run"
);
}
}
#[allow(clippy::needless_return)]
pub(crate) fn bind_socket(paths: &ShepPaths, socket: &Path) -> Result<Listener, BootError> {
#[cfg(windows)]
{
const ERROR_ACCESS_DENIED: i32 = 5;
return match Listener::bind(socket) {
Ok(listener) => Ok(listener),
Err(err) if err.raw_os_error() == Some(ERROR_ACCESS_DENIED) => {
Err(BootError::AlreadyRunning {
pid: read_pidfile(paths)?,
})
}
Err(source) => Err(BootError::io(socket, source)),
};
}
#[cfg(unix)]
{
const SUN_PATH_CAPACITY: usize = if cfg!(target_os = "linux") { 108 } else { 104 };
let len = socket.as_os_str().as_encoded_bytes().len();
if len >= SUN_PATH_CAPACITY {
return Err(BootError::SocketPathTooLong {
path: socket.to_path_buf(),
len,
limit: SUN_PATH_CAPACITY - 1,
});
}
warn_if_socket_dir_is_loose(socket);
match Listener::bind(socket) {
Ok(listener) => Ok(listener),
Err(err) if err.kind() == ErrorKind::AddrInUse => {
match std::os::unix::net::UnixStream::connect(socket) {
Ok(_) => Err(BootError::AlreadyRunning {
pid: read_pidfile(paths)?,
}),
Err(probe)
if matches!(
probe.kind(),
ErrorKind::ConnectionRefused | ErrorKind::NotFound
) =>
{
std::fs::remove_file(socket)
.map_err(|source| BootError::io(socket, source))?;
Listener::bind(socket).map_err(|source| BootError::io(socket, source))
}
Err(source) => Err(BootError::io(socket, source)),
}
}
Err(source) => Err(BootError::io(socket, source)),
}
}
}
pub const READY_FD_ENV: &str = "SHEP_READY_FD";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonReady {
pub(crate) pid: u32,
pub(crate) version: String,
}
pub(super) fn write_ready(mut pipe: std::fs::File, ready: &DaemonReady) -> Result<(), BootError> {
use std::io::Write;
let mut line = serde_json::to_string(ready).expect("DaemonReady always serializes");
line.push('\n');
pipe.write_all(line.as_bytes())
.map_err(BootError::ReadyWrite)?;
Ok(())
}
#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
use crate::boot::{init_dirs, paths_in};
#[tokio::test]
async fn a_second_bind_on_a_live_control_address_reports_already_running() {
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
init_dirs(&paths).unwrap();
let _live = bind_socket(&paths, &paths.socket).expect("the first bind must succeed");
let refusal = bind_socket(&paths, &paths.socket)
.expect_err("a second daemon must not bind the same pipe");
assert!(
matches!(refusal, BootError::AlreadyRunning { .. }),
"a taken pipe name must read as AlreadyRunning, got {refusal:?}"
);
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::boot::pidfile::write_pidfile;
use crate::boot::{BootOptions, SIGNAL_TEST_LOCK, boot_with_idle_sweep, init_dirs};
use crate::fake::ScriptedRunner;
use crate::testing::test_paths;
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
#[test]
fn socket_path_honors_a_config_override() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
assert_eq!(socket_path(&paths, None), paths.socket);
let custom = dir.path().join("custom.sock");
assert_eq!(socket_path(&paths, Some(&custom)), custom);
}
#[tokio::test]
async fn an_over_length_socket_path_names_the_limit_and_the_variable() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let long = dir.path().join("x".repeat(200));
let err = bind_socket(&paths, &long).expect_err("a path this long cannot bind");
assert!(
matches!(err, BootError::SocketPathTooLong { .. }),
"refused before the syscall, not translated after it: {err:?}"
);
let rendered = err.to_string();
assert!(
rendered.contains("$SHEP_HOME"),
"the message names what to shorten: {rendered}"
);
assert!(
rendered.contains("bytes"),
"and the limit it is measured against: {rendered}"
);
assert!(
!rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
"no em or en dash in copy a user reads: {rendered}"
);
}
#[tokio::test]
async fn bind_socket_binds_a_fresh_path() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let listener = bind_socket(&paths, &paths.socket).unwrap();
assert!(paths.socket.exists());
drop(listener);
}
#[track_caller]
fn stale_socket_leftover(socket: &Path) {
for _ in 0..20 {
let _ = std::fs::remove_file(socket);
drop(std::os::unix::net::UnixListener::bind(socket).unwrap());
for _ in 0..40 {
match std::os::unix::net::UnixStream::connect(socket) {
Err(refused)
if matches!(
refused.kind(),
ErrorKind::ConnectionRefused | ErrorKind::NotFound
) =>
{
return;
}
Ok(_) => std::thread::sleep(Duration::from_millis(5)),
Err(other) => {
panic!("probing the fabricated leftover socket failed: {other}")
}
}
}
}
panic!(
"{} never went stale: something kept answering on it",
socket.display()
);
}
#[tokio::test]
async fn a_socket_left_by_a_crash_is_unlinked_and_rebound() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
stale_socket_leftover(&paths.socket);
assert!(paths.socket.exists(), "the stale file must still be there");
let listener = bind_socket(&paths, &paths.socket).unwrap();
assert!(paths.socket.exists());
drop(listener);
}
#[tokio::test]
async fn a_live_socket_is_reported_as_already_running() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let live = tokio::net::UnixListener::bind(&paths.socket).unwrap();
write_pidfile(&paths, 4242).unwrap();
assert!(matches!(
bind_socket(&paths, &paths.socket),
Err(BootError::AlreadyRunning { pid: Some(4242) })
));
assert!(
paths.socket.exists(),
"a live daemon's socket must never be unlinked"
);
std::os::unix::net::UnixStream::connect(&paths.socket)
.expect("the live listener must still be accepting after a refused bind");
drop(live);
}
#[derive(Debug)]
enum RaceOutcome {
Won { socket_still_accepts: bool },
AlreadyRunning,
Other(String),
}
const RACER_VERDICT_BOUND: Duration = Duration::from_secs(10);
#[track_caller]
fn swap_verdicts(outbox: &mpsc::Sender<()>, inbox: &mpsc::Receiver<()>) {
outbox
.send(())
.expect("the sibling holds its inbox open until it reports");
inbox
.recv_timeout(RACER_VERDICT_BOUND)
.expect("the other racer panicked or wedged before it reported");
}
#[test]
fn two_concurrent_boots_on_a_stale_socket_exactly_one_wins() {
for _ in 0..25 {
let _guard = SIGNAL_TEST_LOCK.blocking_lock();
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
stale_socket_leftover(&paths.socket);
let start = Arc::new(std::sync::Barrier::new(2));
let (outboxes, inboxes): (Vec<_>, Vec<_>) =
(0..2).map(|_| mpsc::channel::<()>()).unzip();
let handles: Vec<_> = inboxes
.into_iter()
.enumerate()
.map(|(racer, inbox)| {
let paths = paths.clone();
let start = Arc::clone(&start);
let outbox = outboxes[1 - racer].clone();
std::thread::spawn(move || {
start.wait(); let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
match boot_with_idle_sweep(
ScriptedRunner::new(vec![]),
paths,
BootOptions::default(),
)
.await
{
Ok(daemon) => {
let reachable =
std::os::unix::net::UnixStream::connect(daemon.socket())
.is_ok();
swap_verdicts(&outbox, &inbox);
drop(daemon);
RaceOutcome::Won {
socket_still_accepts: reachable,
}
}
Err(BootError::AlreadyRunning { .. }) => {
swap_verdicts(&outbox, &inbox);
RaceOutcome::AlreadyRunning
}
Err(other) => {
swap_verdicts(&outbox, &inbox);
RaceOutcome::Other(other.to_string())
}
}
})
})
})
.collect();
drop(outboxes);
let outcomes: Vec<RaceOutcome> =
handles.into_iter().map(|h| h.join().unwrap()).collect();
for outcome in &outcomes {
if let RaceOutcome::Other(msg) = outcome {
panic!("a racer hit neither Ok nor AlreadyRunning: {msg}");
}
}
let wins = outcomes
.iter()
.filter(|o| matches!(o, RaceOutcome::Won { .. }))
.count();
let already_running = outcomes
.iter()
.filter(|o| matches!(o, RaceOutcome::AlreadyRunning))
.count();
assert_eq!(
wins, 1,
"exactly one racer must win a boot on the same $SHEP_HOME: {outcomes:?}"
);
assert_eq!(
already_running, 1,
"the loser must be refused as AlreadyRunning, not silently succeed or hit some other error: {outcomes:?}"
);
assert!(
matches!(
outcomes
.iter()
.find(|o| matches!(o, RaceOutcome::Won { .. }))
.unwrap(),
RaceOutcome::Won {
socket_still_accepts: true
}
),
"the winner's own socket must still accept a connection, proving its bind \
wasn't the one the loser's remove_file clobbered: {outcomes:?}"
);
}
}
#[test]
fn readiness_reports_pid_and_version_then_closes_the_pipe() {
use std::io::Read;
let (mut reader, writer) = std::io::pipe().unwrap();
let pipe = std::fs::File::from(std::os::fd::OwnedFd::from(writer));
let ready = DaemonReady {
pid: 4242,
version: "0.1.0".to_string(),
};
write_ready(pipe, &ready).unwrap();
let mut line = String::new();
reader.read_to_string(&mut line).unwrap();
assert_eq!(line.trim_end(), serde_json::to_string(&ready).unwrap());
assert!(line.ends_with('\n'), "the parent reads a line: {line:?}");
}
}