Skip to main content

Crate anchovy

Crate anchovy 

Source
Expand description

§anchovy

Unix sockets can carry open file descriptors alongside data, but nothing in the standard async I/O stack handles this. In async Rust you have to drop down to sendmsg/recvmsg yourself. anchovy handles that: it wraps a UnixStream and implements AsyncRead/AsyncWrite with fd passing via SCM_RIGHTS ancillary messages.

§Usage

[dependencies]
anchovy = "0.1"

Use AnchovyStream<DBUS_SCM_RIGHTS> for D-Bus or AnchovyStream<WAYLAND_SCM_RIGHTS> for Wayland. For other protocols, set S to rustix::cmsg_space!(ScmRights(N)), where N is the maximum number of file descriptors you expect per message.

§Sending file descriptors

Push OwnedFd values into the write queue before writing. All queued descriptors go out together in a single sendmsg call, then the queue is cleared.

use anchovy::{AnchovyStream, DBUS_SCM_RIGHTS};
use std::os::fd::OwnedFd;
use tokio::io::AsyncWriteExt;

async fn send_fd(stream: &mut AnchovyStream<DBUS_SCM_RIGHTS>, fd: OwnedFd) -> std::io::Result<()> {
    stream.write_queue_mut().push_back(fd);
    stream.write_all(b"payload").await
}

§Receiving file descriptors

Descriptors received with a message land in the read queue. Drain it after each read.

use anchovy::{AnchovyStream, DBUS_SCM_RIGHTS};
use tokio::io::AsyncReadExt;

async fn recv_fds(stream: &mut AnchovyStream<DBUS_SCM_RIGHTS>) -> std::io::Result<()> {
    let mut buf = vec![0u8; 64];
    stream.read(&mut buf).await?;
    for fd in stream.read_queue_mut().drain(..) {
        // handle fd
    }
    Ok(())
}

§Origin

waynest and abus both needed this and ended up writing the same wrapper independently. anchovy is that wrapper, extracted into a shared crate before the two implementations diverged further.

§License

This project is licensed under the Apache-2.0 License. For more information, please see the LICENSE file.

Structs§

AnchovyStream
A Unix socket stream with support for passing file descriptors via SCM_RIGHTS ancillary messages.

Constants§

DBUS_FD_LIMIT
Maximum number of file descriptors that can be passed in a single D-Bus message, as defined by the D-Bus specification.
DBUS_SCM_RIGHTS
Ancillary buffer size (bytes) required to send or receive up to DBUS_FD_LIMIT file descriptors via SCM_RIGHTS in a single recvmsg / sendmsg call.
WAYLAND_FD_LIMIT
Maximum number of file descriptors that can be passed in a single Wayland message, as defined by the Wayland reference implementation (WAYLAND_MAX_FDS_OUT).
WAYLAND_SCM_RIGHTS
Ancillary buffer size (bytes) required to send or receive up to WAYLAND_FD_LIMIT file descriptors via SCM_RIGHTS in a single recvmsg / sendmsg call.

Traits§

IntoUnixStream
Converts a Unix stream type into a std::os::unix::net::UnixStream.