1//! Functions which operate on file descriptors which might be terminals.
2
3use crate::backend;
4use backend::fd::AsFd;
5#[cfg(all(feature = "alloc", feature = "procfs"))]
6#[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))]
7use {
8 crate::ffi::CString, crate::io, crate::path::SMALL_PATH_BUFFER_SIZE, alloc::vec::Vec,
9 backend::fd::BorrowedFd,
10};
11
12/// `isatty(fd)`—Tests whether a file descriptor refers to a terminal.
13///
14/// # References
15/// - [POSIX]
16/// - [Linux]
17///
18/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/isatty.html
19/// [Linux]: https://man7.org/linux/man-pages/man3/isatty.3.html
20#[inline]
21pub fn isatty<Fd: AsFd>(fd: Fd) -> bool {
22 backend::termios::syscalls::isatty(fd.as_fd())
23}
24
25/// `ttyname_r(fd)`
26///
27/// If `reuse` already has available capacity, reuse it if possible.
28///
29/// # References
30/// - [POSIX]
31/// - [Linux]
32///
33/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/ttyname.html
34/// [Linux]: https://man7.org/linux/man-pages/man3/ttyname.3.html
35#[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))]
36#[cfg(all(feature = "alloc", feature = "procfs"))]
37#[cfg_attr(doc_cfg, doc(cfg(feature = "procfs")))]
38#[doc(alias = "ttyname_r")]
39#[inline]
40pub fn ttyname<Fd: AsFd, B: Into<Vec<u8>>>(dirfd: Fd, reuse: B) -> io::Result<CString> {
41 _ttyname(dirfd.as_fd(), reuse.into())
42}
43
44#[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))]
45#[cfg(all(feature = "alloc", feature = "procfs"))]
46#[allow(unsafe_code)]
47fn _ttyname(dirfd: BorrowedFd<'_>, mut buffer: Vec<u8>) -> io::Result<CString> {
48 buffer.clear();
49 buffer.reserve(SMALL_PATH_BUFFER_SIZE);
50
51 loop {
52 match backend::termios::syscalls::ttyname(dirfd, buffer.spare_capacity_mut()) {
53 Err(io::Errno::RANGE) => {
54 // Use `Vec` reallocation strategy to grow capacity
55 // exponentially.
56 buffer.reserve(buffer.capacity() + 1);
57 }
58 Ok(len) => {
59 // SAFETY: Assume the backend returns the length of the string
60 // excluding the NUL.
61 unsafe {
62 buffer.set_len(len + 1);
63 }
64
65 // SAFETY:
66 // - "ttyname_r stores this pathname in the buffer buf"
67 // - [POSIX definition 3.271: Pathname]: "A string that is used to identify a
68 // file."
69 // - [POSIX definition 3.375: String]: "A contiguous sequence of bytes
70 // terminated by and including the first null byte."
71 //
72 // Thus, there will be a single NUL byte at the end of the
73 // string.
74 //
75 // [POSIX definition 3.271: Pathname]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_271
76 // [POSIX definition 3.375: String]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_375
77 unsafe {
78 return Ok(CString::from_vec_with_nul_unchecked(buffer));
79 }
80 }
81 Err(errno) => return Err(errno),
82 }
83 }
84}
85