#Passing File Descriptors (SCM_RIGHTS)

D-Bus is a great control plane for IPC. It handles method routing, permissions, and signals cleanly. But if you want to stream video frames, audio buffers, or large files, serializing gigabytes into D-Bus byte arrays will grind your CPU and memory to a halt.

The solution in the D-Bus specification is file descriptor passing. Instead of copying the data across the bus, you pass an open operating system file descriptor (pipe, memfd, socket, or file handle) directly through the Unix domain socket.

Goose provides full, leak-proof support for out-of-band descriptor passing via SCM_RIGHTS.


#How It Works Under the Hood

The most confusing part of D-Bus file descriptor passing is that the descriptor never travels in the message body.

  1. The Body Payload ('h'): The message body only contains a 32-bit integer index (0, 1, 2, ...).
  2. The Ancillary Stream (SCM_RIGHTS): The physical file descriptors are transferred out-of-band through the kernel via sendmsg using a control message (cmsghdr).
  3. Correlation: When Goose receives the message, it correlates the body index with the array of received file descriptors and produces a ResolvedFd.

#Interactive Transport Visualizer

Walk through each stage of out-of-band descriptor transport and see how lifetimes are managed:

Interactive Visualizer

SCM_RIGHTS Transport and Lifetime Visualizer

Why D-Bus file descriptors never travel inside the message body, and how Goose connects the dots.

D-Bus Stream (Standard I/O)
Signature: 'h' (UNIX_FD)
Body Payload: 0x00000000 (Index 0)
Only a 32-bit zero-based index is serialized into the message body. The physical file handle is NOT written to the socket stream.
+
Kernel Ancillary Message (SCM_RIGHTS)
cmsg_level: SOL_SOCKET
cmsg_type: SCM_RIGHTS
Kernel Payload: [ fd: 7 ]
Transferred out-of-band via sendmsg(). The Linux kernel intercepts this buffer to duplicate the open file description.

#Safety and Leak Prevention

File descriptor leaks are insidious because they quietly exhaust the system descriptor limit (EMFILE). Goose guarantees leak-free operation:

#1. Automatic `O_CLOEXEC`

Every descriptor pulled from the socket buffer is tagged with FD_CLOEXEC. Child processes created via fork or exec will never accidentally inherit open descriptors.

#2. Automatic Auto-Close

If your method finishes and you haven't duplicated or taken the descriptor, freeMessage() closes the descriptor automatically.

#3. Duplication for Long-Lived Use

If you need the descriptor to stay open after your method handler returns (for example, to pass it to a background worker), call rfd.duplicate():

zig
pub fn ProcessAsync(self: *@This(), rfd: goose.ResolvedFd) !void {
    _ = self;
    // Duplicates the handle with O_CLOEXEC via fcntl F_DUPFD_CLOEXEC
    const persistent_handle = try rfd.duplicate();

    // Now persistent_handle remains open even after this method returns
    // and Goose closes rfd.handle!
    try startWorker(persistent_handle);
}

#End-to-End Example: Streaming Data Over a Pipe

Here is a complete example of creating a pipe on the client, sending the read handle to a server over D-Bus, and streaming data directly through the kernel buffer without copying:

#1. The Server (Receiving the Descriptor)

The server method takes ResolvedFd directly:

zig
const std = @import("std");
const goose = @import("goose");
const GStr = goose.core.value.GStr;
const ResolvedFd = goose.ResolvedFd;

pub const StreamServer = struct {
    conn: *goose.Connection,

    pub fn init(conn: *goose.Connection, _: void) @This() {
        return .{ .conn = conn };
    }

    pub fn ReceiveLogs(self: *@This(), service_name: GStr, rfd: ResolvedFd) !u32 {
        _ = self;
        std.debug.print("Reading logs for '{s}' from FD {d}...\n", .{
            service_name.s,
            rfd.handle,
        });

        var total: usize = 0;
        var buf: [512]u8 = undefined;

        while (true) {
            const n = std.posix.read(rfd.handle, &buf) catch |err| {
                if (err == error.WouldBlock) break;
                return err;
            };
            if (n == 0) break; // EOF reached
            total += n;
            std.debug.print("Read chunk: {s}\n", .{buf[0..n]});
        }

        return @intCast(total);
    }
};

#2. The Client (Passing the Descriptor)

The client creates a pipe, writes data into the write-end, and passes the read-end over D-Bus:

zig
const std = @import("std");
const goose = @import("goose");
const GStr = goose.core.value.GStr;
const ResolvedFd = goose.ResolvedFd;

pub fn streamLogsToService(conn: *goose.Connection, allocator: std.mem.Allocator) !void {
    // 1. Create a local pipe
    var pipe_fds: [2]std.posix.fd_t = undefined;
    const rc = std.posix.system.pipe(&pipe_fds);
    if (std.posix.errno(rc) != .SUCCESS) return error.PipeFailed;
    defer _ = std.posix.system.close(pipe_fds[1]); // Close write end when done

    // 2. Write payload into the pipe
    const sample_data = "System check passed: 100% operational.\n";
    _ = std.posix.system.write(pipe_fds[1], sample_data.ptr, sample_data.len);

    // 3. Prepare method call arguments
    var encoder = try goose.message.BodyEncoder.encode(allocator, .{
        GStr.new("auth-service"),
        ResolvedFd.init(pipe_fds[0], 0),
    });
    defer encoder.deinit();

    // 4. Send call with the descriptor attached
    const fds_to_send = [_]std.posix.fd_t{pipe_fds[0]};
    var reply = try conn.methodCallWithFds(
        "com.example.StreamServer",
        "/com/example/StreamServer",
        "com.example.StreamServer",
        "ReceiveLogs",
        encoder.signature(),
        encoder.body(),
        &fds_to_send,
    );
    defer conn.freeMessage(&reply);

    // 5. Close our local read end
    _ = std.posix.system.close(pipe_fds[0]);

    // 6. Decode bytes processed
    var dec = goose.message.BodyDecoder.fromMessage(allocator, reply);
    const total_read = try dec.decode(u32);
    std.debug.print("Server received {d} bytes over the pipe!\n", .{total_read});
}

#Batch Descriptor Transfers (`[]ResolvedFd`)

Goose also supports transferring multiple file descriptors in a single call. In your method signature, accept a slice:

zig
pub fn TransferMultiple(self: *@This(), rfds: []goose.ResolvedFd) !u32 {
    _ = self;
    std.debug.print("Received {d} open descriptors:\n", .{rfds.len});
    for (rfds, 0..) |rfd, i| {
        std.debug.print("  Descriptor #{d}: handle={d}\n", .{ i, rfd.handle });
    }
    return @intCast(rfds.len);
}

In D-Bus introspection, []ResolvedFd is automatically advertised with the signature 'ah'.