Debian Codegraph @

src/system/term/mod.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 mod user_term;
2
3 use std::{
4 ffi::{CString, OsString, c_char, c_uchar},
5 fmt,
6 fs::File,
7 io,
8 os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd},
9 ptr::null_mut,
10 };
11
12 use libc::{TIOCSWINSZ, ioctl, winsize};
13
14 use crate::cutils::{cerr, is_fifo_or_sock, os_string_from_ptr, safe_isatty};
15
16 use super::interface::ProcessId;
17
18 mod find_tty;
19
20 pub(crate) use user_term::UserTerm;
21
22 pub(crate) struct Pty {
23 /// The file path of the leader side of the pty.
24 pub(crate) path: CString,
25 /// The leader side of the pty.
26 pub(crate) leader: PtyLeader,
27 /// The follower side of the pty.
28 pub(crate) follower: PtyFollower,
29 }
30
31 impl Pty {
32 pub(crate) fn open() -> io::Result<Self> {
33 const PATH_MAX: usize = libc::PATH_MAX as _;
34 // Allocate a buffer to hold the path to the pty.
35 let mut path = vec![0 as c_uchar; PATH_MAX];
36 // Create two integers to hold the file descriptors for each side of the pty.
37 let (mut leader, mut follower) = (0, 0);
38
39 // SAFETY:
40 // - openpty is passed two valid pointers as its first two arguments
41 // - path is a valid array that can hold PATH_MAX characters; and casting `u8` to `i8` is
42 // valid since all values are initialized to zero.
43 // - the last two arguments are allowed to be NULL
44 cerr(unsafe {
45 libc::openpty(
46 &mut leader,
47 &mut follower,
48 path.as_mut_ptr().cast(),
49 null_mut::<libc::termios>(),
50 null_mut::<libc::winsize>(),
51 )
52 })?;
53
54 // Get the index of the first null byte and truncate `path` so it doesn't have any null
55 // bytes. If there are no null bytes the path is left as it is.
56 if let Some(index) = path
57 .iter()
58 .enumerate()
59 .find_map(|(index, &byte)| (byte == 0).then_some(index))
60 {
61 path.truncate(index);
62 }
63
64 // This will not panic because `path` was truncated to not have any null bytes.
65 let path = CString::new(path).unwrap();
66
67 Ok(Self {
68 path,
69 leader: PtyLeader {
70 // SAFETY: `openpty` has set `leader` to an open fd suitable for assuming ownership by `OwnedFd`.
71 file: unsafe { OwnedFd::from_raw_fd(leader) }.into(),
72 },
73 follower: PtyFollower {
74 // SAFETY: `openpty` has set `follower` to an open fd suitable for assuming ownership by `OwnedFd`.
75 file: unsafe { OwnedFd::from_raw_fd(follower) }.into(),
76 },
77 })
78 }
79 }
80
81 pub(crate) struct PtyLeader {
82 file: File,
83 }
84
85 impl PtyLeader {
86 pub(crate) fn set_size(&self, term_size: &TermSize) -> io::Result<()> {
87 // SAFETY: the TIOCSWINSZ expects an initialized pointer of type `winsize`
88 // https://www.man7.org/linux/man-pages/man2/TIOCSWINSZ.2const.html
89 //
90 // An object of type TermSize is safe to cast to `winsize` since it is a
91 // repr(transparent) "newtype" struct.
92 cerr(unsafe {
93 ioctl(
94 self.file.as_raw_fd(),
95 TIOCSWINSZ,
96 (term_size as *const TermSize).cast::<libc::winsize>(),
97 )
98 })?;
99
100 Ok(())
101 }
102
103 pub(crate) fn set_nonblocking(&self) -> io::Result<()> {
104 let fd = self.file.as_fd();
105 // SAFETY: these two calls to fcntl are memory safe (and the file descriptor is valid as well)
106 unsafe {
107 let flags = cerr(libc::fcntl(fd.as_raw_fd(), libc::F_GETFL))?;
108
109 // Set the O_NONBLOCK flag
110 cerr(libc::fcntl(
111 fd.as_raw_fd(),
112 libc::F_SETFL,
113 flags | libc::O_NONBLOCK,
114 ))?;
115 }
116 Ok(())
117 }
118 }
119
120 impl io::Read for PtyLeader {
121 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
122 self.file.read(buf)
123 }
124 }
125
126 impl io::Write for PtyLeader {
127 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
128 self.file.write(buf)
129 }
130
131 fn flush(&mut self) -> io::Result<()> {
132 self.file.flush()
133 }
134 }
135
136 impl AsFd for PtyLeader {
137 fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
138 self.file.as_fd()
139 }
140 }
141
142 pub(crate) struct PtyFollower {
143 file: File,
144 }
145
146 impl PtyFollower {
147 pub(crate) fn try_clone(&self) -> io::Result<Self> {
148 self.file.try_clone().map(|file| Self { file })
149 }
150 }
151
152 impl AsFd for PtyFollower {
153 fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
154 self.file.as_fd()
155 }
156 }
157
158 impl From<PtyFollower> for std::process::Stdio {
159 fn from(follower: PtyFollower) -> Self {
160 follower.file.into()
161 }
162 }
163
164 mod sealed {
165 use std::os::fd::AsFd;
166
167 pub(crate) trait Sealed {}
168
169 impl<F: AsFd> Sealed for F {}
170
171 /// This is known to be a real TTY. No need to use `safe_isatty` before calling any ioctl.
172 pub(crate) trait SafeTty {}
173
174 impl<T: SafeTty> SafeTty for &mut T {}
175 impl SafeTty for super::UserTerm {}
176 impl SafeTty for super::PtyLeader {}
177 impl SafeTty for super::PtyFollower {}
178 }
179
180 pub(crate) trait Terminal: sealed::Sealed {
181 fn is_terminal_for_pgrp(&self, pgrp: ProcessId) -> bool;
182 fn tcgetpgrp(&self) -> io::Result<ProcessId>
183 where
184 Self: sealed::SafeTty;
185 fn tcsetpgrp(&self, pgrp: ProcessId) -> io::Result<()>
186 where
187 Self: sealed::SafeTty;
188 fn make_controlling_terminal(&self) -> io::Result<()>
189 where
190 Self: sealed::SafeTty;
191 fn ttyname(&self) -> io::Result<OsString>;
192 fn is_pipe_or_socket(&self) -> bool;
193 fn tcgetsid(&self) -> io::Result<ProcessId>
194 where
195 Self: sealed::SafeTty;
196 }
197
198 impl<F: AsFd> Terminal for F {
199 /// Check if the foreground process group ID associated with this terminal is `pgrp`.
200 /// Returns false if this is not actually a terminal.
201 fn is_terminal_for_pgrp(&self, pgrp: ProcessId) -> bool {
202 if !safe_isatty(self.as_fd()) {
203 return false;
204 }
205
206 // SAFETY: tcgetpgrp cannot cause UB
207 let Ok(id) = cerr(unsafe { libc::tcgetpgrp(self.as_fd().as_raw_fd()) }) else {
208 return false;
209 };
210 ProcessId::new(id) == pgrp
211 }
212 /// Get the foreground process group ID associated with this terminal.
213 fn tcgetpgrp(&self) -> io::Result<ProcessId> {
214 // SAFETY: tcgetpgrp cannot cause UB
215 let id = cerr(unsafe { libc::tcgetpgrp(self.as_fd().as_raw_fd()) })?;
216 Ok(ProcessId::new(id))
217 }
218 /// Set the foreground process group ID associated with this terminal to `pgrp`.
219 fn tcsetpgrp(&self, pgrp: ProcessId) -> io::Result<()> {
220 // SAFETY: tcsetpgrp cannot cause UB
221 cerr(unsafe { libc::tcsetpgrp(self.as_fd().as_raw_fd(), pgrp.inner()) }).map(|_| ())
222 }
223
224 /// Make the given terminal the controlling terminal of the calling process.
225 fn make_controlling_terminal(&self) -> io::Result<()> {
226 // SAFETY: this is a correct way to call the TIOCSCTTY ioctl, see:
227 // https://www.man7.org/linux/man-pages/man2/TIOCNOTTY.2const.html
228 cerr(unsafe { libc::ioctl(self.as_fd().as_raw_fd(), libc::TIOCSCTTY, 0) })?;
229 Ok(())
230 }
231
232 /// Get the filename of the tty
233 fn ttyname(&self) -> io::Result<OsString> {
234 let mut buf: [c_char; 1024] = [0; 1024];
235
236 if !safe_isatty(self.as_fd()) {
237 return Err(io::ErrorKind::Unsupported.into());
238 }
239
240 // SAFETY: `buf` is a valid and initialized pointer, and its correct length is passed
241 cerr(unsafe { libc::ttyname_r(self.as_fd().as_raw_fd(), buf.as_mut_ptr(), buf.len()) })?;
242 // SAFETY: `buf` will have been initialized by the `ttyname_r` call, if it succeeded
243 Ok(unsafe { os_string_from_ptr(buf.as_ptr()) })
244 }
245
246 fn is_pipe_or_socket(&self) -> bool {
247 is_fifo_or_sock(self.as_fd())
248 }
249
250 fn tcgetsid(&self) -> io::Result<ProcessId> {
251 // SAFETY: tcgetsid cannot cause UB
252 let id = cerr(unsafe { libc::tcgetsid(self.as_fd().as_raw_fd()) })?;
253 Ok(ProcessId::new(id))
254 }
255 }
256
257 /// Try to get the path of the current TTY
258 pub fn current_tty_name() -> io::Result<OsString> {
259 if let Some(tty) = find_tty::ttyname_from_dev()? {
260 return Ok(tty);
261 }
262
263 io::stdin()
264 .ttyname()
265 .or_else(|_| io::stdout().ttyname())
266 .or_else(|_| io::stderr().ttyname())
267 }
268
269 #[repr(transparent)]
270 pub(crate) struct TermSize {
271 raw: winsize,
272 }
273
274 impl PartialEq for TermSize {
275 fn eq(&self, other: &Self) -> bool {
276 self.raw.ws_col == other.raw.ws_col && self.raw.ws_row == other.raw.ws_row
277 }
278 }
279
280 impl fmt::Display for TermSize {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 write!(f, "{} x {}", self.raw.ws_row, self.raw.ws_col)
283 }
284 }
285
286 #[allow(clippy::undocumented_unsafe_blocks)]
287 #[cfg(test)]
288 mod tests {
289 use std::{
290 ffi::OsString,
291 io::{Read, Write},
292 os::unix::{net::UnixStream, prelude::OsStringExt},
293 path::PathBuf,
294 process::exit,
295 };
296
297 use crate::system::{fork_for_test, getpgid, setsid, term::*};
298
299 #[test]
300 fn open_pty() {
301 let pty = Pty::open().unwrap();
302 assert!(safe_isatty(pty.leader.file.as_fd()));
303 assert!(safe_isatty(pty.follower.file.as_fd()));
304
305 let path = PathBuf::from(OsString::from_vec(pty.path.into_bytes()));
306 assert!(path.try_exists().unwrap());
307 assert!(path.starts_with("/dev/pts/"));
308 }
309
•310 //#[test]
311 fn tcsetpgrp_and_tcgetpgrp_are_consistent() {
312 // Create a socket so the child can send us a byte if successful.
313 let (mut rx, mut tx) = UnixStream::pair().unwrap();
314
315 unsafe {
316 fork_for_test(|| {
317 // Open a new pseudoterminal.
318 let leader = Pty::open().unwrap().leader;
319 // On FreeBSD this returns an unspecified PID when there is no foreground process
320 // group, so skip this check on FreeBSD.
321 if cfg!(not(target_os = "freebsd")) {
322 // The pty leader should not have a foreground process group yet.
323 assert_eq!(leader.tcgetpgrp().unwrap().inner(), 0);
324 }
325 // Create a new session so we can change the controlling terminal.
326 setsid().unwrap();
327 // Set the pty leader as the controlling terminal.
328 leader.make_controlling_terminal().unwrap();
329 // Set us as the foreground process group of the pty leader.
330 let pgid = getpgid(ProcessId::new(0)).unwrap();
331 leader.tcsetpgrp(pgid).unwrap();
332 // Check that we are in fact the foreground process group of the pty leader.
333 assert_eq!(pgid, leader.tcgetpgrp().unwrap());
334 // If we haven't panicked yet, send a byte to the parent.
335 tx.write_all(&[42]).unwrap();
336
337 exit(0);
338 })
339 };
340
341 drop(tx);
342
343 // Read one byte from the children to confirm that it did not panic.
344 let mut buf = [0];
345 rx.read_exact(&mut buf).unwrap();
346 assert_eq!(buf[0], 42);
347 }
348 }