| 1 | use std::{ffi::c_int, io, process::Command}; |
| 2 | |
| 3 | use super::{ |
| 4 | ExitReason, HandleSigchld, |
| 5 | event::PollEvent, |
| 6 | event::{EventRegistry, Process, StopReason}, |
| 7 | io_util::was_interrupted, |
| 8 | terminate_process, |
| 9 | }; |
| 10 | use crate::{ |
| 11 | common::bin_serde::BinPipe, |
| 12 | system::signal::{ |
| 13 | SignalHandler, SignalHandlerBehavior, SignalNumber, SignalSet, SignalStream, SignalsState, |
| 14 | consts::*, register_handlers, |
| 15 | }, |
| 16 | }; |
| 17 | use crate::{ |
| 18 | exec::{SpawnNoexecHandler, exec_command, handle_sigchld, signal_fmt}, |
| 19 | log::{dev_error, dev_info, dev_warn}, |
| 20 | system::{ |
| 21 | ForkResult, fork, getpgid, getpgrp, |
| 22 | interface::ProcessId, |
| 23 | kill, killpg, |
| 24 | term::{Terminal, UserTerm}, |
| 25 | wait::WaitOptions, |
| 26 | }, |
| 27 | }; |
| 28 | |
| 29 | pub(super) fn exec_no_pty( |
| 30 | sudo_pid: ProcessId, |
| 31 | spawn_noexec_handler: Option<SpawnNoexecHandler>, |
| 32 | command: Command, |
| 33 | ) -> io::Result<ExitReason> { |
| 34 | // FIXME (ogsudo): Initialize the policy plugin's session here. |
| 35 | |
| 36 | let original_signals = SignalsState::save()?; |
| 37 | |
| 38 | // Block all the signals until we are done setting up the signal handlers so we don't miss |
| 39 | // SIGCHLD. |
| 40 | let original_set = match SignalSet::full().and_then(|set| set.block()) { |
| 41 | Ok(original_set) => Some(original_set), |
| 42 | Err(err) => { |
| 43 | dev_warn!("cannot block signals: {err}"); |
| 44 | None |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | // FIXME (ogsudo): Some extra config happens here if selinux is available. |
| 49 | |
| 50 | // Use a pipe to get the IO error if `exec` fails. |
| 51 | let (errpipe_tx, errpipe_rx) = BinPipe::pair()?; |
| 52 | |
| 53 | // SAFETY: There should be no other threads at this point. |
| 54 | let ForkResult::Parent(command_pid) = unsafe { fork() }.map_err(|err| { |
| 55 | dev_warn!("unable to fork command process: {err}"); |
| 56 | err |
| 57 | })? |
| 58 | else { |
| 59 | exec_command(command, original_set, original_signals, errpipe_tx); |
| 60 | }; |
| 61 | |
| 62 | if let Some(spawner) = spawn_noexec_handler { |
| 63 | spawner.spawn(); |
| 64 | } |
| 65 | |
| 66 | dev_info!("executed command with pid {command_pid}"); |
| 67 | |
| 68 | let mut registry = EventRegistry::new(); |
| 69 | |
| 70 | let mut closure = ExecClosure::new( |
| 71 | command_pid, |
| 72 | sudo_pid, |
| 73 | errpipe_rx, |
| 74 | &mut registry, |
| 75 | original_signals, |
| 76 | )?; |
| 77 | |
| 78 | // Restore the signal mask now that the handlers have been setup. |
| 79 | if let Some(set) = original_set { |
| 80 | if let Err(err) = set.set_mask() { |
| 81 | dev_warn!("cannot restore signal mask: {err}"); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | let command_exit_reason = match registry.event_loop(&mut closure) { |
| 86 | StopReason::Break(err) => return Err(err), |
| 87 | StopReason::Exit(reason) => reason, |
| 88 | }; |
| 89 | |
| 90 | // Restore signal handlers |
| 91 | drop(closure.signal_handlers); |
| 92 | |
| 93 | Ok(command_exit_reason) |
| 94 | } |
| 95 | |
| 96 | struct ExecClosure { |
| 97 | command_pid: Option<ProcessId>, |
| 98 | sudo_pid: ProcessId, |
| 99 | parent_pgrp: ProcessId, |
| 100 | errpipe_rx: BinPipe<i32>, |
| 101 | original_signals: SignalsState, |
| 102 | signal_stream: &'static SignalStream, |
| 103 | signal_handlers: [SignalHandler; ExecClosure::SIGNALS.len()], |
| 104 | } |
| 105 | |
| 106 | impl ExecClosure { |
| 107 | const SIGNALS: [SignalNumber; 12] = [ |
| 108 | SIGINT, SIGQUIT, SIGTSTP, SIGTERM, SIGHUP, SIGALRM, SIGPIPE, SIGUSR1, SIGUSR2, SIGCHLD, |
| 109 | SIGCONT, SIGWINCH, |
| 110 | ]; |
| 111 | |
| 112 | fn new( |
| 113 | command_pid: ProcessId, |
| 114 | sudo_pid: ProcessId, |
| 115 | errpipe_rx: BinPipe<i32>, |
| 116 | registry: &mut EventRegistry<Self>, |
| 117 | mut original_signals: SignalsState, |
| 118 | ) -> io::Result<Self> { |
| 119 | registry.register_event(&errpipe_rx, PollEvent::Readable, |_| ExecEvent::ErrPipe); |
| 120 | |
| 121 | let signal_stream = SignalStream::init()?; |
| 122 | |
| 123 | registry.register_event(signal_stream, PollEvent::Readable, |_| ExecEvent::Signal); |
| 124 | |
| 125 | let signal_handlers = register_handlers(Self::SIGNALS, &mut original_signals)?; |
| 126 | |
| 127 | Ok(Self { |
| 128 | command_pid: Some(command_pid), |
| 129 | errpipe_rx, |
| 130 | sudo_pid, |
| 131 | parent_pgrp: getpgrp(), |
| 132 | original_signals, |
| 133 | signal_stream, |
| 134 | signal_handlers, |
| 135 | }) |
| 136 | } |
| 137 | |
| 138 | /// Decides if the signal sent by the process with `signaler_pid` PID is self-terminating. |
| 139 | /// |
| 140 | /// A signal is self-terminating if `signaler_pid`: |
| 141 | /// - is the same PID of the command, or |
| 142 | /// - is in the process group of the command and either sudo or the command is the leader. |
| 143 | fn is_self_terminating(&self, signaler_pid: ProcessId) -> bool { |
| 144 | if signaler_pid.is_valid() { |
| 145 | if Some(signaler_pid) == self.command_pid { |
| 146 | return true; |
| 147 | } |
| 148 | |
| 149 | if let Ok(signaler_pgrp) = getpgid(signaler_pid) { |
| 150 | if Some(signaler_pgrp) == self.command_pid || signaler_pgrp == self.sudo_pid { |
| 151 | return true; |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | false |
| 157 | } |
| 158 | |
| 159 | /// Suspend the main process. |
| 160 | fn suspend_parent(&mut self, signal: SignalNumber) { |
| 161 | let mut opt_tty = UserTerm::open().ok(); |
| 162 | let mut opt_pgrp = None; |
| 163 | |
| 164 | if let Some(tty) = opt_tty.as_ref() { |
| 165 | if let Ok(saved_pgrp) = tty.tcgetpgrp() { |
| 166 | // Save the terminal's foreground process group so we can restore it after resuming |
| 167 | // if needed. |
| 168 | opt_pgrp = Some(saved_pgrp); |
| 169 | } else { |
| 170 | opt_tty.take(); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | if let Some(saved_pgrp) = opt_pgrp { |
| 175 | // This means that the command was stopped trying to access the terminal. If the |
| 176 | // terminal has a different foreground process group and we own the terminal, we give |
| 177 | // it to the command and let it continue. |
| 178 | if let SIGTTOU | SIGTTIN = signal { |
| 179 | if saved_pgrp == self.parent_pgrp { |
| 180 | if let Some(command_pgrp) = self.command_pid.and_then(|pid| getpgid(pid).ok()) { |
| 181 | if command_pgrp != self.parent_pgrp |
| 182 | && opt_tty |
| 183 | .as_ref() |
| 184 | .is_some_and(|tty| tty.tcsetpgrp_nobg(command_pgrp).is_ok()) |
| 185 | { |
| 186 | if let Err(err) = killpg(command_pgrp, SIGCONT) { |
| 187 | dev_warn!("cannot send SIGCONT to command ({command_pgrp}): {err}"); |
| 188 | } |
| 189 | |
| 190 | return; |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | let sigtstp_handler = if signal == SIGTSTP { |
| 198 | SignalHandler::register( |
| 199 | signal, |
| 200 | SignalHandlerBehavior::Default, |
| 201 | &mut self.original_signals, |
| 202 | ) |
| 203 | .map_err(|err| dev_warn!("cannot set handler for {}: {err}", signal_fmt(signal))) |
| 204 | .ok() |
| 205 | } else { |
| 206 | None |
| 207 | }; |
| 208 | |
| 209 | if let Err(err) = kill(self.sudo_pid, signal) { |
| 210 | dev_warn!( |
| 211 | "cannot send {} to {} (sudo): {err}", |
| 212 | signal_fmt(signal), |
| 213 | self.sudo_pid |
| 214 | ); |
| 215 | } |
| 216 | |
| 217 | drop(sigtstp_handler); |
| 218 | |
| 219 | if let Some(saved_pgrp) = opt_pgrp { |
| 220 | // Restore the foreground process group after resuming. |
| 221 | if saved_pgrp != self.parent_pgrp { |
| 222 | if let Some(tty) = opt_tty { |
| 223 | tty.tcsetpgrp_nobg(saved_pgrp).ok(); |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn on_signal(&mut self, registry: &mut EventRegistry<Self>) { |
| 230 | let info = match self.signal_stream.recv() { |
| 231 | Ok(info) => info, |
| 232 | Err(err) => { |
| 233 | dev_error!("sudo could not receive signal: {err}"); |
| 234 | return; |
| 235 | } |
| 236 | }; |
| 237 | |
| 238 | dev_info!("received{}", info); |
| 239 | |
| 240 | let Some(command_pid) = self.command_pid else { |
| 241 | dev_info!("command was terminated, ignoring signal"); |
| 242 | return; |
| 243 | }; |
| 244 | |
| 245 | match info.signal() { |
| 246 | SIGCHLD => handle_sigchld(self, registry, "command", command_pid), |
| 247 | signal => { |
| 248 | // FIXME: we should handle SIGWINCH here if we want to support I/O plugins that |
| 249 | // react on window change events. |
| 250 | |
| 251 | if let Some(pid) = info.signaler_pid() { |
| 252 | if self.is_self_terminating(pid) { |
| 253 | // Skip the signal if it was sent by the user and it is self-terminating. |
| 254 | return; |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | if signal == SIGALRM { |
| 259 | terminate_process(command_pid, false); |
| 260 | } else { |
| 261 | kill(command_pid, signal).ok(); |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 269 | enum ExecEvent { |
| 270 | Signal, |
| 271 | ErrPipe, |
| 272 | } |
| 273 | |
| 274 | impl Process for ExecClosure { |
| 275 | type Event = ExecEvent; |
| 276 | type Break = io::Error; |
| 277 | type Exit = ExitReason; |
| 278 | |
| 279 | fn on_event(&mut self, event: Self::Event, registry: &mut EventRegistry<Self>) { |
| 280 | match event { |
| 281 | ExecEvent::Signal => self.on_signal(registry), |
| 282 | ExecEvent::ErrPipe => { |
| 283 | match self.errpipe_rx.read() { |
| 284 | Err(err) if was_interrupted(&err) => { /* Retry later */ } |
| 285 | Err(err) => registry.set_break(err), |
| 286 | Ok(error_code) => { |
| 287 | // Received error code from the command, forward it to the parent. |
| 288 | registry.set_break(io::Error::from_raw_os_error(error_code)); |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | impl HandleSigchld for ExecClosure { |
| 297 | const OPTIONS: WaitOptions = WaitOptions::new().all().untraced().no_hang(); |
| 298 | |
| 299 | fn on_exit(&mut self, exit_code: c_int, registry: &mut EventRegistry<Self>) { |
| 300 | registry.set_exit(ExitReason::Code(exit_code)); |
| 301 | self.command_pid = None; |
| 302 | } |
| 303 | |
| 304 | fn on_term(&mut self, signal: SignalNumber, registry: &mut EventRegistry<Self>) { |
| 305 | registry.set_exit(ExitReason::Signal(signal)); |
| 306 | self.command_pid = None; |
| 307 | } |
| 308 | |
| 309 | fn on_stop(&mut self, signal: SignalNumber, _registry: &mut EventRegistry<Self>) { |
| 310 | self.suspend_parent(signal); |
| 311 | } |
| 312 | } |