Skip to main content

hyprstream_9p/
socket_transport.rs

1//! Socket-backed [`P9Transport`] — a native 9P transport over a byte stream.
2//!
3//! This is the **client-side** counterpart to the server-side [`Translator`]
4//! accept loop: where the translator *reads* length-prefixed 9P frames off a
5//! `tokio::net` stream and *dispatches* them to a [`Backend`], `SocketTransport`
6//! *carries* complete 9P frames between a [`P9Client`] and a remote 9P2000.L
7//! server over the same wire (a Unix domain socket or TCP). It is the inverse of
8//! the DMA transport ([`crate::dma`]): identical [`P9Transport`] contract, but a
9//! real OS socket instead of a SharedArrayBuffer ring, so it carries across
10//! process (and host) boundaries.
11//!
12//! ## Framing contract
13//!
14//! [`P9Client`] hands `send` a complete 9P message whose first four bytes are the
15//! self-counting `size[4]` field, and expects `recv` to return exactly one such
16//! complete frame. `recv` therefore reads the 4-byte length prefix first, then
17//! the `size - 4` remaining body bytes, handling partial reads via
18//! [`read_exact`](tokio::io::AsyncReadExt::read_exact) — matching the framing the
19//! [`Translator`] itself uses on the server side.
20//!
21//! ## Concurrency
22//!
23//! The read and write halves each sit behind their own async `Mutex`, so the
24//! transport is `Send + Sync`. Whole request/response pairs are serialized one
25//! level up (in [`Remote9pMount`](crate::remote_mount::Remote9pMount), which
26//! holds the [`P9Client`] behind a single mutex), which is what keeps
27//! interleaved T-messages from racing on one connection.
28//!
29//! [`Translator`]: crate::translator::Translator
30//! [`Backend`]: crate::backend::Backend
31//! [`P9Client`]: crate::client::P9Client
32
33use std::path::Path;
34
35use anyhow::{Context, Result};
36use tokio::io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf};
37use tokio::net::{TcpStream, UnixStream};
38use tokio::sync::Mutex;
39
40use crate::client::P9Transport;
41
42/// A [`P9Transport`] backed by an `AsyncRead + AsyncWrite` byte stream.
43///
44/// Construct it directly from any stream via [`SocketTransport::new`], or use the
45/// [`connect_uds`](SocketTransport::connect_uds) /
46/// [`connect_tcp`](SocketTransport::connect_tcp) helpers for the common Unix and
47/// TCP cases.
48pub struct SocketTransport<S> {
49    rx: Mutex<ReadHalf<S>>,
50    tx: Mutex<WriteHalf<S>>,
51}
52
53impl<S> SocketTransport<S>
54where
55    S: AsyncRead + AsyncWrite + Send + 'static,
56{
57    /// Wrap an already-connected byte stream as a 9P transport.
58    pub fn new(stream: S) -> Self {
59        let (rx, tx) = split(stream);
60        Self {
61            rx: Mutex::new(rx),
62            tx: Mutex::new(tx),
63        }
64    }
65}
66
67impl SocketTransport<UnixStream> {
68    /// Dial a 9P server listening on a Unix domain socket at `path`.
69    pub async fn connect_uds(path: impl AsRef<Path>) -> Result<Self> {
70        let path = path.as_ref();
71        let stream = UnixStream::connect(path)
72            .await
73            .with_context(|| format!("connect 9P UDS at {path:?}"))?;
74        Ok(Self::new(stream))
75    }
76}
77
78impl SocketTransport<TcpStream> {
79    /// Dial a 9P server listening on a TCP `addr`.
80    pub async fn connect_tcp(addr: impl tokio::net::ToSocketAddrs) -> Result<Self> {
81        let stream = TcpStream::connect(addr)
82            .await
83            .context("connect 9P TCP endpoint")?;
84        // 9P is request/response with small messages; disable Nagle to avoid
85        // coalescing latency. Best-effort — failure here is non-fatal.
86        let _ = stream.set_nodelay(true);
87        Ok(Self::new(stream))
88    }
89}
90
91#[async_trait::async_trait]
92impl<S> P9Transport for SocketTransport<S>
93where
94    S: AsyncRead + AsyncWrite + Send + 'static,
95{
96    async fn send(&self, data: &[u8]) -> Result<()> {
97        let mut tx = self.tx.lock().await;
98        tx.write_all(data).await.context("9P socket send")?;
99        tx.flush().await.context("9P socket flush")?;
100        Ok(())
101    }
102
103    async fn recv(&self) -> Result<Vec<u8>> {
104        let mut rx = self.rx.lock().await;
105
106        // Read the 4-byte self-counting size prefix first...
107        let mut len_buf = [0u8; 4];
108        rx.read_exact(&mut len_buf)
109            .await
110            .context("9P socket recv: size prefix")?;
111        let total = u32::from_le_bytes(len_buf) as usize;
112
113        // A valid 9P2000.L message is at least size[4] + type[1] + tag[2].
114        if total < 7 {
115            anyhow::bail!("invalid 9P frame size: {total}");
116        }
117
118        // ...then the remaining `total - 4` body bytes. `read_exact` loops over
119        // partial reads until the full frame has arrived.
120        let mut buf = vec![0u8; total];
121        buf[..4].copy_from_slice(&len_buf);
122        rx.read_exact(&mut buf[4..])
123            .await
124            .context("9P socket recv: message body")?;
125        Ok(buf)
126    }
127}