1use anyhow::Error;
41use downcast_rs::{impl_downcast, Downcast};
42#[cfg(feature = "serde_support")]
43use serde_derive::*;
44use std::io::Result as IoResult;
45#[cfg(windows)]
46use std::os::windows::prelude::{AsRawHandle, RawHandle};
47
48#[derive(Debug)]
53pub struct ContainedPtyChild {
54 #[cfg(unix)]
55 pub(crate) child: std::process::Child,
56 #[cfg(windows)]
57 pub(crate) child: win::WinChild,
58}
59
60impl ContainedPtyChild {
61 #[cfg(unix)]
62 pub(crate) fn new(child: std::process::Child) -> Self {
63 Self { child }
64 }
65
66 #[cfg(windows)]
67 pub(crate) fn new(child: win::WinChild) -> Self {
68 Self { child }
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum ContainedPtySpawnErrorStage {
75 BeforeSpawn,
77 Receipt,
79 Adoption,
81 Resume,
83}
84
85enum FailedChildRecoveryCommand {
86 Adopt(ContainedPtyChild),
87 Attempt {
88 timeout: std::time::Duration,
89 #[cfg(test)]
90 fault: FailedChildRecoveryFault,
91 response: std::sync::mpsc::SyncSender<IoResult<bool>>,
92 },
93}
94
95#[cfg(test)]
96#[derive(Clone, Copy)]
97enum FailedChildRecoveryFault {
98 None,
99 #[cfg(unix)]
100 KillError,
101 #[cfg(unix)]
102 Deadline,
103}
104
105struct FailedChildRecovery {
106 sender: std::sync::mpsc::Sender<FailedChildRecoveryCommand>,
107 pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
108}
109
110impl FailedChildRecovery {
111 fn prepare() -> IoResult<Self> {
112 let (sender, receiver) = std::sync::mpsc::channel();
113 let pending = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
114 let worker_pending = std::sync::Arc::clone(&pending);
115 std::thread::Builder::new()
116 .name("sysprims-pty-recovery".to_string())
117 .spawn(move || failed_child_recovery_worker(receiver, worker_pending))?;
118 Ok(Self { sender, pending })
119 }
120
121 fn attach(&self, child: ContainedPtyChild) {
122 self.pending
123 .store(true, std::sync::atomic::Ordering::Release);
124 if let Err(error) = self.sender.send(FailedChildRecoveryCommand::Adopt(child)) {
125 let child = match error.0 {
126 FailedChildRecoveryCommand::Adopt(child) => child,
127 FailedChildRecoveryCommand::Attempt { .. } => unreachable!(),
128 };
129 bounded_local_recovery_or_abort(child);
130 }
131 }
132
133 fn attempt(&self, timeout: std::time::Duration) -> IoResult<bool> {
134 self.attempt_inner(
135 timeout,
136 #[cfg(test)]
137 FailedChildRecoveryFault::None,
138 )
139 }
140
141 fn attempt_inner(
142 &self,
143 timeout: std::time::Duration,
144 #[cfg(test)] fault: FailedChildRecoveryFault,
145 ) -> IoResult<bool> {
146 if !self.pending.load(std::sync::atomic::Ordering::Acquire) {
147 return Ok(true);
148 }
149
150 let timeout = timeout.min(std::time::Duration::from_secs(2));
151 let (response, result) = std::sync::mpsc::sync_channel(1);
152 self.sender
153 .send(FailedChildRecoveryCommand::Attempt {
154 timeout,
155 #[cfg(test)]
156 fault,
157 response,
158 })
159 .map_err(|_| {
160 std::io::Error::new(
161 std::io::ErrorKind::BrokenPipe,
162 "exact-child recovery owner stopped",
163 )
164 })?;
165 result
166 .recv_timeout(timeout + std::time::Duration::from_millis(250))
167 .map_err(|error| {
168 std::io::Error::new(
169 std::io::ErrorKind::TimedOut,
170 format!("exact-child recovery response unavailable: {error}"),
171 )
172 })?
173 }
174
175 #[cfg(all(test, unix))]
176 fn attempt_with_fault(
177 &self,
178 timeout: std::time::Duration,
179 fault: FailedChildRecoveryFault,
180 ) -> IoResult<bool> {
181 self.attempt_inner(timeout, fault)
182 }
183
184 fn is_pending(&self) -> bool {
185 self.pending.load(std::sync::atomic::Ordering::Acquire)
186 }
187}
188
189fn failed_child_recovery_worker(
190 receiver: std::sync::mpsc::Receiver<FailedChildRecoveryCommand>,
191 pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
192) {
193 let mut child = None;
194 while let Ok(command) = receiver.recv() {
195 match command {
196 FailedChildRecoveryCommand::Adopt(adopted) => {
197 debug_assert!(child.is_none());
198 child = Some(adopted);
199 }
200 FailedChildRecoveryCommand::Attempt {
201 timeout,
202 #[cfg(test)]
203 fault,
204 response,
205 } => {
206 let result = attempt_failed_child_recovery(
207 &mut child,
208 timeout,
209 #[cfg(test)]
210 fault,
211 );
212 pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
213 let _ = response.send(result);
214 }
215 }
216 }
217
218 while child.is_some() {
221 let _ = attempt_failed_child_recovery(
222 &mut child,
223 std::time::Duration::from_secs(2),
224 #[cfg(test)]
225 FailedChildRecoveryFault::None,
226 );
227 pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
228 if child.is_some() {
229 std::thread::sleep(std::time::Duration::from_millis(10));
230 }
231 }
232}
233
234fn attempt_failed_child_recovery(
235 child: &mut Option<ContainedPtyChild>,
236 timeout: std::time::Duration,
237 #[cfg(test)] fault: FailedChildRecoveryFault,
238) -> IoResult<bool> {
239 let owned_child = match child.as_mut() {
240 Some(child) => child,
241 None => return Ok(true),
242 };
243
244 if Child::try_wait(owned_child)?.is_some() {
245 child.take();
246 return Ok(true);
247 }
248
249 #[cfg(test)]
250 match fault {
251 #[cfg(unix)]
252 FailedChildRecoveryFault::KillError => {
253 return Err(std::io::Error::new(
254 std::io::ErrorKind::PermissionDenied,
255 "injected exact-child kill failure",
256 ));
257 }
258 #[cfg(unix)]
259 FailedChildRecoveryFault::Deadline => {
260 std::thread::sleep(timeout.min(std::time::Duration::from_millis(10)));
261 return Ok(false);
262 }
263 FailedChildRecoveryFault::None => {}
264 }
265
266 ChildKiller::kill(owned_child)?;
269
270 let timeout = timeout.min(std::time::Duration::from_secs(2));
271 let deadline = std::time::Instant::now() + timeout;
272 loop {
273 match Child::try_wait(owned_child)? {
274 Some(_) => {
275 child.take();
276 return Ok(true);
277 }
278 None if std::time::Instant::now() < deadline => {
279 std::thread::sleep(std::time::Duration::from_millis(10));
280 }
281 None => return Ok(false),
282 }
283 }
284}
285
286fn bounded_local_recovery_or_abort(mut child: ContainedPtyChild) -> ! {
287 let _ = ChildKiller::kill(&mut child);
288 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
289 loop {
290 match Child::try_wait(&mut child) {
291 Ok(Some(_)) => {
292 std::process::abort();
293 }
294 Ok(None) if std::time::Instant::now() < deadline => {
295 std::thread::sleep(std::time::Duration::from_millis(10));
296 }
297 Ok(None) | Err(_) => std::process::abort(),
298 }
299 }
300}
301
302pub struct ContainedPtySpawnError {
309 stage: ContainedPtySpawnErrorStage,
310 source: Error,
311 recovery: Option<FailedChildRecovery>,
312}
313
314impl ContainedPtySpawnError {
315 pub(crate) fn before_spawn(source: Error) -> Self {
316 Self {
317 stage: ContainedPtySpawnErrorStage::BeforeSpawn,
318 source,
319 recovery: None,
320 }
321 }
322
323 pub(crate) fn after_spawn(
324 stage: ContainedPtySpawnErrorStage,
325 source: Error,
326 child: ContainedPtyChild,
327 recovery: FailedChildRecovery,
328 ) -> Self {
329 debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
330 recovery.attach(child);
331 let mut error = Self {
332 stage,
333 source,
334 recovery: Some(recovery),
335 };
336 let _ = error.recover(std::time::Duration::from_secs(2));
337 error
338 }
339
340 #[cfg(all(test, unix))]
341 pub(crate) fn after_spawn_pending_for_test(
342 stage: ContainedPtySpawnErrorStage,
343 source: Error,
344 child: ContainedPtyChild,
345 recovery: FailedChildRecovery,
346 ) -> Self {
347 debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
348 recovery.attach(child);
349 Self {
350 stage,
351 source,
352 recovery: Some(recovery),
353 }
354 }
355
356 pub fn stage(&self) -> ContainedPtySpawnErrorStage {
358 self.stage
359 }
360
361 pub fn recovery_pending(&self) -> bool {
363 self.recovery
364 .as_ref()
365 .is_some_and(FailedChildRecovery::is_pending)
366 }
367
368 pub fn recover(&mut self, timeout: std::time::Duration) -> IoResult<bool> {
373 match self.recovery.as_mut() {
374 Some(recovery) => recovery.attempt(timeout),
375 None => Ok(true),
376 }
377 }
378}
379
380impl std::fmt::Debug for ContainedPtySpawnError {
381 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382 formatter
383 .debug_struct("ContainedPtySpawnError")
384 .field("stage", &self.stage)
385 .field("source", &self.source)
386 .field("recovery_pending", &self.recovery_pending())
387 .finish()
388 }
389}
390
391impl std::fmt::Display for ContainedPtySpawnError {
392 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 self.source.fmt(formatter)
394 }
395}
396
397impl std::error::Error for ContainedPtySpawnError {
398 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
399 Some(self.source.as_ref())
400 }
401}
402
403pub type ContainedPtyGuard = sysprims_timeout::ContainmentGuard<ContainedPtyChild>;
405
406pub mod cmdbuilder;
407pub use cmdbuilder::CommandBuilder;
408
409#[cfg(unix)]
410pub mod unix;
411#[cfg(windows)]
412pub mod win;
413
414pub mod serial;
415
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
419pub struct PtySize {
420 pub rows: u16,
422 pub cols: u16,
424 pub pixel_width: u16,
427 pub pixel_height: u16,
430}
431
432impl Default for PtySize {
433 fn default() -> Self {
434 PtySize {
435 rows: 24,
436 cols: 80,
437 pixel_width: 0,
438 pixel_height: 0,
439 }
440 }
441}
442
443pub trait MasterPty: Downcast + Send {
445 fn resize(&self, size: PtySize) -> Result<(), Error>;
449 fn get_size(&self) -> Result<PtySize, Error>;
451 fn try_clone_reader(&self) -> Result<Box<dyn std::io::Read + Send>, Error>;
454 fn take_writer(&self) -> Result<Box<dyn std::io::Write + Send>, Error>;
459
460 #[cfg(unix)]
463 fn process_group_leader(&self) -> Option<libc::pid_t>;
464
465 #[cfg(unix)]
470 fn as_raw_fd(&self) -> Option<unix::RawFd>;
471
472 #[cfg(unix)]
473 fn tty_name(&self) -> Option<std::path::PathBuf>;
474
475 #[cfg(unix)]
478 fn get_termios(&self) -> Option<nix::sys::termios::Termios> {
479 None
480 }
481}
482impl_downcast!(MasterPty);
483
484pub trait Child: std::fmt::Debug + ChildKiller + Downcast + Send {
487 fn try_wait(&mut self) -> IoResult<Option<ExitStatus>>;
492 fn wait(&mut self) -> IoResult<ExitStatus>;
495 fn process_id(&self) -> Option<u32>;
498 #[cfg(windows)]
501 fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle>;
502}
503impl_downcast!(Child);
504
505pub trait ChildKiller: std::fmt::Debug + Downcast + Send {
507 fn kill(&mut self) -> IoResult<()>;
509
510 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync>;
514}
515impl_downcast!(ChildKiller);
516
517pub trait SlavePty {
520 fn spawn_command(&self, cmd: CommandBuilder) -> Result<Box<dyn Child + Send + Sync>, Error>;
522
523 fn spawn_contained_command(
529 &self,
530 cmd: CommandBuilder,
531 ) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
532 let _ = cmd;
533 Err(ContainedPtySpawnError::before_spawn(anyhow::anyhow!(
534 "spawn-time PTY containment is unavailable for this PTY implementation"
535 )))
536 }
537}
538
539#[derive(Debug, Clone)]
541pub struct ExitStatus {
542 code: u32,
543 signal: Option<String>,
544}
545
546impl ExitStatus {
547 pub fn with_exit_code(code: u32) -> Self {
549 Self { code, signal: None }
550 }
551
552 pub fn with_signal(signal: &str) -> Self {
554 Self {
555 code: 1,
556 signal: Some(signal.to_string()),
557 }
558 }
559
560 pub fn success(&self) -> bool {
562 match self.signal {
563 None => self.code == 0,
564 Some(_) => false,
565 }
566 }
567
568 pub fn exit_code(&self) -> u32 {
570 self.code
571 }
572
573 pub fn signal(&self) -> Option<&str> {
575 self.signal.as_deref()
576 }
577}
578
579impl From<std::process::ExitStatus> for ExitStatus {
580 fn from(status: std::process::ExitStatus) -> ExitStatus {
581 #[cfg(unix)]
582 {
583 use std::os::unix::process::ExitStatusExt;
584
585 if let Some(signal) = status.signal() {
586 let signame = unsafe { libc::strsignal(signal) };
587 let signal = if signame.is_null() {
588 format!("Signal {signal}")
589 } else {
590 let signame = unsafe { std::ffi::CStr::from_ptr(signame) };
591 signame.to_string_lossy().to_string()
592 };
593
594 return ExitStatus {
595 code: status.code().map(|c| c as u32).unwrap_or(1),
596 signal: Some(signal),
597 };
598 }
599 }
600
601 let code =
602 status
603 .code()
604 .map(|c| c as u32)
605 .unwrap_or_else(|| if status.success() { 0 } else { 1 });
606
607 ExitStatus { code, signal: None }
608 }
609}
610
611impl std::fmt::Display for ExitStatus {
612 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
613 if self.success() {
614 write!(fmt, "Success")
615 } else {
616 match &self.signal {
617 Some(sig) => write!(fmt, "Terminated by {sig}"),
618 None => write!(fmt, "Exited with code {}", self.code),
619 }
620 }
621 }
622}
623
624pub struct PtyPair {
625 pub slave: Box<dyn SlavePty + Send>,
628 pub master: Box<dyn MasterPty + Send>,
629}
630
631pub trait PtySystem: Downcast {
635 fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair>;
639}
640impl_downcast!(PtySystem);
641
642impl Child for std::process::Child {
643 fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
644 std::process::Child::try_wait(self).map(|status| status.map(Into::into))
645 }
646
647 fn wait(&mut self) -> IoResult<ExitStatus> {
648 std::process::Child::wait(self).map(Into::into)
649 }
650
651 fn process_id(&self) -> Option<u32> {
652 Some(self.id())
653 }
654
655 #[cfg(windows)]
656 fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
657 Some(std::os::windows::io::AsRawHandle::as_raw_handle(self))
658 }
659}
660
661impl Child for ContainedPtyChild {
662 fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
663 #[cfg(unix)]
664 return std::process::Child::try_wait(&mut self.child).map(|status| status.map(Into::into));
665
666 #[cfg(windows)]
667 return Child::try_wait(&mut self.child);
668 }
669
670 fn wait(&mut self) -> IoResult<ExitStatus> {
671 #[cfg(unix)]
672 return std::process::Child::wait(&mut self.child).map(Into::into);
673
674 #[cfg(windows)]
675 return Child::wait(&mut self.child);
676 }
677
678 fn process_id(&self) -> Option<u32> {
679 #[cfg(unix)]
680 return Some(self.child.id());
681
682 #[cfg(windows)]
683 return Child::process_id(&self.child);
684 }
685
686 #[cfg(windows)]
687 fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
688 Child::as_raw_handle(&self.child)
689 }
690}
691
692impl sysprims_timeout::ContainmentChild for ContainedPtyChild {
693 fn process_id(&self) -> Option<u32> {
694 Child::process_id(self)
695 }
696
697 fn try_wait(&mut self) -> IoResult<bool> {
698 Child::try_wait(self).map(|status| status.is_some())
699 }
700
701 #[cfg(windows)]
702 fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
703 Child::as_raw_handle(self)
704 }
705}
706
707#[derive(Debug)]
708struct ProcessSignaller {
709 pid: Option<u32>,
710
711 #[cfg(windows)]
712 handle: Option<filedescriptor::OwnedHandle>,
713}
714
715#[cfg(windows)]
716impl ChildKiller for ProcessSignaller {
717 fn kill(&mut self) -> IoResult<()> {
718 if let Some(handle) = &self.handle {
719 unsafe {
720 if winapi::um::processthreadsapi::TerminateProcess(handle.as_raw_handle() as _, 127)
721 == 0
722 {
723 return Err(std::io::Error::last_os_error());
724 }
725 }
726 }
727 Ok(())
728 }
729 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
730 Box::new(Self {
731 pid: self.pid,
732 handle: self.handle.as_ref().and_then(|h| h.try_clone().ok()),
733 })
734 }
735}
736
737#[cfg(unix)]
738impl ChildKiller for ProcessSignaller {
739 fn kill(&mut self) -> IoResult<()> {
740 if let Some(pid) = self.pid {
741 let result = unsafe { libc::kill(pid as i32, libc::SIGHUP) };
742 if result != 0 {
743 return Err(std::io::Error::last_os_error());
744 }
745 }
746 Ok(())
747 }
748
749 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
750 Box::new(Self { pid: self.pid })
751 }
752}
753
754impl ChildKiller for std::process::Child {
755 fn kill(&mut self) -> IoResult<()> {
756 #[cfg(unix)]
757 {
758 let result = unsafe { libc::kill(self.id() as i32, libc::SIGHUP) };
762 if result != 0 {
763 return Err(std::io::Error::last_os_error());
764 }
765
766 for attempt in 0..5 {
773 if attempt > 0 {
774 std::thread::sleep(std::time::Duration::from_millis(50));
775 }
776
777 if let Ok(Some(_)) = self.try_wait() {
778 return Ok(());
780 }
781 }
782
783 }
785
786 std::process::Child::kill(self)
787 }
788
789 #[cfg(windows)]
790 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
791 struct RawDup(RawHandle);
792 impl AsRawHandle for RawDup {
793 fn as_raw_handle(&self) -> RawHandle {
794 self.0
795 }
796 }
797
798 Box::new(ProcessSignaller {
799 pid: self.process_id(),
800 handle: Child::as_raw_handle(self)
801 .as_ref()
802 .and_then(|h| filedescriptor::OwnedHandle::dup(&RawDup(*h)).ok()),
803 })
804 }
805
806 #[cfg(unix)]
807 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
808 Box::new(ProcessSignaller {
809 pid: self.process_id(),
810 })
811 }
812}
813
814impl ChildKiller for ContainedPtyChild {
815 fn kill(&mut self) -> IoResult<()> {
816 ChildKiller::kill(&mut self.child)
817 }
818
819 fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
820 ChildKiller::clone_killer(&self.child)
821 }
822}
823
824pub fn native_pty_system() -> Box<dyn PtySystem + Send> {
825 Box::new(NativePtySystem::default())
826}
827
828#[cfg(unix)]
829pub type NativePtySystem = unix::UnixPtySystem;
830#[cfg(windows)]
831pub type NativePtySystem = win::conpty::ConPtySystem;