1#[cfg(unix)]
2use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
3
4#[cfg(unix)]
5use std::os::unix::io::{AsRawFd, FromRawFd};
6
7#[cfg(unix)]
8use tokio::net::UnixStream;
9
10#[cfg(unix)]
11use super::{lock_path, recoverer_lock_path};
12
13#[cfg(unix)]
14pub(super) fn open_lock_file(path: &std::path::Path) -> std::io::Result<std::fs::File> {
15 open_mutating_daemon_lock(path, false)
16}
17
18#[cfg(unix)]
21pub fn open_mutating_daemon_lock(
22 path: &std::path::Path,
23 read_write: bool,
24) -> std::io::Result<std::fs::File> {
25 let is_default_lock_parent = path.parent() == Some(super::khive_dir().as_path());
26 if is_default_lock_parent {
27 super::run_daemon::prepare_default_rendezvous_directory().map_err(lock_error)?;
28 }
29 if !is_default_lock_parent {
32 if let Some(parent) = path.parent() {
33 let _ = std::fs::create_dir_all(parent);
34 }
35 }
36 checked_open_lock(path, true, read_write, true)?
37 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "created lock is absent"))
38}
39
40#[cfg(unix)]
41fn lock_error(error: anyhow::Error) -> std::io::Error {
42 std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("{error:#}"))
43}
44
45#[cfg(unix)]
48pub(super) fn checked_open_lock(
49 path: &std::path::Path,
50 create: bool,
51 read_write: bool,
52 tighten: bool,
53) -> std::io::Result<Option<std::fs::File>> {
54 checked_open_lock_with_hooks(path, create, read_write, tighten, || {}, || {})
55}
56
57#[cfg(unix)]
58pub(super) fn checked_open_lock_with_hooks(
59 path: &std::path::Path,
60 create: bool,
61 read_write: bool,
62 tighten: bool,
63 before_openat: impl FnOnce(),
64 after_open: impl FnOnce(),
65) -> std::io::Result<Option<std::fs::File>> {
66 checked_open_lock_with_faults(
67 path,
68 create,
69 read_write,
70 tighten,
71 before_openat,
72 after_open,
73 (false, false),
74 )
75}
76
77#[cfg(unix)]
79pub(super) fn checked_open_lock_with_faults(
80 path: &std::path::Path,
81 create: bool,
82 read_write: bool,
83 tighten: bool,
84 before_openat: impl FnOnce(),
85 after_open: impl FnOnce(),
86 faults: (bool, bool),
87) -> std::io::Result<Option<std::fs::File>> {
88 checked_open_lock_with_observe_hook(
89 path,
90 create,
91 read_write,
92 tighten,
93 before_openat,
94 after_open,
95 (faults.0, faults.1, || {}),
96 )
97}
98
99#[cfg(unix)]
100pub(super) fn checked_open_lock_with_observe_hook(
101 path: &std::path::Path,
102 create: bool,
103 read_write: bool,
104 tighten: bool,
105 before_openat: impl FnOnce(),
106 after_open: impl FnOnce(),
107 faults_and_observer: (bool, bool, impl FnOnce()),
108) -> std::io::Result<Option<std::fs::File>> {
109 use std::os::unix::ffi::OsStrExt;
110 let (fail_metadata, fail_chmod, after_observe) = faults_and_observer;
111
112 let parent = path
113 .parent()
114 .filter(|p| !p.as_os_str().is_empty())
115 .unwrap_or_else(|| std::path::Path::new("."));
116 let leaf = path.file_name().ok_or_else(|| {
117 std::io::Error::new(
118 std::io::ErrorKind::InvalidInput,
119 "lock path has no basename",
120 )
121 })?;
122 let leaf = std::ffi::CString::new(leaf.as_bytes()).map_err(|_| {
123 std::io::Error::new(
124 std::io::ErrorKind::InvalidInput,
125 "lock basename contains NUL",
126 )
127 })?;
128 let observed_parent = match std::fs::symlink_metadata(parent) {
129 Ok(metadata) => metadata,
130 Err(error) if !create && error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
131 Err(error) => {
132 return Err(std::io::Error::new(
133 error.kind(),
134 format!("cannot inspect lock parent {}: {error}", parent.display()),
135 ))
136 }
137 };
138 super::ensure_pid_file_dir_is_trusted(path).map_err(lock_error)?;
139 let directory = std::fs::OpenOptions::new()
140 .read(true)
141 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
142 .open(parent)
143 .map_err(|error| {
144 std::io::Error::new(
145 error.kind(),
146 format!(
147 "refusing lock parent {} (mode {:04o}): {error}",
148 parent.display(),
149 observed_parent.mode() & 0o7777
150 ),
151 )
152 })?;
153 let opened_parent = directory.metadata()?;
154 if !observed_parent.is_dir()
155 || !opened_parent.is_dir()
156 || observed_parent.dev() != opened_parent.dev()
157 || observed_parent.ino() != opened_parent.ino()
158 {
159 return Err(std::io::Error::new(
160 std::io::ErrorKind::PermissionDenied,
161 "lock parent changed during open",
162 ));
163 }
164 before_openat();
165 let current_parent = std::fs::symlink_metadata(parent)?;
166 if !current_parent.is_dir()
167 || current_parent.dev() != opened_parent.dev()
168 || current_parent.ino() != opened_parent.ino()
169 {
170 return Err(std::io::Error::new(
171 std::io::ErrorKind::PermissionDenied,
172 "lock parent changed before openat",
173 ));
174 }
175 let uid = unsafe { libc::geteuid() } as u32;
177 let mut observed = match std::fs::symlink_metadata(path) {
178 Ok(metadata) => {
179 if !metadata.is_file() || metadata.uid() != uid || metadata.nlink() != 1 {
180 return Err(std::io::Error::new(
181 std::io::ErrorKind::PermissionDenied,
182 format!(
183 "refusing lock {}: owner uid {}, mode {:04o}",
184 path.display(),
185 metadata.uid(),
186 metadata.mode() & 0o7777
187 ),
188 ));
189 }
190 Some(metadata)
191 }
192 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
193 Err(error) => return Err(error),
194 };
195 if observed.is_none() && !create {
196 return Ok(None);
197 }
198 after_observe();
199 let access = if read_write {
200 libc::O_RDWR
201 } else if tighten && !create {
202 libc::O_RDONLY
203 } else if create {
204 libc::O_WRONLY
205 } else {
206 libc::O_RDONLY
207 };
208 let mut flags = access | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC;
209 let mut created = observed.is_none();
210 if created {
211 flags |= libc::O_CREAT | libc::O_EXCL;
212 }
213 let mut fd = unsafe { libc::openat(directory.as_raw_fd(), leaf.as_ptr(), flags, 0o600) };
215 if fd < 0
216 && created
217 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::AlreadyExists
218 {
219 let metadata = std::fs::symlink_metadata(path)?;
222 if !metadata.is_file() || metadata.uid() != uid || metadata.nlink() != 1 {
223 return Err(std::io::Error::new(
224 std::io::ErrorKind::PermissionDenied,
225 format!(
226 "refusing lock {}: owner uid {}, mode {:04o}",
227 path.display(),
228 metadata.uid(),
229 metadata.mode() & 0o7777
230 ),
231 ));
232 }
233 observed = Some(metadata);
234 created = false;
235 flags &= !(libc::O_CREAT | libc::O_EXCL);
236 fd = unsafe { libc::openat(directory.as_raw_fd(), leaf.as_ptr(), flags, 0o600) };
238 }
239 if fd < 0
240 && !create
241 && tighten
242 && !read_write
243 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::PermissionDenied
244 {
245 flags = (flags & !libc::O_ACCMODE) | libc::O_WRONLY;
246 fd = unsafe { libc::openat(directory.as_raw_fd(), leaf.as_ptr(), flags, 0o600) };
248 }
249 if fd < 0 {
250 let error = std::io::Error::last_os_error();
251 let observed_mode = observed
252 .as_ref()
253 .map(|metadata| format!("{:04o}", metadata.mode() & 0o7777))
254 .unwrap_or_else(|| "absent".to_owned());
255 return Err(std::io::Error::new(
256 error.kind(),
257 format!(
258 "cannot safely open lock {} (observed mode {observed_mode}): {error}",
259 path.display()
260 ),
261 ));
262 }
263 let file = unsafe { std::fs::File::from_raw_fd(fd) };
265 let identity_changed = std::cell::Cell::new(false);
266 let result = (|| -> std::io::Result<()> {
267 if fail_metadata {
268 return Err(std::io::Error::other("injected metadata failure"));
269 }
270 let opened = file.metadata()?;
271 if !opened.is_file()
272 || opened.uid() != uid
273 || opened.nlink() != 1
274 || observed.as_ref().is_some_and(|metadata| {
275 metadata.dev() != opened.dev() || metadata.ino() != opened.ino()
276 })
277 {
278 identity_changed.set(true);
279 return Err(std::io::Error::new(
280 std::io::ErrorKind::PermissionDenied,
281 format!(
282 "lock {} changed during open (mode {:04o})",
283 path.display(),
284 opened.mode() & 0o7777
285 ),
286 ));
287 }
288 after_open();
289 let check_identity = || -> std::io::Result<()> {
290 let current_parent = std::fs::symlink_metadata(parent)?;
291 let current_lock = std::fs::symlink_metadata(path)?;
292 if !current_parent.is_dir()
293 || current_parent.dev() != opened_parent.dev()
294 || current_parent.ino() != opened_parent.ino()
295 || !current_lock.is_file()
296 || current_lock.dev() != opened.dev()
297 || current_lock.ino() != opened.ino()
298 {
299 return Err(std::io::Error::new(
300 std::io::ErrorKind::PermissionDenied,
301 "lock or parent changed during open",
302 ));
303 }
304 Ok(())
305 };
306 check_identity().inspect_err(|_| {
307 identity_changed.set(true);
308 })?;
309 if tighten {
310 let latest = file.metadata()?;
311 if !latest.is_file() || latest.uid() != uid || latest.nlink() != 1 {
312 identity_changed.set(true);
313 return Err(std::io::Error::new(
314 std::io::ErrorKind::PermissionDenied,
315 "lock ownership changed",
316 ));
317 }
318 let mode = latest.mode() & 0o7777;
319 let target = if created { 0o600 } else { mode & 0o600 };
320 if target != mode {
321 if fail_chmod {
322 return Err(std::io::Error::other("injected chmod failure"));
323 }
324 file.set_permissions(std::fs::Permissions::from_mode(target))?;
325 }
326 }
327 check_identity().inspect_err(|_| {
328 identity_changed.set(true);
329 })?;
330 Ok(())
331 })();
332 if let Err(error) = result {
333 if created {
334 let guidance = if identity_changed.get() {
335 "the lock path or its parent changed; inspect the path and do not remove the replacement"
336 } else {
337 "after confirming no daemon is running and verifying the entry is the leftover lock, remove it and retry; do not remove an unverified entry"
338 };
339 return Err(std::io::Error::new(
340 error.kind(),
341 format!(
342 "failed to finish creating lock {}: {error}; {guidance}",
343 path.display()
344 ),
345 ));
346 }
347 return Err(error);
348 }
349 Ok(Some(file))
350}
351
352#[cfg(unix)]
353fn acquire_flock_blocking(path: &std::path::Path, label: &str) -> Option<std::fs::File> {
354 let file = match open_lock_file(path) {
355 Ok(f) => f,
356 Err(e) => {
357 tracing::warn!(target: "khive_runtime::daemon", error = %e, path = ?path, "cannot open {label} lock file");
358 return None;
359 }
360 };
361 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
363 if rc != 0 {
364 tracing::warn!(target: "khive_runtime::daemon", "flock LOCK_EX failed on {label} lock");
365 return None;
366 }
367 Some(file)
368}
369
370#[cfg(unix)]
377pub fn acquire_recovery_lock() -> Option<std::fs::File> {
378 acquire_flock_blocking(&lock_path(), "recovery")
379}
380
381#[cfg(unix)]
396fn try_acquire_flock_until(
397 path: &std::path::Path,
398 deadline: std::time::Instant,
399) -> std::io::Result<Option<std::fs::File>> {
400 let file = open_lock_file(path)?;
401 let poll_interval = std::time::Duration::from_millis(10);
402 loop {
403 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
405 if rc == 0 {
406 return Ok(Some(file));
407 }
408 let err = std::io::Error::last_os_error();
409 if err.raw_os_error() != Some(libc::EWOULDBLOCK) {
410 return Err(err);
411 }
412 let now = std::time::Instant::now();
413 if now >= deadline {
414 return Ok(None);
415 }
416 std::thread::sleep(poll_interval.min(deadline - now));
417 }
418}
419
420#[cfg(unix)]
427pub fn try_acquire_daemon_boot_guard_until(
428 deadline: std::time::Instant,
429) -> std::io::Result<Option<DaemonBootGuard>> {
430 try_acquire_flock_until(&lock_path(), deadline)
431}
432
433#[cfg(unix)]
439pub fn try_acquire_recoverer_lock_until(
440 deadline: std::time::Instant,
441) -> std::io::Result<Option<std::fs::File>> {
442 try_acquire_flock_until(&recoverer_lock_path(), deadline)
443}
444
445#[cfg(unix)]
449pub type DaemonBootGuard = std::fs::File;
450
451#[cfg(unix)]
461pub fn acquire_daemon_boot_guard() -> anyhow::Result<DaemonBootGuard> {
462 let explicit_rendezvous = super::lifecycle::path_override(super::lifecycle::PID_PATH_ENV)
463 .is_some()
464 || super::lifecycle::path_override(super::lifecycle::SOCKET_PATH_ENV).is_some();
465 if !explicit_rendezvous {
466 super::run_daemon::prepare_default_rendezvous_directory().map_err(|error| {
467 tracing::warn!(target: "khive_runtime::daemon", %error, "cannot prepare default daemon rendezvous");
468 anyhow::anyhow!("failed to acquire daemon boot/recovery lock")
469 })?;
470 }
471 acquire_recovery_lock()
472 .ok_or_else(|| anyhow::anyhow!("failed to acquire daemon boot/recovery lock"))
473}
474
475#[cfg(unix)]
482#[derive(Clone, Copy, PartialEq, Eq)]
483pub(super) struct SocketIdentity {
484 dev: u64,
485 ino: u64,
486}
487
488#[cfg(unix)]
489pub(super) fn socket_identity(path: &std::path::Path) -> Option<SocketIdentity> {
490 use std::os::unix::fs::MetadataExt;
491 let meta = std::fs::metadata(path).ok()?;
492 Some(SocketIdentity {
493 dev: meta.dev(),
494 ino: meta.ino(),
495 })
496}
497
498#[cfg(unix)]
512pub(crate) fn peer_uid(stream: &UnixStream) -> std::io::Result<u32> {
513 use std::os::fd::AsRawFd;
514 let fd = stream.as_raw_fd();
515
516 #[cfg(any(target_os = "macos", target_os = "ios", target_vendor = "apple"))]
517 {
518 let mut uid: libc::uid_t = 0;
519 let mut gid: libc::gid_t = 0;
520 let rc = unsafe { libc::getpeereid(fd, &mut uid, &mut gid) };
523 if rc != 0 {
524 return Err(std::io::Error::last_os_error());
525 }
526 Ok(uid as u32)
527 }
528
529 #[cfg(target_os = "linux")]
530 {
531 let mut cred = libc::ucred {
532 pid: 0,
533 uid: 0,
534 gid: 0,
535 };
536 let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
537 let rc = unsafe {
541 libc::getsockopt(
542 fd,
543 libc::SOL_SOCKET,
544 libc::SO_PEERCRED,
545 (&mut cred as *mut libc::ucred).cast::<libc::c_void>(),
546 &mut len,
547 )
548 };
549 if rc != 0 {
550 return Err(std::io::Error::last_os_error());
551 }
552 Ok(cred.uid)
553 }
554
555 #[cfg(not(any(
556 target_os = "linux",
557 target_os = "macos",
558 target_os = "ios",
559 target_vendor = "apple"
560 )))]
561 {
562 let _ = fd;
563 Err(std::io::Error::new(
564 std::io::ErrorKind::Unsupported,
565 "peer-credential capture is not implemented for this platform",
566 ))
567 }
568}
569
570#[cfg(unix)]
591pub(crate) fn uid_is_permitted(peer: u32, daemon_euid: u32) -> bool {
592 peer == daemon_euid
593}