ctb_workspace_ipc/multiplex/
session.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Session-layer helpers for framed IPC transports.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::auth::capability::TokenValidator;
30use crate::error::Error;
31use crate::error::to_ipc_error;
32use crate::protocol::{Hello, HelloErr, HelloOk, Message};
33use crate::router::{ConnectionContext, Router};
34use crate::transport::FramedConnection;
35use crate::types::ConnectionId;
36use anyhow::anyhow;
37use async_trait::async_trait;
38use bytes::Bytes;
39use std::fmt::Debug;
40
41/// A higher-level session that speaks the Message protocol over a `FramedConnection`.
42#[async_trait]
43pub trait Session: Send + Sync + std::fmt::Debug {
44    /// Send a structured message.
45    async fn send(&self, msg: &Message) -> Result<(), Error>;
46
47    /// Receive the next structured message (deserializing from frames). None on EOF.
48    async fn recv(&self) -> Result<Option<Message>, Error>;
49
50    /// Send a file descriptor via `SCM_RIGHTS` (Unix only).
51    ///
52    /// This is used for transferring memfd-backed shared memory blobs.
53    /// The FD should be sent after the control message that references it.
54    #[cfg(unix)]
55    async fn send_fd(&self, fd: std::os::unix::io::RawFd) -> Result<(), Error> {
56        let _ = fd;
57        Err(Error::Unsupported(
58            "FD passing not supported on this session".to_string(),
59        ))
60    }
61
62    /// Receive a file descriptor via `SCM_RIGHTS` (Unix only).
63    ///
64    /// This is used for receiving memfd-backed shared memory blobs.
65    /// The FD should be received after the control message that references it.
66    #[cfg(unix)]
67    async fn recv_fd(&self) -> Result<std::os::unix::io::RawFd, Error> {
68        Err(Error::Unsupported(
69            "FD passing not supported on this session".to_string(),
70        ))
71    }
72
73    /// Client-side handshake helper.
74    ///
75    /// Sends `Hello` and waits for `HelloOk` or `HelloErr`. Returns bound capability
76    /// set on success. Avoids panics; errors map to [`Error`].
77    async fn client_handshake(
78        &self,
79        hello: Hello,
80    ) -> Result<crate::auth::capability::CapabilitySet, Error>
81    where
82        Self: Sized,
83    {
84        self.send(&Message::Hello(hello)).await?;
85        loop {
86            let Some(msg) = self.recv().await? else {
87                return Err(to_ipc_error(anyhow!("eof before HelloOk")));
88            };
89            match msg {
90                Message::HelloOk(ok) => {
91                    return Ok(ok.bound_capabilities);
92                }
93                Message::HelloErr(err) => {
94                    return Err(to_ipc_error(anyhow!(
95                        "handshake failed: {}",
96                        err.message
97                    )));
98                }
99                // Ignore unrelated messages during handshake.
100                _ => {}
101            }
102        }
103    }
104
105    /// Server-side handshake helper.
106    ///
107    /// Waits for Hello, validates the token, replies with HelloOk/HelloErr,
108    /// and registers the connection on success.
109    async fn server_handshake(
110        &self,
111        validator: &dyn TokenValidator,
112        router: &dyn Router,
113        connection_id: ConnectionId,
114    ) -> Result<crate::auth::capability::CapabilitySet, Error>
115    where
116        Self: Sized,
117    {
118        let Some(msg) = self.recv().await? else {
119            return Err(to_ipc_error(anyhow!("eof awaiting Hello")));
120        };
121        let Message::Hello(hello) = msg else {
122            return Err(to_ipc_error(anyhow!("expected Hello")));
123        };
124
125        let bound = match validator.validate(&hello.token) {
126            Ok(set) => set,
127            Err(e) => {
128                // Send HelloErr and return error.
129                let _ = self
130                    .send(&Message::HelloErr(HelloErr::new(format!("{e:#}"))))
131                    .await;
132                return Err(to_ipc_error(anyhow!("token invalid: {e:#}")));
133            }
134        };
135
136        // Send success response.
137        self.send(&Message::HelloOk(HelloOk::new(bound.clone())))
138            .await?;
139
140        // Register connection context.
141        let ctx = ConnectionContext {
142            id: connection_id,
143            capabilities: bound.clone(),
144            metadata: hello.client_info.as_ref().map(|ci| {
145                serde_json::json!({
146                    "name": ci.name,
147                    "version": ci.version,
148                    "process_kind": ci.process_kind
149                })
150            }),
151        };
152        router.register_connection(ctx).await?;
153
154        Ok(bound)
155    }
156}
157
158/// Adapter implementing Session on top of a framed connection that transports
159/// raw Bytes. Messages are encoded/decoded with postcard.
160#[derive(Debug)]
161pub struct FramedSession<T> {
162    inner: T,
163    #[cfg(unix)]
164    fd_queue: tokio::sync::Mutex<Vec<std::os::unix::io::RawFd>>,
165    #[cfg(unix)]
166    fd_notify: tokio::sync::Notify,
167}
168
169impl<T: Clone + std::fmt::Debug> FramedSession<T> {
170    /// Create a new framed session from a lower-level transport.
171    pub fn new(inner: T) -> Self {
172        Self {
173            inner,
174            #[cfg(unix)]
175            fd_queue: tokio::sync::Mutex::new(Vec::new()),
176            #[cfg(unix)]
177            fd_notify: tokio::sync::Notify::new(),
178        }
179    }
180}
181
182#[async_trait]
183impl<T> Session for FramedSession<T>
184where
185    T: FramedConnection + Clone + std::fmt::Debug + 'static,
186{
187    /// Serialize Message with postcard and send as a single frame.
188    async fn send(&self, msg: &Message) -> Result<(), Error> {
189        let bytes = postcard_helpers::encode(msg, "Message")
190            .context("postcard serialize Message")
191            .map_err(to_ipc_error)?;
192        self.inner.send_frame(Bytes::from(bytes)).await
193    }
194
195    /// Receive one frame, deserialize with postcard into Message.
196    async fn recv(&self) -> Result<Option<Message>, Error> {
197        loop {
198            #[cfg(unix)]
199            let maybe = self.inner.recv_frame_with_fds().await?;
200            #[cfg(not(unix))]
201            let maybe = self
202                .inner
203                .recv_frame()
204                .await?
205                .map(|frame| (frame, Vec::<i32>::new()));
206
207            let Some((frame, fds)) = maybe else {
208                return Ok(None);
209            };
210
211            #[cfg(unix)]
212            {
213                if !fds.is_empty() {
214                    let mut q = self.fd_queue.lock().await;
215                    q.extend(fds);
216                    self.fd_notify.notify_waiters();
217                }
218
219                // 0xFD is a transport-only marker used by `send_fd`.
220                if frame.as_ref() == [0xFD] {
221                    continue;
222                }
223            }
224
225            let msg = postcard_helpers::decode::<Message>(&frame, "Message")
226                .context("postcard deserialize Message")
227                .map_err(to_ipc_error)?;
228            return Ok(Some(msg));
229        }
230    }
231
232    /// Send a file descriptor via `SCM_RIGHTS` (Unix only).
233    ///
234    /// This delegates to the underlying `FramedConnection`'s FD passing support.
235    /// The FD is sent alongside a dummy frame (FD passing requires at least 1
236    /// byte of data in the sendmsg call).
237    #[cfg(unix)]
238    async fn send_fd(&self, fd: std::os::unix::io::RawFd) -> Result<(), Error> {
239        self.inner
240            .send_frame_with_fds(Bytes::from_static(&[0xFD]), &[fd])
241            .await
242    }
243
244    /// Receive a file descriptor via `SCM_RIGHTS` (Unix only).
245    ///
246    /// This delegates to the underlying `FramedConnection`'s FD passing support.
247    #[cfg(unix)]
248    async fn recv_fd(&self) -> Result<std::os::unix::io::RawFd, Error> {
249        loop {
250            if let Some(fd) = self.fd_queue.lock().await.pop() {
251                return Ok(fd);
252            }
253            self.fd_notify.notified().await;
254        }
255    }
256}
257
258// NOTE:
259// `Arc<T>` implements `FramedConnection` via a blanket impl in `transport.rs`,
260// including `send_frame_with_fds` / `recv_frame_with_fds` on Unix.
261//
262// Keep FD passing support on the `Session` trait (and on `FramedSession<T>`)
263// rather than adding transport-specific inherent helpers here.