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!("pty", "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!("pty", "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::NullableHandle::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!("pty", "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!("pty", "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!("pty", "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
179 #[fasync::run_singlethreaded(test)]
180 async fn can_create_pty() -> Result<(), Error> {
181 let _ = ServerPty::new()?;
182 Ok(())
183 }
184
185 #[fasync::run_singlethreaded(test)]
186 async fn can_open_client_pty() -> Result<(), Error> {
187 let server_pty = ServerPty::new()?;
188 let client_pty = server_pty.open_client_pty().await?;
189 assert!(client_pty.as_raw_fd() > 0);
190
191 Ok(())
192 }
193
194 #[fasync::run_singlethreaded(test)]
195 async fn can_spawn_shell_process() -> Result<(), Error> {
196 let server_pty = ServerPty::new()?;
197 let cmd = c"/pkg/bin/sh";
198 let process = server_pty.spawn_with_argv(&cmd, &[cmd], None).await?;
199
200 let mut started = false;
201 if let Ok(info) = process.process_info() {
202 started = info.flags.contains(zx::ProcessInfoFlags::STARTED);
203 }
204
205 assert_eq!(started, true);
206
207 Ok(())
208 }
209
210 #[fasync::run_singlethreaded(test)]
211 async fn shell_process_is_spawned() -> Result<(), Error> {
212 let process = spawn_pty().await?;
213
214 let info = process.process_info().unwrap();
215 assert!(info.flags.contains(zx::ProcessInfoFlags::STARTED));
216
217 Ok(())
218 }
219
220 #[fasync::run_singlethreaded(test)]
221 async fn spawned_shell_process_is_running() -> Result<(), Error> {
222 let process = spawn_pty().await?;
223
224 assert!(process.is_running());
225 Ok(())
226 }
227
228 #[fasync::run_singlethreaded(test)]
229 async fn exited_shell_process_is_not_running() -> Result<(), Error> {
230 let window_size = WindowSize { width: 300 as u32, height: 300 as u32 };
231 let pty = ServerPty::new().unwrap();
232
233 let process = pty.spawn_with_argv(&c"/pkg/bin/exit_with_code_util", &[c"42"], None).await?;
236 let () = process.pty.resize(window_size).await?;
237
238 process
241 .process
242 .wait_one(
243 zx::Signals::PROCESS_TERMINATED,
244 zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(60)),
245 )
246 .expect("shell process did not exit in time");
247
248 assert!(!process.is_running());
249 Ok(())
250 }
251
252 #[fasync::run_singlethreaded(test)]
253 async fn can_write_to_shell() -> Result<(), Error> {
254 let process = spawn_pty().await?;
255 let mut evented_fd = unsafe { fasync::net::EventedFd::new(process.pty.try_clone_fd()?)? };
260
261 evented_fd.write_all("a".as_bytes()).await?;
262
263 Ok(())
264 }
265
266 #[ignore] #[fasync::run_singlethreaded(test)]
268 async fn shell_process_is_not_running_after_writing_exit() -> Result<(), Error> {
269 let process = spawn_pty().await?;
270 let mut evented_fd = unsafe { fasync::net::EventedFd::new(process.pty.try_clone_fd()?)? };
275
276 evented_fd.write_all("exit\n".as_bytes()).await?;
277
278 process
281 .process
282 .wait_one(
283 zx::Signals::PROCESS_TERMINATED,
284 zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(60)),
285 )
286 .expect("shell process did not exit in time");
287
288 assert!(!process.is_running());
289
290 Ok(())
291 }
292
293 #[fasync::run_singlethreaded(test)]
294 async fn can_resize_window() -> Result<(), Error> {
295 let process = spawn_pty().await?;
296 let () = process.pty.resize(WindowSize { width: 400, height: 400 }).await?;
297 Ok(())
298 }
299
300 async fn spawn_pty() -> Result<ShellProcess, Error> {
301 let window_size = WindowSize { width: 300 as u32, height: 300 as u32 };
302 let pty = ServerPty::new()?;
303 let process = pty.spawn(Some(&c"/pkg/bin/sh"), None).await.context("failed to spawn")?;
304 let () = process.pty.resize(window_size).await?;
305 Ok(process)
306 }
307}