1use anyhow::{Context as _, Error};
6use fidl::endpoints::ServerEnd;
7use fidl_fuchsia_hardware_pty::{DeviceMarker, DeviceProxy, WindowSize};
8use fuchsia_component::client::connect_to_protocol;
9use fuchsia_trace as ftrace;
10use std::ffi::CStr;
11use std::fs::File;
12use std::os::fd::OwnedFd;
13use zx::{self as zx, HandleBased as _, ProcessInfo, ProcessInfoFlags};
14
15#[derive(Clone)]
17pub struct ServerPty {
18 proxy: DeviceProxy,
20}
21
22pub struct ShellProcess {
23 pub pty: ServerPty,
24
25 process: zx::Process,
28}
29
30impl ServerPty {
31 pub fn new() -> Result<Self, Error> {
33 ftrace::duration!(c"pty", c"Pty:new");
34 let proxy =
35 connect_to_protocol::<DeviceMarker>().context("could not connect to pty service")?;
36 Ok(Self { proxy })
37 }
38
39 pub async fn spawn(
49 self,
50 command: Option<&CStr>,
51 environ: Option<&[&CStr]>,
52 ) -> Result<ShellProcess, Error> {
53 let command = command.unwrap_or(&c"/boot/bin/sh");
54 self.spawn_with_argv(command, &[command], environ).await
55 }
56
57 pub async fn spawn_with_argv(
58 self,
59 command: &CStr,
60 argv: &[&CStr],
61 environ: Option<&[&CStr]>,
62 ) -> Result<ShellProcess, Error> {
63 ftrace::duration!(c"pty", c"Pty:spawn");
64 let client_pty = self.open_client_pty().await.context("unable to create client_pty")?;
65 let process = match fdio::spawn_etc(
66 &zx::Job::from_handle(zx::Handle::invalid()),
67 fdio::SpawnOptions::CLONE_ALL - fdio::SpawnOptions::CLONE_STDIO,
68 command,
69 argv,
70 environ,
71 &mut [fdio::SpawnAction::transfer_fd(client_pty, fdio::SpawnAction::USE_FOR_STDIO)],
72 ) {
73 Ok(process) => process,
74 Err((status, reason)) => {
75 return Err(status).context(format!("failed to spawn shell: {}", reason));
76 }
77 };
78
79 Ok(ShellProcess { pty: self, process })
80 }
81
82 pub fn try_clone_fd(&self) -> Result<File, Error> {
84 use std::os::fd::AsRawFd as _;
85
86 let Self { proxy } = self;
87 let (client_end, server_end) = fidl::endpoints::create_endpoints();
88 let () = proxy.clone(server_end)?;
89 let file: File = fdio::create_fd(client_end.into())
90 .context("failed to create FD from server PTY")?
91 .into();
92 let fd = file.as_raw_fd();
93 let previous = {
94 let res = unsafe { libc::fcntl(fd, libc::F_GETFL) };
95 if res == -1 {
96 Err(std::io::Error::last_os_error()).context("failed to get file status flags")
97 } else {
98 Ok(res)
99 }
100 }?;
101 let new = previous | libc::O_NONBLOCK;
102 if new != previous {
103 let res = unsafe { libc::fcntl(fd, libc::F_SETFL, new) };
104 let () = if res == -1 {
105 Err(std::io::Error::last_os_error()).context("failed to set file status flags")
106 } else {
107 Ok(())
108 }?;
109 }
110 Ok(file)
111 }
112
113 pub async fn resize(&self, window_size: WindowSize) -> Result<(), Error> {
115 ftrace::duration!(c"pty", c"Pty:resize");
116 let Self { proxy } = self;
117 let () = proxy
118 .set_window_size(&window_size)
119 .await
120 .map(zx::Status::ok)
121 .context("unable to call resize window")?
122 .context("failed to resize window")?;
123 Ok(())
124 }
125
126 async fn open_client_pty(&self) -> Result<OwnedFd, Error> {
128 ftrace::duration!(c"pty", c"Pty:open_client_pty");
129 let (client_end, server_end) = fidl::endpoints::create_endpoints();
130 let () = self.open_client(server_end).await.context("failed to open client")?;
131 let fd =
132 fdio::create_fd(client_end.into()).context("failed to create FD from client PTY")?;
133 Ok(fd)
134 }
135
136 pub async fn open_client(&self, server_end: ServerEnd<DeviceMarker>) -> Result<(), Error> {
140 let Self { proxy } = self;
141 ftrace::duration!(c"pty", c"Pty:open_client");
142
143 let () = proxy
144 .open_client(0, server_end)
145 .await
146 .map(zx::Status::ok)
147 .context("failed to interact with PTY device")?
148 .context("failed to attach PTY to channel")?;
149
150 Ok(())
151 }
152}
153
154impl ShellProcess {
155 pub fn process_info(&self) -> Result<ProcessInfo, Error> {
157 let Self { pty: _, process } = self;
158 process.info().context("failed to get process info")
159 }
160
161 pub fn is_running(&self) -> bool {
163 self.process_info()
164 .map(|info| {
165 info.flags.contains(zx::ProcessInfoFlags::STARTED)
166 && !info.flags.contains(ProcessInfoFlags::EXITED)
167 })
168 .unwrap_or_default()
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175 use fuchsia_async as fasync;
176 use futures::io::AsyncWriteExt as _;
177 use std::os::unix::io::AsRawFd as _;
178 use zx::AsHandleRef as _;
179
180 #[fasync::run_singlethreaded(test)]
181 async fn can_create_pty() -> Result<(), Error> {
182 let _ = ServerPty::new()?;
183 Ok(())
184 }
185
186 #[fasync::run_singlethreaded(test)]
187 async fn can_open_client_pty() -> Result<(), Error> {
188 let server_pty = ServerPty::new()?;
189 let client_pty = server_pty.open_client_pty().await?;
190 assert!(client_pty.as_raw_fd() > 0);
191
192 Ok(())
193 }
194
195 #[fasync::run_singlethreaded(test)]
196 async fn can_spawn_shell_process() -> Result<(), Error> {
197 let server_pty = ServerPty::new()?;
198 let cmd = c"/pkg/bin/sh";
199 let process = server_pty.spawn_with_argv(&cmd, &[cmd], None).await?;
200
201 let mut started = false;
202 if let Ok(info) = process.process_info() {
203 started = info.flags.contains(zx::ProcessInfoFlags::STARTED);
204 }
205
206 assert_eq!(started, true);
207
208 Ok(())
209 }
210
211 #[fasync::run_singlethreaded(test)]
212 async fn shell_process_is_spawned() -> Result<(), Error> {
213 let process = spawn_pty().await?;
214
215 let info = process.process_info().unwrap();
216 assert!(info.flags.contains(zx::ProcessInfoFlags::STARTED));
217
218 Ok(())
219 }
220
221 #[fasync::run_singlethreaded(test)]
222 async fn spawned_shell_process_is_running() -> Result<(), Error> {
223 let process = spawn_pty().await?;
224
225 assert!(process.is_running());
226 Ok(())
227 }
228
229 #[fasync::run_singlethreaded(test)]
230 async fn exited_shell_process_is_not_running() -> Result<(), Error> {
231 let window_size = WindowSize { width: 300 as u32, height: 300 as u32 };
232 let pty = ServerPty::new().unwrap();
233
234 let process = pty.spawn_with_argv(&c"/pkg/bin/exit_with_code_util", &[c"42"], None).await?;
237 let () = process.pty.resize(window_size).await?;
238
239 process
242 .process
243 .wait_handle(
244 zx::Signals::PROCESS_TERMINATED,
245 zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(60)),
246 )
247 .expect("shell process did not exit in time");
248
249 assert!(!process.is_running());
250 Ok(())
251 }
252
253 #[fasync::run_singlethreaded(test)]
254 async fn can_write_to_shell() -> Result<(), Error> {
255 let process = spawn_pty().await?;
256 let mut evented_fd = unsafe { fasync::net::EventedFd::new(process.pty.try_clone_fd()?)? };
261
262 evented_fd.write_all("a".as_bytes()).await?;
263
264 Ok(())
265 }
266
267 #[ignore] #[fasync::run_singlethreaded(test)]
269 async fn shell_process_is_not_running_after_writing_exit() -> Result<(), Error> {
270 let process = spawn_pty().await?;
271 let mut evented_fd = unsafe { fasync::net::EventedFd::new(process.pty.try_clone_fd()?)? };
276
277 evented_fd.write_all("exit\n".as_bytes()).await?;
278
279 process
282 .process
283 .wait_handle(
284 zx::Signals::PROCESS_TERMINATED,
285 zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(60)),
286 )
287 .expect("shell process did not exit in time");
288
289 assert!(!process.is_running());
290
291 Ok(())
292 }
293
294 #[fasync::run_singlethreaded(test)]
295 async fn can_resize_window() -> Result<(), Error> {
296 let process = spawn_pty().await?;
297 let () = process.pty.resize(WindowSize { width: 400, height: 400 }).await?;
298 Ok(())
299 }
300
301 async fn spawn_pty() -> Result<ShellProcess, Error> {
302 let window_size = WindowSize { width: 300 as u32, height: 300 as u32 };
303 let pty = ServerPty::new()?;
304 let process = pty.spawn(Some(&c"/pkg/bin/sh"), None).await.context("failed to spawn")?;
305 let () = process.pty.resize(window_size).await?;
306 Ok(process)
307 }
308}