| 1 | use std::collections::VecDeque; |
| 2 | use std::ffi::c_int; |
| 3 | use std::io; |
| 4 | use std::os::fd::{FromRawFd, OwnedFd}; |
| 5 | use std::process::{Command, Stdio}; |
| 6 | |
| 7 | use libc::{O_CLOEXEC, close}; |
| 8 | |
| 9 | use crate::cutils::cerr; |
| 10 | use crate::exec::event::{EventHandle, EventRegistry, PollEvent, Process, StopReason}; |
| 11 | use crate::exec::use_pty::SIGCONT_FG; |
| 12 | use crate::exec::use_pty::monitor::exec_monitor; |
| 13 | use crate::exec::{ |
| 14 | ExitReason, SpawnNoexecHandler, |
| 15 | io_util::retry_while_interrupted, |
| 16 | use_pty::backchannel::{BackchannelPair, MonitorMessage, ParentBackchannel, ParentMessage}, |
| 17 | }; |
| 18 | use crate::exec::{HandleSigchld, cond_fmt, handle_sigchld, signal_fmt, terminate_process}; |
| 19 | use crate::log::{dev_error, dev_info, dev_warn}; |
| 20 | use crate::system::signal::{ |
| 21 | SignalHandler, SignalHandlerBehavior, SignalNumber, SignalSet, SignalStream, SignalsState, |
| 22 | consts::*, register_handlers, |
| 23 | }; |
| 24 | use crate::system::term::{Pty, PtyFollower, PtyLeader, TermSize, Terminal, UserTerm}; |
| 25 | use crate::system::wait::WaitOptions; |
| 26 | use crate::system::{_exit, ForkResult, Group, User, chown, fork, getpgrp, kill, killpg}; |
| 27 | use crate::system::{getpgid, interface::ProcessId}; |
| 28 | |
| 29 | use super::pipe::Pipe; |
| 30 | use super::{CommandStatus, SIGCONT_BG}; |
| 31 | |
| 32 | pub(in crate::exec) fn exec_pty( |
| 33 | sudo_pid: ProcessId, |
| 34 | spawn_noexec_handler: Option<SpawnNoexecHandler>, |
| 35 | mut command: Command, |
| 36 | user_tty: UserTerm, |
| 37 | pty_owner: &User, |
| 38 | background: bool, |
| 39 | ) -> io::Result<ExitReason> { |
| 40 | // Allocate a pseudoterminal. |
| 41 | let pty = get_pty(pty_owner)?; |
| 42 | |
| 43 | let mut original_signals = SignalsState::save()?; |
| 44 | |
| 45 | // Create backchannels to communicate with the monitor. |
| 46 | let mut backchannels = BackchannelPair::new().map_err(|err| { |
| 47 | dev_error!("cannot create backchannel: {err}"); |
| 48 | err |
| 49 | })?; |
| 50 | |
| 51 | // We don't want to receive SIGTTIN/SIGTTOU |
| 52 | match SignalHandler::register( |
| 53 | SIGTTIN, |
| 54 | SignalHandlerBehavior::Ignore, |
| 55 | &mut original_signals, |
| 56 | ) { |
| 57 | Ok(handler) => handler.forget(), |
| 58 | Err(err) => dev_warn!("cannot set handler for SIGTTIN: {err}"), |
| 59 | } |
| 60 | match SignalHandler::register( |
| 61 | SIGTTOU, |
| 62 | SignalHandlerBehavior::Ignore, |
| 63 | &mut original_signals, |
| 64 | ) { |
| 65 | Ok(handler) => handler.forget(), |
| 66 | Err(err) => dev_warn!("cannot set handler for SIGTTOU: {err}"), |
| 67 | } |
| 68 | |
| 69 | // FIXME (ogsudo): Initialize the policy plugin's session here by calling |
| 70 | // `policy_init_session`. |
| 71 | // FIXME (ogsudo): initializes ttyblock sigset here by calling `init_ttyblock` |
| 72 | |
| 73 | // Fetch the parent process group so we can send signals to it. |
| 74 | let parent_pgrp = getpgrp(); |
| 75 | |
| 76 | // Set all the IO streams for the command to the follower side of the pty. |
| 77 | let clone_follower = || -> io::Result<PtyFollower> { |
| 78 | pty.follower.try_clone().map_err(|err| { |
| 79 | dev_error!("cannot clone pty follower: {err}"); |
| 80 | err |
| 81 | }) |
| 82 | }; |
| 83 | |
| 84 | command.stdin(clone_follower()?); |
| 85 | command.stdout(clone_follower()?); |
| 86 | command.stderr(clone_follower()?); |
| 87 | |
| 88 | let mut registry = EventRegistry::<ParentClosure>::new(); |
| 89 | |
| 90 | // Pipe data between both terminals |
| 91 | let mut tty_pipe = Pipe::new( |
| 92 | user_tty, |
| 93 | pty.leader, |
| 94 | &mut registry, |
| 95 | ParentEvent::Tty, |
| 96 | ParentEvent::Pty, |
| 97 | ); |
| 98 | |
| 99 | if background { |
| 100 | tty_pipe.disable_input(&mut registry); |
| 101 | } |
| 102 | |
| 103 | let user_tty = tty_pipe.left_mut(); |
| 104 | |
| 105 | // Check if we are the foreground process |
| 106 | let mut foreground = user_tty |
| 107 | .tcgetpgrp() |
| 108 | .is_ok_and(|tty_pgrp| tty_pgrp == parent_pgrp); |
| 109 | dev_info!( |
| 110 | "sudo is running in the {}", |
| 111 | cond_fmt(foreground, "foreground", "background") |
| 112 | ); |
| 113 | |
| 114 | // FIXME: maybe all these boolean flags should be on a dedicated type. |
| 115 | |
| 116 | // Whether the command should be executed in the background (this is not the `-b` flag) |
| 117 | let mut exec_bg = false; |
| 118 | // Whether the user's terminal is in raw mode or not. |
| 119 | let mut term_raw = false; |
| 120 | // Whether to preserve oflag for the terminal |
| 121 | let mut preserve_oflag = false; |
| 122 | |
| 123 | // Check if we are part of a pipeline. |
| 124 | // FIXME: Here's where we should intercept the IO streams if we want to implement IO logging. |
| 125 | // FIXME: ogsudo creates pipes for the IO streams and uses events to read from the strams to |
| 126 | // the pipes. Investigate why. |
| 127 | if !io::stdin().is_terminal_for_pgrp(parent_pgrp) { |
| 128 | if background { |
| 129 | // Running in background (sudo -b), no access to terminal input. |
| 130 | // In non-pty mode, the command runs in an orphaned process |
| 131 | // group and reads from the controlling terminal fail with EIO. |
| 132 | // We cannot do the same while running in a pty but if we set |
| 133 | // stdin to a half-closed pipe, reads from it will get EOF. |
| 134 | dev_info!("stdin is not a terminal, creating a pipe"); |
| 135 | exec_bg = true; |
| 136 | |
| 137 | let mut pipes = [-1, -1]; |
| 138 | // SAFETY: A valid pointer to a mutable array of 2 fds is passed in. |
| 139 | unsafe { |
| 140 | cerr(libc::pipe2(pipes.as_mut_ptr(), O_CLOEXEC))?; |
| 141 | } |
| 142 | // SAFETY: pipe2 created two owned pipe fds. |
| 143 | unsafe { |
| 144 | command.stdin(OwnedFd::from_raw_fd(pipes[0])); |
| 145 | close(pipes[1]); |
| 146 | } |
| 147 | } else { |
| 148 | dev_info!("stdin is not a terminal, command will inherit it"); |
| 149 | if io::stdin().is_pipe_or_socket() { |
| 150 | exec_bg = true; |
| 151 | } |
| 152 | command.stdin(Stdio::inherit()); |
| 153 | } |
| 154 | |
| 155 | if foreground && parent_pgrp != sudo_pid { |
| 156 | // If sudo is not the process group leader and stdin is not a terminal we might be |
| 157 | // running as a background job via a shell script. Starting in the foreground would |
| 158 | // change the terminal mode. |
| 159 | exec_bg = true; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if !io::stdout().is_terminal_for_pgrp(parent_pgrp) { |
| 164 | dev_info!("stdout is not a terminal, command will inherit it"); |
| 165 | if io::stdout().is_pipe_or_socket() { |
| 166 | exec_bg = true; |
| 167 | preserve_oflag = true; |
| 168 | } |
| 169 | command.stdout(Stdio::inherit()); |
| 170 | } |
| 171 | |
| 172 | if !io::stderr().is_terminal_for_pgrp(parent_pgrp) { |
| 173 | dev_info!("stderr is not a terminal, command will inherit it"); |
| 174 | command.stderr(Stdio::inherit()); |
| 175 | } |
| 176 | |
| 177 | // If there is another process later in the pipeline, don't interfere |
| 178 | // with its access to the Tty |
| 179 | if io::stdout().is_pipe_or_socket() { |
| 180 | foreground = false; |
| 181 | } |
| 182 | |
| 183 | // Copy terminal settings from `/dev/tty` to the pty. |
| 184 | if let Err(err) = user_tty.copy_to(&pty.follower) { |
| 185 | dev_error!("cannot copy terminal settings to pty: {err}"); |
| 186 | foreground = false; |
| 187 | } |
| 188 | |
| 189 | // Start in raw mode unless we're part of a pipeline or backgrounded. |
| 190 | if foreground && !exec_bg { |
| 191 | // Clearer this way that set_raw_mode only conditionally runs |
| 192 | if user_tty.set_raw_mode(false, preserve_oflag).is_ok() { |
| 193 | term_raw = true; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | let tty_size = tty_pipe.left().get_size().map_err(|err| { |
| 198 | dev_error!("cannot get terminal size: {err}"); |
| 199 | err |
| 200 | })?; |
| 201 | |
| 202 | // Block all the signals until we are done setting up the signal handlers so we don't miss |
| 203 | // SIGCHLD. |
| 204 | let original_set = match SignalSet::full().and_then(|set| set.block()) { |
| 205 | Ok(original_set) => Some(original_set), |
| 206 | Err(err) => { |
| 207 | dev_warn!("cannot block signals: {err}"); |
| 208 | None |
| 209 | } |
| 210 | }; |
| 211 | |
| 212 | if !foreground { |
| 213 | tty_pipe.disable_input(&mut registry); |
| 214 | } |
| 215 | |
| 216 | // SAFETY: There should be no other threads at this point. |
| 217 | let ForkResult::Parent(monitor_pid) = (unsafe { fork() }).map_err(|err| { |
| 218 | dev_error!("cannot fork monitor process: {err}"); |
| 219 | err |
| 220 | })? |
| 221 | else { |
| 222 | // Close the file descriptors that we don't access |
| 223 | drop(tty_pipe); |
| 224 | drop(backchannels.parent); |
| 225 | |
| 226 | // If `exec_monitor` returns, it means we failed to execute the command somehow. |
| 227 | match exec_monitor( |
| 228 | pty.follower, |
| 229 | command, |
| 230 | foreground && !exec_bg, |
| 231 | &mut backchannels.monitor, |
| 232 | original_set, |
| 233 | original_signals, |
| 234 | ) { |
| 235 | Ok(exec_output) => match exec_output {}, |
| 236 | Err(err) => { |
| 237 | // Disable nonblocking assertions as we will not poll the backchannel anymore. |
| 238 | backchannels.monitor.set_nonblocking_assertions(true); |
| 239 | |
| 240 | match err.try_into() { |
| 241 | Ok(msg) => { |
| 242 | if let Err(err) = backchannels.monitor.send(&msg) { |
| 243 | dev_error!("cannot send status to parent: {err}"); |
| 244 | } |
| 245 | } |
| 246 | Err(err) => { |
| 247 | dev_warn!("execution error {err:?} cannot be send over backchannel") |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // We call `_exit` instead of `exit` to avoid flushing the parent's IO streams by accident. |
| 254 | _exit(1); |
| 255 | }; |
| 256 | |
| 257 | if let Some(spawner) = spawn_noexec_handler { |
| 258 | spawner.spawn(); |
| 259 | } |
| 260 | |
| 261 | // Close the file descriptors that we don't access |
| 262 | drop(pty.follower); |
| 263 | drop(backchannels.monitor); |
| 264 | |
| 265 | // Send green light to the monitor after closing the follower. |
| 266 | retry_while_interrupted(|| backchannels.parent.send(&MonitorMessage::Edge)).map_err(|err| { |
| 267 | dev_error!("cannot send green light to monitor: {err}"); |
| 268 | err |
| 269 | })?; |
| 270 | |
| 271 | let mut closure = ParentClosure::new( |
| 272 | monitor_pid, |
| 273 | sudo_pid, |
| 274 | parent_pgrp, |
| 275 | backchannels.parent, |
| 276 | tty_pipe, |
| 277 | tty_size, |
| 278 | foreground, |
| 279 | term_raw, |
| 280 | preserve_oflag, |
| 281 | &mut registry, |
| 282 | original_signals, |
| 283 | )?; |
| 284 | |
| 285 | // Restore the signal mask now that the handlers have been setup. |
| 286 | if let Some(set) = original_set { |
| 287 | if let Err(err) = set.set_mask() { |
| 288 | dev_warn!("cannot restore signal mask: {err}"); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | let exit_reason = closure.run(registry); |
| 293 | // FIXME (ogsudo): Retry if `/dev/tty` is revoked. |
| 294 | |
| 295 | // Flush the terminal |
| 296 | closure.tty_pipe.right().set_nonblocking()?; |
| 297 | closure.tty_pipe.flush_left().ok(); |
| 298 | |
| 299 | // Restore the terminal settings |
| 300 | if closure.term_raw { |
| 301 | // Only restore the terminal if sudo is the foreground process. |
| 302 | if let Ok(pgrp) = closure.tty_pipe.left().tcgetpgrp() { |
| 303 | if pgrp == closure.parent_pgrp { |
| 304 | match closure.tty_pipe.left_mut().restore(false) { |
| 305 | Ok(()) => closure.term_raw = false, |
| 306 | Err(err) => dev_warn!("cannot restore terminal settings: {err}"), |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | // Restore signal handlers |
| 313 | drop(closure.signal_handlers); |
| 314 | |
| 315 | exit_reason |
| 316 | } |
| 317 | |
| 318 | fn get_pty(pty_owner: &User) -> io::Result<Pty> { |
| 319 | let tty_gid = Group::from_name(c"tty") |
| 320 | .unwrap_or(None) |
| 321 | .map(|group| group.gid); |
| 322 | |
| 323 | let pty = Pty::open().map_err(|err| { |
| 324 | dev_error!("cannot allocate pty: {err}"); |
| 325 | io::Error::new(io::ErrorKind::NotFound, "unable to open pty") |
| 326 | })?; |
| 327 | |
| 328 | let gid = tty_gid.unwrap_or(User::effective_gid()); |
| 329 | chown(&pty.path, pty_owner.uid, gid).map_err(|err| { |
| 330 | dev_error!("cannot change owner for pty: {err}"); |
| 331 | err |
| 332 | })?; |
| 333 | |
| 334 | Ok(pty) |
| 335 | } |
| 336 | |
| 337 | struct ParentClosure { |
| 338 | // The monitor PID. |
| 339 | // |
| 340 | /// This is `Some` iff the process is still running. |
| 341 | monitor_pid: Option<ProcessId>, |
| 342 | sudo_pid: ProcessId, |
| 343 | parent_pgrp: ProcessId, |
| 344 | command_pid: Option<ProcessId>, |
| 345 | tty_pipe: Pipe<UserTerm, PtyLeader>, |
| 346 | tty_size: TermSize, |
| 347 | foreground: bool, |
| 348 | term_raw: bool, |
| 349 | preserve_oflag: bool, |
| 350 | backchannel: ParentBackchannel, |
| 351 | message_queue: VecDeque<MonitorMessage>, |
| 352 | backchannel_write_handle: EventHandle, |
| 353 | original_signals: SignalsState, |
| 354 | signal_stream: &'static SignalStream, |
| 355 | signal_handlers: [SignalHandler; ParentClosure::SIGNALS.len()], |
| 356 | } |
| 357 | |
| 358 | impl ParentClosure { |
| 359 | const SIGNALS: [SignalNumber; 11] = [ |
| 360 | SIGINT, SIGQUIT, SIGTSTP, SIGTERM, SIGHUP, SIGALRM, SIGUSR1, SIGUSR2, SIGCHLD, SIGCONT, |
| 361 | SIGWINCH, |
| 362 | ]; |
| 363 | |
| 364 | #[allow(clippy::too_many_arguments)] |
| 365 | fn new( |
| 366 | monitor_pid: ProcessId, |
| 367 | sudo_pid: ProcessId, |
| 368 | parent_pgrp: ProcessId, |
| 369 | mut backchannel: ParentBackchannel, |
| 370 | tty_pipe: Pipe<UserTerm, PtyLeader>, |
| 371 | tty_size: TermSize, |
| 372 | foreground: bool, |
| 373 | term_raw: bool, |
| 374 | preserve_oflag: bool, |
| 375 | registry: &mut EventRegistry<Self>, |
| 376 | mut original_signals: SignalsState, |
| 377 | ) -> io::Result<Self> { |
| 378 | // Enable nonblocking assertions as we will poll this inside the event loop. |
| 379 | backchannel.set_nonblocking_asserts(true); |
| 380 | |
| 381 | registry.register_event(&backchannel, PollEvent::Readable, ParentEvent::Backchannel); |
| 382 | let mut backchannel_write_handle = |
| 383 | registry.register_event(&backchannel, PollEvent::Writable, ParentEvent::Backchannel); |
| 384 | // Ignore write events on the backchannel as we don't want to poll it for writing if there |
| 385 | // are no messages in the queue. |
| 386 | backchannel_write_handle.ignore(registry); |
| 387 | |
| 388 | let signal_stream = SignalStream::init()?; |
| 389 | |
| 390 | registry.register_event(signal_stream, PollEvent::Readable, |_| ParentEvent::Signal); |
| 391 | |
| 392 | let signal_handlers = register_handlers(Self::SIGNALS, &mut original_signals)?; |
| 393 | |
| 394 | Ok(Self { |
| 395 | monitor_pid: Some(monitor_pid), |
| 396 | sudo_pid, |
| 397 | parent_pgrp, |
| 398 | command_pid: None, |
| 399 | tty_pipe, |
| 400 | tty_size, |
| 401 | foreground, |
| 402 | term_raw, |
| 403 | preserve_oflag, |
| 404 | backchannel, |
| 405 | message_queue: VecDeque::new(), |
| 406 | backchannel_write_handle, |
| 407 | original_signals, |
| 408 | signal_stream, |
| 409 | signal_handlers, |
| 410 | }) |
| 411 | } |
| 412 | |
| 413 | fn run(&mut self, registry: EventRegistry<Self>) -> io::Result<ExitReason> { |
| 414 | let result = match registry.event_loop(self) { |
| 415 | StopReason::Break(err) | StopReason::Exit(ParentExit::Backchannel(err)) => Err(err), |
| 416 | StopReason::Exit(ParentExit::Command(exit_reason)) => Ok(exit_reason), |
| 417 | }; |
| 418 | // Send red light to the monitor after processing all events |
| 419 | retry_while_interrupted(|| self.backchannel.send(&MonitorMessage::Edge)).map_err( |
| 420 | |err| { |
| 421 | dev_error!("cannot send red light to monitor: {err}"); |
| 422 | err |
| 423 | }, |
| 424 | )?; |
| 425 | |
| 426 | result |
| 427 | } |
| 428 | |
| 429 | /// Read an event from the backchannel and return the event if it should break the event loop. |
| 430 | fn on_message_received(&mut self, registry: &mut EventRegistry<Self>) { |
| 431 | match self.backchannel.recv() { |
| 432 | Err(err) => { |
| 433 | match err.kind() { |
| 434 | // If we get EOF the monitor exited or was killed |
| 435 | io::ErrorKind::UnexpectedEof => { |
| 436 | dev_info!("received EOF from backchannel"); |
| 437 | registry.set_exit(err.into()); |
| 438 | } |
| 439 | // We can try later if receive is interrupted. |
| 440 | io::ErrorKind::Interrupted => {} |
| 441 | // Failed to read command status. This means that something is wrong with the socket |
| 442 | // and we should stop. |
| 443 | _ => { |
| 444 | dev_error!("cannot receive message from backchannel: {err}"); |
| 445 | if !registry.got_break() { |
| 446 | registry.set_break(err); |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | Ok(event) => { |
| 452 | match event { |
| 453 | // Received the PID of the command. This means that the command is already |
| 454 | // executing. |
| 455 | ParentMessage::CommandPid(pid) => { |
| 456 | dev_info!("received command PID ({pid}) from monitor"); |
| 457 | self.command_pid = pid.into(); |
| 458 | } |
| 459 | ParentMessage::CommandStatus(status) => { |
| 460 | // The command terminated or the monitor was not able to spawn it. We should stop |
| 461 | // either way. |
| 462 | match status { |
| 463 | CommandStatus::Exit(exit_code) => { |
| 464 | dev_info!("command exited with status code {exit_code}"); |
| 465 | registry.set_exit(ExitReason::Code(exit_code).into()); |
| 466 | } |
| 467 | CommandStatus::Term(signal) => { |
| 468 | dev_info!("command was terminated by {}", signal_fmt(signal)); |
| 469 | registry.set_exit(ExitReason::Signal(signal).into()); |
| 470 | } |
| 471 | CommandStatus::Stop(signal) => { |
| 472 | dev_info!( |
| 473 | "command was stopped by {}, suspending parent", |
| 474 | signal_fmt(signal) |
| 475 | ); |
| 476 | // Suspend parent and tell monitor how to resume on return |
| 477 | if let Some(signal) = self.suspend_pty(signal, registry) { |
| 478 | self.schedule_signal(signal, registry); |
| 479 | } |
| 480 | |
| 481 | self.tty_pipe.resume_events(registry); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | ParentMessage::IoError(code) => { |
| 486 | let err = io::Error::from_raw_os_error(code); |
| 487 | dev_info!("received error ({code}) for monitor: {err}"); |
| 488 | registry.set_break(err); |
| 489 | } |
| 490 | ParentMessage::ShortRead => { |
| 491 | dev_info!("received short read error for monitor"); |
| 492 | registry.set_break(io::ErrorKind::UnexpectedEof.into()); |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// Decides if the signal sent by the process with `signaler_pid` PID is self-terminating. |
| 500 | /// |
| 501 | /// A signal is self-terminating if `signaler_pid`: |
| 502 | /// - is the same PID of the command, or |
| 503 | /// - is in the process group of the command and either sudo or the command is the leader. |
| 504 | fn is_self_terminating(&self, signaler_pid: ProcessId) -> bool { |
| 505 | if signaler_pid.is_valid() { |
| 506 | if Some(signaler_pid) == self.command_pid { |
| 507 | return true; |
| 508 | } |
| 509 | |
| 510 | if let Ok(signaler_pgrp) = getpgid(signaler_pid) { |
| 511 | if Some(signaler_pgrp) == self.command_pid || signaler_pgrp == self.sudo_pid { |
| 512 | return true; |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | false |
| 518 | } |
| 519 | |
| 520 | /// Schedule sending a signal event to the monitor using the backchannel. |
| 521 | /// |
| 522 | /// The signal message will be sent once the backchannel is ready to be written. |
| 523 | fn schedule_signal(&mut self, signal: c_int, registry: &mut EventRegistry<Self>) { |
| 524 | dev_info!("scheduling message with {} for monitor", signal_fmt(signal)); |
| 525 | self.message_queue.push_back(MonitorMessage::Signal(signal)); |
| 526 | |
| 527 | // Start polling the backchannel for writing if not already. |
| 528 | self.backchannel_write_handle.resume(registry); |
| 529 | } |
| 530 | |
| 531 | /// Send the first message in the event queue using the backchannel, if any. |
| 532 | /// |
| 533 | /// Calling this function will block until the backchannel can be written. |
| 534 | fn check_message_queue(&mut self, registry: &mut EventRegistry<Self>) { |
| 535 | if let Some(msg) = self.message_queue.front() { |
| 536 | dev_info!("sending message {msg:?} to monitor over backchannel"); |
| 537 | match self.backchannel.send(msg) { |
| 538 | // The event was sent, remove it from the queue |
| 539 | Ok(()) => { |
| 540 | self.message_queue.pop_front().unwrap(); |
| 541 | // Stop polling the backchannel for writing if the queue is empty. |
| 542 | if self.message_queue.is_empty() { |
| 543 | self.backchannel_write_handle.ignore(registry); |
| 544 | } |
| 545 | } |
| 546 | Err(err) => { |
| 547 | // We can try later if send is interrupted. |
| 548 | if err.kind() != io::ErrorKind::Interrupted { |
| 549 | // There's something wrong with the backchannel, break the event loop. |
| 550 | dev_error!("cannot send via backchannel {err}"); |
| 551 | registry.set_break(err); |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /// Suspend sudo if the command is suspended. |
| 559 | /// |
| 560 | /// Return `SIGCONT_FG` or `SIGCONT_BG` to state whether the command should be resumed in the |
| 561 | /// foreground or not. |
| 562 | fn suspend_pty( |
| 563 | &mut self, |
| 564 | signal: SignalNumber, |
| 565 | registry: &mut EventRegistry<Self>, |
| 566 | ) -> Option<SignalNumber> { |
| 567 | // Ignore `SIGCONT` while suspending to avoid resuming the terminal twice. |
| 568 | let sigcont_handler = SignalHandler::register( |
| 569 | SIGCONT, |
| 570 | SignalHandlerBehavior::Ignore, |
| 571 | &mut self.original_signals, |
| 572 | ) |
| 573 | .map_err(|err| dev_warn!("cannot set handler for SIGCONT: {err}")) |
| 574 | .ok(); |
| 575 | |
| 576 | if let SIGTTOU | SIGTTIN = signal { |
| 577 | // If sudo is already the foreground process we can resume the command in the |
| 578 | // foreground. Otherwise, we have to suspend and resume later. |
| 579 | if !self.foreground && self.check_foreground().is_err() { |
| 580 | // User's tty was revoked. |
| 581 | return None; |
| 582 | } |
| 583 | |
| 584 | if self.foreground { |
| 585 | dev_info!( |
| 586 | "command received {}, parent running in the foreground", |
| 587 | signal_fmt(signal) |
| 588 | ); |
| 589 | if !self.term_raw { |
| 590 | // Format the same as og-sudo to reduce risk of divergence |
| 591 | #[allow(clippy::collapsible_if)] |
| 592 | if self |
| 593 | .tty_pipe |
| 594 | .left_mut() |
| 595 | .set_raw_mode(false, self.preserve_oflag) |
| 596 | .is_ok() |
| 597 | { |
| 598 | self.term_raw = true; |
| 599 | } |
| 600 | } |
| 601 | // Resume command in the foreground |
| 602 | self.tty_pipe.enable_input(registry); |
| 603 | return Some(SIGCONT_FG); |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | // Stop polling the terminals. |
| 608 | self.tty_pipe.ignore_events(registry); |
| 609 | |
| 610 | if self.term_raw { |
| 611 | match self.tty_pipe.left_mut().restore(false) { |
| 612 | Ok(()) => self.term_raw = false, |
| 613 | Err(err) => dev_warn!("cannot restore terminal settings: {err}"), |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | let signal_handler = if signal != SIGSTOP { |
| 618 | SignalHandler::register( |
| 619 | signal, |
| 620 | SignalHandlerBehavior::Default, |
| 621 | &mut self.original_signals, |
| 622 | ) |
| 623 | .map_err(|err| dev_warn!("cannot set handler for {}: {err}", signal_fmt(signal))) |
| 624 | .ok() |
| 625 | } else { |
| 626 | None |
| 627 | }; |
| 628 | |
| 629 | if self.parent_pgrp != self.sudo_pid && kill(self.parent_pgrp, 0).is_err() |
| 630 | || killpg(self.parent_pgrp, signal).is_err() |
| 631 | { |
| 632 | dev_error!("no parent to suspend, terminating command"); |
| 633 | if let Some(command_pid) = self.command_pid.take() { |
| 634 | terminate_process(command_pid, true); |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | drop(signal_handler); |
| 639 | |
| 640 | if self.command_pid.is_none() || self.resume_terminal().is_err() { |
| 641 | return None; |
| 642 | } |
| 643 | |
| 644 | let ret_signal = if self.term_raw { |
| 645 | SIGCONT_FG |
| 646 | } else { |
| 647 | SIGCONT_BG |
| 648 | }; |
| 649 | |
| 650 | // Restore the handler for SIGCONT. |
| 651 | drop(sigcont_handler); |
| 652 | |
| 653 | Some(ret_signal) |
| 654 | } |
| 655 | |
| 656 | /// Check whether we are part of the foreground process group and update the foreground flag. |
| 657 | fn check_foreground(&mut self) -> io::Result<()> { |
| 658 | let pgrp = self.tty_pipe.left().tcgetpgrp()?; |
| 659 | self.foreground = pgrp == self.parent_pgrp; |
| 660 | Ok(()) |
| 661 | } |
| 662 | |
| 663 | /// Restore the terminal when sudo resumes after receiving `SIGCONT`. |
| 664 | fn resume_terminal(&mut self) -> io::Result<()> { |
| 665 | self.check_foreground()?; |
| 666 | |
| 667 | // Update the pty settings based on the user's tty. |
| 668 | self.tty_pipe |
| 669 | .left() |
| 670 | .copy_to(self.tty_pipe.right()) |
| 671 | .map_err(|err| { |
| 672 | dev_error!("cannot copy terminal settings to pty: {err}"); |
| 673 | err |
| 674 | })?; |
| 675 | // FIXME: sync the terminal size here. |
| 676 | dev_info!( |
| 677 | "parent is in {} ({} -> {})", |
| 678 | cond_fmt(self.foreground, "foreground", "background"), |
| 679 | cond_fmt(self.term_raw, "raw", "cooked"), |
| 680 | cond_fmt(self.foreground, "raw", "cooked"), |
| 681 | ); |
| 682 | |
| 683 | if self.foreground { |
| 684 | // We're in the foreground, set tty to raw mode. |
| 685 | if self |
| 686 | .tty_pipe |
| 687 | .left_mut() |
| 688 | .set_raw_mode(false, self.preserve_oflag) |
| 689 | .is_ok() |
| 690 | { |
| 691 | self.term_raw = true; |
| 692 | } |
| 693 | } else { |
| 694 | // We're in the background, cannot access tty. |
| 695 | self.term_raw = false; |
| 696 | } |
| 697 | |
| 698 | Ok(()) |
| 699 | } |
| 700 | |
| 701 | fn on_signal(&mut self, registry: &mut EventRegistry<Self>) { |
| 702 | let info = match self.signal_stream.recv() { |
| 703 | Ok(info) => info, |
| 704 | Err(err) => { |
| 705 | dev_error!("parent could not receive signal: {err}"); |
| 706 | return; |
| 707 | } |
| 708 | }; |
| 709 | |
| 710 | dev_info!("parent received{}", info); |
| 711 | |
| 712 | let Some(monitor_pid) = self.monitor_pid else { |
| 713 | dev_info!("monitor was terminated, ignoring signal"); |
| 714 | return; |
| 715 | }; |
| 716 | |
| 717 | match info.signal() { |
| 718 | SIGCHLD => handle_sigchld(self, registry, "monitor", monitor_pid), |
| 719 | SIGCONT => { |
| 720 | self.resume_terminal().ok(); |
| 721 | } |
| 722 | SIGWINCH => { |
| 723 | if let Err(err) = self.handle_sigwinch() { |
| 724 | dev_warn!("cannot resize terminal: {}", err); |
| 725 | } |
| 726 | } |
| 727 | signal => { |
| 728 | if let Some(pid) = info.signaler_pid() { |
| 729 | if self.is_self_terminating(pid) { |
| 730 | // Skip the signal if it was sent by the user and it is self-terminating. |
| 731 | return; |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | // FIXME: check `send_command_status` |
| 736 | self.schedule_signal(signal, registry) |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | fn handle_sigwinch(&mut self) -> io::Result<()> { |
| 742 | let new_size = self.tty_pipe.left().get_size()?; |
| 743 | |
| 744 | if new_size != self.tty_size { |
| 745 | dev_info!("updating pty size from {} to {new_size}", self.tty_size); |
| 746 | // Set the pty size. |
| 747 | self.tty_pipe.right().set_size(&new_size)?; |
| 748 | // Send SIGWINCH to the command. |
| 749 | if let Some(command_pid) = self.command_pid { |
| 750 | killpg(command_pid, SIGWINCH).ok(); |
| 751 | } |
| 752 | // Update the terminal size. |
| 753 | self.tty_size = new_size; |
| 754 | } |
| 755 | |
| 756 | Ok(()) |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | enum ParentExit { |
| 761 | /// Error while reading from the backchannel. |
| 762 | Backchannel(io::Error), |
| 763 | /// The command exited. |
| 764 | Command(ExitReason), |
| 765 | } |
| 766 | |
| 767 | impl From<io::Error> for ParentExit { |
| 768 | fn from(err: io::Error) -> Self { |
| 769 | Self::Backchannel(err) |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | impl From<ExitReason> for ParentExit { |
| 774 | fn from(reason: ExitReason) -> Self { |
| 775 | Self::Command(reason) |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 780 | enum ParentEvent { |
| 781 | Signal, |
| 782 | Tty(PollEvent), |
| 783 | Pty(PollEvent), |
| 784 | Backchannel(PollEvent), |
| 785 | } |
| 786 | |
| 787 | impl Process for ParentClosure { |
| 788 | type Event = ParentEvent; |
| 789 | type Break = io::Error; |
| 790 | type Exit = ParentExit; |
| 791 | |
| 792 | fn on_event(&mut self, event: Self::Event, registry: &mut EventRegistry<Self>) { |
| 793 | match event { |
| 794 | ParentEvent::Signal => self.on_signal(registry), |
| 795 | ParentEvent::Tty(poll_event) => { |
| 796 | // Check if tty which existed is now gone. |
| 797 | if self.tty_pipe.left().tcgetsid().is_err() { |
| 798 | dev_warn!("tty gone (closed/detached), ignoring future events"); |
| 799 | self.tty_pipe.ignore_events(registry); |
| 800 | } else { |
| 801 | self.tty_pipe.on_left_event(poll_event, registry).ok(); |
| 802 | } |
| 803 | } |
| 804 | ParentEvent::Pty(poll_event) => { |
| 805 | self.tty_pipe.on_right_event(poll_event, registry).ok(); |
| 806 | } |
| 807 | ParentEvent::Backchannel(poll_event) => match poll_event { |
| 808 | PollEvent::Readable => self.on_message_received(registry), |
| 809 | PollEvent::Writable => self.check_message_queue(registry), |
| 810 | }, |
| 811 | } |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | impl HandleSigchld for ParentClosure { |
| 816 | const OPTIONS: WaitOptions = WaitOptions::new().all().untraced().no_hang(); |
| 817 | |
| 818 | fn on_exit(&mut self, _exit_code: c_int, _registry: &mut EventRegistry<Self>) { |
| 819 | self.monitor_pid = None; |
| 820 | } |
| 821 | |
| 822 | fn on_term(&mut self, _signal: SignalNumber, _registry: &mut EventRegistry<Self>) { |
| 823 | self.monitor_pid = None; |
| 824 | } |
| 825 | |
| 826 | fn on_stop(&mut self, signal: SignalNumber, registry: &mut EventRegistry<Self>) { |
| 827 | if let Some(signal) = self.suspend_pty(signal, registry) { |
| 828 | self.schedule_signal(signal, registry); |
| 829 | } |
| 830 | self.tty_pipe.resume_events(registry); |
| 831 | } |
| 832 | } |