Compare commits

...
81 Commits
Author SHA1 Message Date
DeFiDude bf7d16fc36 tests: keep child-spawning tests apart from lock and FIFO tests 2026-10-25 23:14:14 -06:00
DeFiDude 48adcf726e discovery: never announce Backbone clients and read only reachable_on 2026-10-25 21:49:07 -06:00
DeFiDude f1caa4571d docs: record the TCP client's i2p_tunneled option 2026-10-25 21:44:34 -06:00
DeFiDude 30e433a9cb runtime: read AutoInterface devices and I2P peers exactly as Python lists them 2026-10-25 21:11:23 -06:00
DeFiDude b56a427c4a docs: call the RPC key an admin credential 2026-10-25 21:05:17 -06:00
DeFiDude 0267f42001 rnstatus: show the network an auto-connected interface came from 2026-10-25 21:03:24 -06:00
DeFiDude 5ac4820b32 management: answer the status profiling flag as Python does 2026-10-25 20:53:59 -06:00
DeFiDude c3b3fd1c1f interfaces: wait for the real reconnect in local socket tests 2026-10-25 20:49:42 -06:00
DeFiDude 55072d1ca2 discovery: require an explicit reachable address 2026-10-25 19:38:38 -06:00
DeFiDude 06597b5869 tcp: honor I2P-tunneled client socket timeouts 2026-10-25 19:34:27 -06:00
DeFiDude 442196c71a runtime: read AutoInterface device lists from parsed config 2026-10-25 18:46:54 -06:00
DeFiDude 45b49db0c1 i2p: accept SAM reply lines up to Python's 64 KiB limit 2026-10-25 12:41:57 -06:00
DeFiDude 21100300fc i2p: keep the session's private key out of freed memory and debug output 2026-10-25 12:00:48 -06:00
DeFiDude 6aa1d4bbf1 transport: keep each IFAC key in one wiped allocation shared by its interface records 2026-10-25 11:50:58 -06:00
DeFiDude 3311c0a7b1 runtime: wipe the IFAC passphrase in interface options and keep it out of debug output 2026-10-25 11:39:52 -06:00
DeFiDude 6bdc82af93 identity: encode ratchet files into a pre-sized buffer and correct key-file notes 2026-10-25 11:23:44 -06:00
DeFiDude 215250d2b2 tests: control the residue harness and check secrets drop inside each check 2026-10-25 11:18:06 -06:00
DeFiDude 881f7b926d identity: test raw keys that begin like the older envelope format 2026-10-25 11:12:09 -06:00
DeFiDude d1c6d508c9 persistence: retry file readbacks that a signal interrupts 2026-10-25 11:09:40 -06:00
DeFiDude 5366b1d3d3 identity: decode legacy key files without leaving key copies in freed memory 2026-10-25 11:00:38 -06:00
DeFiDude 588fdfc123 ratkey: wipe security key responses that carry an ECDH shared secret 2026-10-25 10:34:56 -06:00
DeFiDude a551770f63 crypto: wipe HKDF output, including IFAC masks, when it is dropped 2026-10-25 10:34:56 -06:00
DeFiDude 416f1ae86c crypto: wipe AES key schedules and CBC state when ciphers are dropped 2026-10-25 10:09:58 -06:00
DeFiDude ad10380bbb crypto: keep plaintext, derived keys and key files out of freed memory 2026-10-25 09:34:02 -06:00
DeFiDude 708b37b017 persistence: verify writes through a wiped buffer and test real write failures 2026-10-25 09:33:48 -06:00
DeFiDude 6d2619cc48 docs: add operator notes for remote management on the transport identity 2026-10-25 07:14:41 -06:00
DeFiDude 8c841a92f1 docs: correct the Python release that gates auto-connect 2026-10-25 07:14:39 -06:00
DeFiDude 56b6bcefa5 docs: reword two discovery comments 2026-10-25 07:14:38 -06:00
DeFiDude efbc495e84 api: make discovery rejection reasons non-exhaustive 2026-10-25 07:14:26 -06:00
DeFiDude 2992377739 tests: check that a wire announce without valid IFAC is never held 2026-10-25 07:13:41 -06:00
DeFiDude 692260e79b status: name the network an auto-connected interface came from 2026-10-25 07:11:57 -06:00
DeFiDude 48e355a943 discovery: never auto-connect to onion or local addresses, or to an endpoint already in use 2026-10-25 07:09:37 -06:00
DeFiDude cd091604d2 management: refuse Resources on remote management Links, as Python does 2026-10-25 07:07:50 -06:00
DeFiDude 08d246ed22 management: filter remote path tables as Python compares destinations and hop limits 2026-10-25 07:07:16 -06:00
DeFiDude 04f9324cd5 transport: count dropped realtime Link packets in the interface's dropped bytes 2026-10-25 07:06:50 -06:00
DeFiDude e16c8b4d39 transport: count a path request only once its tag passes the duplicate check 2026-10-25 07:06:33 -06:00
DeFiDude 4683cb2c2a link: add a clock that keeps counting while the system is suspended 2026-10-25 06:35:18 -06:00
DeFiDude 379312e305 docs: describe I2P discovery generically 2026-10-25 06:24:04 -06:00
DeFiDude b79bcdb38b i2p: keep the server's key in Python's key file, and announce a new address on the interval 2026-10-25 06:23:59 -06:00
DeFiDude 4c6217597a i2p: give configured peers the global ingress settings, as Python does 2026-10-25 06:23:40 -06:00
DeFiDude cb929d5f65 i2p: never tear down a bootstrap-only I2P interface, as Python never detaches one 2026-10-25 06:21:47 -06:00
DeFiDude ef551de12b tests: time out the first connect in the backlog tests, so a slow refusal still fails first 2026-10-25 06:20:05 -06:00
DeFiDude 09ae5d6e26 transport: remember the identity of every validated announce before deciding its path 2026-10-25 06:04:12 -06:00
DeFiDude 9d7b2bd429 api: expose synthesis verification and the client drivers' Python names 2026-10-25 03:40:37 -06:00
DeFiDude f3f72ead60 i2p: announce one discoverable interface at its own b32 and keep peers at Python's defaults 2026-10-25 03:34:53 -06:00
DeFiDude 53515b3d41 docs: note that an I2P interface runs its server only when connectable 2026-10-25 03:21:41 -06:00
DeFiDude 846833a197 docs: describe the hub restart change generically 2026-10-25 03:21:08 -06:00
DeFiDude c44744ecee tests: give tunnel test names, paths and aspects neutral prefixes 2026-10-25 03:20:57 -06:00
DeFiDude 4ea028eb75 tests: run the Unix shared-instance tunnel tests only on Unix 2026-10-25 03:19:47 -06:00
DeFiDude fbbc311192 tunnel: expire handled tunnels after TUNNEL_TIMEOUT as Python does 2026-10-25 03:18:33 -06:00
DeFiDude 1801cf291a local: drop traffic queued while the shared instance was unreachable 2026-10-25 03:11:40 -06:00
DeFiDude 264b00eb3d interfaces: drop traffic queued while a client's connection attempts fail 2026-10-25 03:07:38 -06:00
DeFiDude 2e8fa290dc discovery: announce KISS TCP clients and unset radio parameters as Python does 2026-10-25 03:00:21 -06:00
DeFiDude feb11b0089 discovery: name rsRNS and auto-connect only to the stacks Python 1.5 trusts 2026-10-25 02:51:31 -06:00
DeFiDude 1371918851 transport: process released and replayed announces without re-checking IFAC or recounting bytes 2026-10-25 02:51:05 -06:00
DeFiDude 65d95eed33 status: give Python 1.5 rnstatus and rnpath full interface stats, locally and remotely 2026-10-25 02:50:33 -06:00
DeFiDude 6e412dc9e0 interfaces: open every TCP, Backbone and I2P client connection with a tunnel synthesis 2026-10-24 23:29:20 -06:00
DeFiDude b774544cbb transport: drop multi-hop PLAIN and GROUP packets as Python's packet filter does 2026-10-24 23:10:14 -06:00
DeFiDude af65181e49 transport: accept valid tunnel syntheses and bind tunnels as in Python 2026-10-24 23:06:26 -06:00
DeFiDude acd59b178e transport: never rebind saved paths to accepted clients and load tunnels unbound 2026-10-24 23:00:56 -06:00
DeFiDude 52ab6c02d7 transport: stop sharing interface id 0 and run every configured I2P peer 2026-10-24 22:52:07 -06:00
DeFiDude f9d848866e transport: give interface stat entries a default 2026-10-24 19:02:11 -06:00
DeFiDude 562bc99da7 android-usb: read one max-size packet per bulk transfer 2026-10-22 23:09:12 -06:00
DeFiDude d738238b4e tests: retry the listener signal check when startup was interrupted 2026-10-21 17:33:39 -06:00
DeFiDude e5e8401fc7 link: count the responder's LRPROOF as Link outbound, as in Python 2026-10-21 17:33:39 -06:00
DeFiDude d047641898 link: accept peer identification before the RTT packet, as in Python 2026-10-21 16:08:08 -06:00
DeFiDude 76cfd48b29 tests: skip long backdated timeouts on freshly booted Windows clocks 2026-10-20 23:30:56 -06:00
DeFiDude 42b53c5538 persistence: accept every filesystem and warn on network or RAM storage 2026-10-20 20:27:10 -06:00
DeFiDude 5468316087 ci: pin Rust 1.96.0 instead of floating stable 2026-10-20 20:08:40 -06:00
DeFiDude c4788883f3 api: record RNode rejection, IFAC status and interface enable additions 2026-10-20 18:50:36 -06:00
DeFiDude 8b046794f1 docs: note pending radio and status changes 2026-10-20 17:17:30 -06:00
DeFiDude 85f29bcfd3 config: start an interface only when it is enabled, as upstream 2026-10-20 17:16:28 -06:00
DeFiDude 465ec096a5 status: report IFAC like upstream, only for interfaces that have it 2026-10-20 16:33:12 -06:00
DeFiDude b6f9e788b2 rnode: confirm effective settings on every transport and retry unopenable ports 2026-10-20 15:17:08 -06:00
DeFiDude 1a835f0acc ble: hold native RNode startup until the Android bridge attaches 2026-10-20 12:46:18 -06:00
DeFiDude 506852837c ble: validate effective RNode settings and stop on definitive rejection 2026-10-20 10:27:03 -06:00
DeFiDude 8fcf0b678a ratchet: require prepared namespaces for durable received keys 2026-10-13 17:41:23 -06:00
DeFiDude 817a640ed1 runtime: defer bounded request work with exact endpoint ownership 2026-10-13 00:30:19 -06:00
DeFiDude 4bba059d93 persistence: qualify native Android locking and CI boundaries 2026-10-13 00:07:28 -06:00
DeFiDude 7a33f4297f protocol: enforce capacity, ownership and durable admission boundaries 2026-10-12 23:57:46 -06:00
DeFiDude df94572ff6 tests: retain RNode and cache-miss regression coverage 2026-10-12 23:57:45 -06:00
148 changed files with 21811 additions and 2812 deletions

No files matched your search

+2 -2
View File
@@ -50,7 +50,7 @@ jobs:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: false
@@ -74,7 +74,7 @@ jobs:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
components: clippy, rustfmt
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
+51
View File
@@ -2,6 +2,57 @@
## Unreleased
- RNode drivers confirm the settings the radio applies once it is on, on every transport, and stop with the rejected setting named (for example TX power below an amplifier's minimum) instead of transmitting at other settings or retrying forever.
- Serial and TCP RNodes keep retrying a port that is missing, busy or not permitted every 5 seconds, as in Python Reticulum, and report which.
- Android Bluetooth RNode sessions wait for the bridge before starting, so a slow reconnect no longer drops a healthy link.
- Interface status reports IFAC like Python Reticulum: `rnstatus-rs` shows the network name and access line only for interfaces that use IFAC.
- Interfaces start only when `enabled` or `interface_enabled` is yes, as in Python Reticulum. A section with neither key is now skipped with a warning instead of starting, so add `enabled = yes` to it. An RNodeMulti subinterface with its own flag follows that flag, so a subinterface set to no never transmits.
- Durable storage works on any filesystem again, as in Python Reticulum, including ZFS, Docker overlays, external drives and network shares. A flush the filesystem lacks is skipped and logged once, and network or RAM-backed storage logs a warning instead of refusing to start.
- A Link accepts the peer's identification as soon as its handshake completes, as in Python Reticulum, so a request a Python client sends right after identifying no longer fails for lack of an identity. Only the receiving side of a Link accepts identification.
- The receiving side of a Link counts its Link proof as sent traffic, as in Python Reticulum, so it no longer answers keepalives before the Link is established and its traffic totals include the proof.
- A connectable I2P interface now starts alongside a Unix-socket shared instance or another connectable I2P interface, and an I2P interface runs one connection for every configured peer, plus its server when connectable, as in Python Reticulum.
- Hub restarts restore saved paths and tunnels as in Python Reticulum.
- Transport hubs now accept tunnel synthesis, so a Python client that reconnects gets its paths back without announcing again, and losing a tunnel's interface no longer drops paths the hub learned through other interfaces, as in Python Reticulum.
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down or failing to open is dropped when it opens, as in Python Reticulum.
- A client of a Unix-socket shared instance drops traffic queued while the instance was unreachable, as in Python Reticulum.
- I2P interfaces announce their own address for discovery, and the peers listed in `peers` keep Python's defaults, sharing only the interface's IFAC, as in Python Reticulum.
- A bootstrap-only I2P interface keeps running once discovered interfaces connect, as in Python Reticulum, which never detaches an I2P interface.
- A connectable I2P interface keeps its I2P address across restarts. Its key is stored in Python Reticulum's key file under `storage/i2p`, readable by its owner only; as in Python Reticulum, a node without `enable_transport` or `static_transport_identity` gets a new address each start.
- Every validated announce refreshes the identity remembered for its destination, including path responses and replays that leave the path unchanged, so a destination's identity stays recallable as in Python Reticulum.
- Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum.
- `rnstatus-rs -R` and `rnpath-rs -R` take the remote node's transport identity hash, which `rnstatus` shows as the transport instance on a transport node. A node with `enable_transport` off and no `static_transport_identity` gets a new management destination each start, as in Python Reticulum; set `static_transport_identity = yes` on a leaf you manage remotely. `storage/remote_management_identity` is no longer used and can be deleted.
- Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum.
- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum.
- Discovery announces a KISS-framed TCP client as a KISS interface and sends and reads unset radio parameters as nil, so Python and `rnsd-rs` read each other's KISS, Weave and RNode announces, as in Python Reticulum.
- `rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps counting while the system is suspended, for deadlines that must hold in real time across a sleep.
- An interface counts a path request in its stats only once its tag passes the duplicate check, as in Python Reticulum 1.5.
- A realtime Link packet dropped at a full transmit queue counts toward the interface's dropped bytes.
- `rnpath -R` filters the remote path and rate tables as Python Reticulum compares them: a destination hash of another length matches nothing, and the hop limit compares as a number instead of wrapping above 255.
- Remote management Links refuse Resources other than requests and responses, as Python Reticulum's do.
- `rnsd-rs` never auto-connects a discovered interface at an onion address, at 127.0.0.1 or 0.0.0.0, or at a host and port that an interface already connects to, as in Python Reticulum.
- Interface stats name the network an auto-connected interface was discovered through (`autoconnect_source`), as in Python Reticulum.
- Decryption, key derivation and identity and ratchet file handling no longer leave copies of keys or plaintext in freed memory, and identity files larger than 1 KiB are refused.
- A 64-byte identity file always loads as a raw key, as in Python Reticulum. About one key in 29,000 began with bytes that were misread as the older envelope format, and its identity failed to load.
- Writing, verifying and recovering state files retries a read that a signal interrupts instead of failing.
- Interface options wipe their IFAC passphrase when dropped, and the debug output of IFAC settings no longer shows it.
- Each interface's IFAC key lives in one allocation that is wiped when dropped, so interface tables no longer leave copies of it in freed memory.
- I2P interfaces no longer leave their private key in freed memory when they read it, store it or exchange it with the SAM bridge. They refuse a key file larger than 16 KiB and, as Python Reticulum's SAM client does, a SAM reply line longer than 64 KiB.
- Remote management answers the profiling flag of `rnstatus -R -z` with empty results, and leaves a status request that is not a list of flags unanswered, as Python Reticulum does.
- `rnstatus-rs` shows the network an auto-connected interface was discovered through on a `Source` line under its name, as Python's `rnstatus` does, and its JSON output carries it as `autoconnect_source`.
- AutoInterface's `devices` and `ignored_devices` take effect, and they and I2P `peers` are read as Python Reticulum reads lists: a quoted name that contains a comma stays one name, and `devices = ,` allows every interface.
- TCP client interfaces read `i2p_tunneled`, as Python Reticulum does, and give a connection tunneled over I2P its longer I2P socket timeouts.
- TCP server and Backbone interfaces are announced for discovery only with `reachable_on` set, and Backbone clients never, as in Python Reticulum. A discoverable server without `reachable_on` logs a warning and is not announced, so set `reachable_on` to keep announcing it. The `discovery_reachable_on` key is no longer read.
## 1.4.0 - 2026-10-12
- Corrected packet-size limits across interfaces and Links, including IFAC overhead, and reject unsupported Link setups before sending them.
- Added application-controlled acknowledgements so propagation nodes can confirm a message only after safely storing it.
- Prevent stale interface or Link callbacks from acknowledging a different connection after reconnect or cancellation.
- Reject malformed Resource metadata and invalid timeout values without panics or excessive allocation.
- Added checked durable file operations for identities, ratchets, and application storage, with explicit recovery after interrupted writes.
- Updated public interface, Link, and storage APIs. This source-breaking release uses the `~1.4.0` compatibility line.
## 1.3.0 - 2026-10-12
### Added
Generated
+17 -10
View File
@@ -11,6 +11,7 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
@@ -328,6 +329,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -1624,7 +1626,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1645,9 +1647,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"proptest",
"rand 0.8.5",
"rmp-serde",
@@ -1656,6 +1659,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
@@ -1664,7 +1668,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bluer",
"btleplug",
@@ -1697,9 +1701,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"proptest",
"rand 0.8.5",
"rmpv",
@@ -1708,12 +1713,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1723,6 +1729,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.21",
"tokio",
"tracing",
@@ -1730,7 +1737,7 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"bip39",
@@ -1756,7 +1763,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1783,7 +1790,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
@@ -1810,7 +1817,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1830,7 +1837,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"proptest",
"rns-crypto",
+12 -12
View File
@@ -14,7 +14,7 @@ members = [
]
[workspace.package]
version = "1.3.0"
version = "1.4.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.89"
@@ -23,9 +23,9 @@ rust-version = "1.89"
# Crypto
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
aes = { version = "0.8", features = ["zeroize"] }
des = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
cbc = { version = "0.1", features = ["alloc", "zeroize"] }
hkdf = "0.12"
hmac = "0.12"
md-5 = "0.10"
@@ -80,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
proptest = "1"
# Workspace crates
rns-crypto = { path = "crates/rns-crypto", version = "~1.3.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "~1.3.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "~1.3.0" }
rns-transport = { path = "crates/rns-transport", version = "~1.3.0" }
rns-link = { path = "crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "crates/rns-protocol", version = "~1.3.0" }
rns-interface = { path = "crates/rns-interface", version = "~1.3.0" }
rns-runtime = { path = "crates/rns-runtime", version = "~1.3.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.3.0" }
rns-crypto = { path = "crates/rns-crypto", version = "~1.4.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "~1.4.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "~1.4.0" }
rns-transport = { path = "crates/rns-transport", version = "~1.4.0" }
rns-link = { path = "crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "crates/rns-protocol", version = "~1.4.0" }
rns-interface = { path = "crates/rns-interface", version = "~1.4.0" }
rns-runtime = { path = "crates/rns-runtime", version = "~1.4.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.4.0" }
+13 -1
View File
@@ -118,7 +118,7 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
```text
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [-i] [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|prx|ptx|held]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|arxc|atxc|prx|ptx|prxc|ptxc|held|pvs|ivs|flt|txdrp|txdrb]
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
[-d|--discovered] [-D] [-m [-I SECONDS]] [FILTER]
[-R <transport_hash> -i <identity_file>]
@@ -236,6 +236,12 @@ shared_instance_port = 37432
instance_control_port = 37433
```
Programs use the control port with the instance's RPC key: `rpc_key` under
`[reticulum]` when it is set, otherwise a key derived from the transport
identity. That key is an admin credential: a program that has it can read the
daemon's network state, drop its paths and block identities, so treat it like
a password and give it only to programs you trust.
## Interface Support
###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it.
@@ -295,6 +301,12 @@ Known gaps and intentional limits:
- `rnpath-rs` remote mode is read-only for table/rates, including destination
filters, apart from the remote blackhole-list query path. Remote mutations
and remote active path requests are full gaps.
- Interface discovery announces name this stack `rsRNS` and its version. Python
Reticulum 1.5.5 and later auto-connects only to Backbone interfaces
announced by Python Reticulum 1.5.2 or later, so a Python node auto-connects
to an `rsRNS` interface only with `autoconnect_unverified_implementations =
yes` in its `[reticulum]` section. `rnsd-rs` follows the same rule, and the
same option lets it auto-connect to any announced Backbone interface.
- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates`
is not supported for the time being.
- `rns-ratkey` hardware identity support is feature-gated and still has known
+2
View File
@@ -69,6 +69,8 @@ endpoint, not the identity of the packet socket. Selecting a trustworthy matchin
pair remains the application's responsibility. These policies do not move
AutoInterface's interoperable UDP ports or alter Reticulum wire formats.
The in-development [capacity, IFAC and receipt migration guide](migrations/capacity-and-receipts.md) describes the next coordinated source boundary. It does not select a release version.
## Stability
The 1.3 line changes the six discovery coordinate fields to `Option<f64>` so
+17 -8
View File
@@ -11,6 +11,7 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
@@ -225,6 +226,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -1170,13 +1172,15 @@ dependencies = [
name = "rns-application-api-fixture"
version = "0.0.0"
dependencies = [
"rns-identity",
"rns-protocol",
"rns-runtime",
"rns-transport",
]
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1194,9 +1198,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand",
"rmp-serde",
"rmpv",
@@ -1204,6 +1209,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.20",
"tracing",
"windows-sys 0.61.2",
@@ -1212,7 +1218,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bluer",
"btleplug",
@@ -1245,9 +1251,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand",
"rmpv",
"rns-crypto",
@@ -1255,12 +1262,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.20",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1269,6 +1277,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -1276,7 +1285,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1303,7 +1312,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1322,7 +1331,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
+2
View File
@@ -11,5 +11,7 @@ default = []
all = ["rns-runtime/ble", "rns-runtime/rnode-tcp", "rns-runtime/serial"]
[dependencies]
rns-protocol = { path = "../../crates/rns-protocol" }
rns-identity = { path = "../../crates/rns-identity" }
rns-transport = { path = "../../crates/rns-transport" }
rns-runtime = { path = "../../crates/rns-runtime", default-features = false }
+29 -1
View File
@@ -134,7 +134,7 @@ pub mod shared_ownership {
}
}
/// The 1.4 discovery API distinguishes unknown components from true zeros.
/// The 1.3 discovery API distinguishes unknown components from true zeros.
pub mod nullable_discovery {
use rns_transport::discovery::DiscoveryInterfaceConfig;
use rns_transport::discovery::app_data::DiscoveryInfo;
@@ -163,3 +163,31 @@ pub mod nullable_discovery {
[info.latitude, info.longitude, info.height]
}
}
/// Application admission carries non-cloneable authority separately from bytes.
pub mod application_packet_admission {
use rns_runtime::link_manager::{
InboundLinkPacket, LinkPacketReceiptOutcome, LinkPacketRejection,
};
pub async fn accept(packet: InboundLinkPacket) -> Option<LinkPacketReceiptOutcome> {
let (payload, receipt) = packet.into_parts();
let outcome = receipt?.accept().await.ok();
drop(payload);
outcome
}
pub fn compile_surface() {
let _ = LinkPacketRejection::InvalidPropagationStamp;
let _ = rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy;
let _ = rns_runtime::interface_factory::InterfacePostInit::try_from_section;
let _ = rns_runtime::config::ifac::parse_ifac_size;
let _ = rns_runtime::config::ifac_lock::ConfigWriteLock::acquire;
let _ = rns_identity::persistence::durable_write;
let _ = rns_identity::persistence::durable_reconcile_hash;
let _ = rns_transport::messages::InterfacePacketCapacity::new(500, 508, false);
let _ = rns_transport::messages::InterfaceTransportSender::new;
let _ = rns_transport::link_messages::dispatch_link_request;
let _ = rns_transport::link_messages::LinkRequestDispatchError::NoInterface;
let _ = rns_transport::ifac::try_ifac_sign;
let _ = rns_protocol::resource_control::check_control_frame;
}
}
+179
View File
@@ -0,0 +1,179 @@
# 1.4 source migration (unreleased)
The 1.4 source line introduces explicit interface-capacity ownership and durable
application admission. Existing published releases are unchanged. Migrate
Reticulum dependents together to ~1.4.0; a source version alone is not publication.
Follow [capacity, IFAC configuration, receipts and timing](capacity-and-receipts.md)
for the full API and configuration transition. In particular:
- Replace `InterfacePostInit::from_section` with fallible `try_from_section`,
and propagate semantic configuration errors before spawning interfaces.
- `LinkManager::set_link_packet_channel` returns a result. The legacy tuple
receiver cannot enable ProveApp; use the bounded typed packet channel and
exact endpoint binding for application-controlled receipts.
- Custom interface handles and entries must supply exact owner and typed packet
capacity facts. Construct their bound sender before producer tasks start.
Link endpoint bindings retain the interface owner captured from the admitted
request/proof, rather than looking up whichever interface currently has an ID.
- Request admission and proof validation are separate. Retain one attempt-owned
result and deadline; cancelled/refused attempts cannot change a replacement.
Build `InterfaceStatRpcEntry` with `..Default::default()` and `InterfaceEntry`
with `..InterfaceEntry::new(...)`, so fields added on the 1.4 line stay
source compatible.
`rns_link::mtu_discovery::SignallingData` remains a public re-export of the
shared `rns_wire::link_signalling::SignallingData`; existing imports and checked
handshake callers can continue using that alias. Cargo-public-api renders
canonical type paths from rns-wire, so its twelve moved snapshot lines are
explicitly recorded despite preserved source identity. `new/pack/unpack` remain
low-level representation helpers; use checked signalling APIs for admission.
`rpc::InterfaceStatEntry::ifac_size` is now `Option<usize>`, `None` when the
interface has no IFAC, and the entry gains `ifac_signature` and `ifac_netname`,
as in Python's interface stats. Interface sections start only when
`interface_enabled` or `enabled` is true; add `enabled = yes` to sections that
relied on the old default. `ConfigSection::interface_enabled`, `has_enable_key`
and `invalid_enable_key` expose that rule to embedders.
Strict persistence accepts every filesystem; `DurabilityUnsupported` no longer
reports an unqualified filesystem. `persistence::storage_risk` classifies network
or user-space (`Remote`) and RAM-backed (`Volatile`) storage so applications can
warn their users.
`I2PServerConfig` gains `b32`, which receives the server's b32 address when
SAM creates its session, and `key_path`, the file that keeps the server's
private key, and so its address, across sessions; the runtime sets it to
Python's key file under `storage/i2p`. `i2p::destination_b32` derives the
address from a SAM private key; build the config with `new`.
`discovery::announcer::Announcer::reconfigure` replaces a registered
interface's config but keeps its announce interval.
`TunnelEntry::interface_id` is now `Option<InterfaceId>`, `None` while the
tunnel is unbound, instead of the id-0 sentinel. `spawn_local_server` and
`spawn_i2p_server` take the listener's allocated `InterfaceId`, which their
accepted clients report as `parent_id`. `InterfaceEntry::parent_id` carries it
into transport; set it from `InterfaceHandle::parent_id`. Persisted tunnels now
load unbound into the tunnel table, so `TransportActor::pending_tunnel_entries`
is gone.
`TunnelSynthesisData::unpack` accepts exactly 176 bytes, and `is_signed` is
the check transport applies before admitting one. The TCP, Backbone and I2P
client configs' `python_name` is the Python `str()` their syntheses hash. Announces join the
tunnel named by their interface's latest synthesis, which `handle_tunnel` and
`TunnelTable::insert` record and `TunnelTable::void_interface` clears; writing
`interface_id` directly no longer rebinds an interface. `handle_tunnel` no
longer takes a timeout: a tunnel expires `TUNNEL_TIMEOUT` after its synthesis,
as in Python. `TunnelTable::cull_expired` and `cull_expired_batch` also drop
tunnels set to expire more than twice `TUNNEL_TIMEOUT` ahead.
`TcpClientConfig`, `BackboneClientConfig` and `I2PClientConfig` gain
`tunnel_identity`. With a `TunnelIdentity` set, the client opens every
connection with a tunnel synthesis signed by it; the runtime sets it from
`ReticulumHandle::transport_identity`. Build these configs with `new` so the
field defaults to `None`. A KISS-framed TCP client never synthesizes. Every
TCP, Backbone and I2P client, the shared-instance TCP client included, drops
its queued traffic when a connection opens after an outage or a failed
attempt, and the Unix shared-instance client drops it when it reconnects.
`TcpClientConfig` gains `i2p_tunneled`, which gives a TCP connection tunneled
over I2P Python's longer I2P socket timeouts; the runtime reads it from the
interface's `i2p_tunneled` key. Build the config with `new` so it defaults to
`false`.
Interface stats carry Python 1.5's per-interface counters.
`IngressController` counts announces and path requests received and sent;
`InterfaceEntry` gains `protocol_violations`, `ifac_violations`,
`packet_filter_hits` and `tx_dropped_bytes`; `InterfaceStatRpcEntry` reports
all of them plus `parent_id`; `rpc::InterfaceStatEntry` carries them, the
listener's name, and now implements `Default`. Build it with
`..Default::default()`. The control port and remote management answer with
one Python-shaped stats dict, so `remote_management_schema` is removed:
decode a `/status` answer as `[stats, link_count?]`, and a `/path` answer with
`rpc::decode_response_for_request`. Remote management answers on the transport
identity, so `rnstatus -R` and `rnpath -R` take its hash. A node with
`enable_transport` off and no `static_transport_identity` gets a new management
destination each start, as in Python. The runtime no longer reads
`storage/remote_management_identity`, and leaves the file in place for the
operator to delete.
Interface discovery carries Python 1.5's implementation keys.
`DiscoveryInfo` gains `impl_name` and `impl_version`; build it with
`..Default::default()`. `discovery::autoconnect::qualifies` applies Python's
auto-connect rule, with `ReticulumConfig::autoconnect_unverified_implementations`
as its opt-in. The receiver no longer stores types that are never listed, so
`discovery::Reason` gains `UnlistedType` and becomes `#[non_exhaustive]`, so a
match needs a wildcard arm.
`rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps
counting while the system is suspended: `CLOCK_BOOTTIME` on Linux and Android,
`CLOCK_MONOTONIC_RAW` on Apple platforms and the performance counter on
Windows, with `std::time::Instant` as a best-effort fallback elsewhere. Use it
for a deadline that must hold in real time across a sleep, and check that
deadline on a regular tick: tokio's timers and the operating system's waits
count awake time only, so a timer armed for it fires late by the whole sleep.
Readings are process-local and do not convert to or from `std::time::Instant`.
rns-link gains the target dependencies `libc` (unix) and `windows-sys`
(Windows), so dependents that build with `--locked` refresh their lock files.
`hkdf::derive_key_64` returns `Zeroizing<[u8; 64]>` and `hkdf::hkdf_sha256`
returns `Zeroizing<Vec<u8>>`, so derived keys are wiped when they are dropped.
Pass `&key[..]` where a slice is expected and compare `&okm[..]` with a plain
`Vec`; the bytes are unchanged. `Zeroizing<[u8; 64]>` is not `Copy`, so code
that copied the key borrows it instead. `token::decrypt` still returns
`Vec<u8>` and wipes its buffer when decryption fails; wrap a secret plaintext
in `Zeroizing`. `Identity::from_file` reads at most 1025 bytes and refuses a
file larger than 1 KiB.
`InterfacePostInit::ifac_passphrase` is `Option<Zeroizing<String>>`, so the
passphrase is wiped when the options are dropped: read it with
`.as_deref().map(String::as_str)` and wrap a new one in `Zeroizing::new`.
`RuntimeInterfaceIfacConfig` prints `<redacted>` in place of its passphrase.
`InterfaceEntry::ifac_key` is `Option<rns_identity::ifac::IfacKey>`, one
allocation that clones share and that is wiped when the last one drops, so
interface tables never copy the key. `with_ifac` still takes the key bytes;
otherwise set `Some(key.into())` or `IfacKey::derive(network_name,
passphrase)`, and read the bytes through `&*key`.
rns-crypto re-exports `zeroize` for crates that hold its wiped types without
depending on it, and `rns_identity::persistence::read_secret_file` reads a
bounded secret file into one wiped buffer. An I2P interface refuses a key file
larger than 16 KiB and a SAM reply line longer than 64 KiB, and
`I2PServerConfig` prints `<redacted>` in place of a configured key.
rns-crypto enables the `zeroize` features of `aes` and `cbc`, so AES key
schedules and CBC state are wiped when dropped; dependents that build with
`--locked` refresh their lock files.
The compatibility floor remains unchanged. Its cumulative exact-removal list
also retains the already-reviewed [1.3 migration](1.3.md) for discovery ownership
and nullable coordinates; it is not reclassified as a new 1.4 change. Additive
struct fields can require literal-construction updates even when no old public
line disappears. No whole-crate waiver or baseline reset is used.
Disk-backed Destination handlers can use
`LinkManager::register_deferred_request_handler` after installing an exact
endpoint dispatch handle. Existing synchronous handlers remain supported. The
new callback receives `DestinationRequest` and a one-shot
`DeferredRequestResponder`; move both into the actual bounded worker and return
promptly. Read `response_byte_limit()` before allocating or retiring stored
items. Check `is_cancelled()` before work, and retain the responder until the
worker has actually stopped. `respond(RequestOutcome)` returns a typed completion
receiver: `Sent` means the packet was queued or the response Resource started,
not that the remote application accepted it.
Admission reserves one of four process-wide slots and a conservative share of
256 MiB before invoking the callback. Charge is sixteen times request capacity,
eight times the effective response capacity, plus 16 MiB of construction scratch.
The token may report a smaller limit than registration requested. This accounts
for the bounded handler's planning structures and current response/Resource
construction; arbitrary application allocations are outside this contract.
Response allocation capacity, including optional follow-up Resource metadata,
must fit the token. Requests expire after 120 seconds. Refused admission never
invokes the callback. Dropping a manager revokes response authority while a live
worker retains its reservation; completed response Resources retain that same
reservation until terminal cleanup.
Deferred handlers require exact endpoint ownership. Queued response packets and
Resource advertisement, part, request, hash-map update and cancellation commands
carry `SendLinkEndpointExact` authority. The actor rejects an old token even when
a replacement uses the same Link ID, interface and role. Existing legacy send
commands remain available; they do not acquire this generation-bound guarantee.
+117
View File
@@ -0,0 +1,117 @@
# Capacity, IFAC configuration, and application packet receipts
These changes are part of the unreleased1.4.0 source line. They do not change
the existing published1.3.0 release or establish a new release date.
## Interface ownership and packet capacity
`InterfaceHandle` and `InterfaceEntry` carry an `InterfaceOwner` and an
`InterfacePacketCapacity`. The historical `mtu` field remains available for
statistics. Admission uses the separate clear-packet and IFAC-bearing wire
budgets, and `link_mtu_upgrade` explicitly controls upgrade permission.
Custom drivers must create `InterfaceTransportSender` before starting any task
or callback that can publish input or cleanup events. Copy its `owner()` into
the handle, and retain clones of that sender across carrier reconnects. Each
accepted child and replacement registration needs a fresh sender and owner.
Send inbound packets and driver-originated deregistration through this sender;
raw unowned events are refused. Do not wrap messages twice. Coordinated IFAC or
capacity changes use a new owner revision and rebind producers; ordinary
bitrate/online changes do not establish a new capacity promise.
Async driver sends wait until the actor accepts that owner registration. This
keeps the first packet of a newly accepted connection from racing registration;
retiring the owner releases pending sends with an error. Custom actor harnesses
must explicitly mark the owner registered when they accept its registration.
The conservative custom-driver default is `InterfacePacketCapacity::base(mtu)`.
Explicitly declare additional IFAC headroom or upgrade support only when the
whole-packet driver guarantee supports it. Framing and BLE fragmentation are
outside these budgets. TCP fixed MTUs must fit the actual wire budget after IFAC.
Active IFAC also limits the complete wire packet to HKDF-SHA256's 8160-byte
expansion limit; subtract the configured tag size for its clear-packet ceiling.
General Links require at least 500 clear packet bytes. An interface with less
capacity can still carry fitting non-Link traffic, but reports
`LinkCapacityUnavailable` for general Links. RNode's 508-byte wire budget carries
500 clear bytes with IFAC tags up to eight bytes. Larger tags are never silently
weakened. Current local endpoints remain capped at 500; safe transit can preserve
larger peer offers. Legacy or zero Link signalling means 500; nonzero values below
500, malformed shapes, disabled endpoint modes, and proofs above the original
offer are rejected before endpoint state changes.
Initiators send `SendLinkRequest` with a per-attempt oneshot result, or call
`link_messages::dispatch_link_request`. The result preserves typed capacity
errors before waiting for a proof. Keep one establishment deadline around both
admission and proof waiting. Drop the result receiver when cancelling: an actor
that has not dispatched that attempt then emits no request. This acknowledgement
means local driver admission, not peer receipt. It does not replace signature
verification or the exact interface owner retained from the request/proof path.
## Explicit IFAC units
An explicit `ifac_size` is interpreted as bits only when accompanied by
`ifac_size_unit = bits`. The byte escape hatch is `ifac_size_bytes`; it cannot
coexist with the bits fields. Supported effective sizes are 1–64 bytes. A bare
old `ifac_size` requires migration; its historical meaning is not guessed.
Omitting all size keys retains the interface class default. Explicit malformed
sizes remain errors even when credentials are absent. Disabled interfaces may
retain old settings, but must be migrated before enabling them.
`InterfacePostInit::try_from_section` replaces the infallible constructor. Use
the shared `config::ifac::parse_ifac_size` decoder rather than another parser.
`validate_config_capacity` checks explicit driver promises before spawn.
Malformed file syntax still fails the file; semantic errors isolate the affected
enabled interface.
Preview an explicitly selected migration without starting the network:
```sh
rnsd-rs -c /path/to/config-directory config ifac-units --source-units bytes --interface Radio
```
Use `--source-units bits` when that is the known source convention. Add `--write`
to publish the reviewed plan. Publication checks that the source is unchanged,
takes the shared OS-backed config lock, and retains a unique private backup.
An older binary requires restoring its original configuration before rollback.
## Ordinary Link packet proofs
Ordinary `DATA` with context `None` follows explicit `ProofStrategy` policy.
`ProveNone` delivers without a proof. `ProveAll` preserves automatic proofs and
delivers independently of proof queue admission. `ProveApp` requires both an
exact endpoint dispatch handle and the bounded typed inbound channel; it cannot
use the legacy tuple channel. Configuration setters return a result.
For application-controlled admission, receive `InboundLinkPacket`, retain its
`Bytes` and non-cloneable `LinkPacketReceipt` through validation and persistence,
then consume the receipt with `accept()`. Awaiting its result distinguishes local
driver admission (`Sent`) from expiration, closed ownership, dropping, or failure.
`Sent` does not mean physical radio transmission or remote delivery. Dropping the
receipt produces no proof. `reject_and_close(InvalidPropagationStamp)` orders the
protocol rejection before teardown when it can be admitted. Use
`close_without_proof()` for a storage/quota failure that requires teardown without
claiming an invalid propagation stamp; it retains the same exact-owner checks.
Authority is tied to the exact Link generation. Expired, closed, or replaced
owners cannot send a late proof. Payload clones retain admission credits until
they are actually dropped, even if the receipt expires. Limits are 64 packets
and 2 MiB per Link, and 256 packets and 8 MiB process-wide for this ordinary
application-controlled ingress. Resource, Channel, RPC, Direct, and voice
protocol owners retain their own admission rules.
## Durable storage and local timing
`rns_identity::persistence::durable_write` returns a privately constructed receipt
only after exact verification and the native platform barriers succeed. It is
separate from the existing cache writer. Errors distinguish pre-publication
failure from `CommitUncertain`; keep recovery material and withhold higher-level
acceptance on uncertainty. `durable_reconcile` and bounded streaming
`durable_reconcile_hash` renew barriers as well as verifying bytes. A receipt
attests those calls, not hardware infallibility or the provenance of a message.
Directory migration still requires an application journal and native recovery.
Use `Link::try_extend_establishment_timeout` for checked timeout extension.
Invalid floating-point times and unrepresentable deadlines are rejected before
transport side effects. Channel RTTs have a finite local ceiling and its sending
window remains bounded even when public tuning fields contain extreme values.
+109 -45
View File
@@ -4,7 +4,7 @@
"packages": [
{
"name": "rns-crypto",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -34,7 +34,9 @@
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"zeroize"
],
"sourceKind": "registry"
},
{
@@ -46,7 +48,8 @@
"optional": false,
"defaultFeatures": true,
"features": [
"alloc"
"alloc",
"zeroize"
],
"sourceKind": "registry"
},
@@ -173,7 +176,7 @@
},
{
"name": "rns-identity",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -239,7 +242,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -252,7 +255,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -284,6 +287,17 @@
"features": [],
"sourceKind": "registry"
},
{
"name": "sha2",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.10",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
@@ -319,6 +333,17 @@
],
"sourceKind": "registry"
},
{
"name": "libc",
"rename": null,
"kind": null,
"target": "cfg(unix)",
"requirement": "^0.2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "windows-sys",
"rename": null,
@@ -336,7 +361,7 @@
},
{
"name": "rns-interface",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -452,7 +477,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -465,7 +490,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -476,7 +501,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -487,7 +512,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -696,7 +721,7 @@
},
{
"name": "rns-link",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -759,7 +784,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
@@ -770,7 +795,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -781,7 +806,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
@@ -821,12 +846,36 @@
"derive"
],
"sourceKind": "registry"
},
{
"name": "libc",
"rename": null,
"kind": null,
"target": "cfg(unix)",
"requirement": "^0.2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "windows-sys",
"rename": null,
"kind": null,
"target": "cfg(windows)",
"requirement": "^0.61",
"optional": false,
"defaultFeatures": true,
"features": [
"Win32_System_Performance"
],
"sourceKind": "registry"
}
]
},
{
"name": "rns-protocol",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -892,7 +941,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -905,7 +954,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -916,7 +965,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -924,6 +973,19 @@
],
"sourceKind": "path"
},
{
"name": "serde",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"derive"
],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
@@ -963,7 +1025,7 @@
},
{
"name": "rns-ratkey",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -993,7 +1055,9 @@
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"zeroize"
],
"sourceKind": "registry"
},
{
@@ -1078,7 +1142,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1091,7 +1155,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1197,7 +1261,7 @@
},
{
"name": "rns-runtime",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1312,7 +1376,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1325,7 +1389,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1336,7 +1400,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1347,7 +1411,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1358,7 +1422,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1369,7 +1433,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1380,7 +1444,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1475,7 +1539,7 @@
},
{
"name": "rns-tools",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1586,7 +1650,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1599,7 +1663,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1610,7 +1674,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1621,7 +1685,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": true,
"defaultFeatures": true,
"features": [
@@ -1634,7 +1698,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -1647,7 +1711,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1658,7 +1722,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1751,7 +1815,7 @@
},
{
"name": "rns-transport",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1831,7 +1895,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1844,7 +1908,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1855,7 +1919,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1926,7 +1990,7 @@
},
{
"name": "rns-wire",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1955,7 +2019,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
+3 -2
View File
@@ -1,4 +1,5 @@
pub mod rns_crypto
pub use rns_crypto::zeroize
pub mod rns_crypto::aes_cbc
pub enum rns_crypto::aes_cbc::AesCbcError
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
@@ -33,8 +34,8 @@ pub mod rns_crypto::hkdf
pub enum rns_crypto::hkdf::HkdfError
pub rns_crypto::hkdf::HkdfError::ExpansionFailed
pub rns_crypto::hkdf::HkdfError::OutputTooLong(usize)
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<zeroize::Zeroizing<[u8; 64]>, rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, rns_crypto::hkdf::HkdfError>
pub mod rns_crypto::hmac
pub fn rns_crypto::hmac::hmac_sha256(&[u8], &[u8]) -> [u8; 32]
pub fn rns_crypto::hmac::hmac_verify(&[u8], &[u8], &[u8; 32]) -> bool
+57
View File
@@ -38,6 +38,7 @@ pub fn rns_identity::announce_state::RatchetControlState::new([u8; 16], [u8; 16]
pub fn rns_identity::announce_state::RatchetControlState::prepare_announce(&self, u64) -> core::io::error::Result<core::option::Option<Self>>
pub fn rns_identity::announce_state::RatchetControlState::rotation_due(&self, u64, u64) -> bool
pub fn rns_identity::announce_state::RatchetControlState::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::with_rotation_at(&self, u64) -> Self
pub mod rns_identity::destination
#[repr(u8)] pub enum rns_identity::destination::AllowPolicy
@@ -247,9 +248,23 @@ pub mod rns_identity::ifac
pub enum rns_identity::ifac::IfacError
pub rns_identity::ifac::IfacError::HkdfFailed(rns_crypto::hkdf::HkdfError)
pub rns_identity::ifac::IfacError::InvalidSalt
pub struct rns_identity::ifac::IfacKey(_)
impl rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::derive(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<Self, rns_identity::ifac::IfacError>
impl core::cmp::Eq for rns_identity::ifac::IfacKey
impl core::cmp::PartialEq for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::eq(&self, &Self) -> bool
impl core::convert::From<[u8; 64]> for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::from([u8; 64]) -> Self
impl core::fmt::Debug for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_identity::ifac::IfacKey
pub type rns_identity::ifac::IfacKey::Target = [u8; 64]
pub fn rns_identity::ifac::IfacKey::deref(&self) -> &[u8; 64]
pub const rns_identity::ifac::IFAC_SALT: &str
pub fn rns_identity::ifac::derive_ifac_identity(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<(rns_identity::identity::Identity, [u8; 64], [u8; 64]), rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::derive_ifac_key(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<[u8; 64], rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::ifac_signature(&[u8; 64]) -> core::option::Option<[u8; 64]>
pub fn rns_identity::ifac::split_ifac_key(&[u8; 64]) -> (&[u8], &[u8])
pub mod rns_identity::known_destinations
pub struct rns_identity::known_destinations::KnownDestination
@@ -283,9 +298,49 @@ pub fn rns_identity::known_destinations::KnownDestinations::default() -> Self
pub mod rns_identity::name_hash
pub fn rns_identity::name_hash::name_hash(&str) -> [u8; 10]
pub mod rns_identity::persistence
pub enum rns_identity::persistence::DurableCleanupOutcome
pub rns_identity::persistence::DurableCleanupOutcome::AlreadyAbsent
pub rns_identity::persistence::DurableCleanupOutcome::Removed
pub enum rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableCommitPhase::CommitUncertain
pub rns_identity::persistence::DurableCommitPhase::NotCommitted
pub enum rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableErrorKind::DurabilityUnsupported
pub rns_identity::persistence::DurableErrorKind::InvalidInput
pub rns_identity::persistence::DurableErrorKind::Io
pub rns_identity::persistence::DurableErrorKind::Verification
#[non_exhaustive] pub enum rns_identity::persistence::StorageRisk
pub rns_identity::persistence::StorageRisk::Remote
pub rns_identity::persistence::StorageRisk::Volatile
impl core::fmt::Display for rns_identity::persistence::StorageRisk
pub fn rns_identity::persistence::StorageRisk::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_identity::persistence::DurableDirectoryReceipt
impl rns_identity::persistence::DurableDirectoryReceipt
pub fn rns_identity::persistence::DurableDirectoryReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableFileReceipt
impl rns_identity::persistence::DurableFileReceipt
pub fn rns_identity::persistence::DurableFileReceipt::content_hash(&self) -> [u8; 32]
pub fn rns_identity::persistence::DurableFileReceipt::is_empty(&self) -> bool
pub fn rns_identity::persistence::DurableFileReceipt::len(&self) -> usize
pub fn rns_identity::persistence::DurableFileReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableWriteError
pub rns_identity::persistence::DurableWriteError::kind: rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableWriteError::phase: rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableWriteError::recovery_paths: alloc::vec::Vec<std::path::PathBuf>
pub fn rns_identity::persistence::atomic_write(&std::path::Path, &[u8]) -> core::io::error::Result<()>
pub fn rns_identity::persistence::durable_create_dir_all(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_directory(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_hash(&std::path::Path, [u8; 32], usize) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_remove(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableCleanupOutcome, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_rename_directory(&std::path::Path, &std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_write(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_secret_file(&std::path::Path, usize) -> core::io::error::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::storage_risk(&std::path::Path) -> core::io::error::Result<core::option::Option<rns_identity::persistence::StorageRisk>>
pub fn rns_identity::persistence::try_lock_exclusive(&std::fs::File) -> core::io::error::Result<()>
pub fn rns_identity::persistence::validate_durable_storage_directory(&std::path::Path) -> core::result::Result<(), rns_identity::persistence::DurableWriteError>
pub mod rns_identity::ratchet
pub enum rns_identity::ratchet::RatchetRingFormat
pub rns_identity::ratchet::RatchetRingFormat::Canonical
@@ -335,6 +390,7 @@ pub fn rns_identity::ratchet::RatchetRing::rotate(&mut self) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::rotate_at(&mut self, f64) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::save(&self, &std::path::Path, &[u8; 64]) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::set_ratchet_interval(&mut self, u64) -> bool
pub fn rns_identity::ratchet::RatchetRing::set_retained_ratchets(&mut self, usize) -> bool
impl core::default::Default for rns_identity::ratchet::RatchetRing
@@ -354,6 +410,7 @@ pub fn rns_identity::ratchet::ReceivedRatchet::new([u8; 32]) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::new_at([u8; 32], f64) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::ratchet_id(&self) -> alloc::vec::Vec<u8>
pub fn rns_identity::ratchet::ReceivedRatchet::save(&self, &std::path::Path) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::ReceivedRatchet::save_durable(&self, &std::path::Path) -> core::io::error::Result<()>
pub struct rns_identity::ratchet::ReceivedRatchetStore
impl rns_identity::ratchet::ReceivedRatchetStore
pub fn rns_identity::ratchet::ReceivedRatchetStore::clean_expired(&mut self)
+33 -2
View File
@@ -121,8 +121,10 @@ pub rns_interface::backbone::BackboneClientConfig::name: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::prefer_ipv6: bool
pub rns_interface::backbone::BackboneClientConfig::target_host: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::target_port: u16
pub rns_interface::backbone::BackboneClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::backbone::BackboneClientConfig
pub fn rns_interface::backbone::BackboneClientConfig::new(&str, &str, u16) -> Self
pub fn rns_interface::backbone::BackboneClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::backbone::BackboneServerConfig
pub rns_interface::backbone::BackboneServerConfig::block_fast_flapping: bool
pub rns_interface::backbone::BackboneServerConfig::device: core::option::Option<alloc::string::String>
@@ -454,9 +456,13 @@ pub rns_interface::i2p::I2PClientConfig::peer_destination: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::reconnect_delay: u64
pub rns_interface::i2p::I2PClientConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::sam_port: u16
pub rns_interface::i2p::I2PClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::i2p::I2PClientConfig
pub fn rns_interface::i2p::I2PClientConfig::new(&str, &str) -> Self
pub fn rns_interface::i2p::I2PClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::i2p::I2PServerConfig
pub rns_interface::i2p::I2PServerConfig::b32: core::option::Option<tokio::sync::watch::Sender<core::option::Option<alloc::string::String>>>
pub rns_interface::i2p::I2PServerConfig::key_path: core::option::Option<std::path::PathBuf>
pub rns_interface::i2p::I2PServerConfig::keyfile: core::option::Option<alloc::string::String>
pub rns_interface::i2p::I2PServerConfig::mode: rns_interface::traits::InterfaceMode
pub rns_interface::i2p::I2PServerConfig::name: alloc::string::String
@@ -465,6 +471,8 @@ pub rns_interface::i2p::I2PServerConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PServerConfig::sam_port: u16
impl rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::new(&str) -> Self
impl core::fmt::Debug for rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::i2p::BITRATE_GUESS: u64
pub const rns_interface::i2p::DEFAULT_SAM_ADDRESS: &str
pub const rns_interface::i2p::DEFAULT_SAM_PORT: u16
@@ -478,11 +486,12 @@ pub const rns_interface::i2p::RECONNECT_WAIT: u64
pub const rns_interface::i2p::RECONNECT_WAIT_MAX: u64
pub const rns_interface::i2p::SAM_VERSION: &str
pub const rns_interface::i2p::TUNNEL_KEEPALIVE: u64
pub fn rns_interface::i2p::destination_b32(&str) -> core::option::Option<alloc::string::String>
pub fn rns_interface::i2p::parse_sam_reply(&str) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String)>
pub fn rns_interface::i2p::sam_reply_get<'a>(&'a [(alloc::string::String, alloc::string::String)], &str) -> core::option::Option<&'a str>
pub fn rns_interface::i2p::sam_reply_has_token(&[(alloc::string::String, alloc::string::String)], &str) -> bool
pub async fn rns_interface::i2p::spawn_i2p_client(rns_interface::i2p::I2PClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, rns_interface::traits::InterfaceId, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub mod rns_interface::kiss
pub struct rns_interface::kiss::KissDeframer
impl rns_interface::kiss::KissDeframer
@@ -560,7 +569,7 @@ pub fn rns_interface::local::python_shared_socket_name(&str) -> alloc::string::S
pub fn rns_interface::local::socket_path(core::option::Option<&std::path::Path>) -> std::path::PathBuf
pub fn rns_interface::local::socket_path_for(&str) -> alloc::string::String
pub async fn rns_interface::local::spawn_local_client(rns_interface::local::LocalClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, rns_interface::traits::InterfaceId, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub mod rns_interface::pipe
pub struct rns_interface::pipe::PipeInterfaceConfig
pub rns_interface::pipe::PipeInterfaceConfig::command: alloc::string::String
@@ -658,6 +667,11 @@ pub rns_interface::rnode::RNodeFirmwareCompatibility::Unsupported
pub rns_interface::rnode::RNodeObservedRadioState::Off
pub rns_interface::rnode::RNodeObservedRadioState::On
pub rns_interface::rnode::RNodeObservedRadioState::Unknown
#[non_exhaustive] pub enum rns_interface::rnode::RNodePortFailureClass
pub rns_interface::rnode::RNodePortFailureClass::AccessDenied
pub rns_interface::rnode::RNodePortFailureClass::InUse
pub rns_interface::rnode::RNodePortFailureClass::NotFound
pub rns_interface::rnode::RNodePortFailureClass::Unavailable
pub enum rns_interface::rnode::RNodeResponse
pub rns_interface::rnode::RNodeResponse::None
pub rns_interface::rnode::RNodeResponse::Packet(rns_transport::messages::TransportMessage)
@@ -671,6 +685,7 @@ pub rns_interface::rnode::RNodeRuntimePhase::ShuttingDown
pub rns_interface::rnode::RNodeRuntimePhase::Stopped
#[non_exhaustive] pub enum rns_interface::rnode::RNodeRuntimeReason
pub rns_interface::rnode::RNodeRuntimeReason::CapabilityAdmissionRejected
pub rns_interface::rnode::RNodeRuntimeReason::ConfigurationRejected
pub rns_interface::rnode::RNodeRuntimeReason::ConnectionAttemptFailed
pub rns_interface::rnode::RNodeRuntimeReason::ConnectionLost
pub rns_interface::rnode::RNodeRuntimeReason::DeviceReset
@@ -751,11 +766,13 @@ pub fn rns_interface::rnode::RNodeRadioSettings::from(&rns_interface::rnode::RNo
pub rns_interface::rnode::RNodeRuntimeSnapshot::capability: rns_interface::rnode::RNodeCapabilityState
pub rns_interface::rnode::RNodeRuntimeSnapshot::capability_admission_failure: core::option::Option<rns_interface::rnode::RNodeCapabilityAdmissionFailureClass>
pub rns_interface::rnode::RNodeRuntimeSnapshot::configuration: rns_interface::rnode::RNodeConfigurationState
pub rns_interface::rnode::RNodeRuntimeSnapshot::configuration_rejection: core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub rns_interface::rnode::RNodeRuntimeSnapshot::connection_generation: u64
pub rns_interface::rnode::RNodeRuntimeSnapshot::detection: rns_interface::rnode::RNodeDetectionState
pub rns_interface::rnode::RNodeRuntimeSnapshot::disconnect_total: u64
pub rns_interface::rnode::RNodeRuntimeSnapshot::firmware_compatibility: rns_interface::rnode::RNodeFirmwareCompatibility
pub rns_interface::rnode::RNodeRuntimeSnapshot::phase: rns_interface::rnode::RNodeRuntimePhase
pub rns_interface::rnode::RNodeRuntimeSnapshot::port_failure: core::option::Option<rns_interface::rnode::RNodePortFailureClass>
pub rns_interface::rnode::RNodeRuntimeSnapshot::radio: rns_interface::rnode::RNodeObservedRadioState
pub rns_interface::rnode::RNodeRuntimeSnapshot::reason: core::option::Option<rns_interface::rnode::RNodeRuntimeReason>
pub rns_interface::rnode::RNodeRuntimeSnapshot::reconnect_attempt: u64
@@ -1070,6 +1087,8 @@ pub rns_interface::rnode_protocol::RNodeReadinessBlocker::RadioInitialisationFau
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware::minimum: rns_interface::rnode_protocol::RNodeFirmwareVersion
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware::observed: rns_interface::rnode_protocol::RNodeFirmwareVersion
impl rns_interface::rnode_protocol::RNodeReadinessBlocker
pub const fn rns_interface::rnode_protocol::RNodeReadinessBlocker::rejected_evidence(self) -> core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub enum rns_interface::rnode_protocol::RNodeReadinessEvidence
pub rns_interface::rnode_protocol::RNodeReadinessEvidence::Bandwidth
pub rns_interface::rnode_protocol::RNodeReadinessEvidence::CodingRate
@@ -1100,12 +1119,14 @@ pub rns_interface::rnode_protocol::RNodeProtocolEvidence::tx_power: core::option
pub struct rns_interface::rnode_protocol::RNodeProtocolState
impl rns_interface::rnode_protocol::RNodeProtocolState
pub fn rns_interface::rnode_protocol::RNodeProtocolState::apply_frame(&mut self, u8, &[u8]) -> rns_interface::rnode_protocol::RNodeProtocolEffect
pub fn rns_interface::rnode_protocol::RNodeProtocolState::definitive_rejection(&self) -> core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::detection_observed(&self) -> bool
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::evidence(&self) -> rns_interface::rnode_protocol::RNodeProtocolEvidence
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::flow_permission_observed(&self) -> bool
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::new(rns_interface::rnode_protocol::RNodeProtocolTarget) -> Self
pub fn rns_interface::rnode_protocol::RNodeProtocolState::readiness(&self) -> rns_interface::rnode_protocol::RNodeReadiness
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::target(&self) -> rns_interface::rnode_protocol::RNodeProtocolTarget
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::with_effective_settings(rns_interface::rnode_protocol::RNodeProtocolTarget) -> Self
pub struct rns_interface::rnode_protocol::RNodeProtocolTarget
pub rns_interface::rnode_protocol::RNodeProtocolTarget::bandwidth: u32
pub rns_interface::rnode_protocol::RNodeProtocolTarget::coding_rate: u8
@@ -1142,14 +1163,17 @@ pub mod rns_interface::tcp
pub struct rns_interface::tcp::TcpClientConfig
pub rns_interface::tcp::TcpClientConfig::connect_timeout_secs: u64
pub rns_interface::tcp::TcpClientConfig::fixed_mtu: core::option::Option<u32>
pub rns_interface::tcp::TcpClientConfig::i2p_tunneled: bool
pub rns_interface::tcp::TcpClientConfig::kiss_framing: bool
pub rns_interface::tcp::TcpClientConfig::max_reconnect_tries: core::option::Option<usize>
pub rns_interface::tcp::TcpClientConfig::mode: rns_interface::traits::InterfaceMode
pub rns_interface::tcp::TcpClientConfig::name: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_host: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_port: u16
pub rns_interface::tcp::TcpClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::tcp::TcpClientConfig
pub fn rns_interface::tcp::TcpClientConfig::new(&str, &str, u16) -> Self
pub fn rns_interface::tcp::TcpClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::tcp::TcpInterfaceState
pub rns_interface::tcp::TcpInterfaceState::detached: core::sync::atomic::AtomicBool
pub rns_interface::tcp::TcpInterfaceState::online: core::sync::atomic::AtomicBool
@@ -1217,11 +1241,18 @@ pub rns_interface::traits::InterfaceHandle::mode: rns_interface::traits::Interfa
pub rns_interface::traits::InterfaceHandle::mtu: u32
pub rns_interface::traits::InterfaceHandle::name: alloc::string::String
pub rns_interface::traits::InterfaceHandle::online: alloc::sync::Arc<core::sync::atomic::AtomicBool>
pub rns_interface::traits::InterfaceHandle::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_interface::traits::InterfaceHandle::packet_capacity: rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_interface::traits::InterfaceHandle::parent_id: core::option::Option<rns_interface::traits::InterfaceId>
pub rns_interface::traits::InterfaceHandle::read_task: tokio::runtime::task::join::JoinHandle<()>
pub rns_interface::traits::InterfaceHandle::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub rns_interface::traits::InterfaceHandle::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
pub rns_interface::traits::InterfaceHandle::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub struct rns_interface::traits::TunnelIdentity(pub alloc::sync::Arc<rns_identity::identity::Identity>)
impl rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>
impl core::fmt::Debug for rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::traits::AR_FREQ_DECAY: f64
pub const rns_interface::traits::AR_MINFREQ_HZ: f64
pub const rns_interface::traits::DEFAULT_AR_GRACE: u32
+37 -12
View File
@@ -1,4 +1,27 @@
pub mod rns_link
pub mod rns_link::clock
pub struct rns_link::clock::ContinuousInstant(_)
impl rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::checked_add(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::checked_duration_since(self, Self) -> core::option::Option<core::time::Duration>
pub fn rns_link::clock::ContinuousInstant::checked_sub(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::duration_since(self, Self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::elapsed(self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::now() -> Self
pub fn rns_link::clock::ContinuousInstant::saturating_duration_since(self, Self) -> core::time::Duration
impl core::ops::arith::Add<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add(self, core::time::Duration) -> Self
impl core::ops::arith::AddAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add_assign(&mut self, core::time::Duration)
impl core::ops::arith::Sub for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = core::time::Duration
pub fn rns_link::clock::ContinuousInstant::sub(self, Self) -> core::time::Duration
impl core::ops::arith::Sub<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub(self, core::time::Duration) -> Self
impl core::ops::arith::SubAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub_assign(&mut self, core::time::Duration)
pub mod rns_link::constants
pub const rns_link::constants::ACCEPT_ALL: u8
pub const rns_link::constants::ACCEPT_APP: u8
@@ -49,6 +72,7 @@ pub enum rns_link::handshake::HandshakeError
pub rns_link::handshake::HandshakeError::InvalidLength(usize)
pub rns_link::handshake::HandshakeError::InvalidSignature
pub rns_link::handshake::HandshakeError::KeyDerivation(rns_link::key_derivation::LinkKeyError)
pub rns_link::handshake::HandshakeError::Signalling(rns_wire::link_signalling::LinkSignallingError)
pub rns_link::handshake::HandshakeError::TooShort
pub rns_link::handshake::HandshakeError::UnsupportedMode(u8)
pub struct rns_link::handshake::EphemeralKeys
@@ -64,20 +88,20 @@ impl zeroize::Zeroize for rns_link::handshake::EphemeralKeys
pub fn rns_link::handshake::EphemeralKeys::zeroize(&mut self)
pub struct rns_link::handshake::LinkProofData
pub rns_link::handshake::LinkProofData::responder_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData
pub rns_link::handshake::LinkProofData::signalling: rns_wire::link_signalling::SignallingData
pub rns_link::handshake::LinkProofData::signature: [u8; 64]
impl rns_link::handshake::LinkProofData
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::handshake::LinkProofData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkProofData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::LinkProofData::validate(&self, &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 16], &[u8; 32]) -> bool
pub struct rns_link::handshake::LinkRequestData
pub rns_link::handshake::LinkRequestData::peer_ed25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::peer_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData
pub rns_link::handshake::LinkRequestData::signalling: rns_wire::link_signalling::SignallingData
impl rns_link::handshake::LinkRequestData
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_wire::link_signalling::SignallingData) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkRequestData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::compute_link_id(&[u8; 16], &[u8]) -> [u8; 16]
pub fn rns_link::handshake::compute_link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
@@ -287,6 +311,7 @@ pub fn rns_link::link::Link::track_incoming_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_outgoing_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_phy_stats(&mut self, bool)
pub fn rns_link::link::Link::traffic_stats(&self) -> (u64, u64, u64, u64)
pub fn rns_link::link::Link::try_extend_establishment_timeout(&mut self, f64) -> core::result::Result<(), rns_link::link::TimeoutError>
pub fn rns_link::link::Link::untrack_resource(&mut self, &[u8; 32])
pub fn rns_link::link::Link::update_outgoing_resource_state(&mut self, usize, rns_link::link::OutboundResourceState)
pub fn rns_link::link::Link::update_pending_request_id(&mut self, &[u8; 16], [u8; 16]) -> bool
@@ -301,19 +326,19 @@ pub struct rns_link::link::LinkPhyStats
pub rns_link::link::LinkPhyStats::q: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::rssi: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::snr: core::option::Option<f64>
pub struct rns_link::link::TimeoutError
pub type rns_link::link::LinkCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ParsedRequestData = ([u8; 16], [u8; 16], f64, alloc::vec::Vec<u8>)
pub type rns_link::link::RemoteIdentifiedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ResourceCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync)>
pub mod rns_link::mtu_discovery
pub struct rns_link::mtu_discovery::SignallingData
pub rns_link::mtu_discovery::SignallingData::mode: u8
pub rns_link::mtu_discovery::SignallingData::mtu: u32
impl rns_link::mtu_discovery::SignallingData
pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self
pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]
pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
pub use rns_link::mtu_discovery::LinkMtu
pub use rns_link::mtu_discovery::LinkSignalling
pub use rns_link::mtu_discovery::LinkSignallingError
pub use rns_link::mtu_discovery::SignallingData
pub use rns_link::mtu_discovery::parse_proof_signalling
pub use rns_link::mtu_discovery::parse_request_signalling
pub mod rns_link::request
pub enum rns_link::request::RequestState
pub rns_link::request::RequestState::Delivered
+14
View File
@@ -129,6 +129,7 @@ pub const rns_protocol::channel::FAST_RATE_THRESHOLD: usize
pub const rns_protocol::channel::MAX_TRIES: usize
pub const rns_protocol::channel::MIN_TIMEOUT_BASE: f64
pub const rns_protocol::channel::RTT_FAST: f64
pub const rns_protocol::channel::RTT_MAX: f64
pub const rns_protocol::channel::RTT_MEDIUM: f64
pub const rns_protocol::channel::RTT_SLOW: f64
pub const rns_protocol::channel::SEQ_MAX: u16
@@ -206,6 +207,10 @@ pub enum rns_protocol::resource::CancelType
pub rns_protocol::resource::CancelType::Icl
pub rns_protocol::resource::CancelType::Rcl
pub enum rns_protocol::resource::ResourceError
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::context: rns_wire::context::PacketContext
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::encoded_len: usize
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::mtu: usize
pub rns_protocol::resource::ResourceError::Corrupt
pub rns_protocol::resource::ResourceError::DecompressionFailed
pub rns_protocol::resource::ResourceError::DecryptFailed
@@ -483,14 +488,23 @@ pub rns_protocol::resource_adv::ResourceAdvertisement::segment_index: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::total_segments: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::transfer_size: usize
impl rns_protocol::resource_adv::ResourceAdvertisement
pub fn rns_protocol::resource_adv::ResourceAdvertisement::encoded_len(&self) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::get_map_hashes(&self) -> alloc::vec::Vec<[u8; 4]>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::new(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize) -> Self
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack_into<W: core::io::write::Write>(&self, W) -> core::result::Result<(), rmp_serde::encode::Error>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::unpack(&[u8]) -> core::result::Result<Self, alloc::string::String>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::with_metadata_size(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize, usize) -> Self
pub const rns_protocol::resource_adv::OVERHEAD: usize
pub fn rns_protocol::resource_adv::collision_guard_size(usize) -> usize
pub fn rns_protocol::resource_adv::hashmap_max_len(usize) -> usize
pub mod rns_protocol::resource_control
pub const rns_protocol::resource_control::HASHMAP_STRIDE: usize
pub fn rns_protocol::resource_control::check_advertisement(&rns_protocol::resource_adv::ResourceAdvertisement, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::check_control_frame(rns_wire::context::PacketContext, usize, bool, usize, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::encode_hashmap_update(&[u8; 32], usize, &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_control::encrypted_len(usize) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::preflight_outbound(usize, core::option::Option<usize>, core::option::Option<&[u8]>, bool, bool, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub mod rns_protocol::rnsh
pub enum rns_protocol::rnsh::RnshCodecError
pub rns_protocol::rnsh::RnshCodecError::Decode(alloc::string::String)
+135 -53
View File
@@ -38,6 +38,57 @@ pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::poll_write(core::pin
pub const rns_runtime::buffer_stream::DEFAULT_CLOSE_TIMEOUT: core::time::Duration
pub const rns_runtime::buffer_stream::DEFAULT_READER_CAPACITY: usize
pub mod rns_runtime::config
pub mod rns_runtime::config::ifac
pub enum rns_runtime::config::ifac::IfacConfigError
pub rns_runtime::config::ifac::IfacConfigError::IfacUnitsRequired
pub rns_runtime::config::ifac::IfacConfigError::Invalid
pub rns_runtime::config::ifac::IfacConfigError::Invalid::field: &'static str
pub rns_runtime::config::ifac::IfacConfigError::Invalid::reason: &'static str
pub enum rns_runtime::config::ifac::IfacMigrationError
pub rns_runtime::config::ifac::IfacMigrationError::EmptySelection
pub rns_runtime::config::ifac::IfacMigrationError::Invalid
pub rns_runtime::config::ifac::IfacMigrationError::Invalid::error: rns_runtime::config::ifac::IfacConfigError
pub rns_runtime::config::ifac::IfacMigrationError::Invalid::interface: alloc::string::String
pub rns_runtime::config::ifac::IfacMigrationError::NotFound(alloc::string::String)
pub rns_runtime::config::ifac::IfacMigrationError::SourceMismatch
pub rns_runtime::config::ifac::IfacMigrationError::Syntax(rns_runtime::config::ConfigError)
pub enum rns_runtime::config::ifac::IfacSourceUnits
pub rns_runtime::config::ifac::IfacSourceUnits::Bits
pub rns_runtime::config::ifac::IfacSourceUnits::Bytes
pub struct rns_runtime::config::ifac::IfacMigrationPlan
impl rns_runtime::config::ifac::IfacMigrationPlan
pub fn rns_runtime::config::ifac::IfacMigrationPlan::changes(&self) -> &[rns_runtime::config::ifac::IfacUnitChange]
pub fn rns_runtime::config::ifac::IfacMigrationPlan::is_unchanged(&self) -> bool
pub fn rns_runtime::config::ifac::IfacMigrationPlan::proposed_config(&self) -> &str
pub fn rns_runtime::config::ifac::IfacMigrationPlan::source_hash(&self) -> [u8; 32]
pub fn rns_runtime::config::ifac::IfacMigrationPlan::source_matches(&self, &str) -> bool
impl core::fmt::Debug for rns_runtime::config::ifac::IfacMigrationPlan
pub fn rns_runtime::config::ifac::IfacMigrationPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::config::ifac::IfacUnitChange
pub rns_runtime::config::ifac::IfacUnitChange::effective_bytes: usize
pub rns_runtime::config::ifac::IfacUnitChange::interface: alloc::string::String
pub rns_runtime::config::ifac::IfacUnitChange::previous_value: usize
pub struct rns_runtime::config::ifac::PropertySpan
pub rns_runtime::config::ifac::PropertySpan::key: alloc::string::String
pub rns_runtime::config::ifac::PropertySpan::path: alloc::vec::Vec<alloc::string::String>
pub rns_runtime::config::ifac::PropertySpan::range: core::ops::range::Range<usize>
pub rns_runtime::config::ifac::PropertySpan::section: alloc::string::String
pub struct rns_runtime::config::ifac::SectionSpan
pub rns_runtime::config::ifac::SectionSpan::header_end: usize
pub rns_runtime::config::ifac::SectionSpan::path: alloc::vec::Vec<alloc::string::String>
pub rns_runtime::config::ifac::SectionSpan::range: core::ops::range::Range<usize>
pub rns_runtime::config::ifac::SectionSpan::section: alloc::string::String
pub const rns_runtime::config::ifac::SIZE_KEYS: &[&str]
pub fn rns_runtime::config::ifac::migration_candidates(&rns_runtime::config::Config) -> alloc::vec::Vec<rns_runtime::config::ifac::IfacUnitChange>
pub fn rns_runtime::config::ifac::parse_ifac_size(&rns_runtime::config::ConfigSection) -> core::result::Result<core::option::Option<usize>, rns_runtime::config::ifac::IfacConfigError>
pub fn rns_runtime::config::ifac::plan_ifac_unit_migration(&str, &[alloc::string::String], rns_runtime::config::ifac::IfacSourceUnits) -> core::result::Result<rns_runtime::config::ifac::IfacMigrationPlan, rns_runtime::config::ifac::IfacMigrationError>
pub fn rns_runtime::config::ifac::property_spans(&str) -> core::result::Result<alloc::vec::Vec<rns_runtime::config::ifac::PropertySpan>, rns_runtime::config::ConfigError>
pub fn rns_runtime::config::ifac::section_spans(&str) -> core::result::Result<alloc::vec::Vec<rns_runtime::config::ifac::SectionSpan>, rns_runtime::config::ConfigError>
pub fn rns_runtime::config::ifac::validate_ifac_update(core::option::Option<&str>, &str) -> core::result::Result<(), rns_runtime::config::ifac::IfacMigrationError>
pub mod rns_runtime::config::ifac_lock
pub struct rns_runtime::config::ifac_lock::ConfigWriteLock
impl rns_runtime::config::ifac_lock::ConfigWriteLock
pub fn rns_runtime::config::ifac_lock::ConfigWriteLock::acquire(&std::path::Path) -> core::io::error::Result<Self>
pub enum rns_runtime::config::ConfigError
pub rns_runtime::config::ConfigError::InvalidValue
pub rns_runtime::config::ConfigError::InvalidValue::key: alloc::string::String
@@ -78,6 +129,9 @@ pub fn rns_runtime::config::ConfigSection::get_int(&self, &str) -> core::option:
pub fn rns_runtime::config::ConfigSection::get_list(&self, &str) -> core::option::Option<alloc::vec::Vec<alloc::string::String>>
pub fn rns_runtime::config::ConfigSection::get_uint(&self, &str) -> core::option::Option<u64>
pub fn rns_runtime::config::ConfigSection::has(&self, &str) -> bool
pub fn rns_runtime::config::ConfigSection::has_enable_key(&self) -> bool
pub fn rns_runtime::config::ConfigSection::interface_enabled(&self) -> bool
pub fn rns_runtime::config::ConfigSection::invalid_enable_key(&self) -> core::option::Option<&'static str>
pub fn rns_runtime::config::ConfigSection::new() -> Self
pub fn rns_runtime::config::ConfigSection::set(&mut self, &str, &str)
pub fn rns_runtime::config::ConfigSection::set_list(&mut self, &str, alloc::vec::Vec<alloc::string::String>)
@@ -118,6 +172,7 @@ pub rns_runtime::destination_runtime::DestinationRuntimeError::Destination(rns_i
pub rns_runtime::destination_runtime::DestinationRuntimeError::InvalidEventCapacity
pub rns_runtime::destination_runtime::DestinationRuntimeError::LinkSend(rns_runtime::link_manager::LinkSendError)
pub rns_runtime::destination_runtime::DestinationRuntimeError::ManagerUnavailable
pub rns_runtime::destination_runtime::DestinationRuntimeError::OrdinaryPacketConfiguration(rns_runtime::link_manager::LinkPacketConfigurationError)
pub struct rns_runtime::destination_runtime::DestinationEvents
pub rns_runtime::destination_runtime::DestinationEvents::channel_messages: tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkChannelMessage>
pub rns_runtime::destination_runtime::DestinationEvents::link_packet_proofs: tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkPacketProof>
@@ -278,14 +333,14 @@ pub rns_runtime::interface_factory::InterfacePostInit::announces_from_internal:
pub rns_runtime::interface_factory::InterfacePostInit::bitrate: core::option::Option<u64>
pub rns_runtime::interface_factory::InterfacePostInit::default_ifac_size: usize
pub rns_runtime::interface_factory::InterfacePostInit::ifac_network_name: core::option::Option<alloc::string::String>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<alloc::string::String>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<zeroize::Zeroizing<alloc::string::String>>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_size: core::option::Option<usize>
pub rns_runtime::interface_factory::InterfacePostInit::ingress_control: bool
pub rns_runtime::interface_factory::InterfacePostInit::ingress_overrides: rns_transport::ingress::IngressOverrides
pub rns_runtime::interface_factory::InterfacePostInit::outgoing: bool
pub rns_runtime::interface_factory::InterfacePostInit::recursive_prs: bool
impl rns_runtime::interface_factory::InterfacePostInit
pub fn rns_runtime::interface_factory::InterfacePostInit::from_section(&rns_runtime::config::ConfigSection) -> Self
pub fn rns_runtime::interface_factory::InterfacePostInit::try_from_section(&rns_runtime::config::ConfigSection) -> core::result::Result<Self, rns_runtime::interface_factory::InterfaceFactoryError>
pub fn rns_runtime::interface_factory::InterfacePostInit::with_default_ifac_size(self, usize) -> Self
pub struct rns_runtime::interface_factory::KissSerialConfig
pub rns_runtime::interface_factory::KissSerialConfig::baud_rate: u32
@@ -362,6 +417,7 @@ pub rns_runtime::interface_factory::SerialInterfaceConfig::port: alloc::string::
pub rns_runtime::interface_factory::SerialInterfaceConfig::stop_bits: u8
pub fn rns_runtime::interface_factory::default_ifac_size_for(&rns_runtime::interface_factory::InterfaceConfig) -> usize
pub fn rns_runtime::interface_factory::synthesize_interface(&str, &rns_runtime::config::ConfigSection) -> core::result::Result<rns_runtime::interface_factory::InterfaceConfig, rns_runtime::interface_factory::InterfaceFactoryError>
pub fn rns_runtime::interface_factory::validate_config_capacity(&rns_runtime::interface_factory::InterfaceConfig, &rns_runtime::interface_factory::InterfacePostInit) -> core::result::Result<(), rns_runtime::interface_factory::InterfaceFactoryError>
pub mod rns_runtime::jobs
pub enum rns_runtime::jobs::Job
pub rns_runtime::jobs::Job::CleanCache
@@ -397,6 +453,7 @@ pub rns_runtime::link_client::LinkClientError::LinkCrypto(alloc::string::String)
pub rns_runtime::link_client::LinkClientError::NoSigningKey
pub rns_runtime::link_client::LinkClientError::ProofInvalid(alloc::string::String)
pub rns_runtime::link_client::LinkClientError::PubkeyNotDiscovered
pub rns_runtime::link_client::LinkClientError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::link_client::LinkClientError::Timeout(&'static str)
pub rns_runtime::link_client::LinkClientError::TransportUnavailable
pub rns_runtime::link_client::LinkClientError::UnexpectedResponse(alloc::string::String)
@@ -411,6 +468,15 @@ pub rns_runtime::link_manager::ChannelSendError::LinkNotActive
pub rns_runtime::link_manager::ChannelSendError::LinkNotFound
pub rns_runtime::link_manager::ChannelSendError::NoSessionKeys
pub rns_runtime::link_manager::ChannelSendError::TransportUnavailable
pub enum rns_runtime::link_manager::DeferredResponseError
pub rns_runtime::link_manager::DeferredResponseError::Closed
pub rns_runtime::link_manager::DeferredResponseError::TooLarge
pub enum rns_runtime::link_manager::DeferredResponseOutcome
pub rns_runtime::link_manager::DeferredResponseOutcome::Closed
pub rns_runtime::link_manager::DeferredResponseOutcome::Dropped
pub rns_runtime::link_manager::DeferredResponseOutcome::Expired
pub rns_runtime::link_manager::DeferredResponseOutcome::Sent
pub rns_runtime::link_manager::DeferredResponseOutcome::Unavailable
pub enum rns_runtime::link_manager::DestinationControlError
pub rns_runtime::link_manager::DestinationControlError::Destination(rns_identity::destination::DestinationError)
pub rns_runtime::link_manager::DestinationControlError::DestinationUnavailable
@@ -486,6 +552,18 @@ pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData
pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData::result_tx: core::option::Option<tokio::sync::oneshot::Sender<core::result::Result<(), rns_runtime::link_manager::DestinationControlError>>>
pub rns_runtime::link_manager::LinkManagerCommand::Shutdown
pub enum rns_runtime::link_manager::LinkPacketConfigurationError
pub rns_runtime::link_manager::LinkPacketConfigurationError::ExactDispatchRequired
pub rns_runtime::link_manager::LinkPacketConfigurationError::LegacyChannel
pub rns_runtime::link_manager::LinkPacketConfigurationError::TypedChannelRequired
pub enum rns_runtime::link_manager::LinkPacketReceiptOutcome
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Closed
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Dropped
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Expired
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Sent
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Unavailable
pub enum rns_runtime::link_manager::LinkPacketRejection
pub rns_runtime::link_manager::LinkPacketRejection::InvalidPropagationStamp
pub enum rns_runtime::link_manager::LinkPayloadSendReceipt
pub rns_runtime::link_manager::LinkPayloadSendReceipt::Packet(rns_runtime::link_manager::LinkPacketSendReceipt)
pub rns_runtime::link_manager::LinkPayloadSendReceipt::Resource(rns_runtime::link_manager::LinkResourceSendReceipt)
@@ -535,6 +613,13 @@ pub struct rns_runtime::link_manager::ChannelSendReceipt
pub rns_runtime::link_manager::ChannelSendReceipt::link_id: [u8; 16]
pub rns_runtime::link_manager::ChannelSendReceipt::packet_hash: [u8; 32]
pub rns_runtime::link_manager::ChannelSendReceipt::sequence: u16
pub struct rns_runtime::link_manager::DeferredRequestResponder
impl rns_runtime::link_manager::DeferredRequestResponder
pub fn rns_runtime::link_manager::DeferredRequestResponder::is_cancelled(&self) -> bool
pub fn rns_runtime::link_manager::DeferredRequestResponder::respond(self, rns_runtime::link_manager::RequestOutcome) -> core::result::Result<tokio::sync::oneshot::Receiver<rns_runtime::link_manager::DeferredResponseOutcome>, rns_runtime::link_manager::DeferredResponseError>
pub fn rns_runtime::link_manager::DeferredRequestResponder::response_byte_limit(&self) -> usize
impl core::ops::drop::Drop for rns_runtime::link_manager::DeferredRequestResponder
pub fn rns_runtime::link_manager::DeferredRequestResponder::drop(&mut self)
pub struct rns_runtime::link_manager::DestinationAnnounceOptions
pub rns_runtime::link_manager::DestinationAnnounceOptions::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::link_manager::DestinationAnnounceOptions::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
@@ -551,6 +636,14 @@ pub rns_runtime::link_manager::DestinationRequest::path: alloc::string::String
pub rns_runtime::link_manager::DestinationRequest::remote_identity: core::option::Option<rns_identity::identity::Identity>
pub rns_runtime::link_manager::DestinationRequest::request_id: [u8; 16]
pub rns_runtime::link_manager::DestinationRequest::requested_at: f64
pub struct rns_runtime::link_manager::InboundLinkPacket
impl rns_runtime::link_manager::InboundLinkPacket
pub fn rns_runtime::link_manager::InboundLinkPacket::destination_hash(&self) -> [u8; 16]
pub fn rns_runtime::link_manager::InboundLinkPacket::into_parts(self) -> (bytes::bytes::Bytes, core::option::Option<rns_runtime::link_manager::LinkPacketReceipt>)
pub fn rns_runtime::link_manager::InboundLinkPacket::link_id(&self) -> [u8; 16]
pub fn rns_runtime::link_manager::InboundLinkPacket::packet_hash(&self) -> [u8; 32]
pub fn rns_runtime::link_manager::InboundLinkPacket::payload(&self) -> &bytes::bytes::Bytes
pub fn rns_runtime::link_manager::InboundLinkPacket::role(&self) -> rns_link::link::LinkRole
pub struct rns_runtime::link_manager::LinkChannelMessage
pub rns_runtime::link_manager::LinkChannelMessage::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkChannelMessage::msg_type: u16
@@ -574,8 +667,11 @@ pub fn rns_runtime::link_manager::LinkManager::get_link_mut(&mut self, &[u8; 16]
pub fn rns_runtime::link_manager::LinkManager::link_identities_handle(&self) -> alloc::sync::Arc<std::sync::poison::mutex::Mutex<std::collections::hash::map::HashMap<[u8; 16], [u8; 16]>>>
pub fn rns_runtime::link_manager::LinkManager::link_interface(&self, &[u8; 16]) -> core::option::Option<rns_transport::messages::InterfaceId>
pub fn rns_runtime::link_manager::LinkManager::new(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Receiver<rns_transport::link_messages::DestinationEvent>, [u8; 16], core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>) -> Self
pub fn rns_runtime::link_manager::LinkManager::ordinary_packet_overload_count(&self) -> u64
pub fn rns_runtime::link_manager::LinkManager::ordinary_packet_proof_strategy(&self) -> rns_identity::destination::ProofStrategy
pub fn rns_runtime::link_manager::LinkManager::process_destination_packet(&self, &[u8], &rns_identity::identity::Identity) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_runtime::link_manager::LinkManager::register_channel_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
pub fn rns_runtime::link_manager::LinkManager::register_deferred_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, usize, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest, rns_runtime::link_manager::DeferredRequestResponder) + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::register_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static
pub async fn rns_runtime::link_manager::LinkManager::run(self)
pub async fn rns_runtime::link_manager::LinkManager::run_with_commands(self, tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkManagerCommand>)
@@ -589,14 +685,16 @@ pub fn rns_runtime::link_manager::LinkManager::set_accounting_event_channel(&mut
pub fn rns_runtime::link_manager::LinkManager::set_announce_handler<F>(&mut self, F) where F: core::ops::function::FnMut() + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_channel_message_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkChannelMessage>)
pub fn rns_runtime::link_manager::LinkManager::set_destination_delivery_proof_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<rns_runtime::link_manager::DestinationDeliveryProof>)
pub fn rns_runtime::link_manager::LinkManager::set_inbound_link_packet_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::InboundLinkPacket>) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_inbound_raw_channel(&mut self, tokio::sync::mpsc::bounded::Sender<alloc::vec::Vec<u8>>)
pub fn rns_runtime::link_manager::LinkManager::set_link_closed_channel(&mut self, tokio::sync::mpsc::bounded::Sender<[u8; 16]>)
pub fn rns_runtime::link_manager::LinkManager::set_link_endpoint_dispatch_handle(&mut self, rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle)
pub fn rns_runtime::link_manager::LinkManager::set_link_established_channel(&mut self, tokio::sync::mpsc::bounded::Sender<[u8; 16]>)
pub fn rns_runtime::link_manager::LinkManager::set_link_identified_channel(&mut self, tokio::sync::mpsc::bounded::Sender<([u8; 16], [u8; 16])>)
pub fn rns_runtime::link_manager::LinkManager::set_link_identity_gate<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16]) -> bool + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_proof_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkPacketProof>)
pub fn rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy(&mut self, rns_identity::destination::ProofStrategy) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_outbound_resource_proof_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkResourceProof>)
pub fn rns_runtime::link_manager::LinkManager::set_request_handler<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16], alloc::vec::Vec<u8>) -> core::option::Option<alloc::vec::Vec<u8>> + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_request_handler_ex<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16], alloc::vec::Vec<u8>) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static
@@ -616,6 +714,14 @@ pub fn rns_runtime::link_manager::LinkManager::with_destination(tokio::sync::mps
pub struct rns_runtime::link_manager::LinkPacketProof
pub rns_runtime::link_manager::LinkPacketProof::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkPacketProof::packet_hash: [u8; 32]
pub struct rns_runtime::link_manager::LinkPacketReceipt
impl rns_runtime::link_manager::LinkPacketReceipt
pub fn rns_runtime::link_manager::LinkPacketReceipt::accept(self) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
pub fn rns_runtime::link_manager::LinkPacketReceipt::close_without_proof(self) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
pub fn rns_runtime::link_manager::LinkPacketReceipt::drop_without_proof(self)
pub fn rns_runtime::link_manager::LinkPacketReceipt::reject_and_close(self, rns_runtime::link_manager::LinkPacketRejection) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
impl core::ops::drop::Drop for rns_runtime::link_manager::LinkPacketReceipt
pub fn rns_runtime::link_manager::LinkPacketReceipt::drop(&mut self)
pub struct rns_runtime::link_manager::LinkPacketSendReceipt
pub rns_runtime::link_manager::LinkPacketSendReceipt::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkPacketSendReceipt::packet_hash: [u8; 32]
@@ -657,6 +763,7 @@ pub rns_runtime::link_session::LinkSessionError::PayloadTooLarge::actual: usize
pub rns_runtime::link_session::LinkSessionError::PayloadTooLarge::max: usize
pub rns_runtime::link_session::LinkSessionError::ProofInvalid(alloc::string::String)
pub rns_runtime::link_session::LinkSessionError::PublicKeyUnavailable
pub rns_runtime::link_session::LinkSessionError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource::actual: usize
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource::max: usize
@@ -697,6 +804,7 @@ pub rns_runtime::link_session::LinkSessionResourceDirection::Inbound
pub rns_runtime::link_session::LinkSessionResourceDirection::Outbound
pub enum rns_runtime::link_session::LinkSessionResourceError
pub rns_runtime::link_session::LinkSessionResourceError::Cancelled
pub rns_runtime::link_session::LinkSessionResourceError::Control(rns_protocol::resource::ResourceError)
pub rns_runtime::link_session::LinkSessionResourceError::Failed(alloc::string::String)
pub rns_runtime::link_session::LinkSessionResourceError::InvalidAdvertisement(alloc::string::String)
pub rns_runtime::link_session::LinkSessionResourceError::LinkCrypto
@@ -860,6 +968,7 @@ pub use rns_runtime::prelude::RNodeConfigurationState
pub use rns_runtime::prelude::RNodeDetectionState
pub use rns_runtime::prelude::RNodeFirmwareCompatibility
pub use rns_runtime::prelude::RNodeObservedRadioState
pub use rns_runtime::prelude::RNodePortFailureClass
pub use rns_runtime::prelude::RNodeRuntimePhase
pub use rns_runtime::prelude::RNodeRuntimeReason
pub use rns_runtime::prelude::RNodeRuntimeSnapshot
@@ -890,6 +999,7 @@ pub rns_runtime::prelude::DestinationRuntimeError::Destination(rns_identity::des
pub rns_runtime::prelude::DestinationRuntimeError::InvalidEventCapacity
pub rns_runtime::prelude::DestinationRuntimeError::LinkSend(rns_runtime::link_manager::LinkSendError)
pub rns_runtime::prelude::DestinationRuntimeError::ManagerUnavailable
pub rns_runtime::prelude::DestinationRuntimeError::OrdinaryPacketConfiguration(rns_runtime::link_manager::LinkPacketConfigurationError)
pub enum rns_runtime::prelude::LinkConnectError
pub rns_runtime::prelude::LinkConnectError::Control(rns_runtime::reticulum::ControlError)
pub rns_runtime::prelude::LinkConnectError::IdentityUnavailable(alloc::string::String)
@@ -916,6 +1026,7 @@ pub rns_runtime::prelude::LinkSessionError::PayloadTooLarge::actual: usize
pub rns_runtime::prelude::LinkSessionError::PayloadTooLarge::max: usize
pub rns_runtime::prelude::LinkSessionError::ProofInvalid(alloc::string::String)
pub rns_runtime::prelude::LinkSessionError::PublicKeyUnavailable
pub rns_runtime::prelude::LinkSessionError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource::actual: usize
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource::max: usize
@@ -953,6 +1064,7 @@ pub rns_runtime::prelude::LinkSessionEvent::ResourceStarted::total_segments: usi
pub rns_runtime::prelude::LinkSessionEvent::Stale
pub enum rns_runtime::prelude::LinkSessionResourceError
pub rns_runtime::prelude::LinkSessionResourceError::Cancelled
pub rns_runtime::prelude::LinkSessionResourceError::Control(rns_protocol::resource::ResourceError)
pub rns_runtime::prelude::LinkSessionResourceError::Failed(alloc::string::String)
pub rns_runtime::prelude::LinkSessionResourceError::InvalidAdvertisement(alloc::string::String)
pub rns_runtime::prelude::LinkSessionResourceError::LinkCrypto
@@ -1322,6 +1434,7 @@ pub enum rns_runtime::probe::ProbeError
pub rns_runtime::probe::ProbeError::EncryptError(alloc::string::String)
pub rns_runtime::probe::ProbeError::Internal(alloc::string::String)
pub rns_runtime::probe::ProbeError::InvalidName
pub rns_runtime::probe::ProbeError::InvalidTimeout
pub rns_runtime::probe::ProbeError::MtuExceeded(usize, usize)
pub rns_runtime::probe::ProbeError::NoIdentity
pub rns_runtime::probe::ProbeError::PacketTimeout
@@ -1333,61 +1446,13 @@ pub rns_runtime::probe::ProbeOutcome::hops: u8
pub rns_runtime::probe::ProbeOutcome::interface: core::option::Option<alloc::string::String>
pub rns_runtime::probe::ProbeOutcome::rtt: core::time::Duration
pub rns_runtime::probe::ProbeOutcome::via: core::option::Option<[u8; 16]>
pub fn rns_runtime::probe::checked_probe_timeout(f64) -> core::result::Result<core::time::Duration, rns_runtime::probe::ProbeError>
pub fn rns_runtime::probe::default_probe_app_name() -> &'static str
pub fn rns_runtime::probe::parse_dest_hash(&str) -> core::result::Result<[u8; 16], rns_runtime::probe::ProbeError>
pub async fn rns_runtime::probe::probe_once(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, [u8; 16], &str, usize, core::option::Option<core::time::Duration>, core::option::Option<core::time::Duration>, bool) -> core::result::Result<rns_runtime::probe::ProbeOutcome, rns_runtime::probe::ProbeError>
pub async fn rns_runtime::probe::spawn_probe_responder(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, rns_identity::identity::Identity, &str) -> core::result::Result<[u8; 16], rns_runtime::probe::ProbeError>
pub mod rns_runtime::remote_management
pub async fn rns_runtime::remote_management::start_remote_management(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &rns_identity::identity::Identity, alloc::vec::Vec<[u8; 16]>) -> core::result::Result<[u8; 16], alloc::string::String>
pub mod rns_runtime::remote_management_schema
pub struct rns_runtime::remote_management_schema::InterfaceStats
pub rns_runtime::remote_management_schema::InterfaceStats::announce_queue: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::bitrate: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::blocked_ips: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::burst_activated: f64
pub rns_runtime::remote_management_schema::InterfaceStats::burst_active: bool
pub rns_runtime::remote_management_schema::InterfaceStats::clients: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::hash: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::InterfaceStats::held_announces: u64
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_netname: core::option::Option<alloc::string::String>
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_size: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::incoming_announce_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::incoming_pr_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::mode: u8
pub rns_runtime::remote_management_schema::InterfaceStats::name: alloc::string::String
pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_announce_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_pr_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_activated: f64
pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_active: bool
pub rns_runtime::remote_management_schema::InterfaceStats::rxb: u64
pub rns_runtime::remote_management_schema::InterfaceStats::rxs: u64
pub rns_runtime::remote_management_schema::InterfaceStats::short_name: alloc::string::String
pub rns_runtime::remote_management_schema::InterfaceStats::status: bool
pub rns_runtime::remote_management_schema::InterfaceStats::txb: u64
pub rns_runtime::remote_management_schema::InterfaceStats::txs: u64
pub rns_runtime::remote_management_schema::InterfaceStats::type_: alloc::string::String
pub struct rns_runtime::remote_management_schema::PathEntry
pub rns_runtime::remote_management_schema::PathEntry::expires: f64
pub rns_runtime::remote_management_schema::PathEntry::hash: alloc::vec::Vec<u8>
pub rns_runtime::remote_management_schema::PathEntry::hops: u8
pub rns_runtime::remote_management_schema::PathEntry::interface: alloc::string::String
pub rns_runtime::remote_management_schema::PathEntry::timestamp: f64
pub rns_runtime::remote_management_schema::PathEntry::via: core::option::Option<alloc::vec::Vec<u8>>
pub struct rns_runtime::remote_management_schema::RateEntry
pub rns_runtime::remote_management_schema::RateEntry::hash: alloc::vec::Vec<u8>
pub rns_runtime::remote_management_schema::RateEntry::rate: f64
pub struct rns_runtime::remote_management_schema::TransportStats
pub rns_runtime::remote_management_schema::TransportStats::interfaces: alloc::vec::Vec<rns_runtime::remote_management_schema::InterfaceStats>
pub rns_runtime::remote_management_schema::TransportStats::network_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::probe_responder: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::rss: core::option::Option<u64>
pub rns_runtime::remote_management_schema::TransportStats::rxb: u64
pub rns_runtime::remote_management_schema::TransportStats::rxs: u64
pub rns_runtime::remote_management_schema::TransportStats::transport_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::transport_uptime: core::option::Option<f64>
pub rns_runtime::remote_management_schema::TransportStats::txb: u64
pub rns_runtime::remote_management_schema::TransportStats::txs: u64
pub mod rns_runtime::resource_source
pub enum rns_runtime::resource_source::ResourceSourceError
pub rns_runtime::resource_source::ResourceSourceError::Io(core::io::error::Error)
@@ -1567,6 +1632,7 @@ impl core::fmt::Debug for rns_runtime::reticulum::RecalledDestination
pub fn rns_runtime::reticulum::RecalledDestination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::reticulum::ReticulumConfig
pub rns_runtime::reticulum::ReticulumConfig::autoconnect_discovered_interfaces: usize
pub rns_runtime::reticulum::ReticulumConfig::autoconnect_unverified_implementations: bool
pub rns_runtime::reticulum::ReticulumConfig::blackhole_sources: alloc::vec::Vec<[u8; 16]>
pub rns_runtime::reticulum::ReticulumConfig::blackhole_update_interval: f64
pub rns_runtime::reticulum::ReticulumConfig::bootstrap_configs: alloc::vec::Vec<std::path::PathBuf>
@@ -1682,6 +1748,8 @@ pub struct rns_runtime::reticulum::RuntimeInterfaceIfacConfig
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::ifac_size: core::option::Option<usize>
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::network_name: core::option::Option<alloc::string::String>
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::passphrase: core::option::Option<alloc::string::String>
impl core::fmt::Debug for rns_runtime::reticulum::RuntimeInterfaceIfacConfig
pub fn rns_runtime::reticulum::RuntimeInterfaceIfacConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::reticulum::SendOptions
pub rns_runtime::reticulum::SendOptions::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_runtime::reticulum::SendOptions::create_receipt: bool
@@ -1743,6 +1811,7 @@ pub rns_runtime::rncp::RncpError::NoIdentity
pub rns_runtime::rncp::RncpError::NoSigningKey
pub rns_runtime::rncp::RncpError::PathTimeout
pub rns_runtime::rncp::RncpError::ProofInvalid(alloc::string::String)
pub rns_runtime::rncp::RncpError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::rncp::RncpError::ResourceCreate(alloc::string::String)
pub rns_runtime::rncp::RncpError::ResourceFailed(alloc::string::String)
pub rns_runtime::rncp::RncpError::Timeout(&'static str)
@@ -1840,6 +1909,7 @@ pub rns_runtime::rnsh::RnshError::PathTimeout
pub rns_runtime::rnsh::RnshError::Process(alloc::string::String)
pub rns_runtime::rnsh::RnshError::ProofInvalid(alloc::string::String)
pub rns_runtime::rnsh::RnshError::Remote(alloc::string::String)
pub rns_runtime::rnsh::RnshError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::rnsh::RnshError::Timeout(&'static str)
pub rns_runtime::rnsh::RnshError::TransportUnavailable
impl core::convert::From<rns_protocol::channel::ChannelError> for rns_runtime::rnsh::RnshError
@@ -1961,6 +2031,9 @@ pub rns_runtime::rpc::InterfaceStatEntry::announce_queue: core::option::Option<u
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_grace: core::option::Option<u32>
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_penalty: core::option::Option<f64>
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_target: core::option::Option<f64>
pub rns_runtime::rpc::InterfaceStatEntry::announces_received: u64
pub rns_runtime::rpc::InterfaceStatEntry::announces_sent: u64
pub rns_runtime::rpc::InterfaceStatEntry::autoconnect_source: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::bitrate: u64
pub rns_runtime::rpc::InterfaceStatEntry::blocked_ips: core::option::Option<u64>
pub rns_runtime::rpc::InterfaceStatEntry::burst_activated: f64
@@ -1968,7 +2041,10 @@ pub rns_runtime::rpc::InterfaceStatEntry::burst_active: bool
pub rns_runtime::rpc::InterfaceStatEntry::clients: core::option::Option<u64>
pub rns_runtime::rpc::InterfaceStatEntry::held_announces: u64
pub rns_runtime::rpc::InterfaceStatEntry::id: u64
pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: usize
pub rns_runtime::rpc::InterfaceStatEntry::ifac_netname: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: core::option::Option<usize>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_violations: u64
pub rns_runtime::rpc::InterfaceStatEntry::incoming_announce_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::incoming_pr_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::mode: alloc::string::String
@@ -1977,12 +2053,18 @@ pub rns_runtime::rpc::InterfaceStatEntry::name: alloc::string::String
pub rns_runtime::rpc::InterfaceStatEntry::online: bool
pub rns_runtime::rpc::InterfaceStatEntry::outgoing_announce_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::outgoing_pr_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::packet_filter_hits: u64
pub rns_runtime::rpc::InterfaceStatEntry::parent_interface_name: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::path_requests_received: u64
pub rns_runtime::rpc::InterfaceStatEntry::path_requests_sent: u64
pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_activated: f64
pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_active: bool
pub rns_runtime::rpc::InterfaceStatEntry::protocol_violations: u64
pub rns_runtime::rpc::InterfaceStatEntry::role: alloc::string::String
pub rns_runtime::rpc::InterfaceStatEntry::rx_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::rx_rate: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_dropped_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_drops: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_rate: u64
pub struct rns_runtime::rpc::PathTableEntry
+251 -6
View File
@@ -55,7 +55,6 @@ pub rns_transport::actor::TransportActor::path_waiters: std::collections::hash::
pub rns_transport::actor::TransportActor::pending_discovery_prs: alloc::collections::vec_deque::VecDeque<rns_transport::actor::PendingDiscoveryPathRequest>
pub rns_transport::actor::TransportActor::pending_local_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::messages::InterfaceId>
pub rns_transport::actor::TransportActor::pending_path_entries: alloc::vec::Vec<rns_transport::persistence::PersistedPathEntry>
pub rns_transport::actor::TransportActor::pending_tunnel_entries: alloc::vec::Vec<rns_transport::persistence::PersistedTunnelEntry>
pub rns_transport::actor::TransportActor::rate_table: rns_transport::rate_limit::RateTable
pub rns_transport::actor::TransportActor::receipt_msg_ids: std::collections::hash::map::HashMap<[u8; 16], alloc::string::String>
pub rns_transport::actor::TransportActor::receipt_proof_txs: std::collections::hash::map::HashMap<[u8; 16], tokio::sync::mpsc::unbounded::UnboundedSender<rns_transport::link_messages::DestinationEvent>>
@@ -306,6 +305,7 @@ pub fn rns_transport::discovery::announcer::Announcer::is_empty(&self) -> bool
pub fn rns_transport::discovery::announcer::Announcer::len(&self) -> usize
pub fn rns_transport::discovery::announcer::Announcer::new(alloc::sync::Arc<dyn rns_transport::discovery::stamper::DiscoveryStamper>) -> Self
pub fn rns_transport::discovery::announcer::Announcer::prepare(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::PreparedAnnounce>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub fn rns_transport::discovery::announcer::Announcer::reconfigure(&mut self, rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::DiscoveryInterfaceConfig) -> bool
pub fn rns_transport::discovery::announcer::Announcer::register(&mut self, rns_transport::messages::InterfaceId, [u8; 16], rns_transport::discovery::announcer::DiscoveryInterfaceConfig)
pub fn rns_transport::discovery::announcer::Announcer::tick(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::AnnounceRequest>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub struct rns_transport::discovery::announcer::DiscoveryInterfaceConfig
@@ -360,6 +360,8 @@ pub rns_transport::discovery::app_data::DiscoveryInfo::frequency: core::option::
pub rns_transport::discovery::app_data::DiscoveryInfo::height: core::option::Option<f64>
pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netkey: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netname: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::impl_name: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::impl_version: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::interface_type: alloc::string::String
pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: core::option::Option<f64>
pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: core::option::Option<f64>
@@ -381,6 +383,8 @@ pub fn rns_transport::discovery::app_data::sanitize_name(&str) -> alloc::string:
pub fn rns_transport::discovery::app_data::split_flags(&[u8]) -> core::result::Result<(u8, &[u8]), rns_transport::discovery::app_data::AppDataError>
pub fn rns_transport::discovery::app_data::split_stamp(&[u8]) -> core::result::Result<(&[u8], &[u8]), rns_transport::discovery::app_data::AppDataError>
pub type rns_transport::discovery::app_data::DiscoveryEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::option::Option<alloc::vec::Vec<u8>> + 'a)
pub mod rns_transport::discovery::autoconnect
pub fn rns_transport::discovery::autoconnect::qualifies(&rns_transport::discovery::app_data::DiscoveryInfo, bool) -> bool
pub mod rns_transport::discovery::blackhole_manifest
pub enum rns_transport::discovery::blackhole_manifest::ManifestError
pub rns_transport::discovery::blackhole_manifest::ManifestError::BadField(&'static str)
@@ -432,9 +436,12 @@ pub const rns_transport::discovery::constants::key::REACHABLE_ON: u8
pub const rns_transport::discovery::constants::key::SPREADING_FACTOR: u8
pub const rns_transport::discovery::constants::key::TRANSPORT: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_ID: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_IMPL: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_VERS: u8
pub const rns_transport::discovery::constants::ANNOUNCE_JOB_INTERVAL_SECS: u64
pub const rns_transport::discovery::constants::APP_NAME: &str
pub const rns_transport::discovery::constants::AUTOCONNECT_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)]
pub const rns_transport::discovery::constants::BLACKHOLE_ASPECTS: &[&str]
pub const rns_transport::discovery::constants::BLACKHOLE_ASPECT_FILTER: &str
pub const rns_transport::discovery::constants::BLACKHOLE_INITIAL_WAIT_SECS: u64
@@ -444,10 +451,13 @@ pub const rns_transport::discovery::constants::BLACKHOLE_UPDATE_INTERVAL_SECS: u
pub const rns_transport::discovery::constants::DEFAULT_STAMP_VALUE: u8
pub const rns_transport::discovery::constants::DETACH_THRESHOLD_TICKS: u64
pub const rns_transport::discovery::constants::DISCOVERABLE_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::DISCOVERED_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::DISCOVERY_ASPECTS: &[&str]
pub const rns_transport::discovery::constants::DISCOVERY_ASPECT_FILTER: &str
pub const rns_transport::discovery::constants::FLAG_ENCRYPTED: u8
pub const rns_transport::discovery::constants::FLAG_SIGNED: u8
pub const rns_transport::discovery::constants::IMPLEMENTATION_NAME: &str
pub const rns_transport::discovery::constants::IMPLEMENTATION_VERSION: &str
pub const rns_transport::discovery::constants::MONITOR_INTERVAL_SECS: u64
pub const rns_transport::discovery::constants::STAMP_SIZE: usize
pub const rns_transport::discovery::constants::THRESHOLD_REMOVE_SECS: u64
@@ -472,11 +482,13 @@ pub const rns_transport::discovery::key::REACHABLE_ON: u8
pub const rns_transport::discovery::key::SPREADING_FACTOR: u8
pub const rns_transport::discovery::key::TRANSPORT: u8
pub const rns_transport::discovery::key::TRANSPORT_ID: u8
pub const rns_transport::discovery::key::TRANSPORT_IMPL: u8
pub const rns_transport::discovery::key::TRANSPORT_VERS: u8
pub mod rns_transport::discovery::receiver
pub enum rns_transport::discovery::receiver::Outcome
pub rns_transport::discovery::receiver::Outcome::Accepted
pub rns_transport::discovery::receiver::Outcome::Rejected(rns_transport::discovery::receiver::Reason)
pub enum rns_transport::discovery::receiver::Reason
#[non_exhaustive] pub enum rns_transport::discovery::receiver::Reason
pub rns_transport::discovery::receiver::Reason::DecodeFailed
pub rns_transport::discovery::receiver::Reason::DecryptFailed
pub rns_transport::discovery::receiver::Reason::EncryptedWithoutKey
@@ -485,6 +497,7 @@ pub rns_transport::discovery::receiver::Reason::MissingAppData
pub rns_transport::discovery::receiver::Reason::StampInvalid
pub rns_transport::discovery::receiver::Reason::StorageFailed
pub rns_transport::discovery::receiver::Reason::UnauthorizedSource
pub rns_transport::discovery::receiver::Reason::UnlistedType
pub rns_transport::discovery::receiver::Reason::ValidationBusy
pub struct rns_transport::discovery::receiver::ReceiverConfig
pub rns_transport::discovery::receiver::ReceiverConfig::decryptor: core::option::Option<alloc::sync::Arc<dyn rns_transport::discovery::receiver::DiscoveryDecryptor>>
@@ -575,7 +588,7 @@ pub rns_transport::discovery::ManifestError::NotAMap
pub enum rns_transport::discovery::Outcome
pub rns_transport::discovery::Outcome::Accepted
pub rns_transport::discovery::Outcome::Rejected(rns_transport::discovery::receiver::Reason)
pub enum rns_transport::discovery::Reason
#[non_exhaustive] pub enum rns_transport::discovery::Reason
pub rns_transport::discovery::Reason::DecodeFailed
pub rns_transport::discovery::Reason::DecryptFailed
pub rns_transport::discovery::Reason::EncryptedWithoutKey
@@ -584,6 +597,7 @@ pub rns_transport::discovery::Reason::MissingAppData
pub rns_transport::discovery::Reason::StampInvalid
pub rns_transport::discovery::Reason::StorageFailed
pub rns_transport::discovery::Reason::UnauthorizedSource
pub rns_transport::discovery::Reason::UnlistedType
pub rns_transport::discovery::Reason::ValidationBusy
pub enum rns_transport::discovery::SkipReason
pub rns_transport::discovery::SkipReason::EncryptionFailed
@@ -605,6 +619,7 @@ pub fn rns_transport::discovery::announcer::Announcer::is_empty(&self) -> bool
pub fn rns_transport::discovery::announcer::Announcer::len(&self) -> usize
pub fn rns_transport::discovery::announcer::Announcer::new(alloc::sync::Arc<dyn rns_transport::discovery::stamper::DiscoveryStamper>) -> Self
pub fn rns_transport::discovery::announcer::Announcer::prepare(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::PreparedAnnounce>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub fn rns_transport::discovery::announcer::Announcer::reconfigure(&mut self, rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::DiscoveryInterfaceConfig) -> bool
pub fn rns_transport::discovery::announcer::Announcer::register(&mut self, rns_transport::messages::InterfaceId, [u8; 16], rns_transport::discovery::announcer::DiscoveryInterfaceConfig)
pub fn rns_transport::discovery::announcer::Announcer::tick(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::AnnounceRequest>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub struct rns_transport::discovery::BlackholeManifestEntry
@@ -684,6 +699,7 @@ pub fn rns_transport::discovery::receiver::ReceiverConfig::process_event(&self,
pub const rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS: u64
pub const rns_transport::discovery::APP_NAME: &str
pub const rns_transport::discovery::AUTOCONNECT_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)]
pub const rns_transport::discovery::BLACKHOLE_ASPECTS: &[&str]
pub const rns_transport::discovery::BLACKHOLE_ASPECT_FILTER: &str
pub const rns_transport::discovery::BLACKHOLE_INITIAL_WAIT: core::time::Duration
@@ -697,10 +713,13 @@ pub const rns_transport::discovery::BLACKHOLE_UPDATE_INTERVAL_SECS: u64
pub const rns_transport::discovery::DEFAULT_STAMP_VALUE: u8
pub const rns_transport::discovery::DETACH_THRESHOLD_TICKS: u64
pub const rns_transport::discovery::DISCOVERABLE_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::DISCOVERED_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::DISCOVERY_ASPECTS: &[&str]
pub const rns_transport::discovery::DISCOVERY_ASPECT_FILTER: &str
pub const rns_transport::discovery::FLAG_ENCRYPTED: u8
pub const rns_transport::discovery::FLAG_SIGNED: u8
pub const rns_transport::discovery::IMPLEMENTATION_NAME: &str
pub const rns_transport::discovery::IMPLEMENTATION_VERSION: &str
pub const rns_transport::discovery::MONITOR_INTERVAL_SECS: u64
pub const rns_transport::discovery::STAMP_SIZE: usize
pub const rns_transport::discovery::THRESHOLD_REMOVE_SECS: u64
@@ -738,9 +757,15 @@ pub fn rns_transport::hashlist::PacketHashlist::new_with_capacity(usize) -> Self
impl core::default::Default for rns_transport::hashlist::PacketHashlist
pub fn rns_transport::hashlist::PacketHashlist::default() -> Self
pub mod rns_transport::ifac
pub enum rns_transport::ifac::IfacSignError
pub rns_transport::ifac::IfacSignError::InvalidTagSize
pub rns_transport::ifac::IfacSignError::PacketTooLarge
pub rns_transport::ifac::IfacSignError::ShortPacket
pub const rns_transport::ifac::MAX_IFAC_WIRE_BYTES: usize
pub fn rns_transport::ifac::has_ifac_flag(&[u8]) -> bool
pub fn rns_transport::ifac::ifac_sign(&[u8], &[u8; 64], usize) -> alloc::vec::Vec<u8>
pub fn rns_transport::ifac::ifac_verify(&[u8], &[u8; 64], usize) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_transport::ifac::try_ifac_sign(&[u8], &[u8; 64], usize) -> core::result::Result<alloc::vec::Vec<u8>, rns_transport::ifac::IfacSignError>
pub mod rns_transport::ingress
pub struct rns_transport::ingress::HeldAnnounce
pub rns_transport::ingress::HeldAnnounce::destination_hash: [u8; 16]
@@ -750,6 +775,8 @@ pub rns_transport::ingress::HeldAnnounce::receiving_interface_id: u64
pub struct rns_transport::ingress::IngressController
impl rns_transport::ingress::IngressController
pub fn rns_transport::ingress::IngressController::age(&self) -> f64
pub fn rns_transport::ingress::IngressController::announces_received(&self) -> u64
pub fn rns_transport::ingress::IngressController::announces_sent(&self) -> u64
pub fn rns_transport::ingress::IngressController::burst_activated(&self) -> std::time::Instant
pub fn rns_transport::ingress::IngressController::burst_freq(&self) -> f64
pub fn rns_transport::ingress::IngressController::burst_freq_new(&self) -> f64
@@ -768,6 +795,8 @@ pub fn rns_transport::ingress::IngressController::is_pr_burst_active(&self) -> b
pub fn rns_transport::ingress::IngressController::new() -> Self
pub fn rns_transport::ingress::IngressController::outgoing_announce_frequency(&self) -> f64
pub fn rns_transport::ingress::IngressController::outgoing_pr_frequency(&self) -> f64
pub fn rns_transport::ingress::IngressController::path_requests_received(&self) -> u64
pub fn rns_transport::ingress::IngressController::path_requests_sent(&self) -> u64
pub fn rns_transport::ingress::IngressController::pr_burst_activated(&self) -> std::time::Instant
pub fn rns_transport::ingress::IngressController::pr_burst_freq(&self) -> f64
pub fn rns_transport::ingress::IngressController::pr_burst_freq_new(&self) -> f64
@@ -779,9 +808,12 @@ pub fn rns_transport::ingress::IngressController::should_egress_limit_pr(&mut se
pub fn rns_transport::ingress::IngressController::should_ingress_limit(&mut self) -> bool
pub fn rns_transport::ingress::IngressController::should_ingress_limit_pr(&mut self) -> bool
pub fn rns_transport::ingress::IngressController::try_release_held(&mut self) -> core::option::Option<rns_transport::ingress::HeldAnnounce>
pub fn rns_transport::ingress::IngressController::try_with_overrides(&rns_transport::ingress::IngressOverrides) -> core::result::Result<Self, rns_transport::ingress::IngressOverrideError>
pub fn rns_transport::ingress::IngressController::with_overrides(&rns_transport::ingress::IngressOverrides) -> Self
impl core::default::Default for rns_transport::ingress::IngressController
pub fn rns_transport::ingress::IngressController::default() -> Self
pub struct rns_transport::ingress::IngressOverrideError
pub rns_transport::ingress::IngressOverrideError::field: &'static str
pub struct rns_transport::ingress::IngressOverrides
pub rns_transport::ingress::IngressOverrides::burst_freq: core::option::Option<f64>
pub rns_transport::ingress::IngressOverrides::burst_freq_new: core::option::Option<f64>
@@ -797,6 +829,60 @@ pub rns_transport::ingress::IngressOverrides::pr_burst_freq: core::option::Optio
pub rns_transport::ingress::IngressOverrides::pr_burst_freq_new: core::option::Option<f64>
impl rns_transport::ingress::IngressOverrides
pub fn rns_transport::ingress::IngressOverrides::is_empty(&self) -> bool
pub fn rns_transport::ingress::IngressOverrides::validate(&self) -> core::result::Result<(), rns_transport::ingress::IngressOverrideError>
pub mod rns_transport::interface_ownership
pub enum rns_transport::interface_ownership::InterfaceCapacityError
pub rns_transport::interface_ownership::InterfaceCapacityError::Empty
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::interface_ownership::InterfaceCapacityError::InvalidIfac
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub struct rns_transport::interface_ownership::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::interface_ownership::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_transport::interface_ownership::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::interface_ownership::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::interface_ownership::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::interface_ownership::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub mod rns_transport::link_endpoint_dispatch
#[non_exhaustive] pub enum rns_transport::link_endpoint_dispatch::LinkEndpointDispatchError
pub rns_transport::link_endpoint_dispatch::LinkEndpointDispatchError::Closed
@@ -841,6 +927,7 @@ pub rns_transport::link_messages::DestinationEvent::DeliveryProof::msg_id: alloc
pub rns_transport::link_messages::DestinationEvent::DeliveryProof::rtt: core::option::Option<core::time::Duration>
pub rns_transport::link_messages::DestinationEvent::InboundPacket
pub rns_transport::link_messages::DestinationEvent::InboundPacket::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_messages::DestinationEvent::InboundPacket::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::link_messages::DestinationEvent::InboundPacket::metrics: rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::DestinationEvent::InboundPacket::raw: bytes::bytes::Bytes
pub rns_transport::link_messages::DestinationEvent::LinkClosed
@@ -849,8 +936,14 @@ pub rns_transport::link_messages::DestinationEvent::LinkEstablished
pub rns_transport::link_messages::DestinationEvent::LinkEstablished::link_id: [u8; 16]
pub rns_transport::link_messages::DestinationEvent::LinkRequest
pub rns_transport::link_messages::DestinationEvent::LinkRequest::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_messages::DestinationEvent::LinkRequest::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::link_messages::DestinationEvent::LinkRequest::metrics: rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::DestinationEvent::LinkRequest::raw: bytes::bytes::Bytes
pub enum rns_transport::link_messages::LinkRequestDispatchError
pub rns_transport::link_messages::LinkRequestDispatchError::Capacity(rns_transport::interface_ownership::InterfaceCapacityError)
pub rns_transport::link_messages::LinkRequestDispatchError::InvalidRequest
pub rns_transport::link_messages::LinkRequestDispatchError::NoInterface
pub rns_transport::link_messages::LinkRequestDispatchError::TransportUnavailable
pub struct rns_transport::link_messages::AnnounceRequest
pub rns_transport::link_messages::AnnounceRequest::app_name: alloc::string::String
pub rns_transport::link_messages::AnnounceRequest::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
@@ -868,6 +961,7 @@ pub struct rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::PacketMetrics::q: core::option::Option<f32>
pub rns_transport::link_messages::PacketMetrics::rssi: core::option::Option<f32>
pub rns_transport::link_messages::PacketMetrics::snr: core::option::Option<f32>
pub async fn rns_transport::link_messages::dispatch_link_request(&tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, rns_transport::messages::OutboundRequest) -> core::result::Result<(), rns_transport::link_messages::LinkRequestDispatchError>
pub mod rns_transport::link_table
pub struct rns_transport::link_table::ExpiredLink
pub rns_transport::link_table::ExpiredLink::destination_hash: [u8; 16]
@@ -879,13 +973,17 @@ pub rns_transport::link_table::ExpiredLink::taken_hops: u8
impl core::convert::From<&rns_transport::link_table::LinkEntry> for rns_transport::link_table::ExpiredLink
pub fn rns_transport::link_table::ExpiredLink::from(&rns_transport::link_table::LinkEntry) -> Self
pub struct rns_transport::link_table::LinkEntry
pub rns_transport::link_table::LinkEntry::accepted_mtu_ceiling: u32
pub rns_transport::link_table::LinkEntry::destination_hash: [u8; 16]
pub rns_transport::link_table::LinkEntry::established: bool
pub rns_transport::link_table::LinkEntry::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_table::LinkEntry::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>
pub rns_transport::link_table::LinkEntry::next_hop: core::option::Option<[u8; 16]>
pub rns_transport::link_table::LinkEntry::proof_timeout: f64
pub rns_transport::link_table::LinkEntry::receiving_interface: rns_transport::messages::InterfaceId
pub rns_transport::link_table::LinkEntry::receiving_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>
pub rns_transport::link_table::LinkEntry::remaining_hops: u8
pub rns_transport::link_table::LinkEntry::requested_mode: u8
pub rns_transport::link_table::LinkEntry::taken_hops: u8
pub rns_transport::link_table::LinkEntry::timestamp: f64
pub rns_transport::link_table::LinkEntry::validated: bool
@@ -904,9 +1002,26 @@ pub fn rns_transport::link_table::LinkTable::iter(&self) -> impl core::iter::tra
pub fn rns_transport::link_table::LinkTable::len(&self) -> usize
pub fn rns_transport::link_table::LinkTable::new() -> Self
pub fn rns_transport::link_table::LinkTable::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_transport::link_table::LinkEntry>
pub fn rns_transport::link_table::LinkTable::remove_interface(&mut self, rns_transport::messages::InterfaceId)
impl core::default::Default for rns_transport::link_table::LinkTable
pub fn rns_transport::link_table::LinkTable::default() -> Self
pub mod rns_transport::link_transit
pub enum rns_transport::link_transit::LinkTransitError
pub rns_transport::link_transit::LinkTransitError::Capacity(rns_transport::interface_ownership::InterfaceCapacityError)
pub rns_transport::link_transit::LinkTransitError::InvalidSignalling(rns_wire::link_signalling::LinkSignallingError)
pub rns_transport::link_transit::LinkTransitError::StaleInterface
pub rns_transport::link_transit::LinkTransitError::UnsupportedTransitModeTransform
pub mod rns_transport::messages
pub enum rns_transport::messages::InterfaceCapacityError
pub rns_transport::messages::InterfaceCapacityError::Empty
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::messages::InterfaceCapacityError::InvalidIfac
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub enum rns_transport::messages::InterfaceRole
pub rns_transport::messages::InterfaceRole::LocalClient
pub rns_transport::messages::InterfaceRole::Normal
@@ -979,6 +1094,10 @@ pub rns_transport::messages::TransportMessage::DeregisterDestination::hash: [u8;
pub rns_transport::messages::TransportMessage::DeregisterInterface
pub rns_transport::messages::TransportMessage::DeregisterInterface::id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::Inbound(rns_transport::messages::InboundPacket)
pub rns_transport::messages::TransportMessage::InterfaceEvent
pub rns_transport::messages::TransportMessage::InterfaceEvent::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::InterfaceEvent::message: alloc::boxed::Box<rns_transport::messages::TransportMessage>
pub rns_transport::messages::TransportMessage::InterfaceEvent::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_transport::messages::TransportMessage::Outbound(rns_transport::messages::OutboundRequest)
pub rns_transport::messages::TransportMessage::OutboundAttached
pub rns_transport::messages::TransportMessage::OutboundAttached::interface_id: rns_transport::messages::InterfaceId
@@ -1004,6 +1123,7 @@ pub rns_transport::messages::TransportMessage::RegisterLink
pub rns_transport::messages::TransportMessage::RegisterLink::destination_hash: [u8; 16]
pub rns_transport::messages::TransportMessage::RegisterLink::initiator: bool
pub rns_transport::messages::TransportMessage::RegisterLink::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::RegisterLink::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::messages::TransportMessage::RegisterLink::link_id: [u8; 16]
pub rns_transport::messages::TransportMessage::RegisterLink::next_hop: core::option::Option<[u8; 16]>
pub rns_transport::messages::TransportMessage::RegisterLink::remaining_hops: u8
@@ -1045,6 +1165,13 @@ pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::link_
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::result_tx: tokio::sync::oneshot::Sender<rns_transport::messages::LinkEndpointSendResult>
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::role: rns_transport::messages::LinkEndpointRole
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::authority: rns_transport::link_endpoint_dispatch::LinkEndpointDispatchToken
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::result_tx: tokio::sync::oneshot::Sender<rns_transport::messages::LinkEndpointSendResult>
pub rns_transport::messages::TransportMessage::SendLinkRequest
pub rns_transport::messages::TransportMessage::SendLinkRequest::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkRequest::result_tx: tokio::sync::oneshot::Sender<core::result::Result<(), rns_transport::link_messages::LinkRequestDispatchError>>
pub rns_transport::messages::TransportMessage::SendPacket
pub rns_transport::messages::TransportMessage::SendPacket::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::TransportMessage::SendPacket::receipt: core::option::Option<rns_transport::messages::TrackedReceiptRegistration>
@@ -1235,8 +1362,9 @@ pub rns_transport::messages::InterfaceEntry::announce_rate_target: core::option:
pub rns_transport::messages::InterfaceEntry::announces_from_internal: bool
pub rns_transport::messages::InterfaceEntry::bitrate: u64
pub rns_transport::messages::InterfaceEntry::direction: rns_transport::constants::InterfaceDirection
pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<[u8; 64]>
pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<rns_identity::ifac::IfacKey>
pub rns_transport::messages::InterfaceEntry::ifac_size: usize
pub rns_transport::messages::InterfaceEntry::ifac_violations: u64
pub rns_transport::messages::InterfaceEntry::ingress: rns_transport::ingress::IngressController
pub rns_transport::messages::InterfaceEntry::inspection: core::option::Option<rns_transport::messages::InterfaceInspectionSource>
pub rns_transport::messages::InterfaceEntry::mode: rns_transport::constants::InterfaceMode
@@ -1244,18 +1372,29 @@ pub rns_transport::messages::InterfaceEntry::mtu: u32
pub rns_transport::messages::InterfaceEntry::multipoint: bool
pub rns_transport::messages::InterfaceEntry::name: alloc::string::String
pub rns_transport::messages::InterfaceEntry::online: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>>
pub rns_transport::messages::InterfaceEntry::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_transport::messages::InterfaceEntry::packet_capacity: rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_transport::messages::InterfaceEntry::packet_filter_hits: u64
pub rns_transport::messages::InterfaceEntry::parent_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::InterfaceEntry::protocol_violations: u64
pub rns_transport::messages::InterfaceEntry::recursive_prs: bool
pub rns_transport::messages::InterfaceEntry::role: rns_transport::messages::InterfaceRole
pub rns_transport::messages::InterfaceEntry::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub rns_transport::messages::InterfaceEntry::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
pub rns_transport::messages::InterfaceEntry::tx_dropped_bytes: u64
pub rns_transport::messages::InterfaceEntry::tx_drops: alloc::sync::Arc<core::sync::atomic::AtomicU64>
pub rns_transport::messages::InterfaceEntry::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
impl rns_transport::messages::InterfaceEntry
pub fn rns_transport::messages::InterfaceEntry::accepts_clear_packet(&self, usize) -> bool
pub fn rns_transport::messages::InterfaceEntry::active_ifac_bytes(&self) -> usize
pub fn rns_transport::messages::InterfaceEntry::effective_clear_mtu(&self) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::messages::InterfaceEntry::new(alloc::string::String, rns_transport::constants::InterfaceMode, rns_transport::constants::InterfaceDirection, u64, u32, tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_announce_rate(self, f64, u32, f64) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_counters(self, alloc::sync::Arc<core::sync::atomic::AtomicBool>, alloc::sync::Arc<core::sync::atomic::AtomicU64>, alloc::sync::Arc<core::sync::atomic::AtomicU64>) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_ifac(self, [u8; 64], usize) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_multipoint(self, bool) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_owner(self, rns_transport::interface_ownership::InterfaceOwner) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_packet_capacity(self, rns_transport::interface_ownership::InterfacePacketCapacity) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_role(self, rns_transport::messages::InterfaceRole) -> Self
impl core::fmt::Debug for rns_transport::messages::InterfaceEntry
pub fn rns_transport::messages::InterfaceEntry::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
@@ -1268,12 +1407,41 @@ pub fn rns_transport::messages::InterfaceInspectionSource::new<F>(F) -> Self whe
pub fn rns_transport::messages::InterfaceInspectionSource::snapshot(&self) -> rns_transport::messages::InterfaceInspectionSnapshot
impl core::fmt::Debug for rns_transport::messages::InterfaceInspectionSource
pub fn rns_transport::messages::InterfaceInspectionSource::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_transport::messages::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::messages::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::messages::InterfacePacketCapacity
pub rns_transport::messages::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::messages::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::messages::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::messages::InterfaceStatRpcEntry
pub rns_transport::messages::InterfaceStatRpcEntry::announce_cap: f64
pub rns_transport::messages::InterfaceStatRpcEntry::announce_queue: core::option::Option<u64>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_grace: core::option::Option<u32>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_penalty: core::option::Option<f64>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_target: core::option::Option<f64>
pub rns_transport::messages::InterfaceStatRpcEntry::announces_received: u64
pub rns_transport::messages::InterfaceStatRpcEntry::announces_sent: u64
pub rns_transport::messages::InterfaceStatRpcEntry::bitrate: u64
pub rns_transport::messages::InterfaceStatRpcEntry::blocked_ips: core::option::Option<u64>
pub rns_transport::messages::InterfaceStatRpcEntry::burst_activated: f64
@@ -1282,6 +1450,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::clients: core::option::Optio
pub rns_transport::messages::InterfaceStatRpcEntry::held_announces: u64
pub rns_transport::messages::InterfaceStatRpcEntry::id: rns_transport::messages::InterfaceId
pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: usize
pub rns_transport::messages::InterfaceStatRpcEntry::ifac_violations: u64
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_announce_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_pr_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::mode: alloc::string::String
@@ -1290,16 +1459,38 @@ pub rns_transport::messages::InterfaceStatRpcEntry::name: alloc::string::String
pub rns_transport::messages::InterfaceStatRpcEntry::online: bool
pub rns_transport::messages::InterfaceStatRpcEntry::outgoing_announce_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::outgoing_pr_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::packet_filter_hits: u64
pub rns_transport::messages::InterfaceStatRpcEntry::parent_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::InterfaceStatRpcEntry::path_requests_received: u64
pub rns_transport::messages::InterfaceStatRpcEntry::path_requests_sent: u64
pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_activated: f64
pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_active: bool
pub rns_transport::messages::InterfaceStatRpcEntry::protocol_violations: u64
pub rns_transport::messages::InterfaceStatRpcEntry::role: alloc::string::String
pub rns_transport::messages::InterfaceStatRpcEntry::rx_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::rx_rate: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_dropped_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_drops: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_rate: u64
pub struct rns_transport::messages::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub struct rns_transport::messages::LinkEndpointBinding
pub rns_transport::messages::LinkEndpointBinding::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::LinkEndpointBinding::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::messages::LinkEndpointBinding::link_id: [u8; 16]
pub rns_transport::messages::LinkEndpointBinding::role: rns_transport::messages::LinkEndpointRole
pub struct rns_transport::messages::LinkEndpointLifecycleEvent
@@ -1660,7 +1851,7 @@ pub fn rns_transport::traffic::TrafficCounter::default() -> Self
pub mod rns_transport::tunnel
pub struct rns_transport::tunnel::TunnelEntry
pub rns_transport::tunnel::TunnelEntry::expires: f64
pub rns_transport::tunnel::TunnelEntry::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::tunnel::TunnelEntry::interface_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::tunnel::TunnelEntry::tunnel_id: [u8; 32]
pub rns_transport::tunnel::TunnelEntry::tunnel_paths: std::collections::hash::map::HashMap<[u8; 16], rns_transport::tunnel::TunnelPath>
pub struct rns_transport::tunnel::TunnelPath
@@ -1676,6 +1867,7 @@ pub rns_transport::tunnel::TunnelSynthesisData::public_key: [u8; 64]
pub rns_transport::tunnel::TunnelSynthesisData::random_hash: [u8; 16]
pub rns_transport::tunnel::TunnelSynthesisData::signature: [u8; 64]
impl rns_transport::tunnel::TunnelSynthesisData
pub fn rns_transport::tunnel::TunnelSynthesisData::is_signed(&self) -> bool
pub fn rns_transport::tunnel::TunnelSynthesisData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_transport::tunnel::TunnelSynthesisData::tunnel_id(&self) -> [u8; 32]
pub fn rns_transport::tunnel::TunnelSynthesisData::unpack(&[u8]) -> core::option::Option<Self>
@@ -1694,9 +1886,62 @@ pub fn rns_transport::tunnel::TunnelTable::len(&self) -> usize
pub fn rns_transport::tunnel::TunnelTable::new() -> Self
pub fn rns_transport::tunnel::TunnelTable::remove(&mut self, &[u8; 32]) -> core::option::Option<rns_transport::tunnel::TunnelEntry>
pub fn rns_transport::tunnel::TunnelTable::tunnel_paths(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 16], &rns_transport::tunnel::TunnelPath)>
pub fn rns_transport::tunnel::TunnelTable::void_interface(&mut self, rns_transport::messages::InterfaceId) -> usize
impl core::default::Default for rns_transport::tunnel::TunnelTable
pub fn rns_transport::tunnel::TunnelTable::default() -> Self
pub fn rns_transport::tunnel::build_tunnel_synthesis_packet(&rns_identity::identity::Identity, [u8; 32]) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId, f64)
pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId)
pub fn rns_transport::tunnel::interface_hash(&str) -> [u8; 32]
pub enum rns_transport::InterfaceCapacityError
pub rns_transport::InterfaceCapacityError::Empty
pub rns_transport::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::InterfaceCapacityError::InvalidIfac
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub struct rns_transport::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::InterfacePacketCapacity
pub rns_transport::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::now_f64() -> f64
+32
View File
@@ -95,6 +95,38 @@ impl rns_wire::header::PacketHeader
pub fn rns_wire::header::PacketHeader::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_wire::header::PacketHeader::size(&self) -> usize
pub fn rns_wire::header::PacketHeader::unpack(&[u8]) -> core::result::Result<(Self, usize), rns_wire::header::HeaderError>
pub mod rns_wire::link_signalling
pub enum rns_wire::link_signalling::LinkSignallingError
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::actual: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::legacy: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::modern: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidMode(u8)
pub rns_wire::link_signalling::LinkSignallingError::InvalidMtu(u32)
pub rns_wire::link_signalling::LinkSignallingError::MduUnavailable
pub struct rns_wire::link_signalling::LinkMtu(_)
impl rns_wire::link_signalling::LinkMtu
pub const rns_wire::link_signalling::LinkMtu::BASE: Self
pub fn rns_wire::link_signalling::LinkMtu::checked_mdu(self) -> core::result::Result<usize, rns_wire::link_signalling::LinkSignallingError>
pub const fn rns_wire::link_signalling::LinkMtu::get(self) -> u32
pub fn rns_wire::link_signalling::LinkMtu::try_from_signal(core::option::Option<u32>) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub struct rns_wire::link_signalling::LinkSignalling
pub rns_wire::link_signalling::LinkSignalling::mode: u8
pub rns_wire::link_signalling::LinkSignalling::mtu: rns_wire::link_signalling::LinkMtu
pub rns_wire::link_signalling::LinkSignalling::signalling_present: bool
pub struct rns_wire::link_signalling::SignallingData
pub rns_wire::link_signalling::SignallingData::mode: u8
pub rns_wire::link_signalling::SignallingData::mtu: u32
impl rns_wire::link_signalling::SignallingData
pub fn rns_wire::link_signalling::SignallingData::new(u8, u32) -> Self
pub fn rns_wire::link_signalling::SignallingData::pack(&self) -> [u8; 3]
pub fn rns_wire::link_signalling::SignallingData::try_new(u8, u32) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
pub const rns_wire::link_signalling::BASE_LINK_MTU: u32
pub const rns_wire::link_signalling::DEFAULT_LINK_MODE: u8
pub const rns_wire::link_signalling::MAX_SIGNALLED_LINK_MTU: u32
pub fn rns_wire::link_signalling::parse_proof_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::parse_request_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub mod rns_wire::packet
pub enum rns_wire::packet::PacketError
pub rns_wire::packet::PacketError::ExceedsMtu(usize)
+102 -19
View File
@@ -24,8 +24,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-crypto.txt",
"itemCount": 91,
"sha256": "4d1e3c0a13e48a84f2510c6586024b3d8f5781b367459bc17d714ca485f1aa63"
"itemCount": 92,
"sha256": "1f4539cfe1dfc1bf78a75e95dc98a3bf14a432cf0292d8d654fc043d5c4d21dc"
},
{
"name": "rns-wire",
@@ -33,8 +33,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-wire.txt",
"itemCount": 370,
"sha256": "7ce9011e531c1642912512d9d975b8a7def0bb41f691b6b16177eddecf5bef6d"
"itemCount": 402,
"sha256": "47f17ed4b47f0fc9ccaccc42d00b7635b07083c4eae6782a4f5de7e1452e4688"
},
{
"name": "rns-identity",
@@ -42,8 +42,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-identity.txt",
"itemCount": 374,
"sha256": "f2b692070a3fa1a2cc98edbb40bc75d205daadfa9da9d9994ee194e8436e00c9"
"itemCount": 431,
"sha256": "377cb3b72a97b071e0d590c399d0cc0433b60fe5a6ae37a73657283d3622f037"
},
{
"name": "rns-transport",
@@ -51,8 +51,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-transport.txt",
"itemCount": 1702,
"sha256": "30f20b408ac255e1f005e25e79e4999d813ebc6b4f1a501bf573de58db0e25ab"
"itemCount": 1947,
"sha256": "79cd60b1cde9c92e97f58ded693d3754b53311ec16f161ffa5b90775ec3c4a45"
},
{
"name": "rns-link",
@@ -60,8 +60,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-link.txt",
"itemCount": 359,
"sha256": "59d2f211857314e044bf31e5b78e4460483411c9b26c08904f8996295b189984"
"itemCount": 384,
"sha256": "6c7db32623681ef8b2fdce0c54edbb992d307f0fae8b361c65109a6d262d9389"
},
{
"name": "rns-protocol",
@@ -69,8 +69,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-protocol.txt",
"itemCount": 624,
"sha256": "9fd1968c43d3a80b5da65416f43a805e3bfd3420c91acc8ad63a7a3ca58b359c"
"itemCount": 638,
"sha256": "f90d8a7a284b50df43e3c9936f7b3a3a9c4104f4e31cc9ef1c60b833239b7ec6"
},
{
"name": "rns-interface",
@@ -78,8 +78,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-interface.txt",
"itemCount": 1406,
"sha256": "b097f01fc5eac53ed0ce5b6150c47c12f69fb63072ac31789a3995167123af3a"
"itemCount": 1437,
"sha256": "202181006ad3505dc4977f95740d5cd813fe664c5060806d2f757851ca0befb5"
},
{
"name": "rns-runtime",
@@ -87,8 +87,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-runtime.txt",
"itemCount": 2063,
"sha256": "ca162e9ddb542f0daf5817ac26d32be80346d36bdadd70673bf2cdc2535e4e29"
"itemCount": 2145,
"sha256": "a4496892f8c4f6aeb9f840179e1a967b576679056045dd4511d5fe064f32544c"
},
{
"name": "rns-tools",
@@ -110,13 +110,21 @@
}
],
"approvedBreakingChanges": {
"releaseLine": "1.3",
"migrationGuide": "api/migrations/1.3.md",
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"removed": {
"rns-crypto": [
"pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>",
"pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>"
],
"rns-transport": [
"pub enum rns_transport::discovery::Reason",
"pub enum rns_transport::discovery::receiver::Reason",
"pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId, f64)",
"pub rns_transport::actor::DiscoveryPathRequest::requesting_interface: rns_transport::messages::InterfaceId",
"pub rns_transport::actor::DiscoveryPathRequest::timeout: f64",
"pub rns_transport::actor::TransportActor::discovery_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::actor::DiscoveryPathRequest>",
"pub rns_transport::actor::TransportActor::pending_tunnel_entries: alloc::vec::Vec<rns_transport::persistence::PersistedTunnelEntry>",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::height: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::latitude: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::longitude: f64",
@@ -125,7 +133,82 @@
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::longitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::height: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64"
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64",
"pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<[u8; 64]>",
"pub rns_transport::tunnel::TunnelEntry::interface_id: rns_transport::messages::InterfaceId"
],
"rns-link": [
"impl rns_link::mtu_discovery::SignallingData",
"pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self",
"pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]",
"pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>",
"pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self",
"pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]",
"pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>",
"pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::mtu_discovery::SignallingData::mode: u8",
"pub rns_link::mtu_discovery::SignallingData::mtu: u32",
"pub struct rns_link::mtu_discovery::SignallingData"
],
"rns-interface": [
"pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>",
"pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>"
],
"rns-runtime": [
"pub fn rns_runtime::interface_factory::InterfacePostInit::from_section(&rns_runtime::config::ConfigSection) -> Self",
"pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)",
"pub mod rns_runtime::remote_management_schema",
"pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::announce_queue: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::bitrate: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::blocked_ips: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::clients: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::hash: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::held_announces: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_netname: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_size: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::mode: u8",
"pub rns_runtime::remote_management_schema::InterfaceStats::name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::short_name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::status: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::txb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::txs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::type_: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::expires: f64",
"pub rns_runtime::remote_management_schema::PathEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::PathEntry::hops: u8",
"pub rns_runtime::remote_management_schema::PathEntry::interface: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::timestamp: f64",
"pub rns_runtime::remote_management_schema::PathEntry::via: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::RateEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::RateEntry::rate: f64",
"pub rns_runtime::remote_management_schema::TransportStats::interfaces: alloc::vec::Vec<rns_runtime::remote_management_schema::InterfaceStats>",
"pub rns_runtime::remote_management_schema::TransportStats::network_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::probe_responder: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::rss: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::TransportStats::rxb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::rxs: u64",
"pub rns_runtime::remote_management_schema::TransportStats::transport_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::transport_uptime: core::option::Option<f64>",
"pub rns_runtime::remote_management_schema::TransportStats::txb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::txs: u64",
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: usize",
"pub struct rns_runtime::remote_management_schema::InterfaceStats",
"pub struct rns_runtime::remote_management_schema::PathEntry",
"pub struct rns_runtime::remote_management_schema::RateEntry",
"pub struct rns_runtime::remote_management_schema::TransportStats"
]
}
}
+13 -2
View File
@@ -7,6 +7,7 @@ use alloc::vec::Vec;
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use cbc::{Decryptor, Encryptor};
use thiserror::Error;
use zeroize::Zeroizing;
const AES_BLOCK_SIZE: usize = 16;
@@ -46,7 +47,8 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
return Err(AesCbcError::NotBlockAligned);
}
let mut buf = plaintext.to_vec();
// Wiped if an error leaves this plaintext copy unencrypted.
let mut buf = Zeroizing::new(plaintext.to_vec());
match key.len() {
16 => {
let enc = Encryptor::<Aes128>::new_from_slices(key, iv)
@@ -68,7 +70,7 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
}
n => return Err(AesCbcError::InvalidKeyLength(n)),
}
Ok(buf)
Ok(core::mem::take(&mut *buf))
}
/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it.
@@ -174,6 +176,15 @@ mod tests {
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn cipher_state_is_wiped_on_drop() {
fn wiped_on_drop<T: zeroize::ZeroizeOnDrop>() {}
wiped_on_drop::<Encryptor<Aes128>>();
wiped_on_drop::<Encryptor<Aes256>>();
wiped_on_drop::<Decryptor<Aes128>>();
wiped_on_drop::<Decryptor<Aes256>>();
}
/// Different key sizes must produce different ciphertexts for the same input.
#[test]
fn test_aes128_vs_aes256_distinct_ciphertexts() {
+19 -8
View File
@@ -5,6 +5,7 @@ use alloc::vec::Vec;
use hkdf::Hkdf;
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
@@ -23,19 +24,20 @@ pub enum HkdfError {
/// HKDF-SHA256 key derivation (RFC 5869).
///
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
/// specified by the RFC; `info = None` uses an empty context string.
/// specified by the RFC; `info = None` uses an empty context string. The
/// output is wiped when it is dropped.
pub fn hkdf_sha256(
length: usize,
ikm: &[u8],
salt: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Vec<u8>, HkdfError> {
) -> Result<Zeroizing<Vec<u8>>, HkdfError> {
if length > MAX_OUTPUT_LENGTH {
return Err(HkdfError::OutputTooLong(length));
}
let hk = Hkdf::<Sha256>::new(salt, ikm);
let mut okm = vec![0u8; length];
let mut okm = Zeroizing::new(vec![0u8; length]);
hk.expand(info.unwrap_or(b""), &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
@@ -43,11 +45,13 @@ pub fn hkdf_sha256(
/// Derive the 64-byte session key used for RNS link encryption:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> {
let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?;
let mut out = [0u8; 64];
out.copy_from_slice(&okm);
Ok(out)
/// The key is expanded straight into its return buffer, which is wiped on drop.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<Zeroizing<[u8; 64]>, HkdfError> {
let mut okm = Zeroizing::new([0u8; 64]);
Hkdf::<Sha256>::new(Some(salt), shared_secret)
.expand(b"", &mut okm[..])
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
#[cfg(test)]
@@ -84,5 +88,12 @@ mod tests {
fn test_derive_key_64() {
let key = derive_key_64(b"shared_secret", b"salt_value").unwrap();
assert_eq!(key.len(), 64);
let cases: [(&[u8], &[u8]); 2] = [(b"shared_secret", b"salt_value"), (&[7; 32], &[9; 16])];
for (ikm, salt) in cases {
assert_eq!(
&derive_key_64(ikm, salt).unwrap()[..],
&hkdf_sha256(64, ikm, Some(salt), None).unwrap()[..]
);
}
}
}
+4
View File
@@ -16,6 +16,10 @@ pub mod token;
pub mod x25519;
pub use token::TOKEN_OVERHEAD;
/// The wiping types in this crate's API, such as the output of
/// [`hkdf::hkdf_sha256`], for crates that hold secrets without depending on
/// `zeroize` themselves.
pub use zeroize;
use alloc::string::String;
use core::fmt::Write;
+14 -5
View File
@@ -63,7 +63,7 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
let iv = random_16();
let padded = pkcs7::pad(plaintext);
let padded = Zeroizing::new(pkcs7::pad(plaintext));
let ciphertext =
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
@@ -82,6 +82,10 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
/// (padding-oracle defence). HMAC comparison is constant-time.
///
/// The plaintext is returned in the buffer it was decrypted into, and a failed
/// decryption wipes that buffer. Callers wrap a secret plaintext in
/// [`Zeroizing`] so it is wiped when dropped.
pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
@@ -105,12 +109,17 @@ pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
return Err(TokenError::AuthenticationFailed);
}
let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?;
let mut padded = Zeroizing::new(
aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?,
);
let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?;
let len = pkcs7::unpad(&padded)
.map_err(|_| TokenError::AuthenticationFailed)?
.len();
padded.truncate(len);
Ok(plaintext.to_vec())
Ok(core::mem::take(&mut *padded))
}
#[cfg(test)]
+168
View File
@@ -0,0 +1,168 @@
//! Shared by the secret-residue test binaries. A recording allocator copies
//! every block the calling thread frees while a check runs; each check then
//! searches those copies for its secrets.
#![allow(dead_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::{Cell, UnsafeCell};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
const RECORD_CAPACITY: usize = 8 << 20;
struct Recording(UnsafeCell<[u8; RECORD_CAPACITY]>);
// Written only by the armed thread while armed, read only after disarming.
unsafe impl Sync for Recording {}
static RECORDING: Recording = Recording(UnsafeCell::new([0; RECORD_CAPACITY]));
static RECORDED: AtomicUsize = AtomicUsize::new(0);
static OVERFLOWED: AtomicBool = AtomicBool::new(false);
static PEAK: AtomicUsize = AtomicUsize::new(0);
static SERIAL: Mutex<()> = Mutex::new(());
thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
}
struct RecordingAllocator;
fn armed() -> bool {
ARMED.try_with(Cell::get).unwrap_or(false)
}
unsafe impl GlobalAlloc for RecordingAllocator {
// Blocks handed out while armed start zeroed, so a recorded block holds
// only what was written during the check, never a reused block's old bytes.
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if !armed() {
return unsafe { System.alloc(layout) };
}
PEAK.fetch_max(layout.size(), Ordering::Relaxed);
unsafe { System.alloc_zeroed(layout) }
}
// The default `realloc` frees the old block through `dealloc`, so blocks
// left behind by growth are recorded too.
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if armed() {
let start = RECORDED.load(Ordering::Relaxed);
let end = start + 4 + layout.size();
if end <= RECORD_CAPACITY {
let base = RECORDING.0.get().cast::<u8>();
unsafe {
base.add(start)
.cast::<[u8; 4]>()
.write_unaligned((layout.size() as u32).to_le_bytes());
std::ptr::copy_nonoverlapping(ptr, base.add(start + 4), layout.size());
}
RECORDED.store(end, Ordering::Relaxed);
} else {
OVERFLOWED.store(true, Ordering::Relaxed);
}
}
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOCATOR: RecordingAllocator = RecordingAllocator;
pub fn serial() -> MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub struct Freed {
pub blocks: Vec<Vec<u8>>,
pub peak_allocation: usize,
}
/// Run `f` and return its result with a copy of every block it freed.
pub fn freed_by<R>(f: impl FnOnce() -> R) -> (R, Freed) {
RECORDED.store(0, Ordering::Relaxed);
OVERFLOWED.store(false, Ordering::Relaxed);
PEAK.store(0, Ordering::Relaxed);
ARMED.with(|armed| armed.set(true));
let result = f();
ARMED.with(|armed| armed.set(false));
assert!(
!OVERFLOWED.load(Ordering::Relaxed),
"freed blocks exceeded the recording buffer"
);
let len = RECORDED.load(Ordering::Relaxed);
let recorded = unsafe { std::slice::from_raw_parts(RECORDING.0.get().cast::<u8>(), len) };
let mut blocks = Vec::new();
let mut at = 0;
while at < len {
let size = u32::from_le_bytes(recorded[at..at + 4].try_into().unwrap()) as usize;
blocks.push(recorded[at + 4..at + 4 + size].to_vec());
at += 4 + size;
}
let freed = Freed {
blocks,
peak_allocation: PEAK.load(Ordering::Relaxed),
};
(result, freed)
}
/// Whether `block` holds 16 consecutive bytes of `secret`.
pub fn holds(block: &[u8], secret: &[u8]) -> bool {
!find(&[block.to_vec()], &[secret]).is_empty()
}
/// For each block holding 16 consecutive bytes of any of `secrets`: its
/// length and the indexes of the secrets it holds.
pub fn find(blocks: &[Vec<u8>], secrets: &[&[u8]]) -> Vec<(usize, Vec<usize>)> {
let mut windows: HashMap<&[u8], Vec<usize>> = HashMap::new();
for (index, secret) in secrets.iter().enumerate() {
assert!(secret.len() >= 16, "secret is too short to search for");
for window in secret.windows(16) {
let owners = windows.entry(window).or_default();
if owners.last() != Some(&index) {
owners.push(index);
}
}
}
let mut found = Vec::new();
for block in blocks {
let mut held: Vec<usize> = block
.windows(16)
.filter_map(|window| windows.get(window))
.flatten()
.copied()
.collect();
held.sort_unstable();
held.dedup();
if !held.is_empty() {
found.push((block.len(), held));
}
}
found
}
/// Fail if any freed block holds part of a secret.
pub fn assert_no_residue(freed: &Freed, secrets: &[(&str, &[u8])]) {
let values: Vec<&[u8]> = secrets.iter().map(|(_, secret)| *secret).collect();
let mut found = Vec::new();
for (len, held) in find(&freed.blocks, &values) {
for index in held {
found.push(format!("{} in a freed {len}-byte block", secrets[index].0));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
pub fn pseudo_random<const N: usize>(seed: u64) -> [u8; N] {
let mut state = seed;
let mut out = [0u8; N];
for byte in &mut out {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
*byte = (state >> 24) as u8;
}
out
}
+137
View File
@@ -0,0 +1,137 @@
//! Plaintext and key material must not survive in freed heap memory.
mod residue;
use residue::{assert_no_residue, freed_by, holds, pseudo_random, serial};
use rns_crypto::{aes_cbc, hkdf, hmac, token};
use std::hint::black_box;
use zeroize::Zeroizing;
#[test]
fn the_harness_finds_unwiped_copies() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(12);
let ((), dropped) = freed_by(|| drop(black_box(secret.to_vec())));
// A wiped buffer that grew still frees its first block unwiped.
let ((), grown) = freed_by(|| {
let mut copy = Zeroizing::new(Vec::with_capacity(32));
copy.extend_from_slice(&secret[..32]);
copy.extend_from_slice(&secret[32..]);
black_box(&copy);
});
for (case, freed) in [("dropped", dropped), ("grown", grown)] {
assert!(
freed.blocks.iter().any(|block| holds(block, &secret)),
"{case}: copy not found"
);
}
}
#[test]
fn the_harness_ignores_bytes_freed_before_the_check() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(13);
// Large enough that the allocator hands the same block straight back.
drop(black_box(secret.repeat(1024)));
let ((), freed) = freed_by(|| drop(black_box(Vec::<u8>::with_capacity(64 * 1024))));
assert_no_residue(&freed, &[("secret", &secret)]);
}
#[test]
fn token_encrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(1);
let plaintext: [u8; 100] = pseudo_random(2);
let (token, freed) = freed_by(|| token::encrypt(&plaintext, &key).unwrap());
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
assert_eq!(
&Zeroizing::new(token::decrypt(&token, &key).unwrap())[..],
&plaintext[..]
);
}
#[test]
fn token_decrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(3);
let plaintext: [u8; 100] = pseudo_random(4);
let token = token::encrypt(&plaintext, &key).unwrap();
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(token::decrypt(&token, &key).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn token_decrypt_wipes_an_authenticated_plaintext_with_bad_padding() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(5);
let mut plaintext: [u8; 64] = pseudo_random(6);
plaintext[63] = 0;
let iv = [0x24u8; 16];
let mut token = iv.to_vec();
token.extend_from_slice(&aes_cbc::encrypt(&key[32..], &iv, &plaintext).unwrap());
let mac = hmac::hmac_sha256(&key[..32], &token);
token.extend_from_slice(&mac);
let (result, freed) = freed_by(|| token::decrypt(&token, &key));
assert!(matches!(
result,
Err(token::TokenError::AuthenticationFailed)
));
assert_no_residue(&freed, &[("plaintext", &plaintext[..63])]);
}
#[test]
fn aes_cbc_encrypt_with_a_bad_key_frees_no_plaintext() {
let _serial = serial();
let plaintext: [u8; 64] = pseudo_random(7);
let (result, freed) = freed_by(|| aes_cbc::encrypt(&[0x11; 24], &[0x22; 16], &plaintext));
assert!(matches!(
result,
Err(aes_cbc::AesCbcError::InvalidKeyLength(24))
));
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn derive_key_64_frees_no_key() {
let _serial = serial();
let shared: [u8; 32] = pseudo_random(8);
let salt: [u8; 16] = pseudo_random(9);
let expected = hkdf::hkdf_sha256(64, &shared, Some(&salt), None).unwrap();
let ((), freed) = freed_by(|| {
let derived = hkdf::derive_key_64(&shared, &salt).unwrap();
assert_eq!(&derived[..], &expected[..]);
});
assert_no_residue(&freed, &[("derived key", &expected)]);
}
#[test]
fn hkdf_output_is_wiped_when_dropped() {
let _serial = serial();
let ikm: [u8; 32] = pseudo_random(10);
let salt: [u8; 16] = pseudo_random(11);
let expected = hkdf::derive_key_64(&ikm, &salt).unwrap();
let ((), freed) = freed_by(|| {
let okm: Zeroizing<Vec<u8>> = hkdf::hkdf_sha256(64, &ikm, Some(&salt), None).unwrap();
assert_eq!(&okm[..], &expected[..]);
});
assert_no_residue(&freed, &[("HKDF output", &expected[..])]);
}
+4
View File
@@ -19,6 +19,10 @@ serde_bytes = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
sha2 = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
+21 -1
View File
@@ -100,6 +100,20 @@ impl RatchetControlState {
/// Persist this state as a signed, bounded MessagePack envelope.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, false)
}
/// Persist announce ordering before releasing the corresponding wire bytes.
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, true)
}
fn save_verified_impl(
&self,
path: &Path,
identity: &Identity,
durable: bool,
) -> std::io::Result<()> {
if identity.hash != self.identity_hash {
return Err(invalid_data("control state identity binding mismatch"));
}
@@ -131,7 +145,13 @@ impl RatchetControlState {
if encoded.len() > CONTROL_STATE_MAX_BYTES {
return Err(invalid_data("ratchet control state exceeds size limit"));
}
persistence::atomic_write(path, &encoded)
if durable {
persistence::durable_write(path, &encoded)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &encoded)
}
}
/// Load and verify state for exactly `identity` and `destination_hash`.
+54 -12
View File
@@ -3,11 +3,11 @@ use rns_crypto::hkdf::derive_key_64;
use rns_crypto::sha::truncated_hash;
use rns_crypto::token;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use crate::persistence::{self, SecretBytes};
use std::fmt;
use std::path::Path;
use std::sync::Arc;
@@ -198,12 +198,16 @@ impl Identity {
Ok(id)
}
/// Load an identity from file, accepting either the current msgpack envelope
/// or a legacy raw 64-byte private key.
/// Load an identity from file, accepting either the raw 64-byte private key
/// that Python and [`Self::to_file`] write, or the older msgpack envelope.
/// A file larger than 1 KiB is refused once 1025 bytes have been read.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
let data = std::fs::read(path)?;
let data = persistence::read_secret_file(path, IDENTITY_FILE_MAX_BYTES)?;
if let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data) {
// An envelope never fits in 64 bytes, so a raw key is never parsed as one.
if data.len() != 64
&& let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data)
{
return Self::from_private_key(&persisted.private_key);
}
@@ -311,7 +315,7 @@ impl Identity {
shared.zeroize();
let derived = derived?;
let ciphertext =
token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
token::encrypt(plaintext, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
let mut result = Vec::with_capacity(32 + ciphertext.len());
result.extend_from_slice(&ephemeral_pub.to_bytes());
@@ -358,7 +362,7 @@ impl Identity {
let derived_result = derive_key_64(&shared, &self.hash);
shared.zeroize();
if let Ok(derived) = derived_result
&& let Ok(plaintext) = token::decrypt(ct, &derived)
&& let Ok(plaintext) = token::decrypt(ct, &derived[..])
{
return Ok(DecryptionResult {
plaintext,
@@ -387,7 +391,7 @@ impl Identity {
shared.zeroize();
let derived = derived_result?;
let plaintext =
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
token::decrypt(ct, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(DecryptionResult {
plaintext,
ratchet_id: None,
@@ -439,10 +443,15 @@ impl fmt::Display for Identity {
}
}
/// Identity files are a raw key or a small envelope; reading stops one byte
/// past this limit and refuses the file.
const IDENTITY_FILE_MAX_BYTES: usize = 1024;
// Msgpack envelope wrapping the raw 64-byte private key on disk.
#[derive(Serialize, Deserialize)]
struct IdentityPersisted {
private_key: Vec<u8>,
#[derive(Deserialize)]
struct IdentityPersisted<'a> {
#[serde(borrow)]
private_key: SecretBytes<'a, IDENTITY_FILE_MAX_BYTES>,
}
#[cfg(test)]
@@ -592,6 +601,39 @@ mod tests {
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn raw_keys_that_begin_like_an_envelope_load_as_raw_keys() {
let dir = std::env::temp_dir().join(format!(
"reticulum_identity_test_envelope_prefix_{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
// One-field msgpack arrays holding an empty array, 61 bytes of binary
// that end exactly at byte 64, and three integers.
let prefixes: [&[u8]; 3] = [&[0x91, 0x90], &[0x91, 0xc4, 0x3d], &[0x91, 0x93, 1, 2, 3]];
let mut failures = Vec::new();
for (index, prefix) in prefixes.into_iter().enumerate() {
let mut key = [0u8; 64];
for (offset, byte) in key.iter_mut().enumerate() {
*byte = (offset as u8).wrapping_mul(37).wrapping_add(index as u8);
}
key[..prefix.len()].copy_from_slice(prefix);
let expected = Identity::from_private_key(&key).unwrap();
let path = dir.join(format!("identity-{index}"));
std::fs::write(&path, key).unwrap();
match Identity::from_file(&path) {
Ok(loaded) => {
assert_eq!(loaded.hash, expected.hash, "prefix {prefix:02x?}");
assert_eq!(*loaded.get_private_key().unwrap(), key);
}
Err(e) => failures.push(format!("prefix {prefix:02x?}: {e}")),
}
}
std::fs::remove_dir_all(&dir).unwrap();
assert!(failures.is_empty(), "{failures:?}");
}
#[test]
fn test_file_backward_compat_raw() {
let dir = std::env::temp_dir().join("reticulum_identity_test_compat");
+100 -5
View File
@@ -1,6 +1,9 @@
use std::sync::Arc;
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use thiserror::Error;
use zeroize::Zeroizing;
/// Fixed IFAC HKDF salt shared with the Python reference.
///
@@ -27,7 +30,17 @@ pub fn derive_ifac_key(
network_name: Option<&str>,
passphrase: Option<&str>,
) -> Result<[u8; 64], IfacError> {
let mut ifac_origin = Vec::new();
let mut key = [0u8; 64];
derive_into(network_name, passphrase, &mut key)?;
Ok(key)
}
fn derive_into(
network_name: Option<&str>,
passphrase: Option<&str>,
key: &mut [u8; 64],
) -> Result<(), IfacError> {
let mut ifac_origin = Zeroizing::new(Vec::with_capacity(64));
if let Some(name) = network_name {
ifac_origin.extend_from_slice(&sha256(name.as_bytes()));
@@ -36,14 +49,60 @@ pub fn derive_ifac_key(
ifac_origin.extend_from_slice(&sha256(key.as_bytes()));
}
let ifac_origin_hash = sha256(&ifac_origin);
let ifac_origin_hash = Zeroizing::new(sha256(&ifac_origin));
let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?;
let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?;
let mut key = [0u8; 64];
let derived = hkdf_sha256(64, &*ifac_origin_hash, Some(&salt), None)?;
key.copy_from_slice(&derived);
Ok(key)
Ok(())
}
/// A derived IFAC key in one heap allocation, wiped when its last clone
/// drops. Clones share the allocation, so tables and queues that move or copy
/// an interface's settings never copy the key.
#[derive(Clone)]
pub struct IfacKey(Arc<Zeroizing<[u8; 64]>>);
impl IfacKey {
/// [`derive_ifac_key`], written straight into the shared allocation.
pub fn derive(network_name: Option<&str>, passphrase: Option<&str>) -> Result<Self, IfacError> {
let mut key = Arc::new(Zeroizing::new([0u8; 64]));
derive_into(
network_name,
passphrase,
Arc::get_mut(&mut key).expect("a new Arc is unique"),
)?;
Ok(Self(key))
}
}
impl From<[u8; 64]> for IfacKey {
fn from(key: [u8; 64]) -> Self {
Self(Arc::new(Zeroizing::new(key)))
}
}
impl std::ops::Deref for IfacKey {
type Target = [u8; 64];
fn deref(&self) -> &[u8; 64] {
&self.0
}
}
impl PartialEq for IfacKey {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
impl Eq for IfacKey {}
impl std::fmt::Debug for IfacKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("IfacKey(<redacted>)")
}
}
/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`.
@@ -64,6 +123,14 @@ pub fn derive_ifac_identity(
Ok((identity, ifac_key, signature))
}
/// The IFAC identity's signature over `SHA-256(ifac_key)`, which Python
/// publishes as an interface's `ifac_signature`.
pub fn ifac_signature(ifac_key: &[u8; 64]) -> Option<[u8; 64]> {
crate::identity::Identity::from_private_key(ifac_key)
.ok()?
.sign(&sha256(ifac_key))
}
/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes.
pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
(&key[..32], &key[32..])
@@ -83,6 +150,17 @@ fn hex_decode(s: &str) -> Option<Vec<u8>> {
mod tests {
use super::*;
#[test]
fn shared_key_matches_the_derived_bytes() {
let key = IfacKey::derive(Some("testnet"), Some("password")).unwrap();
assert_eq!(
*key,
derive_ifac_key(Some("testnet"), Some("password")).unwrap()
);
assert_eq!(key, IfacKey::from(*key));
assert_eq!(format!("{key:?}"), "IfacKey(<redacted>)");
}
#[test]
fn test_ifac_derivation_deterministic() {
let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
@@ -139,5 +217,22 @@ mod tests {
let key_hash = sha256(&ifac_key);
assert!(identity.verify(&key_hash, &signature));
assert_eq!(ifac_signature(&ifac_key), Some(signature));
}
/// Upstream `Identity.from_bytes(key).sign(Identity.full_hash(key))` for
/// the `ifac_testnet_password` vector key.
#[test]
fn ifac_signature_matches_upstream() {
let key = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
let expected = hex_decode(
"ce6b8bc4028852077243868e4b5f7faadb715c7a2fb75d1a211d30035f65b0c1\
fc4271ef61e91599e7bcc42723afe97503e3c432b01264185233274e3603e708",
)
.unwrap();
assert_eq!(
ifac_signature(&key).unwrap().as_slice(),
expected.as_slice()
);
}
}
+346 -70
View File
@@ -3,6 +3,17 @@ use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use zeroize::Zeroizing;
mod file_lock;
mod strict;
pub use file_lock::try_lock_exclusive;
pub use strict::{
DurableCleanupOutcome, DurableCommitPhase, DurableDirectoryReceipt, DurableErrorKind,
DurableFileReceipt, DurableWriteError, StorageRisk, durable_create_dir_all, durable_reconcile,
durable_reconcile_directory, durable_reconcile_hash, durable_remove, durable_rename_directory,
durable_write, storage_risk, validate_durable_storage_directory,
};
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
@@ -60,25 +71,132 @@ fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code))]
enum InjectedFailure {
Create,
Write,
Flush,
Sync,
VerifyTemp,
Rename,
VerifyFinal,
/// `Read::read`, retried when a signal interrupts it.
fn read_retrying(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
fn fail_if(stage: InjectedFailure, injected: Option<InjectedFailure>) -> std::io::Result<()> {
if injected == Some(stage) {
Err(std::io::Error::other(format!(
"injected atomic-write failure at {stage:?}"
)))
} else {
Ok(())
/// Compare the file at `path` with `data`. The file is read through a stack
/// buffer that is wiped afterwards, so reading back a secret leaves no copy.
fn verify_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
let mut file = fs::File::open(path)?;
let mut offset: usize = 0;
let mut chunk = Zeroizing::new([0u8; 8192]);
loop {
let count = read_retrying(&mut file, &mut chunk[..])?;
if count == 0 {
break;
}
let end = offset
.checked_add(count)
.filter(|end| data.get(offset..*end) == Some(&chunk[..count]))
.ok_or_else(|| invalid_data("file readback mismatch"))?;
offset = end;
}
if offset != data.len() {
return Err(invalid_data("file readback length mismatch"));
}
Ok(())
}
/// Read a secret file of at most `max_len` bytes into one buffer that is
/// allocated up front and wiped on drop, so neither growth nor a failed read
/// leaves a copy behind. A longer file is refused with `InvalidData` once
/// `max_len + 1` bytes have been read.
pub fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
let mut file = fs::File::open(path)?;
let mut data = Zeroizing::new(vec![0u8; max_len.saturating_add(1)]);
let mut filled = 0;
while filled < data.len() {
match read_retrying(&mut file, &mut data[filled..])? {
0 => break,
count => filled += count,
}
}
if filled > max_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("file exceeds {max_len}-byte limit"),
));
}
data.truncate(filled);
Ok(data)
}
/// A msgpack byte field read from a secret file. Binary and string values
/// borrow from a slice input; integer arrays fill a buffer reserved once (at
/// most `MAX` bytes) and wiped on drop, so neither growth nor a failed decode
/// leaves a copy behind.
pub(crate) enum SecretBytes<'a, const MAX: usize> {
Borrowed(&'a [u8]),
Owned(Zeroizing<Vec<u8>>),
}
impl<const MAX: usize> std::ops::Deref for SecretBytes<'_, MAX> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
Self::Borrowed(bytes) => bytes,
Self::Owned(bytes) => bytes,
}
}
}
impl<'de: 'a, 'a, const MAX: usize> serde::Deserialize<'de> for SecretBytes<'a, MAX> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_bytes(SecretBytesVisitor::<MAX>)
}
}
struct SecretBytesVisitor<const MAX: usize>;
impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor<MAX> {
type Value = SecretBytes<'de, MAX>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a byte array")
}
fn visit_borrowed_bytes<E: serde::de::Error>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(bytes))
}
fn visit_borrowed_str<E: serde::de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(text.as_bytes()))
}
fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes.to_vec())))
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
self.visit_bytes(text.as_bytes())
}
fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes)))
}
fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Self::Value, E> {
self.visit_byte_buf(text.into_bytes())
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let capacity = seq.size_hint().unwrap_or(0).min(MAX);
let mut bytes = Zeroizing::new(Vec::with_capacity(capacity));
while let Some(byte) = seq.next_element::<u8>()? {
if bytes.len() == capacity {
return Err(serde::de::Error::invalid_length(capacity + 1, &self));
}
bytes.push(byte);
}
Ok(SecretBytes::Owned(bytes))
}
}
@@ -91,22 +209,12 @@ fn fail_if(stage: InjectedFailure, injected: Option<InjectedFailure>) -> std::io
/// the rename the parent directory is fsynced best-effort so the directory
/// entry itself survives power loss.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
atomic_write_inner(path, data, None)
}
fn atomic_write_inner(
path: &Path,
data: &[u8],
injected: Option<InjectedFailure>,
) -> std::io::Result<()> {
let _write_guard = ATOMIC_WRITE_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp_path = unique_temp_path(path)?;
let result = (|| {
fail_if(InjectedFailure::Create, injected)?;
#[cfg(unix)]
let mut f = {
use std::os::unix::fs::OpenOptionsExt;
@@ -122,32 +230,14 @@ fn atomic_write_inner(
.create_new(true)
.open(&tmp_path)?;
fail_if(InjectedFailure::Write, injected)?;
f.write_all(data)?;
fail_if(InjectedFailure::Flush, injected)?;
f.flush()?;
fail_if(InjectedFailure::Sync, injected)?;
f.sync_all()?;
drop(f);
fail_if(InjectedFailure::VerifyTemp, injected)?;
let temp_data = read_file_bounded(&tmp_path, data.len())?
.ok_or_else(|| invalid_data("atomic-write temp file disappeared"))?;
if temp_data != data {
return Err(invalid_data("atomic-write temp verification failed"));
}
fail_if(InjectedFailure::Rename, injected)?;
verify_bytes(&tmp_path, data)?;
atomic_replace(&tmp_path, path)?;
fail_if(InjectedFailure::VerifyFinal, injected)?;
let final_data = read_file_bounded(path, data.len())?
.ok_or_else(|| invalid_data("atomic-write target disappeared"))?;
if final_data != data {
return Err(invalid_data("atomic-write final verification failed"));
}
verify_bytes(path, data)?;
#[cfg(unix)]
if let Some(dir) = path.parent()
@@ -203,7 +293,7 @@ mod tests {
use super::*;
use std::path::PathBuf;
fn unique_test_dir(label: &str) -> PathBuf {
pub(super) fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!(
@@ -257,43 +347,146 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Root ignores directory permissions.
#[cfg(unix)]
pub(super) fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
/// Holds the macOS user immutable flag (`chflags uchg`) on a file.
#[cfg(target_os = "macos")]
pub(super) struct Immutable(PathBuf);
#[cfg(target_os = "macos")]
impl Immutable {
pub(super) fn new(path: &Path) -> Self {
Self::set(path, libc::UF_IMMUTABLE);
Self(path.to_path_buf())
}
fn set(path: &Path, flags: libc::c_uint) {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::chflags(path.as_ptr(), flags) }, 0);
}
}
#[cfg(target_os = "macos")]
impl Drop for Immutable {
fn drop(&mut self) {
Self::set(&self.0, 0);
}
}
#[test]
fn test_atomic_write_faults_before_rename_preserve_previous_file() {
let dir = unique_test_dir("atomic-faults");
fn atomic_write_into_a_missing_directory_fails_without_creating_it() {
let dir = unique_test_dir("atomic-missing-parent");
let err = atomic_write(&dir.join("state"), b"candidate").unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
assert!(!dir.exists());
}
#[cfg(unix)]
#[test]
fn atomic_write_in_a_read_only_directory_keeps_the_previous_file() {
use std::os::unix::fs::PermissionsExt;
if is_root() {
return;
}
let dir = unique_test_dir("atomic-read-only");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
fs::set_permissions(&dir, fs::Permissions::from_mode(0o500)).unwrap();
for stage in [
InjectedFailure::Create,
InjectedFailure::Write,
InjectedFailure::Flush,
InjectedFailure::Sync,
InjectedFailure::VerifyTemp,
InjectedFailure::Rename,
let result = atomic_write(&path, b"candidate");
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
assert_eq!(
result.unwrap_err().kind(),
std::io::ErrorKind::PermissionDenied
);
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn atomic_write_onto_a_directory_leaves_it_and_no_temporary_file() {
let dir = unique_test_dir("atomic-directory-target");
let target = dir.join("state");
fs::create_dir_all(&target).unwrap();
fs::write(target.join("kept"), b"kept").unwrap();
assert!(atomic_write(&target, b"candidate").is_err());
assert_eq!(fs::read(target.join("kept")).unwrap(), b"kept");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(target_os = "macos")]
#[test]
fn atomic_write_onto_an_immutable_file_keeps_it() {
let dir = unique_test_dir("atomic-immutable");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let immutable = Immutable::new(&path);
let result = atomic_write(&path, b"candidate");
drop(immutable);
assert!(result.is_err());
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn readback_verification_rejects_changed_short_and_long_files() {
let dir = unique_test_dir("readback");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
let data: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
fs::write(&path, &data).unwrap();
verify_bytes(&path, &data).unwrap();
let mut changed = data.clone();
changed[12_345] ^= 1;
for (name, contents) in [
("changed", changed),
("short", data[..data.len() - 1].to_vec()),
("long", [&data[..], b"!"].concat()),
("empty", Vec::new()),
] {
let err = atomic_write_inner(&path, b"candidate", Some(stage)).unwrap_err();
assert!(err.to_string().contains("injected"));
assert_eq!(fs::read(&path).unwrap(), b"previous", "stage {stage:?}");
fs::write(&path, contents).unwrap();
let err = verify_bytes(&path, &data).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{name}");
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_atomic_write_final_readback_failure_is_reported() {
let dir = unique_test_dir("atomic-readback-fault");
fn secret_reads_are_bounded() {
let dir = unique_test_dir("secret-read");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let path = dir.join("secret");
let err = atomic_write_inner(&path, b"candidate", Some(InjectedFailure::VerifyFinal))
.unwrap_err();
assert!(err.to_string().contains("injected"));
fs::write(&path, [0xA5; 64]).unwrap();
assert_eq!(&read_secret_file(&path, 64).unwrap()[..], &[0xA5; 64]);
assert_eq!(
fs::read(&path).unwrap(),
b"candidate",
"the caller must not commit live state even if replacement reached disk"
read_secret_file(&path, 63).unwrap_err().kind(),
std::io::ErrorKind::InvalidData
);
fs::write(&path, b"").unwrap();
assert!(read_secret_file(&path, 64).unwrap().is_empty());
assert_eq!(
read_secret_file(&dir.join("missing"), 64)
.unwrap_err()
.kind(),
std::io::ErrorKind::NotFound
);
fs::remove_dir_all(dir).unwrap();
@@ -321,4 +514,87 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Feed `data` to `read` through a FIFO in two halves, signalling the
/// reading thread while it waits for the second. The handler is installed
/// without `SA_RESTART`, so that wait fails with EINTR.
#[cfg(unix)]
pub(super) fn read_through_a_signal<T: Send + 'static>(
label: &str,
data: &[u8],
read: impl FnOnce(&Path) -> std::io::Result<T> + Send + 'static,
) -> std::io::Result<T> {
use std::os::unix::ffi::OsStrExt;
extern "C" fn ignore(_: libc::c_int) {}
let dir = unique_test_dir(label);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("fifo");
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
unsafe {
assert_eq!(libc::mkfifo(c_path.as_ptr(), 0o600), 0);
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
libc::sigemptyset(&mut action.sa_mask);
assert_eq!(
libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
0
);
}
let (thread_tx, thread_rx) = std::sync::mpsc::channel();
let reader_path = path.clone();
let reader = std::thread::spawn(move || {
thread_tx
.send(unsafe { libc::pthread_self() } as usize)
.unwrap();
read(&reader_path)
});
let thread = thread_rx.recv().unwrap() as libc::pthread_t;
let mut fifo = fs::OpenOptions::new().write(true).open(&path).unwrap();
let (first, second) = data.split_at(data.len() / 2);
fifo.write_all(first).unwrap();
for _ in 0..5 {
std::thread::sleep(std::time::Duration::from_millis(20));
unsafe { libc::pthread_kill(thread, libc::SIGUSR1) };
}
// A reader that gave up has closed its end.
let _ = fifo.write_all(second);
drop(fifo);
// Fail instead of hanging if another descriptor still holds the writer.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !reader.is_finished() {
assert!(
std::time::Instant::now() < deadline,
"reader of {} saw no EOF 30 s after the writer closed",
path.display()
);
std::thread::sleep(std::time::Duration::from_millis(1));
}
let result = reader.join().unwrap();
fs::remove_dir_all(dir).unwrap();
result
}
#[cfg(unix)]
#[test]
fn readback_verification_retries_an_interrupted_read() {
let data = vec![0x5a; 64];
let expected = data.clone();
let result = read_through_a_signal("verify-interrupted", &data, move |path| {
verify_bytes(path, &expected)
});
assert!(result.is_ok(), "{result:?}");
}
#[cfg(unix)]
#[test]
fn secret_file_read_retries_an_interrupted_read() {
let data = vec![0xa5; 64];
let read = read_through_a_signal("secret-read-interrupted", &data, |path| {
read_secret_file(path, 1024)
});
assert_eq!(read.unwrap()[..], data[..]);
}
}
@@ -0,0 +1,72 @@
//! Nonblocking OS file-lock portability. Android's standard-library File lock
//! implementation is unsupported on some supported toolchains; bionic flock
//! provides the same retained-open-file-description ownership on that target.
use std::fs::File;
use std::io;
/// Take an exclusive advisory lock without waiting. Retain the original file
/// for the complete protected operation; do not clone/close handles to transfer
/// ownership since duplication semantics differ by platform. Closing the owning
/// handles (including on process exit) releases the lock. Contention is
/// `WouldBlock`, and unsupported or failed backends are errors, never success.
/// Do not delete/recreate the lock file while an owner may still hold it.
pub fn try_lock_exclusive(file: &File) -> io::Result<()> {
#[cfg(target_os = "android")]
{
use std::os::fd::AsRawFd;
// SAFETY: the borrowed File keeps its descriptor alive for this call;
// flock neither takes ownership nor writes through any Rust pointer.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(target_os = "android"))]
file.try_lock().map_err(|error| match error {
std::fs::TryLockError::WouldBlock => {
io::Error::new(io::ErrorKind::WouldBlock, "file is locked by another owner")
}
std::fs::TryLockError::Error(error) => error,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn lock_files() -> (std::path::PathBuf, File, File) {
let path = super::super::tests::unique_test_dir("native-lock");
let first = File::create_new(&path).unwrap();
let second = File::options().read(true).write(true).open(&path).unwrap();
(path, first, second)
}
#[test]
fn native_file_lock_contends_and_releases_on_drop() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(first);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
#[cfg(unix)]
#[test]
fn native_file_lock_duplicate_keeps_exclusion_until_last_close() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
let retained = first.try_clone().unwrap();
drop(first);
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(retained);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
}
File diff suppressed because it is too large. Load diff
+108 -64
View File
@@ -8,7 +8,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::{Zeroize, Zeroizing};
use crate::identity::Identity;
use crate::persistence;
use crate::persistence::{self, SecretBytes};
const RATCHET_FILE_MAX_BYTES: usize = 64 * 1024;
const RATCHET_PACKED_MAX_BYTES: usize = 32 * 1024;
@@ -30,25 +30,38 @@ fn pack_ratchet_keys(keys: &[[u8; 32]]) -> std::io::Result<Zeroizing<Vec<u8>>> {
.iter()
.map(|key| serde_bytes::Bytes::new(key))
.collect();
let packed = Zeroizing::new(
rmp_serde::to_vec(&byte_keys).map_err(|e| std::io::Error::other(e.to_string()))?,
);
// Sized up front: a growing buffer would free copies of the keys.
let mut packed = Zeroizing::new(Vec::with_capacity(RATCHET_PACKED_MAX_BYTES));
rmp_serde::encode::write(&mut *packed, &byte_keys)
.map_err(|e| std::io::Error::other(e.to_string()))?;
if packed.len() > RATCHET_PACKED_MAX_BYTES {
return Err(invalid_data("packed ratchet ring exceeds size limit"));
}
Ok(packed)
}
fn encode_ring_file(signature: &[u8; 64], packed: &[u8]) -> std::io::Result<Zeroizing<Vec<u8>>> {
let persisted = RatchetRingPersistedWrite {
signature,
ratchets: packed,
};
// Sized up front: a growing buffer would free copies of the keys.
let mut buf = Zeroizing::new(Vec::with_capacity(RATCHET_FILE_MAX_BYTES));
rmp_serde::encode::write_named(&mut *buf, &persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?;
if buf.len() > RATCHET_FILE_MAX_BYTES {
return Err(invalid_data("ratchet ring file exceeds size limit"));
}
Ok(buf)
}
fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result<Vec<[u8; 32]>> {
if packed.len() > RATCHET_PACKED_MAX_BYTES {
return Err(invalid_data("packed ratchet ring exceeds size limit"));
}
let mut encoded_keys: Vec<serde_bytes::ByteBuf> =
let encoded_keys: Vec<SecretBytes<'_, RATCHET_PACKED_MAX_BYTES>> =
rmp_serde::from_slice(packed).map_err(|e| std::io::Error::other(e.to_string()))?;
if encoded_keys.len() > RATCHET_COUNT {
for key in &mut encoded_keys {
key.as_mut().zeroize();
}
return Err(invalid_data(format!(
"ratchet ring contains {} keys; maximum is {RATCHET_COUNT}",
encoded_keys.len()
@@ -56,18 +69,13 @@ fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result<Vec<[u8; 32]>> {
}
if encoded_keys.iter().any(|key| key.len() != 32) {
for key in &mut encoded_keys {
key.as_mut().zeroize();
}
return Err(invalid_data("ratchet private key must be exactly 32 bytes"));
}
let mut keys = Vec::with_capacity(RATCHET_COUNT);
for encoded in &mut encoded_keys {
let mut key = [0u8; 32];
keys.resize(encoded_keys.len(), [0u8; 32]);
for (key, encoded) in keys.iter_mut().zip(&encoded_keys) {
key.copy_from_slice(encoded);
keys.push(key);
encoded.as_mut().zeroize();
}
Ok(keys)
}
@@ -287,24 +295,28 @@ impl RatchetRing {
/// should prefer [`Self::save_verified`], which cannot sign the wrong data.
pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> {
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
signature: signature.to_vec(),
ratchets: ratchets_packed.to_vec(),
});
let buf = Zeroizing::new(
rmp_serde::to_vec_named(&*persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?,
);
if buf.len() > RATCHET_FILE_MAX_BYTES {
return Err(invalid_data("ratchet ring file exceeds size limit"));
}
let buf = encode_ring_file(signature, &ratchets_packed)?;
persistence::atomic_write(path, &buf)
}
/// Sign the packed key list with `identity`, persist it, and verify the
/// final bytes before returning.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, false)
}
/// Acknowledge only the platform's strict file and namespace barriers.
/// An uncertain publication is an error, never a successful checkpoint.
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, true)
}
fn save_verified_impl(
&self,
path: &Path,
identity: &Identity,
durable: bool,
) -> std::io::Result<()> {
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
let signature = identity.sign(&ratchets_packed).ok_or_else(|| {
std::io::Error::new(
@@ -313,18 +325,14 @@ impl RatchetRing {
)
})?;
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
signature: signature.to_vec(),
ratchets: ratchets_packed.to_vec(),
});
let buf = Zeroizing::new(
rmp_serde::to_vec_named(&*persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?,
);
if buf.len() > RATCHET_FILE_MAX_BYTES {
return Err(invalid_data("ratchet ring file exceeds size limit"));
let buf = encode_ring_file(&signature, &ratchets_packed)?;
if durable {
persistence::durable_write(path, &buf)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &buf)
}
persistence::atomic_write(path, &buf)
}
/// Load the ring, retrying with 1s/2s/4s backoff to ride out transient
@@ -338,8 +346,9 @@ impl RatchetRing {
std::thread::sleep(std::time::Duration::from_millis(*delay));
}
match Self::try_load(path) {
Ok(decoded) => return Ok((decoded.ring, decoded.signature)),
let data = persistence::read_secret_file(path, RATCHET_FILE_MAX_BYTES);
match data.and_then(|data| Self::decode(&data).map(|d| (d.ring, d.signature))) {
Ok(loaded) => return Ok(loaded),
Err(e) => {
if attempt < delays_ms.len() - 1 {
tracing::warn!(
@@ -363,7 +372,8 @@ impl RatchetRing {
/// files are accepted only when their old current-public-key signature is
/// valid; their unsigned rotation timestamp is deliberately ignored.
pub fn load_verified(path: &Path, identity: &Identity) -> std::io::Result<LoadedRatchetRing> {
let decoded = Self::try_load(path)?;
let data = persistence::read_secret_file(path, RATCHET_FILE_MAX_BYTES)?;
let decoded = Self::decode(&data)?;
let format = if identity.verify(&decoded.packed, &decoded.signature) {
RatchetRingFormat::Canonical
@@ -384,14 +394,9 @@ impl RatchetRing {
})
}
fn try_load(path: &Path) -> std::io::Result<DecodedRatchetRing> {
let data = Zeroizing::new(
persistence::read_file_bounded(path, RATCHET_FILE_MAX_BYTES)?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
);
fn decode(data: &[u8]) -> std::io::Result<DecodedRatchetRing<'_>> {
let persisted: RatchetRingPersistedRead =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
rmp_serde::from_slice(data).map_err(|e| std::io::Error::other(e.to_string()))?;
if persisted.signature.len() != 64 {
return Err(std::io::Error::new(
@@ -403,7 +408,7 @@ impl RatchetRing {
let mut signature = [0u8; 64];
signature.copy_from_slice(&persisted.signature);
let packed = Zeroizing::new(persisted.ratchets);
let packed = persisted.ratchets;
let keys = unpack_ratchet_keys(&packed)?;
let had_legacy_rotation = persisted.last_rotation.is_some();
@@ -528,11 +533,11 @@ impl PersistentRatchetRing {
}
}
struct DecodedRatchetRing {
struct DecodedRatchetRing<'a> {
ring: RatchetRing,
signature: [u8; 64],
had_legacy_rotation: bool,
packed: Zeroizing<Vec<u8>>,
packed: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
}
/// A rotation candidate owns a duplicate secret ring and zeroises it on drop
@@ -552,20 +557,20 @@ impl PreparedRatchetRotation {
}
}
#[derive(Serialize, Zeroize)]
struct RatchetRingPersistedWrite {
#[derive(Serialize)]
struct RatchetRingPersistedWrite<'a> {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
signature: &'a [u8; 64],
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
ratchets: &'a [u8],
}
#[derive(Deserialize)]
struct RatchetRingPersistedRead {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
struct RatchetRingPersistedRead<'a> {
#[serde(borrow)]
signature: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
#[serde(borrow)]
ratchets: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
#[serde(default)]
last_rotation: Option<f64>,
}
@@ -638,6 +643,19 @@ impl ReceivedRatchet {
/// Persist to `{ratchetdir}/{hex(dest_hash)}` in the shared msgpack format.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
self.save_impl(path, false)
}
/// Persist a received public ratchet with strict platform barriers.
///
/// The caller must establish the complete parent namespace with the strict
/// directory helpers before publishing or checkpointing cryptographic state.
/// Unlike the legacy cache writer, this method never creates missing parents.
pub fn save_durable(&self, path: &Path) -> std::io::Result<()> {
self.save_impl(path, true)
}
fn save_impl(&self, path: &Path, durable: bool) -> std::io::Result<()> {
let persisted = ReceivedRatchetPersisted {
ratchet: self.ratchet_pub.to_vec(),
received: self.received_at,
@@ -645,11 +663,17 @@ impl ReceivedRatchet {
let buf = rmp_serde::to_vec_named(&persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?;
if let Some(parent) = path.parent() {
if !durable && let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
persistence::atomic_write(path, &buf)
if durable {
persistence::durable_write(path, &buf)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &buf)
}
}
pub fn load(path: &Path) -> std::io::Result<Self> {
@@ -1122,8 +1146,8 @@ mod tests {
let keys = vec![[0x44; 32]; RATCHET_COUNT + 1];
let packed = rmp_serde::to_vec(&keys).unwrap();
let envelope = RatchetRingPersistedWrite {
signature: vec![0u8; 64],
ratchets: packed,
signature: &[0u8; 64],
ratchets: &packed,
};
std::fs::write(&path, rmp_serde::to_vec_named(&envelope).unwrap()).unwrap();
assert_eq!(
@@ -1196,6 +1220,26 @@ mod tests {
assert_eq!(ring.ratchet_interval(), 60);
}
#[test]
fn strict_received_ratchet_refuses_missing_namespace_without_creating_it() {
let dir = std::env::temp_dir().join(format!(
"reticulum-received-strict-{}",
hex::encode(rns_crypto::random::random_32())
));
let path = dir.join("identity/ratchets/received/peer");
let received = ReceivedRatchet::new_at([7; 32], 100.);
assert!(received.save_durable(&path).is_err());
assert!(
!dir.exists(),
"strict writes must not create weak parent entries"
);
// The legacy, non-acknowledged cache API keeps its historical behavior.
received.save(&path).unwrap();
assert_eq!(ReceivedRatchet::load(&path).unwrap().ratchet_pub, [7; 32]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_received_ratchet_msgpack_roundtrip() {
let dir = std::env::temp_dir().join("reticulum_recv_ratchet_test");
@@ -0,0 +1,100 @@
//! Writes beyond the process file-size limit fail with EFBIG and keep the
//! previous file. Each test re-runs itself in a child with a lowered limit.
//! Spawning stays out of the unit-test binary: until a child execs it holds
//! copies of all its parent's descriptors, close-on-exec ones included, so a
//! sibling test's lock or FIFO end would outlive that test's close.
#![cfg(unix)]
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use rns_identity::persistence::{DurableCommitPhase, atomic_write, durable_write};
fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"reticulum-{label}-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
NEXT_ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
dir
}
/// Re-run `test` in a child process whose files are limited to `limit`
/// bytes, with SIGXFSZ ignored so a longer write fails with EFBIG. Returns
/// true in the child, which then runs the test body.
fn in_file_size_limited_child(test: &str, limit: u64) -> bool {
const CHILD: &str = "RNS_FILE_SIZE_LIMITED_CHILD";
if std::env::var_os(CHILD).is_some() {
unsafe {
libc::signal(libc::SIGXFSZ, libc::SIG_IGN);
let mut current = std::mem::zeroed::<libc::rlimit>();
assert_eq!(libc::getrlimit(libc::RLIMIT_FSIZE, &mut current), 0);
current.rlim_cur = limit as libc::rlim_t;
assert_eq!(libc::setrlimit(libc::RLIMIT_FSIZE, &current), 0);
}
return true;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([test, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"file-size-limited child failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
false
}
#[test]
fn atomic_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"atomic_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let dir = unique_test_dir("atomic-file-size");
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let err = atomic_write(&path, &[0x5a; 16384]).unwrap_err();
assert_eq!(err.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn strict_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"strict_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let root = unique_test_dir("durable-file-size");
let target = root.join("state");
durable_write(&target, b"old").unwrap();
let failure = durable_write(&target, &[0x5a; 16384]).unwrap_err();
assert_eq!(failure.phase, DurableCommitPhase::NotCommitted);
let source = std::error::Error::source(&failure)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.unwrap();
assert_eq!(source.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&target).unwrap(), b"old");
assert_eq!(failure.recovery_paths.len(), 2);
fs::remove_dir_all(root).unwrap();
}
+424
View File
@@ -0,0 +1,424 @@
//! Private keys, derived keys and plaintext must not survive in freed heap
//! memory when identities are stored, loaded and used.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
use rns_identity::ifac::derive_ifac_key;
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
use zeroize::Zeroizing;
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let path = std::env::temp_dir().join(format!(
"rns-residue-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn derived_key(private: &[u8; 32], ephemeral_public: &[u8], salt: &[u8]) -> Zeroizing<Vec<u8>> {
let private = X25519PrivateKey::from_bytes(private);
let public = X25519PublicKey::from_bytes(ephemeral_public.try_into().unwrap());
let shared = Zeroizing::new(private.exchange(&public));
hkdf_sha256(64, &*shared, Some(salt), None).unwrap()
}
#[test]
fn identity_to_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("to-file");
let key: [u8; 64] = pseudo_random(11);
let identity = Identity::from_private_key(&key).unwrap();
let path = dir.0.join("identity");
let ((), freed) = freed_by(|| identity.to_file(&path).unwrap());
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(std::fs::read(&path).unwrap(), key);
}
#[test]
fn identity_from_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file");
let key: [u8; 64] = pseudo_random(12);
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_file_with_a_msgpack_looking_key_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file-msgpack-prefix");
// A one-field array holding a long integer array: a parse of this key as
// an envelope runs out of input partway through.
let mut key = [0u8; 64];
key[..4].copy_from_slice(&[0x91, 0xdc, 0xff, 0xff]);
let tail: [u8; 60] = pseudo_random(13);
for (out, byte) in key[4..].iter_mut().zip(tail) {
*out = byte & 0x7f;
}
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key[4..])]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_envelope_file_frees_no_key() {
#[derive(serde::Serialize)]
struct Envelope {
private_key: Vec<u8>,
}
let _serial = serial();
let dir = TempDir::new("from-envelope");
let key: [u8; 64] = pseudo_random(14);
let expected = Identity::from_private_key(&key).unwrap().hash;
let envelope = Envelope {
private_key: key.to_vec(),
};
for (name, bytes) in [
("named", rmp_serde::to_vec_named(&envelope).unwrap()),
("compact", rmp_serde::to_vec(&envelope).unwrap()),
] {
let path = dir.0.join(name);
std::fs::write(&path, bytes).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(
&freed,
&[
("private key", &key),
("msgpack integers private key", &msgpack_integers(&key)),
],
);
assert_eq!(hash, expected, "{name} envelope");
}
}
#[test]
fn identity_from_file_refuses_an_oversize_file_without_reading_it_whole() {
let _serial = serial();
let dir = TempDir::new("from-file-oversize");
let path = dir.0.join("identity");
std::fs::write(&path, vec![0xc1; 1 << 20]).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert!(
freed.peak_allocation < 64 * 1024,
"loading allocated {} bytes",
freed.peak_allocation
);
}
#[test]
fn identity_encrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(15);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(16);
let (ciphertext, freed) = freed_by(|| identity.encrypt(&plaintext, None).unwrap());
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(17);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(18);
let ciphertext = identity.encrypt(&plaintext, None).unwrap();
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(identity.decrypt(&ciphertext, None, false).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_ratchet_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(19);
let identity = Identity::from_private_key(&key).unwrap();
let ratchet: [u8; 32] = pseudo_random(20);
let ratchet_public = X25519PrivateKey::from_bytes(&ratchet)
.public_key()
.to_bytes();
let plaintext: [u8; 100] = pseudo_random(21);
let ciphertext = identity.encrypt(&plaintext, Some(&ratchet_public)).unwrap();
let derived = derived_key(&ratchet, &ciphertext[..32], &identity.hash);
let ((), freed) = freed_by(|| {
let ratchets = [&ratchet];
let decrypted = identity
.decrypt_with_ratchet_id(&ciphertext, Some(&ratchets), true)
.unwrap();
let plaintext_copy = Zeroizing::new(decrypted.plaintext);
assert_eq!(&plaintext_copy[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[
("plaintext", &plaintext),
("derived key", &derived),
("ratchet key", &ratchet),
],
);
}
#[test]
fn ratchet_ring_save_and_load_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(22)).unwrap();
let mut ring = RatchetRing::new();
for _ in 0..200 {
ring.rotate();
}
let keys = Zeroizing::new(ring.private_keys().to_vec());
let path = dir.0.join("ratchets");
let ((), saved) = freed_by(|| ring.save_verified(&path, &identity).unwrap());
let ((), read) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let mut found = Vec::new();
for (stage, freed) in [("save", &saved), ("load", &read)] {
for residue in ratchet_key_residue(freed, &keys) {
found.push(format!("{stage}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn ifac_key_derivation_frees_no_key() {
let _serial = serial();
let passphrase = "correct horse battery staple";
let key = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
let ((), freed) = freed_by(|| {
let derived = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
assert_eq!(derived, key);
});
assert_no_residue(
&freed,
&[
("IFAC key", &key),
("passphrase hash", &sha256(passphrase.as_bytes())),
],
);
}
/// A key as msgpack writes it in an integer array: bytes above 0x7f carry a
/// 0xcc prefix.
fn msgpack_integers(key: &[u8]) -> Vec<u8> {
key.iter()
.flat_map(|&byte| {
if byte < 0x80 {
vec![byte]
} else {
vec![0xcc, byte]
}
})
.collect()
}
/// Ratchet keys found in freed blocks: raw, as packed in an integer array, and
/// as that packing appears again inside the file's integer array.
fn ratchet_key_residue(freed: &residue::Freed, keys: &[[u8; 32]]) -> Vec<String> {
type Encode = fn(&[u8]) -> Vec<u8>;
let forms: [(&str, Encode); 3] = [
("raw", |key| key.to_vec()),
("msgpack integers", msgpack_integers),
("nested msgpack integers", |key| {
msgpack_integers(&msgpack_integers(key))
}),
];
let mut found = Vec::new();
for (form, encode) in forms {
let encoded: Vec<Vec<u8>> = keys.iter().map(|key| encode(key)).collect();
let secrets: Vec<&[u8]> = encoded.iter().map(Vec::as_slice).collect();
let sizes: Vec<usize> = residue::find(&freed.blocks, &secrets)
.into_iter()
.map(|(len, _)| len)
.collect();
if !sizes.is_empty() {
found.push(format!(
"{form} ratchet keys in freed blocks of {sizes:?} bytes"
));
}
}
found
}
/// Releases before the canonical envelope wrote the packed ring and its keys
/// as msgpack integer arrays.
#[derive(serde::Serialize)]
struct LegacyRatchets<T> {
signature: Vec<u8>,
ratchets: Vec<u8>,
last_rotation: T,
}
fn legacy_keys(count: u64, seed: u64) -> Vec<[u8; 32]> {
(0..count).map(|i| pseudo_random(seed + i)).collect()
}
fn legacy_signature(identity: &Identity, keys: &[[u8; 32]]) -> Vec<u8> {
let current_public = X25519PrivateKey::from_bytes(&keys[0])
.public_key()
.to_bytes();
identity.sign(&current_public).unwrap().to_vec()
}
#[test]
fn legacy_ratchet_ring_load_frees_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(23)).unwrap();
let keys = legacy_keys(120, 1000);
let legacy = LegacyRatchets {
signature: legacy_signature(&identity, &keys),
ratchets: rmp_serde::to_vec(&keys).unwrap(),
last_rotation: 0.0,
};
let path = dir.0.join("ratchets");
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
let ((), freed) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let found = ratchet_key_residue(&freed, &keys);
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn failed_legacy_ratchet_ring_loads_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets-failed");
let identity = Identity::from_private_key(&pseudo_random::<64>(25)).unwrap();
// Few enough keys that the packed ring is decoded without regrowing.
let keys = legacy_keys(40, 2000);
let signature = legacy_signature(&identity, &keys);
let packed = rmp_serde::to_vec(&keys).unwrap();
assert_eq!(packed[..3], [0xdc, 0x00, 40]);
let mut short_packed = packed.clone();
short_packed[2] += 1;
let file = |signature: &[u8], ratchets: &[u8]| {
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.to_vec(),
ratchets: ratchets.to_vec(),
last_rotation: 0.0,
})
.unwrap()
};
let cases = [
("short signature", file(&signature[..63], &packed)),
(
"malformed rotation",
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.clone(),
ratchets: packed.clone(),
last_rotation: "never",
})
.unwrap(),
),
("missing key", file(&signature, &short_packed)),
];
let mut found = Vec::new();
for (case, bytes) in cases {
let path = dir.0.join(case.replace(' ', "-"));
std::fs::write(&path, bytes).unwrap();
let (result, freed) = freed_by(|| RatchetRing::load_verified(&path, &identity).map(drop));
assert!(result.is_err(), "{case}");
for residue in ratchet_key_residue(&freed, &keys) {
found.push(format!("{case}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn identity_from_a_truncated_envelope_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("truncated-envelope");
let mut key: [u8; 64] = pseudo_random(24);
for byte in &mut key {
*byte &= 0x7f;
}
// A one-field envelope declaring 65 key bytes and ending after 64.
let path = dir.0.join("identity");
std::fs::write(&path, [&[0x91, 0xdc, 0x00, 0x41][..], &key].concat()).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert_no_residue(&freed, &[("private key", &key)]);
}
+46 -11
View File
@@ -1,5 +1,6 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -15,7 +16,7 @@ use crate::android_usb_lifecycle::{
UsbReadDrainOutcome, UsbReadResult, UsbReaderBackend, UsbShutdownReport, UsbTransferError,
UsbTxGate, UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk,
resolve_usb_device, run_usb_rnode_capability_startup, run_usb_rnode_startup, run_usb_tx_pump,
spawn_owned_usb_io,
spawn_owned_usb_io, usb_bulk_read_size,
};
#[cfg(test)]
use crate::kiss;
@@ -663,6 +664,7 @@ struct JniUsbReader {
device_name: String,
attached: Arc<AtomicBool>,
idle_polls: u8,
read_size: i32,
}
struct PendingAndroidUsbOpen {
@@ -918,8 +920,8 @@ impl UsbReaderBackend for JniUsbReader {
if !self.attached.load(Ordering::Acquire) {
return Err("Android USB device detached".into());
}
let read_size = self.read_size;
with_env(|env| {
const READ_SIZE: i32 = 1_024;
let connection = self
.connection
.as_ref()
@@ -929,7 +931,7 @@ impl UsbReaderBackend for JniUsbReader {
.as_ref()
.ok_or("USB reader endpoint already released")?;
let buffer = env
.new_byte_array(READ_SIZE)
.new_byte_array(read_size)
.map_err(|error| jni_failure(env, "USB read buffer allocation", error))?;
let value = env
.call_method(
@@ -939,7 +941,7 @@ impl UsbReaderBackend for JniUsbReader {
&[
JValue::Object(endpoint.as_obj()),
JValue::Object(buffer.into()),
JValue::Int(READ_SIZE),
JValue::Int(read_size),
JValue::Int(USB_READ_TIMEOUT_MS),
],
)
@@ -991,9 +993,9 @@ impl UsbReaderBackend for JniUsbReader {
return Ok(UsbReadResult::Idle);
}
self.idle_polls = 0;
if read > READ_SIZE {
if read > read_size {
return Err(format!(
"USB bulk read returned invalid length {read} (capacity {READ_SIZE})"
"USB bulk read returned invalid length {read} (capacity {read_size})"
));
}
let bytes = env
@@ -1221,7 +1223,7 @@ fn open_usb_serial_attached(
attached: attached.clone(),
};
let setup = (|| -> Result<(GlobalRef, GlobalRef), String> {
let setup = (|| -> Result<(GlobalRef, GlobalRef, i32), String> {
// CDC-Data (0x0A) or vendor-specific (0xFF), with a matched
// IN/OUT endpoint pair from one interface.
let iface_count = env
@@ -1333,16 +1335,25 @@ fn open_usb_serial_attached(
}
clear_pending_jni_exception(env);
let max_packet_size = env
.call_method(ep_in, "getMaxPacketSize", "()I", &[])
.map_err(|error| jni_failure(env, "getMaxPacketSize", error))?
.i()
.map_err(|error| jni_failure(env, "USB endpoint packet size", error))?;
let input_endpoint = env
.new_global_ref(ep_in)
.map_err(|error| jni_failure(env, "USB input endpoint global reference", error))?;
let output_endpoint = env
.new_global_ref(ep_out)
.map_err(|error| jni_failure(env, "USB output endpoint global reference", error))?;
Ok((input_endpoint, output_endpoint))
Ok((
input_endpoint,
output_endpoint,
usb_bulk_read_size(max_packet_size),
))
})();
let (input_endpoint, output_endpoint) = match setup {
let (input_endpoint, output_endpoint, read_size) = match setup {
Ok(endpoints) => endpoints,
Err(error) => return Err(cleanup_failed_android_usb_open(owner, error)),
};
@@ -1371,6 +1382,7 @@ fn open_usb_serial_attached(
device_name: dev_name.to_string(),
attached,
idle_polls: 0,
read_size,
},
))
});
@@ -1597,6 +1609,8 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
transport_tx: mpsc::Sender<TransportMessage>,
options: RNodeStartupOptions,
) -> Result<SpawnedRNodeInterface, RNodeSpawnError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate_device_selector()?;
config.validate().map_err(|error| {
InterfaceError::SendFailed(format!("rnode config {}: {error}", error.field()))
@@ -1750,6 +1764,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
let mut stop_requested = false;
let mut drain_reader_tail = false;
let mut terminal_reason = RNodeRuntimeReason::ConnectionLost;
let mut configuration_rejected = None;
loop {
tokio::select! {
@@ -1853,7 +1868,21 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
outcome = forwarding => outcome,
};
match outcome {
UsbInboundOutcome::Complete => {}
UsbInboundOutcome::Complete => {
// Retrying settings the radio cannot use
// only fails again; shutdown detaches it.
if let Some(rejected) = inbound.definitive_rejection() {
tracing::warn!(
name = %read_name,
rejected = ?rejected,
"Android USB RNode rejected the configured settings"
);
configuration_rejected = Some(rejected);
terminal_reason =
RNodeRuntimeReason::ConfigurationRejected;
break;
}
}
UsbInboundOutcome::StopRequested => {
stop_requested = true;
terminal_reason = RNodeRuntimeReason::StopRequested;
@@ -1927,6 +1956,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
terminal_reason,
RNodeRuntimeReason::TransportConsumerClosed
| RNodeRuntimeReason::DriverTerminated
| RNodeRuntimeReason::ConfigurationRejected
);
if terminal {
inbound.shutting_down(terminal_reason);
@@ -1956,7 +1986,10 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
online_task.store(false, Ordering::SeqCst);
if terminal {
inbound.stopped(terminal_reason);
match configuration_rejected {
Some(rejected) => inbound.stopped_for_configuration_rejection(rejected),
None => inbound.stopped(terminal_reason),
}
shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report));
return;
}
@@ -2003,6 +2036,8 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
);
let interface = InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name,
mode: config.mode,
+180 -29
View File
@@ -22,8 +22,10 @@ use crate::rnode_capabilities::RNodeRadioAdmission;
use crate::rnode_capability_preflight::RNodeCapabilityPreflight;
use crate::rnode_protocol::{
RNodeProtocolFrame, RNodeProtocolState, RNodeProtocolTarget, RNodeReadiness,
RNodeReadinessEvidence,
};
use crate::traits::InterfaceId;
#[cfg(test)]
use rns_transport::messages::TransportMessage;
const MIN_TRANSFER_TIMEOUT: Duration = Duration::from_millis(1);
@@ -307,6 +309,18 @@ pub(crate) trait UsbReaderBackend: Send + 'static {
fn read(&mut self) -> Result<UsbReadResult, String>;
}
/// Bulk IN request size: exactly one max-size packet. A longer request stays
/// open when the device's data ends on a packet boundary without a ZLP, times
/// out, and usbdevfs then discards everything it had received.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) const fn usb_bulk_read_size(max_packet_size: i32) -> i32 {
if max_packet_size > 0 && max_packet_size <= 1_024 {
max_packet_size
} else {
64
}
}
pub(crate) enum UsbConnectionCleanup<O> {
Closed {
release_interface: Result<(), String>,
@@ -878,6 +892,26 @@ impl UsbInboundState {
}
}
/// The setting this generation's radio definitively rejected.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) fn definitive_rejection(&self) -> Option<RNodeReadinessEvidence> {
self.projection
.as_ref()
.and_then(|projection| projection.protocol.definitive_rejection())
}
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) fn stopped_for_configuration_rejection(&mut self, rejected: RNodeReadinessEvidence) {
if let Some(gate) = &self.tx_gate {
gate.close();
}
if let Some(projection) = self.projection.as_mut() {
projection
.publisher
.stopped_for_configuration_rejection(rejected);
}
}
/// Return the lifecycle publisher after one physical USB generation ends.
///
/// Framing and protocol evidence are intentionally generation-local, but
@@ -906,7 +940,7 @@ pub(crate) async fn forward_usb_read_chunk(
bytes: &[u8],
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
) -> UsbInboundOutcome {
forward_usb_read_chunk_inner(
@@ -926,7 +960,7 @@ async fn forward_usb_read_chunk_inner(
bytes: &[u8],
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
deadline: Option<tokio::time::Instant>,
) -> UsbInboundOutcome {
@@ -992,7 +1026,7 @@ pub(crate) async fn drain_usb_reader_tail(
state: &mut UsbInboundState,
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
deadline: tokio::time::Instant,
) -> UsbReadDrainOutcome {
@@ -1457,7 +1491,7 @@ pub(crate) async fn run_usb_rnode_startup<O: UsbConnectionLifecycle>(
// admission, without making ROM availability a normal-startup requirement.
// Preserve only detect/firmware evidence; queued RF echoes, READY permits,
// DATA and partial framing cannot establish post-init operational readiness.
let mut protocol = RNodeProtocolState::new(target);
let mut protocol = RNodeProtocolState::with_effective_settings(target);
let mut deframer = kiss::RawKissDeframer::new();
let mut observe = |event| -> Result<(), UsbWriteFailure> {
let UsbIoEvent::Read(bytes) = event else {
@@ -2195,6 +2229,15 @@ where
mod tests {
use super::*;
#[test]
fn bulk_reads_request_exactly_one_max_size_packet() {
assert_eq!(usb_bulk_read_size(64), 64);
assert_eq!(usb_bulk_read_size(512), 512);
assert_eq!(usb_bulk_read_size(0), 64);
assert_eq!(usb_bulk_read_size(-1), 64);
assert_eq!(usb_bulk_read_size(4_096), 64);
}
fn usb_candidate(
device_name: &str,
vendor_id: u16,
@@ -2577,7 +2620,7 @@ mod tests {
&framed_protocol_frames(evidence),
1,
&AtomicU64::new(0),
&transport,
&crate::traits::test_registered_sender(1, transport.clone()),
&mut inbound_stop
)
.await,
@@ -2907,12 +2950,14 @@ mod tests {
kiss::frame_with_command_into(rnode::CMD_RESET, &[0xF8], &mut bytes);
kiss::frame_with_command_into(kiss::CMD_DATA, &[1, 2, 3], &mut bytes);
let received = AtomicU64::new(0);
let bound_transport = crate::traits::test_registered_sender(1, transport.clone());
let episode_start = tokio::time::Instant::now();
tokio::time::timeout(USB_PROTOCOL_READINESS_DEADLINE * 2, async {
tokio::select! {
exit = pump => assert_eq!(exit.unwrap(), UsbTxPumpExit::ReadinessTimedOut),
result = forward_usb_read_chunk(
&mut inbound, &bytes, 1, &received, &transport, &mut inbound_stop_rx
&mut inbound, &bytes, 1, &received,
&bound_transport, &mut inbound_stop_rx
) => panic!("full transport queue cannot conclude before pump expiry: {result:?}"),
}
})
@@ -3284,6 +3329,69 @@ mod tests {
.await;
}
/// A cold amplifier board echoes the requested power, then its floor once
/// on: the generation must report a terminal rejection and never open TX.
#[tokio::test]
async fn effective_usb_generation_reports_a_definitive_rejection() {
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 2);
let (mut publisher, driver) =
rnode::new_rnode_driver_observation(rnode::RNodeTransportClass::Usb);
publisher.connection_established();
let mut inbound = UsbInboundState::projected_with_protocol_state(
RNodeProtocolState::with_effective_settings(target),
publisher,
);
let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false)));
inbound.attach_tx_gate(gate.clone());
let (_stop_tx, mut stop_rx) = mpsc::channel(1);
let (transport_tx, _transport_rx) = mpsc::channel(1);
let mut floor = post_radio_on_echoes(target);
floor[2] = (rnode::CMD_TXPOWER, vec![13]);
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(required_protocol_frames(target)),
0x88,
&AtomicU64::new(0),
&crate::traits::test_registered_sender(0x88, transport_tx.clone()),
&mut stop_rx,
)
.await,
UsbInboundOutcome::Complete
);
assert_eq!(inbound.definitive_rejection(), None);
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(floor),
0x88,
&AtomicU64::new(0),
&crate::traits::test_registered_sender(0x88, transport_tx),
&mut stop_rx,
)
.await,
UsbInboundOutcome::Complete
);
assert_eq!(
inbound.definitive_rejection(),
Some(RNodeReadinessEvidence::TransmitPower)
);
assert!(!gate.can_send());
inbound.stopped_for_configuration_rejection(RNodeReadinessEvidence::TransmitPower);
let stopped = driver.snapshot();
assert_eq!(stopped.phase, rnode::RNodeRuntimePhase::Stopped);
assert_eq!(
stopped.reason,
Some(rnode::RNodeRuntimeReason::ConfigurationRejected)
);
assert_eq!(
stopped.configuration_rejection,
Some(RNodeReadinessEvidence::TransmitPower)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ordinary_usb_startup_discards_preinit_rf_ready_and_partial_frames() {
struct PreinitReader(Option<Vec<u8>>);
@@ -3336,6 +3444,7 @@ mod tests {
for (command, frame) in required_protocol_frames(USB_TEST_TARGET)
.into_iter()
.skip(2)
.chain(post_radio_on_echoes(USB_TEST_TARGET))
{
inbound.project_frame(command, &frame);
}
@@ -3370,6 +3479,22 @@ mod tests {
]
}
/// What RNode firmware echoes for the settings re-asserted after
/// `RADIO_STATE_ON` when the hardware uses them as requested.
fn post_radio_on_echoes(target: RNodeProtocolTarget) -> [(u8, Vec<u8>); 3] {
[
(
rnode::CMD_FREQUENCY,
target.frequency.to_be_bytes().to_vec(),
),
(
rnode::CMD_BANDWIDTH,
target.bandwidth.to_be_bytes().to_vec(),
),
(rnode::CMD_TXPOWER, vec![target.tx_power]),
]
}
fn framed_protocol_frames(frames: impl IntoIterator<Item = (u8, Vec<u8>)>) -> Vec<u8> {
let mut wire = Vec::new();
for (command, payload) in frames {
@@ -3784,7 +3909,7 @@ mod tests {
&[0xBB, kiss::FEND],
0x66,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x66, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -3796,10 +3921,14 @@ mod tests {
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(required_protocol_frames(target)),
&framed_protocol_frames(
required_protocol_frames(target)
.into_iter()
.chain(post_radio_on_echoes(target))
),
0x66,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x66, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -3919,8 +4048,12 @@ mod tests {
let stale_enqueued = Arc::new(AtomicBool::new(false));
let response = capability_response(0xB8);
let stale_rf = framed_protocol_frames(required_protocol_frames(target).into_iter().skip(2));
let post_init =
framed_protocol_frames(required_protocol_frames(target).into_iter().skip(2));
let post_init = framed_protocol_frames(
required_protocol_frames(target)
.into_iter()
.skip(2)
.chain(post_radio_on_echoes(target)),
);
let reader = SeparateStaleReader {
writer_calls: calls.clone(),
capability_reads: response.chunks(512).map(|chunk| chunk.to_vec()).collect(),
@@ -3995,7 +4128,7 @@ mod tests {
&bytes,
0x77,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(0x77, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4027,7 +4160,7 @@ mod tests {
chunk,
0x55,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x55, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4042,7 +4175,12 @@ mod tests {
snapshot.configuration,
rnode::RNodeConfigurationState::Verified
);
match transport_rx.recv().await.expect("projected packet") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("projected packet")
{
TransportMessage::Inbound(packet) => {
assert_eq!(packet.raw.as_ref(), payload);
assert_eq!(packet.interface_id, 0x55);
@@ -4077,7 +4215,7 @@ mod tests {
&wire,
7,
&received,
&transport_tx,
&crate::traits::test_registered_sender(7, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4104,7 +4242,7 @@ mod tests {
&ready_blocked,
8,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(8, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4146,7 +4284,7 @@ mod tests {
&mut inbound,
9,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(9, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
@@ -4212,7 +4350,7 @@ mod tests {
&late_detect,
10,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(10, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4656,7 +4794,7 @@ mod tests {
&kiss::frame(&[1, 2, 3]),
1,
&AtomicU64::new(0),
&forward_transport,
&crate::traits::test_registered_sender(1, forward_transport.clone()),
&mut forward_stop_rx,
)
.await
@@ -4836,7 +4974,7 @@ mod tests {
&kiss::frame(&[1, 3, 5]),
2,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(2, transport_tx.clone()),
&mut stop_rx,
),
)
@@ -4845,7 +4983,10 @@ mod tests {
UsbInboundOutcome::Complete
);
assert!(matches!(
transport_rx.recv().await,
transport_rx
.recv()
.await
.map(crate::traits::test_event_body),
Some(TransportMessage::Inbound(_))
));
@@ -4890,14 +5031,19 @@ mod tests {
&mut inbound,
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
.await,
UsbReadDrainOutcome::Drained
);
match transport_rx.recv().await.expect("forwarded packet") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("forwarded packet")
{
TransportMessage::Inbound(packet) => {
assert_eq!(packet.raw.as_ref(), payload);
assert_eq!(packet.interface_id, 77);
@@ -4914,7 +5060,7 @@ mod tests {
&kiss::frame(&second_payload),
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4962,7 +5108,7 @@ mod tests {
&mut UsbInboundState::new(),
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
deadline,
)
@@ -5124,7 +5270,7 @@ mod tests {
&bytes,
91,
&received,
&transport_tx,
&crate::traits::test_registered_sender(91, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -5139,7 +5285,7 @@ mod tests {
&mut inbound,
91,
&received,
&transport_tx,
&crate::traits::test_registered_sender(91, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
@@ -5155,7 +5301,12 @@ mod tests {
.await
.expect("simultaneous completion did not settle");
match transport_rx.recv().await.expect("forwarded reader tail") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("forwarded reader tail")
{
TransportMessage::Inbound(packet) => assert_eq!(packet.raw.as_ref(), [7, 8, 9]),
_ => panic!("unexpected transport message"),
}
@@ -5188,7 +5339,7 @@ mod tests {
&mut UsbInboundState::new(),
9,
&received,
&transport_tx,
&crate::traits::test_registered_sender(9, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
+5
View File
@@ -3,6 +3,7 @@
//! Beacons go to a multicast group derived from `SHA-256(group_id)` every
//! ~1.6 s; data flows over unicast UDP. Peers age out after 22 s of silence.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -1039,6 +1040,8 @@ pub async fn spawn_auto_interface(
transport_tx: mpsc::Sender<TransportMessage>,
is_foreground: Arc<AtomicBool>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let mcast_group = derive_multicast_address(
&config.group_id,
config.discovery_scope,
@@ -1761,6 +1764,8 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(1196, 1196, true),
parent_id: None,
name,
mode,
+6
View File
@@ -1,5 +1,7 @@
//! AX.25-over-KISS — prepends a UI header (src/dst call+SSID) and strips on RX.
#[cfg(feature = "serial")]
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
#[cfg(feature = "serial")]
use std::sync::Arc;
#[cfg(feature = "serial")]
@@ -232,6 +234,8 @@ pub async fn spawn_ax25kiss_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
})?;
@@ -406,6 +410,8 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
+75 -6
View File
@@ -4,6 +4,7 @@
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
//! malformed-peer memory blow-up.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -18,7 +19,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
@@ -102,6 +104,8 @@ pub struct BackboneClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Signs a tunnel synthesis for every connection; `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl BackboneClientConfig {
@@ -114,8 +118,19 @@ impl BackboneClientConfig {
connect_timeout_secs: INITIAL_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(BackboneClientInterface)` (BackboneInterface.py:1114-1117).
pub fn python_name(&self) -> String {
format!(
"BackboneInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone, Copy)]
@@ -359,7 +374,7 @@ fn child_mtu() -> u32 {
async fn backbone_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
@@ -515,6 +530,8 @@ fn spawn_backbone_server_on_listener(
fast_flap_runtime: FastFlapRuntime,
listener: TcpListener,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
@@ -582,8 +599,10 @@ fn spawn_backbone_server_on_listener(
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let transport_tx2 =
InterfaceTransportSender::new(client_id, transport_tx.actor_sender());
let child_owner = transport_tx2.owner();
let dereg_tx = transport_tx2.clone();
let cname = client_name.clone();
let active_client_guard =
ActiveClientGuard::new(Arc::clone(&task_active_clients));
@@ -601,6 +620,12 @@ fn spawn_backbone_server_on_listener(
let handle = InterfaceHandle {
id: client_id,
owner: child_owner,
packet_capacity: InterfacePacketCapacity::new(
child_mtu().min(262144),
262144,
true,
),
parent_id: Some(id),
name: client_name,
mode,
@@ -638,6 +663,8 @@ fn spawn_backbone_server_on_listener(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::base(500),
parent_id: None,
name,
mode,
@@ -663,6 +690,8 @@ pub async fn spawn_backbone_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(TX_CHANNEL_DEPTH);
@@ -675,11 +704,15 @@ pub async fn spawn_backbone_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let target = match tokio::time::timeout(
Duration::from_secs(config.connect_timeout_secs),
resolve_target(&config.target_host, config.target_port, config.prefer_ipv6),
@@ -755,8 +788,14 @@ pub async fn spawn_backbone_client(
};
tune_stream(&stream);
online2.store(true, Ordering::SeqCst);
tries = 0;
// Python synthesizes on every connection (BackboneInterface.py:922,
// :1019).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online2).await;
let c_online = Arc::new(AtomicBool::new(true));
let (reader, writer) = stream.into_split();
@@ -807,6 +846,8 @@ pub async fn spawn_backbone_client(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(child_mtu().min(262144), 262144, true),
parent_id: None,
name,
mode,
@@ -832,6 +873,26 @@ mod tests {
use super::*;
use std::net::{Ipv4Addr, SocketAddr};
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
(
"10.0.0.1",
"BackboneInterface[Golden Backbone/10.0.0.1:4243]",
),
(
"fd00::1",
"BackboneInterface[Golden Backbone/[fd00::1]:4243]",
),
] {
assert_eq!(
BackboneClientConfig::new("Golden Backbone", host, 4243).python_name(),
expected
);
}
}
#[derive(Clone)]
struct TestClock {
now: Arc<Mutex<Duration>>,
@@ -1238,6 +1299,7 @@ mod tests {
listener,
)
.unwrap();
parent.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let _stream = TcpStream::connect(listen_addr).await.unwrap();
@@ -1245,6 +1307,7 @@ mod tests {
.await
.expect("accepted child handle timed out")
.expect("child handle channel closed");
child.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(1));
clock.advance(Duration::from_millis(1));
child.read_task.abort();
@@ -1286,6 +1349,7 @@ mod tests {
listener,
)
.unwrap();
parent.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
@@ -1313,11 +1377,16 @@ mod tests {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(8);
let handle = spawn_backbone_client(cfg, 99, tx).await.unwrap();
handle.owner.mark_registered();
// Wait for the read_task to finish — guarded by a generous timeout
// to absorb the one RECONNECT_WAIT sleep + connect attempt.
let dereg = tokio::time::timeout(Duration::from_secs(15), async {
loop {
match rx.recv().await {
match rx
.recv()
.await
.map(|event| crate::traits::test_event_for_handle(event, &handle))
{
Some(TransportMessage::DeregisterInterface { id }) => return Some(id),
Some(_) => continue,
None => return None,
+19 -3
View File
@@ -29,6 +29,7 @@
//! Keepalive: 15s interval, 1-byte ping; 3 misses → disconnect. Cap 7
//! simultaneous peers.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -5188,7 +5189,7 @@ fn central_writer_key(address: &str) -> String {
))]
struct PeerReadLoopCtx {
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
peer_online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
peer_writers: PeerWriterRegistry,
@@ -5472,6 +5473,8 @@ pub async fn spawn_ble_peer_interface(
foreground_wake: Arc<tokio::sync::Notify>,
seed_addresses: Vec<String>,
) -> Result<InterfaceHandle, InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let name = config.name.clone();
// Reset the process-wide running flag and advance the session generation
@@ -6843,6 +6846,8 @@ pub async fn spawn_ble_peer_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 500, false),
parent_id: None,
name,
mode: config.mode,
@@ -6869,6 +6874,17 @@ pub async fn spawn_ble_peer_interface(
#[cfg(test)]
mod tests {
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
#[test]
fn remembered_candidates_obey_discovery_expiry_capacity_and_backoff() {
let recent = new_recently_disconnected();
@@ -6896,7 +6912,7 @@ mod tests {
recent.lock().unwrap().insert(
address.into(),
(
Instant::now() - RECONNECT_BACKOFF_DURATION,
ago_or_skip!(RECONNECT_BACKOFF_DURATION),
RECONNECT_BACKOFF_FAILURES,
),
);
@@ -6904,7 +6920,7 @@ mod tests {
recent
.lock()
.unwrap()
.insert(address.into(), (Instant::now() - RECONNECT_PRUNE_AFTER, 0));
.insert(address.into(), (ago_or_skip!(RECONNECT_PRUNE_AFTER), 0));
assert!(remembered_peer_candidate(&[], &connected, &recent).is_none());
}
+349 -16
View File
@@ -3,6 +3,7 @@
mod generation;
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -58,7 +59,9 @@ use crate::rnode::{
};
use crate::rnode_capabilities::RNodeRadioAdmission;
use crate::rnode_capability_preflight::{RNodeCapabilityPreflight, build_rnode_capability_request};
use crate::rnode_protocol::{RNodeProtocolState, RNodeProtocolTarget, RNodeReadiness};
use crate::rnode_protocol::{
RNodeProtocolState, RNodeProtocolTarget, RNodeReadiness, RNodeReadinessEvidence,
};
use crate::traits::{
InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode,
};
@@ -1613,6 +1616,33 @@ impl NativePendingOutbound {
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum NativeBridgeAttach {
Attached,
Closed,
Stopped,
}
/// Wait without a deadline for the bridge's first byte, which only an attached
/// GATT link produces. Nothing is consumed: the attach marker is an exact
/// zero-count acknowledgement that every startup reducer already discards.
async fn await_native_bridge_attach(
stream: &tokio::net::TcpStream,
running: &AtomicBool,
) -> NativeBridgeAttach {
let mut first = [0u8; 1];
loop {
if !running.load(Ordering::SeqCst) {
return NativeBridgeAttach::Stopped;
}
match tokio::time::timeout(RUNNING_POLL, stream.peek(&mut first)).await {
Ok(Ok(0) | Err(_)) => return NativeBridgeAttach::Closed,
Ok(Ok(_)) => return NativeBridgeAttach::Attached,
Err(_) => {}
}
}
}
fn native_bridge_acknowledged_data_frames(command: u8, payload: &[u8]) -> Option<u64> {
if command != RNODE_NATIVE_BRIDGE_ACK_COMMAND
|| payload.len() != RNODE_NATIVE_BRIDGE_ACK_PAYLOAD_LEN
@@ -1634,6 +1664,14 @@ enum NativeStartupReductionError {
PreReadyDataOverflow,
}
/// At the readiness deadline the echoes in hand are the verdict, as upstream.
fn deadline_rejection(state: &RNodeProtocolState) -> Option<RNodeReadinessEvidence> {
match state.readiness() {
RNodeReadiness::Blocked(blocker) => blocker.rejected_evidence(),
RNodeReadiness::Ready => None,
}
}
fn reduce_native_startup_bytes(
protocol_state: &mut RNodeProtocolState,
deframer: &mut kiss::RawKissDeframer,
@@ -2685,6 +2723,8 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
transport_tx: mpsc::Sender<TransportMessage>,
options: RNodeStartupOptions,
) -> Result<SpawnedRNodeInterface, RNodeSpawnError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate().map_err(|error| {
InterfaceError::SendFailed(format!("rnode config {}: {error}", error.field()))
})?;
@@ -2900,7 +2940,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
continue;
}
};
let mut protocol_state = RNodeProtocolState::new(protocol_target);
let mut protocol_state = RNodeProtocolState::with_effective_settings(protocol_target);
let mut deframer = kiss::RawKissDeframer::new();
ble_diag("[ble] sending detect sequence");
trace_ble_lifecycle(generation_id, "detect_write", "started", None, None);
@@ -3223,6 +3263,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
enum StartupReadinessOutcome {
Ready,
Retry(&'static str),
Rejected(RNodeReadinessEvidence),
Stopped,
}
let readiness_deadline = tokio::time::Instant::now() + RNODE_BLE_READINESS_TIMEOUT;
@@ -3230,6 +3271,9 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
if matches!(protocol_state.readiness(), RNodeReadiness::Ready) {
break StartupReadinessOutcome::Ready;
}
if let Some(rejected) = protocol_state.definitive_rejection() {
break StartupReadinessOutcome::Rejected(rejected);
}
tokio::select! {
notification = notification_stream.next() => match notification {
Some(notification) if notification.uuid == NUS_TX_CHAR_UUID => {
@@ -3265,7 +3309,10 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
}
}
_ = tokio::time::sleep_until(readiness_deadline) => {
break StartupReadinessOutcome::Retry("typed readiness timed out");
break match deadline_rejection(&protocol_state) {
Some(rejected) => StartupReadinessOutcome::Rejected(rejected),
None => StartupReadinessOutcome::Retry("typed readiness timed out"),
};
}
}
};
@@ -3277,6 +3324,19 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
}
trace_ble_lifecycle(generation_id, "typed_readiness", "ready", None, None);
}
StartupReadinessOutcome::Rejected(rejected) => {
// Retrying settings the radio cannot use only loops; the
// radio stays as the reassertion left it (never RADIO_OFF).
trace_ble_lifecycle(generation_id, "typed_readiness", "rejected", None, None);
tracing::warn!(
name = %log_name,
rejected = ?rejected,
"BLE RNode rejected the configured settings"
);
bounded_ble_disconnect(&conn.peripheral).await;
snapshot_publisher.stopped_for_configuration_rejection(rejected);
return;
}
StartupReadinessOutcome::Stopped => {
trace_ble_lifecycle(
generation_id,
@@ -3607,6 +3667,8 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
let interface = InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name,
mode,
@@ -3632,6 +3694,10 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
/// Android-only TCP-bridge variant. btleplug's deprecated JNI breaks on
/// Android 14+, so Kotlin (`RatspeakBleGatt.kt`) owns the GATT lifecycle
/// and forwards NUS bytes over `tcp_port`.
///
/// The bridge admits the local connection before its GATT link exists, so
/// each TCP generation sends nothing until the bridge writes its first byte;
/// Kotlin marks attachment with a zero-count acknowledgement.
pub async fn spawn_ble_rnode_interface_native(
config: BleRNodeConfig,
id: InterfaceId,
@@ -3683,6 +3749,8 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
tcp_port: u16,
options: RNodeStartupOptions,
) -> Result<SpawnedRNodeInterface, RNodeSpawnError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
use tokio::io::{AsyncReadExt, AsyncWriteExt};
config.validate().map_err(|error| {
@@ -3780,8 +3848,32 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
}
};
match await_native_bridge_attach(&stream, &running_task).await {
NativeBridgeAttach::Attached => {}
NativeBridgeAttach::Stopped => {
publish_ble_stopped(&mut snapshot_publisher, RNodeRuntimeReason::StopRequested);
return;
}
NativeBridgeAttach::Closed => {
snapshot_publisher.connection_attempt_failed();
if reconnect_try_exhausted(&mut tries) {
snapshot_publisher.stopped(RNodeRuntimeReason::DriverTerminated);
return;
}
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
publish_ble_stopped(
&mut snapshot_publisher,
RNodeRuntimeReason::StopRequested,
);
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
}
let (mut tcp_read, mut tcp_write) = stream.into_split();
let mut protocol_state = RNodeProtocolState::new(protocol_target);
let mut protocol_state = RNodeProtocolState::with_effective_settings(protocol_target);
let mut startup_deframer = kiss::RawKissDeframer::new();
let mut startup_pre_ready_data: Vec<Vec<u8>> = Vec::new();
let mut startup_pre_ready_data_bytes = 0usize;
@@ -4004,6 +4096,7 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
enum NativeStartupOutcome {
Ready,
Retry(&'static str),
Rejected(RNodeReadinessEvidence),
Stopped,
}
let mut startup_buf = [0u8; 4096];
@@ -4014,6 +4107,9 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
if matches!(protocol_state.readiness(), RNodeReadiness::Ready) {
break NativeStartupOutcome::Ready;
}
if let Some(rejected) = protocol_state.definitive_rejection() {
break NativeStartupOutcome::Rejected(rejected);
}
tokio::select! {
result = tcp_read.read(&mut startup_buf) => match result {
Ok(0) => break NativeStartupOutcome::Retry(
@@ -4057,7 +4153,10 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
}
}
_ = tokio::time::sleep_until(readiness_deadline) => {
break NativeStartupOutcome::Retry("typed readiness timed out");
break match deadline_rejection(&protocol_state) {
Some(rejected) => NativeStartupOutcome::Rejected(rejected),
None => NativeStartupOutcome::Retry("typed readiness timed out"),
};
}
}
};
@@ -4068,6 +4167,17 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
bluetooth_persistence_completed = true;
}
}
NativeStartupOutcome::Rejected(rejected) => {
// Retrying settings the radio cannot use only loops; the
// radio stays as the reassertion left it (never RADIO_OFF).
tracing::warn!(
name = %log_name,
rejected = ?rejected,
"BLE RNode native rejected the configured settings"
);
snapshot_publisher.stopped_for_configuration_rejection(rejected);
return;
}
NativeStartupOutcome::Stopped => {
snapshot_publisher.shutting_down(RNodeRuntimeReason::StopRequested);
let _ = tcp_write.write_all(&rnode::build_detach_sequence()).await;
@@ -4421,6 +4531,8 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
let interface = InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name,
mode,
@@ -4586,7 +4698,7 @@ mod tests {
#[test]
fn native_startup_holds_pre_ready_data_and_preserves_post_ready_order() {
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 17);
let mut state = RNodeProtocolState::new(target);
let mut state = RNodeProtocolState::with_effective_settings(target);
for (command, frame) in [
(rnode::CMD_DETECT, vec![rnode::DETECT_RESP]),
(
@@ -4616,6 +4728,10 @@ mod tests {
rnode::CMD_RADIO_STATE,
&[rnode::RADIO_STATE_ON],
));
same_read.extend(kiss::frame_with_command(
rnode::CMD_TXPOWER,
&[target.tx_power],
));
same_read.extend(kiss::frame(retained));
let mut deframer = kiss::RawKissDeframer::new();
let mut pre_ready_data = Vec::new();
@@ -4644,7 +4760,7 @@ mod tests {
#[test]
fn native_startup_carries_partial_data_begun_after_ready_into_active_read() {
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 17);
let mut state = RNodeProtocolState::new(target);
let mut state = RNodeProtocolState::with_effective_settings(target);
for (command, frame) in [
(rnode::CMD_DETECT, vec![rnode::DETECT_RESP]),
(
@@ -4671,6 +4787,10 @@ mod tests {
let split = framed.len() / 2;
let mut first_read =
kiss::frame_with_command(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON]);
first_read.extend(kiss::frame_with_command(
rnode::CMD_TXPOWER,
&[target.tx_power],
));
first_read.extend_from_slice(&framed[..split]);
let mut startup_deframer = kiss::RawKissDeframer::new();
@@ -4705,7 +4825,7 @@ mod tests {
#[test]
fn native_startup_pre_ready_data_bound_exceeds_rnode_receive_buffer_and_fails_explicitly() {
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 17);
let mut state = RNodeProtocolState::new(target);
let mut state = RNodeProtocolState::with_effective_settings(target);
let mut deframer = kiss::RawKissDeframer::new();
let mut pre_ready_data = Vec::new();
let mut pre_ready_data_bytes = 0;
@@ -5378,7 +5498,7 @@ mod tests {
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 6);
assert_eq!(frames.len(), 9);
assert_eq!(
frames[0],
(
@@ -5386,9 +5506,13 @@ mod tests {
ble_cfg.frequency.to_be_bytes().to_vec()
)
);
assert_eq!(
frames[5],
(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
);
assert_eq!(
frames.last().unwrap(),
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
&(rnode::CMD_TXPOWER, vec![ble_cfg.tx_power])
);
}
@@ -5410,18 +5534,21 @@ mod tests {
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 8);
assert_eq!(frames.len(), 11);
assert_eq!(
frames[0],
(rnode::CMD_FREQUENCY, cfg.frequency.to_be_bytes().to_vec())
);
assert_eq!(
frames.last().unwrap(),
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
&(rnode::CMD_TXPOWER, vec![cfg.tx_power])
);
assert_eq!(frame_command_count(&frames, rnode::CMD_ST_ALOCK), 1);
assert_eq!(frame_command_count(&frames, rnode::CMD_LT_ALOCK), 1);
let radio_on = frames.len() - 1;
let radio_on = frames
.iter()
.position(|frame| *frame == (rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON]))
.expect("RADIO_STATE_ON present");
let st = frames
.iter()
.position(|(cmd, _)| *cmd == rnode::CMD_ST_ALOCK)
@@ -5723,7 +5850,7 @@ mod tests {
);
assert_eq!(
frames.last(),
Some(&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON]))
Some(&(rnode::CMD_TXPOWER, vec![config.tx_power]))
);
assert!(frames.iter().all(|(command, _)| {
!matches!(
@@ -5897,6 +6024,14 @@ mod tests {
}
fn native_ready_response(config: &BleRNodeConfig) -> Vec<u8> {
native_cold_radio_response(config, config.tx_power)
}
/// Echoes of a radio that was off when the reassertion began: the first
/// transmit-power echo repeats the request, while the post-`RADIO_STATE_ON`
/// re-assertion reports `effective_tx_power`, as RNode firmware does behind
/// a power amplifier.
fn native_cold_radio_response(config: &BleRNodeConfig, effective_tx_power: u8) -> Vec<u8> {
let mut response = kiss::frame_with_command(rnode::CMD_DETECT, &[rnode::DETECT_RESP]);
response.extend(kiss::frame_with_command(
rnode::CMD_FW_VERSION,
@@ -5926,6 +6061,18 @@ mod tests {
rnode::CMD_RADIO_STATE,
&[rnode::RADIO_STATE_ON],
));
response.extend(kiss::frame_with_command(
rnode::CMD_FREQUENCY,
&config.frequency.to_be_bytes(),
));
response.extend(kiss::frame_with_command(
rnode::CMD_BANDWIDTH,
&config.bandwidth.to_be_bytes(),
));
response.extend(kiss::frame_with_command(
rnode::CMD_TXPOWER,
&[effective_tx_power],
));
response
}
@@ -5952,6 +6099,90 @@ mod tests {
frames
}
/// Android's bridge marks an attached GATT generation with a zero-count
/// acknowledgement.
async fn native_test_attach(stream: &mut tokio::net::TcpStream) {
use tokio::io::AsyncWriteExt;
let mut attach = RNODE_NATIVE_BRIDGE_ACK_MAGIC.to_vec();
attach.extend_from_slice(&0u64.to_be_bytes());
stream
.write_all(&kiss::frame_with_command(
RNODE_NATIVE_BRIDGE_ACK_COMMAND,
&attach,
))
.await
.expect("write native bridge attachment");
}
/// The bridge admits Rust before GATT exists; startup must not spend its
/// deadline, or leave stale probes queued, until the bridge attaches.
#[tokio::test]
async fn native_ble_sends_nothing_until_the_bridge_attaches() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.expect("bind unattached bridge");
let port = listener
.local_addr()
.expect("unattached bridge address")
.port();
let config = BleRNodeConfig::new("native-unattached", "ble://RNode 0544");
let server_config = config.clone();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("accept unattached bridge");
let mut early = [0u8; 64];
assert!(
tokio::time::timeout(
RNODE_BLE_CAPABILITY_PREFLIGHT_TIMEOUT * 3,
stream.read(&mut early),
)
.await
.is_err(),
"nothing may be written before the bridge attaches"
);
native_test_attach(&mut stream).await;
native_test_read_through_command(&mut stream, rnode::CMD_MCU).await;
let mut handshake = kiss::frame_with_command(rnode::CMD_DETECT, &[rnode::DETECT_RESP]);
handshake.extend(kiss::frame_with_command(
rnode::CMD_FW_VERSION,
&[rnode::REQUIRED_FW_VER_MAJ, rnode::REQUIRED_FW_VER_MIN],
));
stream.write_all(&handshake).await.expect("write handshake");
native_test_read_through_command(&mut stream, rnode::CMD_MCU).await;
stream
.write_all(&native_ready_response(&server_config))
.await
.expect("write Ready evidence");
let mut trailing = [0u8; 64];
let _ = tokio::time::timeout(Duration::from_secs(3), stream.read(&mut trailing)).await;
});
let (transport_tx, _transport_rx) = mpsc::channel(8);
let spawned = spawn_ble_rnode_interface_native_with_driver_and_options(
config,
0xB1E0_0544,
transport_tx,
port,
RNodeStartupOptions::default(),
)
.await
.expect("spawn unattached interface");
let online = spawned.interface.online.clone();
tokio::time::timeout(Duration::from_secs(10), async {
while !online.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("an attached bridge reaches Ready on its first generation");
assert_eq!(spawned.driver.snapshot().reconnect_total, 0);
spawned.driver.request_shutdown();
server.await.expect("unattached bridge task");
}
#[tokio::test]
async fn native_ble_waits_for_ready_retries_payload_and_persists_bluetooth_once() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -5983,6 +6214,7 @@ mod tests {
.accept()
.await
.expect("accept native reliability generation");
native_test_attach(&mut stream).await;
let probe = native_test_read_through_command(&mut stream, rnode::CMD_MCU).await;
assert!(
@@ -6112,6 +6344,7 @@ mod tests {
)
.await
.expect("spawn native reliability interface");
spawned.interface.owner.mark_registered();
let tx = spawned.interface.tx.clone();
let online = spawned.interface.online.clone();
let txb = spawned
@@ -6155,7 +6388,9 @@ mod tests {
.await
.expect("same-read post-Ready inbound timeout")
.expect("same-read post-Ready transport message");
let TransportMessage::Inbound(inbound) = inbound else {
let TransportMessage::Inbound(inbound) =
crate::traits::test_event_for_handle(inbound, &spawned.interface)
else {
panic!("expected inbound transport packet after Ready");
};
assert_eq!(inbound.raw, post_ready_inbound);
@@ -6189,7 +6424,9 @@ mod tests {
.await
.expect("pre-Ready physical DATA release timeout")
.expect("pre-Ready physical DATA transport message");
let TransportMessage::Inbound(held_inbound) = held_inbound else {
let TransportMessage::Inbound(held_inbound) =
crate::traits::test_event_for_handle(held_inbound, &spawned.interface)
else {
panic!("expected held inbound transport packet after reconnect Ready");
};
assert_eq!(held_inbound.raw, pre_ready_reconnect_inbound);
@@ -6220,6 +6457,99 @@ mod tests {
server.await.expect("native reliability bridge task");
}
/// A cold radio echoes the requested transmit power, then the amplifier
/// floor once it is on. The effective echo must decide, once, without a
/// reconnect loop or RADIO_OFF.
#[tokio::test]
async fn native_ble_rejects_effective_transmit_power_terminally() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.expect("bind rejection bridge");
let port = listener
.local_addr()
.expect("rejection bridge address")
.port();
let mut config = BleRNodeConfig::new("native-rejection", "ble://RNode D7F1");
config.tx_power = 2;
let server_config = config.clone();
let server = tokio::spawn(async move {
let (mut stream, _) = listener
.accept()
.await
.expect("accept rejection generation");
native_test_attach(&mut stream).await;
native_test_read_through_command(&mut stream, rnode::CMD_MCU).await;
let mut handshake = kiss::frame_with_command(rnode::CMD_DETECT, &[rnode::DETECT_RESP]);
handshake.extend(kiss::frame_with_command(
rnode::CMD_FW_VERSION,
&[rnode::REQUIRED_FW_VER_MAJ, rnode::REQUIRED_FW_VER_MIN],
));
stream.write_all(&handshake).await.expect("write handshake");
let init = native_test_read_through_command(&mut stream, rnode::CMD_MCU).await;
assert!(init.iter().all(|(command, frame)| {
*command != rnode::CMD_RADIO_STATE || frame.as_slice() != [rnode::RADIO_STATE_OFF]
}));
stream
.write_all(&native_cold_radio_response(&server_config, 13))
.await
.expect("write cold-radio echoes");
let mut trailing = Vec::new();
let _ = tokio::time::timeout(Duration::from_secs(2), stream.read_to_end(&mut trailing))
.await;
let mut deframer = kiss::RawKissDeframer::new();
assert!(deframer.feed(&trailing).iter().all(|(command, frame)| {
*command != rnode::CMD_RADIO_STATE || frame.as_slice() != [rnode::RADIO_STATE_OFF]
}));
assert!(
tokio::time::timeout(Duration::from_millis(1_500), listener.accept())
.await
.is_err(),
"a definitive rejection must not reconnect"
);
});
let (transport_tx, _transport_rx) = mpsc::channel(8);
let spawned = spawn_ble_rnode_interface_native_with_driver_and_options(
config,
0xB1E0_D7F1,
transport_tx,
port,
RNodeStartupOptions::default(),
)
.await
.expect("spawn rejection interface");
let online = spawned.interface.online.clone();
let mut snapshots = spawned.driver.watch();
let stopped = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let snapshot = snapshots
.changed()
.await
.expect("rejection publisher closed");
if snapshot.phase == rnode::RNodeRuntimePhase::Stopped {
break snapshot;
}
}
})
.await
.expect("definitive rejection must stop well before the readiness deadline");
assert_eq!(
stopped.reason,
Some(RNodeRuntimeReason::ConfigurationRejected)
);
assert_eq!(
stopped.configuration_rejection,
Some(RNodeReadinessEvidence::TransmitPower)
);
assert!(!online.load(Ordering::SeqCst));
server.await.expect("rejection bridge task");
}
#[tokio::test]
async fn strict_desktop_ble_preflight_admits_verified_and_unverified_without_data_leakage() {
for (response, expected_capability) in [
@@ -6832,6 +7162,7 @@ mod tests {
.port();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("accept rejecting bridge");
native_test_attach(&mut stream).await;
let mut deframer = kiss::RawKissDeframer::new();
let mut buffer = [0u8; 1024];
loop {
@@ -6870,6 +7201,7 @@ mod tests {
)
.await
.expect("spawn strict native observer");
spawned.interface.owner.mark_registered();
let mut subscription = spawned.driver.watch();
let terminal = tokio::time::timeout(Duration::from_secs(2), async {
loop {
@@ -7268,6 +7600,7 @@ mod tests {
let handle = spawn_ble_rnode_interface(config, 99, transport_tx)
.await
.expect("Failed to spawn BLE RNode interface");
handle.owner.mark_registered();
assert!(handle.online.load(Ordering::SeqCst));
assert_eq!(handle.mtu, 508);
+369 -58
View File
@@ -2,17 +2,20 @@
//! Handshake: HELLO → SESSION CREATE → STREAM CONNECT/ACCEPT;
//! stream then carries HDLC-framed packets.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use rns_crypto::zeroize::Zeroizing;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -36,6 +39,12 @@ pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const SAM_VERSION: &str = "3.1";
/// The longest SAM reply line read: the line limit of Python's asyncio SAM
/// client, far past a SESSION STATUS that carries a private key.
const SAM_REPLY_MAX_BYTES: usize = 64 * 1024;
/// An I2P key file holds one base64 SAM private key of a few kilobytes.
const I2P_KEY_FILE_MAX_BYTES: usize = 16 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum SamError {
#[error("SAM I/O error: {0}")]
@@ -78,23 +87,81 @@ pub fn sam_reply_has_token(pairs: &[(String, String)], token: &str) -> bool {
pairs.iter().any(|(k, v)| k == token && v.is_empty())
}
async fn read_sam_reply(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
) -> Result<String, SamError> {
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
if n == 0 {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Ok(line.trim_end().to_string())
/// The value of `key` in a reply, borrowed from it.
fn reply_value<'a>(reply: &'a str, key: &str) -> Option<&'a str> {
reply
.split_whitespace()
.find_map(|token| token.strip_prefix(key)?.strip_prefix('='))
}
async fn sam_hello(
/// Whether a reply holds `token` with no value.
fn reply_has_token(reply: &str, token: &str) -> bool {
reply
.split_whitespace()
.any(|word| word == token || word.strip_suffix('=') == Some(token))
}
/// A reply for an error message, with any private key left out.
fn without_destination(reply: &str) -> String {
reply
.split_whitespace()
.map(|token| {
if token.starts_with("DESTINATION=") {
"DESTINATION=<redacted>"
} else {
token
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Read one reply line into a buffer reserved once and wiped on drop, since a
/// SESSION STATUS reply carries the session's private key. Bytes are read one
/// at a time, so nothing past the line is consumed.
async fn read_sam_reply<R: AsyncRead + Unpin>(
reader: &mut R,
) -> Result<Zeroizing<String>, SamError> {
let mut line = Zeroizing::new(Vec::with_capacity(SAM_REPLY_MAX_BYTES));
loop {
match reader.read_u8().await {
Ok(b'\n') => break,
Ok(_) if line.len() == SAM_REPLY_MAX_BYTES => {
return Err(SamError::UnexpectedReply(format!(
"reply longer than {SAM_REPLY_MAX_BYTES} bytes"
)));
}
Ok(byte) => line.push(byte),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof && !line.is_empty() => break,
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Err(e) => return Err(e.into()),
}
}
let end = line
.iter()
.rposition(|byte| !byte.is_ascii_whitespace())
.map_or(0, |last| last + 1);
line.truncate(end);
match String::from_utf8(std::mem::take(&mut *line)) {
Ok(text) => Ok(Zeroizing::new(text)),
Err(error) => {
drop(Zeroizing::new(error.into_bytes()));
Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SAM reply is not UTF-8",
)))
}
}
}
async fn sam_hello<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
) -> Result<(), SamError> {
let hello_msg = format!("HELLO VERSION MIN={} MAX={}\n", SAM_VERSION, SAM_VERSION);
writer.write_all(hello_msg.as_bytes()).await?;
@@ -106,7 +173,7 @@ async fn sam_hello(
if !sam_reply_has_token(&pairs, "HELLO") || !sam_reply_has_token(&pairs, "REPLY") {
return Err(SamError::HandshakeFailed(format!(
"expected HELLO REPLY, got: {}",
reply
reply.as_str()
)));
}
@@ -118,43 +185,58 @@ async fn sam_hello(
))),
None => Err(SamError::HandshakeFailed(format!(
"no RESULT in HELLO reply: {}",
reply
reply.as_str()
))),
}
}
/// Returns the destination (base64). `private_key=None` = transient.
async fn sam_session_create(
/// Returns the session's private key (base64), wiped on drop.
/// `private_key=None` = transient.
async fn sam_session_create<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
session_id: &str,
private_key: Option<&str>,
) -> Result<String, SamError> {
let dest_param = match private_key {
Some(key) => key.to_string(),
None => "TRANSIENT".to_string(),
transient_signature_type: Option<u8>,
) -> Result<Zeroizing<String>, SamError> {
let transient;
let destination = match (private_key, transient_signature_type) {
(Some(key), _) => key,
(None, Some(signature_type)) => {
transient = format!("TRANSIENT SIGNATURE_TYPE={signature_type}");
&transient
}
(None, None) => "TRANSIENT",
};
let create_msg = format!(
"SESSION CREATE STYLE=STREAM ID={} DESTINATION={}\n",
session_id, dest_param
);
// Sized up front: the command carries the private key.
let mut create_msg = Zeroizing::new(String::with_capacity(
64 + session_id.len() + destination.len(),
));
for part in [
"SESSION CREATE STYLE=STREAM ID=",
session_id,
" DESTINATION=",
destination,
"\n",
] {
create_msg.push_str(part);
}
writer.write_all(create_msg.as_bytes()).await?;
writer.flush().await?;
let reply = read_sam_reply(reader).await?;
let pairs = parse_sam_reply(&reply);
if !sam_reply_has_token(&pairs, "SESSION") || !sam_reply_has_token(&pairs, "STATUS") {
if !reply_has_token(&reply, "SESSION") || !reply_has_token(&reply, "STATUS") {
return Err(SamError::SessionFailed(format!(
"expected SESSION STATUS, got: {}",
reply
without_destination(&reply)
)));
}
match sam_reply_get(&pairs, "RESULT") {
match reply_value(&reply, "RESULT") {
Some("OK") => {}
Some(other) => {
let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details");
let msg_detail = reply_value(&reply, "MESSAGE").unwrap_or("no details");
return Err(SamError::SessionFailed(format!(
"SESSION RESULT={}: {}",
other, msg_detail
@@ -163,13 +245,13 @@ async fn sam_session_create(
None => {
return Err(SamError::SessionFailed(format!(
"no RESULT in SESSION STATUS: {}",
reply
without_destination(&reply)
)));
}
}
match sam_reply_get(&pairs, "DESTINATION") {
Some(dest) => Ok(dest.to_string()),
match reply_value(&reply, "DESTINATION") {
Some(dest) => Ok(Zeroizing::new(dest.to_string())),
None => Err(SamError::SessionFailed(
"SESSION STATUS OK but no DESTINATION returned".to_string(),
)),
@@ -197,7 +279,7 @@ async fn sam_stream_connect(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::StreamFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -212,7 +294,7 @@ async fn sam_stream_connect(
}
None => Err(SamError::StreamFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
))),
}
}
@@ -234,7 +316,7 @@ async fn sam_stream_accept(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::AcceptFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -250,7 +332,7 @@ async fn sam_stream_accept(
None => {
return Err(SamError::AcceptFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
)));
}
}
@@ -282,15 +364,39 @@ fn generate_session_id() -> String {
format!("reticulum_{:016x}", id)
}
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct I2PServerConfig {
pub name: String,
pub sam_host: String,
pub sam_port: u16,
/// Base64 private key for a persistent destination; `None` = transient.
/// Base64 private key for the server's destination, used before `key_path`.
pub keyfile: Option<String>,
/// File holding the server's private key, as Python keeps it under
/// `storage/i2p` (I2PInterface.py:225-255): every session uses it, and
/// the first session's key is written to it when it is missing.
pub key_path: Option<std::path::PathBuf>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Receives the server's b32 address (Python `I2PInterface.b32`) whenever
/// SAM creates its session.
pub b32: Option<tokio::sync::watch::Sender<Option<String>>>,
}
// The key is the destination's secret; debug output names only its presence.
impl std::fmt::Debug for I2PServerConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("I2PServerConfig")
.field("name", &self.name)
.field("sam_host", &self.sam_host)
.field("sam_port", &self.sam_port)
.field("keyfile", &self.keyfile.as_ref().map(|_| "<redacted>"))
.field("key_path", &self.key_path)
.field("reconnect_delay", &self.reconnect_delay)
.field("mode", &self.mode)
.field("b32", &self.b32)
.finish()
}
}
impl I2PServerConfig {
@@ -300,12 +406,99 @@ impl I2PServerConfig {
sam_host: DEFAULT_SAM_ADDRESS.to_string(),
sam_port: DEFAULT_SAM_PORT,
keyfile: None,
key_path: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
b32: None,
}
}
}
/// i2plib's signature type for new destinations, EdDSA-SHA512-Ed25519
/// (RNS/vendor/i2plib/sam.py:91-93).
const NEW_DESTINATION_SIGNATURE_TYPE: u8 = 7;
/// The stored key, `None` when there is none yet, read into buffers that are
/// wiped on drop. A file that cannot be read is an error, so it is never
/// replaced.
fn read_private_key(path: &std::path::Path) -> std::io::Result<Option<Zeroizing<String>>> {
let data = match rns_identity::persistence::read_secret_file(path, I2P_KEY_FILE_MAX_BYTES) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let key = std::str::from_utf8(&data)
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "I2P key file is not UTF-8")
})?
.trim();
Ok((!key.is_empty()).then(|| Zeroizing::new(key.to_string())))
}
/// Keep a session's private key readable by its owner only, replaced
/// atomically, as the other private keys are.
fn store_private_key(path: &std::path::Path, key: &str) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
rns_identity::persistence::atomic_write(path, key.as_bytes())
}
/// The b32 address of the destination in a SAM private key: the hash of its
/// first 387 bytes plus its certificate (i2plib `Destination.base32`,
/// RNS/vendor/i2plib/sam.py:113-129).
pub fn destination_b32(private_key: &str) -> Option<String> {
let key = i2p_base64_decode(private_key)?;
let certificate = usize::from(u16::from_be_bytes(key.get(385..387)?.try_into().ok()?));
let hash = rns_crypto::sha::sha256(key.get(..387 + certificate)?);
Some(base32_lowercase(&hash))
}
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`), into a buffer
/// sized up front and wiped on drop: the input is usually a private key.
fn i2p_base64_decode(text: &str) -> Option<Zeroizing<Vec<u8>>> {
let mut bytes = Zeroizing::new(Vec::with_capacity(text.len() * 3 / 4));
let (mut buffer, mut bits) = (0u32, 0u32);
for c in text.trim_end_matches('=').bytes() {
let value = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'-' => 62,
b'~' => 63,
_ => return None,
};
buffer = buffer << 6 | u32::from(value);
bits += 6;
if bits >= 8 {
bits -= 8;
bytes.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
Some(bytes)
}
/// RFC 4648 base32, lowercase and unpadded.
fn base32_lowercase(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
let mut text = String::with_capacity(bytes.len().div_ceil(5) * 8);
let (mut buffer, mut bits) = (0u32, 0u32);
for byte in bytes {
buffer = buffer << 8 | u32::from(*byte);
bits += 8;
while bits >= 5 {
bits -= 5;
text.push(char::from(ALPHABET[(buffer >> bits) as usize & 31]));
}
buffer &= (1 << bits) - 1;
}
if bits > 0 {
text.push(char::from(ALPHABET[(buffer << (5 - bits)) as usize & 31]));
}
text
}
#[derive(Debug, Clone)]
pub struct I2PClientConfig {
pub name: String,
@@ -317,6 +510,8 @@ pub struct I2PClientConfig {
pub max_reconnect_tries: Option<usize>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Signs a tunnel synthesis for every connection; `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl I2PClientConfig {
@@ -329,8 +524,14 @@ impl I2PClientConfig {
max_reconnect_tries: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(I2PInterfacePeer)` (I2PInterface.py:714-715).
pub fn python_name(&self) -> String {
format!("I2PInterfacePeer[{}]", self.name)
}
}
/// Connect via SAM streaming session, run HDLC-framed I/O; exponential reconnect.
@@ -339,6 +540,8 @@ pub async fn spawn_i2p_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -353,10 +556,14 @@ pub async fn spawn_i2p_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let mut pacer = ReconnectPacer::new(config.reconnect_delay, config.max_reconnect_tries);
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let session_id = generate_session_id();
let session_stream = match connect_to_sam(&config.sam_host, config.sam_port).await {
@@ -379,10 +586,10 @@ pub async fn spawn_i2p_client(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(
name = %config.name,
error = %e,
@@ -401,9 +608,10 @@ pub async fn spawn_i2p_client(
let _our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
None,
None,
)
.await
{
@@ -505,8 +713,14 @@ pub async fn spawn_i2p_client(
"I2P client: stream connected"
);
online_task.store(true, Ordering::SeqCst);
pacer.reset();
// Python synthesizes on every connection (I2PInterface.py:503,
// :533).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online_task).await;
// BufReader may have prefetched past the handshake; flush its tail first.
let buffered = stream_buf_reader.buffer().to_vec();
@@ -569,6 +783,8 @@ pub async fn spawn_i2p_client(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -593,10 +809,13 @@ pub async fn spawn_i2p_client(
/// is recreated if the control socket drops.
pub async fn spawn_i2p_server(
config: I2PServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let name = config.name.clone();
let mode = config.mode;
@@ -624,21 +843,40 @@ pub async fn spawn_i2p_server(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(name = %config.name, error = %e, "I2P server: SAM HELLO failed");
tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await;
continue;
}
let private_key = config.keyfile.as_deref();
let (private_key, store_key) = match (&config.keyfile, config.key_path.as_deref()) {
(Some(key), _) => (Some(Zeroizing::new(key.clone())), false),
(None, None) => (None, false),
(None, Some(path)) => match read_private_key(path) {
Ok(key) => {
let missing = key.is_none();
(key, missing)
}
Err(error) => {
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: cannot read its private key; this session's address is transient"
);
(None, false)
}
},
};
let our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
private_key,
private_key.as_deref().map(String::as_str),
Some(NEW_DESTINATION_SIGNATURE_TYPE),
)
.await
{
@@ -661,6 +899,20 @@ pub async fn spawn_i2p_server(
dest_len = our_dest.len(),
"I2P server: session created, accepting streams"
);
if store_key
&& let Some(path) = config.key_path.as_deref()
&& let Err(error) = store_private_key(path, &our_dest)
{
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: failed to store its private key; its address changes with the next session"
);
}
if let Some(b32) = &config.b32 {
b32.send_replace(destination_b32(&our_dest));
}
online_task.store(true, Ordering::SeqCst);
// Each STREAM ACCEPT needs its own SAM TCP connection.
@@ -747,7 +999,9 @@ pub async fn spawn_i2p_server(
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let transport_tx2 =
InterfaceTransportSender::new(client_id, transport_tx.actor_sender());
let child_owner = transport_tx2.owner();
let peer_name = client_name.clone();
let c_read_task = tokio::spawn(async move {
i2p_read_loop(
@@ -764,7 +1018,9 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
owner: child_owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: Some(id),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -804,7 +1060,9 @@ pub async fn spawn_i2p_server(
});
Ok(InterfaceHandle {
id: 0,
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -833,7 +1091,7 @@ async fn i2p_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
initial_data: &[u8],
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &InterfaceTransportSender,
online: &AtomicBool,
rxb: &AtomicU64,
) {
@@ -948,6 +1206,16 @@ impl ReconnectPacer {
mod tests {
use super::*;
#[test]
fn peer_python_name_matches_python() {
// Python 1.5.5 `str()` output for this interface.
let peer = "abcdefghijklmnop.b32.i2p";
assert_eq!(
I2PClientConfig::new(&format!("Golden I2P to {peer}"), peer).python_name(),
"I2PInterfacePeer[Golden I2P to abcdefghijklmnop.b32.i2p]"
);
}
#[test]
fn test_i2p_client_config() {
let cfg = I2PClientConfig::new("i2p0", "ABCDEF1234.b32.i2p");
@@ -1056,6 +1324,49 @@ mod tests {
assert!(!sam_reply_has_token(&pairs, "NONEXISTENT"));
}
fn i2p_base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
let mut text = String::new();
for chunk in bytes.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
text
}
fn private_key(certificate: &[u8], secret: u8) -> Vec<u8> {
let mut key: Vec<u8> = (0..384).map(|n| n as u8).collect();
key.extend_from_slice(certificate);
key.extend(std::iter::repeat_n(secret, 288));
key
}
/// Only the destination, keys plus certificate, names the address
/// (i2plib sam.py:113-129); the golden is checked against i2plib in tests.
#[test]
fn the_b32_address_hashes_only_the_destination() {
let ed25519 = [5, 0, 4, 0, 7, 0, 0];
let b32 = destination_b32(&i2p_base64(&private_key(&ed25519, 0x42))).unwrap();
assert_eq!(b32.len(), 52);
assert!(b32.bytes().all(|c| matches!(c, b'a'..=b'z' | b'2'..=b'7')));
assert_eq!(
destination_b32(&i2p_base64(&private_key(&ed25519, 0x24))).as_ref(),
Some(&b32)
);
assert_ne!(
destination_b32(&i2p_base64(&private_key(&[0, 0, 0], 0x42))).as_ref(),
Some(&b32)
);
assert_eq!(destination_b32("not+base64"), None);
assert_eq!(destination_b32(&i2p_base64(&[0; 300])), None);
}
#[test]
fn test_generate_session_id() {
let id1 = generate_session_id();
+28 -8
View File
@@ -164,7 +164,7 @@ impl Default for KissDeframer {
pub struct RawKissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
command: Option<u8>,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
}
@@ -174,7 +174,7 @@ impl RawKissDeframer {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
command: None,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
@@ -196,12 +196,14 @@ impl RawKissDeframer {
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command, frame_data));
if let Some(command) = self.command {
frames.push((command, frame_data));
}
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
self.command = None;
i = hit + 1;
}
None => {
@@ -221,9 +223,9 @@ impl RawKissDeframer {
/// for the next FEND to resync — matching the previous byte-loop.
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if self.command.is_none() {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
self.command = Some(first);
chunk = rest;
} else {
return;
@@ -232,7 +234,7 @@ impl RawKissDeframer {
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
return;
}
self.buffer.extend_from_slice(chunk);
@@ -241,7 +243,7 @@ impl RawKissDeframer {
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
}
}
@@ -326,6 +328,24 @@ mod tests {
assert_eq!(frames[0].0, CMD_DATA);
}
#[test]
fn extended_fe_command_survives_every_chunk_boundary() {
let expected = vec![(0xfe, vec![1, FEND, FESC, 2])];
let frame = frame_with_command(0xfe, &expected[0].1);
for split in 0..=frame.len() {
let mut decoder = RawKissDeframer::new();
let mut got = decoder.feed(&frame[..split]);
got.extend(decoder.feed(&frame[split..]));
assert_eq!(got, expected, "split {split}");
}
let mut decoder = RawKissDeframer::new();
let got: Vec<_> = frame
.iter()
.flat_map(|byte| decoder.feed(&[*byte]))
.collect();
assert_eq!(got, expected);
}
#[test]
fn test_raw_deframer_preserves_extended_commands() {
let mut deframer = RawKissDeframer::new();
+6
View File
@@ -1,5 +1,6 @@
//! Serial port + KISS framing; CMD_DATA + CMD_READY flow control.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -89,6 +90,8 @@ async fn spawn_kiss_with_port(
transport_tx: mpsc::Sender<TransportMessage>,
port: Box<dyn serialport::SerialPort>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
tracing::info!(
name = %config.name,
port = %config.port,
@@ -283,6 +286,8 @@ async fn spawn_kiss_with_port(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
@@ -371,6 +376,7 @@ mod tests {
let driver = spawn_kiss_with_port(config, 1, inbound, Box::new(slave))
.await
.unwrap();
driver.owner.mark_registered();
let mut revoke = kiss::frame_with_command(kiss::CMD_READY, &[0]);
revoke.extend(kiss::frame(b"read barrier"));
master.write_all(&revoke).unwrap();
+207 -44
View File
@@ -1,6 +1,7 @@
//! Shared-instance IPC. Unix domain sockets where available, TCP on
//! 127.0.0.1 as fallback. HDLC-framed.
use rns_transport::messages::{InterfaceOwner, InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -33,16 +34,6 @@ pub const FALLBACK_TCP_PORT: u16 = 37428;
#[cfg(unix)]
const LOCAL_RECONNECT_WAIT_SECS: u64 = 8;
#[cfg(all(unix, not(test)))]
fn local_reconnect_wait() -> std::time::Duration {
std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS)
}
#[cfg(all(unix, test))]
fn local_reconnect_wait() -> std::time::Duration {
std::time::Duration::from_millis(50)
}
pub fn socket_path_for(instance_name: &str) -> String {
format!("/tmp/rns_{}.sock", instance_name)
}
@@ -103,7 +94,7 @@ impl Default for LocalClientConfig {
async fn local_read_loop<R: AsyncReadExt + Unpin>(
mut reader: R,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
@@ -178,7 +169,7 @@ async fn run_local_client_connection<R, W>(
mut writer: W,
rx: &mut mpsc::Receiver<Bytes>,
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &InterfaceTransportSender,
rxb: &AtomicU64,
txb: &AtomicU64,
) -> LocalClientConnectionEnd
@@ -253,6 +244,8 @@ where
R: AsyncReadExt + Unpin + Send + 'static,
W: AsyncWriteExt + Unpin + Send + 'static,
{
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
@@ -277,6 +270,8 @@ where
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id,
name,
mode: InterfaceMode::Full,
@@ -297,16 +292,20 @@ where
}
}
/// Handle for the listener pseudo-interface (id 0): inbound-only, no
/// per-byte counters of its own.
/// Handle for the listener pseudo-interface: inbound-only, no per-byte
/// counters of its own.
fn server_listener_handle(
id: InterfaceId,
name: String,
online: Arc<AtomicBool>,
tx: mpsc::Sender<Bytes>,
read_task: tokio::task::JoinHandle<()>,
owner: InterfaceOwner,
) -> InterfaceHandle {
InterfaceHandle {
id: 0,
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name,
mode: InterfaceMode::Full,
@@ -397,10 +396,12 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let owner = InterfaceOwner::new();
let listener = bind_unix_listener(&config.socket_path)?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local server listening");
@@ -421,7 +422,7 @@ mod platform {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
Some(id),
reader,
writer,
transport_tx.clone(),
@@ -444,7 +445,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
Ok(server_listener_handle(name, online, tx, read_task))
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -452,6 +455,8 @@ mod platform {
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let initial_stream = connect_unix_stream(&config.socket_path).await?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
@@ -495,13 +500,16 @@ mod platform {
"local shared-instance connection lost; reconnecting"
);
loop {
tokio::time::sleep(local_reconnect_wait()).await;
tokio::time::sleep(std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS))
.await;
if transport_tx.is_closed() || rx.is_closed() {
return;
}
match connect_unix_stream(&task_socket_path).await {
Ok(connected) => {
stream = connected;
// Python drops traffic while offline (LocalInterface.py:218).
while rx.try_recv().is_ok() {}
task_online.store(true, Ordering::SeqCst);
tracing::info!(
name = %task_name,
@@ -525,6 +533,8 @@ mod platform {
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name: config.name,
mode: InterfaceMode::Full,
@@ -564,11 +574,13 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = fallback_tcp_addr(&config.socket_path);
let owner = InterfaceOwner::new();
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "local server (TCP fallback) listening");
@@ -590,7 +602,7 @@ mod platform {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
Some(id),
reader,
writer,
transport_tx.clone(),
@@ -613,7 +625,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
Ok(server_listener_handle(name, online, tx, read_task))
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -646,11 +660,12 @@ mod platform {
)]
pub async fn spawn_local_server(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
platform::spawn_local_server_impl(config, id_gen, transport_tx, handle_tx).await
platform::spawn_local_server_impl(config, id, id_gen, transport_tx, handle_tx).await
}
#[tracing::instrument(
@@ -695,6 +710,24 @@ mod tests {
}
}
/// The client's real reconnect wait, plus one missed attempt on a loaded host.
#[cfg(unix)]
const RECONNECT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(2 * LOCAL_RECONNECT_WAIT_SECS);
/// The server hands off an accepted client before that client has
/// necessarily published itself online, so wait for the flag itself.
#[cfg(unix)]
async fn wait_until_online(online: &AtomicBool) {
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while !online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("stable client handle must return online after reconnect");
}
#[test]
fn test_local_mtu() {
assert_eq!(LOCAL_MTU, 262_144);
@@ -733,9 +766,12 @@ mod tests {
name: "test-local-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 499, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 499);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -747,12 +783,21 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 42, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.parent_id, Some(server_handle.id));
assert_eq!(
accepted.packet_capacity,
InterfacePacketCapacity::new(262144, 262144, true)
);
let payload = Bytes::from_static(b"local ipc test");
client_handle.tx.send(payload.clone()).await.unwrap();
@@ -761,7 +806,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -777,7 +822,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 42);
@@ -804,9 +849,11 @@ mod tests {
socket_path: socket_path.clone(),
name: "dereg-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 599, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -817,11 +864,13 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 77, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client; server's per-client read_loop sees EOF and exits.
@@ -833,7 +882,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
@@ -869,12 +920,14 @@ mod tests {
};
let server_handle = spawn_local_server(
server_config(),
699,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
@@ -885,11 +938,13 @@ mod tests {
)
.await
.unwrap();
client_handle.owner.mark_registered();
let first_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for first accepted client")
.expect("handle channel closed");
first_accepted.owner.mark_registered();
server_handle.read_task.abort();
first_accepted.read_task.abort();
@@ -902,19 +957,22 @@ mod tests {
.await
.expect("client did not observe server shutdown");
let restarted_server =
spawn_local_server(server_config(), id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let second_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
assert!(
client_handle.online.load(Ordering::SeqCst),
"stable client handle must return online after reconnect"
);
let restarted_server = spawn_local_server(
server_config(),
699,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
wait_until_online(&client_handle.online).await;
let payload = Bytes::from_static(b"after shared restart");
second_accepted.tx.send(payload.clone()).await.unwrap();
@@ -922,7 +980,7 @@ mod tests {
.await
.expect("timeout waiting for post-restart frame")
.expect("transport channel closed");
match inbound {
match crate::traits::test_event_for_handle(inbound, &client_handle) {
TransportMessage::Inbound(packet) => {
assert_eq!(packet.interface_id, 88);
assert_eq!(packet.raw, payload);
@@ -936,4 +994,109 @@ mod tests {
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
/// Python's `LocalClientInterface` drops outgoing traffic while offline
/// (LocalInterface.py:218), so nothing queued during an outage reaches
/// the restarted shared instance.
#[cfg(unix)]
#[tokio::test]
async fn test_local_client_drops_traffic_queued_while_disconnected() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(950));
let socket_path = unique_test_socket_path("reticulum_offline_queue_test");
let server_config = || LocalServerConfig {
socket_path: socket_path.clone(),
name: "restartable-local-server".to_string(),
};
let server_handle = spawn_local_server(
server_config(),
698,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
name: "offline-local-client".to_string(),
},
89,
transport_tx.clone(),
)
.await
.unwrap();
client_handle.owner.mark_registered();
let first_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for first accepted client")
.expect("handle channel closed");
server_handle.read_task.abort();
first_accepted.read_task.abort();
drop(first_accepted.tx);
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while client_handle.online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("client did not observe server shutdown");
client_handle
.tx
.send(Bytes::from_static(b"queued while offline"))
.await
.unwrap();
let restarted_server = spawn_local_server(
server_config(),
698,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
// Online is published only after the offline queue is dropped.
wait_until_online(&client_handle.online).await;
let after = Bytes::from_static(b"after reconnect");
client_handle.tx.send(after.clone()).await.unwrap();
let first_frame = tokio::time::timeout(std::time::Duration::from_secs(3), async {
loop {
match transport_rx.recv().await.expect("transport channel closed") {
TransportMessage::InterfaceEvent {
interface_id,
message,
..
} if interface_id == second_accepted.id => {
if let TransportMessage::Inbound(packet) = *message {
return packet.raw;
}
}
_ => {}
}
}
})
.await
.expect("the reconnected client's traffic reaches the shared instance");
assert_eq!(
first_frame, after,
"traffic queued while disconnected is dropped"
);
restarted_server.read_task.abort();
second_accepted.read_task.abort();
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
}
+5
View File
@@ -1,5 +1,6 @@
//! HDLC-framed data over a subprocess's stdin/stdout; respawns on exit.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -41,6 +42,8 @@ pub async fn spawn_pipe_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -189,6 +192,8 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
File diff suppressed because it is too large. Load diff
@@ -160,7 +160,7 @@ impl RNodeCapabilityPreflight {
pub(crate) fn into_protocol_state(self) -> RNodeProtocolState {
let target = self.protocol_state.target();
let evidence = self.protocol_state.evidence();
let mut admitted = RNodeProtocolState::new(target);
let mut admitted = RNodeProtocolState::with_effective_settings(target);
if evidence.detected {
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
}
+43 -6
View File
@@ -3,6 +3,7 @@
//! selected virtual port; one write task prepends `CMD_SEL_INT` so the device
//! picks the right radio.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashSet;
use std::io::Write;
use std::sync::Arc;
@@ -205,7 +206,9 @@ impl RNodeMultiConfig {
}
}
/// SEL_INT, push params, then RADIO_STATE=ON last.
/// SEL_INT, push params, RADIO_STATE=ON, then frequency, bandwidth and TX
/// power again: firmware maps them to what the hardware will use only while
/// the radio is on, so these last echoes report the effective settings.
pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec<u8> {
let mut out = Vec::with_capacity(80);
@@ -236,6 +239,17 @@ pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec<u8
kiss::frame_with_command_into(rnode::CMD_LT_ALOCK, &[c1, c2], &mut out);
}
kiss::frame_with_command_into(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON], &mut out);
kiss::frame_with_command_into(
rnode::CMD_FREQUENCY,
&config.frequency.to_be_bytes(),
&mut out,
);
kiss::frame_with_command_into(
rnode::CMD_BANDWIDTH,
&config.bandwidth.to_be_bytes(),
&mut out,
);
kiss::frame_with_command_into(rnode::CMD_TXPOWER, &[config.tx_power], &mut out);
out
}
@@ -290,6 +304,9 @@ struct RadioEvidence {
coding_rate: Option<u8>,
tx_power: Option<u8>,
radio_state: Option<u8>,
/// A TX power echo arrived while the radio was on, so the evidence holds
/// the effective values.
effective: bool,
}
impl RadioEvidence {
@@ -300,6 +317,7 @@ impl RadioEvidence {
&& self.coding_rate.is_some()
&& self.tx_power.is_some()
&& self.radio_state.is_some()
&& self.effective
}
fn validate(self, config: &SubInterfaceConfig) -> Result<(), String> {
@@ -440,12 +458,14 @@ impl StartupEvidence {
let value = one_byte(payload, "TX power")?;
if let Some(radio) = self.selected_radio_mut() {
radio.tx_power = Some(value);
radio.effective |= radio.radio_state == Some(rnode::RADIO_STATE_ON);
}
}
rnode::CMD_RADIO_STATE => {
let value = one_byte(payload, "radio state")?;
if let Some(radio) = self.selected_radio_mut() {
radio.radio_state = Some(value);
radio.effective &= value == rnode::RADIO_STATE_ON;
}
}
CMD_ERROR => {
@@ -741,6 +761,10 @@ pub async fn spawn_rnode_multi_interface(
// stays ordered relative to each data frame.
let (write_tx, mut write_rx) = mpsc::channel::<WriteRequest>(256);
let transport_senders: Vec<_> = ids
.iter()
.map(|id| InterfaceTransportSender::new(*id, transport_tx.clone()))
.collect();
let mut background_lanes = Vec::with_capacity(num_subs);
let mut handles = Vec::with_capacity(num_subs);
let mut sub_txb: Vec<Arc<AtomicU64>> = Vec::with_capacity(num_subs);
@@ -819,6 +843,8 @@ pub async fn spawn_rnode_multi_interface(
handles.push(InterfaceHandle {
id: ids[i],
owner: transport_senders[i].owner(),
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name: sub_name,
mode: sub_cfg.mode,
@@ -1046,7 +1072,7 @@ pub async fn spawn_rnode_multi_interface(
snr,
q: None,
});
if transport_tx.send(msg).await.is_err() {
if transport_senders[local_idx].send(msg).await.is_err() {
tracing::warn!(
parent = %parent_name,
"transport channel closed"
@@ -1414,8 +1440,8 @@ mod tests {
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&seq);
// sel_int + freq + bw + sf + cr + txpower + radio_state
assert_eq!(frames.len(), 7);
// sel_int + freq + bw + sf + cr + txpower + radio_state + freq + bw + txpower
assert_eq!(frames.len(), 10);
}
#[test]
@@ -1427,8 +1453,8 @@ mod tests {
let seq = build_subinterface_init(0, &sub_cfg);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&seq);
// 7 base + 2 airtime limits
assert_eq!(frames.len(), 9);
// 10 base + 2 airtime limits
assert_eq!(frames.len(), 12);
}
#[test]
@@ -1772,10 +1798,21 @@ mod tests {
state
.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON])
.unwrap();
// Pre-RADIO_ON echoes are the request, not what the radio will use.
assert!(!state.radio_complete(0));
state
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power])
.unwrap();
assert!(state.radio_complete(0));
assert!(state.radios[0].validate(&config).is_ok());
// An amplifier floor reported once on is a mismatch.
state
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power + 3])
.unwrap();
assert!(state.radios[0].validate(&config).is_err());
let mut mismatch = state.radios[0];
mismatch.coding_rate = Some(config.coding_rate + 1);
assert!(mismatch.validate(&config).is_err());
+188 -2
View File
@@ -260,6 +260,21 @@ pub enum RNodeReadinessBlocker {
Mismatch(RNodeReadinessEvidence),
}
impl RNodeReadinessBlocker {
/// The evidence the device definitively rejected, if this blocker is one
/// that retrying the same settings cannot clear. Mirrors upstream Android
/// `RNodeInterface`, which records invalid configuration and firmware as
/// hardware errors and stops reconnecting, but retries a radio
/// initialisation failure.
pub const fn rejected_evidence(self) -> Option<RNodeReadinessEvidence> {
match self {
Self::Mismatch(evidence) => Some(evidence),
Self::UnsupportedFirmware { .. } => Some(RNodeReadinessEvidence::Firmware),
Self::RadioInitialisationFault | Self::Missing(_) => None,
}
}
}
/// Derived readiness of the generic RNode session.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RNodeReadiness {
@@ -296,13 +311,24 @@ pub enum RNodeProtocolEffect {
Rejected(RNodeFrameRejection),
}
/// Pure, order-independent reducer for generic single-radio readiness.
/// Pure reducer for generic single-radio readiness.
///
/// Order-independent unless created with
/// [`RNodeProtocolState::with_effective_settings`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RNodeProtocolState {
target: RNodeProtocolTarget,
evidence: RNodeProtocolEvidence,
detection_observed: bool,
flow_permission_observed: bool,
effective: Option<EffectiveSettings>,
}
/// Progress toward a transmit-power echo that follows `RADIO_STATE_ON`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct EffectiveSettings {
radio_on: bool,
confirmed: bool,
}
impl RNodeProtocolState {
@@ -323,9 +349,27 @@ impl RNodeProtocolState {
},
detection_observed: false,
flow_permission_observed: false,
effective: None,
}
}
/// Like [`Self::new`], but readiness also waits for a transmit-power echo
/// that follows `RADIO_STATE_ON`.
///
/// RNode firmware maps frequency, bandwidth and amplifier-backed transmit
/// power to what the hardware will use only while the radio is on; a cold
/// radio echoes the request. Callers re-assert those settings after
/// `RADIO_STATE_ON` (as `rnode::build_init_sequence` does), so readiness
/// and [`Self::definitive_rejection`] judge the effective values.
pub const fn with_effective_settings(target: RNodeProtocolTarget) -> Self {
let mut state = Self::new(target);
state.effective = Some(EffectiveSettings {
radio_on: false,
confirmed: false,
});
state
}
pub const fn target(&self) -> RNodeProtocolTarget {
self.target
}
@@ -350,11 +394,57 @@ impl RNodeProtocolState {
/// Rejected frames leave state unchanged.
pub fn apply_frame(&mut self, command: u8, payload: &[u8]) -> RNodeProtocolEffect {
match RNodeProtocolFrame::decode(command, payload) {
Ok(frame) => self.apply_decoded_frame(frame),
Ok(frame) => {
let before = self.effective;
let effect = self.apply_decoded_frame(frame);
self.observe_effective_settings(frame);
match (effect, frame) {
(RNodeProtocolEffect::NoChange, RNodeProtocolFrame::RadioState(_))
if self.effective != before =>
{
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::RadioState)
}
(RNodeProtocolEffect::NoChange, RNodeProtocolFrame::TransmitPower(_))
if self.effective != before =>
{
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::TransmitPower)
}
_ => effect,
}
}
Err(error) => RNodeProtocolEffect::Rejected(error),
}
}
/// The setting the device definitively rejected: a blocker that retrying
/// the same settings cannot clear. With effective settings this waits for
/// the post-`RADIO_STATE_ON` transmit-power echo.
pub fn definitive_rejection(&self) -> Option<RNodeReadinessEvidence> {
if self.effective.is_some_and(|effective| !effective.confirmed) {
return None;
}
match self.readiness() {
RNodeReadiness::Blocked(blocker) => blocker.rejected_evidence(),
RNodeReadiness::Ready => None,
}
}
fn observe_effective_settings(&mut self, frame: RNodeProtocolFrame) {
let Some(effective) = self.effective.as_mut() else {
return;
};
match frame {
RNodeProtocolFrame::RadioState(RNodeRadioState::On) => effective.radio_on = true,
RNodeProtocolFrame::RadioState(RNodeRadioState::Off) | RNodeProtocolFrame::Reset => {
*effective = EffectiveSettings::default();
}
RNodeProtocolFrame::TransmitPower(_) if effective.radio_on => {
effective.confirmed = true;
}
_ => {}
}
}
/// Derive readiness in stable blocker order.
pub fn readiness(&self) -> RNodeReadiness {
use RNodeReadinessBlocker::{Mismatch, Missing};
@@ -411,6 +501,9 @@ impl RNodeProtocolState {
}
Some(_) => {}
}
if self.effective.is_some_and(|effective| !effective.confirmed) {
return RNodeReadiness::Blocked(Missing(TransmitPower));
}
match self.evidence.tx_power {
None => return RNodeReadiness::Blocked(Missing(TransmitPower)),
Some(tx_power) if tx_power != self.target.tx_power => {
@@ -1001,4 +1094,97 @@ mod tests {
RNodeReadiness::Blocked(RNodeReadinessBlocker::RadioInitialisationFault)
);
}
#[test]
fn only_configuration_and_firmware_rejections_are_definitive() {
use RNodeReadinessBlocker::{Mismatch, Missing, RadioInitialisationFault};
use RNodeReadinessEvidence::{Firmware, TransmitPower};
assert_eq!(
Mismatch(TransmitPower).rejected_evidence(),
Some(TransmitPower)
);
let unsupported = RNodeReadinessBlocker::UnsupportedFirmware {
observed: RNodeFirmwareVersion::new(1, 51),
minimum: RNodeFirmwareVersion::MINIMUM_SUPPORTED,
};
assert_eq!(unsupported.rejected_evidence(), Some(Firmware));
assert_eq!(Missing(TransmitPower).rejected_evidence(), None);
assert_eq!(RadioInitialisationFault.rejected_evidence(), None);
let mut state = ready_state();
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power - 4]);
let RNodeReadiness::Blocked(blocker) = state.readiness() else {
panic!("a different transmit power echo must block readiness");
};
assert_eq!(blocker.rejected_evidence(), Some(TransmitPower));
}
fn apply_all(state: &mut RNodeProtocolState, frames: &[(u8, Vec<u8>)]) {
for (command, payload) in frames {
state.apply_frame(*command, payload);
}
}
#[test]
fn effective_settings_wait_for_a_transmit_power_echo_after_radio_on() {
let mut state = RNodeProtocolState::with_effective_settings(TARGET);
apply_all(&mut state, &required_frames());
// Pre-RADIO_ON echoes alone satisfy the order-independent reducer only.
assert_eq!(
state.readiness(),
RNodeReadiness::Blocked(RNodeReadinessBlocker::Missing(
RNodeReadinessEvidence::TransmitPower
))
);
assert_eq!(state.definitive_rejection(), None);
// An unchanged value still confirms, and reports the change.
assert_eq!(
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]),
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::TransmitPower)
);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
// A radio that turns off needs a fresh confirmation.
state.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_OFF]);
state.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON]);
assert_ne!(state.readiness(), RNodeReadiness::Ready);
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
}
#[test]
fn effective_settings_judge_the_amplifier_mapped_echo() {
// A cold amplifier board echoes the request, then its floor once on.
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 2);
let mut state = RNodeProtocolState::with_effective_settings(target);
let mut frames = required_frames().to_vec();
frames[6] = (rnode::CMD_TXPOWER, vec![2]);
apply_all(&mut state, &frames);
assert_eq!(state.definitive_rejection(), None);
state.apply_frame(rnode::CMD_TXPOWER, &[13]);
assert_eq!(
state.definitive_rejection(),
Some(RNodeReadinessEvidence::TransmitPower)
);
// The legacy reducer accepts the same cold echoes.
let mut legacy = RNodeProtocolState::new(target);
apply_all(&mut legacy, &frames);
assert_eq!(legacy.readiness(), RNodeReadiness::Ready);
}
#[test]
fn effective_settings_reset_with_the_device() {
let mut state = RNodeProtocolState::with_effective_settings(TARGET);
apply_all(&mut state, &required_frames());
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
state.apply_frame(rnode::CMD_RESET, &[0xF8]);
apply_all(&mut state, &required_frames());
assert_ne!(state.readiness(), RNodeReadiness::Ready);
}
}
+5
View File
@@ -1,6 +1,7 @@
//! HDLC-framed data over a serial port. Uses `serialport` with
//! `spawn_blocking` because no mature async driver exists yet.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -81,6 +82,8 @@ pub async fn spawn_serial_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
@@ -192,6 +195,8 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
+170 -43
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -9,7 +10,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -26,15 +28,30 @@ pub const TCP_KEEPIDLE: u32 = 5;
pub const TCP_KEEPINTVL: u32 = 2;
pub const TCP_KEEPCNT: u32 = 12;
/// Tuned keepalive (idle/interval/count + Linux `TCP_USER_TIMEOUT`) for plain
/// TCP client and accepted sockets, matching Python `set_timeouts_linux`.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream) {
/// Python's ordinary TCP or I2P Linux timeout values through the shared Rust
/// socket tuner. Accepted sockets use ordinary TCP tuning.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream, i2p_tunneled: bool) {
let (idle, interval, count, user_timeout) = if i2p_tunneled {
(
crate::i2p::I2P_PROBE_AFTER,
crate::i2p::I2P_PROBE_INTERVAL,
crate::i2p::I2P_PROBES as u32,
crate::i2p::I2P_TCP_USER_TIMEOUT,
)
} else {
(
TCP_KEEPIDLE as u64,
TCP_KEEPINTVL as u64,
TCP_KEEPCNT,
DEFAULT_TCP_USER_TIMEOUT,
)
};
crate::socket_tuning::set_keepalive_tuned(
stream,
std::time::Duration::from_secs(TCP_KEEPIDLE as u64),
std::time::Duration::from_secs(TCP_KEEPINTVL as u64),
TCP_KEEPCNT,
std::time::Duration::from_secs(DEFAULT_TCP_USER_TIMEOUT as u64),
std::time::Duration::from_secs(idle),
std::time::Duration::from_secs(interval),
count,
std::time::Duration::from_secs(user_timeout as u64),
);
}
@@ -44,11 +61,16 @@ pub struct TcpClientConfig {
pub target_host: String,
pub target_port: u16,
pub kiss_framing: bool,
/// Use the longer socket timeouts for a TCP connection tunneled over I2P.
pub i2p_tunneled: bool,
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
pub fixed_mtu: Option<u32>,
/// Signs a tunnel synthesis for every connection unless KISS-framed;
/// `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl TcpClientConfig {
@@ -58,12 +80,24 @@ impl TcpClientConfig {
target_host: host.to_string(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
}
}
/// Python `str(TCPClientInterface)` (TCPInterface.py:457-461).
pub fn python_name(&self) -> String {
format!(
"TCPInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone)]
@@ -182,7 +216,7 @@ use crate::socket_tuning::set_socket_buffers;
async fn tcp_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
state: Arc<TcpInterfaceState>,
kiss_framing: bool,
) {
@@ -294,6 +328,16 @@ pub async fn spawn_tcp_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
if config
.fixed_mtu
.is_some_and(|mtu| !(500..=262144).contains(&mtu))
{
return Err(crate::traits::InterfaceError::SendFailed(
"fixed_mtu must be between 500 and 262144 clear packet bytes".into(),
));
}
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(1024);
@@ -310,12 +354,16 @@ pub async fn spawn_tcp_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut backoff = RECONNECT_WAIT_INITIAL;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let addr = format!("{}:{}", config.target_host, config.target_port);
let stream = match tokio::time::timeout(
std::time::Duration::from_secs(config.connect_timeout_secs),
@@ -360,7 +408,7 @@ pub async fn spawn_tcp_client(
}
};
set_tcp_keepalive_tuned(&stream);
set_tcp_keepalive_tuned(&stream, config.i2p_tunneled);
// Nagle off for low-latency packets; larger buffers for bulk transfers.
let _ = stream.set_nodelay(true);
@@ -368,9 +416,16 @@ pub async fn spawn_tcp_client(
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
state.online.store(true, Ordering::SeqCst);
online2.store(true, Ordering::SeqCst);
tries = 0;
backoff = RECONNECT_WAIT_INITIAL;
// Python synthesizes on every non-KISS connection
// (TCPInterface.py:178-179, :298-299).
let synthesis = config
.tunnel_identity
.as_ref()
.filter(|_| !kiss_framing)
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online2).await;
let (reader, writer) = stream.into_split();
@@ -424,6 +479,14 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
fixed_mtu
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU))
.min(262144),
262144,
fixed_mtu.is_some() || crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -461,6 +524,8 @@ async fn spawn_tcp_accepted(
kiss_framing: bool,
mode: InterfaceMode,
) -> InterfaceHandle {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let (tx, conn_rx) = mpsc::channel::<Bytes>(1024);
@@ -470,7 +535,7 @@ async fn spawn_tcp_accepted(
let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone());
state.online.store(true, Ordering::SeqCst);
set_tcp_keepalive_tuned(&stream);
set_tcp_keepalive_tuned(&stream, false);
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
@@ -494,6 +559,14 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: Some(parent_id),
name,
mode,
@@ -523,6 +596,8 @@ pub async fn spawn_tcp_server(
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let addr = match config.device.as_deref() {
Some(device) => {
let ip = address_for_device(device, config.prefer_ipv6).ok_or_else(|| {
@@ -559,7 +634,7 @@ pub async fn spawn_tcp_server(
client_id,
id,
client_name,
transport_tx.clone(),
transport_tx.actor_sender(),
kiss_framing,
mode,
)
@@ -584,6 +659,14 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -608,6 +691,24 @@ pub async fn spawn_tcp_server(
mod tests {
use super::*;
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
("127.0.0.1", "TCPInterface[Golden Uplink/127.0.0.1:4242]"),
("::1", "TCPInterface[Golden Uplink/[::1]:4242]"),
(
"hub.example.org",
"TCPInterface[Golden Uplink/hub.example.org:4242]",
),
] {
assert_eq!(
TcpClientConfig::new("Golden Uplink", host, 4242).python_name(),
expected
);
}
}
#[test]
fn test_tcp_client_config() {
let config = TcpClientConfig::new("test", "127.0.0.1", 4242);
@@ -623,9 +724,8 @@ mod tests {
assert!(!config.prefer_ipv6);
}
/// T1-2 regression: the client/accept paths must apply the TUNED keepalive
/// (idle 5s + 12 probes × 2s ≈ 29s dead-peer parity with Python), not just
/// SO_KEEPALIVE. Reads the options back via getsockopt.
/// Read back Python's Linux timeout values applied by the shared Rust
/// socket tuner for ordinary TCP and I2P-tunneled connections.
#[cfg(unix)]
#[tokio::test]
async fn tuned_keepalive_applies_python_probe_values() {
@@ -653,33 +753,35 @@ mod tests {
let client = client.unwrap();
let (server, _) = accepted.unwrap();
for stream in [&client, &server] {
set_tcp_keepalive_tuned(stream);
let fd = stream.as_ref().as_raw_fd();
// BSD getsockopt returns the option bit, not 1 — assert enabled.
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
for (i2p_tunneled, _expected) in [(false, [5, 2, 12, 24]), (true, [10, 9, 5, 45])] {
for stream in [&client, &server] {
set_tcp_keepalive_tuned(stream, i2p_tunneled);
let fd = stream.as_ref().as_raw_fd();
// BSD getsockopt returns the option bit, not 1 — assert enabled.
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
#[cfg(target_os = "linux")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
#[cfg(target_os = "macos")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert_eq!(idle, TCP_KEEPIDLE as i32);
#[cfg(target_os = "linux")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
#[cfg(target_os = "macos")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert_eq!(idle, _expected[0]);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
_expected[1]
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
_expected[2]
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
TCP_KEEPINTVL as i32
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
TCP_KEEPCNT as i32
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
_expected[3] * 1000
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
(DEFAULT_TCP_USER_TIMEOUT * 1000) as i32
);
}
}
@@ -700,12 +802,13 @@ mod tests {
config.connect_timeout_secs = 2;
let handle = spawn_tcp_client(config, 77, transport_tx).await.unwrap();
handle.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(10), transport_rx.recv())
.await
.expect("expected DeregisterInterface before timeout")
.expect("transport channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &handle) {
TransportMessage::DeregisterInterface { id } => assert_eq!(id, 77),
other => panic!("expected DeregisterInterface, got {other:?}"),
}
@@ -759,6 +862,7 @@ mod tests {
spawn_tcp_server(server_cfg2, 99, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 99);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -768,29 +872,42 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.packet_capacity.max_wire_packet_bytes, 262144);
let payload = Bytes::from_static(b"hello from client");
client_handle.tx.send(payload.clone()).await.unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), transport_rx.recv())
.await
.is_err(),
"the first packet waits for accepted-child registration"
);
accepted.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for transport message")
.expect("transport channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -806,7 +923,7 @@ mod tests {
.expect("timeout waiting for reply")
.expect("transport channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 1);
@@ -853,13 +970,16 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: 1,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 1,
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
handle.owner.mark_registered();
// Two failed tries with 5s waits each; 20s headroom.
let result =
@@ -887,6 +1007,7 @@ mod tests {
spawn_tcp_server(server_cfg, 88, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -895,19 +1016,23 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client-side tasks; server's per-client reader sees EOF and exits.
@@ -919,7 +1044,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
+106
View File
@@ -8,6 +8,8 @@ pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub owner: rns_transport::messages::InterfaceOwner,
pub packet_capacity: rns_transport::messages::InterfacePacketCapacity,
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
@@ -50,6 +52,67 @@ pub(crate) async fn handoff_accepted_interface(
}
}
/// The transport identity a client signs its tunnel syntheses with (Python
/// `Transport.identity`). Debug shows only its hash.
#[derive(Clone)]
pub struct TunnelIdentity(pub Arc<rns_identity::identity::Identity>);
impl TunnelIdentity {
/// A fresh synthesis for the interface whose Python `str()` is
/// `python_name` (Transport.py:2764-2785).
pub fn synthesis(&self, python_name: &str) -> Option<Bytes> {
rns_transport::tunnel::build_tunnel_synthesis_packet(
&self.0,
rns_transport::tunnel::interface_hash(python_name),
)
.map(Bytes::from)
}
}
impl std::fmt::Debug for TunnelIdentity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TunnelIdentity")
.field(&hex::encode(self.0.hash))
.finish()
}
}
/// A host as Python's interface `str()` renders it: IPv6 in brackets.
pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
if host.contains(':') {
format!("[{host}]").into()
} else {
host.into()
}
}
/// Start a client connection as Python does: traffic queued during an outage
/// is dropped (TCPInterface.py:314-315), then the connection's synthesis is
/// queued, and only then does the interface report online.
pub(crate) async fn open_client_connection(
outbound: &tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
after_outage: bool,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
synthesis: Option<Bytes>,
online: &AtomicBool,
) {
if after_outage {
let mut queued = outbound.lock().await;
while queued.try_recv().is_ok() {}
}
if let Some(raw_packet) = synthesis {
let _ = transport_tx
.send(
rns_transport::messages::TransportMessage::SynthesizeTunnel {
interface_id: transport_tx.interface_id(),
raw_packet,
},
)
.await;
}
online.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Interface operating mode. Byte values are on-wire constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
@@ -183,6 +246,45 @@ pub enum InterfaceError {
Io(#[from] std::io::Error),
}
#[cfg(test)]
pub(crate) fn test_registered_sender(
id: rns_transport::messages::InterfaceId,
tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
) -> rns_transport::messages::InterfaceTransportSender {
let sender = rns_transport::messages::InterfaceTransportSender::new(id, tx);
sender.owner().mark_registered();
sender
}
#[cfg(test)]
pub(crate) fn test_event_body(
message: rns_transport::messages::TransportMessage,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent { message, .. } => *message,
message => message,
}
}
#[cfg(test)]
pub(crate) fn test_event_for_handle(
message: rns_transport::messages::TransportMessage,
handle: &InterfaceHandle,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent {
interface_id,
owner,
message,
} => {
assert_eq!(interface_id, handle.id);
assert_eq!(owner, handle.owner);
*message
}
other => panic!("expected registration-bound interface event, got {other:?}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -298,6 +400,8 @@ mod tests {
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 1,
parent_id: Some(0),
name: "rejected-child".to_string(),
@@ -341,6 +445,8 @@ mod tests {
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 2,
parent_id: Some(0),
name: "accepted-child".to_string(),
+11 -2
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -54,6 +55,8 @@ pub async fn spawn_udp_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
// Python UDPInterface `device =`: fill unset listen/forward IPs with the
// NIC's IPv4 broadcast address; a device that can't be resolved is a
// config error, not a silent fallback to wildcard.
@@ -166,6 +169,8 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -236,6 +241,7 @@ mod tests {
let handle = spawn_udp_interface(cfg, 2, transport_tx)
.await
.expect("explicit IPs bypass device resolution");
handle.owner.mark_registered();
handle.read_task.abort();
}
@@ -278,6 +284,7 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
// Reserve two free ports via bind-drop; handle doesn't expose its addr.
let sock_tmp1 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -298,9 +305,11 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
let handle_b = spawn_udp_interface(cfg_b, 20, transport_tx.clone())
.await
.unwrap();
handle_b.owner.mark_registered();
// A → B's listen port; inbound carries B's interface_id (20).
let payload = Bytes::from_static(b"udp test data");
@@ -311,7 +320,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &handle_b) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, 20);
@@ -327,7 +336,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &handle_a) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 10);
@@ -0,0 +1,212 @@
//! A SAM session's private key, read from its key file or returned by the SAM
//! bridge, must not survive in freed heap memory.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_interface::i2p::{I2PClientConfig, I2PServerConfig, spawn_i2p_client, spawn_i2p_server};
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
/// A SAM private key: a destination of 384 key bytes and an Ed25519 key
/// certificate, then 256 private and 32 signing-key bytes. Returns the key's
/// bytes and its I2P base64 text.
fn sam_private_key(seed: u64) -> (Vec<u8>, String) {
let mut key = pseudo_random::<384>(seed).to_vec();
key.extend_from_slice(&[5, 0, 4, 0, 7, 0, 0]);
key.extend_from_slice(&pseudo_random::<288>(seed + 1));
let mut text = String::new();
for chunk in key.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
(key, text)
}
/// A SAM bridge on its own threads, so none of its frees are recorded. A
/// session keeps the key it asks for, a transient one gets `transient`, and a
/// STREAM CONNECT succeeds; every socket then stays open.
fn sam_bridge(transient: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(socket) = socket else { return };
let transient = transient.clone();
std::thread::spawn(move || serve(socket, &transient));
}
});
port
}
fn serve(mut socket: TcpStream, transient: &str) {
let mut reader = BufReader::new(socket.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
let _ = socket.write_all(b"HELLO REPLY RESULT=OK VERSION=3.1\n");
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
if line.starts_with("SESSION CREATE") {
let destination = match line
.split_whitespace()
.find_map(|token| token.strip_prefix("DESTINATION="))
{
Some("TRANSIENT") | None => transient,
Some(key) => key,
};
let _ = socket
.write_all(format!("SESSION STATUS RESULT=OK DESTINATION={destination}\n").as_bytes());
} else if line.starts_with("STREAM CONNECT") {
let _ = socket.write_all(b"STREAM STATUS RESULT=OK\n");
}
let mut rest = Vec::new();
let _ = std::io::Read::read_to_end(&mut reader, &mut rest);
}
/// Run `body` on a current-thread runtime inside the check, then drop the
/// runtime there too, so every task's frees are recorded.
fn checked(body: impl std::future::Future<Output = ()>) -> residue::Freed {
let ((), freed) = freed_by(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(body);
drop(runtime);
});
freed
}
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn temp_dir(label: &str) -> TempDir {
let path = std::env::temp_dir().join(format!("rns-i2p-residue-{label}-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
TempDir(path)
}
async fn run_server(sam_port: u16, key_path: PathBuf) {
let (b32_tx, mut b32_rx) = tokio::sync::watch::channel(None);
let mut config = I2PServerConfig::new("residue");
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
config.key_path = Some(key_path);
config.b32 = Some(b32_tx);
let (transport_tx, _transport_rx) = tokio::sync::mpsc::channel(16);
let (handle_tx, _handle_rx) = tokio::sync::mpsc::channel(16);
let _handle = spawn_i2p_server(
config,
1,
Arc::new(AtomicU64::new(2)),
transport_tx,
handle_tx,
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(10), b32_rx.wait_for(Option::is_some))
.await
.expect("session created")
.unwrap();
// Let the server reach its STREAM ACCEPT.
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[test]
fn i2p_server_with_a_stored_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(10);
let sam_port = sam_bridge(sam_private_key(11).1);
let dir = temp_dir("stored");
let key_path = dir.0.join("i2p.key");
std::fs::write(&key_path, format!("{text}\n")).unwrap();
let freed = checked(run_server(sam_port, key_path));
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_storing_a_new_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(20);
let sam_port = sam_bridge(text.clone());
let dir = temp_dir("new");
let key_path = dir.0.join("i2p.key");
let freed = checked(run_server(sam_port, key_path.clone()));
assert_eq!(std::fs::read_to_string(&key_path).unwrap(), text);
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_client_session_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(30);
let sam_port = sam_bridge(text.clone());
let peer = sam_private_key(40).1;
let freed = checked(async move {
let mut config = I2PClientConfig::new("residue", &peer[..516]);
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
let (transport_tx, mut transport_rx) = tokio::sync::mpsc::channel(16);
let handle = spawn_i2p_client(config, 1, transport_tx).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), async {
while !handle.online.load(Ordering::SeqCst) {
tokio::select! {
_ = transport_rx.recv() => {}
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.expect("client online");
});
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_debug_output_hides_its_key() {
let (_, text) = sam_private_key(50);
let mut config = I2PServerConfig::new("residue");
config.keyfile = Some(text.clone());
let shown = format!("{config:?}");
assert!(!shown.contains(&text[..32]), "{shown}");
assert!(shown.contains("residue"), "{shown}");
}
+6
View File
@@ -22,5 +22,11 @@ rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_System_Performance"] }
[dev-dependencies]
proptest = { workspace = true }
+323
View File
@@ -0,0 +1,323 @@
//! A monotonic clock that keeps counting while the system is suspended.
//!
//! `std::time::Instant` stops while Apple, Linux and Android systems sleep,
//! so a deadline measured on it ends late by the whole sleep. This clock
//! counts that time: `CLOCK_BOOTTIME` on Linux and Android,
//! `CLOCK_MONOTONIC_RAW` (`mach_continuous_time`) on Apple platforms, and the
//! performance counter on Windows. On other targets it is best effort,
//! `std::time::Instant` from the first reading in the process.
//!
//! Timers do not run on this clock: tokio and the operating system's waits
//! count awake time only. Check a deadline against [`ContinuousInstant::now`]
//! on a regular tick instead of arming a timer for it.
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::time::Duration;
/// A reading of the suspend-counting clock, in signed nanoseconds from the
/// platform's origin, usually boot.
///
/// Readings are process-local: never persist one or send it to another
/// process, which is what wall time is for. They do not convert to or from
/// `std::time::Instant`, so the two clocks never mix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContinuousInstant(i64);
impl ContinuousInstant {
/// The current reading.
///
/// # Panics
///
/// If the platform clock fails, as `std::time::Instant::now` does.
pub fn now() -> Self {
Self(backend::now_nanos())
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn duration_since(self, earlier: Self) -> Duration {
self.saturating_duration_since(earlier)
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
/// The time from `earlier` to `self`, or `None` if `earlier` is later.
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
let nanos = i128::from(self.0) - i128::from(earlier.0);
u64::try_from(nanos).ok().map(Duration::from_nanos)
}
/// The time since this reading, including time the system was suspended.
pub fn elapsed(self) -> Duration {
Self::now().duration_since(self)
}
/// `self + duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_add(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) + nanos(duration)?)
}
/// `self - duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_sub(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) - nanos(duration)?)
}
fn from_nanos(nanos: i128) -> Option<Self> {
i64::try_from(nanos).ok().map(Self)
}
}
fn nanos(duration: Duration) -> Option<i128> {
i128::try_from(duration.as_nanos()).ok()
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Add<Duration> for ContinuousInstant {
type Output = Self;
fn add(self, duration: Duration) -> Self {
self.checked_add(duration)
.expect("overflow when adding duration to instant")
}
}
impl AddAssign<Duration> for ContinuousInstant {
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Sub<Duration> for ContinuousInstant {
type Output = Self;
fn sub(self, duration: Duration) -> Self {
self.checked_sub(duration)
.expect("overflow when subtracting duration from instant")
}
}
impl SubAssign<Duration> for ContinuousInstant {
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
impl Sub for ContinuousInstant {
type Output = Duration;
fn sub(self, earlier: Self) -> Duration {
self.duration_since(earlier)
}
}
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
mod backend {
#[cfg(any(target_os = "linux", target_os = "android"))]
const CLOCK: libc::clockid_t = libc::CLOCK_BOOTTIME;
#[cfg(target_vendor = "apple")]
const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC_RAW;
// `time_t` and `c_long` are 32 bits wide on some of these targets.
#[allow(clippy::useless_conversion)]
pub(super) fn now_nanos() -> i64 {
let mut now = std::mem::MaybeUninit::<libc::timespec>::uninit();
// SAFETY: `now` is valid for writes of a timespec for the whole call.
let result = unsafe { libc::clock_gettime(CLOCK, now.as_mut_ptr()) };
assert_eq!(
result,
0,
"clock_gettime failed: {}",
std::io::Error::last_os_error()
);
// SAFETY: a successful `clock_gettime` filled in `now`.
let now = unsafe { now.assume_init() };
i64::from(now.tv_sec) * 1_000_000_000 + i64::from(now.tv_nsec)
}
}
#[cfg(windows)]
mod backend {
use std::sync::OnceLock;
use windows_sys::Win32::System::Performance::{
QueryPerformanceCounter, QueryPerformanceFrequency,
};
fn frequency() -> i64 {
static FREQUENCY: OnceLock<i64> = OnceLock::new();
*FREQUENCY.get_or_init(|| {
let mut frequency = 0;
// SAFETY: `frequency` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceFrequency(&mut frequency) } != 0;
assert!(
succeeded && frequency > 0,
"QueryPerformanceFrequency failed"
);
frequency
})
}
pub(super) fn now_nanos() -> i64 {
let mut counter = 0;
// SAFETY: `counter` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceCounter(&mut counter) } != 0;
assert!(succeeded, "QueryPerformanceCounter failed");
let nanos = i128::from(counter) * 1_000_000_000 / i128::from(frequency());
i64::try_from(nanos).expect("performance counter beyond the clock's range")
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
windows
)))]
mod backend {
use std::sync::OnceLock;
use std::time::Instant;
pub(super) fn now_nanos() -> i64 {
static ORIGIN: OnceLock<Instant> = OnceLock::new();
let origin = *ORIGIN.get_or_init(Instant::now);
i64::try_from(origin.elapsed().as_nanos()).expect("clock beyond its range")
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn readings_never_go_backwards() {
let mut last = ContinuousInstant::now();
for _ in 0..10_000 {
let now = ContinuousInstant::now();
assert!(now >= last, "{now:?} after {last:?}");
last = now;
}
}
/// While the system is awake the clock keeps `Instant`'s rate, which
/// catches a backend's unit or scaling mistake. Each reading is bracketed
/// by two `Instant` readings, so a preemption widens the bounds instead of
/// failing the check.
#[test]
fn it_runs_at_instants_rate_while_awake() {
let bracketed = || {
let before = std::time::Instant::now();
let reading = ContinuousInstant::now();
(before, reading, std::time::Instant::now())
};
let (start_before, start, start_after) = bracketed();
std::thread::sleep(Duration::from_millis(200));
let (end_before, end, end_after) = bracketed();
let advance = (end - start).as_secs_f64();
let shortest = end_before.duration_since(start_after).as_secs_f64();
let longest = end_after.duration_since(start_before).as_secs_f64();
assert!(
(shortest * 0.95..=longest * 1.05).contains(&advance),
"advanced {advance}s while Instant advanced {shortest}s to {longest}s"
);
}
#[test]
fn backdating_never_underflows() {
let now = ContinuousInstant::now();
let century = Duration::from_secs(100 * 365 * 24 * 3600);
let past = now - century;
assert!(past < now);
assert_eq!(now.duration_since(past), century);
let later = ContinuousInstant::now();
assert_eq!(later - past - (later - now), century);
}
#[test]
fn a_later_earlier_reading_saturates() {
let (earlier, later) = (ContinuousInstant(-5), ContinuousInstant(7));
assert_eq!(later - earlier, Duration::from_nanos(12));
assert_eq!(earlier - later, Duration::ZERO);
assert_eq!(earlier.duration_since(later), Duration::ZERO);
assert_eq!(earlier.saturating_duration_since(later), Duration::ZERO);
assert_eq!(earlier.checked_duration_since(later), None);
assert_eq!(later.checked_duration_since(later), Some(Duration::ZERO));
}
#[test]
fn arithmetic_beyond_the_range_is_none() {
let (min, max) = (ContinuousInstant(i64::MIN), ContinuousInstant(i64::MAX));
assert_eq!(max.checked_add(Duration::from_nanos(1)), None);
assert_eq!(min.checked_sub(Duration::from_nanos(1)), None);
assert_eq!(ContinuousInstant(0).checked_add(Duration::MAX), None);
assert_eq!(ContinuousInstant(0).checked_sub(Duration::MAX), None);
assert_eq!(
max.checked_duration_since(min),
Some(Duration::from_nanos(u64::MAX))
);
}
#[test]
#[should_panic(expected = "overflow when adding duration to instant")]
fn adding_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MAX) + Duration::from_nanos(1);
}
#[test]
#[should_panic(expected = "overflow when subtracting duration from instant")]
fn subtracting_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MIN) - Duration::from_nanos(1);
}
#[test]
fn assigning_operators_match_the_plain_ones() {
let start = ContinuousInstant(1_000);
let mut moved = start;
moved += Duration::from_nanos(250);
assert_eq!(moved, start + Duration::from_nanos(250));
moved -= Duration::from_nanos(500);
assert_eq!(moved, start - Duration::from_nanos(250));
}
proptest! {
#[test]
fn a_duration_added_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let start = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match start.checked_add(duration) {
Some(end) => {
prop_assert_eq!(end - start, duration);
prop_assert_eq!(end.checked_sub(duration), Some(start));
prop_assert_eq!(start.saturating_duration_since(end), Duration::ZERO);
prop_assert_eq!(
start.checked_duration_since(end),
(nanos == 0).then_some(Duration::ZERO)
);
}
None => prop_assert!(i128::from(origin) + i128::from(nanos) > i128::from(i64::MAX)),
}
}
#[test]
fn a_duration_subtracted_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let end = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match end.checked_sub(duration) {
Some(start) => {
prop_assert_eq!(end.duration_since(start), duration);
prop_assert_eq!(start.checked_add(duration), Some(end));
}
None => prop_assert!(i128::from(origin) - i128::from(nanos) < i128::from(i64::MIN)),
}
}
}
}
+19 -2
View File
@@ -79,6 +79,7 @@ impl LinkRequestData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_request_signalling(data)?;
let mut x25519_pub = [0u8; 32];
x25519_pub.copy_from_slice(&data[0..32]);
@@ -217,6 +218,7 @@ impl LinkProofData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_proof_signalling(data)?;
let mut signature = [0u8; 64];
signature.copy_from_slice(&data[0..64]);
@@ -272,6 +274,8 @@ pub fn perform_handshake(
#[derive(Debug, thiserror::Error)]
pub enum HandshakeError {
#[error(transparent)]
Signalling(#[from] rns_wire::link_signalling::LinkSignallingError),
#[error("handshake data too short")]
TooShort,
#[error("invalid handshake data length: {0}")]
@@ -527,7 +531,7 @@ mod tests {
x25519_pub: [u8; 32],
ed25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
// EphemeralKeys is the higher-level wrapper; we pack the
@@ -553,7 +557,7 @@ mod tests {
signature: [u8; 64],
responder_x25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
let proof = LinkProofData {
@@ -570,5 +574,18 @@ mod tests {
prop_assert_eq!(unpacked.signalling, signalling);
prop_assert_eq!(unpacked.pack(), packed);
}
/// The representation packer remains permissive, but both handshake
/// parsers reject every nonzero offer below the supported Link floor.
#[test]
fn proptest_handshake_rejects_sub_base_mtu(mode in 0u8..=7, mtu in 1u32..500) {
let signalling = SignallingData::new(mode, mtu).pack();
let mut request = vec![0u8; ECPUBSIZE];
request.extend_from_slice(&signalling);
prop_assert!(LinkRequestData::unpack(&request).is_err());
let mut proof = vec![0u8; 96];
proof.extend_from_slice(&signalling);
prop_assert!(LinkProofData::unpack(&proof).is_err());
}
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::{Zeroize, Zeroizing};
use zeroize::Zeroize;
use crate::constants::{
AES128_DERIVED_KEY_LENGTH, AES256_DERIVED_KEY_LENGTH, MODE_AES128_CBC, MODE_AES256_CBC,
@@ -38,7 +38,7 @@ impl LinkKeys {
rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None)
.map_err(|_| LinkKeyError::HkdfFailed);
shared_key.zeroize();
let derived = Zeroizing::new(derived_result?);
let derived = derived_result?;
let half = derived_key_length / 2;
let signing_key = derived[..half].to_vec();
+1
View File
@@ -2,6 +2,7 @@
//! LR/LRPROOF handshake → AES-256 + HMAC-SHA256 session, MTU discovery,
//! keepalives, request/response. Python reference: `RNS/Link.py`.
pub mod clock;
pub mod constants;
pub mod encryption;
pub mod handshake;
+253 -116
View File
@@ -11,7 +11,7 @@ use crate::handshake::{
};
use crate::keepalive::KeepaliveState;
use crate::key_derivation::LinkKeys;
use crate::mtu_discovery::SignallingData;
use crate::mtu_discovery::{LinkMtu, SignallingData};
use crate::request::RequestReceipt;
/// Link lifecycle states.
@@ -55,6 +55,11 @@ pub enum PacketProofError {
InvalidSignature,
}
/// Local timeout input cannot be represented without overflow.
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)]
#[error("timeout must be finite, nonnegative and representable by this platform")]
pub struct TimeoutError;
/// Reason for link closure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseReason {
@@ -160,6 +165,8 @@ pub struct Link {
pub teardown_reason: Option<CloseReason>,
pub is_initiator: bool,
pub mode: u8,
offered_mode: u8,
offered_mtu: LinkMtu,
ephemeral_keys: Option<EphemeralKeys>,
peer_x25519_pub: Option<[u8; 32]>,
@@ -274,6 +281,8 @@ impl Link {
teardown_reason: None,
is_initiator: true,
mode: DEFAULT_MODE,
offered_mode: DEFAULT_MODE,
offered_mtu: LinkMtu::BASE,
ephemeral_keys: Some(ephemeral_keys),
peer_x25519_pub: None,
peer_packet_proof_key: None,
@@ -320,8 +329,23 @@ impl Link {
}
/// Extend the establishment timeout, typically by the transport's first-hop RTT.
#[deprecated(note = "use try_extend_establishment_timeout to report invalid input")]
pub fn extend_establishment_timeout(&mut self, additional_secs: f64) {
self.establishment_timeout += Duration::from_secs_f64(additional_secs);
let _ = self.try_extend_establishment_timeout(additional_secs);
}
pub fn try_extend_establishment_timeout(
&mut self,
additional_secs: f64,
) -> Result<(), TimeoutError> {
let additional = Duration::try_from_secs_f64(additional_secs).map_err(|_| TimeoutError)?;
let timeout = self
.establishment_timeout
.checked_add(additional)
.ok_or(TimeoutError)?;
self.request_time.checked_add(timeout).ok_or(TimeoutError)?;
self.establishment_timeout = timeout;
Ok(())
}
/// Handle a received link proof (initiator side, Message 2).
@@ -338,90 +362,68 @@ impl Link {
return Err(HandshakeError::InvalidSignature);
}
// LRPROOF is unauthenticated until its signature validates. Reject a
// mismatched mode without mutating the pending Link, otherwise any
// party that learns the link id could cancel establishment before the
// legitimate proof arrives.
if proof_data.len() > 96 {
let proof_mode = (proof_data[96] & MODE_BYTEMASK as u8) >> 5;
if proof_mode != self.mode {
return Err(HandshakeError::InvalidSignature);
}
let checked = rns_wire::link_signalling::parse_proof_signalling(proof_data)?;
if checked.mode != self.offered_mode {
return Err(HandshakeError::InvalidSignature);
}
if !ENABLED_MODES.contains(&checked.mode) {
return Err(HandshakeError::UnsupportedMode(checked.mode));
}
if checked.mtu > self.offered_mtu {
return Err(rns_wire::link_signalling::LinkSignallingError::InvalidMtu(
checked.mtu.get(),
)
.into());
}
let mdu = checked.mtu.checked_mdu()?;
let proof = LinkProofData::unpack(proof_data)?;
if proof.signalling.mode != self.mode {
// Authenticate the original trailer, including zero or exact absence.
// Normalizing metadata must never change bytes covered by the signature.
let mut signed = Vec::with_capacity(83);
signed.extend_from_slice(&self.link_id);
signed.extend_from_slice(&proof.responder_x25519_pub);
signed.extend_from_slice(identity_ed25519_pub_bytes);
signed.extend_from_slice(&proof_data[96..]);
if identity_verify_key
.verify(&signed, &proof.signature)
.is_err()
{
return Err(HandshakeError::InvalidSignature);
}
// Verify the signature before deriving session keys so we never hold keys
// tied to an unvalidated proof, even transiently. Invalid proofs leave
// the initiator Pending so another interface can still deliver the
// authentic proof before the establishment timeout.
if !proof.validate(
identity_verify_key,
&self.link_id,
identity_ed25519_pub_bytes,
) {
return Err(HandshakeError::InvalidSignature);
}
self.establishment_cost += proof_data.len();
self.peer_x25519_pub = Some(proof.responder_x25519_pub);
self.peer_packet_proof_key = Some(*identity_ed25519_pub_bytes);
let ephemeral = self
.ephemeral_keys
.as_ref()
.ok_or(HandshakeError::InvalidSignature)?;
let keys = perform_handshake(
&ephemeral.x25519_prv,
&proof.responder_x25519_pub,
&self.link_id,
self.mode,
checked.mode,
)?;
self.session_keys = Some(keys);
self.state = LinkState::Handshake;
tracing::debug!(link_id = ?self.link_id, "link state -> Handshake (initiator)");
let rtt = self.request_time.elapsed();
let mut rtt_bytes = Vec::new();
rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt.as_secs_f64()))
.map_err(|_| HandshakeError::InvalidSignature)?;
let encrypted_rtt =
link_encrypt(&keys, &rtt_bytes).map_err(|_| HandshakeError::InvalidSignature)?;
// All fallible validation/crypto work completes before pending state,
// key ownership, timing or accounting is changed.
self.establishment_cost = self.establishment_cost.saturating_add(proof_data.len());
self.peer_x25519_pub = Some(proof.responder_x25519_pub);
self.peer_packet_proof_key = Some(*identity_ed25519_pub_bytes);
self.session_keys = Some(keys);
self.mode = checked.mode;
self.mtu = checked.mtu.get();
self.mdu = mdu;
self.rtt = Some(rtt);
self.state = LinkState::Active;
self.activated_at = Some(Instant::now());
tracing::debug!(
link_id = ?self.link_id,
rtt_ms = rtt.as_millis() as u64,
"link state -> Active (initiator)"
);
// Seed the keepalive baseline so stale detection starts from activation.
self.keepalive.mark_activated();
let rtt_secs_val = rtt.as_secs_f64();
if rtt_secs_val > 0.0 && self.establishment_cost > 0 {
self.establishment_rate = Some(self.establishment_cost as f64 / rtt_secs_val);
}
self.keepalive.update_from_rtt(rtt);
if proof.signalling.mtu > 0 {
self.mtu = self.mtu.min(proof.signalling.mtu);
if rtt.as_secs_f64() > 0.0 {
self.establishment_rate = Some(self.establishment_cost as f64 / rtt.as_secs_f64());
}
self.update_mdu();
// RTT is carried as a msgpack f64 so both ends see the same encoding.
let rtt_secs = rtt.as_secs_f64();
let mut rtt_bytes = Vec::new();
rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt_secs))
.map_err(|_| HandshakeError::InvalidSignature)?;
let encrypted_rtt = self
.encrypt(&rtt_bytes)
.map_err(|_| HandshakeError::InvalidSignature)?;
tracing::debug!(link_id = ?self.link_id, rtt_ms = rtt.as_millis() as u64, "link state -> Active (initiator)");
Ok(encrypted_rtt)
}
@@ -491,10 +493,14 @@ impl Link {
let request = LinkRequestData::unpack(request_data)?;
let link_id = compute_link_id(&destination_hash, request_data);
if request.signalling.mode != MODE_AES128_CBC && request.signalling.mode != MODE_AES256_CBC
{
if !ENABLED_MODES.contains(&request.signalling.mode) {
return Err(HandshakeError::UnsupportedMode(request.signalling.mode));
}
// Current host endpoints are deliberately base-only; transit upgrade
// support does not imply high-MTU Resource support at an endpoint.
let offered = LinkMtu::try_from_signal(Some(request.signalling.mtu))?;
let accepted_mtu = offered.min(LinkMtu::BASE);
let accepted_mdu = accepted_mtu.checked_mdu()?;
let responder_keys = EphemeralKeys::generate();
@@ -507,8 +513,7 @@ impl Link {
// The proof binds the link to the responder's long-term identity key, not
// its ephemeral one — that's what lets the initiator authenticate us.
let signalling =
SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32);
let signalling = SignallingData::try_new(request.signalling.mode, accepted_mtu.get())?;
let responder_x25519_pub = responder_keys.x25519_pub.to_bytes();
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
@@ -535,6 +540,8 @@ impl Link {
teardown_reason: None,
is_initiator: false,
mode: request.signalling.mode,
offered_mode: request.signalling.mode,
offered_mtu: accepted_mtu,
ephemeral_keys: Some(responder_keys),
peer_x25519_pub: Some(request.peer_x25519_pub),
peer_packet_proof_key: Some(request.peer_ed25519_pub),
@@ -547,8 +554,8 @@ impl Link {
activated_at: None,
stale_since: None,
keepalive: KeepaliveState::new(false),
mtu: request.signalling.mtu.min(rns_wire::constants::MTU as u32),
mdu: rns_wire::constants::LINK_MDU,
mtu: accepted_mtu.get(),
mdu: accepted_mdu,
resource_strategy: ResourceStrategy::default(),
pending_requests: Vec::new(),
incoming_resources: Vec::new(),
@@ -588,6 +595,7 @@ impl Link {
return Err(HandshakeError::InvalidSignature);
}
let mdu = LinkMtu::try_from_signal(Some(self.mtu))?.checked_mdu()?;
self.establishment_cost += encrypted_data.len();
let plaintext = self
@@ -607,7 +615,7 @@ impl Link {
self.state = LinkState::Active;
self.activated_at = Some(Instant::now());
self.keepalive.mark_activated();
self.update_mdu();
self.mdu = mdu;
tracing::debug!(link_id = ?self.link_id, "link state -> Active (responder)");
if let Some(rtt) = self.rtt {
@@ -694,11 +702,20 @@ impl Link {
}
/// Verify a received LINKIDENTIFY and record the remote identity key.
///
/// As in Python's `Link.receive`, only a responder accepts it, from the
/// handshake on: the initiator turns Active on the proof and may identify
/// before its RTT packet arrives.
pub fn handle_identification(
&mut self,
encrypted_data: &[u8],
) -> Result<[u8; 64], LinkCryptoError> {
if self.state != LinkState::Active {
if self.role() != LinkRole::Responder
|| !matches!(
self.state,
LinkState::Handshake | LinkState::Active | LinkState::Stale
)
{
return Err(LinkCryptoError::DecryptionFailed);
}
@@ -1588,21 +1605,6 @@ impl Link {
self.link_closed_callback = Some(Box::new(cb));
}
/// Recompute MDU from the current MTU.
///
/// MDU = `floor((mtu - header - token) / AES block) * AES block - 1`; the
/// trailing `-1` reserves room for PKCS7 padding worst case.
fn update_mdu(&mut self) {
let mtu = self.mtu as usize;
let overhead =
1 + rns_wire::constants::HEADER_MINSIZE + rns_wire::constants::TOKEN_OVERHEAD;
if mtu > overhead {
self.mdu = ((mtu - overhead) / rns_wire::constants::AES128_BLOCKSIZE)
* rns_wire::constants::AES128_BLOCKSIZE
- 1;
}
}
pub fn is_active(&self) -> bool {
self.state == LinkState::Active
}
@@ -1950,39 +1952,116 @@ mod tests {
}
#[test]
fn test_responder_accepts_python_inbound_modes() {
let dest_hash = [0xA2; 16];
let identity_key = Ed25519PrivateKey::generate();
let (mut request_link, request_data) = Link::new_initiator(dest_hash, 1);
let mut aes128_request = request_data.clone();
aes128_request[64] = MODE_AES128_CBC << 5;
let (responder, proof) =
Link::new_responder(&aes128_request, &identity_key, dest_hash, 1).unwrap();
assert_eq!(responder.mode, MODE_AES128_CBC);
fn responder_mtu_boundary_matrix_is_base_only_and_never_wraps() {
let identity = Ed25519PrivateKey::generate();
let (_, request) = Link::new_initiator([5; 16], 1);
for mtu in 1..500 {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(DEFAULT_MODE, mtu).pack());
assert!(
Link::new_responder(&candidate, &identity, [5; 16], 1).is_err(),
"mtu {mtu}"
);
}
for mtu in [0, 500, 501, MTU_BYTEMASK] {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(DEFAULT_MODE, mtu).pack());
let (responder, proof) =
Link::new_responder(&candidate, &identity, [5; 16], 1).unwrap();
assert_eq!(responder.mtu, 500);
assert_eq!(responder.mdu, rns_wire::constants::LINK_MDU);
assert_eq!(LinkProofData::unpack(&proof).unwrap().signalling.mtu, 500);
}
assert_eq!(
LinkProofData::unpack(&proof).unwrap().signalling.mode,
MODE_AES128_CBC
Link::new_responder(&request[..64], &identity, [5; 16], 1)
.unwrap()
.0
.mtu,
500
);
}
let identity_pub = identity_key.public_key();
#[test]
fn initiator_bad_mtu_proof_never_mutates_pending_owner() {
let identity = Ed25519PrivateKey::generate();
let public = identity.public_key();
let (mut initiator, request) = Link::new_initiator([6; 16], 1);
let (_responder, good) = Link::new_responder(&request, &identity, [6; 16], 1).unwrap();
let parsed = LinkProofData::unpack(&good).unwrap();
let cost = initiator.establishment_cost;
for mtu in (1..500).chain([501, MTU_BYTEMASK]) {
let invalid = LinkProofData::create(
&identity,
&parsed.responder_x25519_pub,
&public.to_bytes(),
&initiator.link_id,
SignallingData::new(DEFAULT_MODE, mtu),
)
.pack();
assert!(
initiator
.validate_proof(&invalid, &public, &public.to_bytes())
.is_err(),
"mtu {mtu}"
);
assert_eq!(initiator.state, LinkState::Pending);
assert!(!initiator.has_keys());
assert_eq!(initiator.establishment_cost, cost);
assert_eq!(initiator.mtu, 500);
assert_eq!(initiator.mdu, rns_wire::constants::LINK_MDU);
}
assert!(
request_link
.validate_proof(&proof, &identity_pub, &identity_pub.to_bytes())
.is_err(),
"initiator requested AES256 and must reject an AES128 proof"
initiator
.validate_proof(&good, &public, &public.to_bytes())
.is_ok()
);
assert_eq!(request_link.state, LinkState::Pending);
}
let mut unsupported_request = request_data;
unsupported_request[64] = MODE_AES256_GCM << 5;
assert!(
matches!(
Link::new_responder(&unsupported_request, &identity_key, dest_hash, 1),
Err(HandshakeError::UnsupportedMode(mode)) if mode == MODE_AES256_GCM
),
"Python raises for unsupported inbound mode 2"
);
#[test]
fn legacy_and_zero_proofs_authenticate_original_bytes_then_normalize() {
let identity = Ed25519PrivateKey::generate();
let public = identity.public_key();
for legacy in [false, true] {
let (mut initiator, request) = Link::new_initiator([7; 16], 1);
let (_, proof) = Link::new_responder(&request, &identity, [7; 16], 1).unwrap();
let parsed = LinkProofData::unpack(&proof).unwrap();
let mut signed = Vec::new();
signed.extend_from_slice(&initiator.link_id);
signed.extend_from_slice(&parsed.responder_x25519_pub);
signed.extend_from_slice(&public.to_bytes());
let signalling = SignallingData::new(DEFAULT_MODE, 0).pack();
if !legacy {
signed.extend_from_slice(&signalling);
}
let mut wire = identity.sign(&signed).to_vec();
wire.extend_from_slice(&parsed.responder_x25519_pub);
if !legacy {
wire.extend_from_slice(&signalling);
}
initiator
.validate_proof(&wire, &public, &public.to_bytes())
.unwrap();
assert_eq!(initiator.mtu, 500);
assert_eq!(initiator.mdu, rns_wire::constants::LINK_MDU);
}
}
#[test]
fn responder_rejects_disabled_modes() {
let identity = Ed25519PrivateKey::generate();
let (_, request) = Link::new_initiator([0xA2; 16], 1);
for mode in 0..=7 {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(mode, 500).pack());
let result = Link::new_responder(&candidate, &identity, [0xA2; 16], 1);
if ENABLED_MODES.contains(&mode) {
assert!(result.is_ok());
} else {
assert!(
matches!(result,Err(HandshakeError::UnsupportedMode(value)) if value==mode)
);
}
}
}
#[test]
@@ -2000,6 +2079,19 @@ mod tests {
assert_eq!(initiator.state, LinkState::Pending);
}
#[test]
fn establishment_extension_rejects_invalid_without_mutation() {
let (mut link, _) = Link::new_initiator([3; 16], 1);
let initial = link.establishment_timeout;
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, f64::MAX] {
assert!(link.try_extend_establishment_timeout(bad).is_err());
assert_eq!(link.establishment_timeout, initial);
}
link.try_extend_establishment_timeout(0.0).unwrap();
link.try_extend_establishment_timeout(2.0).unwrap();
assert_eq!(link.establishment_timeout, initial + Duration::from_secs(2));
}
#[test]
fn test_establishment_timeout() {
let dest_hash = [0xAA; 16];
@@ -2479,6 +2571,51 @@ mod tests {
assert_eq!(responder.remote_identity().unwrap(), &first_pub);
}
#[test]
fn test_identify_before_rtt_is_accepted() {
// Python's initiator turns Active on the proof, so its LINKIDENTIFY can
// reach a responder still waiting for the RTT packet.
let dest_hash = [0xAB; 16];
let identity_key = Ed25519PrivateKey::generate();
let identity_pub = identity_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
let (mut responder, proof_data) =
Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap();
let rtt_data = initiator
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
.unwrap();
assert_eq!(responder.state, LinkState::Handshake);
let client = Ed25519PrivateKey::generate();
let mut client_pub = [0u8; 64];
client_pub[..32].copy_from_slice(&[0x11; 32]);
client_pub[32..].copy_from_slice(&client.public_key().to_bytes());
let identify_data = initiator.identify(&client_pub, &client).unwrap();
assert_eq!(
responder.handle_identification(&identify_data).unwrap(),
client_pub
);
responder.receive_rtt_packet(&rtt_data).unwrap();
assert_eq!(responder.state, LinkState::Active);
assert_eq!(responder.remote_identity(), Some(&client_pub));
}
#[test]
fn test_initiator_rejects_identification() {
// Only the responder learns a remote identity from LINKIDENTIFY.
let (mut initiator, _responder, _) = make_active_link();
let before = initiator.remote_identity().copied();
let peer = Ed25519PrivateKey::generate();
let mut peer_pub = [0u8; 64];
peer_pub[32..].copy_from_slice(&peer.public_key().to_bytes());
let identify_data = initiator.identify(&peer_pub, &peer).unwrap();
assert!(initiator.handle_identification(&identify_data).is_err());
assert!(!initiator.identified);
assert_eq!(initiator.remote_identity().copied(), before);
}
#[test]
fn test_identify_non_initiator_fails() {
let (_initiator, responder, _identity) = make_active_link();
+6 -39
View File
@@ -1,46 +1,13 @@
use crate::constants::{MODE_BYTEMASK, MTU_BYTEMASK};
/// MTU and encryption-mode signalling packed into 3 bytes (big-endian).
///
/// Wire layout: `[23:21] mode (0..=7)`, `[20:0] mtu (0..=2_097_151)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignallingData {
pub mode: u8,
pub mtu: u32,
}
impl SignallingData {
pub fn new(mode: u8, mtu: u32) -> Self {
Self {
mode: mode & 0x07,
mtu: mtu & MTU_BYTEMASK,
}
}
/// Pack into 3 big-endian bytes.
pub fn pack(&self) -> [u8; 3] {
let value = (self.mtu & MTU_BYTEMASK) | ((((self.mode as u32) << 5) & MODE_BYTEMASK) << 16);
let bytes = value.to_be_bytes();
// Value fits in 24 bits; drop the high byte of the u32.
[bytes[1], bytes[2], bytes[3]]
}
/// Parse 3 big-endian bytes. Returns `None` if the input is shorter.
pub fn unpack(bytes: &[u8]) -> Option<Self> {
if bytes.len() < 3 {
return None;
}
let value = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
let mtu = value & MTU_BYTEMASK;
let mode = ((value >> 21) & 0x07) as u8;
Some(Self { mode, mtu })
}
}
//! Shared dependency-neutral Link signalling representation and checked budget.
pub use rns_wire::link_signalling::{
LinkMtu, LinkSignalling, LinkSignallingError, SignallingData, parse_proof_signalling,
parse_request_signalling,
};
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC};
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC, MTU_BYTEMASK};
#[test]
fn test_pack_unpack_roundtrip() {
+1
View File
@@ -17,6 +17,7 @@ tracing = { workspace = true }
bzip2 = { workspace = true }
rmpv = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
+69 -8
View File
@@ -39,6 +39,15 @@ pub const MAX_TRIES: usize = 5;
/// Floor for the `rtt * 2.5` term used as the base of the retransmit backoff.
pub const MIN_TIMEOUT_BASE: f64 = 0.025;
/// Retained RTT ceiling, matching the Link peer-RTT policy.
pub const RTT_MAX: f64 = 720.0;
fn initial_rtt(rtt: f64) -> f64 {
if rtt.is_finite() && rtt >= 0.0 {
rtt.min(RTT_MAX)
} else {
1.0
}
}
/// One outgoing or incoming channel frame.
///
@@ -129,6 +138,7 @@ impl ChannelWindow {
/// `RTT_SLOW` start pinned at a single slot with zero flexibility so we
/// don't spray bursts onto a marginal path.
pub fn new(rtt: f64) -> Self {
let rtt = initial_rtt(rtt);
if rtt > RTT_SLOW {
Self {
window: 1,
@@ -157,6 +167,11 @@ impl ChannelWindow {
/// unlock the fast tier. Any measurement that falls out of a tier resets
/// that tier's counter.
pub fn grow(&mut self, rtt: f64) {
self.clamp_window();
if !rtt.is_finite() || rtt < 0.0 {
return;
}
let rtt = rtt.min(RTT_MAX);
if self.window < self.window_max {
self.window += 1;
}
@@ -171,7 +186,7 @@ impl ChannelWindow {
if rtt > RTT_MEDIUM {
self.medium_rate_rounds = 0;
} else {
self.medium_rate_rounds += 1;
self.medium_rate_rounds = self.medium_rate_rounds.saturating_add(1);
if self.window_max < WINDOW_MAX_MEDIUM
&& self.medium_rate_rounds == FAST_RATE_THRESHOLD
{
@@ -180,7 +195,7 @@ impl ChannelWindow {
}
}
} else {
self.fast_rate_rounds += 1;
self.fast_rate_rounds = self.fast_rate_rounds.saturating_add(1);
if self.window_max < WINDOW_MAX_FAST && self.fast_rate_rounds == FAST_RATE_THRESHOLD {
self.window_max = WINDOW_MAX_FAST;
self.window_min = WINDOW_MIN_LIMIT_FAST;
@@ -191,7 +206,15 @@ impl ChannelWindow {
/// Pull the window in on retransmit. Also walks `window_max` downwards so
/// long-term packet loss actually demotes the link tier, stopping at the
/// configured `window_flexibility` gap above `window_min`.
fn clamp_window(&mut self) {
self.window = self.window.min(WINDOW_MAX);
self.window_min = self.window_min.min(WINDOW_MAX);
self.window_max = self.window_max.min(WINDOW_MAX);
self.window_flexibility = self.window_flexibility.min(WINDOW_MAX);
}
pub fn shrink(&mut self) {
self.clamp_window();
if self.window > self.window_min {
self.window -= 1;
@@ -236,6 +259,7 @@ pub struct Channel {
impl Channel {
pub fn new(rtt: f64) -> Self {
let rtt = initial_rtt(rtt);
Self {
next_tx_sequence: 0,
next_rx_sequence: 0,
@@ -328,7 +352,7 @@ impl Channel {
.iter()
.filter(|e| e.state != MessageState::Delivered)
.count();
outstanding < self.window.window
outstanding < self.window.window.min(WINDOW_MAX)
}
/// True when every outbound envelope has been acknowledged and removed.
@@ -401,7 +425,7 @@ impl Channel {
/// is marked inactive at that point).
pub fn timeout(&mut self, sequence: u16) -> Result<Option<Vec<u8>>, ChannelError> {
if let Some(env) = self.tx_ring.iter_mut().find(|e| e.sequence == sequence) {
env.tries += 1;
env.tries = env.tries.saturating_add(1);
if env.tries > MAX_TRIES {
self.active = false;
return Err(ChannelError::MaxRetriesExceeded);
@@ -532,20 +556,21 @@ impl Channel {
/// based on the latest Link RTT supplied by the owning runtime.
pub fn compute_timeout(&self, tries: usize) -> f64 {
let rtt = self.current_rtt;
let backoff = 1.5_f64.powi(tries.saturating_sub(1) as i32);
let backoff = 1.5_f64.powi((tries.clamp(1, MAX_TRIES) - 1) as i32);
let base = (rtt * 2.5).max(MIN_TIMEOUT_BASE);
let outstanding = self.outstanding_count() as f64 + 1.5;
let outstanding = self.outstanding_count().min(WINDOW_MAX) as f64 + 1.5;
backoff * base * outstanding
}
fn timeout_duration(&self, tries: usize) -> Duration {
Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
Duration::try_from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
.unwrap_or(Duration::from_secs(1))
}
/// Update the live Link RTT used by subsequent retransmit deadlines.
pub fn update_rtt(&mut self, rtt: f64) {
if rtt.is_finite() && rtt >= 0.0 {
self.current_rtt = rtt;
self.current_rtt = rtt.min(RTT_MAX);
}
}
@@ -1041,6 +1066,42 @@ mod tests {
assert_eq!(w.window_max, w.window_min + w.window_flexibility);
}
#[test]
fn channel_hostile_rtt_and_public_window_remain_bounded() {
for rtt in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] {
let mut channel = Channel::new(rtt);
assert_eq!(channel.current_rtt, 1.0);
let before = channel.window.window;
channel.window.grow(rtt);
assert_eq!(channel.window.window, before);
channel.update_rtt(rtt);
assert_eq!(channel.current_rtt, 1.0);
assert!(
channel
.timeout_duration(usize::MAX)
.as_secs_f64()
.is_finite()
);
}
let mut channel = Channel::new(f64::MAX);
assert_eq!(channel.current_rtt, RTT_MAX);
channel.window.window = usize::MAX;
channel.window.window_max = usize::MAX;
channel.window.window_min = usize::MAX;
channel.window.window_flexibility = usize::MAX;
channel.window.grow(0.1);
channel.window.shrink();
assert!(channel.window.window <= WINDOW_MAX);
for _ in 0..WINDOW_MAX {
channel.send(&TestMessage::new(b"bounded")).unwrap();
}
assert!(!channel.is_ready_to_send());
assert_eq!(
channel.compute_timeout(usize::MAX),
channel.compute_timeout(MAX_TRIES)
);
}
#[test]
fn test_window_slow_rtt_init() {
// RTT past RTT_SLOW must start pinned at a single slot with no flex.
+3
View File
@@ -10,3 +10,6 @@ pub mod resource;
pub mod resource_adv;
pub mod rnsh;
pub mod stream_data;
/// Exact Resource control-packet admission using the production encoders.
pub mod resource_control;
+95 -83
View File
@@ -323,6 +323,20 @@ impl OutboundResource {
encrypt_fn: Option<&ResourceEncryptor<'_>>,
collision_retries: usize,
) -> Result<Self, ResourceError> {
let sdu = link_sdu.unwrap_or(SDU);
if sdu == 0 {
return Err(ResourceError::InvalidAdvertisement);
}
// Part slicing is independent from the complete Link control budget.
crate::resource_control::preflight_outbound_with_sdu(
data.len(),
metadata.as_ref().map(Vec::len),
None,
false,
encrypt_fn.is_some(),
sdu,
rns_wire::constants::MTU,
)?;
let (packed_metadata, metadata_size, has_metadata) = if let Some(ref meta) = metadata {
if meta.len() > METADATA_MAX_SIZE {
return Err(ResourceError::MetadataTooLarge);
@@ -404,6 +418,15 @@ impl OutboundResource {
}
if has_collision && collision_retries < Self::MAX_COLLISION_RETRIES {
// Release attempt-local copies before retrying. Holding these until
// recursive return multiplies peak memory by the retry count.
drop(packed_metadata);
drop(full_data);
drop(processed_data);
drop(blob);
drop(parts);
drop(map_hashes);
drop(collision_guard);
return Self::with_options_inner(
data,
auto_compress,
@@ -778,6 +801,12 @@ pub enum ResourceError {
DecompressionFailed,
#[error("invalid metadata prefix: declared {declared} bytes, available {available} bytes")]
InvalidMetadata { declared: usize, available: usize },
#[error("resource control {context:?} requires {encoded_len} packet bytes, MTU is {mtu}")]
ControlFrameTooLarge {
context: rns_wire::context::PacketContext,
encoded_len: usize,
mtu: usize,
},
#[error("invalid advertisement")]
InvalidAdvertisement,
#[error("map hash collision persists after retries")]
@@ -963,6 +992,15 @@ impl LazyMultiSegmentOutbound {
return Err(ResourceError::TooLarge);
}
crate::resource_control::preflight_outbound(
data_size,
metadata.as_ref().map(Vec::len),
request_id.as_deref(),
is_response,
true,
rns_wire::constants::MTU,
)?;
// `original_hash` covers the uncompressed concatenated payload so the
// receiver can verify reassembly across all segments.
let random_hash: [u8; RANDOM_HASH_SIZE] =
@@ -1444,10 +1482,17 @@ impl OutboundTransfer {
}
if !self.advertised {
let advertisement = match self.create_advertisement() {
Ok(bytes) => bytes,
Err(error) => {
self.resource.state = ResourceState::Failed;
return TransferAction::Failed(error.to_string());
}
};
self.advertised = true;
self.started_at = Instant::now();
self.resource.state = ResourceState::Advertised;
return TransferAction::SendAdvertisement(self.create_advertisement());
return TransferAction::SendAdvertisement(advertisement);
}
self.check_timeout()
@@ -1504,7 +1549,13 @@ impl OutboundTransfer {
if self.retries < MAX_ADV_RETRIES {
self.retries += 1;
self.started_at = Instant::now();
TransferAction::SendAdvertisement(self.create_advertisement())
match self.create_advertisement() {
Ok(bytes) => TransferAction::SendAdvertisement(bytes),
Err(error) => {
self.resource.state = ResourceState::Failed;
TransferAction::Failed(error.to_string())
}
}
} else {
self.resource.state = ResourceState::Failed;
TransferAction::Failed("resource advertisement timed out".to_string())
@@ -1801,18 +1852,11 @@ impl OutboundTransfer {
}
// HMU wire layout: resource_hash(32) || msgpack([segment, hashmap]).
let hmu_payload = {
use rmpv::Value;
let arr = Value::Array(vec![
Value::Integer((segment as u64).into()),
Value::Binary(hashmap_bytes),
]);
let mut buf = Vec::new();
buf.extend_from_slice(&self.resource.resource_hash);
rmpv::encode::write_value(&mut buf, &arr)
.expect("msgpack encode should succeed");
buf
};
let hmu_payload = crate::resource_control::encode_hashmap_update(
&self.resource.resource_hash,
segment,
&hashmap_bytes,
);
actions.push(TransferAction::SendHmu(hmu_payload));
}
@@ -1883,9 +1927,17 @@ impl OutboundTransfer {
}
/// Build the msgpack-encoded advertisement that precedes the transfer.
fn create_advertisement(&self) -> Vec<u8> {
use rmpv::Value;
fn create_advertisement(&self) -> Result<Vec<u8>, ResourceError> {
let mtu = rns_wire::constants::MTU;
if let Some(id) = self.resource.request_id.as_deref() {
crate::resource_control::check_control_frame(
rns_wire::context::PacketContext::ResourceAdv,
id.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
}
let mut adv = crate::resource_adv::ResourceAdvertisement::new(
self.resource.total_size,
self.resource.advertisement_data_size,
@@ -1911,59 +1963,8 @@ impl OutboundTransfer {
}
adv.request_id = self.resource.request_id.clone();
let q_val = match &adv.request_id {
Some(id) => Value::Binary(id.clone()),
None => Value::Nil,
};
let pairs: Vec<(Value, Value)> = vec![
(
Value::String("t".into()),
Value::Integer(adv.transfer_size.into()),
),
(
Value::String("d".into()),
Value::Integer(adv.data_size.into()),
),
(
Value::String("n".into()),
Value::Integer(adv.num_parts.into()),
),
(
Value::String("h".into()),
Value::Binary(adv.resource_hash.to_vec()),
),
(
Value::String("r".into()),
Value::Binary(adv.random_hash.to_vec()),
),
(
Value::String("o".into()),
Value::Binary(adv.original_hash.to_vec()),
),
(
Value::String("i".into()),
Value::Integer(adv.segment_index.into()),
),
(
Value::String("l".into()),
Value::Integer(adv.total_segments.into()),
),
(Value::String("q".into()), q_val),
(
Value::String("f".into()),
Value::Integer(adv.flags.to_byte().into()),
),
(
Value::String("m".into()),
Value::Binary(adv.hashmap.clone()),
),
];
let value = Value::Map(pairs);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode failed");
buf
crate::resource_control::check_advertisement(&adv, mtu)?;
Ok(adv.pack())
}
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
@@ -2495,6 +2496,17 @@ impl InboundTransfer {
#[cfg(test)]
mod tests {
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
use super::*;
#[test]
@@ -3007,7 +3019,7 @@ mod tests {
TransferAction::SendAdvertisement(_)
));
transfer.started_at = Instant::now() - Duration::from_secs(60);
transfer.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
transfer.check_timeout(),
TransferAction::SendAdvertisement(_)
@@ -3026,7 +3038,7 @@ mod tests {
.unwrap();
transfer.tick();
transfer.retries = MAX_ADV_RETRIES;
transfer.started_at = Instant::now() - Duration::from_secs(60);
transfer.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
transfer.check_timeout(),
@@ -3410,7 +3422,7 @@ mod tests {
let (data, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
// Lose the first advertisement, then the first receiver request. The
// sender remains Advertised through arbitrary local polling.
sender.started_at = Instant::now() - Duration::from_secs(60);
sender.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
sender.tick(),
TransferAction::SendAdvertisement(_)
@@ -3423,7 +3435,7 @@ mod tests {
assert_eq!(sender.tick(), TransferAction::None);
}
assert_eq!(sender.resource.state, ResourceState::Advertised);
receiver.last_activity = Instant::now() - Duration::from_secs(60);
receiver.last_activity = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
receiver.check_timeout(),
TransferAction::SendRequest(_)
@@ -3448,7 +3460,7 @@ mod tests {
let mut lost_hmu = false;
for _ in 0..1000 {
if matches!(pending, TransferAction::None) {
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
pending = receiver.check_timeout();
}
let TransferAction::SendRequest(request) = pending else {
@@ -3506,7 +3518,7 @@ mod tests {
sender.handle_request(&request);
}
assert_eq!(sender.last_progress, progress_at);
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
sender.last_progress = ago_or_skip!(sender.progress_timeout() + Duration::from_secs(1));
assert_eq!(
sender.tick(),
TransferAction::Failed("resource part requests timed out".to_string())
@@ -3514,13 +3526,13 @@ mod tests {
assert!(sender.handle_request(&request).is_empty());
for _ in 0..MAX_RETRIES {
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
assert!(matches!(
receiver.check_timeout(),
TransferAction::SendRequest(_)
));
}
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
assert!(matches!(
receiver.check_timeout(),
TransferAction::Failed(_)
@@ -3540,7 +3552,7 @@ mod tests {
assert_eq!(sender.resource.state, ResourceState::AwaitingProof);
// Receiver has delivered, but its proof is lost. Sender must release
// ownership as failed, never infer success from all parts being sent.
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
sender.last_progress = ago_or_skip!(sender.progress_timeout() + Duration::from_secs(1));
assert_eq!(
sender.tick(),
TransferAction::Failed("resource proof timed out".to_string())
@@ -3566,14 +3578,14 @@ mod tests {
"do not replace the slow RTT with local scheduling time"
);
assert!(sender.progress_timeout() > Duration::from_secs(180));
sender.last_progress = Instant::now() - Duration::from_secs(180);
sender.last_progress = ago_or_skip!(Duration::from_secs(180));
assert_eq!(sender.check_timeout(), TransferAction::None);
// No absolute transfer deadline: requesting new parts restarts the
// bounded no-progress owner even after a long healthy transfer.
let mut next = vec![HASHMAP_IS_NOT_EXHAUSTED];
next.extend_from_slice(&sender.resource.resource_hash);
next.extend_from_slice(&sender.resource.map_hashes[4]);
sender.started_at = Instant::now() - Duration::from_secs(3600);
sender.started_at = ago_or_skip!(Duration::from_secs(3600));
sender.handle_request(&next);
assert!(sender.last_progress.elapsed() < Duration::from_secs(1));
assert_eq!(sender.check_timeout(), TransferAction::None);
@@ -4753,7 +4765,7 @@ mod tests {
inbound.outstanding_parts = 2;
// Set last_activity far enough in the past to trigger timeout
inbound.last_activity = Instant::now() - Duration::from_secs(60);
inbound.last_activity = ago_or_skip!(Duration::from_secs(60));
let initial_retries = inbound.retries_left;
let action = inbound.check_timeout();
@@ -4789,7 +4801,7 @@ mod tests {
inbound.outstanding_parts = 2;
inbound.retries_left = 0;
inbound.last_activity = Instant::now() - Duration::from_secs(60);
inbound.last_activity = ago_or_skip!(Duration::from_secs(60));
let action = inbound.check_timeout();
assert!(matches!(action, TransferAction::Failed(_)));
+66 -53
View File
@@ -122,6 +122,14 @@ impl ResourceAdvertisement {
pub fn unpack(data: &[u8]) -> Result<Self, String> {
use rmpv::Value;
crate::resource_control::check_control_frame(
rns_wire::context::PacketContext::ResourceAdv,
data.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
rns_wire::constants::MTU,
)
.map_err(|error| error.to_string())?;
let value =
rmpv::decode::read_value(&mut &data[..]).map_err(|e| format!("msgpack decode: {e}"))?;
@@ -205,61 +213,25 @@ impl ResourceAdvertisement {
/// Encode as the msgpack map described on the struct docs.
pub fn pack(&self) -> Vec<u8> {
use rmpv::Value;
let mut output = Vec::new();
self.pack_into(&mut output).expect("Vec messagepack write");
output
}
let q_val = match &self.request_id {
Some(id) => Value::Binary(id.clone()),
None => Value::Nil,
};
/// Write the same wire encoding to either a real buffer or bounded counter.
/// Borrowing fields avoids allocating a duplicate hashmap/request-ID tree.
pub fn pack_into<W: std::io::Write>(&self, writer: W) -> Result<(), rmp_serde::encode::Error> {
serde::Serialize::serialize(
&AdvertisementRef(self),
&mut rmp_serde::Serializer::new(writer),
)
}
let pairs: Vec<(Value, Value)> = vec![
(
Value::String("t".into()),
Value::Integer(self.transfer_size.into()),
),
(
Value::String("d".into()),
Value::Integer(self.data_size.into()),
),
(
Value::String("n".into()),
Value::Integer(self.num_parts.into()),
),
(
Value::String("h".into()),
Value::Binary(self.resource_hash.to_vec()),
),
(
Value::String("r".into()),
Value::Binary(self.random_hash.to_vec()),
),
(
Value::String("o".into()),
Value::Binary(self.original_hash.to_vec()),
),
(
Value::String("i".into()),
Value::Integer(self.segment_index.into()),
),
(
Value::String("l".into()),
Value::Integer(self.total_segments.into()),
),
(Value::String("q".into()), q_val),
(
Value::String("f".into()),
Value::Integer(self.flags.to_byte().into()),
),
(
Value::String("m".into()),
Value::Binary(self.hashmap.clone()),
),
];
let value = Value::Map(pairs);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode should succeed");
buf
pub fn encoded_len(&self) -> Result<usize, crate::resource::ResourceError> {
let mut counter = EncodedLength(0);
self.pack_into(&mut counter)
.map_err(|_| crate::resource::ResourceError::TooLarge)?;
Ok(counter.0)
}
/// Split the packed `hashmap` field into fixed-length map-hash entries.
@@ -277,6 +249,47 @@ impl ResourceAdvertisement {
}
}
struct AdvertisementRef<'a>(&'a ResourceAdvertisement);
struct BinaryRef<'a>(&'a [u8]);
impl serde::Serialize for BinaryRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bytes(self.0)
}
}
impl serde::Serialize for AdvertisementRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let a = self.0;
let mut map = serializer.serialize_map(Some(11))?;
map.serialize_entry("t", &a.transfer_size)?;
map.serialize_entry("d", &a.data_size)?;
map.serialize_entry("n", &a.num_parts)?;
map.serialize_entry("h", &BinaryRef(&a.resource_hash))?;
map.serialize_entry("r", &BinaryRef(&a.random_hash))?;
map.serialize_entry("o", &BinaryRef(&a.original_hash))?;
map.serialize_entry("i", &a.segment_index)?;
map.serialize_entry("l", &a.total_segments)?;
map.serialize_entry("q", &a.request_id.as_deref().map(BinaryRef))?;
map.serialize_entry("f", &a.flags.to_byte())?;
map.serialize_entry("m", &BinaryRef(&a.hashmap))?;
map.end()
}
}
/// Counting sink uses the actual serializer, with no transfer-sized scratch.
struct EncodedLength(usize);
impl std::io::Write for EncodedLength {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 = self
.0
.checked_add(bytes.len())
.ok_or_else(|| std::io::Error::other("length overflow"))?;
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
+351
View File
@@ -0,0 +1,351 @@
//! Checked admission for fixed-stride Resource control frames.
//! A decoder profile is not a promise that the transport can carry a control.
use crate::resource::{
MAPHASH_LEN, MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, RANDOM_HASH_SIZE,
ResourceError, ResourceFlags, SDU, WINDOW_MAX,
};
use crate::resource_adv::ResourceAdvertisement;
use rns_wire::context::PacketContext;
/// Pinned Python Resource hashmap stride. Never derive it from a small custom MTU.
pub const HASHMAP_STRIDE: usize = 74;
/// CBC token framing used by Link encryption, with checked arithmetic.
pub fn encrypted_len(plaintext_len: usize) -> Result<usize, ResourceError> {
plaintext_len
.checked_div(16)
.and_then(|n| n.checked_add(1))
.and_then(|n| n.checked_mul(16))
.and_then(|n| n.checked_add(48))
.ok_or(ResourceError::TooLarge)
}
/// Check the actual Reticulum packet length before encryption or state admission.
pub fn check_control_frame(
context: PacketContext,
payload_len: usize,
encrypted: bool,
header_len: usize,
mtu: usize,
) -> Result<(), ResourceError> {
let body = if encrypted {
encrypted_len(payload_len)?
} else {
payload_len
};
let encoded_len = header_len
.checked_add(body)
.ok_or(ResourceError::TooLarge)?;
if encoded_len > mtu {
return Err(ResourceError::ControlFrameTooLarge {
context,
encoded_len,
mtu,
});
}
Ok(())
}
/// Check one already-described advertisement without allocating its encoded body.
pub fn check_advertisement(
advertisement: &ResourceAdvertisement,
mtu: usize,
) -> Result<(), ResourceError> {
check_control_frame(
PacketContext::ResourceAdv,
advertisement.encoded_len()?,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)
}
/// Preflight the largest control shapes across all segments, before copying the
/// source, allocating parts/hashmaps, reserving a transfer, or invoking encryption.
/// Compression only shrinks the admitted upper bound. The 74-hash stride stays
/// fixed. Request identifiers are borrowed here, including their real length.
pub fn preflight_outbound(
data_len: usize,
metadata_len: Option<usize>,
request_id: Option<&[u8]>,
is_response: bool,
encrypted: bool,
mtu: usize,
) -> Result<(), ResourceError> {
preflight_outbound_with_sdu(
data_len,
metadata_len,
request_id,
is_response,
encrypted,
SDU,
mtu,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn preflight_outbound_with_sdu(
data_len: usize,
metadata_len: Option<usize>,
request_id: Option<&[u8]>,
is_response: bool,
encrypted: bool,
part_sdu: usize,
mtu: usize,
) -> Result<(), ResourceError> {
if part_sdu == 0 {
return Err(ResourceError::InvalidAdvertisement);
}
if data_len > MAX_RESOURCE_SIZE {
return Err(ResourceError::TooLarge);
}
let metadata_wire = metadata_len
.map(|n| n.checked_add(3).ok_or(ResourceError::MetadataTooLarge))
.transpose()?
.unwrap_or(0);
if metadata_wire > MAX_EFFICIENT_SIZE {
return Err(ResourceError::MetadataTooLarge);
}
let total_data = data_len
.checked_add(metadata_wire)
.ok_or(ResourceError::TooLarge)?;
let first = data_len.min(MAX_EFFICIENT_SIZE - metadata_wire);
let total_segments = 1usize
.checked_add(data_len.saturating_sub(first).div_ceil(MAX_EFFICIENT_SIZE))
.ok_or(ResourceError::TooLarge)?;
if total_segments > MAX_SEGMENTS {
return Err(ResourceError::TooLarge);
}
// Request ID storage is bounded by the packet before copying into the small
// temporary advertisement. No attacker-sized allocation precedes admission.
if let Some(id) = request_id {
check_control_frame(
PacketContext::ResourceAdv,
id.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
}
let segment_len = total_data.min(MAX_EFFICIENT_SIZE);
let blob = segment_len
.checked_add(RANDOM_HASH_SIZE)
.ok_or(ResourceError::TooLarge)?;
let transfer_size = if encrypted {
encrypted_len(blob)?
} else {
blob
};
let parts = transfer_size.div_ceil(part_sdu);
let hashes = [[0u8; MAPHASH_LEN]; HASHMAP_STRIDE];
let mut advertisement = ResourceAdvertisement::new(
transfer_size,
total_data,
parts,
[0; 32],
vec![0; RANDOM_HASH_SIZE],
ResourceFlags {
encrypted,
compressed: false,
split: total_segments > 1,
is_request: request_id.is_some() && !is_response,
is_response,
has_metadata: metadata_len.is_some(),
},
&hashes[..parts.min(HASHMAP_STRIDE)],
rns_wire::constants::LINK_MDU,
);
advertisement.segment_index = total_segments;
advertisement.total_segments = total_segments;
advertisement.request_id = request_id.map(<[u8]>::to_vec);
check_advertisement(&advertisement, mtu)?;
// HMU uses the production MessagePack encoder and largest possible segment
// index for this admitted source. At most 296 hashmap octets are materialized.
let max_map_segment = parts.saturating_sub(1) / HASHMAP_STRIDE;
let hmu = encode_hashmap_update(
&[0; 32],
max_map_segment,
&[0; HASHMAP_STRIDE * MAPHASH_LEN],
);
check_control_frame(
PacketContext::ResourceHmu,
hmu.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
// Exhaustion marker + last map hash + resource hash + maximum request window.
check_control_frame(
PacketContext::ResourceReq,
1 + MAPHASH_LEN + 32 + WINDOW_MAX * MAPHASH_LEN,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
check_control_frame(
PacketContext::ResourcePrf,
64,
false,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
check_control_frame(
PacketContext::ResourceIcl,
32,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)
}
/// Shared HMU encoder used by size admission and real transmission.
pub fn encode_hashmap_update(resource_hash: &[u8; 32], segment: usize, hashes: &[u8]) -> Vec<u8> {
use rmpv::Value;
let value = Value::Array(vec![
Value::Integer((segment as u64).into()),
Value::Binary(hashes.to_vec()),
]);
let mut output = resource_hash.to_vec();
rmpv::encode::write_value(&mut output, &value).expect("Vec MessagePack write");
output
}
#[cfg(test)]
mod tests {
use super::*;
fn advertisement(request_id: Option<Vec<u8>>) -> ResourceAdvertisement {
let mut adv = ResourceAdvertisement::new(
1_048_640,
1_048_575,
2260,
[1; 32],
vec![2; 4],
ResourceFlags {
encrypted: true,
compressed: false,
split: false,
is_request: request_id.is_some(),
is_response: false,
has_metadata: false,
},
&[[3; 4]; 74],
rns_wire::constants::LINK_MDU,
);
adv.request_id = request_id;
adv
}
#[test]
fn control_preflight_shared_advertisement_encoder_matches_retained_wire() {
use rmpv::Value;
for id in [None, Some(vec![7; 16])] {
let a = advertisement(id);
let pairs = vec![
("t", Value::from(a.transfer_size as u64)),
("d", Value::from(a.data_size as u64)),
("n", Value::from(a.num_parts as u64)),
("h", Value::Binary(a.resource_hash.to_vec())),
("r", Value::Binary(a.random_hash.clone())),
("o", Value::Binary(a.original_hash.to_vec())),
("i", Value::from(a.segment_index as u64)),
("l", Value::from(a.total_segments as u64)),
(
"q",
a.request_id
.clone()
.map(Value::Binary)
.unwrap_or(Value::Nil),
),
("f", Value::from(a.flags.to_byte())),
("m", Value::Binary(a.hashmap.clone())),
];
let old = Value::Map(
pairs
.into_iter()
.map(|(k, v)| (Value::from(k), v))
.collect(),
);
let mut expected = Vec::new();
rmpv::encode::write_value(&mut expected, &old).unwrap();
assert_eq!(a.pack(), expected);
assert_eq!(a.encoded_len().unwrap(), expected.len());
assert!(check_advertisement(&a, 500).is_ok());
}
let a = advertisement(Some(vec![7; 16]));
let exact = 19 + encrypted_len(a.encoded_len().unwrap()).unwrap();
assert_eq!(exact, 499);
assert!(check_advertisement(&a, 499).is_ok());
assert!(matches!(
check_advertisement(&a, 498),
Err(ResourceError::ControlFrameTooLarge {
encoded_len: 499,
..
})
));
}
#[test]
fn control_preflight_extreme_metadata_shape_uses_no_large_source() {
let mut a = advertisement(Some(vec![7; 16]));
a.data_size = 1 << 30;
a.segment_index = 1024;
a.total_segments = 1025;
a.flags.split = true;
assert!(matches!(
check_advertisement(&a, 500),
Err(ResourceError::ControlFrameTooLarge { .. })
));
assert!(matches!(
preflight_outbound(0, None, Some(&[7; 500]), false, true, 500),
Err(ResourceError::ControlFrameTooLarge { .. })
));
assert!(matches!(
encrypted_len(usize::MAX),
Err(ResourceError::TooLarge)
));
}
#[test]
fn control_preflight_preserves_stride_and_refuses_before_encrypt_or_parts() {
assert_eq!(
HASHMAP_STRIDE,
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU)
);
preflight_outbound(75 * SDU, None, None, false, true, 500).unwrap();
preflight_outbound(MAX_EFFICIENT_SIZE, None, Some(&[0; 16]), false, true, 500).unwrap();
let called = std::cell::Cell::new(false);
let encrypt = |_: &[u8]| {
called.set(true);
Vec::new()
};
let result = crate::resource::OutboundResource::with_options(
vec![0; 32],
false,
None,
Some(0),
Some(&encrypt),
);
assert!(matches!(result, Err(ResourceError::InvalidAdvertisement)));
assert!(!called.get());
}
#[test]
fn control_preflight_late_metadata_mutation_cannot_enter_advertised() {
let mut transfer = crate::resource::OutboundTransfer::new(
vec![0; 16],
false,
std::time::Duration::from_millis(10),
)
.unwrap();
transfer.resource.request_id = Some(vec![0; 500]);
assert!(matches!(
transfer.tick(),
crate::resource::TransferAction::Failed(_)
));
assert_eq!(
transfer.resource.state,
crate::resource::ResourceState::Failed
);
assert!(matches!(
transfer.tick(),
crate::resource::TransferAction::Failed(_)
));
assert!(ResourceAdvertisement::unpack(&vec![0; 500]).is_err());
}
}
+4 -3
View File
@@ -7,6 +7,7 @@ use std::path::Path;
use rns_crypto::hkdf::derive_key_64;
use rns_crypto::token;
use rns_identity::identity::Identity;
use zeroize::Zeroizing;
use crate::apdu::{SLOT_AUTHENTICATION as SLOT_9A, SLOT_KEY_MANAGEMENT as SLOT_9D};
use crate::error::RatkeyError;
@@ -220,13 +221,13 @@ impl HardwareIdentity {
}
}
let shared_secret = self.ecdh(&ephemeral_pub_bytes)?;
let shared_secret = Zeroizing::new(self.ecdh(&ephemeral_pub_bytes)?);
// HKDF-SHA256, salt = identity hash. Matches Identity::decrypt.
let derived = derive_key_64(&shared_secret, &self.identity.hash)
let derived = derive_key_64(&shared_secret[..], &self.identity.hash)
.map_err(|_| RatkeyError::EcdhFailed("HKDF derivation failed".to_string()))?;
token::decrypt(encrypted_token, &derived)
token::decrypt(encrypted_token, &derived[..])
.map_err(|_| RatkeyError::EcdhFailed("decryption failed".to_string()))
}
+23 -18
View File
@@ -7,6 +7,7 @@ use crate::detect::DeviceType;
use crate::error::RatkeyError;
use crate::pin::PinCache;
use crate::transport::PivTransport;
use zeroize::Zeroizing;
/// Device identity captured once at connect time; no per-operation cost.
pub struct DeviceMeta {
@@ -180,28 +181,32 @@ impl<T: PivTransport> PivSession<T> {
/// when the card answers 0x6982 (security status not satisfied) — e.g.
/// pin_policy=ALWAYS slots, or the applet was re-selected since the last
/// VERIFY. The cache expires on its own timeout and is cleared by `lock`.
fn transmit_pin_gated(&mut self, cmd: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(cmd)?;
match apdu::check_response(&resp) {
/// Responses can carry an ECDH shared secret, so they are wiped on drop.
fn transmit_pin_gated(&mut self, cmd: &[u8]) -> Result<Zeroizing<Vec<u8>>, RatkeyError> {
let mut resp = Zeroizing::new(self.transport.transmit(cmd)?);
let mut data_len = apdu::check_response(&resp).map(<[u8]>::len);
if matches!(
data_len,
Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82,
}) => {
let pin = match self.pin_cache.get() {
Some(pin) => zeroize::Zeroizing::new(pin.to_string()),
None => {
return Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82,
});
}
};
self.verify_pin(&pin)?;
let resp = self.transport.transmit(cmd)?;
Ok(apdu::check_response(&resp)?.to_vec())
}
other => Ok(other?.to_vec()),
})
) {
let pin = match self.pin_cache.get() {
Some(pin) => Zeroizing::new(pin.to_string()),
None => {
return Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82,
});
}
};
self.verify_pin(&pin)?;
resp = Zeroizing::new(self.transport.transmit(cmd)?);
data_len = apdu::check_response(&resp).map(<[u8]>::len);
}
resp.truncate(data_len?);
Ok(resp)
}
pub fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
+2 -1
View File
@@ -92,7 +92,8 @@ mod pcsc_transport {
}
fn transmit_once(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
// The receive buffer can hold an ECDH shared secret.
let mut response_buf = zeroize::Zeroizing::new(vec![0u8; MAX_RESPONSE]);
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
+100
View File
@@ -0,0 +1,100 @@
//! A security key's ECDH shared secret, and what is derived from it, must not
//! survive in freed heap memory.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_crypto::ed25519::Ed25519PrivateKey;
use rns_crypto::hkdf::derive_key_64;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_ratkey::apdu::SLOT_KEY_MANAGEMENT;
use rns_ratkey::detect::DeviceType;
use rns_ratkey::{DeviceMeta, HardwareIdentity, PivSession, PivTransport, RatkeyError};
use zeroize::Zeroizing;
/// Answers GENERAL AUTHENTICATE with the X25519 shared secret of its key and
/// the peer key in the command, as a token does.
struct EcdhToken {
key: X25519PrivateKey,
}
impl PivTransport for EcdhToken {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response = Vec::with_capacity(38);
if apdu[1] == 0x87 {
let peer: [u8; 32] = apdu[apdu.len() - 32..].try_into().unwrap();
let shared = Zeroizing::new(self.key.exchange(&X25519PublicKey::from_bytes(&peer)));
response.extend_from_slice(&[0x7c, 0x22, 0x82, 0x20]);
response.extend_from_slice(&*shared);
}
response.extend_from_slice(&[0x90, 0x00]);
Ok(response)
}
fn is_connected(&self) -> bool {
true
}
}
fn session(key: X25519PrivateKey) -> PivSession<EcdhToken> {
PivSession::new(
EcdhToken { key },
DeviceMeta {
device_type: DeviceType::YubiKey5,
serial: None,
firmware: None,
},
)
}
#[test]
fn piv_ecdh_frees_no_shared_secret() {
let _serial = serial();
let key = X25519PrivateKey::from_bytes(&pseudo_random(40));
let peer = X25519PrivateKey::from_bytes(&pseudo_random(41))
.public_key()
.to_bytes();
let expected = Zeroizing::new(key.exchange(&X25519PublicKey::from_bytes(&peer)));
let mut session = session(key);
let ((), freed) = freed_by(|| {
let shared = Zeroizing::new(session.ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer).unwrap());
assert_eq!(*shared, *expected);
});
assert_no_residue(&freed, &[("shared secret", &expected[..])]);
}
#[test]
fn hardware_decrypt_frees_no_shared_secret_or_plaintext() {
let _serial = serial();
let x25519: [u8; 32] = pseudo_random(42);
let key = X25519PrivateKey::from_bytes(&x25519);
let x25519_public = key.public_key().to_bytes();
let ed25519_public = Ed25519PrivateKey::from_bytes(&pseudo_random(43))
.public_key()
.to_bytes();
let mut hardware =
HardwareIdentity::from_keys(ed25519_public, x25519_public, Box::new(session(key))).unwrap();
let plaintext: [u8; 100] = pseudo_random(44);
let ciphertext = hardware.identity.encrypt(&plaintext, None).unwrap();
let shared = Zeroizing::new(X25519PrivateKey::from_bytes(&x25519).exchange(
&X25519PublicKey::from_bytes(ciphertext[..32].try_into().unwrap()),
));
let derived = derive_key_64(&*shared, &hardware.identity.hash).unwrap();
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(hardware.decrypt(&ciphertext, None, false).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[
("shared secret", &shared[..]),
("derived key", &derived[..]),
("plaintext", &plaintext),
],
);
}
+21
View File
@@ -3,6 +3,9 @@
//! multiline values, `#` comments outside quotes, and boolean variants
//! `True`/`Yes`/`On`/`1`.
pub mod ifac;
pub mod ifac_lock;
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;
@@ -71,6 +74,24 @@ impl ConfigSection {
self.get_bool(key).unwrap_or(default)
}
/// Upstream's interface rule (Reticulum.py): enabled only when
/// `interface_enabled` or `enabled` is present and true.
pub fn interface_enabled(&self) -> bool {
self.get_bool("interface_enabled") == Some(true) || self.get_bool("enabled") == Some(true)
}
/// Whether the section sets `interface_enabled` or `enabled` at all.
pub fn has_enable_key(&self) -> bool {
self.has("interface_enabled") || self.has("enabled")
}
/// An enable key whose value is not a boolean, which upstream rejects.
pub fn invalid_enable_key(&self) -> Option<&'static str> {
["interface_enabled", "enabled"]
.into_iter()
.find(|key| self.has(key) && self.get_bool(key).is_none())
}
pub fn get_int(&self, key: &str) -> Option<i64> {
let v = self.get(key)?;
v.parse().ok()
+501
View File
@@ -0,0 +1,501 @@
//! Explicit IFAC units and surgical, owner-selected legacy migration.
//!
//! Runtime sizes remain bytes. File `ifac_size` is bits; ambiguous old values
//! require an explicit migration choice, never an inferred producer/version.
use super::{
Config, ConfigError, ConfigSection, ConfigValue, parse_config_value, strip_comment,
unquote_token,
};
use rns_crypto::sha::sha256;
use std::collections::HashSet;
use std::ops::Range;
pub const SIZE_KEYS: &[&str] = &["ifac_size", "ifac_size_unit", "ifac_size_bytes"];
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum IfacConfigError {
#[error("ifac_size has ambiguous units; choose the existing byte size or Python bit size")]
IfacUnitsRequired,
#[error("{field}: {reason}")]
Invalid {
field: &'static str,
reason: &'static str,
},
}
fn invalid(field: &'static str, reason: &'static str) -> IfacConfigError {
IfacConfigError::Invalid { field, reason }
}
fn scalar<'a>(
section: &'a ConfigSection,
key: &'static str,
) -> Result<Option<&'a str>, IfacConfigError> {
match section.values.get(key) {
None => Ok(None),
Some(ConfigValue::Scalar(v)) => Ok(Some(v.as_str())),
Some(_) => Err(invalid(key, "must be one integer scalar")),
}
}
fn integer(section: &ConfigSection, key: &'static str) -> Result<Option<usize>, IfacConfigError> {
scalar(section, key)?
.map(|v| {
if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) {
return Err(invalid(key, "must be an unsigned decimal integer"));
}
v.parse::<usize>()
.map_err(|_| invalid(key, "integer overflow"))
})
.transpose()
}
/// Decode file units without changing credential activation or class defaults.
/// A legacy byte escape must be diagnosed by the caller when present.
pub fn parse_ifac_size(section: &ConfigSection) -> Result<Option<usize>, IfacConfigError> {
let has_bits = section.has("ifac_size");
let has_unit = section.has("ifac_size_unit");
if section.has("ifac_size_bytes") {
if has_bits || has_unit {
return Err(invalid(
"ifac_size_bytes",
"cannot coexist with ifac_size or ifac_size_unit",
));
}
let bytes = integer(section, "ifac_size_bytes")?.expect("present scalar");
return if (1..=64).contains(&bytes) {
Ok(Some(bytes))
} else {
Err(invalid("ifac_size_bytes", "must be in 1..64 bytes"))
};
}
let unit = scalar(section, "ifac_size_unit")?;
if unit.is_some_and(|u| u != "bits") {
return Err(invalid("ifac_size_unit", "must be exactly bits"));
}
if !has_bits {
return if has_unit {
Err(invalid("ifac_size_unit", "requires ifac_size"))
} else {
Ok(None)
};
}
let bits = integer(section, "ifac_size")?.expect("present scalar");
if unit.is_none() && (1..=64).contains(&bits) {
return Err(IfacConfigError::IfacUnitsRequired);
}
if !(8..=512).contains(&bits) || bits % 8 != 0 {
return Err(invalid(
"ifac_size",
"must be 8..512 bits and divisible by 8",
));
}
Ok(Some(bits / 8))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IfacSourceUnits {
Bytes,
Bits,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfacUnitChange {
pub interface: String,
pub previous_value: usize,
pub effective_bytes: usize,
}
/// Proposed content is private to avoid leaking credentials through Debug output.
pub struct IfacMigrationPlan {
source_hash: [u8; 32],
proposed: String,
changes: Vec<IfacUnitChange>,
}
impl std::fmt::Debug for IfacMigrationPlan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IfacMigrationPlan")
.field("changes", &self.changes)
.finish_non_exhaustive()
}
}
impl IfacMigrationPlan {
pub fn source_hash(&self) -> [u8; 32] {
self.source_hash
}
pub fn proposed_config(&self) -> &str {
&self.proposed
}
pub fn changes(&self) -> &[IfacUnitChange] {
&self.changes
}
pub fn is_unchanged(&self) -> bool {
self.changes.is_empty()
}
pub fn source_matches(&self, content: &str) -> bool {
sha256(content.as_bytes()) == self.source_hash
}
}
#[derive(Debug, thiserror::Error)]
pub enum IfacMigrationError {
#[error("configuration syntax is invalid")]
Syntax(#[source] ConfigError),
#[error("select at least one exact interface name")]
EmptySelection,
#[error("selected interface not found: {0}")]
NotFound(String),
#[error("interface {interface}: {error}")]
Invalid {
interface: String,
error: IfacConfigError,
},
#[error("configuration source span does not match its parsed declaration")]
SourceMismatch,
}
/// Authoritative-parser source ranges. Multiline values are consumed by the same
/// parser, so apparent headers/keywords inside them can never become edit targets.
#[derive(Debug, Clone)]
pub struct PropertySpan {
pub section: String,
pub path: Vec<String>,
pub key: String,
pub range: Range<usize>,
}
#[derive(Debug, Clone)]
pub struct SectionSpan {
pub section: String,
pub path: Vec<String>,
pub range: Range<usize>,
pub header_end: usize,
}
pub fn section_spans(input: &str) -> Result<Vec<SectionSpan>, ConfigError> {
scan_spans(input).map(|(_, sections)| sections)
}
pub fn property_spans(input: &str) -> Result<Vec<PropertySpan>, ConfigError> {
scan_spans(input).map(|(properties, _)| properties)
}
fn scan_spans(input: &str) -> Result<(Vec<PropertySpan>, Vec<SectionSpan>), ConfigError> {
Config::parse(input)?;
let raw: Vec<&str> = input.split_inclusive('\n').collect();
let lines: Vec<&str> = input.lines().collect();
let mut offsets = Vec::with_capacity(raw.len() + 1);
offsets.push(0);
for line in &raw {
offsets.push(offsets.last().copied().unwrap() + line.len());
}
let mut spans = Vec::new();
let mut sections: Vec<SectionSpan> = Vec::new();
let mut section = String::new();
let mut path = Vec::new();
let mut index = 0;
while index < lines.len() {
let line = strip_comment(lines[index]).trim();
if line.is_empty() {
index += 1;
continue;
}
if line.starts_with('[') && line.ends_with(']') {
let depth = line.chars().take_while(|&c| c == '[').count();
let name =
unquote_token(line[depth..line.len() - depth].trim()).map_err(|message| {
ConfigError::Parse {
line: index + 1,
message,
}
})?;
if depth == 1 {
section = name;
path.clear();
} else {
path.truncate(depth - 2);
path.push(name);
}
for previous in sections.iter_mut().rev() {
if previous.range.end == input.len() && previous.path.len() >= depth - 1 {
previous.range.end = offsets[index];
}
}
sections.push(SectionSpan {
section: section.clone(),
path: path.clone(),
range: offsets[index]..input.len(),
header_end: offsets[index + 1],
});
index += 1;
continue;
}
let eq = line.find('=').expect("validated property");
let key = unquote_token(line[..eq].trim()).map_err(|message| ConfigError::Parse {
line: index + 1,
message,
})?;
let (_, end) = parse_config_value(line[eq + 1..].trim(), &lines, index)?;
spans.push(PropertySpan {
section: section.clone(),
path: path.clone(),
key,
range: offsets[index]..offsets[end + 1],
});
index = end + 1;
}
Ok((spans, sections))
}
/// Validate syntax and changed IFAC semantics. Unchanged pre-existing errors may
/// stay blocked while the user migrates another interface; no new error is hidden.
pub fn validate_ifac_update(
previous: Option<&str>,
proposed: &str,
) -> Result<(), IfacMigrationError> {
let next = Config::parse(proposed).map_err(IfacMigrationError::Syntax)?;
let old = previous
.map(Config::parse)
.transpose()
.map_err(IfacMigrationError::Syntax)?;
for (name, section) in next.subsections("interfaces") {
if let Err(error) = parse_ifac_size(section) {
let unchanged = old
.as_ref()
.and_then(|c| c.subsection("interfaces", name))
.is_some_and(|prev| {
SIZE_KEYS
.iter()
.all(|key| prev.values.get(*key) == section.values.get(*key))
&& parse_ifac_size(prev).as_ref().err() == Some(&error)
&& (!section.interface_enabled() || prev.interface_enabled())
});
if !unchanged {
return Err(IfacMigrationError::Invalid {
interface: name.into(),
error,
});
}
}
}
Ok(())
}
pub fn plan_ifac_unit_migration(
content: &str,
selected: &[String],
units: IfacSourceUnits,
) -> Result<IfacMigrationPlan, IfacMigrationError> {
if selected.is_empty() {
return Err(IfacMigrationError::EmptySelection);
}
let config = Config::parse(content).map_err(IfacMigrationError::Syntax)?;
let spans = property_spans(content).map_err(IfacMigrationError::Syntax)?;
let mut changes = Vec::new();
let mut replacements = Vec::new();
let mut seen = HashSet::new();
for name in selected {
if !seen.insert(name) {
continue;
}
let section = config
.subsection("interfaces", name)
.ok_or_else(|| IfacMigrationError::NotFound(name.clone()))?;
match parse_ifac_size(section) {
Ok(_) => continue,
Err(IfacConfigError::IfacUnitsRequired) => (),
Err(error) => {
return Err(IfacMigrationError::Invalid {
interface: name.clone(),
error,
});
}
}
let value = integer(section, "ifac_size")
.map_err(|error| IfacMigrationError::Invalid {
interface: name.clone(),
error,
})?
.unwrap();
let bytes = match units {
IfacSourceUnits::Bytes => value,
IfacSourceUnits::Bits if (8..=64).contains(&value) && value % 8 == 0 => value / 8,
IfacSourceUnits::Bits => {
return Err(IfacMigrationError::Invalid {
interface: name.clone(),
error: invalid("ifac_size", "selected bit size must be a multiple of 8"),
});
}
};
let span = spans
.iter()
.find(|span| {
span.section == "interfaces"
&& span.path == [name.clone()]
&& span.key == "ifac_size"
})
.ok_or(IfacMigrationError::SourceMismatch)?;
let raw = &content[span.range.clone()];
let stripped = raw.trim_end_matches(['\r', '\n']);
let code = strip_comment(stripped);
let comment = &stripped[code.len()..];
let indent = &stripped[..stripped.len() - stripped.trim_start().len()];
let ending = if raw.ends_with("\r\n") { "\r\n" } else { "\n" };
let comment = if comment.is_empty() {
String::new()
} else {
format!(" {comment}")
};
let replacement = format!(
"{indent}ifac_size = {}{comment}{ending}{indent}ifac_size_unit = bits{ending}",
bytes * 8
);
replacements.push((span.range.clone(), replacement));
changes.push(IfacUnitChange {
interface: name.clone(),
previous_value: value,
effective_bytes: bytes,
});
}
replacements.sort_by_key(|(range, _)| range.start);
let mut proposed = content.to_string();
for (range, replacement) in replacements.into_iter().rev() {
proposed.replace_range(range, &replacement);
}
validate_ifac_update(Some(content), &proposed)?;
Ok(IfacMigrationPlan {
source_hash: sha256(content.as_bytes()),
proposed,
changes,
})
}
/// Redacted status consumed by configuration editors. Credentials never enter it.
pub fn migration_candidates(config: &Config) -> Vec<IfacUnitChange> {
config
.subsections("interfaces")
.into_iter()
.filter_map(|(name, section)| {
if parse_ifac_size(section) != Err(IfacConfigError::IfacUnitsRequired) {
return None;
}
Some(IfacUnitChange {
interface: name.into(),
previous_value: integer(section, "ifac_size").ok().flatten()?,
effective_bytes: integer(section, "ifac_size").ok().flatten()?,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn section(body: &str) -> ConfigSection {
Config::parse(&format!("[interfaces]\n[[x]]\n{body}"))
.unwrap()
.subsection("interfaces", "x")
.unwrap()
.clone()
}
#[test]
fn ifac_units_exact_decoder() {
for bytes in 1..=64 {
assert_eq!(
parse_ifac_size(&section(&format!(
"ifac_size={}\nifac_size_unit=bits",
bytes * 8
))),
Ok(Some(bytes))
);
assert_eq!(
parse_ifac_size(&section(&format!("ifac_size_bytes={bytes}"))),
Ok(Some(bytes))
);
assert_eq!(
parse_ifac_size(&section(&format!("ifac_size={bytes}"))),
Err(IfacConfigError::IfacUnitsRequired)
);
}
assert_eq!(parse_ifac_size(&section("ifac_size=72")), Ok(Some(9)));
assert_eq!(parse_ifac_size(&section("ifac_size=128")), Ok(Some(16)));
assert_eq!(parse_ifac_size(&section("")), Ok(None));
for body in [
"ifac_size=0",
"ifac_size=-1",
"ifac_size=8.0",
"ifac_size=+8",
"ifac_size=999999999999999999999999",
"ifac_size=513",
"ifac_size=65",
"ifac_size=8,16",
"ifac_size_unit=bits",
"ifac_size=128\nifac_size_unit=bytes",
"ifac_size_bytes=16\nifac_size=128",
"ifac_size_bytes=16\nifac_size_unit=bits",
"ifac_size_bytes=65",
] {
assert!(parse_ifac_size(&section(body)).is_err(), "{body}");
}
}
#[test]
fn ifac_migration_preserves_other_bytes_and_is_idempotent() {
let input = "[interfaces]\r\n [[\"a\"]]\r\n passphrase = 'not for diagnostics'\r\n 'ifac_size' = 16 # keep this\r\n type=TCPClientInterface\r\n [[b]]\r\n ifac_size=64\r\n";
let plan = plan_ifac_unit_migration(input, &["a".into()], IfacSourceUnits::Bytes).unwrap();
assert_eq!(plan.changes()[0].effective_bytes, 16);
assert_eq!(
plan.proposed_config(),
input.replace(
"'ifac_size' = 16 # keep this\r\n",
"ifac_size = 128 # keep this\r\n ifac_size_unit = bits\r\n"
)
);
assert!(plan.source_matches(input));
assert!(!format!("{plan:?}").contains("not for diagnostics"));
assert!(
plan_ifac_unit_migration(
plan.proposed_config(),
&["a".into()],
IfacSourceUnits::Bytes
)
.unwrap()
.is_unchanged()
);
let bits =
plan_ifac_unit_migration(plan.proposed_config(), &["b".into()], IfacSourceUnits::Bits)
.unwrap();
assert_eq!(bits.changes()[0].effective_bytes, 8);
}
#[test]
fn ifac_migration_never_edits_fake_headers_inside_multiline_values() {
let input = "[other]\ntext = '''\n[interfaces]\n[[a]]\nifac_size=64\n'''\n[interfaces]\n[[a]]\nifac_size=16\n";
let plan = plan_ifac_unit_migration(input, &["a".into()], IfacSourceUnits::Bytes).unwrap();
assert!(plan.proposed_config().contains("[[a]]\nifac_size=64\n'''"));
assert!(
plan.proposed_config()
.ends_with("ifac_size = 128\nifac_size_unit = bits\n")
);
assert!(
plan_ifac_unit_migration(
"[interfaces]\n[[a]]\nifac_size=7",
&["a".into()],
IfacSourceUnits::Bits
)
.is_err()
);
assert!(
plan_ifac_unit_migration(
"[interfaces]\n[[a]]\nifac_size=8\nifac_size=8",
&["a".into()],
IfacSourceUnits::Bits
)
.is_err()
);
}
#[test]
fn ifac_update_preserves_only_unchanged_old_errors() {
let old = "[interfaces]\n[[a]]\ntype=TCPClientInterface\nifac_size=16\n";
assert!(
validate_ifac_update(Some(old), &old.replace("type=", "host=localhost\ntype=")).is_ok()
);
assert!(
validate_ifac_update(Some(old), &old.replace("ifac_size=16", "ifac_size=32")).is_err()
);
assert!(validate_ifac_update(None, old).is_err());
}
}
@@ -0,0 +1,49 @@
//! Cross-process coordination for config snapshots and atomic replacement.
use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
/// Held across source comparison, immutable backup and publication. The lock
/// file remains in place: deleting it would let another writer lock a different
/// inode while the first lock is still held. OS ownership releases on crash.
#[derive(Debug)]
pub struct ConfigWriteLock {
_file: File,
}
impl ConfigWriteLock {
/// Acquire without waiting. All cooperating config writers use this same
/// sibling lock. External editors must be stopped during migration.
pub fn acquire(config_path: &Path) -> io::Result<Self> {
let parent = std::fs::canonicalize(
config_path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new(".")),
)?;
let name = config_path.file_name().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "config has no file name")
})?;
let mut lock_name = std::ffi::OsString::from(".");
lock_name.push(name);
lock_name.push(".write.lock");
let lock_path = parent.join(lock_name);
if std::fs::symlink_metadata(&lock_path)
.is_ok_and(|metadata| !metadata.is_file() || metadata.file_type().is_symlink())
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"config lock must be a regular file",
));
}
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(lock_path)?;
rns_identity::persistence::try_lock_exclusive(&file)?;
Ok(Self { _file: file })
}
}
+298
View File
@@ -0,0 +1,298 @@
//! Bounded authority for completing a Destination request outside the Link loop.
use crate::link_manager::RequestOutcome;
use std::sync::{
Arc, Mutex, OnceLock,
atomic::{AtomicBool, Ordering},
};
use std::time::{Duration, Instant};
use tokio::sync::{Notify, oneshot};
pub(crate) const LIFETIME: Duration = Duration::from_secs(120);
const JOBS: usize = 4;
const BYTES: usize = 256 * 1024 * 1024;
const SCRATCH: usize = 16 * 1024 * 1024;
pub(crate) const MAX_RESPONSE: usize = 64 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeferredResponseOutcome {
Sent,
Closed,
Expired,
Unavailable,
Dropped,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum DeferredResponseError {
#[error("request is no longer live")]
Closed,
#[error("response allocation exceeds the admitted byte limit")]
TooLarge,
}
#[derive(Default, Debug)]
struct Counts {
jobs: usize,
bytes: usize,
}
#[derive(Debug)]
pub(crate) struct RequestLease {
counts: Arc<Mutex<Counts>>,
bytes: usize,
}
impl Drop for RequestLease {
fn drop(&mut self) {
let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
counts.jobs -= 1;
counts.bytes -= self.bytes;
}
}
#[derive(Debug)]
struct State {
alive: AtomicBool,
deadline: Instant,
limit: usize,
notify: Arc<Notify>,
lease: Arc<RequestLease>,
}
/// One-shot completion authority issued only after the manager reserves a job
/// and its bytes. Keep this value inside the actual worker until its I/O ends;
/// dropping a caller's async task must not detach an uncharged blocking job.
///
/// The effective response limit can be lower than the registered ceiling. The
/// reservation includes sixteen times request capacity, eight response buffers and 16 MiB of
/// construction scratch. This is a conservative bound for the current Resource
/// construction path, not a claim that unrelated application allocations are
/// globally capped. Responses must fit by allocation capacity, not just length.
#[derive(Debug)]
pub struct DeferredRequestResponder {
state: Arc<State>,
sender: Option<oneshot::Sender<Resolution>>,
}
#[derive(Debug)]
pub(crate) struct Resolution {
pub outcome: RequestOutcome,
pub reply: oneshot::Sender<DeferredResponseOutcome>,
}
pub(crate) struct PendingResponse {
state: Arc<State>,
receiver: oneshot::Receiver<Resolution>,
}
impl DeferredRequestResponder {
pub fn response_byte_limit(&self) -> usize {
self.state.limit
}
pub fn is_cancelled(&self) -> bool {
!self.state.alive.load(Ordering::Acquire) || Instant::now() >= self.state.deadline
}
/// Queues one result. `Sent` acknowledges transport queue acceptance or
/// Resource initiation, not remote delivery. No response is emitted for a
/// closed/replaced Link, a dropped manager or an expired request.
pub fn respond(
mut self,
outcome: RequestOutcome,
) -> Result<oneshot::Receiver<DeferredResponseOutcome>, DeferredResponseError> {
if self.is_cancelled() {
return Err(DeferredResponseError::Closed);
}
let capacity = match &outcome {
RequestOutcome::Reply(data) => Some(data.capacity()),
RequestOutcome::ReplyWithResource {
ack,
data,
metadata,
..
} => ack
.capacity()
.checked_add(data.capacity())
.and_then(|n| n.checked_add(metadata.as_ref().map_or(0, Vec::capacity))),
RequestOutcome::Drop => Some(0),
};
if capacity.is_none_or(|n| n > self.state.limit) {
return Err(DeferredResponseError::TooLarge);
}
let (reply, result) = oneshot::channel();
self.sender
.take()
.ok_or(DeferredResponseError::Closed)?
.send(Resolution { outcome, reply })
.map_err(|_| DeferredResponseError::Closed)?;
self.state.notify.notify_one();
Ok(result)
}
}
impl Drop for DeferredRequestResponder {
fn drop(&mut self) {
// Close the channel before waking the polling manager. Otherwise the
// wake can race ahead of field destruction and leave an empty receiver
// asleep until its deadline.
self.sender.take();
self.state.notify.notify_one();
}
}
impl PendingResponse {
pub fn try_recv(&mut self) -> Result<Resolution, oneshot::error::TryRecvError> {
self.receiver.try_recv()
}
pub fn deadline(&self) -> Instant {
self.state.deadline
}
pub fn lease(&self) -> Arc<RequestLease> {
self.state.lease.clone()
}
pub fn close(&mut self, outcome: DeferredResponseOutcome) {
self.state.alive.store(false, Ordering::Release);
self.receiver.close();
if let Ok(resolution) = self.receiver.try_recv() {
let _ = resolution.reply.send(outcome);
}
}
}
impl Drop for PendingResponse {
fn drop(&mut self) {
self.close(DeferredResponseOutcome::Closed);
}
}
pub(crate) fn reserve(
input_capacity: usize,
requested_limit: usize,
notify: Arc<Notify>,
) -> Option<(DeferredRequestResponder, PendingResponse)> {
static GLOBAL: OnceLock<Arc<Mutex<Counts>>> = OnceLock::new();
reserve_with(
GLOBAL
.get_or_init(|| Arc::new(Mutex::new(Counts::default())))
.clone(),
input_capacity,
requested_limit,
notify,
)
}
fn reserve_with(
counts: Arc<Mutex<Counts>>,
input_capacity: usize,
requested_limit: usize,
notify: Arc<Notify>,
) -> Option<(DeferredRequestResponder, PendingResponse)> {
reserve_with_deadline(
counts,
input_capacity,
requested_limit,
notify,
Instant::now() + LIFETIME,
)
}
fn reserve_with_deadline(
counts: Arc<Mutex<Counts>>,
input_capacity: usize,
requested_limit: usize,
notify: Arc<Notify>,
deadline: Instant,
) -> Option<(DeferredRequestResponder, PendingResponse)> {
let overhead = input_capacity.checked_mul(16)?.checked_add(SCRATCH)?;
let limit = requested_limit.min(BYTES.checked_sub(overhead)? / 8);
if limit == 0 {
return None;
}
let bytes = limit.checked_mul(8)?.checked_add(overhead)?;
{
let mut counts = counts.lock().unwrap_or_else(|e| e.into_inner());
if counts.jobs >= JOBS || bytes > BYTES.saturating_sub(counts.bytes) {
return None;
}
counts.jobs += 1;
counts.bytes += bytes;
}
let state = Arc::new(State {
alive: AtomicBool::new(true),
deadline,
limit,
notify,
lease: Arc::new(RequestLease { counts, bytes }),
});
let (sender, receiver) = oneshot::channel();
Some((
DeferredRequestResponder {
state: state.clone(),
sender: Some(sender),
},
PendingResponse { state, receiver },
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn closed_request_keeps_worker_credit_and_rejects_late_response() {
let counts = Arc::new(Mutex::new(Counts::default()));
let (worker, mut pending) =
reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap();
pending.close(DeferredResponseOutcome::Closed);
drop(pending);
assert_eq!(counts.lock().unwrap().jobs, 1);
assert!(worker.is_cancelled());
assert_eq!(
worker.respond(RequestOutcome::Reply(vec![1])).unwrap_err(),
DeferredResponseError::Closed
);
assert_eq!(counts.lock().unwrap().jobs, 0);
}
#[test]
fn allocation_capacity_and_global_admission_are_bounded() {
let counts = Arc::new(Mutex::new(Counts::default()));
let mut jobs = Vec::new();
for _ in 0..4 {
jobs.push(reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap());
}
assert!(reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).is_none());
let (worker, pending) = jobs.pop().unwrap();
let bytes = Vec::with_capacity(101);
assert_eq!(
worker.respond(RequestOutcome::Reply(bytes)).unwrap_err(),
DeferredResponseError::TooLarge
);
drop(pending);
assert!(reserve_with(counts, 10, 100, Arc::new(Notify::new())).is_some());
}
#[test]
fn expired_and_oversized_requests_never_acquire_send_authority() {
let counts = Arc::new(Mutex::new(Counts::default()));
assert!(reserve_with(counts.clone(), usize::MAX, 100, Arc::new(Notify::new())).is_none());
assert!(reserve_with(counts.clone(), BYTES / 16, 100, Arc::new(Notify::new())).is_none());
assert_eq!(counts.lock().unwrap().jobs, 0);
let (worker, pending) = reserve_with_deadline(
counts.clone(),
1,
100,
Arc::new(Notify::new()),
Instant::now() - Duration::from_secs(1),
)
.unwrap();
assert!(worker.is_cancelled());
assert_eq!(
worker.respond(RequestOutcome::Reply(vec![1])).unwrap_err(),
DeferredResponseError::Closed
);
drop(pending);
assert_eq!(counts.lock().unwrap().bytes, 0);
}
#[test]
fn queued_result_and_resource_owner_retain_credit() {
let counts = Arc::new(Mutex::new(Counts::default()));
let (worker, mut pending) =
reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap();
let mut ack = worker.respond(RequestOutcome::Reply(vec![1])).unwrap();
assert_eq!(counts.lock().unwrap().jobs, 1);
let resolution = pending.try_recv().unwrap();
let resource_lease = pending.lease();
resolution
.reply
.send(DeferredResponseOutcome::Sent)
.unwrap();
drop(pending);
assert_eq!(ack.try_recv().unwrap(), DeferredResponseOutcome::Sent);
assert_eq!(counts.lock().unwrap().jobs, 1);
drop(resource_lease);
assert_eq!(counts.lock().unwrap().jobs, 0);
}
}
+11 -1
View File
@@ -143,6 +143,8 @@ pub struct DestinationEvents {
#[derive(Debug, thiserror::Error)]
pub enum DestinationRuntimeError {
#[error(transparent)]
OrdinaryPacketConfiguration(#[from] crate::link_manager::LinkPacketConfigurationError),
#[error(transparent)]
Destination(#[from] DestinationError),
#[error(transparent)]
@@ -427,6 +429,13 @@ impl RegisteredDestination {
if options.event_capacity == 0 {
return Err(DestinationRuntimeError::InvalidEventCapacity);
}
// This compatibility constructor receives only the transport mailbox,
// which cannot grant exact endpoint-generation dispatch authority.
if options.proof_strategy == ProofStrategy::ProveApp {
return Err(
crate::link_manager::LinkPacketConfigurationError::ExactDispatchRequired.into(),
);
}
let app_name = app_name.into();
let destination =
Destination::new(Some(&identity), Direction::In, DestType::Single, &app_name)?;
@@ -492,7 +501,7 @@ impl RegisteredDestination {
let (links_closed_tx, links_closed) = mpsc::channel(capacity);
manager.set_link_established_channel(links_established_tx);
manager.set_link_identified_channel(links_identified_tx);
manager.set_link_packet_channel(link_packets_tx);
manager.set_link_packet_channel(link_packets_tx)?;
manager.set_link_packet_proof_channel(link_packet_proofs_tx);
manager.set_resource_completion_channel(resource_completions_tx);
manager.set_outbound_resource_proof_channel(resource_proofs_tx);
@@ -878,6 +887,7 @@ mod tests {
.send(
rns_transport::link_messages::DestinationEvent::InboundPacket {
raw: bytes::Bytes::from(packet.raw),
interface_owner: None,
interface_id: 1,
metrics: rns_transport::link_messages::PacketMetrics::default(),
},
@@ -0,0 +1,447 @@
//! Bounded, one-shot application authority for ordinary Link DATA packets.
use bytes::Bytes;
use rns_link::link::LinkRole;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::{Notify, oneshot};
pub const APPLICATION_PACKET_LIFETIME: Duration = Duration::from_secs(120);
const GLOBAL_SLOTS: usize = 256;
const GLOBAL_BYTES: usize = 8 * 1024 * 1024;
const LINK_SLOTS: usize = 64;
const LINK_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkPacketReceiptOutcome {
Sent,
Expired,
Closed,
Dropped,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkPacketRejection {
InvalidPropagationStamp,
}
#[derive(Debug, thiserror::Error)]
pub enum LinkPacketConfigurationError {
#[error("application-controlled ordinary proofs require an exact endpoint dispatch handle")]
ExactDispatchRequired,
#[error("application-controlled ordinary proofs require the typed bounded inbound channel")]
TypedChannelRequired,
#[error("legacy tuple channel cannot carry application-controlled packet receipts")]
LegacyChannel,
}
#[derive(Default, Debug)]
struct Counts {
slots: usize,
bytes: usize,
}
#[derive(Debug)]
pub(crate) struct PacketLease {
global: Arc<Mutex<Counts>>,
link: Arc<Mutex<Counts>>,
bytes: usize,
}
impl Drop for PacketLease {
fn drop(&mut self) {
let mut global = self.global.lock().unwrap_or_else(|e| e.into_inner());
let mut link = self.link.lock().unwrap_or_else(|e| e.into_inner());
global.slots -= 1;
global.bytes -= self.bytes;
link.slots -= 1;
link.bytes -= self.bytes;
}
}
/// A private identity object distinguishes re-created Links even if their wire
/// ID or transport generation counter is reused.
#[derive(Debug)]
pub(crate) struct PacketEpoch {
pub generation: u64,
pub alive: AtomicBool,
counts: Arc<Mutex<Counts>>,
}
impl PacketEpoch {
pub fn new(generation: u64) -> Arc<Self> {
Arc::new(Self {
generation,
alive: AtomicBool::new(true),
counts: Arc::new(Mutex::new(Counts::default())),
})
}
pub fn reserve(self: &Arc<Self>, bytes: usize) -> Option<Arc<PacketLease>> {
static GLOBAL: OnceLock<Arc<Mutex<Counts>>> = OnceLock::new();
let global = GLOBAL
.get_or_init(|| Arc::new(Mutex::new(Counts::default())))
.clone();
reserve(global, self.counts.clone(), bytes)
}
}
fn reserve(
global: Arc<Mutex<Counts>>,
link: Arc<Mutex<Counts>>,
bytes: usize,
) -> Option<Arc<PacketLease>> {
{
let mut g = global.lock().unwrap_or_else(|e| e.into_inner());
let mut l = link.lock().unwrap_or_else(|e| e.into_inner());
if g.slots >= GLOBAL_SLOTS
|| l.slots >= LINK_SLOTS
|| bytes > GLOBAL_BYTES.saturating_sub(g.bytes)
|| bytes > LINK_BYTES.saturating_sub(l.bytes)
{
return None;
}
g.slots += 1;
g.bytes += bytes;
l.slots += 1;
l.bytes += bytes;
}
Some(Arc::new(PacketLease {
global,
link,
bytes,
}))
}
#[derive(Debug)]
pub(crate) enum Decision {
Accept,
Drop,
Close,
Reject(LinkPacketRejection),
}
#[derive(Debug)]
pub(crate) struct Resolution {
pub decision: Decision,
pub reply: Option<oneshot::Sender<LinkPacketReceiptOutcome>>,
}
/// Stored separately from authority: retained payload clones and live workers
/// keep credits even after expiration or Link teardown.
struct LeasedPayload {
bytes: Vec<u8>,
_lease: Arc<PacketLease>,
}
impl AsRef<[u8]> for LeasedPayload {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
#[derive(Debug)]
pub struct InboundLinkPacket {
payload: Bytes,
link_id: [u8; 16],
destination_hash: [u8; 16],
packet_hash: [u8; 32],
role: LinkRole,
receipt: Option<LinkPacketReceipt>,
}
impl InboundLinkPacket {
pub fn payload(&self) -> &Bytes {
&self.payload
}
pub fn link_id(&self) -> [u8; 16] {
self.link_id
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination_hash
}
pub fn packet_hash(&self) -> [u8; 32] {
self.packet_hash
}
pub fn role(&self) -> LinkRole {
self.role
}
pub fn into_parts(self) -> (Bytes, Option<LinkPacketReceipt>) {
(self.payload, self.receipt)
}
pub(crate) fn new(
bytes: Vec<u8>,
link_id: [u8; 16],
destination_hash: [u8; 16],
packet_hash: [u8; 32],
role: LinkRole,
receipt: Option<LinkPacketReceipt>,
) -> Self {
let payload = match &receipt {
Some(receipt) => Bytes::from_owner(LeasedPayload {
bytes,
_lease: receipt.lease.clone(),
}),
None => Bytes::from(bytes),
};
Self {
payload,
link_id,
destination_hash,
packet_hash,
role,
receipt,
}
}
}
/// Non-cloneable authority for one exact received packet. Resolution does not
/// imply admission until its returned receiver reports `Sent`.
#[derive(Debug)]
pub struct LinkPacketReceipt {
resolver: Option<oneshot::Sender<Resolution>>,
notify: Arc<Notify>,
lease: Arc<PacketLease>,
pub(crate) state: Arc<AtomicU8>,
}
impl LinkPacketReceipt {
pub(crate) fn new(
lease: Arc<PacketLease>,
notify: Arc<Notify>,
) -> (Self, oneshot::Receiver<Resolution>) {
let (tx, rx) = oneshot::channel();
(
Self {
resolver: Some(tx),
notify,
lease,
state: Arc::new(AtomicU8::new(0)),
},
rx,
)
}
pub fn accept(self) -> oneshot::Receiver<LinkPacketReceiptOutcome> {
self.resolve(Decision::Accept)
}
pub fn reject_and_close(
self,
reason: LinkPacketRejection,
) -> oneshot::Receiver<LinkPacketReceiptOutcome> {
self.resolve(Decision::Reject(reason))
}
pub fn drop_without_proof(self) {
drop(self);
}
/// Close only this receipt's still-current Link without a delivery proof or
/// an invalid-stamp error. `Closed` confirms local closure, not peer receipt
/// of the best-effort teardown. Stale authority cannot close a replacement.
pub fn close_without_proof(self) -> oneshot::Receiver<LinkPacketReceiptOutcome> {
self.resolve(Decision::Close)
}
fn resolve(mut self, decision: Decision) -> oneshot::Receiver<LinkPacketReceiptOutcome> {
let (reply, rx) = oneshot::channel();
let resolution = Resolution {
decision,
reply: Some(reply),
};
if let Some(tx) = self.resolver.take()
&& let Err(resolution) = tx.send(resolution)
{
let outcome = terminal_outcome(&self.state).unwrap_or(LinkPacketReceiptOutcome::Closed);
if let Some(tx) = resolution.reply {
let _ = tx.send(outcome);
}
}
self.notify.notify_one();
rx
}
}
impl Drop for LinkPacketReceipt {
fn drop(&mut self) {
if let Some(tx) = self.resolver.take() {
let _ = tx.send(Resolution {
decision: Decision::Drop,
reply: None,
});
}
self.notify.notify_one();
}
}
pub(crate) fn set_terminal(state: &AtomicU8, outcome: LinkPacketReceiptOutcome) {
let value = match outcome {
LinkPacketReceiptOutcome::Sent => 1,
LinkPacketReceiptOutcome::Expired => 2,
LinkPacketReceiptOutcome::Closed => 3,
LinkPacketReceiptOutcome::Dropped => 4,
LinkPacketReceiptOutcome::Unavailable => 5,
};
state.store(value, Ordering::Release);
}
fn terminal_outcome(state: &AtomicU8) -> Option<LinkPacketReceiptOutcome> {
match state.load(Ordering::Acquire) {
1 => Some(LinkPacketReceiptOutcome::Sent),
2 => Some(LinkPacketReceiptOutcome::Expired),
3 => Some(LinkPacketReceiptOutcome::Closed),
4 => Some(LinkPacketReceiptOutcome::Dropped),
5 => Some(LinkPacketReceiptOutcome::Unavailable),
_ => None,
}
}
pub(crate) struct PendingInboundPacket {
pub link_id: [u8; 16],
pub packet_hash: [u8; 32],
pub epoch: Arc<PacketEpoch>,
pub deadline: Instant,
pub state: Arc<AtomicU8>,
pub _lease: Arc<PacketLease>,
pub resolution: oneshot::Receiver<Resolution>,
pub dispatch: Option<PacketDispatch>,
}
pub(crate) struct PacketDispatch {
pub result:
oneshot::Receiver<rns_transport::link_endpoint_dispatch::LinkEndpointDispatchOutcome>,
pub cancellation: rns_transport::link_endpoint_dispatch::LinkEndpointDispatchCancellation,
pub expected_hash: [u8; 32],
pub payload_len: usize,
pub rejecting: bool,
pub ready: Option<
Result<
rns_transport::link_endpoint_dispatch::LinkEndpointDispatchOutcome,
oneshot::error::RecvError,
>,
>,
pub reply: Option<oneshot::Sender<LinkPacketReceiptOutcome>>,
}
impl PendingInboundPacket {
pub fn finish(&mut self, outcome: LinkPacketReceiptOutcome) {
set_terminal(&self.state, outcome);
if let Some(dispatch) = &mut self.dispatch {
if outcome != LinkPacketReceiptOutcome::Sent {
dispatch.cancellation.cancel();
}
if let Some(reply) = dispatch.reply.take() {
let _ = reply.send(outcome);
}
}
if let Ok(resolution) = self.resolution.try_recv()
&& let Some(reply) = resolution.reply
{
let _ = reply.send(outcome);
}
}
}
impl Drop for PendingInboundPacket {
fn drop(&mut self) {
if terminal_outcome(&self.state).is_none() {
self.finish(LinkPacketReceiptOutcome::Closed);
}
}
}
// Register completion wakers without detached tasks or another event queue.
pub(crate) async fn wait_dispatch(pending: &mut [PendingInboundPacket]) {
use std::future::Future;
use std::pin::Pin;
use std::task::Poll;
std::future::poll_fn(|cx| {
for packet in pending.iter_mut() {
if let Some(dispatch) = &mut packet.dispatch {
if dispatch.ready.is_some() {
return Poll::Ready(());
}
if let Poll::Ready(result) = Pin::new(&mut dispatch.result).poll(cx) {
dispatch.ready = Some(result);
return Poll::Ready(());
}
}
}
Poll::Pending
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn payload_owners_retain_credits_after_authority_closes() {
let global = Arc::new(Mutex::new(Counts::default()));
let link = Arc::new(Mutex::new(Counts::default()));
let lease = reserve(global.clone(), link.clone(), 100).unwrap();
let (receipt, rx) = LinkPacketReceipt::new(lease.clone(), Arc::new(Notify::new()));
let event = InboundLinkPacket::new(
vec![0; 100],
[1; 16],
[2; 16],
[3; 32],
LinkRole::Responder,
Some(receipt),
);
let payload = event.payload().clone();
drop(event);
drop(rx);
drop(lease);
assert_eq!(global.lock().unwrap().bytes, 100);
drop(payload);
assert_eq!(global.lock().unwrap().bytes, 0);
}
#[test]
fn reservations_are_atomic_and_per_link_isolation_is_bounded() {
let global = Arc::new(Mutex::new(Counts::default()));
let link = Arc::new(Mutex::new(Counts::default()));
let leases: Vec<_> = (0..LINK_SLOTS)
.map(|_| reserve(global.clone(), link.clone(), 1).unwrap())
.collect();
assert!(reserve(global.clone(), link.clone(), 1).is_none());
assert!(
reserve(
global.clone(),
Arc::new(Mutex::new(Counts::default())),
LINK_BYTES + 1
)
.is_none()
);
assert_eq!(global.lock().unwrap().slots, LINK_SLOTS);
let other = reserve(
global.clone(),
Arc::new(Mutex::new(Counts::default())),
LINK_BYTES,
)
.unwrap();
drop(leases);
drop(other);
assert_eq!(global.lock().unwrap().slots, 0);
}
#[test]
fn global_count_and_byte_limits_include_independent_links() {
let global = Arc::new(Mutex::new(Counts::default()));
let mut leases = Vec::new();
for _ in 0..4 {
let link = Arc::new(Mutex::new(Counts::default()));
for _ in 0..LINK_SLOTS {
leases.push(reserve(global.clone(), link.clone(), 1).unwrap());
}
}
assert_eq!(global.lock().unwrap().slots, GLOBAL_SLOTS);
assert!(reserve(global.clone(), Arc::new(Mutex::new(Counts::default())), 1).is_none());
drop(leases);
let leases: Vec<_> = (0..4)
.map(|_| {
reserve(
global.clone(),
Arc::new(Mutex::new(Counts::default())),
LINK_BYTES,
)
.unwrap()
})
.collect();
assert_eq!(global.lock().unwrap().bytes, GLOBAL_BYTES);
assert!(reserve(global.clone(), Arc::new(Mutex::new(Counts::default())), 1).is_none());
drop(leases);
assert_eq!(global.lock().unwrap().slots, 0);
assert_eq!(global.lock().unwrap().bytes, 0);
}
#[test]
fn late_resolution_reports_expiration_without_reviving_authority() {
let epoch = PacketEpoch::new(1);
let lease = epoch.reserve(1).unwrap();
let (receipt, rx) = LinkPacketReceipt::new(lease, Arc::new(Notify::new()));
set_terminal(&receipt.state, LinkPacketReceiptOutcome::Expired);
drop(rx);
assert_eq!(
receipt.accept().try_recv().unwrap(),
LinkPacketReceiptOutcome::Expired
);
}
}
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -4,8 +4,10 @@
pub mod buffer_stream;
pub mod config;
pub mod constants;
mod deferred_request;
pub mod destination_resolver;
pub mod destination_runtime;
mod inbound_link_packet;
pub mod interface_factory;
mod interface_registry;
pub mod jobs;
@@ -17,7 +19,6 @@ pub mod link_session;
pub mod platform;
pub mod probe;
pub mod remote_management;
pub mod remote_management_schema;
pub mod resource_source;
pub mod reticulum;
pub mod rncp;
@@ -63,8 +64,9 @@ pub mod prelude {
pub use rns_interface::rnode::{
RNodeCapabilityAdmissionError, RNodeCapabilityAdmissionFailureClass, RNodeCapabilityState,
RNodeConfigurationState, RNodeDetectionState, RNodeFirmwareCompatibility,
RNodeObservedRadioState, RNodeRuntimePhase, RNodeRuntimeReason, RNodeRuntimeSnapshot,
RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
RNodeObservedRadioState, RNodePortFailureClass, RNodeRuntimePhase, RNodeRuntimeReason,
RNodeRuntimeSnapshot, RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState,
RNodeTransportClass,
};
pub use rns_link::link::{CloseReason, ResourceStrategy};
pub use rns_transport::path_recovery::{
+28 -8
View File
@@ -27,6 +27,8 @@ use crate::destination_resolver::{
#[derive(Debug, thiserror::Error)]
pub enum LinkClientError {
#[error("link request admission failed: {0}")]
RequestDispatch(#[from] rns_transport::link_messages::LinkRequestDispatchError),
#[error("transport channel closed or full")]
TransportUnavailable,
#[error("timed out waiting for {0}")]
@@ -55,6 +57,7 @@ struct LinkClientEndpoint<'a> {
delivery_rx: &'a mut mpsc::Receiver<DestinationEvent>,
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
}
impl LinkClient {
@@ -77,7 +80,9 @@ impl LinkClient {
overall_timeout: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let started = Instant::now();
let deadline = started + overall_timeout;
let deadline = started
.checked_add(overall_timeout)
.ok_or_else(|| LinkClientError::HandshakeFailed("unrepresentable timeout".into()))?;
let dest_hash =
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
@@ -110,11 +115,18 @@ impl LinkClient {
);
let req_pkt = build_link_request_packet(dest_hash, &request_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: req_pkt,
destination_hash: dest_hash,
}))
.await?;
timeout(
time_remaining(deadline)?,
rns_transport::link_messages::dispatch_link_request(
&self.transport_tx,
OutboundRequest {
raw: req_pkt,
destination_hash: dest_hash,
},
),
)
.await
.map_err(|_| LinkClientError::Timeout("link request admission"))??;
let identity_ed25519_pub: [u8; 32] = pubkey[32..64].try_into().map_err(|_| {
LinkClientError::ProofInvalid("remote public key is not 64 bytes".into())
@@ -141,12 +153,14 @@ impl LinkClient {
}
})?;
let attached_interface = proof.interface_id;
let interface_owner = proof.interface_owner;
let rtt_data = proof.rtt_data;
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
&self.transport_tx,
link_id,
attached_interface,
interface_owner,
LinkEndpointRole::Initiator,
)
.await
@@ -156,6 +170,7 @@ impl LinkClient {
delivery_rx: &mut dest_rx,
lifecycle_rx: &mut endpoint_lifecycle_rx,
attached_interface,
interface_owner,
};
let rtt_pkt =
@@ -300,9 +315,14 @@ async fn wait_for_response(
return Err(LinkClientError::HandshakeFailed("link closed".into()));
}
DestinationEvent::InboundPacket {
raw, interface_id, ..
raw,
interface_id,
interface_owner,
..
} => {
if interface_id != endpoint.attached_interface {
if interface_id != endpoint.attached_interface
|| interface_owner != endpoint.interface_owner
{
continue;
}
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
+11
View File
@@ -170,6 +170,7 @@ pub(crate) enum LinkProofWaitError {
pub(crate) struct ValidatedLinkProof {
pub(crate) rtt_data: Vec<u8>,
pub(crate) interface_id: InterfaceId,
pub(crate) interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
pub(crate) metrics: PacketMetrics,
}
@@ -191,6 +192,7 @@ pub(crate) async fn wait_for_valid_proof(
DestinationEvent::InboundPacket {
raw,
interface_id,
interface_owner,
metrics,
} => {
let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else {
@@ -211,6 +213,7 @@ pub(crate) async fn wait_for_valid_proof(
return Ok(ValidatedLinkProof {
rtt_data,
interface_id,
interface_owner,
metrics,
});
}
@@ -234,6 +237,7 @@ pub(crate) async fn bind(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
interface_id: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
role: LinkEndpointRole,
) -> Result<mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>, LinkEndpointError> {
let (lifecycle_tx, lifecycle_rx) = mpsc::unbounded_channel();
@@ -243,6 +247,7 @@ pub(crate) async fn bind(
binding: LinkEndpointBinding {
link_id,
interface_id,
interface_owner,
role,
},
lifecycle_tx,
@@ -479,11 +484,14 @@ mod tests {
let mut invalid = proof.clone();
invalid[0] ^= 0x80;
let link_id = initiator.link_id;
let original_owner = rns_transport::messages::InterfaceOwner::new();
let proof_owner = rns_transport::messages::InterfaceOwner::new();
let (event_tx, mut event_rx) = mpsc::channel(2);
event_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &invalid),
interface_id: 41,
interface_owner: Some(original_owner.id()),
metrics: PacketMetrics {
rssi: Some(-10.0),
..Default::default()
@@ -495,6 +503,7 @@ mod tests {
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &proof),
interface_id: 42,
interface_owner: Some(proof_owner.id()),
metrics: PacketMetrics {
rssi: Some(-80.0),
..Default::default()
@@ -512,6 +521,7 @@ mod tests {
.await
.unwrap();
assert_eq!(validated.interface_id, 42);
assert_eq!(validated.interface_owner, Some(proof_owner.id()));
assert_eq!(validated.metrics.rssi, Some(-80.0));
assert!(matches!(
initiator.state,
@@ -534,6 +544,7 @@ mod tests {
event_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &proof),
interface_owner: None,
interface_id: 99,
metrics: PacketMetrics::default(),
})
File diff suppressed because it is too large. Load diff
+122 -12
View File
@@ -396,6 +396,8 @@ pub enum LinkSessionResourceError {
OfferExpired,
#[error("inbound resource advertisement is invalid: {0}")]
InvalidAdvertisement(String),
#[error("resource control rejected: {0}")]
Control(#[from] rns_protocol::resource::ResourceError),
#[error("resource transfer failed: {0}")]
Failed(String),
#[error(transparent)]
@@ -418,6 +420,8 @@ pub enum LinkSessionChannelError {
#[derive(Debug, thiserror::Error)]
pub enum LinkSessionError {
#[error("link request admission failed: {0}")]
RequestDispatch(#[from] rns_transport::link_messages::LinkRequestDispatchError),
#[error("transport channel is unavailable")]
TransportUnavailable,
#[error("timed out waiting for {0}")]
@@ -609,6 +613,7 @@ struct SessionActorChannels {
struct DestinationEventContext<'a> {
transport_tx: &'a mpsc::Sender<TransportMessage>,
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
sinks: InboundResourceSinks<'a>,
phy_stats_tx: &'a watch::Sender<LinkPhyStats>,
}
@@ -938,6 +943,9 @@ impl LinkSession {
identity: Identity,
config: LinkSessionConfig,
) -> Result<Self, LinkSessionError> {
let deadline = Instant::now()
.checked_add(config.establishment_timeout)
.ok_or_else(|| LinkSessionError::HandshakeFailed("unrepresentable timeout".into()))?;
let (mut link, request_data) = Link::new_initiator(config.destination_hash, config.hops);
link.track_phy_stats(config.track_phy_stats);
let link_id = link.link_id;
@@ -958,16 +966,18 @@ impl LinkSession {
);
let request = build_link_request_packet(config.destination_hash, &request_data);
if transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: request,
destination_hash: config.destination_hash,
}))
.await
.is_err()
{
return Err(LinkSessionError::TransportUnavailable);
}
tokio::time::timeout(
deadline.saturating_duration_since(Instant::now()),
rns_transport::link_messages::dispatch_link_request(
&transport_tx,
OutboundRequest {
raw: request,
destination_hash: config.destination_hash,
},
),
)
.await
.map_err(|_| LinkSessionError::Timeout("link request admission"))??;
let peer_signing_key: [u8; 32] = config.remote_public_key[32..]
.try_into()
@@ -975,7 +985,7 @@ impl LinkSession {
let verify_key = Ed25519PublicKey::from_bytes(&peer_signing_key)
.map_err(|error| LinkSessionError::ProofInvalid(error.to_string()))?;
let proof = match tokio::time::timeout(
config.establishment_timeout,
deadline.saturating_duration_since(Instant::now()),
crate::link_endpoint::wait_for_valid_proof(
&mut delivery_rx,
&mut link,
@@ -997,6 +1007,7 @@ impl LinkSession {
Err(_) => return Err(LinkSessionError::Timeout("link proof")),
};
let attached_interface = proof.interface_id;
let interface_owner = proof.interface_owner;
let rtt_data = proof.rtt_data;
update_link_phy_stats(&mut link, proof.metrics);
@@ -1007,6 +1018,7 @@ impl LinkSession {
&transport_tx,
link_id,
attached_interface,
interface_owner,
LinkEndpointRole::Initiator,
)
.await
@@ -1063,6 +1075,7 @@ impl LinkSession {
tokio::spawn(run_session_actor(
(link, channel),
attached_interface,
interface_owner,
delivery_rx,
endpoint_lifecycle_rx,
command_rx,
@@ -1140,9 +1153,11 @@ pub async fn lookup_destination(
.find(|entry| entry.dest_hash == destination_hash))
}
#[allow(clippy::too_many_arguments)]
async fn run_session_actor(
link_and_channel: (Link, LinkChannel),
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
mut delivery_rx: mpsc::Receiver<DestinationEvent>,
mut endpoint_lifecycle_rx: mpsc::UnboundedReceiver<
rns_transport::messages::LinkEndpointLifecycleEvent,
@@ -1296,6 +1311,7 @@ async fn run_session_actor(
DestinationEventContext {
transport_tx: &transport_tx,
attached_interface,
interface_owner,
sinks: InboundResourceSinks {
event_tx: &event_tx,
command_tx: &command_tx,
@@ -1993,6 +2009,13 @@ async fn send_resource_action(
return Ok(());
}
};
rns_protocol::resource_control::check_control_frame(
context,
payload.len(),
encrypted,
rns_wire::constants::HEADER_MINSIZE,
link.mtu as usize,
)?;
let body = if encrypted {
link.encrypt(&payload)
.map_err(|_| LinkSessionResourceError::LinkCrypto)?
@@ -3572,6 +3595,7 @@ async fn process_destination_event(
let DestinationEventContext {
transport_tx,
attached_interface,
interface_owner: expected_owner,
sinks,
phy_stats_tx,
} = context;
@@ -3587,12 +3611,13 @@ async fn process_destination_event(
DestinationEvent::InboundPacket {
raw,
interface_id,
interface_owner,
metrics,
} => {
// Python pins an established Link to the interface that delivered
// its proof. Accepting Link traffic from another interface would
// both break route affinity and permit cross-interface injection.
if interface_id != attached_interface {
if interface_id != attached_interface || interface_owner != expected_owner {
return Ok(None);
}
let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else {
@@ -3995,6 +4020,10 @@ mod tests {
tokio::spawn(async move {
while let Some(message) = transport_rx.recv().await {
let observed = match message {
TransportMessage::SendLinkRequest { request, result_tx } => {
let _ = result_tx.send(Ok(()));
TransportMessage::Outbound(request)
}
TransportMessage::SendLinkEndpoint {
link_id,
role,
@@ -4462,6 +4491,7 @@ mod tests {
tokio::spawn(run_session_actor(
(initiator, channel),
7,
None,
delivery_rx,
endpoint_lifecycle_rx,
command_rx,
@@ -4492,6 +4522,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: inbound_packet.clone(),
interface_owner: None,
interface_id: 8,
metrics: Default::default(),
})
@@ -4508,6 +4539,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: inbound_packet,
interface_owner: None,
interface_id: 7,
metrics: Default::default(),
})
@@ -4533,6 +4565,7 @@ mod tests {
.send(rns_transport::messages::LinkEndpointLifecycleEvent {
binding: rns_transport::messages::LinkEndpointBinding {
link_id,
interface_owner: None,
interface_id: 7,
role: LinkEndpointRole::Initiator,
},
@@ -4558,6 +4591,51 @@ mod tests {
);
}
#[tokio::test]
async fn capacity_rejection_finishes_handshake_before_proof_timeout() {
let (tx, mut rx) = mpsc::channel(8);
let connect = tokio::spawn(LinkSession::connect(
tx,
Identity::new(),
LinkSessionConfig {
destination_hash: [0x71; 16],
remote_public_key: Identity::new().get_public_key(),
hops: 1,
establishment_timeout: Duration::from_secs(30),
client_label: "capacity".into(),
identify: false,
track_phy_stats: false,
},
));
let link_id = match rx.recv().await.unwrap() {
TransportMessage::RegisterDestination { hash, .. } => hash,
other => panic!("unexpected registration: {other:?}"),
};
let expected = rns_transport::link_messages::LinkRequestDispatchError::Capacity(
rns_transport::InterfaceCapacityError::LinkCapacityUnavailable {
interface_id: 7,
clear_mtu: 499,
required: 500,
},
);
match rx.recv().await.unwrap() {
TransportMessage::SendLinkRequest { result_tx, .. } => {
result_tx.send(Err(expected)).unwrap();
}
other => panic!("unexpected dispatch: {other:?}"),
}
let result = tokio::time::timeout(Duration::from_secs(1), connect)
.await
.unwrap()
.unwrap();
assert!(
matches!(result, Err(LinkSessionError::RequestDispatch(error)) if error == expected)
);
assert!(
matches!(rx.recv().await, Some(TransportMessage::DeregisterDestination { hash }) if hash == link_id)
);
}
#[tokio::test]
async fn cancelled_handshake_deregisters_temporary_link_destination() {
let destination_hash = [0x33; 16];
@@ -4629,6 +4707,10 @@ mod tests {
other => panic!("unexpected transport message: {other:?}"),
};
let request = match transport_rx.recv().await.unwrap() {
TransportMessage::SendLinkRequest { request, result_tx } => {
let _ = result_tx.send(Ok(()));
request
}
TransportMessage::Outbound(request) => request,
other => panic!("unexpected transport message: {other:?}"),
};
@@ -4643,6 +4725,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: build_proof_packet(link_id, rns_wire::context::PacketContext::None, &proof),
interface_owner: None,
interface_id: 23,
metrics: Default::default(),
})
@@ -4728,6 +4811,10 @@ mod tests {
other => panic!("unexpected transport message: {other:?}"),
};
let request = match transport_rx.recv().await.unwrap() {
TransportMessage::SendLinkRequest { request, result_tx } => {
let _ = result_tx.send(Ok(()));
request
}
TransportMessage::Outbound(request) => request,
other => panic!("unexpected transport message: {other:?}"),
};
@@ -4742,12 +4829,14 @@ mod tests {
let link_id = responder.link_id;
let inbound = move |context, body: &[u8]| DestinationEvent::InboundPacket {
raw: build_data_packet(link_id, context, body),
interface_owner: None,
interface_id: 1,
metrics: PacketMetrics::default(),
};
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: build_proof_packet(link_id, rns_wire::context::PacketContext::None, &proof),
interface_owner: None,
interface_id: 1,
metrics: PacketMetrics::default(),
})
@@ -4820,6 +4909,10 @@ mod tests {
};
let request = match transport_rx.recv().await.unwrap() {
TransportMessage::SendLinkRequest { request, result_tx } => {
let _ = result_tx.send(Ok(()));
request
}
TransportMessage::Outbound(request) => request,
other => panic!("unexpected transport message: {other:?}"),
};
@@ -4844,6 +4937,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet,
interface_owner: None,
interface_id: 1,
metrics: PacketMetrics {
rssi: Some(-87.0),
@@ -4944,6 +5038,7 @@ mod tests {
rns_wire::context::PacketContext::Response,
&response,
),
interface_owner: None,
interface_id: 1,
metrics: PacketMetrics {
rssi: Some(-72.0),
@@ -5072,6 +5167,7 @@ mod tests {
rns_wire::context::PacketContext::LinkProof,
&first_proof,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5100,6 +5196,7 @@ mod tests {
rns_wire::context::PacketContext::LinkProof,
&second_proof,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5136,6 +5233,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: inbound_channel_packet,
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5189,6 +5287,7 @@ mod tests {
rns_wire::context::PacketContext::Channel,
&ignored_prepared.data,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5217,6 +5316,7 @@ mod tests {
rns_wire::context::PacketContext::Channel,
&inbound_stream_prepared.data,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5265,6 +5365,7 @@ mod tests {
rns_wire::context::PacketContext::LinkProof,
&outbound_stream_proof,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5296,6 +5397,7 @@ mod tests {
rns_wire::context::PacketContext::LinkProof,
&eof_proof,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5314,6 +5416,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: inbound.clone(),
interface_owner: None,
interface_id: 9,
metrics: Default::default(),
})
@@ -5332,6 +5435,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: inbound,
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5417,6 +5521,7 @@ mod tests {
rns_wire::context::PacketContext::ResourceReq,
&encrypted_request,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5449,6 +5554,7 @@ mod tests {
rns_wire::context::PacketContext::ResourcePrf,
&resource_proof,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5573,6 +5679,7 @@ mod tests {
rns_wire::context::PacketContext::ResourceAdv,
&responder.encrypt(&inbound_advertisement).unwrap(),
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5623,6 +5730,7 @@ mod tests {
rns_wire::context::PacketContext::Resource,
&part,
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5685,6 +5793,7 @@ mod tests {
rns_wire::context::PacketContext::ResourceAdv,
&responder.encrypt(&rejected_advertisement).unwrap(),
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
@@ -5725,6 +5834,7 @@ mod tests {
rns_wire::context::PacketContext::ResourceAdv,
&responder.encrypt(&cancelled_advertisement).unwrap(),
),
interface_owner: None,
interface_id: 1,
metrics: Default::default(),
})
+76 -2
View File
@@ -25,6 +25,8 @@ const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
#[derive(Debug, Error)]
pub enum ProbeError {
#[error("timeout must be finite, nonnegative and representable")]
InvalidTimeout,
#[error("timed out waiting for path to destination")]
PathTimeout,
#[error("probe size {0} exceeds MTU {1}")]
@@ -261,6 +263,21 @@ pub async fn probe_once(
if size > MTU {
return Err(ProbeError::MtuExceeded(size, MTU));
}
// Validate caller-controlled deadlines before any query, path request or
// destination registration. The receipt wait reserves one final second.
for duration in [proof_wait, path_wait].into_iter().flatten() {
Instant::now()
.checked_add(duration)
.ok_or(ProbeError::InvalidTimeout)?;
}
if let Some(duration) = proof_wait {
let duration = duration
.checked_add(Duration::from_secs(1))
.ok_or(ProbeError::InvalidTimeout)?;
Instant::now()
.checked_add(duration)
.ok_or(ProbeError::InvalidTimeout)?;
}
let has_path = match query(
&transport_tx,
@@ -361,6 +378,13 @@ pub async fn probe_once(
None => default_probe_wait(&transport_tx, dest_hash).await?,
};
let receipt_wait = proof_wait
.checked_add(Duration::from_secs(1))
.ok_or(ProbeError::InvalidTimeout)?;
std::time::Instant::now()
.checked_add(receipt_wait)
.ok_or(ProbeError::InvalidTimeout)?;
// trunc_hash keys `receipt_table`; unique msg_id filters fan-out.
let msg_id = format!(
"probe.{}.{:x}",
@@ -374,7 +398,7 @@ pub async fn probe_once(
destination_hash: dest_hash,
destination_public_key: pubkey,
msg_id: msg_id.clone(),
timeout: Some(proof_wait + Duration::from_secs(1)),
timeout: Some(receipt_wait),
})
.await
.map_err(|_| ProbeError::TransportClosed)?;
@@ -435,7 +459,14 @@ async fn default_probe_wait(
TransportQueryResponse::FloatResult(Some(t)) => t,
_ => rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT,
};
Ok(Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS + first_hop))
let first_hop = checked_probe_timeout(first_hop)?;
let wait = first_hop
.checked_add(Duration::from_secs(DEFAULT_TIMEOUT_SECS as u64))
.ok_or(ProbeError::InvalidTimeout)?;
std::time::Instant::now()
.checked_add(wait)
.ok_or(ProbeError::InvalidTimeout)?;
Ok(wait)
}
pub fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], ProbeError> {
@@ -601,6 +632,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: bytes::Bytes::from(raw),
interface_owner: None,
interface_id: 0,
metrics: Default::default(),
})
@@ -735,6 +767,7 @@ mod tests {
delivery_tx
.send(DestinationEvent::InboundPacket {
raw: bytes::Bytes::from(raw),
interface_owner: None,
interface_id: 0,
metrics: Default::default(),
})
@@ -747,3 +780,44 @@ mod tests {
}
}
}
/// Validate local CLI/API timeout input before starting networking.
pub fn checked_probe_timeout(seconds: f64) -> Result<Duration, ProbeError> {
let duration = Duration::try_from_secs_f64(seconds).map_err(|_| ProbeError::InvalidTimeout)?;
std::time::Instant::now()
.checked_add(duration)
.ok_or(ProbeError::InvalidTimeout)?;
Ok(duration)
}
#[cfg(test)]
mod timeout_tests {
#[tokio::test]
async fn probe_duration_preflight_has_no_transport_side_effects() {
for (proof, path) in [
(Some(std::time::Duration::MAX), None),
(None, Some(std::time::Duration::MAX)),
] {
let (tx, mut rx) = tokio::sync::mpsc::channel(4);
assert!(matches!(
super::probe_once(tx, [0; 16], "probe.test", 1, proof, path, true).await,
Err(super::ProbeError::InvalidTimeout)
));
assert!(rx.try_recv().is_err());
}
}
#[test]
fn probe_timeout_rejects_nonrepresentable_and_preserves_zero() {
for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, f64::MAX] {
assert!(super::checked_probe_timeout(seconds).is_err());
}
assert_eq!(
super::checked_probe_timeout(0.0).unwrap(),
std::time::Duration::ZERO
);
assert_eq!(
super::checked_probe_timeout(1.25).unwrap(),
std::time::Duration::from_millis(1250)
);
}
}
+412 -345
View File
@@ -15,23 +15,35 @@ use tokio::sync::{mpsc, oneshot};
use rns_crypto::sha::truncated_hash;
use rns_identity::destination::Destination;
use rns_identity::identity::Identity;
use rns_transport::messages::{
InterfaceStatRpcEntry, PathTableRpcEntry, RateTableRpcEntry, TransportMessage, TransportQuery,
TransportQueryResponse,
};
use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse};
use crate::remote_management_schema as schema;
use crate::reticulum::InterfaceIfacStats;
use crate::rpc::{self, RpcResponse};
use crate::rpc_server::{TransportStatsSource, stat_entries};
const STATUS_PATH: &str = "/status";
const PATH_PATH: &str = "/path";
/// `identity` must be stable across restarts so clients can cache the dest
/// hash. Empty `allowed_identities` denies all peers, matching Python's
/// `Destination.ALLOW_LIST` semantics.
/// Python registers this destination on `Transport.identity`
/// (Transport.py:367-368), so `rnstatus -R` and `rnpath -R` find it from the
/// transport identity hash. Empty `allowed_identities` denies all peers,
/// matching Python's `Destination.ALLOW_LIST` semantics.
pub async fn start_remote_management(
transport_tx: mpsc::Sender<TransportMessage>,
identity: &Identity,
allowed_identities: Vec<[u8; 16]>,
) -> Result<[u8; 16], String> {
start_remote_management_with_stats(transport_tx, identity, allowed_identities, None, None).await
}
/// As [`start_remote_management`], with the runtime's IFAC records and
/// transport instance, so status replies carry every field of Python's.
pub(crate) async fn start_remote_management_with_stats(
transport_tx: mpsc::Sender<TransportMessage>,
identity: &Identity,
allowed_identities: Vec<[u8; 16]>,
ifac: Option<InterfaceIfacStats>,
transport: Option<TransportStatsSource>,
) -> Result<[u8; 16], String> {
let signing_key = identity
.get_signing_key()
@@ -47,6 +59,8 @@ pub async fn start_remote_management(
app_name,
Some(signing_key),
);
// Python's management Links take the Link default (Link.py:239).
lm.set_resource_strategy(rns_link::link::ResourceStrategy::AcceptNone);
let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes());
let paths_hash: [u8; 16] = truncated_hash(PATH_PATH.as_bytes());
@@ -81,7 +95,7 @@ pub async fn start_remote_management(
}
if path_hash == status_hash {
handle_status(&tx, &data)
handle_status(&tx, &data, ifac.as_ref(), transport.as_ref())
} else if path_hash == paths_hash {
handle_path(&tx, &data)
} else {
@@ -112,17 +126,25 @@ fn peer_allowed(allowed: &[[u8; 16]], peer: &[u8; 16]) -> bool {
allowed.iter().any(|a| a == peer)
}
/// Request: `[include_link_count: bool]`.
/// Response: `[stats_dict]` or `[stats_dict, link_count]`.
fn handle_status(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u8>> {
let include_link_count = parse_status_request(data).unwrap_or(false);
/// Request: `[include_link_count, include_profiling?]`.
/// Response: the control port's stats dict, then the link count when it is
/// asked for, then the profiling results when they are (Transport.py:3325-3337).
/// Rust runs no profiler, so those are nil, as Python's are until its profiler
/// has run (Reticulum.py:1956-1965).
fn handle_status(
tx: &mpsc::Sender<TransportMessage>,
data: &[u8],
ifac: Option<&InterfaceIfacStats>,
transport: Option<&TransportStatsSource>,
) -> Option<Vec<u8>> {
let request = parse_status_request(data)?;
let iface_stats = match blocking_query(tx, TransportQuery::GetInterfaceStats)? {
TransportQueryResponse::InterfaceStats(v) => v,
_ => return None,
};
let link_count = if include_link_count {
let link_count = if request.link_count {
match blocking_query(tx, TransportQuery::GetLinkCount)? {
TransportQueryResponse::IntResult(n) => Some(n.max(0) as u64),
_ => None,
@@ -131,66 +153,139 @@ fn handle_status(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec
None
};
let stats = build_transport_stats(iface_stats);
let bytes = if let Some(lc) = link_count {
rmp_serde::to_vec_named(&(&stats, lc)).ok()?
} else {
rmp_serde::to_vec_named(&(&stats,)).ok()?
};
Some(bytes)
rpc::encode_remote_status(
&stat_entries(iface_stats, ifac),
transport.map(TransportStatsSource::snapshot).as_ref(),
link_count,
request.profiling,
)
.ok()
}
/// Request: `[command: "table"|"rates", destination?: bytes, max_hops?: int]`.
/// Response: list of path-entry or rate-entry dicts.
/// Response: the control port's path or rate table, filtered
/// (Transport.py:3346-3371).
fn handle_path(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u8>> {
let (command, destination, max_hops) = parse_path_request(data)?;
let request = parse_path_request(data)?;
let destination = request.destination.as_ref();
match command.as_str() {
let response = match request.command.as_str() {
"table" => {
let entries = match blocking_query(tx, TransportQuery::GetPathTable)? {
TransportQueryResponse::PathTable(v) => v,
_ => return None,
};
let filtered: Vec<schema::PathEntry> = entries
.into_iter()
.filter(|e| destination.is_none_or(|d| e.hash == d))
.filter(|e| max_hops.is_none_or(|m| e.hops <= m))
.map(path_entry_from_rpc)
.collect();
rmp_serde::to_vec_named(&filtered).ok()
let mut kept = Vec::new();
for e in entries {
if within_hops(request.max_hops.as_ref(), e.hops)? && wanted(destination, &e.hash) {
kept.push(rpc::PathTableEntry {
hash: e.hash.to_vec(),
timestamp: e.timestamp,
via: e.via.map(|v| v.to_vec()),
hops: e.hops,
expires: e.expires,
interface: e.interface,
});
}
}
RpcResponse::PathTable(kept)
}
"rates" => {
let entries = match blocking_query(tx, TransportQuery::GetRateTable)? {
TransportQueryResponse::RateTable(v) => v,
_ => return None,
};
let filtered: Vec<schema::RateEntry> = entries
.into_iter()
.filter(|e| destination.is_none_or(|d| e.hash == d))
.map(rate_entry_from_rpc)
.collect();
rmp_serde::to_vec_named(&filtered).ok()
RpcResponse::RateTable(
entries
.into_iter()
.filter(|e| wanted(destination, &e.hash))
.map(|e| rpc::RateTableEntry {
hash: e.hash.to_vec(),
rate: e.rate,
last: e.last,
rate_violations: e.rate_violations,
blocked_until: e.blocked_until,
timestamps: e.timestamps,
})
.collect(),
)
}
_ => return None,
};
rpc::encode_response(&response).ok()
}
/// Python keeps an entry when a destination argument other than nil equals
/// its hash (Transport.py:3361, :3368), so a hash of another length, or one
/// sent as a string, matches nothing.
fn wanted(destination: Option<&rmpv::Value>, hash: &[u8; 16]) -> bool {
match destination {
None | Some(rmpv::Value::Nil) => true,
Some(rmpv::Value::Binary(wanted)) => wanted.as_slice() == hash,
Some(_) => false,
}
}
/// Python's `hops <= max_hops` (Reticulum.py:1738), or `None` where Python
/// cannot compare the two, which makes its handler raise and send nothing.
fn within_hops(max_hops: Option<&rmpv::Value>, hops: u8) -> Option<bool> {
let Some(max_hops) = max_hops.filter(|max_hops| !max_hops.is_nil()) else {
return Some(true);
};
let hops_f64 = f64::from(hops);
match max_hops {
rmpv::Value::Integer(max) => Some(max.as_i64().is_none_or(|max| i64::from(hops) <= max)),
rmpv::Value::F32(max) => Some(hops_f64 <= f64::from(*max)),
rmpv::Value::F64(max) => Some(hops_f64 <= *max),
rmpv::Value::Boolean(max) => Some(hops <= u8::from(*max)),
_ => None,
}
}
fn parse_status_request(data: &[u8]) -> Option<bool> {
let v: rmpv::Value = rmp_serde::from_slice(data).ok()?;
v.as_array()?.first()?.as_bool()
/// Python's `/status` flags (Transport.py:3329-3335).
#[derive(Debug, PartialEq, Eq)]
struct StatusRequest {
link_count: bool,
profiling: bool,
}
fn parse_path_request(data: &[u8]) -> Option<(String, Option<[u8; 16]>, Option<u8>)> {
/// `None` unless the request is a non-empty list, which Python leaves
/// unanswered (Transport.py:3329).
fn parse_status_request(data: &[u8]) -> Option<StatusRequest> {
let v: rmpv::Value = rmp_serde::from_slice(data).ok()?;
let flags = v.as_array().filter(|flags| !flags.is_empty())?;
Some(StatusRequest {
link_count: python_eq_true(&flags[0]),
profiling: flags.get(1).is_some_and(python_eq_true),
})
}
/// Python's `value == True`, which also holds for 1 and 1.0.
fn python_eq_true(value: &rmpv::Value) -> bool {
match value {
rmpv::Value::Boolean(flag) => *flag,
rmpv::Value::Integer(n) => n.as_u64() == Some(1),
rmpv::Value::F32(n) => *n == 1.0,
rmpv::Value::F64(n) => *n == 1.0,
_ => false,
}
}
/// Python's `/path` arguments, kept as sent (Transport.py:3350-3355).
struct PathRequest {
command: String,
destination: Option<rmpv::Value>,
max_hops: Option<rmpv::Value>,
}
fn parse_path_request(data: &[u8]) -> Option<PathRequest> {
let v: rmpv::Value = rmp_serde::from_slice(data).ok()?;
let args = v.as_array()?;
let command = args.first()?.as_str()?.to_string();
let destination = args
.get(1)
.and_then(|v| v.as_slice())
.and_then(|s| s.try_into().ok());
let max_hops = args.get(2).and_then(|v| v.as_u64()).map(|n| n as u8);
Some((command, destination, max_hops))
Some(PathRequest {
command: args.first()?.as_str()?.to_string(),
destination: args.get(1).cloned(),
max_hops: args.get(2).cloned(),
})
}
/// `block_in_place` requires multi-threaded runtime; single-threaded
@@ -212,98 +307,6 @@ fn blocking_query(
tokio::task::block_in_place(|| resp_rx.blocking_recv().ok())
}
fn build_transport_stats(entries: Vec<InterfaceStatRpcEntry>) -> schema::TransportStats {
let (total_rxb, total_txb) = entries
.iter()
.fold((0u64, 0u64), |(r, t), e| (r + e.rx_bytes, t + e.tx_bytes));
let (total_rxs, total_txs) = entries
.iter()
.fold((0u64, 0u64), |(r, t), e| (r + e.rx_rate, t + e.tx_rate));
let interfaces = entries.into_iter().map(interface_stats_from_rpc).collect();
schema::TransportStats {
interfaces,
rxb: total_rxb,
txb: total_txb,
rxs: total_rxs,
txs: total_txs,
transport_id: None,
network_id: None,
transport_uptime: None,
probe_responder: None,
rss: None,
}
}
fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats {
let mode = mode_from_debug_string(&e.mode);
let ifac_size = if e.ifac_size > 0 {
Some(e.ifac_size as u64)
} else {
None
};
schema::InterfaceStats {
name: e.name.clone(),
short_name: e.name,
hash: None,
type_: "Interface".to_string(),
rxb: e.rx_bytes,
txb: e.tx_bytes,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
held_announces: e.held_announces,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
status: e.online,
mode,
bitrate: Some(e.bitrate),
rxs: e.rx_rate,
txs: e.tx_rate,
announce_queue: e.announce_queue,
clients: e.clients,
blocked_ips: e.blocked_ips,
ifac_signature: None,
ifac_size,
ifac_netname: None,
}
}
fn path_entry_from_rpc(e: PathTableRpcEntry) -> schema::PathEntry {
schema::PathEntry {
hash: e.hash.to_vec(),
timestamp: e.timestamp,
via: e.via.map(|v| v.to_vec()),
hops: e.hops,
expires: e.expires,
interface: e.interface,
}
}
fn rate_entry_from_rpc(e: RateTableRpcEntry) -> schema::RateEntry {
schema::RateEntry {
hash: e.hash.to_vec(),
rate: e.rate,
}
}
/// Maps Debug-formatted InterfaceMode to Python `Interface.MODE_*` integers.
fn mode_from_debug_string(s: &str) -> u8 {
match s {
"Full" => 0x01,
"PointToPoint" => 0x02,
"Access" | "AccessPoint" => 0x03,
"Roaming" => 0x04,
"Boundary" => 0x05,
"Gateway" => 0x06,
_ => 0x01,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -325,164 +328,22 @@ mod tests {
assert!(!peer_allowed(&[peer], &other));
}
#[test]
fn status_response_is_python_compatible_list() {
let stats = schema::TransportStats {
interfaces: vec![schema::InterfaceStats {
name: "TestIf".to_string(),
short_name: "TestIf".to_string(),
hash: None,
type_: "Interface".to_string(),
rxb: 42,
txb: 7,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 0.0,
outgoing_pr_frequency: 0.0,
held_announces: 0,
burst_active: false,
burst_activated: 0.0,
pr_burst_active: false,
pr_burst_activated: 0.0,
status: true,
mode: 0x01,
bitrate: Some(1_000_000),
rxs: 0,
txs: 0,
announce_queue: None,
clients: None,
blocked_ips: None,
ifac_signature: None,
ifac_size: None,
ifac_netname: None,
}],
rxb: 42,
txb: 7,
rxs: 0,
txs: 0,
transport_id: None,
network_id: None,
transport_uptime: None,
probe_responder: None,
rss: None,
};
let encoded = rmp_serde::to_vec_named(&(&stats, 5u64)).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
let arr = decoded.as_array().expect("top level is an array");
assert_eq!(arr.len(), 2, "response is [stats_dict, link_count]");
let stats_map = arr[0].as_map().expect("first element is map");
let has_interfaces = stats_map
.iter()
.any(|(k, _)| k.as_str() == Some("interfaces"));
assert!(has_interfaces, "stats dict has 'interfaces' key");
let interface_map = stats_map
.iter()
.find(|(key, _)| key.as_str() == Some("interfaces"))
.and_then(|(_, value)| value.as_array())
.and_then(|interfaces| interfaces.first())
.and_then(rmpv::Value::as_map)
.expect("first interface is a map");
assert!(
!interface_map
.iter()
.any(|(key, _)| key.as_str() == Some("blocked_ips")),
"absent aggregate count is omitted"
);
assert_eq!(arr[1].as_u64(), Some(5));
}
#[test]
fn status_response_serializes_only_aggregate_blocked_ip_count() {
let stats = schema::InterfaceStats {
name: "Backbone".to_string(),
short_name: "Backbone".to_string(),
hash: None,
type_: "Interface".to_string(),
rxb: 0,
txb: 0,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 0.0,
outgoing_pr_frequency: 0.0,
held_announces: 0,
burst_active: false,
burst_activated: 0.0,
pr_burst_active: false,
pr_burst_activated: 0.0,
status: true,
mode: 0x01,
bitrate: Some(1_000_000),
rxs: 0,
txs: 0,
announce_queue: None,
clients: Some(2),
blocked_ips: Some(3),
ifac_signature: None,
ifac_size: None,
ifac_netname: None,
};
let encoded = rmp_serde::to_vec_named(&stats).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
let map = decoded.as_map().expect("interface stats are a map");
assert_eq!(
map.iter()
.find(|(key, _)| key.as_str() == Some("blocked_ips"))
.and_then(|(_, value)| value.as_u64()),
Some(3)
);
assert!(
!map.iter()
.any(|(key, _)| key.as_str() == Some("blocked_ip_list"))
);
}
#[test]
fn path_response_is_list_of_dicts() {
let entry = schema::PathEntry {
hash: vec![0xAA; 16],
timestamp: 1_700_000_000.0,
via: Some(vec![0xBB; 16]),
hops: 2,
expires: 1_700_001_000.0,
interface: "TestIf".to_string(),
};
let encoded = rmp_serde::to_vec_named(&vec![entry]).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
let arr = decoded.as_array().expect("top-level array");
assert_eq!(arr.len(), 1);
let m = arr[0].as_map().expect("each entry is a map");
let keys: Vec<&str> = m.iter().filter_map(|(k, _)| k.as_str()).collect();
for expected in ["hash", "timestamp", "via", "hops", "expires", "interface"] {
assert!(
keys.contains(&expected),
"missing key {expected} in {keys:?}"
);
}
// hash/via are msgpack bin, not arrays-of-ints
let hash_val = m
.iter()
.find(|(k, _)| k.as_str() == Some("hash"))
.map(|(_, v)| v)
.unwrap();
assert_eq!(
hash_val.as_slice(),
Some(&[0xAA; 16][..]),
"hash is msgpack bin"
);
}
#[test]
fn parse_status_request_decodes_bool_array() {
let flags = |link_count, profiling| {
Some(StatusRequest {
link_count,
profiling,
})
};
let data_true = rmp_serde::to_vec(&(true,)).unwrap();
assert_eq!(parse_status_request(&data_true), Some(true));
assert_eq!(parse_status_request(&data_true), flags(true, false));
let data_false = rmp_serde::to_vec(&(false,)).unwrap();
assert_eq!(parse_status_request(&data_false), Some(false));
assert_eq!(parse_status_request(&data_false), flags(false, false));
let data_both = rmp_serde::to_vec(&(true, true)).unwrap();
assert_eq!(parse_status_request(&data_both), flags(true, true));
let data_empty = rmp_serde::to_vec::<Vec<bool>>(&vec![]).unwrap();
assert_eq!(parse_status_request(&data_empty), None);
@@ -491,10 +352,10 @@ mod tests {
#[test]
fn parse_path_request_table_no_filters() {
let data = rmp_serde::to_vec(&("table",)).unwrap();
let (cmd, dest, max_hops) = parse_path_request(&data).unwrap();
assert_eq!(cmd, "table");
assert_eq!(dest, None);
assert_eq!(max_hops, None);
let request = parse_path_request(&data).unwrap();
assert_eq!(request.command, "table");
assert_eq!(request.destination, None);
assert_eq!(request.max_hops, None);
}
#[test]
@@ -508,51 +369,67 @@ mod tests {
]);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).unwrap();
let (cmd, dest, max_hops) = parse_path_request(&buf).unwrap();
assert_eq!(cmd, "rates");
assert_eq!(dest, Some(dest_bytes));
assert_eq!(max_hops, Some(3));
let request = parse_path_request(&buf).unwrap();
assert_eq!(request.command, "rates");
assert_eq!(
request.destination,
Some(rmpv::Value::Binary(dest_bytes.to_vec()))
);
assert_eq!(request.max_hops, Some(rmpv::Value::from(3u64)));
}
use rns_transport::messages::{InterfaceStatRpcEntry, PathTableRpcEntry, RateTableRpcEntry};
// RNode-like: a default IFAC size is configured, IFAC itself is off.
fn mock_stat_entry() -> InterfaceStatRpcEntry {
InterfaceStatRpcEntry {
id: 1,
name: "MockIf".to_string(),
rx_bytes: 100,
tx_bytes: 200,
rx_rate: 10,
tx_rate: 20,
online: true,
bitrate: 12_000,
mtu: 512,
mode: "Gateway".to_string(),
role: "normal".to_string(),
announce_queue: Some(2),
held_announces: 1,
incoming_announce_frequency: 0.5,
outgoing_announce_frequency: 0.25,
incoming_pr_frequency: 3.0,
outgoing_pr_frequency: 1.5,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: None,
blocked_ips: Some(3),
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 0.02,
ifac_size: 8,
tx_drops: 0,
..Default::default()
}
}
fn spawn_mock_transport() -> mpsc::Sender<TransportMessage> {
spawn_mock_transport_with(vec![mock_stat_entry()])
}
fn spawn_mock_transport_with(
interfaces: Vec<InterfaceStatRpcEntry>,
) -> mpsc::Sender<TransportMessage> {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
if let TransportMessage::Rpc { query, response_tx } = msg {
let resp = match query {
TransportQuery::GetInterfaceStats => {
let stats = vec![InterfaceStatRpcEntry {
id: 1,
name: "MockIf".to_string(),
rx_bytes: 100,
tx_bytes: 200,
rx_rate: 10,
tx_rate: 20,
online: true,
bitrate: 12_000,
mtu: 512,
mode: "Gateway".to_string(),
role: "normal".to_string(),
announce_queue: Some(2),
held_announces: 1,
incoming_announce_frequency: 0.5,
outgoing_announce_frequency: 0.25,
incoming_pr_frequency: 3.0,
outgoing_pr_frequency: 1.5,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: None,
blocked_ips: Some(3),
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 0,
}];
TransportQueryResponse::InterfaceStats(stats)
TransportQueryResponse::InterfaceStats(interfaces.clone())
}
TransportQuery::GetLinkCount => TransportQueryResponse::IntResult(3),
TransportQuery::GetPathTable => {
@@ -594,7 +471,7 @@ mod tests {
let tx = spawn_mock_transport();
let req = rmp_serde::to_vec(&(true,)).unwrap();
let resp = handle_status(&tx, &req).expect("handler produced a response");
let resp = handle_status(&tx, &req, None, None).expect("handler produced a response");
let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap();
let arr = decoded.as_array().expect("response is an array");
@@ -684,17 +561,161 @@ mod tests {
);
}
fn map_get<'a>(map: &'a [(rmpv::Value, rmpv::Value)], key: &str) -> Option<&'a rmpv::Value> {
map.iter()
.find(|(k, _)| k.as_str() == Some(key))
.map(|(_, v)| v)
}
fn remote_interfaces(
stats: &[(rmpv::Value, rmpv::Value)],
) -> Vec<Vec<(rmpv::Value, rmpv::Value)>> {
map_get(stats, "interfaces")
.and_then(rmpv::Value::as_array)
.expect("stats list their interfaces")
.iter()
.map(|interface| interface.as_map().expect("interface is a map").clone())
.collect()
}
/// Python's `/status` answers with `get_interface_stats()` itself
/// (Transport.py:3325-3337), so `rnstatus -R` needs the full 1.5.5 key set.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_status_carries_every_python_155_key() {
let tx = spawn_mock_transport();
let resp = handle_status(&tx, &rmp_serde::to_vec(&(true,)).unwrap(), None, None).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap();
let stats = decoded.as_array().unwrap()[0].as_map().unwrap();
for key in crate::rpc::PYTHON_TOTAL_KEYS {
assert!(map_get(stats, key).is_some(), "missing total {key}");
}
let interface = &remote_interfaces(stats)[0];
for key in crate::rpc::PYTHON_INTERFACE_KEYS {
assert!(map_get(interface, key).is_some(), "missing {key}");
}
assert_eq!(
map_get(interface, "mtu").and_then(rmpv::Value::as_u64),
Some(512),
"rnstatus -R prints the MTU beside the bitrate (rnstatus.py:542-543)"
);
assert!(
map_get(interface, "clients").is_some_and(rmpv::Value::is_nil),
"rnstatus reads clients unguarded (rnstatus.py:489)"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_and_local_stats_map_the_internal_mode_alike() {
let mut internal = mock_stat_entry();
internal.mode = "Internal".to_string();
let tx = spawn_mock_transport_with(vec![internal]);
let resp = handle_status(&tx, &rmp_serde::to_vec(&(false,)).unwrap(), None, None).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap();
let interface = &remote_interfaces(decoded.as_array().unwrap()[0].as_map().unwrap())[0];
assert_eq!(
map_get(interface, "mode").and_then(rmpv::Value::as_u64),
Some(0x07),
"Python MODE_INTERNAL (Interface.py:51), as the local RPC reports it"
);
}
/// `rnpath -R -r` sorts the remote rate table on `last` and reads every
/// rate field (rnpath.py:327-370); Python returns whole rate-table entries
/// (Transport.py:3364-3369, Reticulum.py:1747-1766).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_rates_return_whole_python_rate_entries() {
let tx = spawn_mock_transport();
let resp = handle_path(&tx, &rmp_serde::to_vec(&("rates",)).unwrap()).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap();
let entry = decoded.as_array().unwrap()[0].as_map().unwrap();
assert_eq!(
map_get(entry, "hash").and_then(rmpv::Value::as_slice),
Some(&[0x33; 16][..])
);
assert_eq!(
map_get(entry, "last").and_then(rmpv::Value::as_f64),
Some(1_700_000_000.0)
);
assert_eq!(
map_get(entry, "rate_violations").and_then(rmpv::Value::as_u64),
Some(2)
);
assert_eq!(
map_get(entry, "blocked_until").and_then(rmpv::Value::as_f64),
Some(0.0)
);
let timestamps = map_get(entry, "timestamps")
.and_then(rmpv::Value::as_array)
.expect("timestamps list");
assert_eq!(timestamps[0].as_f64(), Some(1_700_000_000.0));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn handle_status_without_link_count() {
let tx = spawn_mock_transport();
let req = rmp_serde::to_vec(&(false,)).unwrap();
let resp = handle_status(&tx, &req).unwrap();
let resp = handle_status(&tx, &req, None, None).unwrap();
let decoded: rmpv::Value = rmp_serde::from_slice(&resp).unwrap();
let arr = decoded.as_array().unwrap();
assert_eq!(arr.len(), 1, "response is [stats_dict] with no link count");
}
/// The reply after the stats dict, or `None` when no reply is sent.
fn status_reply_tail(
tx: &mpsc::Sender<TransportMessage>,
request: &rmpv::Value,
) -> Option<Vec<rmpv::Value>> {
let mut data = Vec::new();
rmpv::encode::write_value(&mut data, request).unwrap();
let response = handle_status(tx, &data, None, None)?;
let decoded: rmpv::Value = rmp_serde::from_slice(&response).unwrap();
let reply = decoded.as_array().expect("response is a list");
assert!(reply[0].is_map(), "the stats dict comes first");
Some(reply[1..].to_vec())
}
/// Python appends the link count when the first flag `== True`, then the
/// profiling results when the second does, and answers nothing unless the
/// request is a non-empty list (Transport.py:3325-3337). Until a profiler
/// has run, the results are nil (Reticulum.py:1956-1965).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_status_flags_follow_python() {
use rmpv::Value;
let tx = spawn_mock_transport();
let tail = |flags: Vec<Value>| status_reply_tail(&tx, &Value::Array(flags));
let links = Value::from(3);
assert_eq!(tail(vec![true.into()]), Some(vec![links.clone()]));
assert_eq!(tail(vec![false.into()]), Some(vec![]));
assert_eq!(
tail(vec![true.into(), false.into()]),
Some(vec![links.clone()])
);
assert_eq!(
tail(vec![true.into(), true.into()]),
Some(vec![links.clone(), Value::Nil])
);
assert_eq!(
tail(vec![false.into(), true.into()]),
Some(vec![Value::Nil]),
"profiling results take the link count's place when it is not asked for"
);
assert_eq!(
tail(vec![Value::from(1), Value::F64(1.0), true.into()]),
Some(vec![links.clone(), Value::Nil]),
"Python's 1 == True and 1.0 == True hold, and extra flags are ignored"
);
assert_eq!(tail(vec![Value::from(2), Value::from("yes")]), Some(vec![]));
assert_eq!(tail(vec![Value::Nil, true.into()]), Some(vec![Value::Nil]));
assert_eq!(tail(vec![]), None, "an empty request gets no answer");
assert_eq!(status_reply_tail(&tx, &Value::from(true)), None);
assert_eq!(
status_reply_tail(&tx, &Value::Map(vec![(0.into(), true.into())])),
None
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn handle_path_table_end_to_end() {
let tx = spawn_mock_transport();
@@ -741,14 +762,60 @@ mod tests {
assert!(handle_path(&tx, &req).is_none());
}
#[test]
fn mode_mapping_matches_python_constants() {
assert_eq!(mode_from_debug_string("Full"), 0x01);
assert_eq!(mode_from_debug_string("PointToPoint"), 0x02);
assert_eq!(mode_from_debug_string("Access"), 0x03);
assert_eq!(mode_from_debug_string("Roaming"), 0x04);
assert_eq!(mode_from_debug_string("Boundary"), 0x05);
assert_eq!(mode_from_debug_string("Gateway"), 0x06);
assert_eq!(mode_from_debug_string("Unknown"), 0x01);
fn path_request(command: &str, arguments: Vec<rmpv::Value>) -> Vec<u8> {
let mut request = vec![rmpv::Value::from(command)];
request.extend(arguments);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &rmpv::Value::Array(request)).unwrap();
buf
}
fn answered_entries(tx: &mpsc::Sender<TransportMessage>, request: &[u8]) -> Option<usize> {
let response = handle_path(tx, request)?;
let decoded: rmpv::Value = rmp_serde::from_slice(&response).unwrap();
Some(decoded.as_array().expect("response is a list").len())
}
/// Python keeps a path when `hops <= max_hops` compares true and a
/// destination argument equals its hash (Reticulum.py:1738,
/// Transport.py:3361, :3368): a hash of another length, or one sent as a
/// string, matches nothing, and a `max_hops` it cannot compare raises,
/// so no answer is sent.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_path_filters_compare_like_python() {
use rmpv::Value;
let tx = spawn_mock_transport();
let hops = |max_hops: Value| path_request("table", vec![Value::Nil, max_hops]);
assert_eq!(answered_entries(&tx, &hops(Value::from(256))), Some(1));
assert_eq!(answered_entries(&tx, &hops(Value::from(2))), Some(1));
assert_eq!(answered_entries(&tx, &hops(Value::from(1))), Some(0));
assert_eq!(answered_entries(&tx, &hops(Value::from(-1))), Some(0));
assert_eq!(answered_entries(&tx, &hops(Value::F64(1.5))), Some(0));
assert_eq!(answered_entries(&tx, &hops(Value::Nil)), Some(1));
assert_eq!(answered_entries(&tx, &hops(Value::from("two"))), None);
for (command, hash) in [("table", 0x11u8), ("rates", 0x33)] {
let wanted = |destination: Value| {
answered_entries(&tx, &path_request(command, vec![destination]))
};
assert_eq!(wanted(Value::Binary(vec![hash; 16])), Some(1), "{command}");
assert_eq!(wanted(Value::Binary(vec![hash; 8])), Some(0), "{command}");
assert_eq!(
wanted(Value::from(char::from(hash).to_string().repeat(16))),
Some(0),
"{command}"
);
}
assert_eq!(
answered_entries(
&tx,
&path_request(
"rates",
vec![Value::Binary(vec![0x33; 16]), Value::from("two")]
)
),
Some(1),
"rates take no max_hops"
);
}
}
@@ -1,102 +0,0 @@
//! Msgpack wire schema for remote management; field names mirror Python
//! dict keys for `rnstatus -R` / `rnpath -R` interop.
//! See Transport.py:2591-2643, Reticulum.py:1090-1269.
use serde::{Serialize, Serializer};
// rmp_serde's default encodes `Vec<u8>` as array-of-ints; Python expects msgpack bin.
pub(crate) mod bytes_vec {
use super::*;
pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
s.serialize_bytes(bytes)
}
}
pub(crate) mod bytes_opt {
use super::*;
pub fn serialize<S: Serializer>(bytes: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
match bytes {
Some(b) => s.serialize_bytes(b),
None => s.serialize_none(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct InterfaceStats {
pub name: String,
pub short_name: String,
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
pub hash: Option<Vec<u8>>,
#[serde(rename = "type")]
pub type_: String,
pub rxb: u64,
pub txb: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub held_announces: u64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
/// Python field name (not `online`).
pub status: bool,
/// Matches Python `Interface.MODE_*` integers.
pub mode: u8,
#[serde(skip_serializing_if = "Option::is_none")]
pub bitrate: Option<u64>,
pub rxs: u64,
pub txs: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub announce_queue: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub clients: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blocked_ips: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
pub ifac_signature: Option<Vec<u8>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ifac_size: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ifac_netname: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct TransportStats {
pub interfaces: Vec<InterfaceStats>,
pub rxb: u64,
pub txb: u64,
pub rxs: u64,
pub txs: u64,
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
pub transport_id: Option<Vec<u8>>,
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
pub network_id: Option<Vec<u8>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transport_uptime: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
pub probe_responder: Option<Vec<u8>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rss: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PathEntry {
#[serde(with = "bytes_vec")]
pub hash: Vec<u8>,
pub timestamp: f64,
#[serde(with = "bytes_opt")]
pub via: Option<Vec<u8>>,
pub hops: u8,
pub expires: f64,
pub interface: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct RateEntry {
#[serde(with = "bytes_vec")]
pub hash: Vec<u8>,
pub rate: f64,
}
+13
View File
@@ -122,6 +122,19 @@ impl PreparedResourceSource {
.map(|metadata| 3usize.saturating_add(metadata.len()))
.unwrap_or(0);
let request_id = match &purpose {
ResourcePurpose::Request(id) => Some(id.as_slice()),
ResourcePurpose::Ordinary => None,
};
rns_protocol::resource_control::preflight_outbound(
data_size,
options.metadata.as_ref().map(Vec::len),
request_id,
false,
true,
rns_wire::constants::MTU,
)?;
if metadata_wire_size.saturating_add(data_size) <= MAX_EFFICIENT_SIZE {
let mut data = Vec::with_capacity(data_size);
source.read_to_end(&mut data)?;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,170 @@
//! Auto-connecting discovered interfaces as Python's `InterfaceDiscovery`
//! does (Discovery.py:747-870).
use super::*;
use rns_transport::discovery::app_data::DiscoveryInfo;
fn config_dir(tag: &str, config: &str) -> PathBuf {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!(
"rns-autoconnect-{tag}-{}-{nonce}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config"), config).unwrap();
dir
}
async fn start(dir: &Path) -> ReticulumHandle {
init(
Some(dir.to_str().unwrap()),
None,
ShutdownSignal::new(),
Arc::new(AtomicBool::new(true)),
)
.await
.unwrap()
}
async fn unused_port() -> u16 {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
listener.local_addr().unwrap().port()
}
/// A Backbone interface a Python 1.5.5 transport node announced.
fn discovered(name: &str, host: &str, port: u16) -> DiscoveredInterface {
DiscoveredInterface {
info: DiscoveryInfo {
name: name.into(),
transport_id: rns_crypto::sha::truncated_hash(name.as_bytes()),
impl_name: Some("RNS".into()),
impl_version: Some("1.5.5".into()),
interface_type: "BackboneInterface".into(),
transport_enabled: true,
reachable_on: Some(host.into()),
port: Some(port),
..Default::default()
},
network_id: [0x5a; 16],
hops: 1,
stamp_value: 16,
stamp: Vec::new(),
discovered: 0,
last_heard: 0,
heard_count: 1,
status: None,
}
}
async fn autoconnected(handle: &ReticulumHandle) -> usize {
handle.discovery.autoconnected.lock().await.len()
}
fn hub_config(uplink_port: u16) -> String {
format!(
"[reticulum]\n share_instance = No\n enable_transport = Yes\n autoconnect_discovered_interfaces = 4\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = localhost\n target_port = {uplink_port}\n"
)
}
/// Python never auto-connects to an onion address, nor to the literal
/// addresses 127.0.0.1 and 0.0.0.0 (Discovery.py:814-825, :982).
#[tokio::test]
async fn autoconnect_refuses_onion_and_local_addresses() {
let port = unused_port().await;
let dir = config_dir("refused", &hub_config(unused_port().await));
let handle = start(&dir).await;
for host in [
"hiddenservicexyz.onion",
"HiddenServiceXYZ.ONION",
"127.0.0.1",
"0.0.0.0",
] {
maybe_autoconnect_discovered(&handle, discovered(host, host, port)).await;
}
assert_eq!(autoconnected(&handle).await, 0);
maybe_autoconnect_discovered(&handle, discovered("control", "localhost", port)).await;
assert_eq!(
autoconnected(&handle).await,
1,
"control: a hostname connects"
);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
/// Python connects once per endpoint, and never beside a client interface
/// already aimed at it (`interface_exists`, Discovery.py:747-770), however
/// many announcers name the endpoint.
#[tokio::test]
async fn autoconnect_connects_once_per_endpoint() {
let (uplink_port, port) = (unused_port().await, unused_port().await);
let dir = config_dir("endpoints", &hub_config(uplink_port));
let handle = start(&dir).await;
maybe_autoconnect_discovered(&handle, discovered("the uplink", "localhost", uplink_port)).await;
assert_eq!(
autoconnected(&handle).await,
0,
"the configured client already reaches it"
);
for name in ["first", "second", "third"] {
maybe_autoconnect_discovered(&handle, discovered(name, "localhost", port)).await;
}
assert_eq!(autoconnected(&handle).await, 1);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
/// Python names the network that announced an auto-connected interface in
/// its stats, as the announcer's identity hash in hex (Discovery.py:865,
/// Reticulum.py:1611-1612), and `rnstatus` prints it (rnstatus.py:525-526).
#[tokio::test]
async fn an_autoconnected_interface_names_its_source() {
let (uplink_port, port) = (unused_port().await, unused_port().await);
let dir = config_dir("source", &hub_config(uplink_port));
let handle = start(&dir).await;
maybe_autoconnect_discovered(&handle, discovered("sourced", "localhost", port)).await;
let id = *handle
.discovery
.autoconnected
.lock()
.await
.values()
.next()
.expect("the interface auto-connected");
let Some(TransportQueryResponse::InterfaceStats(entries)) = handle
.query_transport(TransportQuery::GetInterfaceStats)
.await
else {
panic!("no interface stats");
};
let records = InterfaceIfacStats(handle.interface_controls.clone());
let stats = crate::rpc_server::stat_entries(entries, Some(&records));
let source = |name: &str| {
stats
.iter()
.find(|entry| entry.name == name)
.unwrap_or_else(|| panic!("{name} is listed"))
.autoconnect_source
.clone()
};
let autoconnected_name = stats
.iter()
.find(|entry| entry.id == id)
.expect("the auto-connected interface is listed")
.name
.clone();
assert_eq!(source(&autoconnected_name), Some(hex::encode([0x5a; 16])));
assert_eq!(source("Uplink"), None);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
@@ -0,0 +1,67 @@
//! Runtime wiring of Python-shaped interface stats and remote management.
use super::*;
fn config_dir(tag: &str, config: &str) -> PathBuf {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("rns-stats-{tag}-{}-{nonce}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config"), config).unwrap();
dir
}
async fn is_local_destination(handle: &ReticulumHandle, dest: [u8; 16]) -> bool {
matches!(
handle
.query_transport(TransportQuery::GetNextHop { dest })
.await,
Some(TransportQueryResponse::HashResult(Some(_)))
)
}
/// `rnstatus -R` and `rnpath -R` take the remote's transport identity hash
/// and derive `rnstransport.remote.management` from it (rnstatus.py:367-369),
/// because Python registers that destination on `Transport.identity`
/// (Transport.py:367-368).
#[tokio::test]
async fn remote_management_answers_on_the_transport_identity() {
let dir = config_dir(
"remote-management",
"[reticulum]\n\
share_instance = No\n\
enable_transport = Yes\n\
enable_remote_management = Yes\n\
remote_management_allowed = 0123456789abcdef0123456789abcdef\n\
\n\
[interfaces]\n",
);
let handle = init(
Some(dir.to_str().unwrap()),
None,
ShutdownSignal::new(),
Arc::new(AtomicBool::new(true)),
)
.await
.unwrap();
let expected = rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.remote.management",
Some(&handle.transport_identity.hash),
);
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
let mut registered = false;
while !registered && tokio::time::Instant::now() < deadline {
registered = is_local_destination(&handle, expected).await;
if !registered {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(&dir);
assert!(
registered,
"the management destination is keyed on the transport identity"
);
}
File diff suppressed because it is too large. Load diff
+52 -22
View File
@@ -57,6 +57,8 @@ pub fn default_rncp_app_name() -> &'static str {
#[derive(Debug, thiserror::Error)]
pub enum RncpError {
#[error("link request admission failed: {0}")]
RequestDispatch(#[from] rns_transport::link_messages::LinkRequestDispatchError),
#[error("transport channel unavailable")]
TransportUnavailable,
#[error("timed out waiting for {0}")]
@@ -538,21 +540,27 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
);
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: link_req_pkt,
destination_hash: dest_hash,
}))
.await
.map_err(|_| RncpError::TransportUnavailable)?;
tokio::time::timeout(
remaining(deadline),
rns_transport::link_messages::dispatch_link_request(
&transport_tx,
OutboundRequest {
raw: link_req_pkt,
destination_hash: dest_hash,
},
),
)
.await
.map_err(|_| RncpError::Timeout("link request admission"))??;
let (rtt_data, attached_interface) =
let (rtt_data, attached_interface, interface_owner) =
wait_for_valid_rncp_proof(&mut lpkt_rx, &mut link, &pubkey, deadline).await?;
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
&transport_tx,
link_id,
attached_interface,
interface_owner,
LinkEndpointRole::Initiator,
)
.await
@@ -629,6 +637,7 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
lpkt_rx: &mut lpkt_rx,
endpoint_lifecycle_rx: &mut endpoint_lifecycle_rx,
attached_interface,
interface_owner,
progress_tx: progress_tx.clone(),
progress_base: completed_parts as f32 / total_parts_nonzero as f32,
progress_span: segment_parts as f32 / total_parts_nonzero as f32,
@@ -700,6 +709,7 @@ struct OutboundDrive<'a> {
lpkt_rx: &'a mut mpsc::Receiver<DestinationEvent>,
endpoint_lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
progress_tx: Option<mpsc::Sender<f32>>,
progress_base: f32,
progress_span: f32,
@@ -715,6 +725,7 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
lpkt_rx,
endpoint_lifecycle_rx,
attached_interface,
interface_owner,
progress_tx,
progress_base,
progress_span,
@@ -765,12 +776,15 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
};
let DestinationEvent::InboundPacket {
raw, interface_id, ..
raw,
interface_id,
interface_owner: event_owner,
..
} = ev
else {
continue;
};
if interface_id != attached_interface {
if interface_id != attached_interface || event_owner != interface_owner {
continue;
}
let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) {
@@ -981,7 +995,14 @@ async fn wait_for_valid_rncp_proof(
link: &mut Link,
public_key: &[u8; 64],
deadline: Instant,
) -> Result<(Vec<u8>, InterfaceId), RncpError> {
) -> Result<
(
Vec<u8>,
InterfaceId,
Option<rns_transport::messages::InterfaceOwnerId>,
),
RncpError,
> {
let identity_ed25519_pub: [u8; 32] = public_key[32..64]
.try_into()
.map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?;
@@ -1001,7 +1022,7 @@ async fn wait_for_valid_rncp_proof(
RncpError::HandshakeFailed("channel closed".into())
}
})?;
Ok((proof.rtt_data, proof.interface_id))
Ok((proof.rtt_data, proof.interface_id, proof.interface_owner))
}
fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes {
@@ -1131,21 +1152,27 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
);
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: link_req_pkt,
destination_hash: dest_hash,
}))
.await
.map_err(|_| RncpError::TransportUnavailable)?;
tokio::time::timeout(
remaining(deadline),
rns_transport::link_messages::dispatch_link_request(
&transport_tx,
OutboundRequest {
raw: link_req_pkt,
destination_hash: dest_hash,
},
),
)
.await
.map_err(|_| RncpError::Timeout("link request admission"))??;
let (rtt_data, attached_interface) =
let (rtt_data, attached_interface, interface_owner) =
wait_for_valid_rncp_proof(&mut lpkt_rx, &mut link, &pubkey, deadline).await?;
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
&transport_tx,
link_id,
attached_interface,
interface_owner,
LinkEndpointRole::Initiator,
)
.await
@@ -1222,12 +1249,15 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
};
let DestinationEvent::InboundPacket {
raw, interface_id, ..
raw,
interface_id,
interface_owner: event_owner,
..
} = ev
else {
continue;
};
if interface_id != attached_interface {
if interface_id != attached_interface || event_owner != interface_owner {
continue;
}
let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) {
+26 -9
View File
@@ -50,6 +50,8 @@ const SIGKILL_NUM: i32 = 9;
#[derive(Debug, thiserror::Error)]
pub enum RnshError {
#[error("link request admission failed: {0}")]
RequestDispatch(#[from] rns_transport::link_messages::LinkRequestDispatchError),
#[error("transport channel unavailable")]
TransportUnavailable,
#[error("timed out waiting for {0}")]
@@ -331,13 +333,18 @@ pub async fn rnsh_client_execute(
);
let link_req_pkt = build_link_request_packet(destination_hash, &request_data);
transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: link_req_pkt,
destination_hash,
}))
.await
.map_err(|_| RnshError::TransportUnavailable)?;
tokio::time::timeout(
remaining(deadline),
rns_transport::link_messages::dispatch_link_request(
&transport_tx,
OutboundRequest {
raw: link_req_pkt,
destination_hash,
},
),
)
.await
.map_err(|_| RnshError::Timeout("link request admission"))??;
let identity_ed25519_pub: [u8; 32] = pubkey[32..64]
.try_into()
@@ -353,11 +360,13 @@ pub async fn rnsh_client_execute(
)
.await?;
let attached_interface = proof.interface_id;
let interface_owner = proof.interface_owner;
let rtt_data = proof.rtt_data;
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
&transport_tx,
link_id,
attached_interface,
interface_owner,
LinkEndpointRole::Initiator,
)
.await
@@ -365,6 +374,7 @@ pub async fn rnsh_client_execute(
registration.endpoint_bound();
let mut endpoint = ClientLinkEndpoint {
attached_interface,
interface_owner,
lifecycle_rx: &mut endpoint_lifecycle_rx,
packet_rx: &mut lpkt_rx,
};
@@ -513,6 +523,7 @@ pub async fn rnsh_client_execute(
struct ClientLinkEndpoint<'a> {
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
packet_rx: &'a mut mpsc::Receiver<DestinationEvent>,
}
@@ -627,6 +638,7 @@ async fn run_client_io_loop(
pending_messages,
event,
endpoint.attached_interface,
endpoint.interface_owner,
).await?;
}
terminal = endpoint.lifecycle_rx.recv() => {
@@ -1687,6 +1699,7 @@ async fn receive_client_messages(
pending_messages,
event,
endpoint.attached_interface,
endpoint.interface_owner,
)
.await
}
@@ -1698,14 +1711,18 @@ async fn process_client_destination_event(
pending_messages: &mut VecDeque<RnshMessage>,
event: DestinationEvent,
attached_interface: InterfaceId,
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
) -> Result<bool, RnshError> {
let DestinationEvent::InboundPacket {
raw, interface_id, ..
raw,
interface_id,
interface_owner: event_owner,
..
} = event
else {
return Ok(false);
};
if interface_id != attached_interface {
if interface_id != attached_interface || event_owner != interface_owner {
return Ok(false);
}
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
+658 -83
View File
@@ -141,7 +141,7 @@ pub struct PathTableEntry {
pub interface: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct InterfaceStatEntry {
pub id: u64,
pub name: String,
@@ -177,8 +177,48 @@ pub struct InterfaceStatEntry {
pub announce_rate_grace: Option<u32>,
pub announce_rate_penalty: Option<f64>,
pub announce_cap: f64,
pub ifac_size: usize,
/// Python's IFAC fields, all `None` for an interface without IFAC.
#[serde(default)]
pub ifac_signature: Option<Vec<u8>>,
#[serde(default)]
pub ifac_size: Option<usize>,
#[serde(default)]
pub ifac_netname: Option<String>,
pub tx_drops: u64,
#[serde(default)]
pub tx_dropped_bytes: u64,
/// Python `arxc`/`atxc`/`prxc`/`ptxc`.
#[serde(default)]
pub announces_received: u64,
#[serde(default)]
pub announces_sent: u64,
#[serde(default)]
pub path_requests_received: u64,
#[serde(default)]
pub path_requests_sent: u64,
#[serde(default)]
pub protocol_violations: u64,
#[serde(default)]
pub ifac_violations: u64,
#[serde(default)]
pub packet_filter_hits: u64,
/// Name of the listener that accepted this interface.
#[serde(default)]
pub parent_interface_name: Option<String>,
/// The network identity, in hex, that announced an auto-connected
/// interface (Python `autoconnect_source`).
#[serde(default)]
pub autoconnect_source: Option<String>,
}
/// What a transport instance adds to its interface stats
/// (Reticulum.py:1700-1705).
#[derive(Debug, Clone, Copy)]
pub(crate) struct TransportStats {
pub(crate) transport_id: [u8; 16],
pub(crate) network_id: Option<[u8; 16]>,
pub(crate) uptime: f64,
pub(crate) probe_responder: Option<[u8; 16]>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -511,81 +551,7 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
})
.collect(),
),
RpcResponse::InterfaceStats(entries) => {
let interfaces = entries
.iter()
.map(|e| {
let mut fields = vec![
("id", PyValue::Int(i128::from(e.id))),
("name", PyValue::String(e.name.clone())),
("short_name", PyValue::String(e.name.clone())),
("type", PyValue::String(e.role.clone())),
("rxb", PyValue::Int(i128::from(e.rx_bytes))),
("txb", PyValue::Int(i128::from(e.tx_bytes))),
("rxs", PyValue::Int(i128::from(e.rx_rate))),
("txs", PyValue::Int(i128::from(e.tx_rate))),
("status", PyValue::Bool(e.online)),
(
"mode",
PyValue::Int(i128::from(mode_to_python_int(&e.mode))),
),
("bitrate", PyValue::Int(i128::from(e.bitrate))),
("mtu", PyValue::Int(i128::from(e.mtu))),
("ifac_size", PyValue::Int(i128::from(e.ifac_size as u64))),
(
"announce_queue",
e.announce_queue
.map(|v| PyValue::Int(i128::from(v)))
.unwrap_or(PyValue::None),
),
("held_announces", PyValue::Int(i128::from(e.held_announces))),
(
"incoming_announce_frequency",
PyValue::Float(e.incoming_announce_frequency),
),
(
"outgoing_announce_frequency",
PyValue::Float(e.outgoing_announce_frequency),
),
(
"incoming_pr_frequency",
PyValue::Float(e.incoming_pr_frequency),
),
(
"outgoing_pr_frequency",
PyValue::Float(e.outgoing_pr_frequency),
),
("burst_active", PyValue::Bool(e.burst_active)),
("burst_activated", PyValue::Float(e.burst_activated)),
("pr_burst_active", PyValue::Bool(e.pr_burst_active)),
("pr_burst_activated", PyValue::Float(e.pr_burst_activated)),
(
"clients",
e.clients
.map(|v| PyValue::Int(i128::from(v)))
.unwrap_or(PyValue::None),
),
("tx_drops", PyValue::Int(i128::from(e.tx_drops))),
];
if let Some(blocked_ips) = e.blocked_ips {
fields.push(("blocked_ips", PyValue::Int(i128::from(blocked_ips))));
}
py_dict(fields)
})
.collect();
let rxb = entries.iter().map(|e| e.rx_bytes).sum::<u64>();
let txb = entries.iter().map(|e| e.tx_bytes).sum::<u64>();
let rxs = entries.iter().map(|e| e.rx_rate).sum::<u64>();
let txs = entries.iter().map(|e| e.tx_rate).sum::<u64>();
py_dict(vec![
("interfaces", PyValue::List(interfaces)),
("rxb", PyValue::Int(i128::from(rxb))),
("txb", PyValue::Int(i128::from(txb))),
("rxs", PyValue::Int(i128::from(rxs))),
("txs", PyValue::Int(i128::from(txs))),
("rss", PyValue::None),
])
}
RpcResponse::InterfaceStats(entries) => interface_stats_value(entries, None),
RpcResponse::RateTable(entries) => PyValue::List(
entries
.iter()
@@ -649,6 +615,215 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
}
}
pub(crate) fn encode_interface_stats(
entries: &[InterfaceStatEntry],
transport: Option<&TransportStats>,
) -> Result<Vec<u8>, RpcError> {
encode_umsgpack(&interface_stats_value(entries, transport))
}
/// Remote management's `/status` answer: `[stats]`, then the link count and
/// nil profiling results when asked for, in that order (Transport.py:3325-3337).
pub(crate) fn encode_remote_status(
entries: &[InterfaceStatEntry],
transport: Option<&TransportStats>,
link_count: Option<u64>,
profiling: bool,
) -> Result<Vec<u8>, RpcError> {
let mut response = vec![interface_stats_value(entries, transport)];
if let Some(link_count) = link_count {
response.push(PyValue::Int(i128::from(link_count)));
}
if profiling {
response.push(PyValue::None);
}
encode_umsgpack(&PyValue::List(response))
}
/// Python 1.5.5 `Reticulum.get_interface_stats()` (Reticulum.py:1494-1716)
/// for the control port and remote management alike. Rust keeps no inbound
/// queues, packet rates, announce or path request byte counters, transmit
/// buffer or gravity, so those keys carry Python's idle values.
fn interface_stats_value(
entries: &[InterfaceStatEntry],
transport: Option<&TransportStats>,
) -> PyValue {
let sum = |select: fn(&InterfaceStatEntry) -> u64| {
entries.iter().map(select).fold(0u64, u64::saturating_add)
};
let mut stats = vec![
(
"interfaces",
PyValue::List(entries.iter().map(interface_stat_value).collect()),
),
("rxb", PyValue::Int(i128::from(sum(|e| e.rx_bytes)))),
("txb", PyValue::Int(i128::from(sum(|e| e.tx_bytes)))),
("rxs", PyValue::Int(i128::from(sum(|e| e.rx_rate)))),
("txs", PyValue::Int(i128::from(sum(|e| e.tx_rate)))),
];
for key in [
"arxb",
"atxb",
"arxs",
"atxs",
"arxf",
"atxf",
"prxb",
"ptxb",
"prxs",
"ptxs",
"prxf",
"ptxf",
"rxpps",
"txpps",
"rxqt",
"rxqd",
"rxqa",
"rxqp",
"rxqil",
"rxqtd",
"rxqdd",
"rxqad",
"rxqpd",
"rxqild",
"tqpressure",
"dqpressure",
"aqpressure",
"pqpressure",
"ilqpressure",
] {
stats.push((key, PyValue::Int(0)));
}
stats.push(("txq", PyValue::None));
if let Some(transport) = transport {
let hash = |hash: Option<[u8; 16]>| {
hash.map(|hash| PyValue::Bytes(hash.to_vec()))
.unwrap_or(PyValue::None)
};
stats.push((
"transport_id",
PyValue::Bytes(transport.transport_id.to_vec()),
));
stats.push(("network_id", hash(transport.network_id)));
stats.push(("transport_uptime", PyValue::Float(transport.uptime)));
stats.push(("probe_responder", hash(transport.probe_responder)));
}
stats.push(("rss", PyValue::None));
py_dict(stats)
}
fn interface_stat_value(e: &InterfaceStatEntry) -> PyValue {
let int = |value: u64| PyValue::Int(i128::from(value));
let optional = |value: Option<PyValue>| value.unwrap_or(PyValue::None);
let mut fields = vec![
("id", int(e.id)),
("name", PyValue::String(e.name.clone())),
("short_name", PyValue::String(e.name.clone())),
(
"hash",
PyValue::Bytes(rns_crypto::sha::sha256(e.name.as_bytes()).to_vec()),
),
("type", PyValue::String(e.role.clone())),
("rxb", int(e.rx_bytes)),
("txb", int(e.tx_bytes)),
("rxs", int(e.rx_rate)),
("txs", int(e.tx_rate)),
("arxb", int(0)),
("atxb", int(0)),
("arxs", int(0)),
("atxs", int(0)),
("prxb", int(0)),
("ptxb", int(0)),
("prxs", int(0)),
("ptxs", int(0)),
("arxc", int(e.announces_received)),
("atxc", int(e.announces_sent)),
("prxc", int(e.path_requests_received)),
("ptxc", int(e.path_requests_sent)),
("status", PyValue::Bool(e.online)),
(
"mode",
PyValue::Int(i128::from(python_interface_mode(&e.mode))),
),
("bitrate", int(e.bitrate)),
("mtu", PyValue::Int(i128::from(e.mtu))),
(
"ifac_signature",
optional(e.ifac_signature.clone().map(PyValue::Bytes)),
),
(
"ifac_size",
optional(e.ifac_size.map(|v| PyValue::Int(i128::from(v as u64)))),
),
(
"ifac_netname",
optional(e.ifac_netname.clone().map(PyValue::String)),
),
(
"autoconnect_source",
optional(e.autoconnect_source.clone().map(PyValue::String)),
),
("announce_queue", optional(e.announce_queue.map(int))),
("held_announces", int(e.held_announces)),
(
"incoming_announce_frequency",
PyValue::Float(e.incoming_announce_frequency),
),
(
"outgoing_announce_frequency",
PyValue::Float(e.outgoing_announce_frequency),
),
(
"incoming_pr_frequency",
PyValue::Float(e.incoming_pr_frequency),
),
(
"outgoing_pr_frequency",
PyValue::Float(e.outgoing_pr_frequency),
),
(
"announce_rate_target",
optional(e.announce_rate_target.map(PyValue::Float)),
),
(
"announce_rate_penalty",
optional(e.announce_rate_penalty.map(PyValue::Float)),
),
(
"announce_rate_grace",
optional(e.announce_rate_grace.map(|v| PyValue::Int(i128::from(v)))),
),
("burst_active", PyValue::Bool(e.burst_active)),
("burst_activated", PyValue::Float(e.burst_activated)),
("burst_count", PyValue::None),
("pr_burst_active", PyValue::Bool(e.pr_burst_active)),
("pr_burst_activated", PyValue::Float(e.pr_burst_activated)),
("pr_burst_count", PyValue::None),
("clients", optional(e.clients.map(int))),
("txdrp", int(e.tx_drops)),
("txdrb", int(e.tx_dropped_bytes)),
("txstalled", PyValue::Bool(false)),
("txbuffered", int(0)),
("tx_drops", int(e.tx_drops)),
("gravity", int(0)),
("announces_to_internal", PyValue::None),
("protocol_violations", int(e.protocol_violations)),
("ifac_violations", int(e.ifac_violations)),
("packet_filter_hits", int(e.packet_filter_hits)),
];
if let Some(parent) = &e.parent_interface_name {
fields.push(("parent_interface_name", PyValue::String(parent.clone())));
fields.push((
"parent_interface_hash",
PyValue::Bytes(rns_crypto::sha::sha256(parent.as_bytes()).to_vec()),
));
}
if let Some(blocked_ips) = e.blocked_ips {
fields.push(("blocked_ips", int(blocked_ips)));
}
py_dict(fields)
}
fn py_value_to_response(value: &PyValue) -> Result<RpcResponse, RpcError> {
match value {
PyValue::Dict(entries) if dict_get(entries, "interfaces").is_some() => {
@@ -854,11 +1029,32 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatEntry>, Rpc
announce_rate_grace: dict_get(m, "announce_rate_grace").and_then(py_u32),
announce_rate_penalty: dict_get(m, "announce_rate_penalty").and_then(py_f64),
announce_cap: dict_get(m, "announce_cap").and_then(py_f64).unwrap_or(0.0),
ifac_signature: match dict_get(m, "ifac_signature") {
Some(PyValue::Bytes(v)) => Some(v.clone()),
_ => None,
},
ifac_size: dict_get(m, "ifac_size")
.and_then(py_u64)
.map(|v| v as usize)
.map(|v| v as usize),
ifac_netname: dict_get(m, "ifac_netname").and_then(py_string),
tx_drops: dict_get(m, "txdrp")
.or_else(|| dict_get(m, "tx_drops"))
.and_then(py_u64)
.unwrap_or(0),
tx_drops: dict_get(m, "tx_drops").and_then(py_u64).unwrap_or(0),
tx_dropped_bytes: dict_get(m, "txdrb").and_then(py_u64).unwrap_or(0),
announces_received: dict_get(m, "arxc").and_then(py_u64).unwrap_or(0),
announces_sent: dict_get(m, "atxc").and_then(py_u64).unwrap_or(0),
path_requests_received: dict_get(m, "prxc").and_then(py_u64).unwrap_or(0),
path_requests_sent: dict_get(m, "ptxc").and_then(py_u64).unwrap_or(0),
protocol_violations: dict_get(m, "protocol_violations")
.and_then(py_u64)
.unwrap_or(0),
ifac_violations: dict_get(m, "ifac_violations").and_then(py_u64).unwrap_or(0),
packet_filter_hits: dict_get(m, "packet_filter_hits")
.and_then(py_u64)
.unwrap_or(0),
parent_interface_name: dict_get(m, "parent_interface_name").and_then(py_string),
autoconnect_source: dict_get(m, "autoconnect_source").and_then(py_string),
})
})
.collect()
@@ -1032,7 +1228,8 @@ fn i64_from_i128(v: i128) -> Result<i64, RpcError> {
i64::try_from(v).map_err(|_| RpcError::Deserialize(format!("integer out of range: {v}")))
}
fn mode_to_python_int(mode: &str) -> u8 {
/// Python `Interface.MODE_*` (Interface.py:45-51) for a Debug-formatted mode.
fn python_interface_mode(mode: &str) -> u8 {
match mode {
"Full" => 0x01,
"PointToPoint" => 0x02,
@@ -1040,7 +1237,6 @@ fn mode_to_python_int(mode: &str) -> u8 {
"Roaming" => 0x04,
"Boundary" => 0x05,
"Gateway" => 0x06,
// Python 1.3.8 MODE_INTERNAL (Interface.py:51).
"Internal" => 0x07,
_ => 0x01,
}
@@ -1696,6 +1892,114 @@ pub enum RpcError {
Io(#[from] std::io::Error),
}
/// Keys Python 1.5.5 `get_interface_stats()` gives every interface
/// (Reticulum.py:1501-1663); `rnstatus` indexes most of them unguarded.
#[cfg(test)]
pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
"clients",
"bitrate",
"rxs",
"txs",
"arxs",
"atxs",
"prxs",
"ptxs",
"ifac_signature",
"ifac_size",
"ifac_netname",
"autoconnect_source",
"name",
"short_name",
"hash",
"type",
"mtu",
"rxb",
"txb",
"arxb",
"atxb",
"arxc",
"atxc",
"prxb",
"ptxb",
"prxc",
"ptxc",
"txdrp",
"txdrb",
"txstalled",
"txbuffered",
"incoming_announce_frequency",
"outgoing_announce_frequency",
"incoming_pr_frequency",
"outgoing_pr_frequency",
"announce_rate_target",
"announce_rate_penalty",
"announce_rate_grace",
"held_announces",
"burst_active",
"burst_activated",
"burst_count",
"pr_burst_active",
"pr_burst_activated",
"pr_burst_count",
"status",
"mode",
"gravity",
"announces_to_internal",
"protocol_violations",
"ifac_violations",
"packet_filter_hits",
];
/// Totals in every Python 1.5.5 stats dict (Reticulum.py:1673-1714).
#[cfg(test)]
pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
"interfaces",
"rxb",
"txb",
"rxs",
"txs",
"arxb",
"atxb",
"arxs",
"atxs",
"arxf",
"atxf",
"prxb",
"ptxb",
"prxs",
"ptxs",
"prxf",
"ptxf",
"rxpps",
"txpps",
"rxqt",
"rxqd",
"rxqa",
"rxqp",
"rxqil",
"rxqtd",
"rxqdd",
"rxqad",
"rxqpd",
"rxqild",
"tqpressure",
"dqpressure",
"aqpressure",
"pqpressure",
"ilqpressure",
"txq",
"rss",
];
/// Added only by a transport instance (Reticulum.py:1700-1705).
#[cfg(test)]
pub(crate) const PYTHON_TRANSPORT_KEYS: &[&str] = &[
"transport_id",
"network_id",
"transport_uptime",
"probe_responder",
];
#[cfg(test)]
mod tests {
use super::*;
@@ -1786,11 +2090,280 @@ mod tests {
announce_rate_grace: Some(5),
announce_rate_penalty: Some(30.0),
announce_cap: 0.02,
ifac_size: 0,
ifac_signature: None,
ifac_size: None,
ifac_netname: None,
tx_drops: 1,
..Default::default()
}
}
fn stats_dict(encoded: &[u8]) -> Vec<(PyDictKey, PyValue)> {
let PyValue::Dict(stats) = decode_umsgpack(encoded).unwrap() else {
panic!("interface stats are a dict");
};
stats
}
fn interface_dicts(stats: &[(PyDictKey, PyValue)]) -> Vec<Vec<(PyDictKey, PyValue)>> {
let Some(PyValue::List(interfaces)) = dict_get(stats, "interfaces") else {
panic!("interface stats list their interfaces");
};
interfaces
.iter()
.map(|interface| as_dict(interface).unwrap().to_vec())
.collect()
}
#[test]
fn interface_stats_carry_every_python_155_key() {
let encoded =
encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])).unwrap();
let stats = stats_dict(&encoded);
for key in PYTHON_TOTAL_KEYS {
assert!(dict_get(&stats, key).is_some(), "missing total {key}");
}
for key in PYTHON_TRANSPORT_KEYS {
assert!(
dict_get(&stats, key).is_none(),
"{key} belongs only to a transport instance"
);
}
let interface = &interface_dicts(&stats)[0];
for key in PYTHON_INTERFACE_KEYS {
assert!(dict_get(interface, key).is_some(), "missing {key}");
}
assert_eq!(dict_get(interface, "txdrp"), Some(&PyValue::Int(1)));
assert_eq!(
dict_get(interface, "txstalled"),
Some(&PyValue::Bool(false))
);
assert_eq!(dict_get(interface, "mtu"), Some(&PyValue::Int(500)));
assert_eq!(dict_get(&stats, "txq"), Some(&PyValue::None));
}
#[test]
fn interface_stats_without_clients_report_python_none() {
let mut entry = interface_stat_entry();
entry.clients = None;
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![entry])).unwrap();
let interface = &interface_dicts(&stats_dict(&encoded))[0];
assert_eq!(
dict_get(interface, "clients"),
Some(&PyValue::None),
"rnstatus reads clients unguarded (rnstatus.py:489)"
);
}
#[test]
fn interface_stats_report_rust_counters_under_python_keys() {
let mut entry = interface_stat_entry();
entry.announces_received = 11;
entry.announces_sent = 12;
entry.path_requests_received = 13;
entry.path_requests_sent = 14;
entry.protocol_violations = 15;
entry.ifac_violations = 16;
entry.packet_filter_hits = 17;
entry.tx_dropped_bytes = 18;
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![entry])).unwrap();
let interface = &interface_dicts(&stats_dict(&encoded))[0];
for (key, value) in [
("arxc", 11),
("atxc", 12),
("prxc", 13),
("ptxc", 14),
("protocol_violations", 15),
("ifac_violations", 16),
("packet_filter_hits", 17),
("txdrb", 18),
] {
assert_eq!(
dict_get(interface, key),
Some(&PyValue::Int(value)),
"{key}"
);
}
let RpcResponse::InterfaceStats(decoded) =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap()
else {
panic!("wrong variant");
};
assert_eq!(
(
decoded[0].announces_received,
decoded[0].announces_sent,
decoded[0].path_requests_received,
decoded[0].path_requests_sent,
decoded[0].protocol_violations,
decoded[0].ifac_violations,
decoded[0].packet_filter_hits,
decoded[0].tx_drops,
decoded[0].tx_dropped_bytes,
),
(11, 12, 13, 14, 15, 16, 17, 1, 18)
);
}
#[test]
fn python_daemon_counters_parse_into_interface_stats() {
let upstream = py_dict(vec![(
"interfaces",
PyValue::List(vec![py_dict(vec![
(
"name",
PyValue::String("TCPInterface[Client on Hub]".to_string()),
),
("status", PyValue::Bool(true)),
("arxc", PyValue::Int(21)),
("atxc", PyValue::Int(22)),
("prxc", PyValue::Int(23)),
("ptxc", PyValue::Int(24)),
("protocol_violations", PyValue::Int(25)),
("ifac_violations", PyValue::Int(26)),
("packet_filter_hits", PyValue::Int(27)),
("txdrp", PyValue::Int(28)),
("txdrb", PyValue::Int(29)),
(
"parent_interface_name",
PyValue::String("TCPServerInterface[Hub/0.0.0.0:4242]".to_string()),
),
])]),
)]);
let encoded = encode_umsgpack(&upstream).unwrap();
let RpcResponse::InterfaceStats(entries) =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap()
else {
panic!("wrong variant");
};
let entry = &entries[0];
assert_eq!(
(
entry.announces_received,
entry.announces_sent,
entry.path_requests_received,
entry.path_requests_sent,
entry.protocol_violations,
entry.ifac_violations,
entry.packet_filter_hits,
entry.tx_drops,
entry.tx_dropped_bytes,
),
(21, 22, 23, 24, 25, 26, 27, 28, 29)
);
assert_eq!(
entry.parent_interface_name.as_deref(),
Some("TCPServerInterface[Hub/0.0.0.0:4242]")
);
}
#[test]
fn a_spawned_interface_names_its_parent_like_python() {
let parent = interface_stat_entry();
let mut child = interface_stat_entry();
child.id = 8;
child.name = "TestIf/client_8".to_string();
child.parent_interface_name = Some(parent.name.clone());
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![parent, child])).unwrap();
let interfaces = interface_dicts(&stats_dict(&encoded));
assert!(dict_get(&interfaces[0], "parent_interface_name").is_none());
assert_eq!(
dict_get(&interfaces[1], "parent_interface_name"),
Some(&PyValue::String("TestIf".to_string()))
);
assert_eq!(
dict_get(&interfaces[1], "parent_interface_hash"),
Some(&PyValue::Bytes(rns_crypto::sha::sha256(b"TestIf").to_vec())),
"Python's get_hash() is the full hash of the interface name (Interface.py:181-183)"
);
assert_eq!(
dict_get(&interfaces[0], "hash"),
Some(&PyValue::Bytes(rns_crypto::sha::sha256(b"TestIf").to_vec()))
);
}
#[test]
fn transport_instance_stats_carry_python_transport_fields() {
let transport = TransportStats {
transport_id: [0x11; 16],
network_id: Some([0x22; 16]),
uptime: 12.5,
probe_responder: Some([0x33; 16]),
};
let encoded = encode_interface_stats(&[interface_stat_entry()], Some(&transport)).unwrap();
let stats = stats_dict(&encoded);
assert_eq!(
dict_get(&stats, "transport_id"),
Some(&PyValue::Bytes(vec![0x11; 16]))
);
assert_eq!(
dict_get(&stats, "network_id"),
Some(&PyValue::Bytes(vec![0x22; 16]))
);
assert_eq!(
dict_get(&stats, "transport_uptime"),
Some(&PyValue::Float(12.5))
);
assert_eq!(
dict_get(&stats, "probe_responder"),
Some(&PyValue::Bytes(vec![0x33; 16]))
);
let bare = TransportStats {
network_id: None,
probe_responder: None,
..transport
};
let stats = stats_dict(&encode_interface_stats(&[], Some(&bare)).unwrap());
assert_eq!(dict_get(&stats, "network_id"), Some(&PyValue::None));
assert_eq!(dict_get(&stats, "probe_responder"), Some(&PyValue::None));
}
#[test]
fn interface_modes_map_to_python_mode_constants() {
for (mode, python) in [
("Full", 0x01),
("PointToPoint", 0x02),
("AccessPoint", 0x03),
("Roaming", 0x04),
("Boundary", 0x05),
("Gateway", 0x06),
("Internal", 0x07),
] {
assert_eq!(python_interface_mode(mode), python, "{mode}");
}
}
/// Python publishes IFAC as signature, size and network name, all `None`
/// without IFAC; clients key off the signature.
#[test]
fn interface_stats_carry_python_ifac_fields() {
let mut ifac = interface_stat_entry();
ifac.ifac_signature = Some(vec![0xAB; 64]);
ifac.ifac_size = Some(8);
ifac.ifac_netname = Some("testnet".to_string());
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![
ifac,
interface_stat_entry(),
]))
.unwrap();
let raw = decode_umsgpack(&encoded).unwrap();
assert!(contains_string_key(&raw, "ifac_signature"));
assert!(contains_string_key(&raw, "ifac_netname"));
let RpcResponse::InterfaceStats(entries) =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap()
else {
panic!("wrong variant");
};
assert_eq!(entries[0].ifac_signature.as_deref(), Some(&[0xAB; 64][..]));
assert_eq!(entries[0].ifac_size, Some(8));
assert_eq!(entries[0].ifac_netname.as_deref(), Some("testnet"));
assert_eq!(entries[1].ifac_signature, None);
assert_eq!(entries[1].ifac_size, None);
assert_eq!(entries[1].ifac_netname, None);
}
#[test]
fn test_interface_stats_response_roundtrip_includes_125_fields() {
let resp = RpcResponse::InterfaceStats(vec![interface_stat_entry()]);
@@ -1838,7 +2411,9 @@ mod tests {
assert!(!entry.pr_burst_active);
assert_eq!(entry.pr_burst_activated, 0.0);
assert_eq!(entry.blocked_ips, None);
assert_eq!(entry.mtu, 0, "Python stats omit MTU");
assert_eq!(entry.mtu, 0, "a legacy dict without MTU reads as 0");
assert_eq!(entry.ifac_signature, None);
assert_eq!(entry.ifac_size, None);
}
_ => panic!("wrong variant"),
}
+315 -53
View File
@@ -8,37 +8,195 @@ use tokio::sync::mpsc;
use rns_transport::messages::TransportMessage;
use crate::lifecycle::ShutdownSignal;
use crate::reticulum::InterfaceIfacStats;
use crate::rpc::{self, RpcError, RpcRequest, RpcResponse};
const MAX_REQUEST_SIZE: usize = 1_048_576;
const MAX_CONTROL_CLIENTS: usize = 64;
const CONTROL_SESSION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
/// What the control port answers from: the transport, plus the runtime's IFAC
/// records and transport instance when a runtime serves it.
#[derive(Clone)]
pub(crate) struct RpcBackend {
transport_tx: mpsc::Sender<TransportMessage>,
ifac: Option<InterfaceIfacStats>,
transport: Option<TransportStatsSource>,
}
impl RpcBackend {
pub(crate) fn new(
transport_tx: mpsc::Sender<TransportMessage>,
ifac: Option<InterfaceIfacStats>,
) -> Self {
Self {
transport_tx,
ifac,
transport: None,
}
}
pub(crate) fn with_transport(mut self, transport: Option<TransportStatsSource>) -> Self {
self.transport = transport;
self
}
}
/// A transport instance's identity, network identity, start and probe
/// responder for its interface stats; the responder registers after the
/// control port starts.
#[derive(Clone)]
pub(crate) struct TransportStatsSource {
transport_id: [u8; 16],
network_id: Option<[u8; 16]>,
started_at: std::time::Instant,
probe_responder: std::sync::Arc<std::sync::OnceLock<[u8; 16]>>,
}
impl TransportStatsSource {
pub(crate) fn new(
transport_id: [u8; 16],
network_id: Option<[u8; 16]>,
started_at: std::time::Instant,
) -> Self {
Self {
transport_id,
network_id,
started_at,
probe_responder: Default::default(),
}
}
pub(crate) fn set_probe_responder(&self, destination: [u8; 16]) {
let _ = self.probe_responder.set(destination);
}
pub(crate) fn snapshot(&self) -> rpc::TransportStats {
rpc::TransportStats {
transport_id: self.transport_id,
network_id: self.network_id,
uptime: self.started_at.elapsed().as_secs_f64(),
probe_responder: self.probe_responder.get().copied(),
}
}
}
/// Transport stat entries as the control port and remote management report
/// them: with IFAC, and accepted clients naming their listener.
pub(crate) fn stat_entries(
entries: Vec<rns_transport::messages::InterfaceStatRpcEntry>,
ifac: Option<&InterfaceIfacStats>,
) -> Vec<rpc::InterfaceStatEntry> {
let names: std::collections::HashMap<u64, String> = entries
.iter()
.map(|entry| (entry.id, entry.name.clone()))
.collect();
entries
.into_iter()
.map(|e| {
let autoconnect_source = ifac.and_then(|records| records.autoconnect_source(e.id));
let ifac = ifac.map(|ifac| ifac.lookup(e.id)).unwrap_or_default();
rpc::InterfaceStatEntry {
autoconnect_source,
parent_interface_name: e.parent_id.and_then(|id| names.get(&id).cloned()),
id: e.id,
name: e.name,
rx_bytes: e.rx_bytes,
tx_bytes: e.tx_bytes,
rx_rate: e.rx_rate,
tx_rate: e.tx_rate,
online: e.online,
bitrate: e.bitrate,
mtu: e.mtu,
mode: e.mode,
role: e.role,
announce_queue: e.announce_queue,
held_announces: e.held_announces,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
clients: e.clients,
blocked_ips: e.blocked_ips,
announce_rate_target: e.announce_rate_target,
announce_rate_grace: e.announce_rate_grace,
announce_rate_penalty: e.announce_rate_penalty,
announce_cap: e.announce_cap,
ifac_signature: ifac.signature.map(Vec::from),
ifac_size: ifac.size,
ifac_netname: ifac.netname,
tx_drops: e.tx_drops,
tx_dropped_bytes: e.tx_dropped_bytes,
announces_received: e.announces_received,
announces_sent: e.announces_sent,
path_requests_received: e.path_requests_received,
path_requests_sent: e.path_requests_sent,
protocol_violations: e.protocol_violations,
ifac_violations: e.ifac_violations,
packet_filter_hits: e.packet_filter_hits,
}
})
.collect()
}
/// Serve the control port from a bare transport; interface stats then carry
/// no IFAC fields.
pub async fn run_rpc_server(
port: u16,
rpc_key: Vec<u8>,
_transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: mpsc::Sender<TransportMessage>,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
serve_rpc_port(port, rpc_key, RpcBackend::new(transport_tx, None), shutdown).await
}
pub(crate) async fn serve_rpc_port(
port: u16,
rpc_key: Vec<u8>,
backend: RpcBackend,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
.await
.map_err(RpcError::Io)?;
run_rpc_server_with_listener(listener, rpc_key, _transport_tx, shutdown).await
run_rpc_server_with_listener(listener, rpc_key, backend, shutdown).await
}
/// Serve the control socket from a bare transport; interface stats then carry
/// no IFAC fields.
#[cfg(unix)]
pub async fn run_unix_rpc_server(
socket_path: &str,
rpc_key: Vec<u8>,
transport_tx: mpsc::Sender<TransportMessage>,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
serve_unix_rpc(
socket_path,
rpc_key,
RpcBackend::new(transport_tx, None),
shutdown,
)
.await
}
#[cfg(unix)]
pub(crate) async fn serve_unix_rpc(
socket_path: &str,
rpc_key: Vec<u8>,
backend: RpcBackend,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
let listener = bind_unix_rpc_listener(socket_path).map_err(RpcError::Io)?;
run_unix_rpc_server_with_listener(
listener,
display_socket_path(socket_path),
rpc_key,
transport_tx,
backend,
shutdown,
)
.await
@@ -46,9 +204,25 @@ pub async fn run_unix_rpc_server(
#[cfg(not(unix))]
pub async fn run_unix_rpc_server(
socket_path: &str,
rpc_key: Vec<u8>,
transport_tx: mpsc::Sender<TransportMessage>,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
serve_unix_rpc(
socket_path,
rpc_key,
RpcBackend::new(transport_tx, None),
shutdown,
)
.await
}
#[cfg(not(unix))]
pub(crate) async fn serve_unix_rpc(
_socket_path: &str,
_rpc_key: Vec<u8>,
_transport_tx: mpsc::Sender<TransportMessage>,
_backend: RpcBackend,
_shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
Err(RpcError::Io(std::io::Error::new(
@@ -60,7 +234,7 @@ pub async fn run_unix_rpc_server(
pub(crate) async fn run_rpc_server_with_listener(
listener: TcpListener,
rpc_key: Vec<u8>,
_transport_tx: mpsc::Sender<TransportMessage>,
backend: RpcBackend,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
let port = listener.local_addr().map_err(RpcError::Io)?.port();
@@ -79,10 +253,10 @@ pub(crate) async fn run_rpc_server_with_listener(
if clients.len() >= MAX_CONTROL_CLIENTS { continue; }
tracing::debug!("RPC connection from {}", addr);
let key = rpc_key.clone();
let tx = _transport_tx.clone();
let backend = backend.clone();
clients.spawn(async move {
let _ = tokio::time::timeout(CONTROL_SESSION_TIMEOUT,
handle_rpc_client(stream, &key, tx)).await;
handle_rpc_client(stream, &key, backend)).await;
});
}
Err(e) => {
@@ -101,7 +275,7 @@ pub(crate) async fn run_unix_rpc_server_with_listener(
listener: tokio::net::UnixListener,
display_path: String,
rpc_key: Vec<u8>,
transport_tx: mpsc::Sender<TransportMessage>,
backend: RpcBackend,
shutdown: ShutdownSignal,
) -> Result<(), RpcError> {
tracing::info!("RPC server listening on {}", display_path);
@@ -119,10 +293,10 @@ pub(crate) async fn run_unix_rpc_server_with_listener(
if clients.len() >= MAX_CONTROL_CLIENTS { continue; }
tracing::debug!("Unix RPC connection accepted");
let key = rpc_key.clone();
let tx = transport_tx.clone();
let backend = backend.clone();
clients.spawn(async move {
let _ = tokio::time::timeout(CONTROL_SESSION_TIMEOUT,
handle_rpc_client(stream, &key, tx)).await;
handle_rpc_client(stream, &key, backend)).await;
});
}
Err(e) => {
@@ -183,7 +357,7 @@ fn display_socket_path(path: &str) -> String {
async fn handle_rpc_client(
mut stream: impl AsyncRead + AsyncWrite + Unpin,
rpc_key: &[u8],
transport_tx: mpsc::Sender<TransportMessage>,
backend: RpcBackend,
) -> Result<(), RpcError> {
let challenge = rpc::new_python_challenge();
let mut challenge_frame = Vec::with_capacity(rpc::MP_CHALLENGE.len() + challenge.len());
@@ -219,18 +393,31 @@ async fn handle_rpc_client(
let req_buf = rpc::read_mp_frame(&mut stream, MAX_REQUEST_SIZE).await?;
let request = rpc::decode_request(&req_buf)?;
let response = process_rpc_request(request, &transport_tx).await;
let resp_data = rpc::encode_response(&response)?;
let resp_data = respond(request, &backend).await?;
rpc::write_mp_frame(&mut stream, &resp_data).await?;
Ok(())
}
async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result<Vec<u8>, RpcError> {
match process_rpc_request(request, &backend.transport_tx, backend.ifac.as_ref()).await {
RpcResponse::InterfaceStats(entries) => rpc::encode_interface_stats(
&entries,
backend
.transport
.as_ref()
.map(TransportStatsSource::snapshot)
.as_ref(),
),
response => rpc::encode_response(&response),
}
}
const TRANSPORT_QUERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TransportQueryFailure {
InvalidTimeout,
SendTimedOut,
ChannelClosed,
ResponseTimedOut,
@@ -240,6 +427,7 @@ enum TransportQueryFailure {
impl TransportQueryFailure {
fn description(self) -> &'static str {
match self {
Self::InvalidTimeout => "invalid timeout: must be finite and representable",
Self::SendTimedOut => "request enqueue timed out",
Self::ChannelClosed => "query channel is closed",
Self::ResponseTimedOut => "response timed out",
@@ -252,6 +440,9 @@ fn transport_failure_response(
operation: &'static str,
failure: TransportQueryFailure,
) -> RpcResponse {
if matches!(failure, TransportQueryFailure::InvalidTimeout) {
return RpcResponse::Error("invalid timeout: must be finite and representable".into());
}
RpcResponse::Error(format!(
"transport actor failed {operation}: {}",
failure.description()
@@ -303,7 +494,15 @@ async fn request_path(
destination_hash: [u8; 16],
timeout_secs: Option<f64>,
) -> Result<bool, TransportQueryFailure> {
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
let seconds = timeout_secs.unwrap_or(5.0);
if !seconds.is_finite() {
return Err(TransportQueryFailure::InvalidTimeout);
}
let wait = std::time::Duration::try_from_secs_f64(seconds.max(0.1))
.map_err(|_| TransportQueryFailure::InvalidTimeout)?;
std::time::Instant::now()
.checked_add(wait)
.ok_or(TransportQueryFailure::InvalidTimeout)?;
match tokio::time::timeout(
TRANSPORT_QUERY_BUDGET,
transport_tx.send(TransportMessage::RequestPath { destination_hash }),
@@ -342,6 +541,7 @@ async fn request_path(
async fn process_rpc_request(
request: RpcRequest,
transport_tx: &mpsc::Sender<TransportMessage>,
ifac: Option<&InterfaceIfacStats>,
) -> RpcResponse {
use rns_transport::messages::{TransportQuery, TransportQueryResponse};
@@ -378,41 +578,7 @@ async fn process_rpc_request(
RpcRequest::GetInterfaceStats => {
match authoritative_query!(TransportQuery::GetInterfaceStats, "interface stats query") {
TransportQueryResponse::InterfaceStats(entries) => {
let rpc_entries = entries
.into_iter()
.map(|e| rpc::InterfaceStatEntry {
id: e.id,
name: e.name,
rx_bytes: e.rx_bytes,
tx_bytes: e.tx_bytes,
rx_rate: e.rx_rate,
tx_rate: e.tx_rate,
online: e.online,
bitrate: e.bitrate,
mtu: e.mtu,
mode: e.mode,
role: e.role,
announce_queue: e.announce_queue,
held_announces: e.held_announces,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
clients: e.clients,
blocked_ips: e.blocked_ips,
announce_rate_target: e.announce_rate_target,
announce_rate_grace: e.announce_rate_grace,
announce_rate_penalty: e.announce_rate_penalty,
announce_cap: e.announce_cap,
ifac_size: e.ifac_size,
tx_drops: e.tx_drops,
})
.collect();
RpcResponse::InterfaceStats(rpc_entries)
RpcResponse::InterfaceStats(stat_entries(entries, ifac))
}
_ => unexpected_transport_response("interface stats query"),
}
@@ -719,6 +885,18 @@ fn packet_hash_to_array(hash: &[u8]) -> Option<[u8; 32]> {
#[cfg(test)]
mod tests {
#[tokio::test]
async fn invalid_path_timeout_never_enqueues_network_work() {
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX] {
assert!(matches!(
super::request_path(&tx, [1; 16], Some(seconds)).await,
Err(super::TransportQueryFailure::InvalidTimeout)
));
assert!(rx.try_recv().is_err());
}
}
use super::*;
// These are cross-process compatibility checks, not latency benchmarks.
@@ -843,7 +1021,13 @@ mod tests {
let shutdown_clone = shutdown.clone();
let handle = tokio::spawn(async move {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
run_rpc_server_with_listener(listener, rpc_key, tx, shutdown_clone).await
run_rpc_server_with_listener(
listener,
rpc_key,
RpcBackend::new(tx, None),
shutdown_clone,
)
.await
});
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -874,6 +1058,77 @@ mod tests {
shutdown.trigger();
}
/// A transport instance adds its identity, network identity, uptime and
/// probe responder to the stats dict (Reticulum.py:1700-1705).
#[tokio::test]
async fn interface_stats_answer_names_the_transport_instance() {
let (actor, tx) = rns_transport::actor::TransportActor::new();
tokio::spawn(actor.run());
let transport = TransportStatsSource::new(
[0x11; 16],
Some([0x22; 16]),
std::time::Instant::now() - std::time::Duration::from_secs(3),
);
let backend = RpcBackend::new(tx, None).with_transport(Some(transport.clone()));
let stats = |encoded: Vec<u8>| -> Vec<(rmpv::Value, rmpv::Value)> {
rmpv::decode::read_value(&mut encoded.as_slice())
.unwrap()
.as_map()
.expect("stats dict")
.clone()
};
let field = |stats: &[(rmpv::Value, rmpv::Value)], key: &str| {
stats
.iter()
.find(|(k, _)| k.as_str() == Some(key))
.map(|(_, v)| v.clone())
.unwrap_or_else(|| panic!("missing {key}"))
};
let before = stats(
respond(RpcRequest::GetInterfaceStats, &backend)
.await
.unwrap(),
);
assert_eq!(
field(&before, "transport_id").as_slice(),
Some(&[0x11; 16][..])
);
assert_eq!(
field(&before, "network_id").as_slice(),
Some(&[0x22; 16][..])
);
assert!(field(&before, "transport_uptime").as_f64().unwrap() >= 3.0);
assert!(
field(&before, "probe_responder").is_nil(),
"no probe responder has registered yet"
);
transport.set_probe_responder([0x33; 16]);
let after = stats(
respond(RpcRequest::GetInterfaceStats, &backend)
.await
.unwrap(),
);
assert_eq!(
field(&after, "probe_responder").as_slice(),
Some(&[0x33; 16][..])
);
let (actor, tx) = rns_transport::actor::TransportActor::new();
tokio::spawn(actor.run());
let leaf = stats(
respond(RpcRequest::GetInterfaceStats, &RpcBackend::new(tx, None))
.await
.unwrap(),
);
assert!(
!leaf.iter().any(|(k, _)| k.as_str() == Some("transport_id")),
"a leaf names no transport instance"
);
}
#[tokio::test]
async fn test_rpc_server_auth_failure() {
let shutdown = ShutdownSignal::new();
@@ -1152,7 +1407,7 @@ listener.close()
tokio::spawn(actor.run());
for req in all_rpc_requests() {
let resp = process_rpc_request(req, &tx).await;
let resp = process_rpc_request(req, &tx, None).await;
assert!(
!matches!(resp, RpcResponse::Error(_)),
"unexpected Error response"
@@ -1173,6 +1428,7 @@ listener.close()
timeout_secs: Some(1.0),
},
&tx,
None,
)
.await
});
@@ -1229,7 +1485,13 @@ listener.close()
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let _ = run_rpc_server_with_listener(listener, rpc_key, tx, shutdown).await;
let _ = run_rpc_server_with_listener(
listener,
rpc_key,
RpcBackend::new(tx, None),
shutdown,
)
.await;
});
port
}
+8 -4
View File
@@ -289,6 +289,8 @@ pub(crate) async fn spawn_authenticated_client(
_ = shutdown.wait() => return Err(SharedInstanceError::Cancelled),
result = credentials.connect() => result?,
};
let transport = rns_transport::InterfaceTransportSender::new(id, transport);
let owner = transport.owner();
let online = Arc::new(AtomicBool::new(true));
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
@@ -360,6 +362,8 @@ pub(crate) async fn spawn_authenticated_client(
Ok((
InterfaceHandle {
id,
owner,
packet_capacity: rns_transport::InterfacePacketCapacity::new(262_144, 262_144, true),
parent_id: None,
name: "Authenticated shared instance".to_string(),
mode: InterfaceMode::Full,
@@ -402,7 +406,7 @@ async fn packet_loop(
stream: &mut PacketStream,
outbound: &mut mpsc::Receiver<Bytes>,
id: u64,
transport: &mpsc::Sender<TransportMessage>,
transport: &rns_transport::InterfaceTransportSender,
rxb: &AtomicU64,
txb: &AtomicU64,
) -> std::io::Result<()> {
@@ -469,18 +473,18 @@ impl BoundControlListener {
pub(crate) async fn run(
self,
key: Vec<u8>,
transport: mpsc::Sender<TransportMessage>,
backend: crate::rpc_server::RpcBackend,
shutdown: ShutdownSignal,
) {
let result = match self {
Self::Tcp(listener) => {
crate::rpc_server::run_rpc_server_with_listener(listener, key, transport, shutdown)
crate::rpc_server::run_rpc_server_with_listener(listener, key, backend, shutdown)
.await
}
#[cfg(unix)]
Self::Unix(listener, path) => {
crate::rpc_server::run_unix_rpc_server_with_listener(
listener, path, key, transport, shutdown,
listener, path, key, backend, shutdown,
)
.await
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more