Files
fips/src/control/mod.rs
T
Johnathan Corgan 3a789370b9 Add an experimental native datagram API addressed by public key
A client process opens a flow to a peer's public key on a chosen port and
sends and receives datagrams on a file descriptor the daemon hands it. No
IPv6 emulation, no TUN device, no DNS: a datagram travels from key to key.
The feature is off by default and is not a stable interface.

The wire needs no change and gets none. Every FSP data packet has carried a
port pair inside its AEAD envelope since v0.2.0, and port 256 is simply the
IPv6 shim. What was missing was a way for a program to ask for a port of its
own and be handed the traffic.

Addressing is the part worth reading twice, because the obvious design is
wrong. The x-only public key is the address. An npub is that key written in
bech32, so converting between them is a local encoding rather than a lookup
or a name service. The 16-byte node address that travels on the wire is the
first half of a SHA-256 of the key: it is a truncated hash, it does not
invert, and it appears nowhere a client can see. An earlier iteration of this
work reported a peer by that hash and could supply a key only sometimes,
which is what treating a wire identifier as an identity produces.

An accepted flow therefore always knows its peer. The key is captured where
the peer is authenticated rather than looked up when a report is rendered:
every inbound datagram passes one call site inside a handler that refuses
anything whose session is not established, and the responder has already
rejected the session unless the claimed address derives from the key it
proved. Reaching for the identity cache instead gives a best-effort answer
from a structure that evicts.

A listener is a descriptor. The daemon writes one message per arrival to it,
carrying the new flow's descriptor and the peer's address, so poll, select
and epoll work on a listener and accepting is a recvmsg. That is what lets
the API be used from a program that already has an event loop, which a
command-and-reply listener could not support: an arrival could not be waited
on beside anything else. There is no accept command and no reject command.
Refusing a flow is closing the descriptor you were handed.

The Rust surface mirrors std::net. FipsStream::connect, FipsListener::bind,
incoming, accept, io::Result and an errno mapping rather than a bespoke
error type. An address is given as an npub, as a key, or as a pair, through
one parameter, the way ToSocketAddrs takes several spellings of one thing.
Each type holds its descriptor and copies of what setup told it and nothing
else, so a stream that outlives its setup connection is not representable.

set_nonblocking, AsFd and the four deadline methods carry the names and
signatures std::net uses for the same jobs. They were asked for by a user
integrating the API with tokio: AsyncFd requires a non-blocking descriptor,
and anything receiving from a peer needs a bounded wait. AsFd is the better
of the two descriptor accessors, because the borrow cannot outlive the value
that owns the descriptor, so a reactor cannot hold a registration for a
descriptor that has since been closed and its number reused by the next
open. The non-blocking flag is read, modified and written back rather than
assigned, since the flag word carries more than that one bit and a caller may
have set O_ASYNC. A zero timeout is refused with EINVAL, because the kernel
reads a zero timeval as "wait for ever", which inverts what a caller passing
zero means; std::net refuses it for the same reason. The two directions are
separate options and stay that way. FipsListener gets no timeout methods,
matching TcpListener: bounding an accept is set_nonblocking plus the caller's
own poll, which the reactor how-to builds. A flow taken from accept is
blocking whatever the listener was set to, because the two are separate
sockets and the daemon hands over a fresh one.

One rule has no counterpart in Berkeley sockets and a client author must know
it: the v1 wire carries no half-close, so nothing peer-driven ever closes a
flow. A server written to read until the flow ends waits for a signal that
cannot arrive, holding a thread and a flow per peer until its process exits.
A program decides its own termination, and the example serves one datagram
per flow.

The tests reach a live daemon rather than a stand-in. Every public item had a
unit test against a hand-written stand-in with canned replies, and the five
entry points a program actually calls first, connect, connect_from,
connect_at, bind and the SOCKET constant, had no coverage of any kind,
because the tests that appear to cover them build a Wire over a socket pair
and hand it to the private open and hold, so nothing ever resolved a socket
path or mapped its errors. examples/native-surface.rs walks all thirty-eight
items against a running daemon and reports the number of assertions it made.
The count is read from the recorder rather than written as a literal, and the
harness asserts the exit status, the completion marker and the count
together, so deleting an assertion fails the check rather than quietly
shrinking it. Watchdogs turn a hang into a named failure, which several of
the walked behaviours would otherwise produce. The shared Docker image is
built once for every integration leg, so the new binary is staged at all ten
places the existing one is, the interop builder included, which gets a stub
because those images exercise the wire between daemon versions and older refs
do not carry the example. The platform gating was tested rather than reasoned
about: flipping all eleven gates so the native API is excluded leaves the
crate compiling clean across the workspace, every target and the profiling
feature.

