listen-fds
A Rust library for handling systemd socket activation.
What is Socket Activation?
Socket activation is a systemd feature that allows services to:
- Start on-demand when connections arrive
- Perform zero-downtime restarts (systemd holds the socket during restart)
- Improve resource utilization (services don't run until needed)
When systemd socket-activates your service, it passes listening sockets (or other file descriptors) via environment variables. This library provides a safe, idiomatic Rust interface for receiving those file descriptors.
Features
- Safe ownership of socket-activated file descriptors
- Automatic PID validation (supports both
LISTEN_PIDand the newerLISTEN_PIDFDID) - Named file descriptor lookup via
LISTEN_FDNAMES - Automatic
FD_CLOEXECsetting for security - Zero-copy borrowing or ownership transfer of FDs
- FD retrieval methods return both the file descriptor and its name (or "unknown" if unnamed)
Installation
Add to your Cargo.toml:
[]
= { = "https://github.com/swick/listen-fds-rs.git" }
Usage
Basic Example
use ListenFds;
use UnixListener;
Using Named File Descriptors
use ListenFds;
use TcpListener;
Borrowing File Descriptors
use ListenFds;
Systemd Configuration Example
Socket Unit (myservice.socket)
[Unit]
Description=My Service Socket
[Socket]
ListenStream=/run/myservice.sock
FileDescriptorName=main
[Install]
WantedBy=sockets.target
Service Unit (myservice.service)
[Unit]
Description=My Service
Requires=myservice.socket
[Service]
Type=simple
ExecStart=/usr/bin/myservice
Enable socket activation:
Safety
The ListenFds::new() function is marked unsafe because:
- It modifies the process environment by removing
LISTEN_*variables - It must be called before spawning any threads (to avoid race conditions with environment access)
- It must be called at most once per process
Call it early in your main() function, before any thread spawning occurs.
PID Validation
The library validates that file descriptors are intended for your process using:
LISTEN_PID: Traditional PID-based validationLISTEN_PIDFDID: Modern pidfd-based validation (more secure, resistant to PID reuse attacks)
If either validation fails, ListenFds::new() returns an error.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
References
- systemd.socket(5)
- sd_listen_fds(3)
- Socket Activation by Lennart Poettering