1use std::os::unix::process::CommandExt;
8use std::process::Command;
9use std::{
10 fs::{File, OpenOptions},
11 os::{
12 fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd},
13 unix::fs::OpenOptionsExt,
14 },
15 path::Path,
16 sync::{
17 atomic::{AtomicBool, AtomicI32, Ordering},
18 Arc,
19 },
20 time::{Duration, Instant},
21};
22
23use sysprims_core::{SysprimsError, SysprimsResult};
24
25use crate::{NohupConfig, NohupOutcome, SetsidConfig, SetsidOutcome};
26
27const SESSION_ACK_MAGIC: [u8; 4] = *b"SYSA";
28const SESSION_ACK_VERSION: u32 = 1;
29
30#[repr(C)]
31#[derive(Clone, Copy)]
32struct SessionAcknowledgement {
33 magic: [u8; 4],
34 version: u32,
35 child_pid: u32,
36 session_id: u32,
37}
38
39const SESSION_ACK_LEN: usize = std::mem::size_of::<SessionAcknowledgement>();
40const SESSION_ACK_WAIT_TIMEOUT: Duration = Duration::from_secs(2);
43
44struct SessionHookState {
45 writer_fd: AtomicI32,
46 token_reader_fd: AtomicI32,
47 invoked: AtomicBool,
48}
49
50impl SessionHookState {
51 fn close_parent_descriptors(&self) {
52 let writer_fd = self.writer_fd.swap(-1, Ordering::AcqRel);
53 if writer_fd >= 0 {
54 unsafe {
57 libc::close(writer_fd);
58 }
59 }
60 let token_reader_fd = self.token_reader_fd.swap(-1, Ordering::AcqRel);
61 if token_reader_fd >= 0 {
62 unsafe {
65 libc::close(token_reader_fd);
66 }
67 }
68 }
69}
70
71impl Drop for SessionHookState {
72 fn drop(&mut self) {
73 self.close_parent_descriptors();
74 }
75}
76
77pub struct UnixSessionAcquisitionHook {
83 state: Arc<SessionHookState>,
84}
85
86impl std::fmt::Debug for UnixSessionAcquisitionHook {
87 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 formatter
89 .debug_struct("UnixSessionAcquisitionHook")
90 .finish_non_exhaustive()
91 }
92}
93
94impl UnixSessionAcquisitionHook {
95 pub unsafe fn acquire(&self) -> std::io::Result<()> {
104 if self
105 .state
106 .invoked
107 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
108 .is_err()
109 {
110 return Err(std::io::Error::from_raw_os_error(libc::EALREADY));
111 }
112
113 let token_reader_fd = self.state.token_reader_fd.load(Ordering::Acquire);
114 if token_reader_fd < 0 {
115 return Err(std::io::Error::from_raw_os_error(libc::EBADF));
116 }
117 let mut token = 0_u8;
118 let token_read =
122 unsafe { libc::read(token_reader_fd, std::ptr::addr_of_mut!(token).cast(), 1) };
123 if token_read != 1 {
124 return Err(if token_read < 0 {
125 std::io::Error::last_os_error()
126 } else {
127 std::io::Error::from_raw_os_error(libc::EALREADY)
128 });
129 }
130
131 let session_id = unsafe { libc::setsid() };
134 if session_id < 0 {
135 return Err(std::io::Error::last_os_error());
136 }
137 let child_pid = unsafe { libc::getpid() };
139 if child_pid <= 0 || session_id != child_pid {
140 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
141 }
142
143 let writer_fd = self.state.writer_fd.load(Ordering::Acquire);
144 if writer_fd < 0 {
145 return Err(std::io::Error::from_raw_os_error(libc::EBADF));
146 }
147
148 let acknowledgement = SessionAcknowledgement {
149 magic: SESSION_ACK_MAGIC,
150 version: SESSION_ACK_VERSION,
151 child_pid: child_pid as u32,
152 session_id: session_id as u32,
153 };
154
155 let written = unsafe {
158 libc::write(
159 writer_fd,
160 std::ptr::addr_of!(acknowledgement).cast(),
161 SESSION_ACK_LEN,
162 )
163 };
164 if written < 0 {
165 return Err(std::io::Error::last_os_error());
166 }
167 if written as usize != SESSION_ACK_LEN {
168 return Err(std::io::Error::from_raw_os_error(libc::EIO));
169 }
170 Ok(())
171 }
172}
173
174pub struct PendingUnixSessionReceipt {
180 reader: OwnedFd,
181 state: Arc<SessionHookState>,
182}
183
184impl std::fmt::Debug for PendingUnixSessionReceipt {
185 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 formatter
187 .debug_struct("PendingUnixSessionReceipt")
188 .finish_non_exhaustive()
189 }
190}
191
192impl PendingUnixSessionReceipt {
193 pub fn into_receipt(self, spawned_child_pid: u32) -> SysprimsResult<UnixSessionReceipt> {
200 self.state.close_parent_descriptors();
201 if spawned_child_pid == 0 || spawned_child_pid > i32::MAX as u32 {
202 return Err(SysprimsError::invalid_argument(
203 "owned child pid is outside the safe Unix process range",
204 ));
205 }
206
207 let acknowledgement = read_session_acknowledgement(&self.reader)?;
208
209 let packet = unsafe {
212 std::ptr::read_unaligned(acknowledgement.as_ptr().cast::<SessionAcknowledgement>())
213 };
214 if packet.magic != SESSION_ACK_MAGIC || packet.version != SESSION_ACK_VERSION {
215 return Err(SysprimsError::invalid_argument(
216 "session acquisition acknowledgement is missing or malformed",
217 ));
218 }
219 if packet.child_pid != spawned_child_pid || packet.session_id != spawned_child_pid {
220 return Err(SysprimsError::invalid_argument(
221 "session acquisition acknowledgement does not match the owned child",
222 ));
223 }
224
225 Ok(UnixSessionReceipt {
226 child_pid: packet.child_pid,
227 process_group_id: packet.session_id,
228 session_id: packet.session_id,
229 })
230 }
231}
232
233fn read_session_acknowledgement(reader: &OwnedFd) -> SysprimsResult<[u8; SESSION_ACK_LEN]> {
234 let deadline = Instant::now() + SESSION_ACK_WAIT_TIMEOUT;
235 loop {
236 let remaining = deadline.saturating_duration_since(Instant::now());
237 if remaining.is_zero() {
238 return Err(SysprimsError::invalid_argument(
239 "session acquisition acknowledgement is missing or malformed",
240 ));
241 }
242 let timeout_ms = remaining.as_millis().max(1).min(libc::c_int::MAX as u128) as libc::c_int;
243 let mut poll_descriptor = libc::pollfd {
244 fd: reader.as_raw_fd(),
245 events: libc::POLLIN | libc::POLLHUP,
246 revents: 0,
247 };
248 let ready = unsafe { libc::poll(&mut poll_descriptor, 1, timeout_ms) };
251 if ready < 0 {
252 let error = std::io::Error::last_os_error();
253 if error.raw_os_error() == Some(libc::EINTR) {
254 continue;
255 }
256 return Err(SysprimsError::system(
257 format!("session acquisition acknowledgement wait failed: {error}"),
258 error.raw_os_error().unwrap_or(0),
259 ));
260 }
261 if ready == 0 {
262 return Err(SysprimsError::invalid_argument(
263 "session acquisition acknowledgement is missing or malformed",
264 ));
265 }
266
267 let mut acknowledgement = [0_u8; SESSION_ACK_LEN * 2];
268 let read = unsafe {
271 libc::read(
272 reader.as_raw_fd(),
273 acknowledgement.as_mut_ptr().cast(),
274 acknowledgement.len(),
275 )
276 };
277 if read < 0 {
278 let error = std::io::Error::last_os_error();
279 if error.raw_os_error() == Some(libc::EAGAIN)
280 || error.raw_os_error() == Some(libc::EWOULDBLOCK)
281 || error.raw_os_error() == Some(libc::EINTR)
282 {
283 continue;
284 }
285 return Err(SysprimsError::system(
286 format!("session acquisition acknowledgement read failed: {error}"),
287 error.raw_os_error().unwrap_or(0),
288 ));
289 }
290 if read as usize != SESSION_ACK_LEN {
291 return Err(SysprimsError::invalid_argument(
292 "session acquisition acknowledgement is missing or malformed",
293 ));
294 }
295 let mut packet = [0_u8; SESSION_ACK_LEN];
296 packet.copy_from_slice(&acknowledgement[..SESSION_ACK_LEN]);
297 return Ok(packet);
298 }
299}
300
301impl Drop for PendingUnixSessionReceipt {
302 fn drop(&mut self) {
303 self.state.close_parent_descriptors();
304 }
305}
306
307#[derive(Debug)]
312pub struct UnixSessionReceipt {
313 child_pid: u32,
314 process_group_id: u32,
315 session_id: u32,
316}
317
318impl UnixSessionReceipt {
319 pub fn child_pid(&self) -> u32 {
320 self.child_pid
321 }
322
323 pub fn process_group_id(&self) -> u32 {
324 self.process_group_id
325 }
326
327 pub fn session_id(&self) -> u32 {
328 self.session_id
329 }
330
331 pub fn session_kind(&self) -> &'static str {
332 "new_session"
333 }
334
335 pub fn identifier_provenance(&self) -> &'static str {
336 "setsid_structural_child_pid"
337 }
338}
339
340pub fn prepare_session_acquisition(
345) -> SysprimsResult<(UnixSessionAcquisitionHook, PendingUnixSessionReceipt)> {
346 let (reader, writer) = create_acknowledgement_pipe()?;
347 let (token_reader, token_writer) = match create_acknowledgement_pipe() {
348 Ok(pipe) => pipe,
349 Err(error) => {
350 unsafe {
352 libc::close(writer);
353 }
354 return Err(error);
355 }
356 };
357 let token = 0xa5_u8;
358 let token_written = unsafe { libc::write(token_writer, std::ptr::addr_of!(token).cast(), 1) };
361 let token_write_error = (token_written != 1).then(std::io::Error::last_os_error);
362 unsafe {
364 libc::close(token_writer);
365 }
366 if let Some(error) = token_write_error {
367 unsafe {
369 libc::close(writer);
370 }
371 return Err(SysprimsError::system(
372 format!("cannot preload session acquisition token: {error}"),
373 error.raw_os_error().unwrap_or(libc::EIO),
374 ));
375 }
376 let state = Arc::new(SessionHookState {
377 writer_fd: AtomicI32::new(writer),
378 token_reader_fd: AtomicI32::new(token_reader.into_raw_fd()),
379 invoked: AtomicBool::new(false),
380 });
381 Ok((
382 UnixSessionAcquisitionHook {
383 state: Arc::clone(&state),
384 },
385 PendingUnixSessionReceipt { reader, state },
386 ))
387}
388
389fn create_acknowledgement_pipe() -> SysprimsResult<(OwnedFd, RawFd)> {
390 let mut descriptors = [-1; 2];
391 #[cfg(any(target_os = "linux", target_os = "android"))]
395 let pipe_result =
396 unsafe { libc::pipe2(descriptors.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) };
397 #[cfg(not(any(target_os = "linux", target_os = "android")))]
398 let pipe_result = unsafe { libc::pipe(descriptors.as_mut_ptr()) };
399 if pipe_result != 0 {
400 return Err(last_system_error(
401 "cannot create session acknowledgement pipe",
402 ));
403 }
404
405 #[cfg(not(any(target_os = "linux", target_os = "android")))]
406 for descriptor in descriptors {
407 let descriptor_flags = unsafe { libc::fcntl(descriptor, libc::F_GETFD) };
410 let status_flags = unsafe { libc::fcntl(descriptor, libc::F_GETFL) };
411 if descriptor_flags < 0
412 || status_flags < 0
413 || unsafe {
414 libc::fcntl(
415 descriptor,
416 libc::F_SETFD,
417 descriptor_flags | libc::FD_CLOEXEC,
418 )
419 } < 0
420 || unsafe { libc::fcntl(descriptor, libc::F_SETFL, status_flags | libc::O_NONBLOCK) }
421 < 0
422 {
423 let error = last_system_error("cannot configure session acknowledgement pipe");
424 unsafe {
427 libc::close(descriptors[0]);
428 libc::close(descriptors[1]);
429 }
430 return Err(error);
431 }
432 }
433
434 Ok((
437 unsafe { OwnedFd::from_raw_fd(descriptors[0]) },
438 descriptors[1],
439 ))
440}
441
442fn last_system_error(context: &str) -> SysprimsError {
443 let error = std::io::Error::last_os_error();
444 SysprimsError::system(
445 format!("{context}: {error}"),
446 error.raw_os_error().unwrap_or(0),
447 )
448}
449
450pub fn run_setsid_impl(
455 command: &str,
456 args: &[&str],
457 config: &SetsidConfig,
458) -> SysprimsResult<SetsidOutcome> {
459 let mut cmd = Command::new(command);
460 cmd.args(args);
461 apply_child_config(&mut cmd, config.cwd.as_deref(), config.env.as_ref());
462
463 unsafe {
466 cmd.pre_exec(|| {
467 if libc::setsid() == -1 {
472 return Err(std::io::Error::last_os_error());
473 }
474 Ok(())
475 });
476 }
477
478 let mut child = cmd.spawn().map_err(|e| {
480 if e.kind() == std::io::ErrorKind::NotFound {
481 SysprimsError::not_found_command(command)
482 } else if e.kind() == std::io::ErrorKind::PermissionDenied {
483 SysprimsError::permission_denied_command(command)
484 } else {
485 SysprimsError::spawn_failed(command, e.to_string())
486 }
487 })?;
488
489 let child_pid = child.id();
490
491 if config.wait {
492 let status = child.wait().map_err(|e| {
494 SysprimsError::system(format!("wait failed: {}", e), e.raw_os_error().unwrap_or(0))
495 })?;
496
497 Ok(SetsidOutcome::Completed {
498 child_pid,
499 exit_status: status,
500 })
501 } else {
502 Ok(SetsidOutcome::Spawned { child_pid })
504 }
505}
506
507pub fn run_nohup_impl(
512 command: &str,
513 args: &[&str],
514 config: &NohupConfig,
515) -> SysprimsResult<NohupOutcome> {
516 let mut cmd = Command::new(command);
517 cmd.args(args);
518 apply_child_config(&mut cmd, config.cwd.as_deref(), config.env.as_ref());
519
520 let explicit_output_file = config.output_file.is_some();
522 let output_file = determine_nohup_output(config)?;
523
524 let stdout_is_tty = unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 };
526 let stderr_is_tty = unsafe { libc::isatty(libc::STDERR_FILENO) == 1 };
527
528 if explicit_output_file || stdout_is_tty {
530 if let Some(ref path) = output_file {
531 let file = open_no_follow_append(Path::new(path))?;
532 cmd.stdout(
533 file.try_clone()
534 .map_err(|e| SysprimsError::system(format!("cannot dup stdout: {}", e), 0))?,
535 );
536
537 if explicit_output_file || stderr_is_tty {
541 cmd.stderr(file);
542 }
543 }
544 }
545
546 unsafe {
549 cmd.pre_exec(|| {
550 libc::signal(libc::SIGHUP, libc::SIG_IGN);
552 Ok(())
553 });
554 }
555
556 let mut child = cmd.spawn().map_err(|e| {
558 if e.kind() == std::io::ErrorKind::NotFound {
559 SysprimsError::not_found_command(command)
560 } else if e.kind() == std::io::ErrorKind::PermissionDenied {
561 SysprimsError::permission_denied_command(command)
562 } else {
563 SysprimsError::spawn_failed(command, e.to_string())
564 }
565 })?;
566
567 let child_pid = child.id();
568
569 if config.wait {
570 let status = child.wait().map_err(|e| {
571 SysprimsError::system(format!("wait failed: {}", e), e.raw_os_error().unwrap_or(0))
572 })?;
573
574 Ok(NohupOutcome::Completed {
575 child_pid,
576 exit_status: status,
577 output_file,
578 })
579 } else {
580 Ok(NohupOutcome::Spawned {
581 child_pid,
582 output_file,
583 })
584 }
585}
586
587fn determine_nohup_output(config: &NohupConfig) -> SysprimsResult<Option<String>> {
591 if let Some(ref path) = config.output_file {
592 return Ok(Some(path.clone()));
593 }
594
595 let stdout_is_tty = unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 };
597 if !stdout_is_tty {
598 return Ok(None);
599 }
600
601 let cwd_path = "nohup.out";
603 if open_no_follow_append(Path::new(cwd_path)).is_ok() {
604 return Ok(Some(cwd_path.to_string()));
605 }
606
607 if let Some(home) = std::env::var_os("HOME") {
609 let home_path = format!("{}/nohup.out", home.to_string_lossy());
610 return Ok(Some(home_path));
611 }
612
613 Ok(Some(cwd_path.to_string()))
615}
616
617fn apply_child_config(
618 cmd: &mut Command,
619 cwd: Option<&Path>,
620 env: Option<&std::collections::BTreeMap<String, String>>,
621) {
622 if let Some(cwd) = cwd {
623 cmd.current_dir(cwd);
624 }
625 if let Some(env) = env {
626 cmd.envs(env);
627 }
628}
629
630fn open_no_follow_append(path: &Path) -> SysprimsResult<File> {
631 OpenOptions::new()
632 .create(true)
633 .append(true)
634 .custom_flags(libc::O_NOFOLLOW)
635 .open(path)
636 .map_err(|e| map_nohup_output_open_error(path, e))
637}
638
639fn map_nohup_output_open_error(path: &Path, err: std::io::Error) -> SysprimsError {
640 if err.kind() == std::io::ErrorKind::PermissionDenied || err.raw_os_error() == Some(libc::ELOOP)
641 {
642 return SysprimsError::permission_denied_path(
643 path.display().to_string(),
644 "open nohup output_file",
645 );
646 }
647
648 SysprimsError::system(
649 format!("cannot open {}: {}", path.display(), err),
650 err.raw_os_error().unwrap_or(0),
651 )
652}
653
654pub fn setsid_impl() -> SysprimsResult<u32> {
659 let result = unsafe { libc::setsid() };
660 if result == -1 {
661 let errno = std::io::Error::last_os_error();
662 Err(SysprimsError::system(
663 "setsid failed",
664 errno.raw_os_error().unwrap_or(0),
665 ))
666 } else {
667 Ok(result as u32)
668 }
669}
670
671pub fn getsid_impl(pid: u32) -> SysprimsResult<u32> {
672 let result = unsafe { libc::getsid(pid as libc::pid_t) };
673 if result == -1 {
674 let errno = std::io::Error::last_os_error();
675 if errno.raw_os_error() == Some(libc::ESRCH) {
676 Err(SysprimsError::not_found(pid))
677 } else {
678 Err(SysprimsError::system(
679 "getsid failed",
680 errno.raw_os_error().unwrap_or(0),
681 ))
682 }
683 } else {
684 Ok(result as u32)
685 }
686}
687
688pub fn setpgid_impl(pid: u32, pgid: u32) -> SysprimsResult<()> {
689 let result = unsafe { libc::setpgid(pid as libc::pid_t, pgid as libc::pid_t) };
690 if result == -1 {
691 let errno = std::io::Error::last_os_error();
692 if errno.raw_os_error() == Some(libc::ESRCH) {
693 Err(SysprimsError::not_found(pid))
694 } else if errno.raw_os_error() == Some(libc::EPERM) {
695 Err(SysprimsError::permission_denied(pid, "setpgid"))
696 } else {
697 Err(SysprimsError::system(
698 "setpgid failed",
699 errno.raw_os_error().unwrap_or(0),
700 ))
701 }
702 } else {
703 Ok(())
704 }
705}
706
707pub fn getpgid_impl(pid: u32) -> SysprimsResult<u32> {
708 let result = unsafe { libc::getpgid(pid as libc::pid_t) };
709 if result == -1 {
710 let errno = std::io::Error::last_os_error();
711 if errno.raw_os_error() == Some(libc::ESRCH) {
712 Err(SysprimsError::not_found(pid))
713 } else {
714 Err(SysprimsError::system(
715 "getpgid failed",
716 errno.raw_os_error().unwrap_or(0),
717 ))
718 }
719 } else {
720 Ok(result as u32)
721 }
722}
723
724#[cfg(test)]
725mod tests {
726 use super::*;
727
728 #[test]
729 fn prepared_hook_mints_same_spawn_receipt() {
730 let (hook, pending) = prepare_session_acquisition().unwrap();
731 let mut command = Command::new("sleep");
732 command.arg("60");
733 unsafe {
736 command.pre_exec(move || hook.acquire());
737 }
738
739 let mut child = command.spawn().unwrap();
740 let receipt = pending.into_receipt(child.id()).unwrap();
741 assert_eq!(receipt.child_pid(), child.id());
742 assert_eq!(receipt.process_group_id(), child.id());
743 assert_eq!(receipt.session_id(), child.id());
744 assert_eq!(receipt.session_kind(), "new_session");
745 assert_eq!(
746 receipt.identifier_provenance(),
747 "setsid_structural_child_pid"
748 );
749
750 child.kill().unwrap();
751 child.wait().unwrap();
752 }
753
754 #[test]
755 fn receipt_reader_waits_for_delayed_child_acknowledgement() {
756 let (reader, writer) = create_acknowledgement_pipe().unwrap();
757 let expected_pid = std::process::id();
758 let writer_thread = std::thread::spawn(move || {
759 std::thread::sleep(Duration::from_millis(25));
760 let acknowledgement = SessionAcknowledgement {
761 magic: SESSION_ACK_MAGIC,
762 version: SESSION_ACK_VERSION,
763 child_pid: expected_pid,
764 session_id: expected_pid,
765 };
766 let written = unsafe {
769 libc::write(
770 writer,
771 std::ptr::addr_of!(acknowledgement).cast(),
772 SESSION_ACK_LEN,
773 )
774 };
775 unsafe {
777 libc::close(writer);
778 }
779 assert_eq!(written, SESSION_ACK_LEN as isize);
780 });
781
782 let acknowledgement = read_session_acknowledgement(&reader).unwrap();
783 writer_thread.join().unwrap();
784 let packet = unsafe {
787 std::ptr::read_unaligned(acknowledgement.as_ptr().cast::<SessionAcknowledgement>())
788 };
789 assert_eq!(packet.magic, SESSION_ACK_MAGIC);
790 assert_eq!(packet.version, SESSION_ACK_VERSION);
791 assert_eq!(packet.child_pid, expected_pid);
792 assert_eq!(packet.session_id, expected_pid);
793 }
794
795 #[test]
796 fn receipt_requires_hook_invocation() {
797 let (_hook, pending) = prepare_session_acquisition().unwrap();
798 let mut child = Command::new("sleep").arg("60").spawn().unwrap();
799
800 let error = pending.into_receipt(child.id()).unwrap_err();
801 assert!(matches!(
802 error,
803 SysprimsError::InvalidArgument { message }
804 if message.contains("acknowledgement is missing or malformed")
805 ));
806
807 child.kill().unwrap();
808 child.wait().unwrap();
809 }
810
811 #[test]
812 fn dropping_pending_closes_hook_descriptors() {
813 let (hook, pending) = prepare_session_acquisition().unwrap();
814 assert!(hook.state.writer_fd.load(Ordering::Acquire) >= 0);
815 assert!(hook.state.token_reader_fd.load(Ordering::Acquire) >= 0);
816
817 drop(pending);
818
819 assert_eq!(hook.state.writer_fd.load(Ordering::Acquire), -1);
820 assert_eq!(hook.state.token_reader_fd.load(Ordering::Acquire), -1);
821 }
822
823 #[test]
824 fn hook_rejects_second_invocation_before_spawn_can_exec() {
825 let (hook, _pending) = prepare_session_acquisition().unwrap();
826 let mut command = Command::new("true");
827 unsafe {
830 command.pre_exec(move || {
831 hook.acquire()?;
832 hook.acquire()
833 });
834 }
835
836 assert!(command.spawn().is_err());
837 }
838
839 #[test]
840 fn prepared_hook_is_single_spawn_even_when_command_is_reused() {
841 let (hook, pending) = prepare_session_acquisition().unwrap();
842 let mut command = Command::new("sleep");
843 command.arg("60");
844 unsafe {
846 command.pre_exec(move || hook.acquire());
847 }
848
849 let mut first_child = command.spawn().unwrap();
850 assert!(
851 command.spawn().is_err(),
852 "shared token must reject a second fork"
853 );
854 let receipt = pending.into_receipt(first_child.id()).unwrap();
855 assert_eq!(receipt.child_pid(), first_child.id());
856 first_child.kill().unwrap();
857 first_child.wait().unwrap();
858 }
859
860 #[test]
861 fn second_session_acquirer_fails_closed_in_either_order() {
862 let (hook_first, _pending_first) = prepare_session_acquisition().unwrap();
863 let mut after_hook = Command::new("true");
864 unsafe {
867 after_hook.pre_exec(move || {
868 hook_first.acquire()?;
869 if libc::setsid() < 0 {
870 return Err(std::io::Error::last_os_error());
871 }
872 Ok(())
873 });
874 }
875 assert!(after_hook.spawn().is_err());
876
877 let (hook_second, _pending_second) = prepare_session_acquisition().unwrap();
878 let mut before_hook = Command::new("true");
879 unsafe {
882 before_hook.pre_exec(move || {
883 if libc::setsid() < 0 {
884 return Err(std::io::Error::last_os_error());
885 }
886 hook_second.acquire()
887 });
888 }
889 assert!(before_hook.spawn().is_err());
890 }
891
892 #[test]
893 fn later_pre_exec_failure_does_not_produce_a_child() {
894 let (hook, _pending) = prepare_session_acquisition().unwrap();
895 let mut command = Command::new("true");
896 unsafe {
899 command.pre_exec(move || {
900 hook.acquire()?;
901 Err(std::io::Error::from_raw_os_error(libc::EACCES))
902 });
903 }
904
905 assert!(command.spawn().is_err());
906 }
907
908 #[test]
909 fn malformed_acknowledgement_cannot_mint_receipt() {
910 let (hook, pending) = prepare_session_acquisition().unwrap();
911 let malformed = [0x5a_u8; 3];
912 let written = unsafe {
915 libc::write(
916 hook.state.writer_fd.load(Ordering::Acquire),
917 malformed.as_ptr().cast(),
918 malformed.len(),
919 )
920 };
921 assert_eq!(written, malformed.len() as isize);
922
923 let error = pending.into_receipt(std::process::id()).unwrap_err();
924 assert!(matches!(
925 error,
926 SysprimsError::InvalidArgument { message }
927 if message.contains("acknowledgement is missing or malformed")
928 ));
929 }
930
931 #[test]
932 fn setsid_spawns_process() {
933 let result = run_setsid_impl("echo", &["hello"], &SetsidConfig::default());
934 assert!(result.is_ok());
935 if let Ok(SetsidOutcome::Spawned { child_pid }) = result {
936 assert!(child_pid > 0);
937 }
938 }
939
940 #[test]
941 fn setsid_wait_returns_status() {
942 let result = run_setsid_impl(
943 "sh",
944 &["-c", "exit 42"],
945 &SetsidConfig {
946 wait: true,
947 ..Default::default()
948 },
949 );
950 assert!(result.is_ok());
951 if let Ok(SetsidOutcome::Completed {
952 child_pid,
953 exit_status,
954 }) = result
955 {
956 assert!(child_pid > 0);
957 assert_eq!(exit_status.code(), Some(42));
958 }
959 }
960
961 #[test]
962 fn setsid_honors_cwd_and_env() {
963 let dir = unique_temp_dir("setsid-cwd-env");
964 std::fs::create_dir_all(&dir).unwrap();
965 std::fs::write(dir.join("marker"), "ok").unwrap();
966
967 let mut env = std::collections::BTreeMap::new();
968 env.insert("SYSPRIMS_SESSION_TEST".to_string(), "expected".to_string());
969
970 let result = run_setsid_impl(
971 "sh",
972 &[
973 "-c",
974 "test -f marker && test \"$SYSPRIMS_SESSION_TEST\" = expected",
975 ],
976 &SetsidConfig {
977 wait: true,
978 cwd: Some(dir.clone()),
979 env: Some(env),
980 ..Default::default()
981 },
982 );
983
984 let _ = std::fs::remove_dir_all(&dir);
985 assert!(result.is_ok());
986 if let Ok(SetsidOutcome::Completed { exit_status, .. }) = result {
987 assert_eq!(exit_status.code(), Some(0));
988 }
989 }
990
991 #[test]
992 fn setsid_not_found_command() {
993 let result = run_setsid_impl("nonexistent_command_xyz", &[], &SetsidConfig::default());
994 assert!(matches!(result, Err(SysprimsError::NotFoundCommand { .. })));
995 }
996
997 #[test]
998 fn getpgid_current_process() {
999 let pgid = getpgid_impl(0);
1000 assert!(pgid.is_ok());
1001 assert!(pgid.unwrap() > 0);
1002 }
1003
1004 #[test]
1005 fn getsid_current_process() {
1006 let sid = getsid_impl(0);
1007 assert!(sid.is_ok());
1008 assert!(sid.unwrap() > 0);
1009 }
1010
1011 #[test]
1012 fn nohup_honors_cwd_and_env() {
1013 let dir = unique_temp_dir("nohup-cwd-env");
1014 std::fs::create_dir_all(&dir).unwrap();
1015 std::fs::write(dir.join("marker"), "ok").unwrap();
1016 let output_file = dir.join("nohup.out");
1017
1018 let mut env = std::collections::BTreeMap::new();
1019 env.insert("SYSPRIMS_SESSION_TEST".to_string(), "expected".to_string());
1020
1021 let result = run_nohup_impl(
1022 "sh",
1023 &[
1024 "-c",
1025 "test -f marker && test \"$SYSPRIMS_SESSION_TEST\" = expected",
1026 ],
1027 &NohupConfig {
1028 wait: true,
1029 cwd: Some(dir.clone()),
1030 output_file: Some(output_file.display().to_string()),
1031 env: Some(env),
1032 },
1033 );
1034
1035 let _ = std::fs::remove_dir_all(&dir);
1036 assert!(result.is_ok());
1037 if let Ok(NohupOutcome::Completed { exit_status, .. }) = result {
1038 assert_eq!(exit_status.code(), Some(0));
1039 }
1040 }
1041
1042 #[test]
1043 fn nohup_rejects_symlink_output_file() {
1044 let dir = unique_temp_dir("nohup-symlink");
1045 std::fs::create_dir_all(&dir).unwrap();
1046 let target = dir.join("target.log");
1047 let link = dir.join("link.log");
1048 std::fs::write(&target, "existing").unwrap();
1049 std::os::unix::fs::symlink(&target, &link).unwrap();
1050
1051 let result = run_nohup_impl(
1052 "sh",
1053 &["-c", "exit 0"],
1054 &NohupConfig {
1055 wait: true,
1056 output_file: Some(link.display().to_string()),
1057 ..Default::default()
1058 },
1059 );
1060
1061 let _ = std::fs::remove_dir_all(&dir);
1062 assert!(matches!(
1063 result,
1064 Err(SysprimsError::PermissionDeniedPath { .. })
1065 ));
1066 }
1067
1068 fn unique_temp_dir(label: &str) -> std::path::PathBuf {
1069 let nanos = std::time::SystemTime::now()
1070 .duration_since(std::time::UNIX_EPOCH)
1071 .unwrap()
1072 .as_nanos();
1073 std::env::temp_dir().join(format!("sysprims-{label}-{}-{nanos}", std::process::id()))
1074 }
1075}