Skip to main content

lsdocs_rpc/
transport.rs

1//! Byte streams a [`Peer`](crate::Peer) runs over, and how frames are cut
2//! from them.
3//!
4//! Each frame is a 4-byte big-endian length followed by that many bytes of
5//! MessagePack. Frames over [`Options::max_frame_len`](crate::Options) are
6//! rejected before they are read into memory.
7//!
8//! - [`stdio`]: for a plugin talking to the host over its stdin and stdout.
9//!   It calls [`protect_stdout`] first, so stray prints cannot corrupt the
10//!   stream.
11//! - [`pipe`]: a named pipe (Windows) or unix socket. The host listens and
12//!   passes the name to the plugin in [`pipe::ENV_VAR`].
13//! - [`memory`]: an in-process pair, for tests and first-party plugins.
14
15use std::io;
16use std::sync::atomic::{AtomicBool, Ordering};
17
18use tokio::io::{AsyncRead, AsyncWrite};
19use tokio_util::codec::LengthDelimitedCodec;
20
21/// Default for [`Options::max_frame_len`](crate::Options): 64 MiB.
22pub const DEFAULT_MAX_FRAME_LEN: usize = 64 * 1024 * 1024;
23
24/// A boxed reading half.
25pub type BoxReader = Box<dyn AsyncRead + Send + Unpin>;
26/// A boxed writing half.
27pub type BoxWriter = Box<dyn AsyncWrite + Send + Unpin>;
28
29/// The two halves of a byte stream.
30pub struct Transport {
31    /// Where incoming bytes come from.
32    pub reader: BoxReader,
33    /// Where outgoing bytes go.
34    pub writer: BoxWriter,
35}
36
37impl Transport {
38    /// Wraps separate reading and writing halves.
39    pub fn new(
40        reader: impl AsyncRead + Send + Unpin + 'static,
41        writer: impl AsyncWrite + Send + Unpin + 'static,
42    ) -> Self {
43        Self {
44            reader: Box::new(reader),
45            writer: Box::new(writer),
46        }
47    }
48
49    /// Splits a bidirectional stream into a transport.
50    pub fn from_stream(stream: impl AsyncRead + AsyncWrite + Send + 'static) -> Self {
51        let (reader, writer) = tokio::io::split(stream);
52        Self::new(reader, writer)
53    }
54}
55
56impl std::fmt::Debug for Transport {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.write_str("Transport { .. }")
59    }
60}
61
62/// The frame codec: u32 big-endian length prefix.
63pub(crate) fn codec(max_frame_len: usize) -> LengthDelimitedCodec {
64    LengthDelimitedCodec::builder()
65        .length_field_type::<u32>()
66        .max_frame_length(max_frame_len)
67        .new_codec()
68}
69
70/// Two connected in-memory transports.
71pub fn memory() -> (Transport, Transport) {
72    let (a, b) = tokio::io::duplex(64 * 1024);
73    (Transport::from_stream(a), Transport::from_stream(b))
74}
75
76/// A transport over this process's stdin and stdout, for a plugin launched
77/// by the host. Calls [`protect_stdout`], so it can be used once per
78/// process. Must be called inside a tokio runtime.
79pub fn stdio() -> io::Result<Transport> {
80    let stdout = tokio::fs::File::from_std(protect_stdout()?);
81    Ok(Transport::new(ThreadStdin::spawn()?, stdout))
82}
83
84/// Stdin read on a dedicated, detached thread.
85///
86/// `tokio::io::stdin` reads on tokio's blocking pool, and that read cannot be
87/// cancelled, so a plugin that finishes while the host still holds its stdin
88/// open would hang at runtime shutdown. A detached thread does not hold up
89/// shutdown and simply ends with the process.
90struct ThreadStdin {
91    rx: tokio::sync::mpsc::Receiver<io::Result<bytes::Bytes>>,
92    buf: bytes::Bytes,
93}
94
95impl ThreadStdin {
96    fn spawn() -> io::Result<Self> {
97        use std::io::Read;
98        let (tx, rx) = tokio::sync::mpsc::channel(4);
99        std::thread::Builder::new()
100            .name("lsdocs-stdin".into())
101            .spawn(move || {
102                let mut stdin = std::io::stdin().lock();
103                let mut buf = vec![0u8; 64 * 1024];
104                loop {
105                    let item = match stdin.read(&mut buf) {
106                        // EOF: dropping `tx` ends the stream.
107                        Ok(0) => break,
108                        Ok(n) => Ok(bytes::Bytes::copy_from_slice(&buf[..n])),
109                        Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
110                        Err(e) => Err(e),
111                    };
112                    let failed = item.is_err();
113                    if tx.blocking_send(item).is_err() || failed {
114                        break;
115                    }
116                }
117            })?;
118        Ok(Self {
119            rx,
120            buf: bytes::Bytes::new(),
121        })
122    }
123}
124
125impl AsyncRead for ThreadStdin {
126    fn poll_read(
127        mut self: std::pin::Pin<&mut Self>,
128        cx: &mut std::task::Context<'_>,
129        out: &mut tokio::io::ReadBuf<'_>,
130    ) -> std::task::Poll<io::Result<()>> {
131        use bytes::Buf;
132        use std::task::Poll;
133        if self.buf.is_empty() {
134            match self.rx.poll_recv(cx) {
135                Poll::Pending => return Poll::Pending,
136                // Reading nothing signals EOF.
137                Poll::Ready(None) => return Poll::Ready(Ok(())),
138                Poll::Ready(Some(Err(e))) => return Poll::Ready(Err(e)),
139                Poll::Ready(Some(Ok(chunk))) => self.buf = chunk,
140            }
141        }
142        let n = out.remaining().min(self.buf.len());
143        out.put_slice(&self.buf[..n]);
144        self.buf.advance(n);
145        Poll::Ready(Ok(()))
146    }
147}
148
149static STDOUT_TAKEN: AtomicBool = AtomicBool::new(false);
150
151/// Takes this process's real stdout for exclusive use and points stdout at
152/// stderr, so later prints (from Rust, C libraries or an embedded Python or
153/// Node runtime that writes to the standard handle) go to stderr instead of
154/// corrupting the protocol stream.
155///
156/// Returns the real stdout as a file. Fails if called more than once.
157///
158/// Language runtimes that cache their own stdout object (e.g. Python's
159/// `sys.stdout`) must also be redirected by the binding.
160pub fn protect_stdout() -> io::Result<std::fs::File> {
161    if STDOUT_TAKEN.swap(true, Ordering::SeqCst) {
162        return Err(io::Error::other("stdout has already been taken"));
163    }
164    use std::io::Write;
165    // Anything already buffered belongs on the original stream.
166    let _ = std::io::stdout().flush();
167    sys::protect_stdout()
168}
169
170#[cfg(unix)]
171#[allow(unsafe_code)]
172mod sys {
173    use std::fs::File;
174    use std::io;
175    use std::os::fd::FromRawFd;
176
177    pub fn protect_stdout() -> io::Result<File> {
178        // SAFETY: plain fd syscalls; the duplicated fd is owned by the
179        // returned File and nothing else.
180        unsafe {
181            let real = libc::fcntl(libc::STDOUT_FILENO, libc::F_DUPFD_CLOEXEC, 3);
182            if real < 0 {
183                return Err(io::Error::last_os_error());
184            }
185            if libc::dup2(libc::STDERR_FILENO, libc::STDOUT_FILENO) < 0 {
186                let e = io::Error::last_os_error();
187                libc::close(real);
188                return Err(e);
189            }
190            Ok(File::from_raw_fd(real))
191        }
192    }
193}
194
195#[cfg(windows)]
196#[allow(unsafe_code)]
197mod sys {
198    use std::fs::File;
199    use std::io;
200    use std::os::windows::io::FromRawHandle;
201
202    use windows_sys::Win32::Foundation::{
203        CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE, INVALID_HANDLE_VALUE,
204    };
205    use windows_sys::Win32::System::Console::{
206        GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, SetStdHandle,
207    };
208    use windows_sys::Win32::System::Threading::GetCurrentProcess;
209
210    pub fn protect_stdout() -> io::Result<File> {
211        // SAFETY: Win32 handle calls on this process's own standard handles.
212        // The duplicated handle is owned by the returned File and nothing
213        // else.
214        unsafe {
215            let out = GetStdHandle(STD_OUTPUT_HANDLE);
216            if out.is_null() || out == INVALID_HANDLE_VALUE {
217                return Err(io::Error::new(
218                    io::ErrorKind::NotFound,
219                    "process has no stdout",
220                ));
221            }
222            let mut real: HANDLE = std::ptr::null_mut();
223            let process = GetCurrentProcess();
224            if DuplicateHandle(
225                process,
226                out,
227                process,
228                &mut real,
229                0,
230                0,
231                DUPLICATE_SAME_ACCESS,
232            ) == 0
233            {
234                return Err(io::Error::last_os_error());
235            }
236            // Win32 callers, including Rust's std, look the handle up on
237            // every write.
238            if SetStdHandle(STD_OUTPUT_HANDLE, GetStdHandle(STD_ERROR_HANDLE)) == 0 {
239                let e = io::Error::last_os_error();
240                CloseHandle(real);
241                return Err(e);
242            }
243            // The C runtime's fd 1 (used by printf and embedded runtimes)
244            // keeps its own copy. This fails harmlessly when the CRT has no
245            // stdio fds, e.g. with no console.
246            libc::dup2(2, 1);
247            Ok(File::from_raw_handle(real as _))
248        }
249    }
250}
251
252/// Named pipe (Windows) or unix socket transports.
253///
254/// The host binds a [`Listener`] to a name from [`unique_name`], launches the
255/// plugin with that name in the [`ENV_VAR`] environment variable, and
256/// accepts one connection. The plugin calls [`connect_from_env`].
257pub mod pipe {
258    use std::io;
259    use std::sync::atomic::{AtomicU32, Ordering};
260
261    use super::Transport;
262
263    /// Environment variable holding the pipe name for the plugin.
264    pub const ENV_VAR: &str = "LSDOCS_PIPE";
265
266    /// A name no other listener in this process uses.
267    pub fn unique_name() -> String {
268        static NEXT: AtomicU32 = AtomicU32::new(0);
269        let id = format!(
270            "lsdocs-{}-{}",
271            std::process::id(),
272            NEXT.fetch_add(1, Ordering::Relaxed)
273        );
274        #[cfg(windows)]
275        {
276            format!(r"\\.\pipe\{id}")
277        }
278        #[cfg(unix)]
279        {
280            std::env::temp_dir()
281                .join(format!("{id}.sock"))
282                .to_string_lossy()
283                .into_owned()
284        }
285    }
286
287    /// Waits for one plugin to connect.
288    #[derive(Debug)]
289    pub struct Listener {
290        #[cfg(windows)]
291        server: tokio::net::windows::named_pipe::NamedPipeServer,
292        #[cfg(unix)]
293        listener: tokio::net::UnixListener,
294        #[cfg(unix)]
295        path: std::path::PathBuf,
296    }
297
298    impl Listener {
299        /// Creates the pipe or socket. Must be called inside a tokio runtime.
300        pub fn bind(name: &str) -> io::Result<Self> {
301            #[cfg(windows)]
302            {
303                let server = tokio::net::windows::named_pipe::ServerOptions::new()
304                    .first_pipe_instance(true)
305                    .create(name)?;
306                Ok(Self { server })
307            }
308            #[cfg(unix)]
309            {
310                let listener = tokio::net::UnixListener::bind(name)?;
311                Ok(Self {
312                    listener,
313                    path: name.into(),
314                })
315            }
316        }
317
318        /// Waits for the plugin to connect.
319        pub async fn accept(self) -> io::Result<Transport> {
320            #[cfg(windows)]
321            {
322                // No Drop impl on Windows, so the server can be moved out.
323                self.server.connect().await?;
324                Ok(Transport::from_stream(self.server))
325            }
326            #[cfg(unix)]
327            {
328                let (stream, _) = self.listener.accept().await?;
329                Ok(Transport::from_stream(stream))
330            }
331        }
332    }
333
334    #[cfg(unix)]
335    impl Drop for Listener {
336        fn drop(&mut self) {
337            let _ = std::fs::remove_file(&self.path);
338        }
339    }
340
341    /// Connects to a listener.
342    pub async fn connect(name: &str) -> io::Result<Transport> {
343        #[cfg(windows)]
344        {
345            use std::time::Duration;
346            use tokio::net::windows::named_pipe::ClientOptions;
347            // ERROR_PIPE_BUSY: another client is mid-connect; retry briefly.
348            const ERROR_PIPE_BUSY: i32 = 231;
349            let mut attempts = 0;
350            loop {
351                match ClientOptions::new().open(name) {
352                    Ok(client) => return Ok(Transport::from_stream(client)),
353                    Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) && attempts < 100 => {
354                        attempts += 1;
355                        tokio::time::sleep(Duration::from_millis(20)).await;
356                    }
357                    Err(e) => return Err(e),
358                }
359            }
360        }
361        #[cfg(unix)]
362        {
363            Ok(Transport::from_stream(
364                tokio::net::UnixStream::connect(name).await?,
365            ))
366        }
367    }
368
369    /// Connects to the listener named in [`ENV_VAR`].
370    pub async fn connect_from_env() -> io::Result<Transport> {
371        let name = std::env::var(ENV_VAR).map_err(|_| {
372            io::Error::new(io::ErrorKind::NotFound, format!("{ENV_VAR} is not set"))
373        })?;
374        connect(&name).await
375    }
376}