The shipped docs tree gains what only the LaTeX manual under design/ had,
which is not published with the daemon. A reference entry covers the whole
surface: addressing and the port tiers, the Berkeley mapping, every method on
FipsAddr, FipsStream, FipsListener and Incoming, the errno table, the
ceilings, the four places data disappears with nothing reported, the line
protocol and the command reference. The errno table gives names rather than
numbers, since the client maps each name onto the libc constant for the
platform it was built for and the supported platforms disagree on the
numbers. A tutorial side trip stands up two throwaway nodes on one machine,
peered over loopback UDP with no TUN and no DNS, then writes a listening
program and a connecting program against them; it needs neither the public
mesh nor root, because the native path is the one that does not go through
the IPv6 adapter. The obligations a client in another language carries are a
how-to of their own, since they are a task rather than a description:
reading the setup connection with recvmsg, associating a descriptor with the
last complete line, telling an empty datagram from a close, and six others.
Serving many peers from one poll loop is another, with the whole program,
because the straightforward listener spawns a thread per flow and that is
wrong at the node's ceiling of 256. The drop causes are a table mapping each
of the seven texts DropReason::as_str produces to the counter it increments,
with drop_oversize called out as the ninth counter that is not in the table.
What a daemon restart costs is a section of its own: every flow and listener
ends, descriptors do not survive, there is no resumption, and datagrams sent
but not yet forwarded are lost through a window nothing bounds.

A stack comparison diagram places the interface against the stack a reader
already knows: the same application over HTTP, TLS, TCP, IP and Ethernet on
one side, and over its own format, FSP, FMP and a FIPS transport on the
other, aligned so each row is one concern. The two columns are not
alternatives and are not drawn as such. An unmodified IPv6 program's packets
reach fips0, and the adapter hands each one to FSP as a payload, so the left
stack runs inside the right one; the left column ends at a fork, eth0 for the
ordinary internet and fips0 for the mesh, and an arrow leaves fips0 and runs
back up into FSP's input. The row where TCP would be is empty on purpose and
names Reliable Object Delivery, which is where that capability is expected to
land. ROD is a v2 capability, the box is dashed because none of it exists
yet, and the design entry says the part a reader needs most: nothing on the
surface anticipates it, so a program written today should assume it does not
exist. Both endpoints carry a scheme and a worked port,
https://<npub>.fips:443 and fips://<npub>:443, with a footnote saying the two
ports are not the same kind of thing, a TCP port inside the tunnel on the
left and an FSP port on the right. The fips:// form is a coinage: nothing in
the tree parses it, nothing registers the scheme, and the API takes a key and
a port as separate arguments rather than a URL. The diagram also says where
the right column stops, since FIPS over UDP still rides IP and Ethernet
beneath. It appears in fips-concepts.md and fips-ipv6-adapter.md, which were
making its argument in prose without a picture, and deliberately not in
fips-architecture.md, which already carries the OSI mapping and makes the
same point about the transport row.

The gateway's control socket moves onto the same bind policy this API uses,
which is the one change here that touches deployed behaviour: fips-gateway
now tightens /run/fips to 0750. That is unreachable under the packaged
deployment, where fips.service has already created the directory at that
mode, and reachable for a source build or a container that starts the gateway
alone.

One changelog entry under Added, describing the released state: what a
client opens and reads, the addressing and why the node address is not it,
the listener being a descriptor, the std::net shape of the Rust surface,
and the one rule Berkeley sockets have no counterpart for. It says in as
many words that the wire is unchanged.
2026-08-21 05:48:23 +00:00

347 lines
12 KiB
Rust

