Skip to main content

rpi_cli/host/
client.rs

1//! Explicit, bounded Unix IPC client for shared Host control. No discovery,
2//! process spawn, transcript access, retry, background reader or Agent ownership.
3//! A dropped exchange closes its connection: it does not undo remote work.
4
5use super::protocol::*;
6#[cfg(unix)]
7use serde::de::DeserializeOwned;
8#[cfg(unix)]
9use serde::Serialize;
10use std::{fmt, path::PathBuf, time::Duration};
11#[cfg(unix)]
12use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
13
14#[derive(Clone)]
15pub struct ConnectionConfig {
16    pub socket_path: PathBuf,
17    pub host_id: HostId,
18    pub token: AuthToken,
19    /// Total connect + filesystem preflight + authentication budget; also the
20    /// total budget of each subsequent exchange, never reset per frame byte.
21    pub timeout: Duration,
22}
23impl fmt::Debug for ConnectionConfig {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.debug_struct("ConnectionConfig")
26            .field("host_id", &self.host_id)
27            .field("timeout", &self.timeout)
28            .finish_non_exhaustive()
29    }
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum Failure {
34    UnsupportedPlatform,
35    InvalidConfiguration,
36    UnsafeEndpoint,
37    Connection,
38    Timeout,
39    Closed,
40    FrameTooLarge,
41    MalformedFrame,
42    IncompatiblePeer,
43    UnsupportedCapability,
44    InvalidCommand,
45    Correlation,
46    EpochChanged,
47}
48
49/// These errors intentionally omit raw peer data, paths, tokens and OS error
50/// Display strings. A mutation's uncertain outcome is NOT a retry instruction.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum ClientError {
53    NotSent(Failure),
54    QueryFailed(Failure),
55    OutcomeUnknown {
56        request_id: RequestId,
57        reason: Failure,
58    },
59    Rejected(ErrorCode),
60}
61impl fmt::Display for ClientError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::NotSent(reason) => write!(f, "shared Host request not sent: {reason:?}"),
65            Self::QueryFailed(reason) => write!(f, "shared Host query failed: {reason:?}"),
66            Self::OutcomeUnknown { request_id, reason } => write!(f,
67                "shared Host outcome unknown for request {request_id}: {reason:?}; query its receipt before retrying"),
68            Self::Rejected(code) => write!(f, "shared Host rejected request: {code:?}"),
69        }
70    }
71}
72impl std::error::Error for ClientError {}
73
74/// One serialized command exchange at a time. Creating another client is an
75/// explicit connection, not another Agent. Drop/detach never sends stop/close.
76pub struct HostClient {
77    #[cfg(unix)]
78    stream: Option<tokio::net::UnixStream>,
79    welcome: Welcome,
80    #[cfg(unix)]
81    timeout: Duration,
82}
83impl fmt::Debug for HostClient {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_struct("HostClient")
86            .field("host_id", &self.welcome.host_id)
87            .field("epoch", &self.welcome.epoch)
88            .finish_non_exhaustive()
89    }
90}
91impl HostClient {
92    #[cfg(unix)]
93    pub async fn connect(config: ConnectionConfig) -> Result<Self, ClientError> {
94        if config.timeout.is_zero()
95            || config.timeout > Duration::from_secs(300)
96            || !config.socket_path.is_absolute()
97        {
98            return Err(ClientError::NotSent(Failure::InvalidConfiguration));
99        }
100        let timeout = config.timeout;
101        let connect = async {
102            check_endpoint(&config.socket_path).await?;
103            let mut stream = tokio::net::UnixStream::connect(&config.socket_path)
104                .await
105                .map_err(|_| Failure::Connection)?;
106            // Recheck the actual connection, not just filesystem metadata. The
107            // parent chain is trusted; this does not isolate hostile same-UID code.
108            let peer = stream.peer_cred().map_err(|_| Failure::UnsafeEndpoint)?;
109            if peer.uid() != nix::unistd::Uid::effective().as_raw() {
110                return Err(Failure::UnsafeEndpoint);
111            }
112            let hello = Hello {
113                protocol: PROTOCOL.into(),
114                version: Version::default(),
115                host_id: config.host_id,
116                token: config.token,
117            };
118            let bytes = encode_frame(&hello, MAX_FRAME_BYTES)?;
119            write_frame(&mut stream, &bytes).await?;
120            let welcome: Welcome = read_frame(&mut stream, MAX_FRAME_BYTES).await?;
121            if !welcome.compatible(config.host_id) {
122                return Err(Failure::IncompatiblePeer);
123            }
124            Ok(Self {
125                stream: Some(stream),
126                welcome,
127                timeout,
128            })
129        };
130        tokio::time::timeout(timeout, connect)
131            .await
132            .map_err(|_| ClientError::NotSent(Failure::Timeout))?
133            .map_err(ClientError::NotSent)
134    }
135
136    #[cfg(not(unix))]
137    pub async fn connect(_config: ConnectionConfig) -> Result<Self, ClientError> {
138        Err(ClientError::NotSent(Failure::UnsupportedPlatform))
139    }
140
141    pub fn welcome(&self) -> &Welcome {
142        &self.welcome
143    }
144
145    #[cfg(unix)]
146    pub async fn call(&mut self, command: Command) -> Result<serde_json::Value, ClientError> {
147        if self.stream.is_none() {
148            return Err(ClientError::NotSent(Failure::Closed));
149        }
150        if !self.welcome.supports(command.capability()) {
151            return Err(ClientError::NotSent(Failure::UnsupportedCapability));
152        }
153        if !command.valid(self.welcome.limits) {
154            return Err(ClientError::NotSent(Failure::InvalidCommand));
155        }
156        let request_id = command.request_id();
157        let request = Request {
158            call_id: CallId::new(),
159            epoch: self.welcome.epoch,
160            command,
161        };
162        let limit = self.welcome.limits.max_frame_bytes;
163        let bytes = encode_frame(&request, limit).map_err(ClientError::NotSent)?;
164        // Move ownership OUT before awaiting. Cancellation midway through either
165        // framing direction drops this socket; no later call can read its reply
166        // as a new request, or append to an incomplete frame.
167        let mut stream = self.stream.take().expect("checked connection");
168        let exchange = async {
169            write_frame(&mut stream, &bytes).await?;
170            let response: Response = read_frame(&mut stream, limit).await?;
171            if response.call_id != request.call_id {
172                return Err(Failure::Correlation);
173            }
174            if response.epoch != request.epoch {
175                return Err(Failure::EpochChanged);
176            }
177            Ok(response.reply)
178        };
179        let result = tokio::time::timeout(self.timeout, exchange)
180            .await
181            .unwrap_or(Err(Failure::Timeout));
182        match result {
183            Ok(reply) => {
184                self.stream = Some(stream);
185                match reply {
186                    Reply::Data { data } => Ok(data),
187                    Reply::Error { code } => Err(ClientError::Rejected(code)),
188                }
189            }
190            Err(reason) => Err(match request_id {
191                Some(request_id) => ClientError::OutcomeUnknown { request_id, reason },
192                None => ClientError::QueryFailed(reason),
193            }),
194        }
195    }
196
197    #[cfg(not(unix))]
198    pub async fn call(&mut self, _command: Command) -> Result<serde_json::Value, ClientError> {
199        Err(ClientError::NotSent(Failure::UnsupportedPlatform))
200    }
201
202    pub fn detach(&mut self) {
203        #[cfg(unix)]
204        {
205            self.stream.take();
206        }
207    }
208}
209
210#[cfg(unix)]
211async fn check_endpoint(path: &std::path::Path) -> Result<(), Failure> {
212    use std::os::unix::fs::{FileTypeExt, MetadataExt};
213    let uid = nix::unistd::Uid::effective().as_raw();
214    let parent = path.parent().ok_or(Failure::InvalidConfiguration)?;
215    let directory = tokio::fs::symlink_metadata(parent)
216        .await
217        .map_err(|_| Failure::UnsafeEndpoint)?;
218    let socket = tokio::fs::symlink_metadata(path)
219        .await
220        .map_err(|_| Failure::UnsafeEndpoint)?;
221    if !directory.is_dir()
222        || directory.uid() != uid
223        || directory.mode() & 0o077 != 0
224        || !socket.file_type().is_socket()
225        || socket.uid() != uid
226        || socket.mode() & 0o077 != 0
227    {
228        return Err(Failure::UnsafeEndpoint);
229    }
230    Ok(())
231}
232
233/// Encoding is bounded; callers must still bound application input before
234/// constructing a large in-memory value. These helpers never log wire data.
235#[cfg(unix)]
236pub(crate) fn encode_frame(value: &impl Serialize, limit: usize) -> Result<Vec<u8>, Failure> {
237    let bytes = serde_json::to_vec(value).map_err(|_| Failure::MalformedFrame)?;
238    if bytes.is_empty() || bytes.len() > limit.min(MAX_FRAME_BYTES) {
239        return Err(Failure::FrameTooLarge);
240    }
241    Ok(bytes)
242}
243#[cfg(unix)]
244pub(crate) async fn write_frame<W: AsyncWrite + Unpin>(
245    writer: &mut W,
246    bytes: &[u8],
247) -> Result<(), Failure> {
248    if bytes.is_empty() || bytes.len() > MAX_FRAME_BYTES {
249        return Err(Failure::FrameTooLarge);
250    }
251    writer
252        .write_u32(bytes.len() as u32)
253        .await
254        .map_err(|_| Failure::Connection)?;
255    writer
256        .write_all(bytes)
257        .await
258        .map_err(|_| Failure::Connection)?;
259    writer.flush().await.map_err(|_| Failure::Connection)
260}
261#[cfg(unix)]
262pub(crate) async fn read_frame<R: AsyncRead + Unpin, T: DeserializeOwned>(
263    reader: &mut R,
264    limit: usize,
265) -> Result<T, Failure> {
266    let length = reader.read_u32().await.map_err(|_| Failure::Connection)? as usize;
267    // Check header BEFORE allocating/reading any announced body.
268    if length == 0 || length > limit.min(MAX_FRAME_BYTES) {
269        return Err(Failure::FrameTooLarge);
270    }
271    let mut bytes = vec![0; length];
272    reader
273        .read_exact(&mut bytes)
274        .await
275        .map_err(|_| Failure::Connection)?;
276    serde_json::from_slice(&bytes).map_err(|_| Failure::MalformedFrame)
277}
278
279#[cfg(all(test, unix))]
280#[path = "client_tests.rs"]
281mod tests;