use super::*;
pub(super) fn image_identity(path: &Path) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(path).ok()?;
Some((meta.dev(), meta.ino()))
}
pub(super) fn spawn_stale_image_watcher(host: Arc<Host>, handoff: HandoffFds) {
let Ok(exe) = std::env::current_exe() else {
return;
};
let Some(start) = image_identity(&exe) else {
return;
};
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(30));
let Some(now) = image_identity(&exe) else {
continue;
};
if now != start {
let err = swap_to_new_image(&host, &exe, &handoff);
let _ = std::fs::write(stale_marker_path(&host.socket), format!("{err:#}"));
return;
}
}
});
}
pub(super) fn spawn_marker_only_watcher(socket: PathBuf) {
let Ok(exe) = std::env::current_exe() else {
return;
};
let Some(start) = image_identity(&exe) else {
return;
};
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(30));
let Some(now) = image_identity(&exe) else {
continue;
};
if now != start {
let _ = std::fs::write(stale_marker_path(&socket), b"");
return;
}
}
});
}
pub(super) const RESUME_LISTENER_ENV: &str = "CROFT_SESSION_RESUME_LISTENER";
pub(super) const RESUME_MASTER_ENV: &str = "CROFT_SESSION_RESUME_MASTER";
pub(super) const RESUME_CHILD_ENV: &str = "CROFT_SESSION_RESUME_CHILD";
pub(super) const RESUME_TOKEN_ENV: &str = "CROFT_SESSION_RESUME_TOKEN";
pub(super) fn sigpipe_action() -> Option<libc::sigaction> {
let mut old: libc::sigaction = unsafe { std::mem::zeroed() };
(unsafe { libc::sigaction(libc::SIGPIPE, std::ptr::null(), &mut old) } == 0).then_some(old)
}
pub(super) fn set_cloexec(fd: std::os::fd::RawFd, on: bool) -> Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
anyhow::ensure!(flags != -1, "F_GETFD({fd}) failed");
let flags = if on {
flags | libc::FD_CLOEXEC
} else {
flags & !libc::FD_CLOEXEC
};
let rc = unsafe { libc::fcntl(fd, libc::F_SETFD, flags) };
anyhow::ensure!(rc != -1, "F_SETFD({fd}) failed");
Ok(())
}
pub(super) fn swap_to_new_image(host: &Host, exe: &Path, handoff: &HandoffFds) -> anyhow::Error {
{
let _clients = host.clients.lock().unwrap();
host.swapping.store(true, Ordering::SeqCst);
}
let invited = broadcast_tracked(host, &encode_control_frame(&Control::HostSwap));
let started = Instant::now();
await_delivery(&invited, started + SWAP_INVITATION_DEADLINE);
let _sealed = seal_against_new_arrivals(host, started + SWAP_FENCE_CAP);
if let Err(e) =
set_cloexec(handoff.listener, false).and_then(|()| set_cloexec(handoff.master, false))
{
let _ = set_cloexec(handoff.listener, true);
let _ = set_cloexec(handoff.master, true);
host.swapping.store(false, Ordering::SeqCst);
return e;
}
let mut cmd = std::process::Command::new(exe);
cmd.args(std::env::args_os().skip(1))
.env(RESUME_LISTENER_ENV, handoff.listener.to_string())
.env(RESUME_MASTER_ENV, handoff.master.to_string())
.env(RESUME_CHILD_ENV, handoff.child_pid.to_string())
.env(RESUME_TOKEN_ENV, &host.token);
use std::os::unix::process::CommandExt;
let sigpipe = sigpipe_action();
let err = anyhow::Error::from(cmd.exec()).context("exec of updated binary");
if let Some(action) = sigpipe {
unsafe { libc::sigaction(libc::SIGPIPE, &action, std::ptr::null_mut()) };
}
let _ = set_cloexec(handoff.listener, true);
let _ = set_cloexec(handoff.master, true);
host.swapping.store(false, Ordering::SeqCst);
err
}
pub(super) struct ResumedSession {
listener: std::os::unix::net::UnixListener,
master: std::os::fd::RawFd,
child_pid: u32,
token: String,
}
pub(super) fn resume_from(var: impl Fn(&str) -> Option<String>) -> Result<Option<ResumedSession>> {
if var(RESUME_LISTENER_ENV).is_none() {
return Ok(None);
}
let parse_fd = |name: &str| -> Result<std::os::fd::RawFd> {
let raw = var(name).with_context(|| format!("resume var {name} missing"))?;
let fd: std::os::fd::RawFd = raw
.parse()
.with_context(|| format!("resume var {name}={raw} is not an fd"))?;
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
anyhow::ensure!(
flags != -1,
"resume fd {fd} ({name}) did not survive the exec"
);
Ok(fd)
};
let listener_fd = parse_fd(RESUME_LISTENER_ENV)?;
let master = parse_fd(RESUME_MASTER_ENV)?;
let child_pid: u32 = var(RESUME_CHILD_ENV)
.context("resume var CROFT_SESSION_RESUME_CHILD missing")?
.parse()
.context("resume child pid unparseable")?;
let token = var(RESUME_TOKEN_ENV).context("resume var CROFT_SESSION_RESUME_TOKEN missing")?;
set_cloexec(listener_fd, true)?;
set_cloexec(master, true)?;
use std::os::fd::FromRawFd;
let listener = unsafe { std::os::unix::net::UnixListener::from_raw_fd(listener_fd) };
Ok(Some(ResumedSession {
listener,
master,
child_pid,
token,
}))
}
pub(super) fn run_resumed(socket: &Path, resumed: ResumedSession) -> Result<i32> {
let _ = std::fs::remove_file(presence_path(socket));
let _ = std::fs::remove_file(stale_marker_path(socket));
write_host_version(socket);
let dup = |fd: std::os::fd::RawFd| -> Result<std::fs::File> {
let d = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
anyhow::ensure!(d != -1, "dup of inherited master fd {fd} failed");
use std::os::fd::FromRawFd;
Ok(unsafe { std::fs::File::from_raw_fd(d) })
};
let reader = dup(resumed.master)?;
let writer = dup(resumed.master)?;
run_host(
socket,
&resumed.token,
resumed.listener,
Box::new(reader),
Box::new(writer),
MasterHandle::Adopted(resumed.master),
ChildHandle::Adopted(resumed.child_pid),
)
}
pub(super) fn seal_against_new_arrivals(
host: &Host,
hard_cap: Instant,
) -> std::sync::MutexGuard<'_, Vec<Client>> {
loop {
let pending = std::mem::take(&mut *host.farewells.lock().unwrap());
if pending.is_empty() {
let sealed = host.clients.lock().unwrap();
if host.farewells.lock().unwrap().is_empty() {
return sealed;
}
drop(sealed);
} else {
let grace = (Instant::now() + FAREWELL_GRACE).min(hard_cap);
await_delivery(&pending, grace);
}
if Instant::now() >= hard_cap {
return host.clients.lock().unwrap();
}
}
}
pub(super) const SWAP_INVITATION_DEADLINE: Duration = Duration::from_secs(6);
pub(super) const FAREWELL_GRACE: Duration = Duration::from_millis(250);
pub(super) const SWAP_FENCE_CAP: Duration = Duration::from_secs(10);