//! Control socket for runtime management and observability.
//!
//! Provides a control interface that accepts commands and returns
//! structured JSON responses. Supports both read-only queries (show_*)
//! and mutating commands (connect, disconnect).
//!
//! Platform-specific implementations:
//! - Unix: Uses a Unix domain socket for local IPC
//! - Windows: Uses a TCP socket on localhost (see commit 3)
pub mod commands;
pub mod firewall_state;
pub mod listening;
pub mod probe;
pub mod protocol;
pub mod queries;
pub mod read_handle;
pub mod snapshot;
use crate::config::ControlConfig;
use protocol::{Request, Response};
use read_handle::{ControlReadHandle, snapshot_dispatch};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, info, warn};
/// Maximum request size in bytes (4 KB).
const MAX_REQUEST_SIZE: usize = 4096;
/// I/O timeout for client connections.
const IO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// A message sent from the accept loop to the main event loop.
pub type ControlMessage = (Request, oneshot::Sender<Response>);
/// Handle a single client connection over any AsyncRead + AsyncWrite stream.
///
/// Shared between Unix and Windows implementations to avoid duplicating
/// the request/response protocol logic.
async fn handle_connection_generic<S>(
stream: S,
control_tx: mpsc::Sender<ControlMessage>,
read_handle: ControlReadHandle,
) -> Result<(), Box<dyn std::error::Error>>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
let (reader, mut writer) = tokio::io::split(stream);
let mut buf_reader = BufReader::new(reader);
let mut line = String::new();
// Read one line with timeout and size limit
let read_result = tokio::time::timeout(IO_TIMEOUT, async {
let mut total = 0usize;
loop {
let n = buf_reader.read_line(&mut line).await?;
if n == 0 {
break; // EOF
}
total += n;
if total > MAX_REQUEST_SIZE {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"request too large",
));
}
if line.ends_with('\n') {
break;
}
}
Ok(())
})
.await;
let response = match read_result {
Ok(Ok(())) if line.is_empty() => Response::error("empty request"),
Ok(Ok(())) => {
// Parse the request
match serde_json::from_str::<Request>(line.trim()) {
Ok(request) => {
// First try to serve the request entirely off-loop from the
// read handle. It returns None for any command with no snapshot
// branch, and those fall through to the rx_loop path below.
match snapshot_dispatch(&request, &read_handle) {
Some(resp) => resp,
None => {
// Send to main loop and wait for response
let (resp_tx, resp_rx) = oneshot::channel();
if control_tx.send((request, resp_tx)).await.is_err() {
Response::error("node shutting down")
} else {
match tokio::time::timeout(IO_TIMEOUT, resp_rx).await {
Ok(Ok(resp)) => resp,
Ok(Err(_)) => Response::error("response channel closed"),
Err(_) => Response::error("query timeout"),
}
}
}
}
}
Err(e) => Response::error(format!("invalid request: {}", e)),
}
}
Ok(Err(e)) => Response::error(format!("read error: {}", e)),
Err(_) => Response::error("read timeout"),
};
// Write response with timeout
let json = serde_json::to_string(&response)?;
let write_result = tokio::time::timeout(IO_TIMEOUT, async {
writer.write_all(json.as_bytes()).await?;
writer.write_all(b"\n").await?;
writer.shutdown().await?;
Ok::<_, std::io::Error>(())
})
.await;
if let Err(_) | Ok(Err(_)) = write_result {
debug!("Control socket write failed or timed out");
}
Ok(())
}
// ============================================================================
// Unix implementation
// ============================================================================
#[cfg(unix)]
mod unix_impl {
use super::*;
use std::path::{Path, PathBuf};
use tokio::net::UnixListener;
/// Control socket listener (Unix domain socket).
///
/// Manages the Unix domain socket lifecycle: bind, accept, cleanup.
pub struct ControlSocket {
listener: UnixListener,
socket_path: PathBuf,
}
impl ControlSocket {
/// Bind a new control socket.
///
/// Creates parent directories if needed, removes stale socket files,
/// and binds the Unix listener.
pub fn bind(config: &ControlConfig) -> Result<Self, std::io::Error> {
let socket_path = PathBuf::from(&config.socket_path);
let listener = crate::utils::sockbind::bind(&socket_path, "control")?;
info!(path = %socket_path.display(), "Control socket listening");
Ok(Self {
listener,
socket_path,
})
}
/// Run the accept loop, forwarding requests to the main event loop via mpsc.
///
/// Each accepted connection is handled in a spawned task:
/// 1. Read one line of JSON (the request)
/// 2. Send (Request, oneshot::Sender) to the main loop
/// 3. Wait for the response via oneshot
/// 4. Write the response as one line of JSON
/// 5. Close the connection
pub(crate) async fn accept_loop(
self,
control_tx: mpsc::Sender<ControlMessage>,
read_handle: ControlReadHandle,
) {
loop {
let (stream, _addr) = match self.listener.accept().await {
Ok(conn) => conn,
Err(e) => {
warn!(error = %e, "Control socket accept failed");
continue;
}
};
let tx = control_tx.clone();
let handle = read_handle.clone();
tokio::spawn(async move {
if let Err(e) = handle_connection_generic(stream, tx, handle).await {
debug!(error = %e, "Control connection error");
}
});
}
}
/// Get the socket path.
pub fn socket_path(&self) -> &Path {
&self.socket_path
}
/// Clean up the socket file.
fn cleanup(&self) {
crate::utils::sockbind::cleanup(&self.socket_path, "control");
}
}
impl Drop for ControlSocket {
fn drop(&mut self) {
self.cleanup();
}
}
}
// ============================================================================
// Windows implementation (TCP on localhost)
// ============================================================================
#[cfg(windows)]
mod windows_impl {
use super::*;
use tokio::net::TcpListener;
/// Default TCP port for the control socket on Windows.
const DEFAULT_CONTROL_PORT: u16 = 21210;
/// Control socket listener (Windows TCP on localhost).
///
/// On Windows, the control socket uses a TCP listener bound to
/// `127.0.0.1` since Windows does not support Unix domain sockets
/// reliably. Only localhost connections are accepted.
///
/// Note: Unlike Unix domain sockets, TCP does not provide filesystem-level
/// ACLs. Any local user can connect to the control port. This is acceptable
/// for single-user Windows installations but should be documented.
pub struct ControlSocket {
listener: TcpListener,
port: u16,
}
impl ControlSocket {
/// Bind a TCP control socket on localhost.
///
/// Parses the port from `config.socket_path` (which is a port number
/// string on Windows, e.g. "21210"). Falls back to the default port
/// with a warning if parsing fails.
pub fn bind(config: &ControlConfig) -> Result<Self, std::io::Error> {
let port: u16 = match config.socket_path.parse() {
Ok(p) => p,
Err(e) => {
warn!(
path = %config.socket_path,
error = %e,
default = DEFAULT_CONTROL_PORT,
"Invalid control port, using default"
);
DEFAULT_CONTROL_PORT
}
};
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
let std_listener = std::net::TcpListener::bind(addr)?;
std_listener.set_nonblocking(true)?;
let listener = TcpListener::from_std(std_listener)?;
info!(port = port, "Control socket listening on localhost");
Ok(Self { listener, port })
}
/// Get the listening port.
pub fn port(&self) -> u16 {
self.port
}
/// Run the accept loop, forwarding requests to the main event loop via mpsc.
///
/// Each accepted connection is handled in a spawned task using the
/// shared `handle_connection_generic` protocol handler.
pub(crate) async fn accept_loop(
self,
control_tx: mpsc::Sender<ControlMessage>,
read_handle: ControlReadHandle,
) {
loop {
let (stream, addr) = match self.listener.accept().await {
Ok(conn) => conn,
Err(e) => {
warn!(error = %e, "Control socket accept failed");
continue;
}
};
// Only accept connections from localhost
if !addr.ip().is_loopback() {
warn!(addr = %addr, "Rejected non-localhost control connection");
continue;
}
let tx = control_tx.clone();
let handle = read_handle.clone();
tokio::spawn(async move {
if let Err(e) = handle_connection_generic(stream, tx, handle).await {
debug!(error = %e, "Control connection error");
}
});
}
}
}
}
// Re-export platform-specific types
#[cfg(unix)]
pub use unix_impl::ControlSocket;
#[cfg(windows)]
pub use windows_impl::ControlSocket;
#[cfg(test)]
mod tests {
#[cfg(windows)]
use super::*;
#[cfg(windows)]
#[tokio::test]
async fn test_tcp_control_socket_bind() {
let config = ControlConfig {
enabled: true,
socket_path: "0".to_string(), // port 0 = ephemeral
};
// Verify the socket binds successfully on an ephemeral port
let _socket = ControlSocket::bind(&config).expect("failed to bind control socket");
}
#[cfg(windows)]
#[tokio::test]
async fn test_tcp_control_socket_invalid_port_uses_default() {
let config = ControlConfig {
enabled: true,
socket_path: "not-a-port".to_string(),
};
// Should fall back to default port 21210. This may fail if 21210
// is already in use, which is acceptable for a unit test.
let result = ControlSocket::bind(&config);
// We mainly verify it doesn't panic on invalid input
if let Ok(socket) = result {
assert_eq!(socket.port(), 21210);
}
}
}