ctb_workspace_ipc/
transport.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//! Length-delimited framed local-socket transport (Tokio).
21//!
22//! This module provides a Tokio-based implementation of framed connections over
23//! local sockets using a length-delimited codec. It includes both the client
24//! and server sides, allowing for bidirectional communication between processes
25//! on the same machine.
26//!
27//! The implementation is based on Tokio's asynchronous runtime and interprocess
28//! crate for local socket communication. It provides a high-level API for
29//! sending and receiving framed messages, as well as managing connections and
30//! listeners.
31
32#[allow(
33    unused_imports,
34    clippy::wildcard_imports,
35    reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38
39use crate::error::Error;
40use async_trait::async_trait;
41use bytes::{Bytes, BytesMut};
42#[cfg(not(unix))]
43use futures::{SinkExt, StreamExt};
44use interprocess::local_socket::{
45    GenericFilePath, GenericNamespaced, ListenerOptions,
46    tokio::{Listener as TokioListener, Stream as TokioStream, prelude::*},
47};
48#[cfg(unix)]
49use nix::libc;
50#[cfg(unix)]
51use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
52use std::sync::Arc;
53use std::sync::atomic::{AtomicBool, Ordering};
54#[cfg(unix)]
55use tokio::io::unix::AsyncFd;
56use tokio::sync::Mutex;
57#[cfg(not(unix))]
58use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
59
60/// Generate a unique local-socket endpoint string.
61///
62/// On Unix this returns a filesystem path under the system temp directory with
63/// a `.sock` suffix. On Windows this returns a namespaced local-socket name
64/// suitable for interprocess named pipes.
65pub fn unique_endpoint(label: &str) -> String {
66    use std::time::{SystemTime, UNIX_EPOCH};
67
68    let pid = std::process::id();
69    let nanos = SystemTime::now()
70        .duration_since(UNIX_EPOCH)
71        .map(|d| d.as_nanos())
72        // Reason for fallback: system clock before UNIX epoch defaults to 0 nanoseconds for endpoint uniqueness
73        .unwrap_or(0);
74
75    #[cfg(unix)]
76    {
77        let mut p = std::env::temp_dir();
78        p.push(format!("ctb-{label}-{pid}-{nanos}.sock"));
79        p.to_string_lossy().into_owned()
80    }
81
82    #[cfg(windows)]
83    {
84        // Namespaced name for Windows named pipes via interprocess local sockets.
85        format!("ctb-{}-{}-{}", label, pid, nanos)
86    }
87}
88
89/// A framed, length-delimited, duplex connection. Multiplexing is layered
90/// above this.
91#[async_trait]
92pub trait FramedConnection: Send + Sync + std::fmt::Debug {
93    /// Send one frame.
94    async fn send_frame(&self, data: Bytes) -> Result<(), Error>;
95    /// Receive one frame. Returns None on EOF.
96    async fn recv_frame(&self) -> Result<Option<Bytes>, Error>;
97    /// Close half or full connection gracefully.
98    async fn close(&self) -> Result<(), Error>;
99
100    /// Send one frame with file descriptors (Unix `SCM_RIGHTS`).
101    ///
102    /// On platforms that don't support FD passing, this returns an error if
103    /// any FDs are provided.
104    #[cfg(unix)]
105    async fn send_frame_with_fds(
106        &self,
107        data: Bytes,
108        fds: &[std::os::unix::io::RawFd],
109    ) -> Result<(), Error> {
110        if !fds.is_empty() {
111            return Err(Error::Unsupported(
112                "FD passing not supported on this connection".to_string(),
113            ));
114        }
115        self.send_frame(data).await
116    }
117
118    /// Receive one frame with file descriptors (Unix `SCM_RIGHTS`).
119    ///
120    /// Returns the frame and any received FDs. On platforms that don't support
121    /// FD passing, the FD vec will always be empty.
122    #[cfg(unix)]
123    async fn recv_frame_with_fds(
124        &self,
125    ) -> Result<Option<(Bytes, Vec<std::os::unix::io::RawFd>)>, Error> {
126        self.recv_frame()
127            .await
128            .map(|opt| opt.map(|b| (b, Vec::new())))
129    }
130}
131
132/// Blanket implementation of `FramedConnection` for `Arc<T>` where `T`
133/// implements `FramedConnection`. This allows wrapping connections in Arc
134/// for cloning while still using the trait methods.
135#[async_trait]
136impl<T: FramedConnection + ?Sized> FramedConnection for Arc<T> {
137    async fn send_frame(&self, data: Bytes) -> Result<(), Error> {
138        (**self).send_frame(data).await
139    }
140
141    async fn recv_frame(&self) -> Result<Option<Bytes>, Error> {
142        (**self).recv_frame().await
143    }
144
145    async fn close(&self) -> Result<(), Error> {
146        (**self).close().await
147    }
148
149    #[cfg(unix)]
150    async fn send_frame_with_fds(
151        &self,
152        data: Bytes,
153        fds: &[std::os::unix::io::RawFd],
154    ) -> Result<(), Error> {
155        (**self).send_frame_with_fds(data, fds).await
156    }
157
158    #[cfg(unix)]
159    async fn recv_frame_with_fds(
160        &self,
161    ) -> Result<Option<(Bytes, Vec<std::os::unix::io::RawFd>)>, Error> {
162        (**self).recv_frame_with_fds().await
163    }
164}
165
166/// Factory to connect or accept connections using local sockets.
167#[async_trait]
168pub trait TransportFactory: Send + Sync {
169    type Conn: FramedConnection;
170
171    /// Client side: connect to an endpoint (e.g., path or named pipe).
172    async fn connect(&self, endpoint: &str) -> Result<Self::Conn, Error>;
173
174    /// Server side: bind and accept incoming connections.
175    async fn bind(
176        &self,
177        endpoint: &str,
178    ) -> Result<Box<dyn TransportListener<Conn = Self::Conn>>, Error>;
179}
180
181#[async_trait]
182pub trait TransportListener: Send + Sync {
183    type Conn: FramedConnection;
184
185    /// Accept the next connection. Returns None when listener is closed.
186    async fn accept(&self) -> Result<Option<Self::Conn>, Error>;
187
188    /// Close the listener.
189    async fn close(&self) -> Result<(), Error>;
190}
191
192/// Concrete framed connection over a Tokio local socket using a
193/// length-delimited codec.
194#[derive(Debug)]
195pub struct LocalSocketFramedConnection {
196    #[cfg(unix)]
197    stream: AsyncFd<std::os::unix::net::UnixStream>,
198    #[cfg(unix)]
199    read_buf: Mutex<BytesMut>,
200    #[cfg(unix)]
201    pending_fds: Mutex<Vec<RawFd>>,
202    #[cfg(unix)]
203    write_lock: Mutex<()>,
204
205    #[cfg(not(unix))]
206    reader: Mutex<
207        FramedRead<tokio::io::ReadHalf<TokioStream>, LengthDelimitedCodec>,
208    >,
209    #[cfg(not(unix))]
210    writer: Mutex<
211        FramedWrite<tokio::io::WriteHalf<TokioStream>, LengthDelimitedCodec>,
212    >,
213}
214
215#[async_trait]
216impl FramedConnection for LocalSocketFramedConnection {
217    /// Send one frame.
218    async fn send_frame(&self, data: Bytes) -> Result<(), Error> {
219        #[cfg(unix)]
220        {
221            self.send_frame_with_fds(data, &[]).await
222        }
223
224        #[cfg(not(unix))]
225        {
226            let mut guard = self.writer.lock().await;
227            let mut bm = BytesMut::with_capacity(data.len());
228            bm.extend_from_slice(&data);
229            SinkExt::send(&mut *guard, bm.into())
230                .await
231                .map_err(Error::from)
232        }
233    }
234
235    /// Receive one frame. Returns None on EOF.
236    async fn recv_frame(&self) -> Result<Option<Bytes>, Error> {
237        #[cfg(unix)]
238        {
239            let maybe = self.recv_frame_with_fds().await?;
240            if let Some((frame, fds)) = maybe {
241                if !fds.is_empty() {
242                    for fd in fds {
243                        let _ = shared_memory::unix::close_fd(fd);
244                    }
245                }
246                Ok(Some(frame))
247            } else {
248                Ok(None)
249            }
250        }
251
252        #[cfg(not(unix))]
253        {
254            let mut guard = self.reader.lock().await;
255            match StreamExt::next(&mut *guard).await {
256                Some(Ok(bm)) => Ok(Some(bm.freeze())),
257                Some(Err(e)) => Err(Error::from(e)),
258                None => Ok(None),
259            }
260        }
261    }
262
263    /// Close half or full connection gracefully.
264    async fn close(&self) -> Result<(), Error> {
265        #[cfg(unix)]
266        {
267            use std::net::Shutdown;
268            let _guard = self.write_lock.lock().await;
269            let stream = self.stream.get_ref();
270            stream.shutdown(Shutdown::Both).map_err(Error::from)
271        }
272
273        #[cfg(not(unix))]
274        {
275            let mut guard = self.writer.lock().await;
276            SinkExt::close(&mut *guard).await.map_err(Error::from)
277        }
278    }
279
280    #[cfg(unix)]
281    #[expect(
282        clippy::large_futures,
283        reason = "required by async send signature"
284    )]
285    async fn send_frame_with_fds(
286        &self,
287        data: Bytes,
288        fds: &[std::os::unix::io::RawFd],
289    ) -> Result<(), Error> {
290        #[cfg(unix)]
291        {
292            let mut buf = BytesMut::new();
293            let len_u32 = u32::try_from(data.len())?;
294            buf.extend_from_slice(&len_u32.to_be_bytes());
295            buf.extend_from_slice(&data);
296
297            self.send_framed_bytes_with_optional_fds(&buf, Some(fds))
298                .await
299        }
300
301        #[cfg(not(unix))]
302        {
303            let _ = fds;
304            self.send_frame(data).await
305        }
306    }
307
308    #[cfg(unix)]
309    #[expect(
310        clippy::large_futures,
311        reason = "required by async recv signature"
312    )]
313    async fn recv_frame_with_fds(
314        &self,
315    ) -> Result<Option<(Bytes, Vec<std::os::unix::io::RawFd>)>, Error> {
316        #[cfg(unix)]
317        {
318            self.recv_next_framed_message().await
319        }
320
321        #[cfg(not(unix))]
322        {
323            self.recv_frame()
324                .await
325                .map(|opt| opt.map(|b| (b, Vec::new())))
326        }
327    }
328}
329
330/// Unix-specific methods for FD passing via `SCM_RIGHTS`.
331#[cfg(unix)]
332impl LocalSocketFramedConnection {
333    #[expect(
334        unsafe_code,
335        reason = "Cmsg space management requires raw pointers"
336    )]
337    fn sendmsg_with_optional_fds(
338        raw_fd: RawFd,
339        buf: &[u8],
340        fds: Option<&[RawFd]>,
341    ) -> std::io::Result<usize> {
342        use std::mem;
343
344        let mut iov = libc::iovec {
345            iov_base: buf.as_ptr().cast::<libc::c_void>().cast_mut(),
346            iov_len: buf.len(),
347        };
348
349        // SAFETY: msghdr is a standard C struct containing simple fields/pointers, zeroing it is safe.
350        let mut msg: libc::msghdr = unsafe { mem::zeroed() };
351        msg.msg_iov = std::ptr::addr_of_mut!(iov);
352        msg.msg_iovlen = 1;
353
354        let mut cmsg_buf: Vec<u8> = Vec::new();
355        if let Some(fds) = fds {
356            if !fds.is_empty() {
357                let fd_bytes =
358                    mem::size_of::<RawFd>().checked_mul(fds.len()).ok_or_else(
359                        || std::io::Error::other("fd buffer overflow"),
360                    )?;
361                let fd_bytes_u32 =
362                    u32::try_from(fd_bytes).map_err(std::io::Error::other)?;
363
364                // SAFETY: CMSG_SPACE is a libc helper macro that calculates buffer size, safe for positive values.
365                let space = unsafe { libc::CMSG_SPACE(fd_bytes_u32) };
366                let space_usize =
367                    usize::try_from(space).map_err(std::io::Error::other)?;
368                cmsg_buf.resize(space_usize, 0);
369                msg.msg_control = cmsg_buf.as_mut_ptr().cast::<libc::c_void>();
370                // musl and glibc differ for some of these libc struct field
371                // types (e.g., `msg_controllen`). Prefer fallible conversions.
372                msg.msg_controllen =
373                    cmsg_buf.len().try_into().map_err(std::io::Error::other)?;
374
375                // SAFETY: We have verified that the control message buffer is sized correctly, and we write fd data using raw pointers to the allocated space.
376                unsafe {
377                    let cmsg = libc::CMSG_FIRSTHDR(std::ptr::addr_of!(msg));
378                    if cmsg.is_null() {
379                        return Err(std::io::Error::other(
380                            "CMSG_FIRSTHDR returned null",
381                        ));
382                    }
383                    (*cmsg).cmsg_level = libc::SOL_SOCKET;
384                    (*cmsg).cmsg_type = libc::SCM_RIGHTS;
385                    let cmsg_len = libc::CMSG_LEN(fd_bytes_u32)
386                        .try_into()
387                        .map_err(std::io::Error::other)?;
388                    (*cmsg).cmsg_len = cmsg_len;
389
390                    let data = libc::CMSG_DATA(cmsg).cast::<RawFd>();
391                    std::ptr::copy_nonoverlapping(
392                        fds.as_ptr(),
393                        data,
394                        fds.len(),
395                    );
396
397                    msg.msg_controllen = (*cmsg)
398                        .cmsg_len
399                        .try_into()
400                        .map_err(std::io::Error::other)?;
401                }
402            }
403        }
404
405        // SAFETY: sendmsg is a standard libc function. We pass a pointer to a valid msghdr structure.
406        let rc = unsafe {
407            libc::sendmsg(
408                raw_fd,
409                std::ptr::addr_of!(msg),
410                libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
411            )
412        };
413        if rc < 0 {
414            return Err(std::io::Error::last_os_error());
415        }
416
417        usize::try_from(rc).map_err(std::io::Error::other)
418    }
419
420    #[expect(unsafe_code, reason = "Cmsg parsing requires raw pointers")]
421    fn recvmsg_with_fds(
422        raw_fd: RawFd,
423        scratch: &mut [u8],
424    ) -> std::io::Result<(usize, Vec<RawFd>)> {
425        use std::mem;
426
427        let mut iov = libc::iovec {
428            iov_base: scratch.as_mut_ptr().cast::<libc::c_void>(),
429            iov_len: scratch.len(),
430        };
431
432        // Space for up to 16 fds.
433        let fd_bytes = mem::size_of::<RawFd>()
434            .checked_mul(16)
435            .ok_or_else(|| std::io::Error::other("fd buffer overflow"))?;
436        let fd_bytes_u32 =
437            u32::try_from(fd_bytes).map_err(std::io::Error::other)?;
438        // SAFETY: CMSG_SPACE is a libc macro that calculates buffer size, safe for positive inputs.
439        let space = unsafe { libc::CMSG_SPACE(fd_bytes_u32) };
440        let space_usize =
441            usize::try_from(space).map_err(std::io::Error::other)?;
442        let mut cmsg_buf = vec![0u8; space_usize];
443
444        // SAFETY: msghdr is a standard C struct and zeroing it is safe.
445        let mut msg: libc::msghdr = unsafe { mem::zeroed() };
446        msg.msg_iov = std::ptr::addr_of_mut!(iov);
447        msg.msg_iovlen = 1;
448        msg.msg_control = cmsg_buf.as_mut_ptr().cast::<libc::c_void>();
449        msg.msg_controllen =
450            cmsg_buf.len().try_into().map_err(std::io::Error::other)?;
451
452        // SAFETY: recvmsg is a standard libc function. We pass a pointer to a valid msghdr structure.
453        let rc = unsafe {
454            libc::recvmsg(
455                raw_fd,
456                std::ptr::addr_of_mut!(msg),
457                libc::MSG_DONTWAIT,
458            )
459        };
460        if rc < 0 {
461            return Err(std::io::Error::last_os_error());
462        }
463
464        let bytes_read = usize::try_from(rc).map_err(std::io::Error::other)?;
465
466        let mut fds_out = Vec::new();
467        // SAFETY: Iterating over control messages in msghdr control buffer is safe because msg has been populated by recvmsg.
468        unsafe {
469            let mut cmsg = libc::CMSG_FIRSTHDR(std::ptr::addr_of!(msg));
470            while !cmsg.is_null() {
471                if (*cmsg).cmsg_level == libc::SOL_SOCKET
472                    && (*cmsg).cmsg_type == libc::SCM_RIGHTS
473                {
474                    let data = libc::CMSG_DATA(cmsg).cast::<u8>();
475
476                    let header_len = usize::try_from(libc::CMSG_LEN(0))
477                        .map_err(std::io::Error::other)?;
478                    let cmsg_len = usize::try_from((*cmsg).cmsg_len)
479                        .map_err(std::io::Error::other)?;
480                    let data_len = cmsg_len.saturating_sub(header_len);
481                    let fd_size = mem::size_of::<RawFd>();
482                    if fd_size > 0 {
483                        // Reason for fallback: invalid ancillary data length division returns 0 file descriptors
484                        let count = data_len.checked_div(fd_size).unwrap_or(0);
485                        for idx in 0..count {
486                            let byte_off =
487                                idx.checked_mul(fd_size).ok_or_else(|| {
488                                    std::io::Error::other("fd offset overflow")
489                                })?;
490                            let fd_ptr = data.add(byte_off).cast::<RawFd>();
491                            let fd = std::ptr::read_unaligned(fd_ptr);
492                            fds_out.push(fd);
493                        }
494                    }
495                }
496                cmsg = libc::CMSG_NXTHDR(std::ptr::addr_of!(msg), cmsg);
497            }
498        }
499
500        Ok((bytes_read, fds_out))
501    }
502
503    async fn send_framed_bytes_with_optional_fds(
504        &self,
505        buf: &[u8],
506        fds: Option<&[RawFd]>,
507    ) -> Result<(), Error> {
508        let _guard = self.write_lock.lock().await;
509
510        let mut offset = 0usize;
511        let mut first_send = true;
512        while offset < buf.len() {
513            let mut guard =
514                self.stream.writable().await.map_err(Error::from)?;
515
516            let send_result = guard.try_io(|inner| {
517                let raw_fd = inner.get_ref().as_raw_fd();
518                let slice = buf.get(offset..).ok_or_else(|| {
519                    std::io::Error::other("send offset out of range")
520                })?;
521                if first_send {
522                    return Self::sendmsg_with_optional_fds(raw_fd, slice, fds);
523                }
524                Self::sendmsg_with_optional_fds(raw_fd, slice, None)
525            });
526
527            let sent = match send_result {
528                Ok(Ok(n)) => n,
529                Ok(Err(e)) => return Err(Error::from(e)),
530                Err(_would_block) => continue,
531            };
532
533            if sent == 0 {
534                return Err(Error::Transport(
535                    "sendmsg returned 0 bytes".to_string(),
536                ));
537            }
538
539            first_send = false;
540            offset = offset.checked_add(sent).ok_or_else(|| {
541                Error::Internal("send offset overflow".to_string())
542            })?;
543        }
544
545        Ok(())
546    }
547
548    async fn recv_next_framed_message(
549        &self,
550    ) -> Result<Option<(Bytes, Vec<RawFd>)>, Error> {
551        loop {
552            // First try to decode a complete frame from the buffered bytes.
553            {
554                let mut buf = self.read_buf.lock().await;
555                if let Some(prefix) = buf.get(..4) {
556                    let len_bytes: [u8; 4] =
557                        prefix.try_into().map_err(|_| {
558                            Error::Internal("bad frame prefix".to_string())
559                        })?;
560                    let len_u32 = u32::from_be_bytes(len_bytes);
561                    let payload_len = usize::try_from(len_u32)?;
562                    let total_len =
563                        payload_len.checked_add(4).ok_or_else(|| {
564                            Error::Internal("frame length overflow".to_string())
565                        })?;
566
567                    if buf.len() >= total_len {
568                        let _ = buf.split_to(4);
569                        let payload = buf.split_to(payload_len).freeze();
570
571                        let mut pending = self.pending_fds.lock().await;
572                        let fds = std::mem::take(&mut *pending);
573                        return Ok(Some((payload, fds)));
574                    }
575                }
576            }
577
578            // Need more bytes.
579            let mut guard =
580                self.stream.readable().await.map_err(Error::from)?;
581            let recv_result = guard.try_io(|inner| {
582                let raw_fd = inner.get_ref().as_raw_fd();
583                let mut scratch = [0u8; 8192];
584                let (bytes_read, received_fds) =
585                    Self::recvmsg_with_fds(raw_fd, &mut scratch)?;
586                Ok((bytes_read, scratch, received_fds))
587            });
588
589            let (bytes_read, scratch, received_fds) = match recv_result {
590                Ok(Ok(v)) => v,
591                Ok(Err(e)) => return Err(Error::from(e)),
592                Err(_would_block) => continue,
593            };
594
595            if bytes_read == 0 {
596                return Ok(None);
597            }
598
599            let n = bytes_read;
600            {
601                let mut pending = self.pending_fds.lock().await;
602                pending.extend(received_fds);
603            }
604            {
605                let mut buf = self.read_buf.lock().await;
606                let Some(bytes) = scratch.get(..n) else {
607                    return Err(Error::Internal(
608                        "recv scratch slice out of range".to_string(),
609                    ));
610                };
611                buf.extend_from_slice(bytes);
612            }
613        }
614    }
615
616    /// Check if FD passing is available on this connection.
617    pub fn supports_fd_passing(&self) -> bool {
618        true
619    }
620}
621
622/// Extract the raw file descriptor from an interprocess `TokioStream`.
623///
624/// The interprocess Stream is an enum that may contain different stream types.
625/// On Unix, the `UdSocket` variant wraps a tokio `UnixStream` which implements
626/// `AsFd`. We use pattern matching to extract the inner stream and get the fd.
627///
628/// Returns -1 if the fd cannot be extracted (e.g., on Windows or unexpected
629/// enum variant).
630#[cfg(unix)]
631fn extract_raw_fd(stream: &TokioStream) -> std::os::unix::io::RawFd {
632    use std::os::fd::{AsFd, AsRawFd};
633
634    // The interprocess crate's TokioStream is an enum.
635    // On Unix, it has a `UdSocket` variant that wraps a type implementing `AsFd`.
636    // We pattern match to access the inner stream and extract its raw fd.
637    match stream {
638        TokioStream::UdSocket(inner) => inner.as_fd().as_raw_fd(),
639    }
640}
641
642/// Concrete transport factory based on Tokio local sockets.
643pub struct LocalSocketTransportFactory;
644
645#[async_trait]
646impl TransportFactory for LocalSocketTransportFactory {
647    type Conn = LocalSocketFramedConnection;
648
649    /// Client side: connect to an endpoint (e.g., path or named pipe).
650    async fn connect(&self, endpoint: &str) -> Result<Self::Conn, Error> {
651        // Build a platform-appropriate name from the provided endpoint string.
652        #[cfg(windows)]
653        let name = endpoint
654            .to_ns_name::<GenericNamespaced>()
655            .map_err(Error::from)?;
656        #[cfg(unix)]
657        let name = endpoint
658            .to_fs_name::<GenericFilePath>()
659            .map_err(Error::from)?;
660        let stream = TokioStream::connect(name).await.map_err(Error::from)?;
661
662        #[cfg(unix)]
663        {
664            let raw_fd = extract_raw_fd(&stream);
665            let dup = shared_memory::unix::dup_fd(raw_fd)?;
666            #[expect(unsafe_code, reason = "creating UnixStream from RawFd")]
667            let unix_stream =
668                // SAFETY: dup is a newly duplicated and valid file descriptor.
669                unsafe { std::os::unix::net::UnixStream::from_raw_fd(dup) };
670            unix_stream.set_nonblocking(true).map_err(Error::from)?;
671            let async_stream =
672                AsyncFd::new(unix_stream).map_err(Error::from)?;
673
674            Ok(LocalSocketFramedConnection {
675                stream: async_stream,
676                read_buf: Mutex::new(BytesMut::new()),
677                pending_fds: Mutex::new(Vec::new()),
678                write_lock: Mutex::new(()),
679            })
680        }
681
682        #[cfg(not(unix))]
683        {
684            let (read, write) = tokio::io::split(stream);
685            let framed_read =
686                FramedRead::new(read, LengthDelimitedCodec::new());
687            let framed_write =
688                FramedWrite::new(write, LengthDelimitedCodec::new());
689            Ok(LocalSocketFramedConnection {
690                reader: Mutex::new(framed_read),
691                writer: Mutex::new(framed_write),
692            })
693        }
694    }
695
696    /// Server side: bind and accept incoming connections.
697    async fn bind(
698        &self,
699        endpoint: &str,
700    ) -> Result<Box<dyn TransportListener<Conn = Self::Conn>>, Error> {
701        // Build a platform-appropriate name from the provided endpoint string.
702        #[cfg(windows)]
703        let name = endpoint
704            .to_ns_name::<GenericNamespaced>()
705            .map_err(Error::from)?;
706        #[cfg(unix)]
707        let name = endpoint
708            .to_fs_name::<GenericFilePath>()
709            .map_err(Error::from)?;
710        let listener = ListenerOptions::new()
711            .name(name)
712            .create_tokio()
713            .map_err(Error::from)?;
714        Ok(Box::new(LocalSocketTransportListener::new(listener)))
715    }
716}
717
718/// Transport listener for Tokio local sockets.
719pub struct LocalSocketTransportListener {
720    inner: Arc<TokioListener>,
721    closed: AtomicBool,
722}
723
724impl LocalSocketTransportListener {
725    pub fn new(listener: TokioListener) -> Self {
726        Self {
727            inner: Arc::new(listener),
728            closed: AtomicBool::new(false),
729        }
730    }
731}
732
733#[async_trait]
734impl TransportListener for LocalSocketTransportListener {
735    type Conn = LocalSocketFramedConnection;
736
737    /// Accept the next connection. Returns None when listener is closed.
738    async fn accept(&self) -> Result<Option<Self::Conn>, Error> {
739        if self.closed.load(Ordering::Relaxed) {
740            return Ok(None);
741        }
742        let stream = match self.inner.accept().await {
743            Ok(s) => s,
744            Err(e) => return Err(Error::from(e)),
745        };
746
747        #[cfg(unix)]
748        {
749            let raw_fd = extract_raw_fd(&stream);
750            let dup = shared_memory::unix::dup_fd(raw_fd)?;
751            #[expect(unsafe_code, reason = "creating UnixStream from RawFd")]
752            let unix_stream =
753                // SAFETY: dup is a newly duplicated and valid file descriptor.
754                unsafe { std::os::unix::net::UnixStream::from_raw_fd(dup) };
755            unix_stream.set_nonblocking(true).map_err(Error::from)?;
756            let async_stream =
757                AsyncFd::new(unix_stream).map_err(Error::from)?;
758
759            Ok(Some(LocalSocketFramedConnection {
760                stream: async_stream,
761                read_buf: Mutex::new(BytesMut::new()),
762                pending_fds: Mutex::new(Vec::new()),
763                write_lock: Mutex::new(()),
764            }))
765        }
766
767        #[cfg(not(unix))]
768        {
769            let (read, write) = tokio::io::split(stream);
770            let framed_read =
771                FramedRead::new(read, LengthDelimitedCodec::new());
772            let framed_write =
773                FramedWrite::new(write, LengthDelimitedCodec::new());
774            Ok(Some(LocalSocketFramedConnection {
775                reader: Mutex::new(framed_read),
776                writer: Mutex::new(framed_write),
777            }))
778        }
779    }
780
781    /// Close the listener.
782    async fn close(&self) -> Result<(), Error> {
783        self.closed.store(true, Ordering::Release);
784        Ok(())
785        // Dropping the listener will close the underlying handle once all Arcs are gone.
786    }
787}
788
789#[cfg(test)]
790#[allow(
791    clippy::panic,
792    clippy::expect_used,
793    clippy::unwrap_used,
794    clippy::unwrap_in_result,
795    clippy::panic_in_result_fn,
796    clippy::indexing_slicing,
797    clippy::arithmetic_side_effects,
798    reason = "Standard repository test boilerplate"
799)]
800mod tests {
801    use crate::debug_fmt;
802
803    use super::*;
804    use anyhow::{Result, ensure};
805    use bytes::Bytes;
806
807    fn unique_echo_endpoint() -> String {
808        super::unique_endpoint("echo")
809    }
810
811    #[crate::ctb_test("tokio")]
812    async fn echo_frames_over_local_socket() -> Result<()> {
813        let endpoint = unique_echo_endpoint();
814
815        // Best-effort cleanup on Unix in case a stale socket path exists.
816        #[cfg(unix)]
817        let _ = std::fs::remove_file(&endpoint);
818
819        let factory = LocalSocketTransportFactory;
820
821        let payloads = vec![
822            Bytes::from_static(b"hello"),
823            Bytes::from_static(b"world"),
824            Bytes::from_static(b"!"),
825        ];
826
827        // Bind server listener.
828        let listener = factory.bind(&endpoint).await?;
829        let listener = Arc::new(listener);
830
831        // Server task: accept a single connection and echo frames until EOF.
832        {
833            let listener = Arc::clone(&listener);
834            tokio::spawn(async move {
835                let conn = match listener.accept().await {
836                    Ok(Some(c)) => c,
837                    Ok(None) => return anyhow::Ok(()),
838                    Err(e) => return Err(anyhow::Error::from(e)),
839                };
840
841                debug_fmt!("Server begins listening");
842                loop {
843                    let maybe = conn.recv_frame().await;
844                    let Some(frame) = maybe? else {
845                        debug_fmt!("Server ending loop");
846                        break;
847                    };
848                    debug_fmt!("Server echoing frame: {:?}", &frame);
849                    conn.send_frame(frame).await?;
850                }
851                debug_fmt!("Server ended loop");
852                conn.close().await.map_err(anyhow::Error::from)
853            })
854        };
855
856        // Client: connect, send frames, receive echoes.
857        let client = factory.connect(&endpoint).await?;
858
859        // Send payloads.
860        for p in &payloads {
861            client.send_frame(p.clone()).await?;
862        }
863
864        debug_fmt!("Done sending on {}; now listening for echoes", &endpoint);
865
866        // Read exactly the expected number of echoes, then close.
867        // FIXME: I can't figure out how to do this with just listening for the
868        // end of stream, rather than counting. Looping makes it hang.
869        /*let mut echoes = Vec::new();
870        loop {
871            match client.recv_frame().await? {
872                Some(b) => echoes.push(b),
873                None => break,
874                }
875            }*/
876        let mut echoes = Vec::with_capacity(payloads.len());
877        for _ in 0..payloads.len() {
878            let Some(b) = client.recv_frame().await? else {
879                break;
880            };
881            debug_fmt!("Client received echo: {:?}", &b);
882            echoes.push(b);
883        }
884        debug_fmt!("Received echoes on {}", &endpoint);
885
886        ensure!(echoes.len() == payloads.len(), "echo count mismatch");
887        for (a, b) in echoes.iter().zip(payloads.iter()) {
888            ensure!(a == b, "echo payload mismatch");
889        }
890
891        // Close listener.
892        listener.close().await?;
893        debug_fmt!("Closing listener!");
894
895        // Cleanup Unix socket path.
896        #[cfg(unix)]
897        let _ = std::fs::remove_file(&endpoint);
898
899        Ok(())
900    }
901
902    #[cfg(unix)]
903    #[crate::ctb_test("tokio")]
904    async fn fd_passing_does_not_corrupt_framing() -> Result<()> {
905        let endpoint = unique_echo_endpoint();
906
907        // Best-effort cleanup on Unix in case a stale socket path exists.
908        let _ = std::fs::remove_file(&endpoint);
909
910        let factory = LocalSocketTransportFactory;
911
912        // Bind server listener.
913        let listener = factory.bind(&endpoint).await?;
914        let listener = Arc::new(listener);
915
916        // Server: accept one connection and expect a marker frame that carries
917        // a single FD, followed by a regular payload frame.
918        {
919            let listener = Arc::clone(&listener);
920            tokio::spawn(async move {
921                let conn = match listener.accept().await {
922                    Ok(Some(c)) => c,
923                    Ok(None) => return anyhow::Ok(()),
924                    Err(e) => return Err(anyhow::Error::from(e)),
925                };
926
927                let Some((marker, fds)) = conn.recv_frame_with_fds().await?
928                else {
929                    anyhow::bail!("eof awaiting marker frame");
930                };
931                ensure!(marker.as_ref() == [0xFD], "marker mismatch");
932                ensure!(fds.len() == 1, "expected 1 fd, got {}", fds.len());
933
934                // Close received fd to avoid leaking.
935                let Some(fd0) = fds.first().copied() else {
936                    anyhow::bail!("missing received fd");
937                };
938                shared_memory::unix::close_fd(fd0)?;
939
940                let Some((payload, fds2)) = conn.recv_frame_with_fds().await?
941                else {
942                    anyhow::bail!("eof awaiting payload frame");
943                };
944                ensure!(fds2.is_empty(), "unexpected fds on payload");
945                ensure!(payload.as_ref() == b"hello", "payload mismatch");
946
947                conn.close().await.map_err(anyhow::Error::from)
948            });
949        }
950
951        // Client: connect and send a marker frame with an FD, then a payload.
952        let client = factory.connect(&endpoint).await?;
953
954        let fd = shared_memory::unix::create_memfd(1)?;
955        client
956            .send_frame_with_fds(Bytes::from_static(&[0xFD]), &[fd])
957            .await?;
958        shared_memory::unix::close_fd(fd)?;
959
960        client.send_frame(Bytes::from_static(b"hello")).await?;
961
962        // Cleanup.
963        listener.close().await?;
964        let _ = std::fs::remove_file(&endpoint);
965        Ok(())
966    }
967}