mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
rpc: Reticulum 1.6.1 shared-instance RPC, with rnstatus and rnpath to match
This commit is contained in:
1 parent
3cd4ecadaa
commit
4c4418ca93
8 files changed
+1396
-149
No files matched your search
@@ -194,7 +194,7 @@ fn handle_path(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u
|
||||
hops: e.hops,
|
||||
expires: e.expires,
|
||||
value: e.value,
|
||||
used: e.used,
|
||||
used: Some(e.used),
|
||||
lr_cost: e.lr_cost,
|
||||
interface: e.interface,
|
||||
interface_hash: Some(e.interface_hash.to_vec()),
|
||||
|
||||
@@ -126,6 +126,8 @@ struct TransportCompletion {
|
||||
}
|
||||
|
||||
const RUNTIME_INTERFACE_DRAIN_DEADLINE: Duration = Duration::from_secs(10);
|
||||
/// Python `Reticulum.RPC_EXIT_TIMEOUT`: the exit deregistration's whole budget.
|
||||
const RPC_EXIT_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Python `Transport.application_identity.hash`: one random requester per
|
||||
/// process for destination type requests (Transport.py).
|
||||
@@ -293,8 +295,12 @@ impl RuntimeShutdownCoordinator {
|
||||
requester: application_requester().to_vec(),
|
||||
signature: None,
|
||||
};
|
||||
if let Err(error) = target.request(&request).await {
|
||||
tracing::debug!(%error, "shared instance RPC failed while deregistering destination types");
|
||||
match tokio::time::timeout(RPC_EXIT_TIMEOUT, target.request(&request)).await {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(error)) => {
|
||||
tracing::debug!("Could not deregister destination types at exit: {error}")
|
||||
}
|
||||
Err(_) => tracing::debug!("Shared instance RPC timed out during exit"),
|
||||
}
|
||||
}
|
||||
let drain = match self.inner.interface_registry.begin_drain() {
|
||||
@@ -2406,24 +2412,71 @@ impl ReticulumHandle {
|
||||
Some((entry, spawned))
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `_detach_interface`: by name, or else by the tunnel id the
|
||||
/// text spells in hex (Reticulum.py:976-1015).
|
||||
async fn detach_running_interface(&self, name: &str) -> Option<bool> {
|
||||
let Some((entry, spawned)) = self.running_interface(name).await else {
|
||||
tracing::warn!("Attempt to detach non-existing interface \"{name}\"");
|
||||
return None;
|
||||
let (entry, spawned) = match self.running_interface(name).await {
|
||||
Some(found) => found,
|
||||
None => {
|
||||
let tunnel_id = python_fromhex(name)?;
|
||||
let Some(found) = self.tunnel_interface(&tunnel_id).await else {
|
||||
tracing::warn!("Attempt to detach non-existing interface \"{name}\"");
|
||||
return None;
|
||||
};
|
||||
found
|
||||
}
|
||||
};
|
||||
if !self.detach_entry(&entry, spawned).await {
|
||||
return Some(false);
|
||||
}
|
||||
// Upstream's detach is synchronous: a reload attaches straight after it.
|
||||
let gone_by = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while self.running_interface(name).await.is_some() && tokio::time::Instant::now() < gone_by
|
||||
{
|
||||
while self.interface_registered(entry.id).await && tokio::time::Instant::now() < gone_by {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
rns_transport::notice!("Interface \"{name}\" was detached");
|
||||
let shown = entry
|
||||
.identity
|
||||
.as_ref()
|
||||
.map_or(entry.name.as_str(), |identity| identity.name.as_str());
|
||||
rns_transport::notice!("Interface {shown} was detached");
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// The last interface whose `tunnel_id or local_tunnel_id` is `tunnel_id`,
|
||||
/// with every interface it spawned.
|
||||
async fn tunnel_interface(
|
||||
&self,
|
||||
tunnel_id: &[u8],
|
||||
) -> Option<(
|
||||
rns_transport::messages::InterfaceStatRpcEntry,
|
||||
Vec<rns_transport::messages::InterfaceId>,
|
||||
)> {
|
||||
let Ok(TransportQueryResponse::InterfaceStats(entries)) = self
|
||||
.query_transport_result(TransportQuery::GetInterfaceStats)
|
||||
.await
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let entry = entries
|
||||
.iter()
|
||||
.rfind(|entry| entry.tunnel_id.is_some_and(|id| id[..] == *tunnel_id))?
|
||||
.clone();
|
||||
let spawned = entries
|
||||
.iter()
|
||||
.filter(|child| child.parent_id == Some(entry.id))
|
||||
.map(|child| child.id)
|
||||
.collect();
|
||||
Some((entry, spawned))
|
||||
}
|
||||
|
||||
async fn interface_registered(&self, id: rns_transport::messages::InterfaceId) -> bool {
|
||||
matches!(
|
||||
self.query_transport_result(TransportQuery::GetInterfaceStats).await,
|
||||
Ok(TransportQueryResponse::InterfaceStats(entries))
|
||||
if entries.iter().any(|entry| entry.id == id)
|
||||
)
|
||||
}
|
||||
|
||||
/// Python `_detach_interface(..., internal_forced=True)`, which transport
|
||||
/// calls for a bad or blackholed tunnel peer: it ignores
|
||||
/// `enable_interface_management`, and a client so detached stays down until
|
||||
@@ -2799,6 +2852,8 @@ fn transport_query_to_rpc_request(query: &TransportQuery) -> Option<crate::rpc::
|
||||
TransportQuery::UnretainDestination { dest } => RpcRequest::UnretainDestination {
|
||||
destination_hash: dest.to_vec(),
|
||||
},
|
||||
TransportQuery::GetLinkDistribution => RpcRequest::GetLinkDistribution,
|
||||
TransportQuery::GetKnownDestinations => RpcRequest::GetKnownDestinations,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -2822,7 +2877,7 @@ fn rpc_response_to_transport_response(
|
||||
out.hops = entry.hops;
|
||||
out.expires = entry.expires;
|
||||
out.value = entry.value;
|
||||
out.used = entry.used;
|
||||
out.used = entry.used.unwrap_or(0.0);
|
||||
out.lr_cost = entry.lr_cost;
|
||||
// Before 1.6.1 the hash is upstream's, of `str(interface)`.
|
||||
out.interface_hash = entry
|
||||
@@ -2900,11 +2955,53 @@ fn rpc_response_to_transport_response(
|
||||
.collect();
|
||||
TransportQueryResponse::BlackholeList(entries)
|
||||
}
|
||||
RpcResponse::LinkDistribution(entries) => TransportQueryResponse::LinkDistribution(
|
||||
entries
|
||||
.into_iter()
|
||||
.filter_map(|entry| {
|
||||
let mut out = rns_transport::messages::LinkDistributionRpcEntry::default();
|
||||
out.destination_hash = entry.destination_hash.as_slice().try_into().ok()?;
|
||||
out.active = entry.active;
|
||||
out.pending = entry.pending;
|
||||
out.traffic = entry.traffic;
|
||||
out.from_interfaces = entry
|
||||
.from_interfaces
|
||||
.iter()
|
||||
.filter_map(|hash| hash.as_slice().try_into().ok())
|
||||
.collect();
|
||||
Some(out)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::KnownDestinations(entries) => TransportQueryResponse::KnownDestinations(
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(crate::rpc::KnownDestinationEntry::to_row)
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::Ok => TransportQueryResponse::Ok,
|
||||
RpcResponse::Error(e) => TransportQueryResponse::Error(e),
|
||||
})
|
||||
}
|
||||
|
||||
/// Python `bytes.fromhex`: pairs of hex digits, ASCII whitespace allowed
|
||||
/// between pairs.
|
||||
fn python_fromhex(text: &str) -> Option<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
let mut chars = text.chars();
|
||||
loop {
|
||||
let high = loop {
|
||||
match chars.next() {
|
||||
None => return Some(bytes),
|
||||
Some(' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c') => {}
|
||||
Some(c) => break c,
|
||||
}
|
||||
};
|
||||
let low = chars.next()?;
|
||||
bytes.push((high.to_digit(16)? * 16 + low.to_digit(16)?) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
fn vec_to_16(bytes: &[u8]) -> Option<[u8; 16]> {
|
||||
if bytes.len() < 16 {
|
||||
return None;
|
||||
@@ -3068,6 +3165,8 @@ fn shared_tcp_port_is_free(port: u16) -> bool {
|
||||
struct TransportStorageStart<'a> {
|
||||
transport_tx: &'a mpsc::Sender<TransportMessage>,
|
||||
storage_dir: &'a Path,
|
||||
/// Where a client without the owner's database loads known destinations.
|
||||
rpc: Option<SharedRpcTarget>,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
@@ -3085,6 +3184,63 @@ impl TransportStorageStart<'_> {
|
||||
if self.transport_tx.send(message).await.is_ok() {
|
||||
let _ = loaded.await;
|
||||
}
|
||||
if role == StorageRole::SharedInstanceClient {
|
||||
self.load_known_destinations_over_rpc().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn query(&self, query: TransportQuery) -> Option<TransportQueryResponse> {
|
||||
let (response_tx, response) = tokio::sync::oneshot::channel();
|
||||
self.transport_tx
|
||||
.send(TransportMessage::Rpc { query, response_tx })
|
||||
.await
|
||||
.ok()?;
|
||||
response.await.ok()
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `Identity.load_known_destinations`: a client that could
|
||||
/// not read the owner's database, as in split mode, asks the shared
|
||||
/// instance; a failed RPC leaves the table empty.
|
||||
async fn load_known_destinations_over_rpc(&self) {
|
||||
if matches!(
|
||||
self.query(TransportQuery::KnownDestinationsLoaded).await,
|
||||
Some(TransportQueryResponse::BoolResult(true))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let Some(target) = &self.rpc else {
|
||||
return;
|
||||
};
|
||||
tracing::debug!(
|
||||
"Potentially running in split mode, attempting to load known destinations over RPC..."
|
||||
);
|
||||
let entries = match target
|
||||
.request(&crate::rpc::RpcRequest::GetKnownDestinations)
|
||||
.await
|
||||
{
|
||||
Ok(crate::rpc::RpcResponse::KnownDestinations(entries)) => entries,
|
||||
Ok(other) => {
|
||||
tracing::error!(
|
||||
?other,
|
||||
"Shared instance RPC failed while getting known destinations"
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
"Shared instance RPC failed while getting known destinations: {error}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let rows: Vec<_> = entries
|
||||
.iter()
|
||||
.filter_map(crate::rpc::KnownDestinationEntry::to_row)
|
||||
.collect();
|
||||
let count = rows.len();
|
||||
self.query(TransportQuery::LoadKnownDestinations { rows })
|
||||
.await;
|
||||
tracing::debug!("Loaded {count} known destinations from shared instance");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4050,6 +4206,10 @@ pub async fn init_with_policy(
|
||||
let mut storage = TransportStorageStart {
|
||||
transport_tx: &transport_tx,
|
||||
storage_dir: &paths.storage_dir,
|
||||
rpc: rc.rpc_key.clone().map(|rpc_key| SharedRpcTarget {
|
||||
endpoint: rc.shared_rpc_endpoint(&socket_base),
|
||||
rpc_key,
|
||||
}),
|
||||
started: false,
|
||||
};
|
||||
let configured_policy = matches!(policy, InstancePolicy::Configured);
|
||||
@@ -11615,6 +11775,133 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `Identity.load_known_destinations`: a client without the
|
||||
/// owner's database loads the table over RPC; one that read it does not ask.
|
||||
#[tokio::test]
|
||||
async fn a_client_without_the_owners_database_loads_known_destinations_over_rpc() {
|
||||
let row = {
|
||||
let mut row = rns_transport::store::KnownDestinationRow::new([0x5a; 16], 7.5, [9; 64]);
|
||||
row.app_data = Some(b"shared".to_vec());
|
||||
row.stamp_value = 4.0;
|
||||
row
|
||||
};
|
||||
let (owner_tx, mut owner_rx) = mpsc::channel::<TransportMessage>(4);
|
||||
let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let served = {
|
||||
let (row, asked) = (row.clone(), asked.clone());
|
||||
tokio::spawn(async move {
|
||||
while let Some(TransportMessage::Rpc { query, response_tx }) = owner_rx.recv().await
|
||||
{
|
||||
if matches!(query, TransportQuery::GetKnownDestinations) {
|
||||
asked.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
let _ = response_tx
|
||||
.send(TransportQueryResponse::KnownDestinations(vec![row.clone()]));
|
||||
}
|
||||
})
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let shutdown = ShutdownSignal::new();
|
||||
tokio::spawn(crate::rpc_server::run_rpc_server_with_listener(
|
||||
listener,
|
||||
vec![0x42; 32],
|
||||
crate::rpc_server::RpcBackend::new(owner_tx),
|
||||
shutdown.clone(),
|
||||
));
|
||||
|
||||
async fn client_storage(
|
||||
dir: &Path,
|
||||
port: u16,
|
||||
) -> Vec<rns_transport::store::KnownDestinationRow> {
|
||||
let (actor, transport_tx) = rns_transport::actor::TransportActor::new();
|
||||
tokio::spawn(actor.run());
|
||||
let mut storage = TransportStorageStart {
|
||||
transport_tx: &transport_tx,
|
||||
storage_dir: dir,
|
||||
rpc: Some(SharedRpcTarget {
|
||||
endpoint: SharedInstanceRpcEndpoint::Tcp(port),
|
||||
rpc_key: vec![0x42; 32],
|
||||
}),
|
||||
started: false,
|
||||
};
|
||||
storage.start(StorageRole::SharedInstanceClient).await;
|
||||
let (response_tx, response) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
query: TransportQuery::GetKnownDestinations,
|
||||
response_tx,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = transport_tx.send(TransportMessage::Shutdown).await;
|
||||
match response.await.unwrap() {
|
||||
TransportQueryResponse::KnownDestinations(rows) => rows,
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
let split = std::env::temp_dir().join(format!(
|
||||
"rns-split-client-{}-{}",
|
||||
std::process::id(),
|
||||
unix_now()
|
||||
));
|
||||
std::fs::create_dir_all(&split).unwrap();
|
||||
assert_eq!(client_storage(&split, port).await, vec![row]);
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 1);
|
||||
|
||||
// The owner's directory holds the database, so the client reads it.
|
||||
let owned = split.join("owned");
|
||||
std::fs::create_dir_all(&owned).unwrap();
|
||||
let mut owner = rns_transport::actor::TransportActor::new().0;
|
||||
owner.initialize_storage(owned.clone());
|
||||
drop(owner);
|
||||
assert!(owned.join("known_destinations.db").is_file());
|
||||
assert!(client_storage(&owned, port).await.is_empty());
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 1, "no RPC with a database");
|
||||
|
||||
shutdown.trigger();
|
||||
served.abort();
|
||||
let _ = std::fs::remove_dir_all(split);
|
||||
}
|
||||
|
||||
/// A shared instance that accepts the exit deregistration and never
|
||||
/// answers cannot hold shutdown past `RPC_EXIT_TIMEOUT` (Reticulum.py).
|
||||
#[tokio::test]
|
||||
async fn exit_deregistration_is_bounded_by_the_rpc_exit_timeout() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (accepted_tx, mut accepted) = oneshot::channel();
|
||||
let silent = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let _ = accepted_tx.send(());
|
||||
std::future::pending::<()>().await;
|
||||
drop(stream);
|
||||
});
|
||||
let (transport_tx, transport_rx) = mpsc::channel::<TransportMessage>(1);
|
||||
drop(transport_rx);
|
||||
let completion = Arc::new(TransportCompletion::default());
|
||||
completion.mark_stopped();
|
||||
let coordinator = RuntimeShutdownCoordinator::new(
|
||||
ShutdownSignal::new(),
|
||||
transport_tx,
|
||||
completion,
|
||||
Arc::new(std::sync::Mutex::new(HashMap::new())),
|
||||
InterfaceRegistry::default(),
|
||||
);
|
||||
coordinator.install_exit_unwants(SharedRpcTarget {
|
||||
endpoint: SharedInstanceRpcEndpoint::Tcp(port),
|
||||
rpc_key: vec![0x42; 32],
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
tokio::time::timeout(Duration::from_secs(1), coordinator.start_and_wait())
|
||||
.await
|
||||
.expect("a silent shared instance must not hold shutdown");
|
||||
assert!(started.elapsed() >= RPC_EXIT_TIMEOUT);
|
||||
assert!(accepted.try_recv().is_ok(), "the deregistration connected");
|
||||
silent.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actor_closed_pending_registration_cannot_strand_runtime_drain() {
|
||||
let (transport_tx, transport_rx) = mpsc::channel::<TransportMessage>(1);
|
||||
|
||||
@@ -204,7 +204,7 @@ fn shared_instance_path_tables_carry_interface_hash_and_state() {
|
||||
hops: 1,
|
||||
expires: 2.0,
|
||||
value: None,
|
||||
used: 0.0,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".into(),
|
||||
interface_hash,
|
||||
|
||||
@@ -1326,3 +1326,72 @@ async fn a_client_answered_with_a_bad_signature_is_torn_down() {
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `_detach_interface`: text that names no interface but spells a
|
||||
/// tunnel id in hex, as `bytes.fromhex` reads it, detaches the interface whose
|
||||
/// `tunnel_id or local_tunnel_id` it is (Reticulum.py:976-1015).
|
||||
#[tokio::test]
|
||||
async fn detach_by_tunnel_id_finds_either_end_of_the_tunnel() {
|
||||
let hub_port = unused_port().await;
|
||||
let hub_dir = config_dir(
|
||||
"detach-hub",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Hub]]\n type = TCPServerInterface\n enabled = yes\n listen_ip = 127.0.0.1\n listen_port = {hub_port}\n"
|
||||
),
|
||||
);
|
||||
let hub = start(&hub_dir).await;
|
||||
let client_dir = config_dir("detach-client", &tcp_client_config(hub_port));
|
||||
let client = start(&client_dir).await;
|
||||
let accepted = wait_for_interface(&hub, |entry| {
|
||||
entry.parent_id.is_some() && entry.tunnel_id.is_some()
|
||||
})
|
||||
.await
|
||||
.expect("the hub takes the client's synthesis");
|
||||
let uplink = wait_for_interface(&client, |entry| {
|
||||
entry.name == "Uplink" && entry.tunnel_id.is_some()
|
||||
})
|
||||
.await
|
||||
.expect("the client names its tunnel");
|
||||
assert_eq!(accepted.tunnel_id, uplink.tunnel_id);
|
||||
let tunnel = hex::encode(accepted.tunnel_id.unwrap());
|
||||
|
||||
assert_eq!(hub.detach_interface("not hex").await.unwrap(), None);
|
||||
assert_eq!(hub.detach_interface(&"00".repeat(32)).await.unwrap(), None);
|
||||
let spaced: Vec<String> = tunnel
|
||||
.to_uppercase()
|
||||
.as_bytes()
|
||||
.chunks(2)
|
||||
.map(|pair| String::from_utf8(pair.to_vec()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
hub.detach_interface(&spaced.join(" ")).await.unwrap(),
|
||||
Some(true)
|
||||
);
|
||||
assert!(
|
||||
interfaces(&hub)
|
||||
.await
|
||||
.iter()
|
||||
.all(|entry| entry.id != accepted.id),
|
||||
"the accepted client is gone"
|
||||
);
|
||||
assert!(
|
||||
interfaces(&hub)
|
||||
.await
|
||||
.iter()
|
||||
.any(|entry| entry.name == "Hub"),
|
||||
"its listener stays"
|
||||
);
|
||||
assert_eq!(client.detach_interface(&tunnel).await.unwrap(), Some(true));
|
||||
assert!(
|
||||
interfaces(&client)
|
||||
.await
|
||||
.iter()
|
||||
.all(|entry| entry.name != "Uplink"),
|
||||
"the client's own end goes by its local tunnel id"
|
||||
);
|
||||
|
||||
client.shutdown_and_wait().await;
|
||||
hub.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(client_dir);
|
||||
let _ = std::fs::remove_dir_all(hub_dir);
|
||||
}
|
||||
+610
-49
@@ -8,6 +8,7 @@
|
||||
|
||||
use rns_transport::inbound_queues::InboundQueueSnapshot;
|
||||
use rns_transport::messages::{InterfaceIdentity, InterfaceStatRpcEntry};
|
||||
use rns_transport::tunnel::RemoteTransportInfo;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub(crate) const MP_CHALLENGE: &[u8] = b"#CHALLENGE#";
|
||||
@@ -119,8 +120,12 @@ pub enum RpcRequest {
|
||||
/// Reply: seconds as a float, or integer 0 without a known bitrate.
|
||||
GetMediumPathTimeout,
|
||||
GetActiveLinkCount,
|
||||
/// Reply: a dictionary; upstream's implementation is a stub answering `{}`.
|
||||
/// Reply: `{destination: {"active", "pending", "traffic", "from_ifs"}}`.
|
||||
GetLinkDistribution,
|
||||
/// Python 1.6.1 `Reticulum.get_known_destinations`; reply:
|
||||
/// `{destination: [last_heard, packet_hash, public_key, app_data, used,
|
||||
/// stamp, stamp_value, lr_cost]}`.
|
||||
GetKnownDestinations,
|
||||
/// Reply: profiler results, or nil when no profiler ran.
|
||||
GetProfilingResults,
|
||||
/// Reply: true, false, or nil when the interface does not exist.
|
||||
@@ -184,6 +189,8 @@ pub enum RpcResponse {
|
||||
/// True, False or None, as upstream's blackhole mutations answer.
|
||||
OptBoolResult(Option<bool>),
|
||||
BlackholeList(Vec<BlackholeEntry>),
|
||||
LinkDistribution(Vec<LinkDistributionEntry>),
|
||||
KnownDestinations(Vec<KnownDestinationEntry>),
|
||||
Ok,
|
||||
Error(String),
|
||||
}
|
||||
@@ -199,9 +206,10 @@ pub struct PathTableEntry {
|
||||
/// known but unstamped (Reticulum.py).
|
||||
#[serde(default)]
|
||||
pub value: Option<f64>,
|
||||
/// Last use in Unix seconds; 0 when never used.
|
||||
/// Last use in Unix seconds; 0 when never used, `None` from a peer
|
||||
/// before 1.6.0.
|
||||
#[serde(default)]
|
||||
pub used: f64,
|
||||
pub used: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub lr_cost: Option<f64>,
|
||||
pub interface: String,
|
||||
@@ -334,6 +342,31 @@ struct InterfaceStatWire {
|
||||
tx_stalled: bool,
|
||||
#[serde(default)]
|
||||
tx_buffered: u64,
|
||||
/// Python 1.6.1 `frxb`, `ftxb` and `afrxc`.
|
||||
#[serde(default)]
|
||||
filtered_rx_bytes: u64,
|
||||
#[serde(default)]
|
||||
filtered_tx_bytes: u64,
|
||||
#[serde(default)]
|
||||
announces_filtered: u64,
|
||||
/// Python `frxs` and `ftxs`; `None` before the first traffic count.
|
||||
#[serde(default)]
|
||||
filtered_speeds: Option<[f64; 2]>,
|
||||
#[serde(default)]
|
||||
tunnel_id: Option<Vec<u8>>,
|
||||
#[serde(default)]
|
||||
remote_transport_id: Option<Vec<u8>>,
|
||||
/// Python `rem_impl`, `rem_vers`, `rem_is_tn`, `rem_dst_cost` and `rem_pr_cost`.
|
||||
#[serde(default)]
|
||||
remote_implementation: Option<String>,
|
||||
#[serde(default)]
|
||||
remote_version: Option<Vec<u64>>,
|
||||
#[serde(default)]
|
||||
remote_is_transport: Option<bool>,
|
||||
#[serde(default)]
|
||||
remote_destination_cost: Option<f64>,
|
||||
#[serde(default)]
|
||||
remote_pr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<&InterfaceStatRpcEntry> for InterfaceStatWire {
|
||||
@@ -413,6 +446,20 @@ impl From<&InterfaceStatRpcEntry> for InterfaceStatWire {
|
||||
.map(|state| i2p_tunnel_state_text(state).to_string()),
|
||||
tx_stalled: e.tx_stalled,
|
||||
tx_buffered: e.tx_buffered,
|
||||
filtered_rx_bytes: e.filtered_rx_bytes,
|
||||
filtered_tx_bytes: e.filtered_tx_bytes,
|
||||
announces_filtered: e.announces_filtered,
|
||||
filtered_speeds: e.filtered_speeds,
|
||||
tunnel_id: e.tunnel_id.map(|id| id.to_vec()),
|
||||
remote_transport_id: e.remote_transport_id.map(|id| id.to_vec()),
|
||||
remote_implementation: e
|
||||
.remote_transport
|
||||
.as_ref()
|
||||
.map(|r| r.implementation.clone()),
|
||||
remote_version: e.remote_transport.as_ref().map(|r| r.version.clone()),
|
||||
remote_is_transport: e.remote_transport.as_ref().map(|r| r.transport),
|
||||
remote_destination_cost: e.remote_transport.as_ref().map(|r| r.destination_cost),
|
||||
remote_pr_cost: e.remote_transport.as_ref().map(|r| r.pr_cost),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -490,6 +537,25 @@ impl From<InterfaceStatWire> for InterfaceStatRpcEntry {
|
||||
e.i2p_tunnel_state = w.tunnel_state.as_deref().map(i2p_tunnel_state_code);
|
||||
e.tx_stalled = w.tx_stalled;
|
||||
e.tx_buffered = w.tx_buffered;
|
||||
e.filtered_rx_bytes = w.filtered_rx_bytes;
|
||||
e.filtered_tx_bytes = w.filtered_tx_bytes;
|
||||
e.announces_filtered = w.announces_filtered;
|
||||
e.filtered_speeds = w.filtered_speeds;
|
||||
e.tunnel_id = w.tunnel_id.and_then(|id| id.try_into().ok());
|
||||
e.remote_transport_id = w.remote_transport_id.and_then(|id| id.try_into().ok());
|
||||
// Python sets the five together from one synthesis extension (Transport.py).
|
||||
e.remote_transport = match (
|
||||
w.remote_implementation,
|
||||
w.remote_version,
|
||||
w.remote_is_transport,
|
||||
w.remote_destination_cost,
|
||||
w.remote_pr_cost,
|
||||
) {
|
||||
(Some(implementation), Some(version), Some(transport), Some(dst), Some(pr)) => Some(
|
||||
RemoteTransportInfo::new(implementation, version, transport, dst, pr),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
e
|
||||
}
|
||||
}
|
||||
@@ -572,6 +638,81 @@ pub struct BlackholeEntry {
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Relayed Links toward one destination (Python `Transport.link_distribution`).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LinkDistributionEntry {
|
||||
pub destination_hash: Vec<u8>,
|
||||
pub active: u64,
|
||||
pub pending: u64,
|
||||
pub traffic: u64,
|
||||
/// `Interface.get_hash()` of each interface a link request arrived on.
|
||||
pub from_interfaces: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl From<&rns_transport::messages::LinkDistributionRpcEntry> for LinkDistributionEntry {
|
||||
fn from(e: &rns_transport::messages::LinkDistributionRpcEntry) -> Self {
|
||||
Self {
|
||||
destination_hash: e.destination_hash.to_vec(),
|
||||
active: e.active,
|
||||
pending: e.pending,
|
||||
traffic: e.traffic,
|
||||
from_interfaces: e.from_interfaces.iter().map(|hash| hash.to_vec()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `Identity.known_destinations` entry under its destination hash.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct KnownDestinationEntry {
|
||||
pub destination_hash: Vec<u8>,
|
||||
pub last_heard: f64,
|
||||
pub packet_hash: Option<Vec<u8>>,
|
||||
pub public_key: Vec<u8>,
|
||||
pub app_data: Option<Vec<u8>>,
|
||||
/// 0 never used, -1 retained, otherwise the Unix time of last use.
|
||||
pub used: f64,
|
||||
pub stamp: Option<Vec<u8>>,
|
||||
pub stamp_value: f64,
|
||||
pub lr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<&rns_transport::store::KnownDestinationRow> for KnownDestinationEntry {
|
||||
fn from(row: &rns_transport::store::KnownDestinationRow) -> Self {
|
||||
Self {
|
||||
destination_hash: row.destination_hash.to_vec(),
|
||||
last_heard: row.last_heard,
|
||||
packet_hash: row.packet_hash.map(|hash| hash.to_vec()),
|
||||
public_key: row.public_key.to_vec(),
|
||||
app_data: row.app_data.clone(),
|
||||
used: row.used,
|
||||
stamp: row.stamp.clone(),
|
||||
stamp_value: row.stamp_value,
|
||||
lr_cost: row.lr_cost,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KnownDestinationEntry {
|
||||
/// The store row, or `None` for a malformed hash or key.
|
||||
pub fn to_row(&self) -> Option<rns_transport::store::KnownDestinationRow> {
|
||||
let mut row = rns_transport::store::KnownDestinationRow::new(
|
||||
self.destination_hash.as_slice().try_into().ok()?,
|
||||
self.last_heard,
|
||||
self.public_key.as_slice().try_into().ok()?,
|
||||
);
|
||||
row.packet_hash = match &self.packet_hash {
|
||||
Some(hash) => Some(hash.as_slice().try_into().ok()?),
|
||||
None => None,
|
||||
};
|
||||
row.app_data = self.app_data.clone();
|
||||
row.used = self.used;
|
||||
row.stamp = self.stamp.clone();
|
||||
row.stamp_value = self.stamp_value;
|
||||
row.lr_cost = self.lr_cost;
|
||||
Some(row)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_request(req: &RpcRequest) -> Result<Vec<u8>, RpcError> {
|
||||
encode_umsgpack(&request_to_py_value(req))
|
||||
}
|
||||
@@ -752,6 +893,7 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
|
||||
RpcRequest::GetMediumPathTimeout => py_get("medium_path_timeout"),
|
||||
RpcRequest::GetActiveLinkCount => py_get("active_link_count"),
|
||||
RpcRequest::GetLinkDistribution => py_get("link_distribution"),
|
||||
RpcRequest::GetKnownDestinations => py_get("known_destinations"),
|
||||
RpcRequest::GetProfilingResults => py_get("profiling_results"),
|
||||
RpcRequest::ManageInterface { operation, name } => py_dict(vec![
|
||||
("manage", PyValue::String(operation.as_str().to_string())),
|
||||
@@ -842,6 +984,7 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
|
||||
"medium_path_timeout" => Ok(RpcRequest::GetMediumPathTimeout),
|
||||
"active_link_count" => Ok(RpcRequest::GetActiveLinkCount),
|
||||
"link_distribution" => Ok(RpcRequest::GetLinkDistribution),
|
||||
"known_destinations" => Ok(RpcRequest::GetKnownDestinations),
|
||||
"profiling_results" => Ok(RpcRequest::GetProfilingResults),
|
||||
other => Err(RpcError::Deserialize(format!(
|
||||
"unknown Python RPC get path: {other}"
|
||||
@@ -1005,18 +1148,14 @@ pub(crate) fn encode_medium_path_timeout(seconds: Option<f64>) -> Result<Vec<u8>
|
||||
encode_umsgpack(&seconds.map(PyValue::Float).unwrap_or(PyValue::Int(0)))
|
||||
}
|
||||
|
||||
/// An empty dictionary, as upstream's stub `link_distribution` answers.
|
||||
pub(crate) fn encode_empty_dict() -> Result<Vec<u8>, RpcError> {
|
||||
encode_umsgpack(&PyValue::Dict(Vec::new()))
|
||||
}
|
||||
|
||||
fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
match resp {
|
||||
RpcResponse::PathTable(entries) => PyValue::List(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
py_dict(vec![
|
||||
// A key an older peer lacks stays absent, as in its dict.
|
||||
let mut fields = vec![
|
||||
("hash", PyValue::Bytes(e.hash.clone())),
|
||||
("timestamp", PyValue::Float(e.timestamp)),
|
||||
(
|
||||
@@ -1026,26 +1165,23 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
("hops", PyValue::Int(i128::from(e.hops))),
|
||||
("expires", PyValue::Float(e.expires)),
|
||||
("value", e.value.map(py_number).unwrap_or(PyValue::None)),
|
||||
("used", py_number(e.used)),
|
||||
(
|
||||
"lr_cost",
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
),
|
||||
("interface", PyValue::String(e.interface.clone())),
|
||||
(
|
||||
"interface_hash",
|
||||
e.interface_hash
|
||||
.clone()
|
||||
.map(PyValue::Bytes)
|
||||
.unwrap_or(PyValue::None),
|
||||
),
|
||||
(
|
||||
"state",
|
||||
e.state
|
||||
.map(|state| PyValue::Int(i128::from(state)))
|
||||
.unwrap_or(PyValue::None),
|
||||
),
|
||||
])
|
||||
];
|
||||
fields.extend(e.used.map(|used| ("used", py_number(used))));
|
||||
fields.push((
|
||||
"lr_cost",
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
));
|
||||
fields.push(("interface", PyValue::String(e.interface.clone())));
|
||||
fields.extend(
|
||||
e.interface_hash
|
||||
.clone()
|
||||
.map(|hash| ("interface_hash", PyValue::Bytes(hash))),
|
||||
);
|
||||
fields.extend(
|
||||
e.state
|
||||
.map(|state| ("state", PyValue::Int(i128::from(state)))),
|
||||
);
|
||||
py_dict(fields)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
@@ -1111,6 +1247,60 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::LinkDistribution(entries) => PyValue::Dict(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let int = |value: u64| PyValue::Int(i128::from(value));
|
||||
(
|
||||
PyDictKey::Bytes(e.destination_hash.clone()),
|
||||
py_dict(vec![
|
||||
("active", int(e.active)),
|
||||
("pending", int(e.pending)),
|
||||
("traffic", int(e.traffic)),
|
||||
(
|
||||
"from_ifs",
|
||||
PyValue::List(
|
||||
e.from_interfaces
|
||||
.iter()
|
||||
.map(|hash| PyValue::Bytes(hash.clone()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::KnownDestinations(entries) => PyValue::Dict(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let bytes = |value: &Option<Vec<u8>>| {
|
||||
value.clone().map(PyValue::Bytes).unwrap_or(PyValue::None)
|
||||
};
|
||||
// Upstream keeps the never-used and retained markers as ints.
|
||||
let used = if e.used == -1.0 {
|
||||
PyValue::Int(-1)
|
||||
} else {
|
||||
py_number(e.used)
|
||||
};
|
||||
(
|
||||
PyDictKey::Bytes(e.destination_hash.clone()),
|
||||
PyValue::List(vec![
|
||||
PyValue::Float(e.last_heard),
|
||||
bytes(&e.packet_hash),
|
||||
PyValue::Bytes(e.public_key.clone()),
|
||||
bytes(&e.app_data),
|
||||
used,
|
||||
bytes(&e.stamp),
|
||||
py_number(e.stamp_value),
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::Ok => PyValue::Bool(true),
|
||||
RpcResponse::Error(e) => py_dict(vec![("error", PyValue::String(e.clone()))]),
|
||||
}
|
||||
@@ -1225,6 +1415,14 @@ fn interface_stats_value(
|
||||
("txb", int(t.txb)),
|
||||
("rxs", speed(t.rxs)),
|
||||
("txs", speed(t.txs)),
|
||||
("lrxb", int(t.lrxb)),
|
||||
("ltxb", int(t.ltxb)),
|
||||
("lrxs", speed(t.lrxs)),
|
||||
("ltxs", speed(t.ltxs)),
|
||||
("frxb", int(t.frxb)),
|
||||
("ftxb", int(t.ftxb)),
|
||||
("frxs", speed(t.frxs)),
|
||||
("ftxs", speed(t.ftxs)),
|
||||
("arxb", int(t.arxb)),
|
||||
("atxb", int(t.atxb)),
|
||||
("arxs", speed(t.arxs)),
|
||||
@@ -1258,9 +1456,9 @@ fn interface_stats_value(
|
||||
("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", "rxpkts", "txpkts", "arxpkts", "atxpkts",
|
||||
"prxpkts", "ptxpkts",
|
||||
"lrxb", "ltxb", "lrxs", "ltxs", "frxb", "ftxb", "frxs", "ftxs", "arxb", "atxb",
|
||||
"arxs", "atxs", "arxf", "atxf", "prxb", "ptxb", "prxs", "ptxs", "prxf", "ptxf",
|
||||
"rxpps", "txpps", "rxpkts", "txpkts", "arxpkts", "atxpkts", "prxpkts", "ptxpkts",
|
||||
] {
|
||||
stats.push((key, PyValue::Int(0)));
|
||||
}
|
||||
@@ -1310,6 +1508,10 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
Some(speeds) => PyValue::Float(speeds[index]),
|
||||
None => int(fallback),
|
||||
};
|
||||
let filtered_speed = |index: usize| match e.filtered_speeds {
|
||||
Some(speeds) => PyValue::Float(speeds[index]),
|
||||
None => int(0),
|
||||
};
|
||||
let mut fields = vec![
|
||||
("id", int(e.id)),
|
||||
("name", PyValue::String(e.name.clone())),
|
||||
@@ -1327,8 +1529,12 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
),
|
||||
("rxb", int(e.rx_bytes)),
|
||||
("txb", int(e.tx_bytes)),
|
||||
("frxb", int(e.filtered_rx_bytes)),
|
||||
("ftxb", int(e.filtered_tx_bytes)),
|
||||
("rxs", speed(0, e.rx_rate)),
|
||||
("txs", speed(1, e.tx_rate)),
|
||||
("frxs", filtered_speed(0)),
|
||||
("ftxs", filtered_speed(1)),
|
||||
("arxb", int(e.announce_rx_bytes)),
|
||||
("atxb", int(e.announce_tx_bytes)),
|
||||
("arxs", speed(2, 0)),
|
||||
@@ -1345,6 +1551,7 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
),
|
||||
("arxc", int(e.announces_received)),
|
||||
("atxc", int(e.announces_sent)),
|
||||
("afrxc", int(e.announces_filtered)),
|
||||
("prxc", int(e.path_requests_received)),
|
||||
("ptxc", int(e.path_requests_sent)),
|
||||
("status", PyValue::Bool(e.online)),
|
||||
@@ -1420,6 +1627,41 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
("protocol_violations", int(e.protocol_violations)),
|
||||
("ifac_violations", int(e.ifac_violations)),
|
||||
("packet_filter_hits", int(e.packet_filter_hits)),
|
||||
(
|
||||
"tunnel_id",
|
||||
optional(e.tunnel_id.clone().map(PyValue::Bytes)),
|
||||
),
|
||||
(
|
||||
"remote_transport_id",
|
||||
optional(e.remote_transport_id.clone().map(PyValue::Bytes)),
|
||||
),
|
||||
(
|
||||
"rem_impl",
|
||||
optional(e.remote_implementation.clone().map(PyValue::String)),
|
||||
),
|
||||
(
|
||||
"rem_vers",
|
||||
optional(e.remote_version.as_ref().map(|version| {
|
||||
PyValue::List(
|
||||
version
|
||||
.iter()
|
||||
.map(|v| PyValue::Int(i128::from(*v)))
|
||||
.collect(),
|
||||
)
|
||||
})),
|
||||
),
|
||||
(
|
||||
"rem_is_tn",
|
||||
optional(e.remote_is_transport.map(PyValue::Bool)),
|
||||
),
|
||||
(
|
||||
"rem_dst_cost",
|
||||
optional(e.remote_destination_cost.map(PyValue::Float)),
|
||||
),
|
||||
(
|
||||
"rem_pr_cost",
|
||||
optional(e.remote_pr_cost.map(PyValue::Float)),
|
||||
),
|
||||
];
|
||||
if let Some(parent) = &e.parent_interface_name {
|
||||
fields.push(("parent_interface_name", PyValue::String(parent.clone())));
|
||||
@@ -1522,13 +1764,12 @@ fn py_value_to_response_for_request(
|
||||
py_optional_float(value)?.unwrap_or(0.0),
|
||||
))),
|
||||
RpcRequest::GetActiveLinkCount => Ok(RpcResponse::IntResult(py_required_int(value)?)),
|
||||
// Upstream's link distribution is a stub that answers `{}`.
|
||||
RpcRequest::GetLinkDistribution => match value {
|
||||
PyValue::Dict(_) => Ok(RpcResponse::Ok),
|
||||
_ => Err(RpcError::Deserialize(
|
||||
"expected link distribution dictionary".to_string(),
|
||||
)),
|
||||
},
|
||||
RpcRequest::GetLinkDistribution => Ok(RpcResponse::LinkDistribution(
|
||||
parse_link_distribution(value)?,
|
||||
)),
|
||||
RpcRequest::GetKnownDestinations => Ok(RpcResponse::KnownDestinations(
|
||||
parse_known_destinations(value)?,
|
||||
)),
|
||||
// `None` means no profiler ran; results themselves are not decoded.
|
||||
RpcRequest::GetProfilingResults => Ok(match value {
|
||||
PyValue::None => RpcResponse::StringResult(None),
|
||||
@@ -1598,7 +1839,7 @@ fn parse_path_table(value: &PyValue) -> Result<Vec<PathTableEntry>, RpcError> {
|
||||
hops: dict_get(m, "hops").and_then(py_u8).unwrap_or(0),
|
||||
expires: dict_get(m, "expires").and_then(py_f64).unwrap_or(0.0),
|
||||
value: dict_get(m, "value").and_then(py_f64),
|
||||
used: dict_get(m, "used").and_then(py_f64).unwrap_or(0.0),
|
||||
used: dict_get(m, "used").and_then(py_f64),
|
||||
lr_cost: dict_get(m, "lr_cost").and_then(py_f64),
|
||||
interface: dict_get(m, "interface")
|
||||
.and_then(py_string)
|
||||
@@ -1761,6 +2002,29 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatRpcEntry>,
|
||||
tunnel_state: dict_get(m, "tunnelstate").and_then(py_string),
|
||||
tx_stalled: dict_get(m, "txstalled").and_then(py_bool).unwrap_or(false),
|
||||
tx_buffered: dict_get(m, "txbuffered").and_then(py_u64).unwrap_or(0),
|
||||
filtered_rx_bytes: dict_get(m, "frxb").and_then(py_u64).unwrap_or(0),
|
||||
filtered_tx_bytes: dict_get(m, "ftxb").and_then(py_u64).unwrap_or(0),
|
||||
announces_filtered: dict_get(m, "afrxc").and_then(py_u64).unwrap_or(0),
|
||||
filtered_speeds: match (dict_get(m, "frxs"), dict_get(m, "ftxs")) {
|
||||
(Some(PyValue::Float(rx)), Some(tx)) => Some([*rx, py_f64(tx).unwrap_or(0.0)]),
|
||||
_ => None,
|
||||
},
|
||||
tunnel_id: match dict_get(m, "tunnel_id") {
|
||||
Some(PyValue::Bytes(id)) => Some(id.clone()),
|
||||
_ => None,
|
||||
},
|
||||
remote_transport_id: match dict_get(m, "remote_transport_id") {
|
||||
Some(PyValue::Bytes(id)) => Some(id.clone()),
|
||||
_ => None,
|
||||
},
|
||||
remote_implementation: dict_get(m, "rem_impl").and_then(py_string),
|
||||
remote_version: match dict_get(m, "rem_vers") {
|
||||
Some(PyValue::List(parts)) => parts.iter().map(py_u64).collect(),
|
||||
_ => None,
|
||||
},
|
||||
remote_is_transport: dict_get(m, "rem_is_tn").and_then(py_bool),
|
||||
remote_destination_cost: dict_get(m, "rem_dst_cost").and_then(py_f64),
|
||||
remote_pr_cost: dict_get(m, "rem_pr_cost").and_then(py_f64),
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
@@ -1836,6 +2100,86 @@ fn parse_blackhole_list(value: &PyValue) -> Result<Vec<BlackholeEntry>, RpcError
|
||||
}
|
||||
}
|
||||
|
||||
/// `{destination: {"active", "pending", "traffic", "from_ifs"}}`; nil, a
|
||||
/// Python client's failed call, reads as empty.
|
||||
fn parse_link_distribution(value: &PyValue) -> Result<Vec<LinkDistributionEntry>, RpcError> {
|
||||
let entries = match value {
|
||||
PyValue::None => return Ok(Vec::new()),
|
||||
PyValue::Dict(entries) => entries,
|
||||
_ => {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected link distribution dictionary".to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, entry)| {
|
||||
let PyDictKey::Bytes(hash) = key else {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected destination hash key".to_string(),
|
||||
));
|
||||
};
|
||||
let m = as_dict(entry)?;
|
||||
let count = |key: &str| dict_get(m, key).and_then(py_u64).unwrap_or(0);
|
||||
Ok(LinkDistributionEntry {
|
||||
destination_hash: hash.clone(),
|
||||
active: count("active"),
|
||||
pending: count("pending"),
|
||||
traffic: count("traffic"),
|
||||
from_interfaces: match dict_get(m, "from_ifs") {
|
||||
Some(PyValue::List(hashes)) => hashes
|
||||
.iter()
|
||||
.filter_map(|hash| match hash {
|
||||
PyValue::Bytes(hash) => Some(hash.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `{destination: [last_heard, packet_hash, public_key, app_data, used, stamp,
|
||||
/// stamp_value, lr_cost]}` (Identity.py); an entry without a key is skipped.
|
||||
fn parse_known_destinations(value: &PyValue) -> Result<Vec<KnownDestinationEntry>, RpcError> {
|
||||
let entries = match value {
|
||||
PyValue::None => return Ok(Vec::new()),
|
||||
PyValue::Dict(entries) => entries,
|
||||
_ => {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected known destinations dictionary".to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(entries
|
||||
.iter()
|
||||
.filter_map(|(key, entry)| {
|
||||
let (PyDictKey::Bytes(hash), PyValue::List(fields)) = (key, entry) else {
|
||||
return None;
|
||||
};
|
||||
let field = |index: usize| fields.get(index).unwrap_or(&PyValue::None);
|
||||
let bytes = |index: usize| match field(index) {
|
||||
PyValue::Bytes(bytes) => Some(bytes.clone()),
|
||||
_ => None,
|
||||
};
|
||||
Some(KnownDestinationEntry {
|
||||
destination_hash: hash.clone(),
|
||||
last_heard: py_f64(field(0)).unwrap_or(0.0),
|
||||
packet_hash: bytes(1),
|
||||
public_key: bytes(2)?,
|
||||
app_data: bytes(3),
|
||||
used: py_f64(field(4)).unwrap_or(0.0),
|
||||
stamp: bytes(5),
|
||||
stamp_value: py_f64(field(6)).unwrap_or(0.0),
|
||||
lr_cost: py_f64(field(7)),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn as_dict(value: &PyValue) -> Result<&[(PyDictKey, PyValue)], RpcError> {
|
||||
match value {
|
||||
PyValue::Dict(entries) => Ok(entries),
|
||||
@@ -2710,7 +3054,7 @@ pub enum RpcError {
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Keys Python 1.5.5 `get_interface_stats()` gives every interface
|
||||
/// Keys Python 1.6.1 `get_interface_stats()` gives every interface
|
||||
/// (Reticulum.py); `rnstatus` indexes most of them unguarded.
|
||||
#[cfg(test)]
|
||||
pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
|
||||
@@ -2766,9 +3110,22 @@ pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
|
||||
"protocol_violations",
|
||||
"ifac_violations",
|
||||
"packet_filter_hits",
|
||||
"frxs",
|
||||
"ftxs",
|
||||
"frxb",
|
||||
"ftxb",
|
||||
"afrxc",
|
||||
"announce_queue",
|
||||
"tunnel_id",
|
||||
"remote_transport_id",
|
||||
"rem_impl",
|
||||
"rem_vers",
|
||||
"rem_is_tn",
|
||||
"rem_dst_cost",
|
||||
"rem_pr_cost",
|
||||
];
|
||||
|
||||
/// Totals in every Python 1.5.5 stats dict (Reticulum.py).
|
||||
/// Totals in every Python 1.6.1 stats dict (Reticulum.py).
|
||||
#[cfg(test)]
|
||||
pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
|
||||
"interfaces",
|
||||
@@ -2776,6 +3133,14 @@ pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
|
||||
"txb",
|
||||
"rxs",
|
||||
"txs",
|
||||
"lrxb",
|
||||
"ltxb",
|
||||
"lrxs",
|
||||
"ltxs",
|
||||
"frxb",
|
||||
"ftxb",
|
||||
"frxs",
|
||||
"ftxs",
|
||||
"arxb",
|
||||
"atxb",
|
||||
"arxs",
|
||||
@@ -2866,7 +3231,7 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1234567890.0 + 604800.0,
|
||||
value: None,
|
||||
used: 0.0,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: None,
|
||||
@@ -2935,7 +3300,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_stats_carry_every_python_155_key() {
|
||||
fn interface_stats_carry_every_python_161_key() {
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])).unwrap();
|
||||
let stats = stats_dict(&encoded);
|
||||
@@ -3264,6 +3629,199 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.6.1's filtered, tunnel and remote transport keys decode and
|
||||
/// encode again unchanged; without a remote transport all `rem_*` are nil.
|
||||
#[test]
|
||||
fn python_161_tunnel_and_filtered_keys_round_trip() {
|
||||
let sent = vec![
|
||||
("name", PyValue::String("TCPInterface[Hub]".to_string())),
|
||||
("type", PyValue::String("TCPInterface".to_string())),
|
||||
("status", PyValue::Bool(true)),
|
||||
("frxb", PyValue::Int(31)),
|
||||
("ftxb", PyValue::Int(0)),
|
||||
("frxs", PyValue::Float(8.5)),
|
||||
("ftxs", PyValue::Float(0.0)),
|
||||
("afrxc", PyValue::Int(3)),
|
||||
("tunnel_id", PyValue::Bytes(vec![0xab; 32])),
|
||||
("remote_transport_id", PyValue::Bytes(vec![0xcd; 16])),
|
||||
("rem_impl", PyValue::String("rns".to_string())),
|
||||
(
|
||||
"rem_vers",
|
||||
PyValue::List(vec![PyValue::Int(1), PyValue::Int(6), PyValue::Int(1)]),
|
||||
),
|
||||
("rem_is_tn", PyValue::Bool(true)),
|
||||
("rem_dst_cost", PyValue::Float(8.0)),
|
||||
("rem_pr_cost", PyValue::Float(0.5)),
|
||||
];
|
||||
let upstream = py_dict(vec![(
|
||||
"interfaces",
|
||||
PyValue::List(vec![py_dict(sent.clone())]),
|
||||
)]);
|
||||
let decoded = decode_response_for_request(
|
||||
&encode_umsgpack(&upstream).unwrap(),
|
||||
&RpcRequest::GetInterfaceStats,
|
||||
)
|
||||
.unwrap();
|
||||
let RpcResponse::InterfaceStats(entries) = &decoded else {
|
||||
panic!("wrong variant");
|
||||
};
|
||||
assert_eq!(entries[0].announces_filtered, 3);
|
||||
assert_eq!(entries[0].tunnel_id, Some([0xab; 32]));
|
||||
assert_eq!(
|
||||
entries[0]
|
||||
.remote_transport
|
||||
.as_ref()
|
||||
.map(|r| r.version.clone()),
|
||||
Some(vec![1, 6, 1])
|
||||
);
|
||||
let reencoded = encode_response(&decoded).unwrap();
|
||||
let interface = &interface_dicts(&stats_dict(&reencoded))[0];
|
||||
for (key, value) in &sent {
|
||||
assert_eq!(dict_get(interface, key), Some(value), "{key}");
|
||||
}
|
||||
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])).unwrap();
|
||||
let interface = &interface_dicts(&stats_dict(&encoded))[0];
|
||||
for key in [
|
||||
"tunnel_id",
|
||||
"remote_transport_id",
|
||||
"rem_impl",
|
||||
"rem_vers",
|
||||
"rem_is_tn",
|
||||
"rem_dst_cost",
|
||||
"rem_pr_cost",
|
||||
] {
|
||||
assert_eq!(dict_get(interface, key), Some(&PyValue::None), "{key}");
|
||||
}
|
||||
assert_eq!(dict_get(interface, "frxs"), Some(&PyValue::Int(0)));
|
||||
}
|
||||
|
||||
/// The link and filtered totals follow the transport's counters.
|
||||
#[test]
|
||||
fn interface_stats_totals_carry_link_and_filtered_traffic() {
|
||||
let mut totals = TrafficTotals::default();
|
||||
totals.measured = true;
|
||||
totals.lrxb = 41;
|
||||
totals.ltxb = 42;
|
||||
totals.lrxs = 4.5;
|
||||
totals.frxb = 43;
|
||||
totals.frxs = 1.5;
|
||||
totals.rx_packets = 44;
|
||||
let encoded = encode_interface_stats(&[], None, Some(&totals), None).unwrap();
|
||||
let stats = stats_dict(&encoded);
|
||||
for (key, value) in [
|
||||
("lrxb", PyValue::Int(41)),
|
||||
("ltxb", PyValue::Int(42)),
|
||||
("lrxs", PyValue::Float(4.5)),
|
||||
("ltxs", PyValue::Float(0.0)),
|
||||
("frxb", PyValue::Int(43)),
|
||||
("ftxb", PyValue::Int(0)),
|
||||
("frxs", PyValue::Float(1.5)),
|
||||
("ftxs", PyValue::Float(0.0)),
|
||||
("rxpkts", PyValue::Int(44)),
|
||||
] {
|
||||
assert_eq!(dict_get(&stats, key), Some(&value), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expected bytes are upstream 1.6.1 `umsgpack.packb` of the same values.
|
||||
#[test]
|
||||
fn link_distribution_and_known_destinations_round_trip_as_upstream() {
|
||||
for (request, hex) in [
|
||||
(
|
||||
RpcRequest::GetKnownDestinations,
|
||||
"81a3676574b26b6e6f776e5f64657374696e6174696f6e73",
|
||||
),
|
||||
(
|
||||
RpcRequest::GetLinkDistribution,
|
||||
"81a3676574b16c696e6b5f646973747269627574696f6e",
|
||||
),
|
||||
] {
|
||||
let encoded = encode_request(&request).unwrap();
|
||||
assert_eq!(hex::encode(&encoded), hex);
|
||||
let decoded = decode_request(&encoded).unwrap();
|
||||
assert_eq!(format!("{decoded:?}"), format!("{request:?}"));
|
||||
}
|
||||
|
||||
let distribution = vec![LinkDistributionEntry {
|
||||
destination_hash: vec![0x11; 16],
|
||||
active: 2,
|
||||
pending: 1,
|
||||
traffic: 4096,
|
||||
from_interfaces: vec![vec![0x22; 32]],
|
||||
}];
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::LinkDistribution(distribution.clone())).unwrap();
|
||||
assert_eq!(
|
||||
hex::encode(&encoded),
|
||||
"81c4101111111111111111111111111111111184a661637469766502a770656e64696e6701a77472616666\
|
||||
6963cd1000a866726f6d5f69667391c42022222222222222222222222222222222222222222222222222\
|
||||
22222222222222"
|
||||
);
|
||||
match decode_response_for_request(&encoded, &RpcRequest::GetLinkDistribution).unwrap() {
|
||||
RpcResponse::LinkDistribution(decoded) => assert_eq!(decoded, distribution),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
|
||||
let known = vec![
|
||||
KnownDestinationEntry {
|
||||
destination_hash: vec![0x33; 16],
|
||||
last_heard: 1_700_000_000.5,
|
||||
packet_hash: Some(vec![0x44; 32]),
|
||||
public_key: vec![0x55; 64],
|
||||
app_data: Some(b"app".to_vec()),
|
||||
used: 0.0,
|
||||
stamp: None,
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
},
|
||||
KnownDestinationEntry {
|
||||
destination_hash: vec![0x66; 16],
|
||||
last_heard: 1_700_000_001.25,
|
||||
packet_hash: None,
|
||||
public_key: vec![0x77; 64],
|
||||
app_data: None,
|
||||
used: -1.0,
|
||||
stamp: Some(vec![0x88; 32]),
|
||||
stamp_value: 8.5,
|
||||
lr_cost: Some(3.25),
|
||||
},
|
||||
];
|
||||
let encoded = encode_response(&RpcResponse::KnownDestinations(known.clone())).unwrap();
|
||||
assert_eq!(
|
||||
hex::encode(&encoded),
|
||||
"82c4103333333333333333333333333333333398cb41d954fc40200000c420444444444444444444\
|
||||
4444444444444444444444444444444444444444444444c440555555555555555555555555555555\
|
||||
55555555555555555555555555555555555555555555555555555555555555555555555555555555\
|
||||
555555555555555555c40361707000c000c0c4106666666666666666666666666666666698cb41d9\
|
||||
54fc40500000c0c44077777777777777777777777777777777777777777777777777777777777777\
|
||||
777777777777777777777777777777777777777777777777777777777777777777c0ffc420888888\
|
||||
8888888888888888888888888888888888888888888888888888888888cb4021000000000000cb40\
|
||||
0a000000000000"
|
||||
);
|
||||
match decode_response_for_request(&encoded, &RpcRequest::GetKnownDestinations).unwrap() {
|
||||
RpcResponse::KnownDestinations(decoded) => assert_eq!(decoded, known),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
let row = known[1].to_row().unwrap();
|
||||
assert_eq!(KnownDestinationEntry::from(&row), known[1]);
|
||||
|
||||
// nil, a Python client's failed call, and an empty table read as empty.
|
||||
for (request, bytes) in [
|
||||
(RpcRequest::GetLinkDistribution, [0xc0]),
|
||||
(RpcRequest::GetKnownDestinations, [0x80]),
|
||||
] {
|
||||
let decoded = decode_response_for_request(&bytes, &request).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
decoded,
|
||||
RpcResponse::LinkDistribution(ref e) if e.is_empty()
|
||||
) || matches!(decoded, RpcResponse::KnownDestinations(ref e) if e.is_empty())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Serde sees the wire entry, not the transport type.
|
||||
#[test]
|
||||
fn interface_stats_serialize_as_the_wire_entry() {
|
||||
@@ -3657,7 +4215,7 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1235172690.0,
|
||||
value: None,
|
||||
used: 0.0,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: Some(rns_crypto::sha::sha256(b"TCPInterface[test]").to_vec()),
|
||||
@@ -3712,7 +4270,7 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1235172690.0,
|
||||
value: Some(6.078125),
|
||||
used: 1234567999.5,
|
||||
used: Some(1234567999.5),
|
||||
lr_cost: Some(3.25),
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: Some(rns_crypto::sha::sha256(b"TCPInterface[test]").to_vec()),
|
||||
@@ -3731,7 +4289,7 @@ mod tests {
|
||||
{
|
||||
RpcResponse::PathTable(entries) => {
|
||||
assert_eq!(entries[0].value, Some(6.078125));
|
||||
assert_eq!(entries[0].used, 1234567999.5);
|
||||
assert_eq!(entries[0].used, Some(1234567999.5));
|
||||
assert_eq!(entries[0].lr_cost, Some(3.25));
|
||||
assert_eq!(entries[0].state, Some(2));
|
||||
assert_eq!(
|
||||
@@ -4067,7 +4625,10 @@ mod tests {
|
||||
hex::encode(encode_medium_path_timeout(Some(22.0)).unwrap()),
|
||||
"cb4036000000000000"
|
||||
);
|
||||
assert_eq!(hex::encode(encode_empty_dict().unwrap()), "80");
|
||||
assert_eq!(
|
||||
hex::encode(encode_response(&RpcResponse::LinkDistribution(Vec::new())).unwrap()),
|
||||
"80"
|
||||
);
|
||||
assert_eq!(hex::encode(encode_none().unwrap()), "c0");
|
||||
assert_eq!(hex::encode(encode_optional_bool(Some(true)).unwrap()), "c3");
|
||||
assert_eq!(
|
||||
@@ -4104,7 +4665,7 @@ mod tests {
|
||||
));
|
||||
assert!(matches!(
|
||||
decode("80", RpcRequest::GetLinkDistribution),
|
||||
RpcResponse::Ok
|
||||
RpcResponse::LinkDistribution(ref e) if e.is_empty()
|
||||
));
|
||||
assert!(matches!(
|
||||
decode("c0", RpcRequest::GetProfilingResults),
|
||||
|
||||
@@ -372,7 +372,6 @@ async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result<Vec<u8>, R
|
||||
Err(response) => rpc::encode_response(&response),
|
||||
};
|
||||
}
|
||||
RpcRequest::GetLinkDistribution => return rpc::encode_empty_dict(),
|
||||
RpcRequest::GetProfilingResults => return rpc::encode_none(),
|
||||
RpcRequest::ManageInterface { operation, name } => {
|
||||
let Some(handle) = backend.interface_manager.as_ref().and_then(|m| m.get()) else {
|
||||
@@ -613,7 +612,7 @@ async fn process_rpc_request(
|
||||
hops: e.hops,
|
||||
expires: e.expires,
|
||||
value: e.value,
|
||||
used: e.used,
|
||||
used: Some(e.used),
|
||||
lr_cost: e.lr_cost,
|
||||
interface: e.interface,
|
||||
interface_hash: Some(e.interface_hash.to_vec()),
|
||||
@@ -667,9 +666,27 @@ async fn process_rpc_request(
|
||||
_ => unexpected_transport_response("active link count query"),
|
||||
}
|
||||
}
|
||||
// Upstream answers `{}` when the table cannot be read (Transport.py).
|
||||
RpcRequest::GetLinkDistribution => {
|
||||
match query_transport(transport_tx, TransportQuery::GetLinkDistribution).await {
|
||||
Ok(TransportQueryResponse::LinkDistribution(entries)) => {
|
||||
RpcResponse::LinkDistribution(entries.iter().map(Into::into).collect())
|
||||
}
|
||||
_ => RpcResponse::LinkDistribution(Vec::new()),
|
||||
}
|
||||
}
|
||||
// An error dictionary would become a Python client's table, so a
|
||||
// failure answers `{}` too.
|
||||
RpcRequest::GetKnownDestinations => {
|
||||
match query_transport(transport_tx, TransportQuery::GetKnownDestinations).await {
|
||||
Ok(TransportQueryResponse::KnownDestinations(rows)) => {
|
||||
RpcResponse::KnownDestinations(rows.iter().map(Into::into).collect())
|
||||
}
|
||||
_ => RpcResponse::KnownDestinations(Vec::new()),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetLowestInterfaceBitrate
|
||||
| RpcRequest::GetMediumPathTimeout
|
||||
| RpcRequest::GetLinkDistribution
|
||||
| RpcRequest::GetProfilingResults
|
||||
| RpcRequest::ManageInterface { .. } => {
|
||||
RpcResponse::Error("request needs the control server's state".to_string())
|
||||
@@ -1110,6 +1127,8 @@ mod tests {
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1292,7 +1311,13 @@ mod tests {
|
||||
let rpc_key = b"closed_actor_key".to_vec();
|
||||
let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await;
|
||||
|
||||
for request in all_rpc_requests() {
|
||||
// The table getters answer `{}` instead, as upstream's do.
|
||||
for request in all_rpc_requests().into_iter().filter(|request| {
|
||||
!matches!(
|
||||
request,
|
||||
RpcRequest::GetLinkDistribution | RpcRequest::GetKnownDestinations
|
||||
)
|
||||
}) {
|
||||
let response = rpc_client_request(port, &rpc_key, request).await;
|
||||
assert!(
|
||||
matches!(response, RpcResponse::Error(_)),
|
||||
@@ -1623,6 +1648,20 @@ listener.close()
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
TransportQuery::GetLinkDistribution => {
|
||||
let mut entry =
|
||||
rns_transport::messages::LinkDistributionRpcEntry::default();
|
||||
entry.destination_hash = [0x11; 16];
|
||||
entry.active = 1;
|
||||
TransportQueryResponse::LinkDistribution(vec![entry])
|
||||
}
|
||||
TransportQuery::GetKnownDestinations => {
|
||||
let mut row = rns_transport::store::KnownDestinationRow::new(
|
||||
[0x22; 16], 7.5, [3; 64],
|
||||
);
|
||||
row.used = -1.0;
|
||||
TransportQueryResponse::KnownDestinations(vec![row])
|
||||
}
|
||||
_ => TransportQueryResponse::Error("unexpected".into()),
|
||||
};
|
||||
let _ = response_tx.send(response);
|
||||
@@ -1631,6 +1670,41 @@ listener.close()
|
||||
tx
|
||||
}
|
||||
|
||||
/// The link table and known destinations come from the transport; a
|
||||
/// transport that cannot answer leaves `{}`, as upstream's fallbacks do.
|
||||
#[tokio::test]
|
||||
async fn link_distribution_and_known_destinations_answer_from_the_transport() {
|
||||
let backend = RpcBackend::new(stats_transport(Vec::new()));
|
||||
for request in [
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
] {
|
||||
let reply = respond(request.clone(), &backend).await.unwrap();
|
||||
match rpc::decode_response_for_request(&reply, &request).unwrap() {
|
||||
RpcResponse::LinkDistribution(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].destination_hash, vec![0x11; 16]);
|
||||
assert_eq!(entries[0].active, 1);
|
||||
}
|
||||
RpcResponse::KnownDestinations(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].destination_hash, vec![0x22; 16]);
|
||||
assert_eq!((entries[0].last_heard, entries[0].used), (7.5, -1.0));
|
||||
}
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
let (closed, _) = mpsc::channel(1);
|
||||
let backend = RpcBackend::new(closed);
|
||||
for request in [
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
] {
|
||||
let reply = respond(request, &backend).await.unwrap();
|
||||
assert_eq!(hex::encode(reply), "80");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expected bytes are upstream 1.6.0 replies.
|
||||
#[tokio::test]
|
||||
async fn lowest_bitrate_and_medium_path_timeout_answer_as_upstream() {
|
||||
@@ -1684,10 +1758,6 @@ listener.close()
|
||||
async fn stub_replies_match_upstream() {
|
||||
let backend = RpcBackend::new(stats_transport(Vec::new()));
|
||||
let reply = |request| respond(request, &backend);
|
||||
assert_eq!(
|
||||
hex::encode(reply(RpcRequest::GetLinkDistribution).await.unwrap()),
|
||||
"80"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(reply(RpcRequest::GetProfilingResults).await.unwrap()),
|
||||
"c0"
|
||||
|
||||
@@ -73,14 +73,35 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
table: bool,
|
||||
|
||||
/// Sort the path table by last use, most recent first
|
||||
/// Show in-use paths only
|
||||
#[arg(short = 'a', long)]
|
||||
active: bool,
|
||||
|
||||
/// Show path usage time
|
||||
#[arg(short = 'u', long)]
|
||||
usage: bool,
|
||||
|
||||
/// Show via transport IDs
|
||||
#[arg(short = 'V', long)]
|
||||
vias: bool,
|
||||
|
||||
/// Show path expiry times
|
||||
#[arg(short = 'E', long)]
|
||||
expiry: bool,
|
||||
|
||||
/// Maximum hops to filter path table by
|
||||
#[arg(short = 'm', long, value_name = "hops", allow_negative_numbers = true)]
|
||||
max: Option<i64>,
|
||||
|
||||
/// Minimum value to filter path table by
|
||||
#[arg(
|
||||
short = 'M',
|
||||
long = "min-value",
|
||||
value_name = "value",
|
||||
allow_negative_numbers = true
|
||||
)]
|
||||
min_value: Option<f64>,
|
||||
|
||||
/// Show announce rate info
|
||||
#[arg(short, long)]
|
||||
rates: bool,
|
||||
@@ -126,11 +147,11 @@ struct Args {
|
||||
unblackhole: bool,
|
||||
|
||||
/// Duration of blackhole enforcement in hours
|
||||
#[arg(long)]
|
||||
#[arg(long, value_name = "hours")]
|
||||
duration: Option<f64>,
|
||||
|
||||
/// Reason for blackholing identity
|
||||
#[arg(long)]
|
||||
#[arg(long, value_name = "reason")]
|
||||
reason: Option<String>,
|
||||
|
||||
/// View published blackhole list for remote transport instance
|
||||
@@ -141,6 +162,14 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
json: bool,
|
||||
|
||||
/// Analyze tables
|
||||
#[arg(short = 'A', long)]
|
||||
analyze: bool,
|
||||
|
||||
/// Path to capture file for analyze mode
|
||||
#[arg(long, value_name = "path")]
|
||||
capture: Option<String>,
|
||||
|
||||
/// Hexadecimal hash of the destination
|
||||
destination: Option<String>,
|
||||
|
||||
@@ -180,7 +209,8 @@ pub(crate) async fn main() -> ExitCode {
|
||||
|| args.rates
|
||||
|| destination.is_some()
|
||||
|| args.drop_via
|
||||
|| args.blackholed)
|
||||
|| args.blackholed
|
||||
|| args.analyze)
|
||||
{
|
||||
let help = <Args as clap::CommandFactory>::command()
|
||||
.render_help()
|
||||
@@ -229,8 +259,11 @@ async fn dispatch_local(args: &Args, ctx: &ClientCtx, destination: Option<&str>)
|
||||
if args.unblackhole {
|
||||
return do_unblackhole(ctx, destination).await;
|
||||
}
|
||||
if args.analyze {
|
||||
return analyze_tables(ctx).await;
|
||||
}
|
||||
if args.table {
|
||||
return show_path_table(ctx, destination, args.max, args.json, args.usage).await;
|
||||
return show_path_table(ctx, destination, args).await;
|
||||
}
|
||||
if args.rates {
|
||||
return show_rate_table(ctx, destination, args.json).await;
|
||||
@@ -620,14 +653,50 @@ fn table_filter(destination: Option<&str>) -> Result<Option<[u8; 16]>, ExitCode>
|
||||
}
|
||||
}
|
||||
|
||||
/// rnpath.py, local shared instance.
|
||||
async fn show_path_table(
|
||||
ctx: &ClientCtx,
|
||||
destination: Option<&str>,
|
||||
max_hops: Option<i64>,
|
||||
/// rnpath.py `-A`: the tables are fetched, then the stub upstream ships at
|
||||
/// 1.6.1 prints its line; `--capture` is accepted and unused.
|
||||
async fn analyze_tables(ctx: &ClientCtx) -> ExitCode {
|
||||
for table in [
|
||||
RpcRequest::GetPathTable { max_hops: None },
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetLinkDistribution,
|
||||
] {
|
||||
if let Err(e) = request(ctx, &table).await {
|
||||
tracing::debug!("Shared instance RPC failed while analyzing tables: {e}");
|
||||
}
|
||||
}
|
||||
println!("Not yet implemented");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// How rnpath.py renders `-t`.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct TableView {
|
||||
filter: Option<[u8; 16]>,
|
||||
json: bool,
|
||||
usage: bool,
|
||||
) -> ExitCode {
|
||||
active: bool,
|
||||
vias: bool,
|
||||
expiry: bool,
|
||||
min_value: Option<f64>,
|
||||
}
|
||||
|
||||
impl TableView {
|
||||
fn new(args: &Args, filter: Option<[u8; 16]>) -> Self {
|
||||
Self {
|
||||
filter,
|
||||
json: args.json,
|
||||
usage: args.usage,
|
||||
active: args.active,
|
||||
vias: args.vias,
|
||||
expiry: args.expiry,
|
||||
min_value: args.min_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// rnpath.py, local shared instance.
|
||||
async fn show_path_table(ctx: &ClientCtx, destination: Option<&str>, args: &Args) -> ExitCode {
|
||||
let filter = match table_filter(destination) {
|
||||
Ok(filter) => filter,
|
||||
Err(code) => return code,
|
||||
@@ -637,89 +706,149 @@ async fn show_path_table(
|
||||
Ok(other) => return unexpected(other),
|
||||
Err(e) => return rpc_failed(e),
|
||||
};
|
||||
if let Some(max) = max_hops {
|
||||
if let Some(max) = args.max {
|
||||
table.retain(|e| i64::from(e.hops) <= max);
|
||||
}
|
||||
table.sort_by(|a, b| (&a.interface, a.hops).cmp(&(&b.interface, b.hops)));
|
||||
print_path_table(table, filter, json, usage, now_epoch())
|
||||
print_path_table(table, TableView::new(args, filter), now_epoch())
|
||||
}
|
||||
|
||||
fn print_path_table(
|
||||
mut table: Vec<rpc::PathTableEntry>,
|
||||
filter: Option<[u8; 16]>,
|
||||
json: bool,
|
||||
usage: bool,
|
||||
now: f64,
|
||||
) -> ExitCode {
|
||||
fn print_path_table(mut table: Vec<rpc::PathTableEntry>, view: TableView, now: f64) -> ExitCode {
|
||||
// rnpath.py dumps the whole table, filter or not.
|
||||
if json {
|
||||
if view.json {
|
||||
println!("{}", path_table_json(&table));
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if usage {
|
||||
if view.usage {
|
||||
sort_by_usage(&mut table);
|
||||
}
|
||||
let mut displayed = 0;
|
||||
for entry in &table {
|
||||
if filter.is_none_or(|f| entry.hash == f) {
|
||||
if view.filter.is_none_or(|f| entry.hash == f) {
|
||||
displayed += 1;
|
||||
println!("{}", path_table_line(entry, now));
|
||||
if let Some(line) = path_table_line(entry, view, now) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if filter.is_some() && displayed == 0 {
|
||||
if view.filter.is_some() && displayed == 0 {
|
||||
println!("No path known");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// rnpath.py.
|
||||
fn path_table_line(entry: &rpc::PathTableEntry, now: f64) -> String {
|
||||
format!(
|
||||
"{} {:>3}h via {} on {} expires in {} {}",
|
||||
/// rnpath.py; `None` for a row `-M` or `-a` filters out.
|
||||
fn path_table_line(entry: &rpc::PathTableEntry, view: TableView, now: f64) -> Option<String> {
|
||||
if let Some(min_value) = view.min_value.filter(|v| *v != 0.0) {
|
||||
let value = entry.value.unwrap_or(0.0);
|
||||
if value == 0.0 || value < min_value {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let state = match entry.state {
|
||||
Some(2) => " (R)",
|
||||
Some(1) => " (u)",
|
||||
_ => " (?)",
|
||||
};
|
||||
let usage = match entry.used {
|
||||
None => ", no usage info".to_string(),
|
||||
Some(used) => {
|
||||
if view.active && used == 0.0 {
|
||||
return None;
|
||||
}
|
||||
match (view.usage, used != 0.0) {
|
||||
(true, true) => format!(
|
||||
", last used {} ago",
|
||||
prettytime(PyNum::Float(now - used), false)
|
||||
),
|
||||
(true, false) => ", never used".to_string(),
|
||||
(false, _) => String::new(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let via = if view.vias {
|
||||
format!(
|
||||
" via {}",
|
||||
pretty_hex_rep(entry.via.as_deref().unwrap_or_default())
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let expiry = if view.expiry {
|
||||
format!(
|
||||
" expires in {}",
|
||||
prettytime(PyNum::Float(entry.expires - now), true)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Some(format!(
|
||||
"{} {:>3}h{state}{via} on {}{expiry} {}{usage}",
|
||||
pretty_hex_rep(&entry.hash),
|
||||
entry.hops,
|
||||
pretty_hex_rep(entry.via.as_deref().unwrap_or_default()),
|
||||
entry.interface,
|
||||
prettytime(PyNum::Float(entry.expires - now), true),
|
||||
cost_suffix(entry.value, entry.lr_cost)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// rnpath.py: most recently used first.
|
||||
/// rnpath.py: most recently used first; a table missing `used` stays as it
|
||||
/// is, as upstream's sort raises and is skipped.
|
||||
fn sort_by_usage(entries: &mut [rpc::PathTableEntry]) {
|
||||
entries.sort_by(|a, b| b.used.total_cmp(&a.used));
|
||||
if entries.iter().all(|e| e.used.is_some()) {
|
||||
entries.sort_by(|a, b| b.used.unwrap_or(0.0).total_cmp(&a.used.unwrap_or(0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The `(dv:<value>/lc:<lr_cost>)` tail of an rnpath 1.6.0 table line (rnpath.py).
|
||||
/// The `(dv:<value>/lc:<lr_cost>)` part of an rnpath table line (rnpath.py).
|
||||
fn cost_suffix(value: Option<f64>, lr_cost: Option<f64>) -> String {
|
||||
format!("(dv:{}/lc:{})", pretty_cost(value), pretty_cost(lr_cost))
|
||||
}
|
||||
|
||||
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py).
|
||||
/// Upstream sends `value` and `used` as int 0 when unset, and floats otherwise.
|
||||
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py), keys a
|
||||
/// peer leaves out omitted. Upstream sends `value` and `used` as int 0 when
|
||||
/// unset, and floats otherwise.
|
||||
fn path_table_json(entries: &[rpc::PathTableEntry]) -> String {
|
||||
let rows: Vec<String> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let via = e
|
||||
.via
|
||||
.as_ref()
|
||||
.map(|v| py_json_str(&hex::encode(v)))
|
||||
.unwrap_or_else(|| "null".to_string());
|
||||
format!(
|
||||
"{{\"hash\": {}, \"timestamp\": {}, \"via\": {via}, \"hops\": {}, \"expires\": {}, \"value\": {}, \"used\": {}, \"lr_cost\": {}, \"interface\": {}}}",
|
||||
py_json_str(&hex::encode(&e.hash)),
|
||||
py_float_repr(e.timestamp),
|
||||
e.hops,
|
||||
py_float_repr(e.expires),
|
||||
e.value.map(py_int_or_float).unwrap_or_else(|| "null".to_string()),
|
||||
py_int_or_float(e.used),
|
||||
e.lr_cost.map(py_float_repr).unwrap_or_else(|| "null".to_string()),
|
||||
py_json_str(&e.interface)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let rows: Vec<String> =
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let via = e
|
||||
.via
|
||||
.as_ref()
|
||||
.map(|v| py_json_str(&hex::encode(v)))
|
||||
.unwrap_or_else(|| "null".to_string());
|
||||
let mut fields = vec![
|
||||
format!("\"hash\": {}", py_json_str(&hex::encode(&e.hash))),
|
||||
format!("\"timestamp\": {}", py_float_repr(e.timestamp)),
|
||||
format!("\"via\": {via}"),
|
||||
format!("\"hops\": {}", e.hops),
|
||||
format!("\"expires\": {}", py_float_repr(e.expires)),
|
||||
format!(
|
||||
"\"value\": {}",
|
||||
e.value
|
||||
.map(py_int_or_float)
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
),
|
||||
];
|
||||
fields.extend(
|
||||
e.used
|
||||
.map(|used| format!("\"used\": {}", py_int_or_float(used))),
|
||||
);
|
||||
fields.push(format!(
|
||||
"\"lr_cost\": {}",
|
||||
e.lr_cost
|
||||
.map(py_float_repr)
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
));
|
||||
fields.push(format!("\"interface\": {}", py_json_str(&e.interface)));
|
||||
fields.extend(e.interface_hash.as_ref().map(|hash| {
|
||||
format!("\"interface_hash\": {}", py_json_str(&hex::encode(hash)))
|
||||
}));
|
||||
fields.extend(e.state.map(|state| format!("\"state\": {state}")));
|
||||
format!("{{{}}}", fields.join(", "))
|
||||
})
|
||||
.collect();
|
||||
format!("[{}]", rows.join(", "))
|
||||
}
|
||||
|
||||
@@ -1296,6 +1425,11 @@ async fn run_remote(args: &Args, remote: &str) -> ExitCode {
|
||||
println!("{OUTPUT_RST}{message}");
|
||||
return stop_runtime(handle, ExitCode::from(255)).await;
|
||||
}
|
||||
// rnpath.py analyzes the local tables even with -R.
|
||||
if args.analyze {
|
||||
println!("{OUTPUT_RST}Not yet implemented");
|
||||
return stop_runtime(handle, ExitCode::SUCCESS).await;
|
||||
}
|
||||
let destination = args.destination.as_deref().filter(|d| !d.is_empty());
|
||||
let filter = match table_filter(destination) {
|
||||
Ok(filter) => filter,
|
||||
@@ -1311,7 +1445,7 @@ fn remote_unimplemented(args: &Args) -> Option<&'static str> {
|
||||
Some("Listing blackholed identities on remote instances not yet implemented")
|
||||
} else if args.blackhole || args.unblackhole {
|
||||
Some("Blackholing identity on remote instances not yet implemented")
|
||||
} else if args.table || args.rates {
|
||||
} else if args.analyze || args.table || args.rates {
|
||||
None
|
||||
} else if args.drop_announces {
|
||||
Some("Dropping announce queues on remote instances not yet implemented")
|
||||
@@ -1360,7 +1494,7 @@ async fn remote_management(
|
||||
{
|
||||
Ok(RpcResponse::PathTable(table)) if !table.is_empty() => {
|
||||
print!("{OUTPUT_RST}");
|
||||
print_path_table(table, filter, args.json, args.usage, now)
|
||||
print_path_table(table, TableView::new(args, filter), now)
|
||||
}
|
||||
_ => remote_request_failed(),
|
||||
}
|
||||
@@ -1522,7 +1656,7 @@ mod tests {
|
||||
hops: 1,
|
||||
expires: 0.0,
|
||||
value: None,
|
||||
used,
|
||||
used: Some(used),
|
||||
lr_cost: None,
|
||||
interface: String::new(),
|
||||
interface_hash: None,
|
||||
|
||||
@@ -87,6 +87,10 @@ struct Args {
|
||||
#[arg(short = 'P', long = "pr-stats")]
|
||||
pr_stats: bool,
|
||||
|
||||
/// Show filtered traffic stats.
|
||||
#[arg(short = 'F', long = "filter-stats")]
|
||||
filter_stats: bool,
|
||||
|
||||
/// Show link stats.
|
||||
#[arg(short, long)]
|
||||
link_stats: bool,
|
||||
@@ -103,6 +107,10 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
totals: bool,
|
||||
|
||||
/// Display tunnel information.
|
||||
#[arg(short = 'T', long)]
|
||||
tunnels: bool,
|
||||
|
||||
/// Display packets per second in totals.
|
||||
#[arg(short = 'p', long)]
|
||||
pps: bool,
|
||||
@@ -115,8 +123,8 @@ struct Args {
|
||||
#[arg(short = 'z', long)]
|
||||
profiling: bool,
|
||||
|
||||
/// Sort interfaces by [rate, traffic, rx, tx, rxs, txs, anns, arx, atx, arxc, atxc, held,
|
||||
/// prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf].
|
||||
/// Sort interfaces by [rate, traffic, rx, tx, rxs, txs, frx, ftx, anns, arx, atx, arxc,
|
||||
/// atxc, afrxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf].
|
||||
#[arg(short, long)]
|
||||
sort: Option<String>,
|
||||
|
||||
@@ -925,8 +933,12 @@ fn sort_key(name: &str) -> Option<fn(&Value) -> f64> {
|
||||
"rate" | "bitrate" => |i| k(i, "bitrate"),
|
||||
"rx" => |i| k(i, "rxb"),
|
||||
"tx" => |i| k(i, "txb"),
|
||||
"frx" => |i| k(i, "frxb"),
|
||||
"ftx" => |i| k(i, "ftxb"),
|
||||
"rxs" => |i| k(i, "rxs"),
|
||||
"txs" => |i| k(i, "txs"),
|
||||
"frxs" => |i| k(i, "frxs"),
|
||||
"ftxs" => |i| k(i, "ftxs"),
|
||||
"traffic" => |i| k(i, "rxb") + k(i, "txb"),
|
||||
"anns" | "announces" => {
|
||||
|i| k(i, "incoming_announce_frequency") + k(i, "outgoing_announce_frequency")
|
||||
@@ -935,6 +947,7 @@ fn sort_key(name: &str) -> Option<fn(&Value) -> f64> {
|
||||
"atx" => |i| k(i, "outgoing_announce_frequency"),
|
||||
"arxc" => |i| k(i, "arxc"),
|
||||
"atxc" => |i| k(i, "atxc"),
|
||||
"afrxc" => |i| k(i, "afrxc"),
|
||||
"prx" => |i| k(i, "incoming_pr_frequency"),
|
||||
"ptx" => |i| k(i, "outgoing_pr_frequency"),
|
||||
"prxc" => |i| k(i, "prxc"),
|
||||
@@ -979,8 +992,6 @@ fn render_status(
|
||||
outln!(out, "{}", py_json(stats));
|
||||
return;
|
||||
}
|
||||
let astats = args.announce_stats;
|
||||
let pstats = args.pr_stats;
|
||||
|
||||
let mut interfaces: Vec<Value> = match get(stats, "interfaces") {
|
||||
Some(Value::Array(list)) => list.clone(),
|
||||
@@ -1044,7 +1055,7 @@ fn render_status(
|
||||
}
|
||||
|
||||
if args.totals {
|
||||
render_totals(out, stats, astats, pstats, args.pps);
|
||||
render_totals(out, stats, args);
|
||||
}
|
||||
if args.queues {
|
||||
render_queues(out, stats);
|
||||
@@ -1164,6 +1175,9 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
py_str_opt(get(ifstat, "mtu"))
|
||||
);
|
||||
}
|
||||
if args.tunnels {
|
||||
render_tunnel_lines(out, ifstat, clients);
|
||||
}
|
||||
|
||||
render_radio_lines(out, ifstat);
|
||||
|
||||
@@ -1405,9 +1419,13 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
}
|
||||
if asr {
|
||||
if truthy(get(ifstat, "arxc")) && truthy(get(ifstat, "atxc")) {
|
||||
let filtered = match get(ifstat, "afrxc").filter(|v| truthy(Some(v))) {
|
||||
Some(count) => format!(", {} filtered", py_str(count)),
|
||||
None => String::new(),
|
||||
};
|
||||
outln!(
|
||||
out,
|
||||
" Announces : {}↓ {}↑ total",
|
||||
" Announces : {}↓ {}↑ total{filtered}",
|
||||
py_str_opt(get(ifstat, "arxc")),
|
||||
py_str_opt(get(ifstat, "atxc"))
|
||||
);
|
||||
@@ -1436,6 +1454,73 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
));
|
||||
}
|
||||
outln!(out, " Traffic : {txstat}\n {rxstat}");
|
||||
|
||||
if args.filter_stats {
|
||||
let mut frxstat = format!("↓{}", prettysize(num(get(ifstat, "frxb")).f(), "B"));
|
||||
let mut ftxstat = format!("↑{}", prettysize(num(get(ifstat, "ftxb")).f(), "B"));
|
||||
if has(ifstat, "frxs") && has(ifstat, "ftxs") {
|
||||
frxstat.push_str(&format!(" {}", prettyspeed(num(get(ifstat, "frxs")).f())));
|
||||
ftxstat.push_str(&format!(" {}", prettyspeed(num(get(ifstat, "ftxs")).f())));
|
||||
}
|
||||
outln!(out, " Filtered : {ftxstat}\n {frxstat}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `-T` (rnstatus.py): the tunnel id, and for a tunnel the peer's transport.
|
||||
fn render_tunnel_lines(out: &mut Out, ifstat: &Value, clients: Option<Num>) {
|
||||
let tunnel_id = get(ifstat, "tunnel_id").filter(|v| truthy(Some(v)));
|
||||
if clients.is_none_or(|c| c.f() == 0.0) {
|
||||
let shown = tunnel_id
|
||||
.and_then(Value::as_slice)
|
||||
.map_or_else(|| "None".to_string(), hex::encode);
|
||||
outln!(out, " Tunnel ID : {shown}");
|
||||
}
|
||||
if tunnel_id.is_none() {
|
||||
return;
|
||||
}
|
||||
let remote_id = match get(ifstat, "remote_transport_id").filter(|v| truthy(Some(v))) {
|
||||
Some(id) => pretty_hex_value(id),
|
||||
None => "Unknown".to_string(),
|
||||
};
|
||||
outln!(out, " Rem.Tr.ID : {remote_id}");
|
||||
let transport = if truthy(get(ifstat, "rem_is_tn")) {
|
||||
", transport enabled"
|
||||
} else {
|
||||
", no transport"
|
||||
};
|
||||
let implementation = match get(ifstat, "rem_impl").filter(|v| truthy(Some(v))) {
|
||||
Some(name) => py_str(name),
|
||||
None => "Unknown implementation".to_string(),
|
||||
};
|
||||
let version = match get(ifstat, "rem_vers").filter(|v| truthy(Some(v))) {
|
||||
Some(Value::Array(parts)) => {
|
||||
let parts: Vec<String> = parts.iter().map(py_str).collect();
|
||||
format!(" {}{transport}", parts.join("."))
|
||||
}
|
||||
Some(other) => format!(" {}{transport}", py_str(other)),
|
||||
None => ", unknown version".to_string(),
|
||||
};
|
||||
outln!(out, " Rem.Vers. : {implementation}{version}");
|
||||
let cost = |key: &str, label: &str| match not_none(ifstat, key) {
|
||||
Some(value) => format!("{label} {}", pretty_cost_value(value)),
|
||||
None => format!("{label} ?"),
|
||||
};
|
||||
outln!(
|
||||
out,
|
||||
" Rem.Csts. : {}, {}",
|
||||
cost("rem_dst_cost", "Dst"),
|
||||
cost("rem_pr_cost", "PR")
|
||||
);
|
||||
}
|
||||
|
||||
/// `RNS.prettycost`: "n" for anything but an int or a float.
|
||||
fn pretty_cost_value(value: &Value) -> String {
|
||||
match value {
|
||||
Value::Integer(_) | Value::F32(_) | Value::F64(_) => {
|
||||
pretty_cost(Some(num(Some(value)).f()))
|
||||
}
|
||||
_ => "n".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional radio, Weave and I2P lines (rnstatus.py), with
|
||||
@@ -1551,30 +1636,33 @@ fn render_radio_lines(out: &mut Out, ifstat: &Value) {
|
||||
}
|
||||
|
||||
/// The traffic totals blocks (rnstatus.py).
|
||||
fn render_totals(out: &mut Out, stats: &Value, astats: bool, pstats: bool, pps: bool) {
|
||||
fn render_totals(out: &mut Out, stats: &Value, args: &Args) {
|
||||
let (astats, pstats) = (args.announce_stats, args.pr_stats);
|
||||
let n = |k: &str| num(get(stats, k)).f();
|
||||
let (mut rxb_str, mut txb_str) = pair(n("rxb"), n("txb"));
|
||||
let rxs = n("rxs");
|
||||
let txs = n("txs");
|
||||
let mut rxstat = format!("{rxb_str} {}", prettyspeed(rxs));
|
||||
let mut txstat = format!("{txb_str} {}", prettyspeed(txs));
|
||||
// Data flow: the share of traffic that is neither announces nor path requests.
|
||||
let data_pct = |rx: bool| {
|
||||
let (whole, parts) = if rx {
|
||||
("rxs", n("prxs") + n("arxs"))
|
||||
} else {
|
||||
("txs", n("ptxs") + n("atxs"))
|
||||
};
|
||||
if truthy(get(stats, whole)) {
|
||||
100.0 - (100.0f64).min(parts / n(whole) * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
}
|
||||
};
|
||||
if (pstats || astats)
|
||||
&& ["prxs", "ptxs", "arxs", "atxs"]
|
||||
.iter()
|
||||
.all(|k| has(stats, k))
|
||||
{
|
||||
let parxs = n("prxs") + n("arxs");
|
||||
let patxs = n("ptxs") + n("atxs");
|
||||
let drxpct = if truthy(get(stats, "rxs")) {
|
||||
100.0 - (100.0f64).min(parxs / rxs * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
};
|
||||
let dtxpct = if truthy(get(stats, "txs")) {
|
||||
100.0 - (100.0f64).min(patxs / txs * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
};
|
||||
let (drxpct, dtxpct) = (data_pct(true), data_pct(false));
|
||||
if rxs > 0.0 {
|
||||
rxstat = format!(
|
||||
"{rxstat}, {}% data ({})",
|
||||
@@ -1590,12 +1678,49 @@ fn render_totals(out: &mut Out, stats: &Value, astats: bool, pstats: bool, pps:
|
||||
);
|
||||
}
|
||||
}
|
||||
if pps {
|
||||
if args.pps {
|
||||
rxstat = format!("{rxstat}, {}", prettysize(n("rxpps"), "pps"));
|
||||
txstat = format!("{txstat}, {}", prettysize(n("txpps"), "pps"));
|
||||
}
|
||||
outln!(out, "\n Totals : {txstat}\n {rxstat}");
|
||||
|
||||
if args.filter_stats {
|
||||
let (mut frxstat, mut ftxstat) = pair(n("frxb"), n("ftxb"));
|
||||
if has(stats, "frxs") && has(stats, "ftxs") {
|
||||
frxstat.push_str(&format!(" {}", prettyspeed(n("frxs"))));
|
||||
ftxstat.push_str(&format!(" {}", prettyspeed(n("ftxs"))));
|
||||
}
|
||||
outln!(
|
||||
out,
|
||||
"\n Filtered : {ftxstat}\n {frxstat}"
|
||||
);
|
||||
}
|
||||
|
||||
if args.link_stats
|
||||
&& ["lrxb", "ltxb", "lrxs", "ltxs"]
|
||||
.iter()
|
||||
.all(|k| has(stats, k))
|
||||
{
|
||||
let (lrxb_str, ltxb_str) = pair(n("lrxb"), n("ltxb"));
|
||||
let link_pct = |link: &str, data: f64| {
|
||||
if data != 0.0 && truthy(get(stats, link)) {
|
||||
(100.0f64).min(n(link) / data * 100.0) as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
let drxs = rxs * (data_pct(true) / 100.0);
|
||||
let dtxs = txs * (data_pct(false) / 100.0);
|
||||
outln!(
|
||||
out,
|
||||
"\n Links : {ltxb_str} {}, {}% of data flow\n {lrxb_str} {}, {}% of data flow",
|
||||
prettyspeed(n("ltxs")),
|
||||
link_pct("ltxs", dtxs),
|
||||
prettyspeed(n("lrxs")),
|
||||
link_pct("lrxs", drxs)
|
||||
);
|
||||
}
|
||||
|
||||
let flow_pct = |part: &str, whole: &str| -> i64 {
|
||||
if truthy(get(stats, whole)) && truthy(get(stats, part)) {
|
||||
(100.0f64).min(n(part) / n(whole) * 100.0) as i64
|
||||
@@ -2243,3 +2368,4 @@ fn truncate_ellipsis(s: &str, limit: usize) -> String {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user