Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_sys/src/pty.rs

6.3 KiB, 35 runs

created by r1870400018:79789, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A pseudo-terminal for a child, and raw mode for the caller's own terminal.
2//!
3//! A program that asks whether it talks to a terminal behaves differently down a pipe.
4//! [`Pty::open`] makes a pair: the child takes the slave as its three streams ([`Pty::stdio`])
5//! and the caller reads and writes the master. The slave is opened from the master itself
6//! (`TIOCGPTPEER`), so the caller needs neither its path nor a second open that could fail; the
7//! slave's node in /dev/pts is the user's alone, mode 620, as for any terminal.
8//!
9//! The slave is not made the child's controlling terminal, which needs `setsid` in the child
10//! before `exec` and so a `pre_exec` hook this crate does not write. A program that needs only
11//! `isatty` and `TIOCGWINSZ` on its own streams, as a multiplexer's client does, works on it;
12//! one that needs a controlling terminal, as `sudo` opening /dev/tty or a shell's job control
13//! do, must be given one elsewhere, as a multiplexer gives each of its panes.
14//!
15//! [`Raw`] puts the caller's terminal in raw mode, every byte passed as typed, and puts it back
16//! as it was when dropped, so a client of a remote terminal cannot leave the user's own one
17//! without echo on an early return.
18//!
19//! The system calls come from `rustix`, which owns the `unsafe` this crate forbids.
20
21use oxedyne_fe2o3_core::prelude::*;
22
23use rustix::{
24 io::ioctl_fionbio,
25 process::{
26 kill_process,
27 Pid,
28 Signal,
29 },
30 pty::{
31 grantpt,
32 ioctl_tiocgptpeer,
33 openpt,
34 unlockpt,
35 OpenptFlags,
36 },
37 termios::{
38 tcgetattr,
39 tcgetwinsize,
40 tcsetattr,
41 tcsetwinsize,
42 OptionalActions,
43 Termios,
44 Winsize,
45 },
46};
47
48use std::{
49 os::fd::{
50 AsFd,
51 BorrowedFd,
52 OwnedFd,
53 },
54 process::Stdio,
55};
56
57/// A master and its slave, the slave for a child's streams.
58#[derive(Debug)]
59pub struct Pty {
60 master: OwnedFd,
61 slave: OwnedFd,
62}
63
64impl Pty {
65 /// A new pair whose terminal is `cols` wide and `rows` high.
66 pub fn open(cols: u16, rows: u16) -> Outcome<Self> {
67 let flags = OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC;
68 let master = match openpt(flags) {
69 Ok(fd) => fd,
70 Err(e) => return Err(err!(e, "Cannot open a pseudo-terminal."; IO, System)),
71 };
72 if let Err(e) = grantpt(&master).and_then(|_| unlockpt(&master)) {
73 return Err(err!(e, "Cannot unlock a new pseudo-terminal's slave."; IO, System));
74 }
75 let slave = match ioctl_tiocgptpeer(&master, flags) {
76 Ok(fd) => fd,
77 Err(e) => return Err(err!(e, "Cannot open a new pseudo-terminal's slave."; IO, System)),
78 };
79 res!(set_size(&master, cols, rows));
80 Ok(Self { master, slave })
81 }
82
83 /// The three standard streams for a child, each its own copy of the slave.
84 pub fn stdio(&self) -> Outcome<[Stdio; 3]> {
85 let dup = || -> Outcome<Stdio> {
86 match self.slave.try_clone() {
87 Ok(fd) => Ok(Stdio::from(fd)),
88 Err(e) => Err(err!(e, "Cannot copy a pseudo-terminal's slave."; IO, System)),
89 }
90 };
91 Ok([res!(dup()), res!(dup()), res!(dup())])
92 }
93
94 pub fn master(&self) -> BorrowedFd<'_> {
95 self.master.as_fd()
96 }
97
98 pub fn slave(&self) -> BorrowedFd<'_> {
99 self.slave.as_fd()
100 }
101
102 /// The master alone, once the child holds its copies of the slave: the caller's copy is
103 /// closed, so the master reads end-of-file (`EIO`) when the last child does.
104 pub fn into_master(self) -> OwnedFd {
105 self.master
106 }
107}
108
109/// Sets the size of the terminal `fd`, a master or a slave, to `cols` by `rows`.
110pub fn set_size<F: AsFd>(fd: F, cols: u16, rows: u16) -> Outcome<()> {
111 let size = Winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
112 match tcsetwinsize(fd, size) {
113 Ok(()) => Ok(()),
114 Err(e) => Err(err!(e, "Cannot set a terminal's size to {}x{}.", cols, rows; IO, System)),
115 }
116}
117
118/// The size of the terminal `fd`, as (columns, rows).
119pub fn size<F: AsFd>(fd: F) -> Outcome<(u16, u16)> {
120 match tcgetwinsize(fd) {
121 Ok(w) => Ok((w.ws_col, w.ws_row)),
122 Err(e) => Err(err!(e, "Cannot read a terminal's size."; IO, System)),
123 }
124}
125
126/// Makes reads and writes of `fd` return at once rather than wait, as an event loop needs.
127pub fn nonblocking<F: AsFd>(fd: F) -> Outcome<()> {
128 match ioctl_fionbio(fd, true) {
129 Ok(()) => Ok(()),
130 Err(e) => Err(err!(e, "Cannot make a descriptor non-blocking."; IO, System)),
131 }
132}
133
134/// Tells the one process `pid` that its terminal's size has changed (`SIGWINCH`), where the
135/// kernel would tell a controlling terminal's whole foreground group: a child that forks must
136/// pass it on or read the size itself. The caller signals only a child it has not yet waited
137/// for, whose number cannot have been given to another process.
138pub fn resized(pid: u32) -> Outcome<()> {
139 let p = res!(i32::try_from(pid).ok().and_then(Pid::from_raw).ok_or_else(|| err!(
140 "The process number {} is not one a signal can be sent to.", pid; Invalid, Input, Range)));
141 match kill_process(p, Signal::WINCH) {
142 Ok(()) => Ok(()),
143 Err(e) => Err(err!(e, "Cannot tell process {} of its terminal's new size.", pid; IO, System)),
144 }
145}
146
147/// A terminal in raw mode, put back as it was when this is dropped.
148pub struct Raw {
149 fd: OwnedFd,
150 was: Termios,
151}
152
153impl Raw {
154 /// Puts the terminal `fd` in raw mode: no echo, no line editing, no signal keys, every byte
155 /// read as it is typed. What was typed ahead is kept for the next read.
156 pub fn enter<F: AsFd>(fd: F) -> Outcome<Self> {
157 let fd = res!(fd.as_fd().try_clone_to_owned());
158 let was = match tcgetattr(&fd) {
159 Ok(t) => t,
160 Err(e) => return Err(err!(e, "Cannot read the terminal's settings: is it a terminal?"; IO, System)),
161 };
162 let mut raw = was.clone();
163 raw.make_raw();
164 if let Err(e) = tcsetattr(&fd, OptionalActions::Now, &raw) {
165 return Err(err!(e, "Cannot put the terminal in raw mode."; IO, System));
166 }
167 Ok(Self { fd, was })
168 }
169}
170
171impl Drop for Raw {
172 fn drop(&mut self) {
173 let _ = tcsetattr(&self.fd, OptionalActions::Now, &self.was);
174 }
175}