| 1 | //! This module is a port of ogsudo's `lib/util/term.c` with some minor changes to make it |
| 2 | //! rust-like. |
| 3 | |
| 4 | use std::{ |
| 5 | ffi::{c_int, c_void}, |
| 6 | fs::{File, OpenOptions}, |
| 7 | io::{self, Read, Write}, |
| 8 | mem::MaybeUninit, |
| 9 | os::fd::{AsFd, AsRawFd, BorrowedFd}, |
| 10 | sync::atomic::{AtomicBool, Ordering}, |
| 11 | }; |
| 12 | |
| 13 | use libc::{ |
| 14 | CS7, CS8, ECHO, ECHOCTL, ECHOE, ECHOK, ECHOKE, ECHONL, ICANON, ICRNL, IEXTEN, IGNCR, IGNPAR, |
| 15 | IMAXBEL, INLCR, INPCK, ISIG, ISTRIP, IXANY, IXOFF, IXON, NOFLSH, OCRNL, ONLCR, ONLRET, ONOCR, |
| 16 | OPOST, PARENB, PARMRK, PARODD, PENDIN, SIGTTOU, TCSADRAIN, TCSAFLUSH, TIOCGWINSZ, TIOCSWINSZ, |
| 17 | TOSTOP, cfgetispeed, cfgetospeed, cfmakeraw, cfsetispeed, cfsetospeed, ioctl, sigaction, |
| 18 | sigemptyset, sighandler_t, siginfo_t, sigset_t, tcflag_t, tcgetattr, tcsetattr, termios, |
| 19 | winsize, |
| 20 | }; |
| 21 | #[cfg(target_os = "linux")] |
| 22 | use libc::{IUTF8, OLCUC}; |
| 23 | |
| 24 | #[cfg(not(target_os = "linux"))] |
| 25 | const IUTF8: libc::tcflag_t = 0; |
| 26 | #[cfg(not(target_os = "linux"))] |
| 27 | const OLCUC: libc::tcflag_t = 0; |
| 28 | |
| 29 | use super::{TermSize, Terminal}; |
| 30 | use crate::{ |
| 31 | cutils::cerr, |
| 32 | system::{interface::ProcessId, make_zeroed_sigaction}, |
| 33 | }; |
| 34 | |
| 35 | const INPUT_FLAGS: tcflag_t = IGNPAR |
| 36 | | PARMRK |
| 37 | | INPCK |
| 38 | | ISTRIP |
| 39 | | INLCR |
| 40 | | IGNCR |
| 41 | | ICRNL |
| 42 | // | IUCLC /* FIXME: not in libc */ |
| 43 | | IXON |
| 44 | | IXANY |
| 45 | | IXOFF |
| 46 | | IMAXBEL |
| 47 | | IUTF8; |
| 48 | const OUTPUT_FLAGS: tcflag_t = OPOST | OLCUC | ONLCR | OCRNL | ONOCR | ONLRET; |
| 49 | const CONTROL_FLAGS: tcflag_t = CS7 | CS8 | PARENB | PARODD; |
| 50 | const LOCAL_FLAGS: tcflag_t = ISIG |
| 51 | | ICANON |
| 52 | // | XCASE /* FIXME: not in libc */ |
| 53 | | ECHO |
| 54 | | ECHOE |
| 55 | | ECHOK |
| 56 | | ECHONL |
| 57 | | NOFLSH |
| 58 | | TOSTOP |
| 59 | | IEXTEN |
| 60 | | ECHOCTL |
| 61 | | ECHOKE |
| 62 | | PENDIN; |
| 63 | |
| 64 | static GOT_SIGTTOU: AtomicBool = AtomicBool::new(false); |
| 65 | |
| 66 | /// This is like `tcsetattr` but it only succeeds if we are in the foreground process group. |
| 67 | /// # Safety |
| 68 | /// |
| 69 | /// The arguments to this function have to be valid arguments to `tcsetattr`. |
| 70 | unsafe fn tcsetattr_nobg(fd: c_int, flags: c_int, tp: *const termios) -> io::Result<()> { |
| 71 | // This function is based around the fact that we receive `SIGTTOU` if we call `tcsetattr` and |
| 72 | // we are not in the foreground process group. |
| 73 | |
| 74 | // SAFETY: is the responsibility of the caller of `tcsetattr_nobg` |
| 75 | let setattr = || cerr(unsafe { tcsetattr(fd, flags, tp) }).map(|_| ()); |
| 76 | |
| 77 | catching_sigttou(setattr) |
| 78 | } |
| 79 | |
| 80 | fn catching_sigttou(mut function: impl FnMut() -> io::Result<()>) -> io::Result<()> { |
| 81 | extern "C" fn on_sigttou(_signal: c_int, _info: *mut siginfo_t, _: *mut c_void) { |
| 82 | GOT_SIGTTOU.store(true, Ordering::SeqCst); |
| 83 | } |
| 84 | |
| 85 | let action = { |
| 86 | let mut raw: libc::sigaction = make_zeroed_sigaction(); |
| 87 | // Call `on_sigttou` if `SIGTTOU` arrives. |
| 88 | raw.sa_sigaction = on_sigttou as *const () as sighandler_t; |
| 89 | // Exclude any other signals from the set |
| 90 | raw.sa_mask = { |
| 91 | let mut sa_mask = MaybeUninit::<sigset_t>::uninit(); |
| 92 | // SAFETY: sa_mask is a valid and dereferenceble pointer; it will |
| 93 | // become initialized by `sigemptyset` |
| 94 | unsafe { |
| 95 | sigemptyset(sa_mask.as_mut_ptr()); |
| 96 | sa_mask.assume_init() |
| 97 | } |
| 98 | }; |
| 99 | raw.sa_flags = 0; |
| 100 | raw |
| 101 | }; |
| 102 | // Reset `GOT_SIGTTOU`. |
| 103 | GOT_SIGTTOU.store(false, Ordering::SeqCst); |
| 104 | |
| 105 | // Set `action` as the action for `SIGTTOU` and store the original action in `original_action` |
| 106 | // to restore it later. |
| 107 | // |
| 108 | // SAFETY: `original_action` is a valid pointer; second, the `action` installed (on_sigttou): |
| 109 | // - is itself a safe function |
| 110 | // - only updates an atomic variable, so cannot violate memory unsafety that way |
| 111 | // - doesn't call any async-unsafe functions (refer to signal-safety(7)) |
| 112 | // Therefore it can safely be installed as a signal handler. |
| 113 | // Furthermore, `sigaction` will initialize `original_action`. |
| 114 | let original_action = unsafe { |
| 115 | let mut original_action = MaybeUninit::<sigaction>::uninit(); |
| 116 | sigaction(SIGTTOU, &action, original_action.as_mut_ptr()); |
| 117 | original_action.assume_init() |
| 118 | }; |
| 119 | |
| 120 | // Call `tcsetattr` until it suceeds and ignore interruptions if we did not receive `SIGTTOU`. |
| 121 | let result = loop { |
| 122 | match function() { |
| 123 | Ok(_) => break Ok(()), |
| 124 | Err(err) => { |
| 125 | let got_sigttou = GOT_SIGTTOU.load(Ordering::SeqCst); |
| 126 | if got_sigttou || err.kind() != io::ErrorKind::Interrupted { |
| 127 | break Err(err); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | }; |
| 132 | |
| 133 | // Restore the original action. |
| 134 | // |
| 135 | // SAFETY: `original_action` is a valid pointer, and was initialized by the preceding |
| 136 | // call to `sigaction` (and not subsequently altered, since it is not mut). The third parameter |
| 137 | // is allowed to be NULL (this means we ignore the previously-installed handler) |
| 138 | unsafe { sigaction(SIGTTOU, &original_action, std::ptr::null_mut()) }; |
| 139 | |
| 140 | result |
| 141 | } |
| 142 | |
| 143 | /// Type to manipulate the settings of the user's terminal. |
| 144 | pub struct UserTerm { |
| 145 | tty: File, |
| 146 | original_termios: Option<termios>, |
| 147 | } |
| 148 | |
| 149 | impl UserTerm { |
| 150 | /// Open the user's terminal. |
| 151 | pub fn open() -> io::Result<Self> { |
| 152 | Ok(Self { |
| 153 | tty: OpenOptions::new().read(true).write(true).open("/dev/tty")?, |
| 154 | original_termios: None, |
| 155 | }) |
| 156 | } |
| 157 | |
| 158 | pub(crate) fn get_size(&self) -> io::Result<TermSize> { |
| 159 | let mut term_size = MaybeUninit::<TermSize>::uninit(); |
| 160 | |
| 161 | // SAFETY: This passes a valid file descriptor and valid pointer (of |
| 162 | // the correct type) to the TIOCGWINSZ ioctl; see: |
| 163 | // https://man7.org/linux/man-pages/man2/TIOCGWINSZ.2const.html |
| 164 | cerr(unsafe { |
| 165 | ioctl( |
| 166 | self.tty.as_raw_fd(), |
| 167 | TIOCGWINSZ, |
| 168 | term_size.as_mut_ptr().cast::<winsize>(), |
| 169 | ) |
| 170 | })?; |
| 171 | |
| 172 | // SAFETY: if we arrived at this point, `term_size` was initialized. |
| 173 | Ok(unsafe { term_size.assume_init() }) |
| 174 | } |
| 175 | |
| 176 | /// Copy the settings of the user's terminal to the `dst` terminal. |
| 177 | pub fn copy_to<D: AsFd>(&self, dst: &D) -> io::Result<()> { |
| 178 | let src = self.tty.as_raw_fd(); |
| 179 | let dst = dst.as_fd().as_raw_fd(); |
| 180 | |
| 181 | // SAFETY: tt_src and tt_dst will be initialized by `tcgetattr`. |
| 182 | let (tt_src, mut tt_dst) = unsafe { |
| 183 | let mut tt_src = MaybeUninit::<termios>::uninit(); |
| 184 | let mut tt_dst = MaybeUninit::<termios>::uninit(); |
| 185 | |
| 186 | cerr(tcgetattr(src, tt_src.as_mut_ptr()))?; |
| 187 | cerr(tcgetattr(dst, tt_dst.as_mut_ptr()))?; |
| 188 | |
| 189 | (tt_src.assume_init(), tt_dst.assume_init()) |
| 190 | }; |
| 191 | |
| 192 | // Clear select input, output, control and local flags. |
| 193 | tt_dst.c_iflag &= !INPUT_FLAGS; |
| 194 | tt_dst.c_oflag &= !OUTPUT_FLAGS; |
| 195 | tt_dst.c_cflag &= !CONTROL_FLAGS; |
| 196 | tt_dst.c_lflag &= !LOCAL_FLAGS; |
| 197 | |
| 198 | // Copy select input, output, control and local flags. |
| 199 | tt_dst.c_iflag |= tt_src.c_iflag & INPUT_FLAGS; |
| 200 | tt_dst.c_oflag |= tt_src.c_oflag & OUTPUT_FLAGS; |
| 201 | tt_dst.c_cflag |= tt_src.c_cflag & CONTROL_FLAGS; |
| 202 | tt_dst.c_lflag |= tt_src.c_lflag & LOCAL_FLAGS; |
| 203 | |
| 204 | // Copy special chars from src verbatim. |
| 205 | tt_dst.c_cc.copy_from_slice(&tt_src.c_cc); |
| 206 | |
| 207 | // Copy speed from `src`. |
| 208 | // |
| 209 | // SAFETY: the cfXXXXspeed calls are passed valid pointers and |
| 210 | // cannot cause UB even if the speed would be incorrect. |
| 211 | unsafe { |
| 212 | let mut speed = cfgetospeed(&tt_src); |
| 213 | // Zero output speed closes the connection. |
| 214 | if speed == libc::B0 { |
| 215 | speed = libc::B38400; |
| 216 | } |
| 217 | cfsetospeed(&mut tt_dst, speed); |
| 218 | |
| 219 | speed = cfgetispeed(&tt_src); |
| 220 | cfsetispeed(&mut tt_dst, speed); |
| 221 | } |
| 222 | |
| 223 | // SAFETY: dst is a valid file descriptor and `tt_dst` is an |
| 224 | // initialized struct obtained through tcgetattr; so this is safe to |
| 225 | // pass to `tcsetattr`. |
| 226 | unsafe { tcsetattr_nobg(dst, TCSAFLUSH, &tt_dst) }?; |
| 227 | |
| 228 | let mut wsize = MaybeUninit::<winsize>::uninit(); |
| 229 | // SAFETY: TIOCGWINSZ ioctl expects one argument of type *mut winsize |
| 230 | cerr(unsafe { ioctl(src, TIOCGWINSZ, wsize.as_mut_ptr()) })?; |
| 231 | // SAFETY: wsize has been initialized by the TIOCGWINSZ ioctl |
| 232 | cerr(unsafe { ioctl(dst, TIOCSWINSZ, wsize.as_ptr()) })?; |
| 233 | |
| 234 | Ok(()) |
| 235 | } |
| 236 | |
| 237 | /// Set the user's terminal to raw mode. Enable terminal signals if `with_signals` is set to |
| 238 | /// `true`. |
| 239 | pub fn set_raw_mode(&mut self, with_signals: bool, preserve_oflag: bool) -> io::Result<()> { |
| 240 | let fd = self.tty.as_raw_fd(); |
| 241 | |
| 242 | // Retrieve the original terminal (if we haven't done so already) |
| 243 | let mut term = if let Some(termios) = self.original_termios { |
| 244 | termios |
| 245 | } else { |
| 246 | // SAFETY: `termios` is a valid pointer to pass to tcgetattr; if that calls succeeds, |
| 247 | // it will have initialized the `termios` structure |
| 248 | *self.original_termios.insert(unsafe { |
| 249 | let mut termios = MaybeUninit::uninit(); |
| 250 | cerr(tcgetattr(fd, termios.as_mut_ptr()))?; |
| 251 | termios.assume_init() |
| 252 | }) |
| 253 | }; |
| 254 | |
| 255 | // Set terminal to raw mode. |
| 256 | let oflag = term.c_oflag; |
| 257 | // SAFETY: `term` is a valid, initialized struct of type `termios`, which |
| 258 | // was previously obtained through `tcgetattr`. |
| 259 | unsafe { cfmakeraw(&mut term) }; |
| 260 | if preserve_oflag { |
| 261 | term.c_oflag = oflag; |
| 262 | } |
| 263 | // Enable terminal signals. |
| 264 | if with_signals { |
| 265 | term.c_cflag |= ISIG; |
| 266 | } |
| 267 | |
| 268 | // SAFETY: `fd` is a valid file descriptor for the tty; for `term`: same as above. |
| 269 | unsafe { tcsetattr_nobg(fd, TCSADRAIN, &term) }?; |
| 270 | |
| 271 | Ok(()) |
| 272 | } |
| 273 | |
| 274 | /// Restore the saved terminal settings if we are in the foreground process group. |
| 275 | /// |
| 276 | /// This change is done after waiting for all the queued output to be written. To discard the |
| 277 | /// queued input `flush` must be set to `true`. |
| 278 | pub fn restore(&mut self, flush: bool) -> io::Result<()> { |
| 279 | if let Some(termios) = self.original_termios.take() { |
| 280 | let fd = self.tty.as_raw_fd(); |
| 281 | let flags = if flush { TCSAFLUSH } else { TCSADRAIN }; |
| 282 | // SAFETY: `fd` is a valid file descriptor for the tty; and `termios` is a valid pointer |
| 283 | // that was obtained through `tcgetattr`. |
| 284 | unsafe { tcsetattr_nobg(fd, flags, &termios) }?; |
| 285 | } |
| 286 | |
| 287 | Ok(()) |
| 288 | } |
| 289 | |
| 290 | /// This is like `tcsetpgrp` but it only suceeds if we are in the foreground process group. |
| 291 | pub fn tcsetpgrp_nobg(&self, pgrp: ProcessId) -> io::Result<()> { |
| 292 | // This function is based around the fact that we receive `SIGTTOU` if we call `tcsetpgrp` and |
| 293 | // we are not in the foreground process group. |
| 294 | |
| 295 | catching_sigttou(|| self.tcsetpgrp(pgrp)) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | impl AsFd for UserTerm { |
| 300 | fn as_fd(&self) -> BorrowedFd<'_> { |
| 301 | self.tty.as_fd() |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | impl Read for UserTerm { |
| 306 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 307 | self.tty.read(buf) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | impl Write for UserTerm { |
| 312 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 313 | self.tty.write(buf) |
| 314 | } |
| 315 | |
| 316 | fn flush(&mut self) -> io::Result<()> { |
| 317 | self.tty.flush() |
| 318 | } |
| 319 | } |