#fd #file-descriptor #unix #socket

withfd

Send and receive data along with file descriptors

2 releases

new 0.1.2 Feb 23, 2024
0.1.1 Apr 18, 2023
0.1.0 Apr 18, 2023

#283 in Unix APIs

Download history 19/week @ 2023-11-03 15/week @ 2023-11-10 19/week @ 2023-11-17 23/week @ 2023-11-24 12/week @ 2023-12-01 14/week @ 2023-12-08 18/week @ 2023-12-15 21/week @ 2023-12-22 7/week @ 2023-12-29 17/week @ 2024-01-05 19/week @ 2024-01-12 14/week @ 2024-01-19 14/week @ 2024-01-26 11/week @ 2024-02-02 18/week @ 2024-02-09 45/week @ 2024-02-16

89 downloads per month
Used in 3 crates (2 directly)

MIT/Apache

17KB
271 lines

withfd

withfd allows passing file descriptors through Unix sockets.

This crate provides adapters for std::os::unix::net::UnixStream and tokio::net::UnixStream (requires the tokio feature) that allow passing file descriptors through them.

The adapter allows you to keep using the ordinary Read and Write (or AsyncRead and AsyncWrite with the tokio feature) interfaces. File descriptors are received and stored as you read, This is different from other similar crates like passfd or sendfd. This is to address the problem where, if you use ordinary read on the UnixStream when the other end has sent a file descriptor, the file descriptor will be dropped. This adapter ensures there is no file descriptors being lost.

Example

Process 1:

use withfd::WithFdExt;
use std::fs::File;
use std::os::unix::io::AsFd;
use std::os::unix::net::UnixListener;

let file = File::open("/etc/passwd").unwrap();
let listener = UnixListener::bind("/tmp/test.sock").unwrap();
let (stream, _) = listener.accept().unwrap();
let mut stream = stream.with_fd();
stream.write_with_fd(b"data", &[file.as_fd()]).unwrap();

Process 2:

use withfd::WithFdExt;
use std::fs::File;
use std::io::Read;
use std::os::unix::io::FromRawFd;
use std::os::unix::net::UnixStream;

let stream = UnixStream::connect("/tmp/test.sock").unwrap();
let mut stream = stream.with_fd();
let mut buf = [0u8; 4];
stream.read_exact(&mut buf[..]).unwrap();
let fd = stream.take_fds().next().unwrap();
let mut file = File::from(fd);
let mut buf = String::new();
file.read_to_string(&mut buf).unwrap();
println!("{}", buf);

Dependencies

~2–12MB
~105K SLoC