uncurses/terminal/raw.rs
1//! Raw mode and terminal state helpers.
2//!
3//! These free functions operate on terminal descriptors on Unix and console
4//! handles on Windows. [`make_raw_mode`] saves the current configuration,
5//! applies raw-mode settings immediately, and returns the previous [`State`].
6//! Pass that state to [`set_state`] with the same handles to restore it.
7//!
8//! ```text
9//! get_state() ── snapshot only ───────────────────────────────┐
10//! │
11//! make_raw_mode() ── returns previous State ── raw mode ── set_state()
12//! ```
13//!
14//! The input and output halves are tracked separately. Nothing requires them
15//! to be the same device: [`Terminal`](super::Terminal) is generic over its
16//! two descriptors, so a caller can pair two unrelated terminals, or pair a
17//! terminal with a pipe. Each half is read, rawified, and restored from its
18//! own attributes, and a half that is not a terminal is skipped.
19//!
20//! [`Terminal::make_raw`](super::Terminal::make_raw) and
21//! [`Terminal::restore`](super::Terminal::restore) wrap this same flow and keep
22//! one saved state inside the terminal handle.
23
24use std::io;
25
26#[cfg(unix)]
27use std::os::fd::{AsFd, AsRawFd};
28#[cfg(windows)]
29use std::os::windows::io::{AsHandle, AsRawHandle};
30#[cfg(windows)]
31use windows_sys::Win32::Foundation::HANDLE;
32
33/// Snapshot of a terminal's configuration.
34///
35/// On Unix this stores one `libc::termios` per half, because the input and
36/// output descriptors are not required to refer to the same terminal device. A
37/// half whose attributes cannot be read is stored as `None` and is skipped when
38/// the state is applied. On Windows it stores both input and output
39/// console-mode bitfields.
40///
41/// A `State` records each half separately, so it is bound to the pair it was
42/// read from. Apply it to that same `(input, output)` pair; applying it to a
43/// different pair writes each half's attributes to a descriptor they did not
44/// come from.
45///
46/// Use values returned by [`Terminal::get_state`](crate::terminal::Terminal::get_state)
47/// or [`Terminal::make_raw`](crate::terminal::Terminal::make_raw) with
48/// [`Terminal::set_state`](crate::terminal::Terminal::set_state) to restore a
49/// terminal to a previous configuration.
50///
51/// The fields are readable so a caller can inspect what was saved — a snapshot
52/// taken before raw mode is otherwise unrecoverable, since re-reading the
53/// descriptor afterwards reports the raw state rather than this one. Both
54/// platforms name the halves `input` and `output`, but what they hold is
55/// inherently platform-specific: a `termios` and a console mode are not the
56/// same concept, so there is no portable shape to offer instead and code that
57/// reads them is unix-only or Windows-only by nature. The unix types come from
58/// the [`libc`](crate::libc) re-export.
59///
60/// The struct is `non_exhaustive`: a `State` is only meaningful when it came
61/// from the terminal, so it is readable but not constructible from outside the
62/// crate.
63///
64/// # Examples
65///
66/// ```no_run
67/// # #[cfg(unix)] {
68/// use uncurses::libc;
69/// use uncurses::terminal::Terminal;
70///
71/// let mut term = Terminal::stdio();
72/// let saved = term.make_raw().unwrap();
73///
74/// // Reading the descriptor now would report the raw state, so this snapshot
75/// // is the only way to see what the terminal looked like beforehand.
76/// if let Some(input) = saved.input {
77/// println!("echo was on: {}", input.c_lflag & libc::ECHO != 0);
78/// }
79/// # }
80/// ```
81#[derive(Clone, Debug)]
82#[non_exhaustive]
83pub struct State {
84 #[cfg(unix)]
85 /// Saved attributes of the input descriptor, or `None` when they could not
86 /// be read — typically because it is not a terminal.
87 pub input: Option<libc::termios>,
88 #[cfg(unix)]
89 /// Saved attributes of the output descriptor, or `None` when they could not
90 /// be read — typically because it is not a terminal.
91 pub output: Option<libc::termios>,
92 #[cfg(windows)]
93 /// Saved console-mode bits of the input handle.
94 pub input: u32,
95 #[cfg(windows)]
96 /// Saved console-mode bits of the output handle.
97 pub output: u32,
98}
99
100/// Return whether `state` delivers input as VT bytes.
101///
102/// On Windows, this checks `ENABLE_VIRTUAL_TERMINAL_INPUT` in the saved input
103/// console mode. Pass the result to
104/// [`EventSource::set_vt_input`](crate::event::EventSource::set_vt_input)
105/// after a console mode change. Unix input is always VT bytes, so this
106/// returns `true` on Unix.
107///
108/// ```no_run
109/// use uncurses::event::EventSource;
110/// use uncurses::terminal::{Terminal, has_vt_input};
111///
112/// # fn main() -> std::io::Result<()> {
113/// let mut term = Terminal::stdio();
114/// let mut events = EventSource::new(term.input())?;
115/// term.make_raw()?;
116/// events.set_vt_input(has_vt_input(&term.get_state()?));
117/// # term.restore()
118/// # }
119/// ```
120pub fn has_vt_input(state: &State) -> bool {
121 #[cfg(windows)]
122 {
123 use windows_sys::Win32::System::Console::ENABLE_VIRTUAL_TERMINAL_INPUT;
124 state.input & ENABLE_VIRTUAL_TERMINAL_INPUT != 0
125 }
126 #[cfg(not(windows))]
127 {
128 let _ = state;
129 true
130 }
131}
132
133#[cfg(windows)]
134unsafe impl Send for State {}
135#[cfg(windows)]
136unsafe impl Sync for State {}
137
138/// Read the current terminal state.
139///
140/// On Unix each descriptor is read independently, so a pair pointing at two
141/// different terminal devices is described in full and a half that is not a
142/// terminal is recorded as `None`. On Windows both input and output console
143/// modes are sampled.
144///
145/// # Parameters
146///
147/// * `input` — terminal input descriptor or handle.
148/// * `output` — terminal output descriptor or handle.
149///
150/// # Returns
151///
152/// A [`State`] describing the current terminal mode.
153///
154/// # Errors
155///
156/// Returns the OS error from the state query. On Unix, an error is returned
157/// only if the attributes of neither descriptor can be read — typically
158/// because neither is a terminal — and the output descriptor's error is the
159/// one reported.
160///
161/// # Panics
162///
163/// This function does not intentionally panic.
164#[cfg(unix)]
165pub fn get_state<I: AsFd, O: AsFd>(input: I, output: O) -> io::Result<State> {
166 use std::mem::MaybeUninit;
167
168 fn try_read(fd: i32) -> io::Result<libc::termios> {
169 let mut t = MaybeUninit::<libc::termios>::uninit();
170 if unsafe { libc::tcgetattr(fd, t.as_mut_ptr()) } != 0 {
171 return Err(io::Error::last_os_error());
172 }
173 Ok(unsafe { t.assume_init() })
174 }
175
176 let input = try_read(input.as_fd().as_raw_fd()).ok();
177 let output = try_read(output.as_fd().as_raw_fd());
178 match (input, output) {
179 // Neither half is a terminal. Report the output error, which is what
180 // this function surfaced when it fell back from input to output.
181 (None, Err(e)) => Err(e),
182 (input, output) => Ok(State {
183 input,
184 output: output.ok(),
185 }),
186 }
187}
188
189/// Apply `state` to the terminal immediately.
190///
191/// On Unix this uses `TCSANOW` and writes each half of `state` to its own
192/// descriptor; a half recorded as `None` is skipped. Both halves are attempted
193/// even if the first one fails, so a partial failure still restores as much as
194/// it can. On Windows both modes stored in [`State`] are written.
195///
196/// When the two descriptors refer to the same terminal, this applies identical
197/// attributes to that device twice. `tcsetattr` is idempotent, so the second
198/// call is a no-op.
199///
200/// # Parameters
201///
202/// * `input` — terminal input descriptor or handle.
203/// * `output` — terminal output descriptor or handle.
204/// * `state` — state previously returned by [`get_state`] or
205/// [`make_raw_mode`].
206///
207/// # Returns
208///
209/// `Ok(())` when every half recorded in `state` was applied.
210///
211/// # Errors
212///
213/// Returns the OS error from applying the state; the input descriptor's error
214/// is the one reported when both halves fail. A half recorded as `None` is not
215/// an error. If one half fails after the other succeeded, the successful half
216/// is not rolled back.
217///
218/// # Panics
219///
220/// This function does not intentionally panic.
221#[cfg(unix)]
222pub fn set_state<I: AsFd, O: AsFd>(input: I, output: O, state: &State) -> io::Result<()> {
223 fn try_write(fd: i32, termios: Option<&libc::termios>) -> io::Result<()> {
224 let Some(termios) = termios else {
225 return Ok(());
226 };
227 if unsafe { libc::tcsetattr(fd, libc::TCSANOW, termios) } != 0 {
228 return Err(io::Error::last_os_error());
229 }
230 Ok(())
231 }
232
233 let applied_input = try_write(input.as_fd().as_raw_fd(), state.input.as_ref());
234 let applied_output = try_write(output.as_fd().as_raw_fd(), state.output.as_ref());
235 applied_input.and(applied_output)
236}
237
238#[cfg(windows)]
239/// Read the current console modes.
240///
241/// Both input and output handles must support `GetConsoleMode`.
242///
243/// # Parameters
244///
245/// * `input` — console input handle.
246/// * `output` — console output handle.
247///
248/// # Returns
249///
250/// A [`State`] containing both console-mode bitfields.
251///
252/// # Errors
253///
254/// Returns the OS error if either console mode cannot be read.
255///
256/// # Panics
257///
258/// This function does not intentionally panic.
259pub fn get_state<I: AsHandle, O: AsHandle>(input: I, output: O) -> io::Result<State> {
260 use windows_sys::Win32::System::Console::GetConsoleMode;
261
262 let ih = input.as_handle().as_raw_handle() as HANDLE;
263 let oh = output.as_handle().as_raw_handle() as HANDLE;
264
265 let mut input_mode: u32 = 0;
266 if unsafe { GetConsoleMode(ih, &mut input_mode) } == 0 {
267 return Err(io::Error::last_os_error());
268 }
269 let mut output_mode: u32 = 0;
270 if unsafe { GetConsoleMode(oh, &mut output_mode) } == 0 {
271 return Err(io::Error::last_os_error());
272 }
273 Ok(State {
274 input: input_mode,
275 output: output_mode,
276 })
277}
278
279#[cfg(windows)]
280/// Apply console modes from `state`.
281///
282/// # Parameters
283///
284/// * `input` — console input handle.
285/// * `output` — console output handle.
286/// * `state` — console modes to apply.
287///
288/// # Returns
289///
290/// `Ok(())` when both input and output modes were applied.
291///
292/// # Errors
293///
294/// Returns the OS error if either `SetConsoleMode` call fails; the input
295/// handle's error is the one reported when both fail. Both handles are
296/// attempted even if the first one fails, so a partial failure still restores
297/// as much as it can. If one handle fails after the other succeeded, the
298/// successful one is not rolled back.
299///
300/// # Panics
301///
302/// This function does not intentionally panic.
303pub fn set_state<I: AsHandle, O: AsHandle>(input: I, output: O, state: &State) -> io::Result<()> {
304 set_state_with_input(input, output, state, |_| {})
305}
306
307#[cfg(windows)]
308pub(super) fn set_state_with_input<I: AsHandle, O: AsHandle>(
309 input: I,
310 output: O,
311 state: &State,
312 on_input: impl FnOnce(u32),
313) -> io::Result<()> {
314 use windows_sys::Win32::System::Console::SetConsoleMode;
315
316 fn try_write(handle: HANDLE, mode: u32) -> io::Result<()> {
317 if unsafe { SetConsoleMode(handle, mode) } == 0 {
318 return Err(io::Error::last_os_error());
319 }
320 Ok(())
321 }
322
323 let ih = input.as_handle().as_raw_handle() as HANDLE;
324 let oh = output.as_handle().as_raw_handle() as HANDLE;
325
326 let applied_input = try_write(ih, state.input);
327 if applied_input.is_ok() {
328 // Input observers must update even if the output mode fails.
329 on_input(state.input);
330 }
331 let applied_output = try_write(oh, state.output);
332 applied_input.and(applied_output)
333}
334
335/// Place the terminal into raw mode.
336///
337/// On Unix this applies a `cfmakeraw(3)`-equivalent termios (`VMIN = 1`,
338/// `VTIME = 0`) using [`set_state`]. The flags match glibc's `cfmakeraw` on
339/// every platform, so raw mode behaves identically everywhere rather than
340/// following each libc's own variation. Each descriptor is rawified from its
341/// own saved attributes, so a pair pointing at two different terminal devices
342/// leaves both in raw mode.
343///
344/// On Windows, raw mode clears cooked input, Quick Edit, and console mouse input
345/// flags. It enables virtual-terminal input and window input. The output handle
346/// has processed output, virtual-terminal processing, and newline-auto-return
347/// disabling set.
348///
349/// # Parameters
350///
351/// * `input` — terminal input descriptor or handle.
352/// * `output` — terminal output descriptor or handle.
353///
354/// # Returns
355///
356/// The pre-call [`State`]. Pass it to [`set_state`] to restore.
357///
358/// # Errors
359///
360/// Returns any error from reading the current state or applying the raw state.
361/// When only one half of a split pair accepts the raw state, the pre-call state
362/// is written back to both halves before the error is returned, so a failure
363/// does not leave a descriptor raw with no way to restore it. That write-back
364/// is best-effort: if it fails too, the original error is still what surfaces.
365///
366/// # Panics
367///
368/// This function does not intentionally panic.
369#[cfg(unix)]
370pub fn make_raw_mode<I: AsFd, O: AsFd>(input: I, output: O) -> io::Result<State> {
371 fn rawify(mut t: libc::termios) -> libc::termios {
372 t.c_iflag &= !(libc::IGNBRK
373 | libc::BRKINT
374 | libc::PARMRK
375 | libc::ISTRIP
376 | libc::INLCR
377 | libc::IGNCR
378 | libc::ICRNL
379 | libc::IXON);
380 t.c_oflag &= !libc::OPOST;
381 t.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
382 t.c_cflag &= !(libc::CSIZE | libc::PARENB);
383 t.c_cflag |= libc::CS8;
384 t.c_cc[libc::VMIN] = 1;
385 t.c_cc[libc::VTIME] = 0;
386 t
387 }
388
389 let original = get_state(&input, &output)?;
390 let raw = State {
391 input: original.input.map(rawify),
392 output: original.output.map(rawify),
393 };
394 if let Err(e) = set_state(&input, &output, &raw) {
395 // One half may have been rawified before the other failed, and the
396 // caller drops `original` along with the error. Put the pre-call state
397 // back so no descriptor is stranded in raw mode; the half that failed
398 // is simply rewritten its own unchanged attributes.
399 let _ = set_state(&input, &output, &original);
400 return Err(e);
401 }
402 Ok(original)
403}
404
405#[cfg(windows)]
406/// Place the console into raw mode.
407///
408/// The input handle has cooked input flags, quick edit, and console mouse input
409/// cleared, with virtual-terminal/window input flags set. The output handle has
410/// virtual-terminal processing and newline-auto-return disabling set.
411///
412/// Applications select mouse reporting through terminal escape sequences.
413/// Clearing console mouse input prevents ConPTY from enabling tracking itself.
414///
415/// # Parameters
416///
417/// * `input` — console input handle.
418/// * `output` — console output handle.
419///
420/// # Returns
421///
422/// The pre-call [`State`]. Pass it to [`set_state`] to restore.
423///
424/// # Errors
425///
426/// Returns any error from reading the current modes or applying the raw modes.
427/// When only one handle accepts the raw modes, the pre-call modes are written
428/// back to both handles before the error is returned, so a failure does not
429/// leave a handle raw with no way to restore it. That write-back is
430/// best-effort: if it fails too, the original error is still what surfaces.
431///
432/// # Panics
433///
434/// This function does not intentionally panic.
435pub fn make_raw_mode<I: AsHandle, O: AsHandle>(input: I, output: O) -> io::Result<State> {
436 use windows_sys::Win32::System::Console::{
437 DISABLE_NEWLINE_AUTO_RETURN, ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS, ENABLE_LINE_INPUT,
438 ENABLE_MOUSE_INPUT, ENABLE_PROCESSED_INPUT, ENABLE_PROCESSED_OUTPUT,
439 ENABLE_QUICK_EDIT_MODE, ENABLE_VIRTUAL_TERMINAL_INPUT, ENABLE_VIRTUAL_TERMINAL_PROCESSING,
440 ENABLE_WINDOW_INPUT,
441 };
442
443 let original = get_state(&input, &output)?;
444 // Clearing quick-edit while setting extended-flags is how the console API
445 // disables mouse selection, which would otherwise swallow mouse input.
446 // Console mouse input would make ConPTY enable tracking independently.
447 let raw_input = (original.input
448 & !(ENABLE_ECHO_INPUT
449 | ENABLE_PROCESSED_INPUT
450 | ENABLE_LINE_INPUT
451 | ENABLE_QUICK_EDIT_MODE
452 | ENABLE_MOUSE_INPUT))
453 | ENABLE_VIRTUAL_TERMINAL_INPUT
454 | ENABLE_EXTENDED_FLAGS
455 | ENABLE_WINDOW_INPUT;
456 // Virtual-terminal processing requires processed output, so set it too.
457 let raw_output = original.output
458 | ENABLE_PROCESSED_OUTPUT
459 | ENABLE_VIRTUAL_TERMINAL_PROCESSING
460 | DISABLE_NEWLINE_AUTO_RETURN;
461
462 let raw = State {
463 input: raw_input,
464 output: raw_output,
465 };
466 if let Err(e) = set_state(&input, &output, &raw) {
467 // One handle may have been switched to raw mode before the other
468 // failed, and the caller drops `original` along with the error. Put the
469 // pre-call modes back so no handle is stranded in raw mode; the handle
470 // that failed is simply rewritten its own unchanged mode.
471 let _ = set_state(&input, &output, &original);
472 return Err(e);
473 }
474 Ok(original)
475}
476
477/// Return whether the descriptor is connected to a terminal.
478///
479/// # Parameters
480///
481/// * `fd` — descriptor to test.
482///
483/// # Returns
484///
485/// `true` when `fd` refers to a terminal.
486///
487/// # Errors and panics
488///
489/// This function does not fail or intentionally panic.
490#[cfg(unix)]
491pub fn is_terminal<F: AsFd>(fd: F) -> bool {
492 unsafe { libc::isatty(fd.as_fd().as_raw_fd()) != 0 }
493}
494
495#[cfg(windows)]
496/// Return whether the handle is connected to a console.
497///
498/// # Parameters
499///
500/// * `h` — handle to test.
501///
502/// # Returns
503///
504/// `true` when `h` supports `GetConsoleMode`.
505///
506/// # Errors and panics
507///
508/// This function does not fail or intentionally panic.
509pub fn is_terminal<H: AsHandle>(h: H) -> bool {
510 use windows_sys::Win32::System::Console::GetConsoleMode;
511 let handle = h.as_handle().as_raw_handle() as HANDLE;
512 let mut mode: u32 = 0;
513 unsafe { GetConsoleMode(handle, &mut mode) != 0 }
514}
515
516#[cfg(not(any(unix, windows)))]
517/// Return whether a handle is connected to a terminal.
518///
519/// On unsupported platforms this always returns `false`.
520pub fn is_terminal<T>(_: T) -> bool {
521 false
522}
523
524#[cfg(all(test, unix, not(target_os = "l4re")))]
525mod tests {
526 use super::*;
527 use crate::testutil::{ScriptedFd, attrs, open_pty_pair, opost, prime};
528 use std::fs::File;
529
530 /// Every flag group `rawify` modifies. Restoration is checked against these
531 /// alone: the tty driver owns the rest, and legitimately changes bits of its
532 /// own — re-enabling canonical mode sets `PENDIN`, for instance — which is
533 /// not something a restored state can or should undo.
534 const RAW_IFLAGS: libc::tcflag_t = libc::IGNBRK
535 | libc::BRKINT
536 | libc::PARMRK
537 | libc::ISTRIP
538 | libc::INLCR
539 | libc::IGNCR
540 | libc::ICRNL
541 | libc::IXON;
542 const RAW_LFLAGS: libc::tcflag_t =
543 libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN;
544 const RAW_CFLAGS: libc::tcflag_t = libc::CSIZE | libc::PARENB;
545
546 /// Raw mode is more than `OPOST`, so check every flag group `rawify`
547 /// touches. A single sentinel bit would let most of it regress unnoticed.
548 fn assert_raw(f: &File, half: &str) {
549 let t = attrs(f);
550 assert_eq!(t.c_oflag & libc::OPOST, 0, "{half}: OPOST still set");
551 assert_eq!(
552 t.c_iflag & RAW_IFLAGS,
553 0,
554 "{half}: cooked input flags still set"
555 );
556 assert_eq!(
557 t.c_lflag & RAW_LFLAGS,
558 0,
559 "{half}: line-editing flags still set"
560 );
561 assert_eq!(
562 t.c_cflag & RAW_CFLAGS,
563 libc::CS8,
564 "{half}: not 8-bit, no parity"
565 );
566 assert_eq!(t.c_cc[libc::VMIN], 1, "{half}: VMIN");
567 assert_eq!(t.c_cc[libc::VTIME], 0, "{half}: VTIME");
568 }
569
570 fn assert_restored(before: &libc::termios, f: &File, half: &str) {
571 let now = attrs(f);
572 assert_eq!(
573 now.c_iflag & RAW_IFLAGS,
574 before.c_iflag & RAW_IFLAGS,
575 "{half}: input flags not restored"
576 );
577 assert_eq!(
578 now.c_oflag & libc::OPOST,
579 before.c_oflag & libc::OPOST,
580 "{half}: OPOST not restored"
581 );
582 assert_eq!(
583 now.c_lflag & RAW_LFLAGS,
584 before.c_lflag & RAW_LFLAGS,
585 "{half}: line-editing flags not restored"
586 );
587 assert_eq!(
588 now.c_cflag & RAW_CFLAGS,
589 before.c_cflag & RAW_CFLAGS,
590 "{half}: control flags not restored"
591 );
592 assert_eq!(
593 now.c_cc[libc::VMIN],
594 before.c_cc[libc::VMIN],
595 "{half}: VMIN not restored"
596 );
597 assert_eq!(
598 now.c_cc[libc::VTIME],
599 before.c_cc[libc::VTIME],
600 "{half}: VTIME not restored"
601 );
602 }
603
604 /// A pipe read end is a descriptor that is definitely not a terminal, and
605 /// unlike `/dev/null` it needs nothing from the filesystem. The write end is
606 /// dropped: nothing is ever read, and `tcgetattr`/`tcsetattr` reject it
607 /// either way.
608 fn not_a_terminal() -> std::io::PipeReader {
609 std::io::pipe().expect("pipe").0
610 }
611
612 /// The two halves are independent devices, so their attributes must be
613 /// sampled independently rather than one standing in for the other.
614 #[test]
615 fn get_state_reads_each_half_independently() {
616 let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
617 return;
618 };
619 prime(&a, true);
620 prime(&b, false);
621
622 let state = get_state(&a, &b).expect("both halves are terminals");
623 assert!(
624 state.input.expect("input half read").c_oflag & libc::OPOST != 0,
625 "input half must report the input device's flags"
626 );
627 assert!(
628 state.output.expect("output half read").c_oflag & libc::OPOST == 0,
629 "output half must report the output device's flags, not the input's"
630 );
631 }
632
633 /// Raw mode has to reach the device frames are written to. When the halves
634 /// are two different terminals, configuring only the input one leaves
635 /// `OPOST` set on the output, and the terminal keeps post-processing
636 /// everything the renderer emits.
637 #[test]
638 fn make_raw_and_restore_cover_both_terminals() {
639 let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
640 return;
641 };
642 prime(&a, true);
643 prime(&b, true);
644 let (before_a, before_b) = (attrs(&a), attrs(&b));
645
646 let original = make_raw_mode(&a, &b).expect("raw mode");
647 assert_raw(&a, "input half");
648 assert_raw(&b, "output half");
649
650 set_state(&a, &b, &original).expect("restore");
651 assert_restored(&before_a, &a, "input half");
652 assert_restored(&before_b, &b, "output half");
653 }
654
655 /// Pairing a terminal with a pipe is normal, and the terminal half must
656 /// still be configured whichever side it is on.
657 #[test]
658 fn non_terminal_half_is_skipped() {
659 let Some((_master, tty)) = open_pty_pair() else {
660 return;
661 };
662 prime(&tty, true);
663 let before = attrs(&tty);
664
665 let state = make_raw_mode(not_a_terminal(), &tty).expect("output half is a terminal");
666 assert!(state.input.is_none(), "a pipe is not a terminal");
667 assert!(state.output.is_some(), "the pty half must be recorded");
668 assert_raw(&tty, "output half");
669 set_state(not_a_terminal(), &tty, &state).expect("restore");
670 assert_restored(&before, &tty, "output half");
671
672 // ...and the same with the halves swapped.
673 let state = make_raw_mode(&tty, not_a_terminal()).expect("input half is a terminal");
674 assert!(state.input.is_some(), "the pty half must be recorded");
675 assert!(state.output.is_none(), "a pipe is not a terminal");
676 assert_raw(&tty, "input half");
677 set_state(&tty, not_a_terminal(), &state).expect("restore");
678 assert_restored(&before, &tty, "input half");
679 }
680
681 /// A half that was recorded as a terminal but rejects the write is a real
682 /// failure and must be reported — while the other half is still attempted,
683 /// so one bad descriptor cannot stop the other from being configured.
684 #[test]
685 fn a_half_that_fails_is_reported_and_the_other_is_still_applied() {
686 let Some((_master, tty)) = open_pty_pair() else {
687 return;
688 };
689 prime(&tty, true);
690
691 // Reading the same pty for both halves gives a state whose halves are
692 // both `Some`, so both are attempted below even though only one of the
693 // descriptors can accept them.
694 let mut target = get_state(&tty, &tty).expect("pty is a terminal");
695 let clear_opost = |mut t: libc::termios| {
696 t.c_oflag &= !libc::OPOST;
697 t
698 };
699 target.input = target.input.map(clear_opost);
700 target.output = target.output.map(clear_opost);
701
702 assert!(
703 set_state(not_a_terminal(), &tty, &target).is_err(),
704 "a failing input half must be reported"
705 );
706 assert!(
707 !opost(&tty),
708 "the output half must be attempted even after the input half failed"
709 );
710
711 prime(&tty, true);
712 assert!(
713 set_state(&tty, not_a_terminal(), &target).is_err(),
714 "a failing output half must be reported"
715 );
716 assert!(!opost(&tty), "the input half must still be applied");
717 }
718
719 #[test]
720 fn get_state_errors_when_neither_half_is_a_terminal() {
721 assert!(get_state(not_a_terminal(), not_a_terminal()).is_err());
722 }
723
724 /// A half can pass `tcgetattr` and then fail `tcsetattr` -- a pty whose
725 /// master closed mid-session, say. The other half is already raw by then,
726 /// and `make_raw_mode` consumes the only copy of the pre-call state on its
727 /// way out, so without the write-back that half is raw forever.
728 #[test]
729 fn a_failed_half_does_not_strand_the_half_that_succeeded() {
730 let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
731 return;
732 };
733 prime(&a, true);
734 prime(&b, true);
735 let (before_a, before_b) = (attrs(&a), attrs(&b));
736
737 // `get_state` sees a terminal, the raw `tcsetattr` does not, and the
738 // write-back sees the terminal again.
739 let pipe = not_a_terminal();
740 let output = ScriptedFd::new(&[&b as &dyn AsFd, &pipe, &b]);
741
742 let Err(err) = make_raw_mode(&a, &output) else {
743 panic!("a pipe cannot be rawified, so make_raw_mode must fail");
744 };
745 // Most systems report a non-terminal descriptor as `ENOTTY`; Solaris
746 // reports `EINVAL`. Either way the error has to come from the write to
747 // the pipe rather than from anywhere else.
748 assert!(
749 matches!(err.raw_os_error(), Some(libc::ENOTTY | libc::EINVAL)),
750 "expected a not-a-terminal error, got {err}"
751 );
752 assert_restored(&before_a, &a, "input half");
753 assert_restored(&before_b, &b, "output half");
754 }
755}