-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpty.rs
More file actions
263 lines (226 loc) · 6.56 KB
/
pty.rs
File metadata and controls
263 lines (226 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use anyhow::{anyhow, Context, Result};
use std::{
ffi::OsStr,
io,
os::unix::{
io::{FromRawFd, RawFd},
process::CommandExt,
},
process::{Command, Stdio},
ptr,
time::Duration,
};
use tokio::fs::File;
use crate::{error::CResult, term::Size};
const PTY_ERR: &str = "[pty.rs] Failed to open pty";
const PRG_ERR: &str = "[pty.rs] Failed to spawn shell";
pub struct Pty {
/// Master FD
fd: RawFd,
/// R/W access to the PTY
file: File,
/// Pid of the child process
pid: i32,
kill_on_drop: bool,
}
pub struct PtyBuilder {
inner: Command,
daemonize: bool,
}
impl PtyBuilder {
pub fn arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
self.inner.arg(arg);
self
}
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.inner.args(args);
self
}
pub fn env_clear(mut self) -> Self {
self.inner.env_clear();
self
}
pub fn env<K, V>(mut self, key: K, val: V) -> Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.env(key, val);
self
}
pub fn envs<I, K, V>(mut self, vars: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.envs(vars);
self
}
pub fn daemonize(mut self) -> Self {
self.daemonize = true;
self
}
pub fn kill_on_drop(mut self) -> Self {
self.daemonize = false;
self
}
pub fn set_daemonize(&mut self, daemonize: bool) {
self.daemonize = daemonize;
}
pub fn current_dir<P: AsRef<std::path::Path>>(mut self, dir: P) -> Self {
self.inner.current_dir(dir);
self
}
pub fn spawn(self, size: &Size) -> Result<Pty> {
let (master, slave) = Pty::open(size)?;
let mut cmd = self.inner;
cmd.stdin(unsafe { Stdio::from_raw_fd(slave) })
.stdout(unsafe { Stdio::from_raw_fd(slave) })
.stderr(unsafe { Stdio::from_raw_fd(slave) });
unsafe {
cmd.pre_exec(Pty::pre_exec);
}
cmd.spawn().map_err(|_| anyhow!(PRG_ERR)).and_then(|e| {
let pty = Pty {
fd: master,
file: unsafe { File::from_raw_fd(master) },
pid: e.id() as i32,
kill_on_drop: !self.daemonize,
};
pty.resize(size)?;
Ok(pty)
})
}
}
impl Pty {
pub fn builder(program: impl AsRef<str>) -> PtyBuilder {
PtyBuilder {
inner: Command::new(program.as_ref()),
daemonize: false,
}
}
pub fn spawn(program: &str, args: Vec<String>, size: &Size) -> Result<Pty> {
Pty::builder(program).args(args).spawn(size)
}
pub fn daemonize(&mut self) {
self.kill_on_drop = false;
}
pub fn pid(&self) -> i32 {
self.pid
}
pub fn file(&self) -> &File {
&self.file
}
pub fn fd(&self) -> RawFd {
self.fd
}
/// Resizes the child pty.
pub fn resize(&self, size: &Size) -> Result<()> {
unsafe {
libc::ioctl(
self.fd,
libc::TIOCSWINSZ,
&libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: 0,
ws_ypixel: 0,
},
)
.to_result()
.map(|_| ())
.context(PTY_ERR)
}
}
/// Creates a pty with the given size and returns the (master, slave)
/// file descriptors attached to it.
pub fn open(size: &Size) -> Result<(RawFd, RawFd)> {
let mut master = 0;
let mut slave = 0;
unsafe {
#[cfg(target_arch = "aarch64")]
libc::openpty(
&mut master,
&mut slave,
ptr::null_mut(),
ptr::null_mut(),
&mut size.into(),
)
.to_result()
.context(PTY_ERR)?;
#[cfg(not(target_arch = "aarch64"))]
libc::openpty(
&mut master,
&mut slave,
ptr::null_mut(),
ptr::null_mut(),
&size.into(),
)
.to_result()
.context(PTY_ERR)?;
// Configure master to be non blocking
let current_config = libc::fcntl(master, libc::F_GETFL, 0)
.to_result()
.context(PTY_ERR)?;
libc::fcntl(master, libc::F_SETFL, current_config)
.to_result()
.context(PTY_ERR)?;
}
Ok((master, slave))
}
// Runs between fork and exec calls
fn pre_exec() -> io::Result<()> {
unsafe {
if libc::getpid() == 0 {
std::process::exit(0);
}
// Create a new process group, this process being the master
libc::setsid().to_result().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Failed to create process group: {}", e),
)
})?;
// Set this process as the controling terminal
libc::ioctl(0, libc::TIOCSCTTY, 1)
.to_result()
.map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Failed to set controlling terminal: {}", e),
)
})?;
}
Ok(())
}
}
/// Handle cleanup automatically
impl Drop for Pty {
fn drop(&mut self) {
unsafe {
if self.kill_on_drop {
let fd = self.fd;
let pid = self.pid;
// Close file descriptor
libc::close(fd);
// Kill the owned processed when the Pty is dropped
libc::kill(pid, libc::SIGTERM);
std::thread::sleep(Duration::from_millis(5));
let mut status = 0;
// make sure the process has exited
libc::waitpid(pid, &mut status, libc::WNOHANG);
// if it hasn't exited, force kill it and clean up the zombie process
if status <= 0 {
// The process exists but hasn't changed state, or there was an error
libc::kill(pid, libc::SIGKILL);
libc::waitpid(pid, &mut status, 0);
}
}
}
}
}