1 //! linux_raw syscalls supporting `rustix::termios`.
2 //!
3 //! # Safety
4 //!
5 //! See the `rustix::backend` module documentation for details.
6 #![allow(unsafe_code)]
7 #![allow(clippy::undocumented_unsafe_blocks)]
8 
9 use super::super::conv::{by_ref, c_uint, ret};
10 use crate::fd::BorrowedFd;
11 use crate::io;
12 use crate::process::{Pid, RawNonZeroPid};
13 use crate::termios::{
14     Action, OptionalActions, QueueSelector, Termios, Winsize, BRKINT, CBAUD, CS8, CSIZE, ECHO,
15     ECHONL, ICANON, ICRNL, IEXTEN, IGNBRK, IGNCR, INLCR, ISIG, ISTRIP, IXON, OPOST, PARENB, PARMRK,
16     VMIN, VTIME,
17 };
18 #[cfg(feature = "procfs")]
19 use crate::{ffi::CStr, fs::FileType, path::DecInt};
20 use core::mem::MaybeUninit;
21 use linux_raw_sys::general::__kernel_pid_t;
22 use linux_raw_sys::ioctl::{
23     TCFLSH, TCGETS, TCSBRK, TCSETS, TCXONC, TIOCGPGRP, TIOCGSID, TIOCGWINSZ, TIOCSPGRP, TIOCSWINSZ,
24 };
25 
26 #[inline]
27 pub(crate) fn tcgetwinsize(fd: BorrowedFd<'_>) -> io::Result<Winsize> {
28     unsafe {
29         let mut result = MaybeUninit::<Winsize>::uninit();
30         ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGWINSZ), &mut result))?;
31         Ok(result.assume_init())
32     }
33 }
34 
35 #[inline]
36 pub(crate) fn tcgetattr(fd: BorrowedFd<'_>) -> io::Result<Termios> {
37     unsafe {
38         let mut result = MaybeUninit::<Termios>::uninit();
39         ret(syscall!(__NR_ioctl, fd, c_uint(TCGETS), &mut result))?;
40         Ok(result.assume_init())
41     }
42 }
43 
44 #[inline]
45 pub(crate) fn tcgetpgrp(fd: BorrowedFd<'_>) -> io::Result<Pid> {
46     unsafe {
47         let mut result = MaybeUninit::<__kernel_pid_t>::uninit();
48         ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGPGRP), &mut result))?;
49         let pid = result.assume_init();
50         debug_assert!(pid > 0);
51         Ok(Pid::from_raw_nonzero(RawNonZeroPid::new_unchecked(
52             pid as u32,
53         )))
54     }
55 }
56 
57 #[inline]
58 pub(crate) fn tcsetattr(
59     fd: BorrowedFd,
60     optional_actions: OptionalActions,
61     termios: &Termios,
62 ) -> io::Result<()> {
63     // Translate from `optional_actions` into an ioctl request code. On MIPS,
64     // `optional_actions` already has `TCGETS` added to it.
65     let request = if cfg!(any(target_arch = "mips", target_arch = "mips64")) {
66         optional_actions as u32
67     } else {
68         TCSETS + optional_actions as u32
69     };
70     unsafe {
71         ret(syscall_readonly!(
72             __NR_ioctl,
73             fd,
74             c_uint(request as u32),
75             by_ref(termios)
76         ))
77     }
78 }
79 
80 #[inline]
81 pub(crate) fn tcsendbreak(fd: BorrowedFd) -> io::Result<()> {
82     unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TCSBRK), c_uint(0))) }
83 }
84 
85 #[inline]
86 pub(crate) fn tcdrain(fd: BorrowedFd) -> io::Result<()> {
87     unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TCSBRK), c_uint(1))) }
88 }
89 
90 #[inline]
91 pub(crate) fn tcflush(fd: BorrowedFd, queue_selector: QueueSelector) -> io::Result<()> {
92     unsafe {
93         ret(syscall_readonly!(
94             __NR_ioctl,
95             fd,
96             c_uint(TCFLSH),
97             c_uint(queue_selector as u32)
98         ))
99     }
100 }
101 
102 #[inline]
103 pub(crate) fn tcflow(fd: BorrowedFd, action: Action) -> io::Result<()> {
104     unsafe {
105         ret(syscall_readonly!(
106             __NR_ioctl,
107             fd,
108             c_uint(TCXONC),
109             c_uint(action as u32)
110         ))
111     }
112 }
113 
114 #[inline]
115 pub(crate) fn tcgetsid(fd: BorrowedFd) -> io::Result<Pid> {
116     unsafe {
117         let mut result = MaybeUninit::<__kernel_pid_t>::uninit();
118         ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGSID), &mut result))?;
119         let pid = result.assume_init();
120         debug_assert!(pid > 0);
121         Ok(Pid::from_raw_nonzero(RawNonZeroPid::new_unchecked(
122             pid as u32,
123         )))
124     }
125 }
126 
127 #[inline]
128 pub(crate) fn tcsetwinsize(fd: BorrowedFd, winsize: Winsize) -> io::Result<()> {
129     unsafe {
130         ret(syscall!(
131             __NR_ioctl,
132             fd,
133             c_uint(TIOCSWINSZ),
134             by_ref(&winsize)
135         ))
136     }
137 }
138 
139 #[inline]
140 pub(crate) fn tcsetpgrp(fd: BorrowedFd<'_>, pid: Pid) -> io::Result<()> {
141     unsafe { ret(syscall!(__NR_ioctl, fd, c_uint(TIOCSPGRP), pid)) }
142 }
143 
144 #[inline]
145 #[must_use]
146 #[allow(clippy::missing_const_for_fn)]
147 pub(crate) fn cfgetospeed(termios: &Termios) -> u32 {
148     termios.c_cflag & CBAUD
149 }
150 
151 #[inline]
152 #[must_use]
153 #[allow(clippy::missing_const_for_fn)]
154 pub(crate) fn cfgetispeed(termios: &Termios) -> u32 {
155     termios.c_cflag & CBAUD
156 }
157 
158 #[inline]
159 pub(crate) fn cfmakeraw(termios: &mut Termios) {
160     // From the Linux [`cfmakeraw` man page]:
161     //
162     // [`cfmakeraw` man page]: https://man7.org/linux/man-pages/man3/cfmakeraw.3.html
163     termios.c_iflag &= !(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
164     termios.c_oflag &= !OPOST;
165     termios.c_lflag &= !(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
166     termios.c_cflag &= !(CSIZE | PARENB);
167     termios.c_cflag |= CS8;
168 
169     // Musl and glibc also do these:
170     termios.c_cc[VMIN] = 1;
171     termios.c_cc[VTIME] = 0;
172 }
173 
174 #[inline]
175 pub(crate) fn cfsetospeed(termios: &mut Termios, speed: u32) -> io::Result<()> {
176     if (speed & !CBAUD) != 0 {
177         return Err(io::Errno::INVAL);
178     }
179     termios.c_cflag &= !CBAUD;
180     termios.c_cflag |= speed;
181     Ok(())
182 }
183 
184 #[inline]
185 pub(crate) fn cfsetispeed(termios: &mut Termios, speed: u32) -> io::Result<()> {
186     if speed == 0 {
187         return Ok(());
188     }
189     if (speed & !CBAUD) != 0 {
190         return Err(io::Errno::INVAL);
191     }
192     termios.c_cflag &= !CBAUD;
193     termios.c_cflag |= speed;
194     Ok(())
195 }
196 
197 #[inline]
198 pub(crate) fn cfsetspeed(termios: &mut Termios, speed: u32) -> io::Result<()> {
199     if (speed & !CBAUD) != 0 {
200         return Err(io::Errno::INVAL);
201     }
202     termios.c_cflag &= !CBAUD;
203     termios.c_cflag |= speed;
204     Ok(())
205 }
206 
207 #[inline]
208 pub(crate) fn isatty(fd: BorrowedFd<'_>) -> bool {
209     // On error, Linux will return either `EINVAL` (2.6.32) or `ENOTTY`
210     // (otherwise), because we assume we're never passing an invalid
211     // file descriptor (which would get `EBADF`). Either way, an error
212     // means we don't have a tty.
213     tcgetwinsize(fd).is_ok()
214 }
215 
216 #[cfg(feature = "procfs")]
217 pub(crate) fn ttyname(fd: BorrowedFd<'_>, buf: &mut [u8]) -> io::Result<usize> {
218     let fd_stat = super::super::fs::syscalls::fstat(fd)?;
219 
220     // Quick check: if `fd` isn't a character device, it's not a tty.
221     if FileType::from_raw_mode(fd_stat.st_mode) != FileType::CharacterDevice {
222         return Err(crate::io::Errno::NOTTY);
223     }
224 
225     // Check that `fd` is really a tty.
226     tcgetwinsize(fd)?;
227 
228     // Get a fd to '/proc/self/fd'.
229     let proc_self_fd = io::proc_self_fd()?;
230 
231     // Gather the ttyname by reading the 'fd' file inside 'proc_self_fd'.
232     let r =
233         super::super::fs::syscalls::readlinkat(proc_self_fd, DecInt::from_fd(fd).as_c_str(), buf)?;
234 
235     // If the number of bytes is equal to the buffer length, truncation may
236     // have occurred. This check also ensures that we have enough space for
237     // adding a NUL terminator.
238     if r == buf.len() {
239         return Err(io::Errno::RANGE);
240     }
241     buf[r] = b'\0';
242 
243     // Check that the path we read refers to the same file as `fd`.
244     let path = CStr::from_bytes_with_nul(&buf[..=r]).unwrap();
245 
246     let path_stat = super::super::fs::syscalls::stat(path)?;
247     if path_stat.st_dev != fd_stat.st_dev || path_stat.st_ino != fd_stat.st_ino {
248         return Err(crate::io::Errno::NODEV);
249     }
250 
251     Ok(r)
252 }
253