Skip to main content

socket_to_stdio/
lib.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use anyhow::Context as _;
6use fidl_fuchsia_io as fio;
7use futures::future::Either;
8use futures::stream::StreamExt as _;
9use futures::{AsyncReadExt as _, AsyncWriteExt as _};
10use std::io::StdoutLock;
11use termion::raw::IntoRawMode as _;
12
13/// Abstracts stdout for `connect_socket_to_stdio`. Allows callers to determine if stdout should be
14/// exclusively owned for the duration of the call.
15pub enum Stdout<'a> {
16    /// Exclusive ownership of stdout (nothing else can write to stdout while this exists),
17    /// put into raw mode.
18    Raw(termion::raw::RawTerminal<StdoutLock<'a>>),
19    /// Shared ownership of stdout (output may be interleaved with output from other sources).
20    Buffered,
21}
22
23impl std::io::Write for Stdout<'_> {
24    fn flush(&mut self) -> Result<(), std::io::Error> {
25        match self {
26            Self::Raw(r) => r.flush(),
27            Self::Buffered => std::io::stdout().flush(),
28        }
29    }
30    fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
31        match self {
32            Self::Raw(r) => r.write(buf),
33            Self::Buffered => std::io::stdout().write(buf),
34        }
35    }
36}
37
38impl Stdout<'_> {
39    pub fn raw() -> anyhow::Result<Self> {
40        let stdout = std::io::stdout();
41
42        if !termion::is_tty(&stdout) {
43            anyhow::bail!("interactive mode does not support piping");
44        }
45
46        // Put the host terminal into raw mode, so input characters are not echoed, streams are not
47        // buffered and newlines are not changed.
48        let term_out =
49            stdout.lock().into_raw_mode().context("could not set raw mode on terminal")?;
50
51        Ok(Self::Raw(term_out))
52    }
53
54    pub fn buffered() -> Self {
55        Self::Buffered
56    }
57}
58
59/// Concurrently:
60///   1. locks stdin and copies the input to `socket`
61///   2. reads data from `socket` and writes it to `stdout`
62/// Finishes when the remote end of the socket closes (when (2) completes).
63pub async fn connect_socket_to_stdio(
64    socket: fidl::Socket,
65    stdout: Stdout<'_>,
66) -> anyhow::Result<()> {
67    connect_socket_to_stdio_impl(
68        fuchsia_async::Socket::from_socket(socket),
69        || std::io::stdin().lock(),
70        stdout,
71    )?
72    .await
73}
74
75/// Same as `connect_socket_to_stdio` but operates on an FDomain socket.
76pub async fn connect_fdomain_socket_to_stdio(
77    socket: fdomain_client::Socket,
78    stdout: Stdout<'_>,
79) -> anyhow::Result<()> {
80    connect_socket_to_stdio_impl(socket, || std::io::stdin().lock(), stdout)?.await
81}
82
83fn connect_socket_to_stdio_impl<R>(
84    socket: impl futures::AsyncRead + futures::AsyncWrite,
85    stdin: impl FnOnce() -> R + Send + 'static,
86    mut stdout: impl std::io::Write,
87) -> anyhow::Result<impl futures::Future<Output = anyhow::Result<()>>>
88where
89    R: std::io::Read,
90{
91    // Use a separate thread to read from stdin without blocking the executor.
92    let (stdin_send, mut stdin_recv) = futures::channel::mpsc::unbounded();
93    let _: std::thread::JoinHandle<_> = std::thread::Builder::new()
94        .name("connect_socket_to_stdio stdin thread".into())
95        .spawn(move || {
96            let mut stdin = stdin();
97            let mut buf = [0u8; fio::MAX_BUF as usize];
98            loop {
99                let bytes_read = stdin.read(&mut buf)?;
100                if bytes_read == 0 {
101                    return Ok::<(), anyhow::Error>(());
102                }
103                let () = stdin_send.unbounded_send(buf[..bytes_read].to_vec())?;
104            }
105        })
106        .context("spawning stdin thread")?;
107
108    let (mut socket_in, mut socket_out) = socket.split();
109
110    let stdin_to_socket = async move {
111        while let Some(stdin) = stdin_recv.next().await {
112            socket_out.write_all(&stdin).await.context("writing to socket")?;
113            socket_out.flush().await.context("flushing socket")?;
114        }
115        Ok::<(), anyhow::Error>(())
116    };
117
118    let socket_to_stdout = async move {
119        let mut buf = vec![0u8; fio::MAX_BUF as usize];
120        loop {
121            let bytes_read = socket_in.read(&mut buf).await.context("reading from socket")?;
122            if bytes_read == 0 {
123                break;
124            }
125            stdout.write_all(&buf[..bytes_read]).context("writing to stdout")?;
126            stdout.flush().context("flushing stdout")?;
127        }
128        Ok::<(), anyhow::Error>(())
129    };
130
131    Ok(async move {
132        futures::pin_mut!(stdin_to_socket);
133        futures::pin_mut!(socket_to_stdout);
134        Ok(match futures::future::select(stdin_to_socket, socket_to_stdout).await {
135            Either::Left((stdin_to_socket, socket_to_stdout)) => {
136                let () = stdin_to_socket?;
137                // Wait for output even after stdin closes. The remote may be responding to the
138                // final input, or the remote may not be reading from stdin at all (consider
139                // "bash -c $CMD").
140                let () = socket_to_stdout.await?;
141            }
142            Either::Right((socket_to_stdout, _)) => {
143                let () = socket_to_stdout?;
144                // No reason to wait for stdin because the socket is closed so writing stdin to it
145                // would fail.
146            }
147        })
148    })
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[fuchsia::test]
156    async fn stdin_to_socket() {
157        let (socket, socket_remote) = fidl::Socket::create_stream();
158        let socket_remote = fuchsia_async::Socket::from_socket(socket_remote);
159
160        let connect_fut =
161            connect_socket_to_stdio_impl(socket_remote, || &b"test input"[..], vec![]).unwrap();
162
163        let (connect_res, bytes_from_socket) = futures::join!(connect_fut, async move {
164            let mut socket = fuchsia_async::Socket::from_socket(socket);
165            let mut out = vec![0u8; 100];
166            let bytes_read = socket.read(&mut out).await.unwrap();
167            drop(socket);
168            out.resize(bytes_read, 0);
169            out
170        });
171        let () = connect_res.unwrap();
172
173        assert_eq!(bytes_from_socket, &b"test input"[..]);
174    }
175
176    #[fuchsia::test]
177    async fn socket_to_stdout() {
178        let (socket, socket_remote) = fidl::Socket::create_stream();
179        assert_eq!(socket.write(&b"test input"[..]).unwrap(), 10);
180        drop(socket);
181        let mut stdout = vec![];
182        let (unblocker, block_until) = std::sync::mpsc::channel();
183
184        let socket_remote = fuchsia_async::Socket::from_socket(socket_remote);
185        let () = connect_socket_to_stdio_impl(
186            socket_remote,
187            move || {
188                let () = block_until.recv().unwrap();
189                &[][..]
190            },
191            &mut stdout,
192        )
193        .unwrap()
194        .await
195        .unwrap();
196
197        // let the stdin_to_socket thread finish before test cleanup
198        unblocker.send(()).unwrap();
199
200        assert_eq!(&stdout[..], &b"test input"[..]);
201    }
202}