Debian Codegraph @

src/exec/use_pty/monitor.rs

raw symbols SCIP
1 use std::{convert::Infallible, ffi::c_int, io, process::Command};
2
3 use crate::exec::{opt_fmt, signal_fmt};
4 use crate::system::signal::{
5 SignalHandler, SignalHandlerBehavior, SignalNumber, SignalSet, SignalStream, SignalsState,
6 consts::*, register_handlers,
7 };
8 use crate::{
9 common::bin_serde::BinPipe,
10 exec::{
11 event::{EventRegistry, Process},
12 exec_command,
13 io_util::{retry_while_interrupted, was_interrupted},
14 use_pty::backchannel::{MonitorBackchannel, MonitorMessage, ParentMessage},
15 },
16 };
17 use crate::{
18 exec::{HandleSigchld, handle_sigchld, terminate_process},
19 system::{
20 _exit, ForkResult, fork, getpgid, getpgrp,
21 interface::ProcessId,
22 killpg, setpgid, setsid,
23 term::{PtyFollower, Terminal},
24 wait::{Wait, WaitError, WaitOptions},
25 },
26 };
27 use crate::{
28 exec::{
29 event::{PollEvent, StopReason},
30 use_pty::{SIGCONT_BG, SIGCONT_FG},
31 },
32 log::{dev_error, dev_info, dev_warn},
33 };
34
35 use super::CommandStatus;
36
37 pub(super) fn exec_monitor(
38 pty_follower: PtyFollower,
39 command: Command,
40 foreground: bool,
41 backchannel: &mut MonitorBackchannel,
42 original_set: Option<SignalSet>,
43 mut original_signals: SignalsState,
44 ) -> io::Result<Infallible> {
45 // SIGTTIN and SIGTTOU are ignored here but the docs state that it shouldn't
46 // be possible to receive them in the first place. Investigate
47 match SignalHandler::register(
48 SIGTTIN,
49 SignalHandlerBehavior::Ignore,
50 &mut original_signals,
51 ) {
52 Ok(handler) => handler.forget(),
53 Err(err) => dev_warn!("cannot set handler for SIGTTIN: {err}"),
54 }
55 match SignalHandler::register(
56 SIGTTOU,
57 SignalHandlerBehavior::Ignore,
58 &mut original_signals,
59 ) {
60 Ok(handler) => handler.forget(),
61 Err(err) => dev_warn!("cannot set handler for SIGTTOU: {err}"),
62 }
63
64 // Start a new terminal session with the monitor as the leader.
65 setsid().map_err(|err| {
66 dev_warn!("cannot start a new session: {err}");
67 err
68 })?;
69
70 // Set the follower side of the pty as the controlling terminal for the session.
71 pty_follower.make_controlling_terminal().map_err(|err| {
72 dev_warn!("cannot set the controlling terminal: {err}");
73 err
74 })?;
75
76 // Use a pipe to get the IO error if `exec_command` fails.
77 let (errpipe_tx, errpipe_rx) = BinPipe::pair()?;
78
79 // Wait for the parent to give us green light before spawning the command. This avoids race
80 // conditions when the command exits quickly.
81 let event = retry_while_interrupted(|| backchannel.recv()).map_err(|err| {
82 dev_warn!("cannot receive green light from parent: {err}");
83 err
84 })?;
85 // Given that `UnixStream` delivers messages in order it shouldn't be possible to
86 // receive an event different to `Edge` at the beginning.
87 debug_assert_eq!(event, MonitorMessage::Edge);
88
89 // FIXME (ogsudo): Some extra config happens here if selinux is available.
90
91 // SAFETY: There should be no other threads at this point.
92 let ForkResult::Parent(command_pid) = unsafe { fork() }.map_err(|err| {
93 dev_warn!("unable to fork command process: {err}");
94 err
95 })?
96 else {
97 drop(errpipe_rx);
98
99 // FIXME (ogsudo): Do any additional configuration that needs to be run after `fork` but before `exec`
100 let command_pid = ProcessId::new(std::process::id() as i32);
101
102 setpgid(ProcessId::new(0), command_pid).ok();
103
104 // Wait for the monitor to set us as the foreground group for the pty if we are in the
105 // foreground.
106 if foreground {
107 while !pty_follower.tcgetpgrp().is_ok_and(|pid| pid == command_pid) {
108 std::thread::yield_now();
109 }
110 }
111
112 // Done with the pty follower.
113 drop(pty_follower);
114
115 exec_command(command, original_set, original_signals, errpipe_tx)
116 };
117
118 // Send the command's PID to the parent.
119 if let Err(err) = backchannel.send(&ParentMessage::CommandPid(command_pid)) {
120 dev_warn!("cannot send command PID to parent: {err}");
121 }
122
123 let mut registry = EventRegistry::new();
124
125 let mut closure = MonitorClosure::new(
126 command_pid,
127 pty_follower,
128 errpipe_rx,
129 backchannel,
130 &mut registry,
131 &mut original_signals,
132 )?;
133
134 // Restore the signal mask now that the handlers have been setup.
135 if let Some(set) = original_set {
136 if let Err(err) = set.set_mask() {
137 dev_warn!("cannot restore signal mask: {err}");
138 }
139 }
140
141 // Set the foreground group for the pty follower.
142 if foreground {
143 if let Err(err) = closure.pty_follower.tcsetpgrp(closure.command_pgrp) {
144 dev_error!(
145 "cannot set foreground process group to {} (command): {err}",
146 closure.command_pgrp
147 );
148 }
149 }
150
151 // FIXME (ogsudo): Here's where the signal mask is removed because the handlers for the signals
152 // have been setup after initializing the closure.
153
154 // Start the event loop.
155 let reason = registry.event_loop(&mut closure);
156
157 // Terminate the command if it's not terminated.
158 if let Some(command_pid) = closure.command_pid {
159 terminate_process(command_pid, true);
160
161 loop {
162 match command_pid.wait(WaitOptions::new()) {
163 Err(WaitError::Io(err)) if was_interrupted(&err) => {}
164 _ => break,
165 }
166 }
167 }
168
169 // Take the controlling tty so the command's children don't receive SIGHUP when we exit.
170 if let Err(err) = closure.pty_follower.tcsetpgrp(closure.monitor_pgrp) {
171 dev_error!(
172 "cannot set foreground process group to {} (monitor): {err}",
173 closure.monitor_pgrp
174 );
175 }
176
177 // Disable nonblocking assertions as we will not poll the backchannel anymore.
178 closure.backchannel.set_nonblocking_assertions(false);
179
180 match reason {
181 StopReason::Break(err) => match err.try_into() {
182 Ok(msg) => {
183 if let Err(err) = closure.backchannel.send(&msg) {
184 dev_warn!("cannot send message over backchannel: {err}")
185 }
186 }
187 Err(err) => {
188 dev_warn!("socket error `{err:?}` cannot be converted to a message")
189 }
190 },
191 StopReason::Exit(command_status) => {
192 if let Err(err) = closure.backchannel.send(&command_status.into()) {
193 dev_warn!("cannot send message over backchannel: {err}")
194 }
195 }
196 }
197
198 // Wait for the parent to give us red light before shutting down. This avoids missing
199 // output when the monitor exits too quickly.
200 let event = retry_while_interrupted(|| backchannel.recv()).map_err(|err| {
201 dev_warn!("cannot receive red light from parent: {err}");
202 err
203 })?;
204 debug_assert_eq!(event, MonitorMessage::Edge);
205
206 // FIXME (ogsudo): The tty is restored here if selinux is available.
207
208 // We call `_exit` instead of `exit` to avoid flushing the parent's IO streams by accident.
209 _exit(1);
210 }
211
212 struct MonitorClosure<'a> {
213 /// The command PID.
214 ///
215 /// This is `Some` iff the process is still running.
216 command_pid: Option<ProcessId>,
217 command_pgrp: ProcessId,
218 monitor_pgrp: ProcessId,
219 pty_follower: PtyFollower,
220 errpipe_rx: BinPipe<i32>,
221 backchannel: &'a mut MonitorBackchannel,
222 signal_stream: &'static SignalStream,
223 _signal_handlers: [SignalHandler; MonitorClosure::SIGNALS.len()],
224 }
225
226 impl<'a> MonitorClosure<'a> {
227 const SIGNALS: [SignalNumber; 8] = [
228 SIGINT, SIGQUIT, SIGTSTP, SIGTERM, SIGHUP, SIGUSR1, SIGUSR2, SIGCHLD,
229 ];
230
231 fn new(
232 command_pid: ProcessId,
233 pty_follower: PtyFollower,
234 errpipe_rx: BinPipe<i32>,
235 backchannel: &'a mut MonitorBackchannel,
236 registry: &mut EventRegistry<Self>,
237 original_signals: &mut SignalsState,
238 ) -> io::Result<Self> {
239 // Store the pgid of the monitor.
240 let monitor_pgrp = getpgrp();
241
242 // Register the callback to receive the IO error if the command fails to execute.
243 registry.register_event(&errpipe_rx, PollEvent::Readable, |_| {
244 MonitorEvent::ReadableErrPipe
245 });
246
247 // Enable nonblocking assertions as we will poll this inside the event loop.
248 backchannel.set_nonblocking_assertions(true);
249
250 // Register the callback to receive events from the backchannel
251 registry.register_event(backchannel, PollEvent::Readable, |_| {
252 MonitorEvent::ReadableBackchannel
253 });
254
255 let signal_stream = SignalStream::init()?;
256
257 registry.register_event(signal_stream, PollEvent::Readable, |_| MonitorEvent::Signal);
258
259 let signal_handlers = register_handlers(Self::SIGNALS, original_signals)?;
260
261 // Put the command in its own process group.
262 let command_pgrp = command_pid;
263 if let Err(err) = setpgid(command_pid, command_pgrp) {
264 dev_warn!("cannot set process group ID for process: {err}");
265 };
266
267 Ok(Self {
268 command_pid: Some(command_pid),
269 command_pgrp,
270 monitor_pgrp,
271 pty_follower,
272 errpipe_rx,
273 backchannel,
274 signal_stream,
275 _signal_handlers: signal_handlers,
276 })
277 }
278
279 /// Based on `mon_backchannel_cb`
280 fn read_backchannel(&mut self, registry: &mut EventRegistry<Self>) {
281 match self.backchannel.recv() {
282 Err(err) => {
283 // We can try later if receive is interrupted.
284 if err.kind() != io::ErrorKind::Interrupted {
285 // There's something wrong with the backchannel, break the event loop.
286 dev_warn!("cannot read from backchannel: {err}");
287 registry.set_break(err);
288 }
289 }
290 Ok(event) => {
291 match event {
292 // We shouldn't receive this event at this point in the protocol
293 MonitorMessage::Edge => unreachable!(),
294 // Forward signal to the command.
295 MonitorMessage::Signal(signal) => {
296 if let Some(command_pid) = self.command_pid {
297 self.send_signal(signal, command_pid, true)
298 }
299 }
300 }
301 }
302 }
303 }
304
305 fn read_errpipe(&mut self, registry: &mut EventRegistry<Self>) {
306 match self.errpipe_rx.read() {
307 Err(err) if was_interrupted(&err) => { /* Retry later */ }
308 Err(err) => registry.set_break(err),
309 Ok(error_code) => {
310 // Received error code from the command, forward it to the parent.
311 registry.set_break(io::Error::from_raw_os_error(error_code));
312 }
313 }
314 }
315
316 /// Send a signal to the command.
317 fn send_signal(&self, signal: c_int, command_pid: ProcessId, from_parent: bool) {
318 dev_info!(
319 "sending {}{} to command",
320 signal_fmt(signal),
321 opt_fmt(from_parent, " from parent"),
322 );
323 match signal {
324 SIGALRM => {
325 terminate_process(command_pid, false);
326 }
327 SIGCONT_FG => {
328 // Continue with the command as the foreground process group
329 if let Err(err) = self.pty_follower.tcsetpgrp(self.command_pgrp) {
330 dev_error!(
331 "cannot set the foreground process group to {} (command): {err}",
332 self.command_pgrp
333 );
334 }
335 killpg(command_pid, SIGCONT).ok();
336 }
337 SIGCONT_BG => {
338 // Continue with the monitor as the foreground process group
339 if let Err(err) = self.pty_follower.tcsetpgrp(self.monitor_pgrp) {
340 dev_error!(
341 "cannot set the foreground process group to {} (monitor): {err}",
342 self.monitor_pgrp
343 );
344 }
345 killpg(command_pid, SIGCONT).ok();
346 }
347 signal => {
348 // Send the signal to the command.
349 killpg(command_pid, signal).ok();
350 }
351 }
352 }
353
354 fn on_signal(&mut self, registry: &mut EventRegistry<Self>) {
355 let info = match self.signal_stream.recv() {
356 Ok(info) => info,
357 Err(err) => {
358 dev_error!("could not receive signal: {err}");
359 return;
360 }
361 };
362
363 dev_info!("monitor received{}", info);
364
365 // Don't do anything if the command has terminated already
366 let Some(command_pid) = self.command_pid else {
367 dev_info!("command was terminated, ignoring signal");
368 return;
369 };
370
371 match info.signal() {
372 SIGCHLD => handle_sigchld(self, registry, "command", command_pid),
373 signal => {
374 if let Some(pid) = info.signaler_pid() {
375 if is_self_terminating(pid, command_pid, self.command_pgrp) {
376 // Skip the signal if it was sent by the user and it is self-terminating.
377 return;
378 }
379 }
380
381 self.send_signal(signal, command_pid, false)
382 }
383 }
384 }
385 }
386
387 /// Decides if the signal sent by the process with `signaler_pid` PID is self-terminating.
388 ///
389 /// A signal is self-terminating if `signaler_pid`:
390 /// - is the same PID of the command, or
391 /// - is in the process group of the command and the command is the leader.
392 fn is_self_terminating(
393 signaler_pid: ProcessId,
394 command_pid: ProcessId,
395 command_pgrp: ProcessId,
396 ) -> bool {
397 if signaler_pid.is_valid() {
398 if signaler_pid == command_pid {
399 return true;
400 }
401
402 if let Ok(grp_leader) = getpgid(signaler_pid) {
403 if grp_leader == command_pgrp {
404 return true;
405 }
406 }
407 }
408
409 false
410 }
411
412 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
413 enum MonitorEvent {
414 Signal,
415 ReadableErrPipe,
416 ReadableBackchannel,
417 }
418
419 impl Process for MonitorClosure<'_> {
420 type Event = MonitorEvent;
421 type Break = io::Error;
422 type Exit = CommandStatus;
423
424 fn on_event(&mut self, event: Self::Event, registry: &mut EventRegistry<Self>) {
425 match event {
426 MonitorEvent::Signal => self.on_signal(registry),
427 MonitorEvent::ReadableErrPipe => self.read_errpipe(registry),
428 MonitorEvent::ReadableBackchannel => self.read_backchannel(registry),
429 }
430 }
431 }
432
433 impl HandleSigchld for MonitorClosure<'_> {
434 const OPTIONS: WaitOptions = WaitOptions::new().untraced().no_hang();
435
436 fn on_exit(&mut self, exit_code: c_int, registry: &mut EventRegistry<Self>) {
437 registry.set_exit(CommandStatus::Exit(exit_code));
438 self.command_pid = None;
439 }
440
441 fn on_term(&mut self, signal: c_int, registry: &mut EventRegistry<Self>) {
442 registry.set_exit(CommandStatus::Term(signal));
443 self.command_pid = None;
444 }
445
446 fn on_stop(&mut self, signal: c_int, _registry: &mut EventRegistry<Self>) {
447 // Save the foreground process group ID so we can restore it later.
448 if let Ok(pgrp) = self.pty_follower.tcgetpgrp() {
449 if pgrp != self.monitor_pgrp {
450 self.command_pgrp = pgrp;
451 }
452 }
453 self.backchannel
454 .send(&CommandStatus::Stop(signal).into())
455 .ok();
456 }
457 }