tilo_process/pty.rs
1//! A pseudo-terminal master whose size and foreground process group are asked of the OS.
2//!
3//! A terminal that shows a session someone else opened receives the master's descriptor and
4//! knows nothing else of the process: the window's size, and where the guest's process group
5//! stands, are `ioctl`s on that descriptor.
6
7use std::fs::File;
8use std::io;
9use std::os::fd::{AsRawFd as _, RawFd};
10
11/// The shape of a terminal: its rows and columns, and its pixels where the OS names them.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub struct WinSize {
14 pub rows: u16,
15 pub cols: u16,
16 pub pixel_width: u16,
17 pub pixel_height: u16,
18}
19
20/// A PTY master over a descriptor this process owns.
21#[derive(Debug)]
22pub struct Master {
23 file: File,
24}
25
26impl Master {
27 #[must_use]
28 pub fn new(file: File) -> Self {
29 Self { file }
30 }
31
32 /// The size the terminal last had.
33 ///
34 /// # Errors
35 ///
36 /// The descriptor is not a PTY, or the OS refused the call.
37 pub fn get_size(&self) -> io::Result<WinSize> {
38 // SAFETY: `winsize` is fully written by the ioctl; the file is a live pty master.
39 let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
40 // SAFETY: as above.
41 let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCGWINSZ, &mut ws) };
42 if rc != 0 {
43 return Err(io::Error::last_os_error());
44 }
45 Ok(WinSize {
46 rows: ws.ws_row,
47 cols: ws.ws_col,
48 pixel_width: ws.ws_xpixel,
49 pixel_height: ws.ws_ypixel,
50 })
51 }
52
53 /// Resize the terminal, so its guest reflows.
54 ///
55 /// # Errors
56 ///
57 /// The descriptor is not a PTY, or the OS refused the call.
58 pub fn resize(&self, size: WinSize) -> io::Result<()> {
59 let ws = libc::winsize {
60 ws_row: size.rows,
61 ws_col: size.cols,
62 ws_xpixel: size.pixel_width,
63 ws_ypixel: size.pixel_height,
64 };
65 // SAFETY: `ws` lives for the call, and the file is a live pty master.
66 let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCSWINSZ, &ws) };
67 if rc != 0 {
68 return Err(io::Error::last_os_error());
69 }
70 Ok(())
71 }
72
73 /// The process group the guest leads, when it leads one.
74 #[must_use]
75 pub fn process_group_leader(&self) -> Option<i32> {
76 let mut pgrp: i32 = -1;
77 // SAFETY: `TIOCGPGRP` writes one `pid_t`; the file is a pty master.
78 let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCGPGRP, &mut pgrp) };
79 (rc == 0 && pgrp > 0).then_some(pgrp)
80 }
81
82 #[must_use]
83 pub fn raw_fd(&self) -> RawFd {
84 self.file.as_raw_fd()
85 }
86
87 /// Another handle on the same master.
88 ///
89 /// # Errors
90 ///
91 /// The OS refused to duplicate it.
92 pub fn try_clone(&self) -> io::Result<File> {
93 self.file.try_clone()
94 }
95}