mirror of
https://github.com/jmcorgan/fips.git
synced 2026-10-05 19:18:25 +00:00
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.
394 lines
14 KiB
Rust
394 lines
14 KiB
Rust
//! What a native API client task asks the node to do.
|
|
//!
|
|
//! The registry lives inside `Node`, so a client task cannot touch it directly.
|
|
//! It sends one of these instead and waits on the `oneshot` it carried. That is
|
|
//! the same shape the control socket uses, and it is why the receive path needs
|
|
//! no lock: only the `rx_loop` ever holds the registry.
|
|
//!
|
|
//! Every variant that can fail carries its reply channel. A dropped reply means
|
|
//! the node is shutting down, which the client task reports as such rather than
|
|
//! waiting.
|
|
|
|
use super::registry::{Arrival, Datagram, Delivery, DropCause, FlowKey, Registry, RegistryError};
|
|
use crate::identity::NodeAddr;
|
|
use secp256k1::XOnlyPublicKey;
|
|
use tokio::sync::{mpsc, oneshot};
|
|
use tracing::trace;
|
|
|
|
/// A request from a client task to the node's registry.
|
|
#[derive(Debug)]
|
|
pub enum NativeMessage {
|
|
/// Bind a listener to a local port, or to an ephemeral one.
|
|
Listen {
|
|
/// The port to hold, or `None` for an ephemeral one.
|
|
port: Option<u16>,
|
|
/// Where the node announces new peers on that port.
|
|
arrivals: mpsc::Sender<Arrival>,
|
|
/// The port actually held, or why none could be.
|
|
reply: oneshot::Sender<Result<u16, RegistryError>>,
|
|
},
|
|
|
|
/// Open a flow to a peer.
|
|
Connect {
|
|
/// The far end, by the x-only public key that is its address.
|
|
peer: XOnlyPublicKey,
|
|
/// The far end's port.
|
|
remote: u16,
|
|
/// The local port, or `None` for an ephemeral one.
|
|
local: Option<u16>,
|
|
/// Where the node delivers this flow's datagrams.
|
|
sink: mpsc::Sender<Datagram>,
|
|
/// What the flow holds, or why it could not be opened.
|
|
reply: oneshot::Sender<Result<Opened, RegistryError>>,
|
|
},
|
|
|
|
/// Take a flow a listener announced.
|
|
Accept {
|
|
/// Which announced flow.
|
|
flow: u64,
|
|
/// Where the node delivers its datagrams from now on.
|
|
sink: mpsc::Sender<Datagram>,
|
|
/// The flow's key, whatever arrived before it was accepted, and the
|
|
/// payload limit.
|
|
reply: oneshot::Sender<Result<Accepted, RegistryError>>,
|
|
},
|
|
|
|
/// Give up a flow whose descriptor closed, or a listener whose port is
|
|
/// being unbound.
|
|
///
|
|
/// Carries no reply: the sender is a task that is ending and has nothing
|
|
/// left to do with the answer. It is sent from the task rather than from a
|
|
/// `Drop`, so it can be awaited and cannot be silently lost to a full
|
|
/// channel.
|
|
Release {
|
|
/// Flows to forget.
|
|
flows: Vec<FlowKey>,
|
|
/// Listener ports to free, along with anything pending on them.
|
|
listeners: Vec<u16>,
|
|
},
|
|
|
|
/// Undo a flow the listener's task promoted but could not hand over.
|
|
///
|
|
/// Separate from [`NativeMessage::Release`] because the two count
|
|
/// differently: a release is a flow a client finished with, and this is one
|
|
/// no client ever held. Sending one message for both halves of the undo
|
|
/// keeps the registry entry and the counter from disagreeing.
|
|
Discard {
|
|
/// The flow to forget.
|
|
key: FlowKey,
|
|
/// Why it could not be handed over.
|
|
reason: DropReason,
|
|
},
|
|
|
|
/// **Debug.** Deliver a datagram as though it had arrived from the mesh.
|
|
///
|
|
/// This drives the same [`Registry::deliver`](super::registry::Registry::deliver)
|
|
/// the FSP receive path will call, so the dispatch rule is exercised before
|
|
/// the wire exists and the wire, when it lands, changes the caller rather
|
|
/// than the rule.
|
|
Arrive {
|
|
/// The peer it appears to come from, by wire address.
|
|
peer: NodeAddr,
|
|
/// That peer's key, decoded from the npub the caller named. Client
|
|
/// asserted rather than authenticated, which is one of the reasons the
|
|
/// command is gated.
|
|
pubkey: XOnlyPublicKey,
|
|
/// Its source port.
|
|
src: u16,
|
|
/// Its destination port on this node.
|
|
dst: u16,
|
|
/// The payload.
|
|
data: Datagram,
|
|
/// What the registry decided to do with it.
|
|
reply: oneshot::Sender<Outcome>,
|
|
},
|
|
}
|
|
|
|
/// One datagram a client wrote to its descriptor, on its way to the mesh.
|
|
///
|
|
/// Travels on its own channel rather than through [`NativeMessage`], so a burst
|
|
/// of client traffic cannot delay a registration and the data arm can drain in
|
|
/// batches the way the TUN arm does.
|
|
#[derive(Debug)]
|
|
pub struct Outbound {
|
|
/// The flow it belongs to, which carries both ports and the destination.
|
|
pub key: FlowKey,
|
|
/// The destination's address. Always known: a connected flow decoded it
|
|
/// from the npub its client named, and an accepted one took it from the
|
|
/// session that authenticated the peer.
|
|
pub peer: XOnlyPublicKey,
|
|
/// The payload, with no port header: the send path adds that.
|
|
pub payload: Datagram,
|
|
}
|
|
|
|
/// A flow the client opened.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Opened {
|
|
/// The local port it holds.
|
|
pub local: u16,
|
|
/// The identifier the client names it by.
|
|
pub flow: u64,
|
|
/// The largest payload it may send, in bytes.
|
|
pub max: u16,
|
|
}
|
|
|
|
/// A flow the client accepted from a listener.
|
|
#[derive(Debug)]
|
|
pub struct Accepted {
|
|
/// Which flow, in both directions.
|
|
pub key: FlowKey,
|
|
/// The peer's address.
|
|
pub peer: XOnlyPublicKey,
|
|
/// Whatever arrived before the client answered.
|
|
pub held: Vec<Datagram>,
|
|
/// The largest payload it may send, in bytes.
|
|
pub max: u16,
|
|
}
|
|
|
|
/// Why a datagram was not delivered, across every path that can refuse one.
|
|
///
|
|
/// [`DropCause`] covers the refusals the registry decides. Delivery can also
|
|
/// fail after the registry has agreed, when a bounded channel to a client is
|
|
/// full, and those three cases are the remaining variants. Keeping one type
|
|
/// over the whole set is what lets a counter match be exhaustive: a match over
|
|
/// `DropCause` alone would silently miss the case a slow client actually causes.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum DropReason {
|
|
/// No listener and no flow holds the destination port.
|
|
NoPort,
|
|
/// A listener holds the port but will not hold another pending flow.
|
|
BacklogFull,
|
|
/// The node is at its flow ceiling.
|
|
TooManyFlows,
|
|
/// A flow awaiting accept will hold no more datagrams.
|
|
PendingQueueFull,
|
|
/// An established flow's client is not draining its descriptor.
|
|
FlowQueueFull,
|
|
/// A listener's client is not reading the arrivals it asked for. The flow
|
|
/// is unregistered as well, so nothing is left pending that nobody knows of.
|
|
ArrivalQueueFull,
|
|
/// A listener's client is not reading its descriptor, so the arrival could
|
|
/// not be written to it. Distinct from `ArrivalQueueFull`: that one is the
|
|
/// rx_loop refusing before anything was opened, and this one is a flow the
|
|
/// daemon had already wired and has to take apart again.
|
|
ListenerNotReading,
|
|
/// A listener's client closed its descriptor between the arrival being
|
|
/// taken off the queue and being written to it. The same cleanup as
|
|
/// `ListenerNotReading` and a different counter: this one is a race a
|
|
/// healthy client can lose, and that one is a client falling behind.
|
|
ListenerGone,
|
|
}
|
|
|
|
impl From<DropCause> for DropReason {
|
|
fn from(cause: DropCause) -> Self {
|
|
match cause {
|
|
DropCause::NoPort => DropReason::NoPort,
|
|
DropCause::BacklogFull => DropReason::BacklogFull,
|
|
DropCause::TooManyFlows => DropReason::TooManyFlows,
|
|
DropCause::QueueFull => DropReason::PendingQueueFull,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl DropReason {
|
|
/// The client-facing text for this reason.
|
|
///
|
|
/// `PendingQueueFull` and `FlowQueueFull` deliberately render alike. They
|
|
/// are distinct to a counter and indistinguishable to a client, which is
|
|
/// what keeps the strings the debug `arrive` command already answers with
|
|
/// unchanged.
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
DropReason::NoPort => "no listener or flow on that port",
|
|
DropReason::BacklogFull => "listener backlog full",
|
|
DropReason::TooManyFlows => "node flow ceiling reached",
|
|
DropReason::PendingQueueFull | DropReason::FlowQueueFull => "queue full",
|
|
DropReason::ArrivalQueueFull => "arrival queue full",
|
|
DropReason::ListenerNotReading => "listener not reading arrivals",
|
|
DropReason::ListenerGone => "listener closed",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What became of a delivered datagram.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Outcome {
|
|
/// An established flow received it.
|
|
Delivered,
|
|
/// A listener was told a new peer arrived, and the datagram was held for
|
|
/// whoever accepts it.
|
|
Announced(u64),
|
|
/// A flow already announced held it while it waits to be accepted.
|
|
Held(u64),
|
|
/// Nothing took it.
|
|
Dropped(DropReason),
|
|
}
|
|
|
|
/// What one served request did, so the shell can count it.
|
|
///
|
|
/// The core decides and answers the client on the request's own channel; this
|
|
/// exists only so the node can bump a counter without the core having to know
|
|
/// what a counter is. Only outcomes something counts are named; everything else
|
|
/// is [`Served::Untracked`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Served {
|
|
/// A client opened a flow to a peer it named.
|
|
Opened,
|
|
/// A listener's task took a pending flow on a client's behalf.
|
|
Accepted,
|
|
/// A flow the daemon wired and could not hand over was taken apart again.
|
|
Discarded(DropReason),
|
|
/// This many established flows were given back when their descriptors
|
|
/// closed or their listener unbound.
|
|
Released(usize),
|
|
/// A datagram of this many bytes was dispatched by the debug arrival
|
|
/// command, which runs the same rule the wire does and is counted the same
|
|
/// way. The length rides along because `deliver` consumes the datagram.
|
|
Delivered(Outcome, usize),
|
|
/// Nothing counted: a listen, or a request the registry refused.
|
|
Untracked,
|
|
}
|
|
|
|
/// Apply one request to `registry` and answer it.
|
|
///
|
|
/// A free function over the registry rather than a method on the node: the node
|
|
/// supplies only `now`, and everything else here is a decision plus the sends
|
|
/// that decision names. That is what lets this be driven in a test without
|
|
/// building a node, and it is the same code the running daemon executes.
|
|
pub fn serve(registry: &mut Registry, message: NativeMessage, now: u64, max: u16) -> Served {
|
|
match message {
|
|
NativeMessage::Listen {
|
|
port,
|
|
arrivals,
|
|
reply,
|
|
} => {
|
|
let _ = reply.send(registry.listen(port, arrivals));
|
|
Served::Untracked
|
|
}
|
|
|
|
NativeMessage::Discard { key, reason } => {
|
|
registry.release(&key);
|
|
Served::Discarded(reason)
|
|
}
|
|
|
|
NativeMessage::Connect {
|
|
peer,
|
|
remote,
|
|
local,
|
|
sink,
|
|
reply,
|
|
} => {
|
|
let opened = registry
|
|
.connect(peer, remote, local, sink, now)
|
|
.map(|(local, flow)| Opened { local, flow, max });
|
|
let served = if opened.is_ok() {
|
|
Served::Opened
|
|
} else {
|
|
Served::Untracked
|
|
};
|
|
let _ = reply.send(opened);
|
|
served
|
|
}
|
|
|
|
NativeMessage::Accept { flow, sink, reply } => {
|
|
let accepted = registry
|
|
.accept(flow, sink, now)
|
|
.map(|(key, peer, held)| Accepted {
|
|
key,
|
|
peer,
|
|
held,
|
|
max,
|
|
});
|
|
let served = if accepted.is_ok() {
|
|
Served::Accepted
|
|
} else {
|
|
Served::Untracked
|
|
};
|
|
let _ = reply.send(accepted);
|
|
served
|
|
}
|
|
|
|
NativeMessage::Release { flows, listeners } => {
|
|
let mut closed = 0;
|
|
for key in &flows {
|
|
if registry.release(key) {
|
|
closed += 1;
|
|
}
|
|
}
|
|
for port in &listeners {
|
|
registry.release_listener(*port);
|
|
}
|
|
Served::Released(closed)
|
|
}
|
|
|
|
NativeMessage::Arrive {
|
|
peer,
|
|
pubkey,
|
|
src,
|
|
dst,
|
|
data,
|
|
reply,
|
|
} => {
|
|
let bytes = data.len();
|
|
let outcome = deliver(registry, peer, pubkey, src, dst, data, now);
|
|
let _ = reply.send(outcome);
|
|
Served::Delivered(outcome, bytes)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Deliver one inbound datagram to whatever owns its destination port.
|
|
///
|
|
/// The FSP receive path calls this once the wire is connected; until then the
|
|
/// debug arrival command is its only caller. Either way the decision is the
|
|
/// registry's and this only performs it.
|
|
pub fn deliver(
|
|
registry: &mut Registry,
|
|
peer: NodeAddr,
|
|
pubkey: XOnlyPublicKey,
|
|
src: u16,
|
|
dst: u16,
|
|
data: Datagram,
|
|
now: u64,
|
|
) -> Outcome {
|
|
match registry.deliver(peer, pubkey, src, dst, now) {
|
|
Delivery::Flow(sink) => {
|
|
// Never block the receive path on a slow client. A full queue costs
|
|
// that client a datagram, not the node its tick.
|
|
match sink.try_send(data) {
|
|
Ok(()) => Outcome::Delivered,
|
|
Err(_) => {
|
|
trace!(dst, "Native API flow queue full, dropping datagram");
|
|
Outcome::Dropped(DropReason::FlowQueueFull)
|
|
}
|
|
}
|
|
}
|
|
|
|
Delivery::Arrived(arrivals, arrival) => {
|
|
let flow = arrival.flow;
|
|
if arrivals.try_send(arrival).is_err() {
|
|
// The client is not reading its own announcements. Undo the
|
|
// registration rather than leaving a pending flow nobody will
|
|
// ever be told about.
|
|
let _ = registry.reject(flow);
|
|
return Outcome::Dropped(DropReason::ArrivalQueueFull);
|
|
}
|
|
if registry.hold(flow, data) {
|
|
Outcome::Announced(flow)
|
|
} else {
|
|
Outcome::Dropped(DropReason::PendingQueueFull)
|
|
}
|
|
}
|
|
|
|
Delivery::Pending(flow) => {
|
|
if registry.hold(flow, data) {
|
|
Outcome::Held(flow)
|
|
} else {
|
|
Outcome::Dropped(DropReason::PendingQueueFull)
|
|
}
|
|
}
|
|
|
|
Delivery::Drop(cause) => Outcome::Dropped(cause.into()),
|
|
}
|
|
}
|