tools: add rnx, rnir, rnpkg, and rngcs; serial drivers follow upstream

This commit is contained in:
DeFiDude committed 2026-11-10 15:36:52 -07:00
1 parent ee52f65aaa
commit 49cb222f88
58 files changed
+6159 -1554

No files matched your search

Generated
+12
View File
@@ -1645,6 +1645,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rns-git"
version = "1.4.0"
dependencies = [
"base64",
"hex",
"rmpv",
"rns-identity",
"rns-tools",
"serde_json",
]
[[package]]
name = "rns-identity"
version = "1.4.0"
+1
View File
@@ -11,6 +11,7 @@ members = [
"crates/rns-runtime",
"crates/rns-tools",
"crates/rns-ratkey",
"crates/rns-git",
]
[workspace.package]
+2 -1
View File
@@ -312,7 +312,8 @@ parity with a later Python release.
Known gaps and intentional limits:
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented.
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented;
of the rngit tools only the `rngcs-rs` commit signer exists.
- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM
dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM
bootstrap, destructive EEPROM wipe, and full signing-key management are not
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "rns-git"
description = "Git over Reticulum: rngit-rs and the rngcs-rs commit signer"
publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license-file.workspace = true
autobins = false
[dependencies]
rns-tools = { path = "../rns-tools" }
rns-identity = { workspace = true }
rmpv = { workspace = true }
base64 = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
[[bin]]
name = "rngcs-rs"
path = "src/bin/rngcs-rs.rs"
+3
View File
@@ -0,0 +1,3 @@
fn main() -> std::process::ExitCode {
rns_git::commitsigs::main()
}
+914
View File
@@ -0,0 +1,914 @@
//! `rngcs`: git commit signing with Reticulum identities, a port of
//! `RNS/Utilities/rngit/commitsigs.py@1.6.0`. git drives it as its
//! `gpg.ssh.program`; the signature is an rsg envelope inside an SSHSIG
//! container, so only rngcs (not `ssh-keygen`) can verify it.
use std::io::{Read, Write};
use std::path::Path;
use std::process::ExitCode;
use rmpv::Value;
use rns_identity::identity::Identity;
use rns_tools::rsg::pyfmt::{py_bytes_repr, py_os_error, py_str_repr, py_utf8_error};
use rns_tools::rsg::{self, Message, Valid};
pub const SSHSIG_MAGIC: &[u8] = b"SSHSIG";
pub const SSHSIG_VERSION: u32 = 1;
pub const NAMESPACE_GIT: &[u8] = b"git";
pub const RESERVED_EMPTY: &[u8] = b"";
pub const HASH_ALGORITHM: &[u8] = b"sha256";
const PROG: &str = "rngcs-rs";
const HELP: &str = include_str!("commitsigs/help.txt");
const OPERATIONS: [&str; 4] = ["sign", "find-principals", "check-novalidate", "verify"];
/// `ssh_string`: a big-endian u32 length, then the bytes.
pub fn ssh_string(data: &[u8]) -> Vec<u8> {
let mut out = (data.len() as u32).to_be_bytes().to_vec();
out.extend_from_slice(data);
out
}
fn read_ssh_string(data: &[u8], offset: usize) -> Result<(&[u8], usize), String> {
if offset + 4 > data.len() {
return Err("Not enough data for string length".to_string());
}
let length = u32::from_be_bytes(data[offset..offset + 4].try_into().expect("4 bytes")) as usize;
if offset + 4 + length > data.len() {
return Err("Not enough data for string content".to_string());
}
Ok((&data[offset + 4..offset + 4 + length], offset + 4 + length))
}
/// `create_ssh_signature`.
pub fn create_ssh_signature(
public_key_wire: &[u8],
namespace: &[u8],
reserved: &[u8],
hash_algorithm: &[u8],
signature_data: &[u8],
) -> Vec<u8> {
let mut blob = SSHSIG_MAGIC.to_vec();
blob.extend_from_slice(&SSHSIG_VERSION.to_be_bytes());
for field in [
public_key_wire,
namespace,
reserved,
hash_algorithm,
signature_data,
] {
blob.extend_from_slice(&ssh_string(field));
}
blob
}
/// The fields `parse_ssh_signature` returns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SshSignature {
pub version: u32,
pub public_key: Vec<u8>,
pub namespace: Vec<u8>,
pub reserved: Vec<u8>,
pub hash_algorithm: Vec<u8>,
pub signature_data: Vec<u8>,
}
/// `parse_ssh_signature`; trailing bytes are ignored as upstream does.
pub fn parse_ssh_signature(sig_data: &[u8]) -> Result<SshSignature, String> {
if !sig_data.starts_with(SSHSIG_MAGIC) {
return Err("Invalid SSH signature: missing SSHSIG magic".to_string());
}
let mut offset = SSHSIG_MAGIC.len();
if offset + 4 > sig_data.len() {
return Err("Invalid SSH signature: truncated".to_string());
}
let version = u32::from_be_bytes(sig_data[offset..offset + 4].try_into().expect("4 bytes"));
if version != SSHSIG_VERSION {
return Err(format!("Unsupported SSH signature version: {version}"));
}
offset += 4;
let mut fields = Vec::with_capacity(5);
for _ in 0..5 {
let (field, next) = read_ssh_string(sig_data, offset)?;
fields.push(field.to_vec());
offset = next;
}
let mut fields = fields.into_iter();
let mut next = || fields.next().expect("five fields");
Ok(SshSignature {
version,
public_key: next(),
namespace: next(),
reserved: next(),
hash_algorithm: next(),
signature_data: next(),
})
}
/// `armor_ssh_signature`: standard base64 in 70-character lines.
pub fn armor_ssh_signature(sig_blob: &[u8]) -> String {
use base64::Engine;
let b64 = base64::engine::general_purpose::STANDARD.encode(sig_blob);
let lines: Vec<&str> = b64
.as_bytes()
.chunks(70)
.map(|chunk| std::str::from_utf8(chunk).expect("base64 is ASCII"))
.collect();
format!(
"-----BEGIN SSH SIGNATURE-----\n{}\n-----END SSH SIGNATURE-----\n",
lines.join("\n")
)
}
fn is_py_space(c: char) -> bool {
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}
/// `unarmor_ssh_signature`: collects the stripped lines between the markers,
/// so the indentation git adds in a `gpgsig` header is tolerated.
pub fn unarmor_ssh_signature(armored: &str) -> Result<Vec<u8>, String> {
let mut b64 = String::new();
let mut in_sig = false;
for line in armored.trim_matches(is_py_space).split('\n') {
if line.contains("BEGIN SSH SIGNATURE") {
in_sig = true;
continue;
}
if line.contains("END SSH SIGNATURE") {
break;
}
if in_sig {
b64.push_str(line.trim_matches(is_py_space));
}
}
if b64.is_empty() {
return Err("No signature data found in armored input".to_string());
}
py_b64decode(&b64)
}
/// Python `base64.b64decode` without `validate`: characters outside the
/// alphabet are skipped and padding is checked as `binascii` does.
fn py_b64decode(text: &str) -> Result<Vec<u8>, String> {
if !text.is_ascii() {
return Err("string argument should contain only ASCII characters".to_string());
}
let mut out = Vec::new();
let (mut quad, mut left, mut pads) = (0, 0u8, 0);
for c in text.bytes() {
let v = 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,
b'=' => {
pads += 1;
continue;
}
_ => continue,
};
pads = 0;
match quad {
0 => {
left = v;
quad = 1;
}
1 => {
out.push((left << 2) | (v >> 4));
left = v & 0x0f;
quad = 2;
}
2 => {
out.push((left << 4) | (v >> 2));
left = v & 0x03;
quad = 3;
}
_ => {
out.push((left << 6) | v);
quad = 0;
}
}
}
match quad {
1 => Err(format!(
"Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4",
out.len() / 3 * 4 + 1
)),
2 | 3 if quad + pads < 4 => Err("Incorrect padding".to_string()),
_ => Ok(out),
}
}
/// `get_pubkey_wire_format`: the OpenSSH `ssh-ed25519` public key blob.
pub fn get_pubkey_wire_format(identity: &Identity) -> Vec<u8> {
let mut wire = ssh_string(b"ssh-ed25519");
wire.extend_from_slice(&ssh_string(&identity.get_public_key()[32..]));
wire
}
/// An email taken from a commit header. `DecodeError` is the int 1 upstream
/// returns after failing to decode it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderEmail {
Email(String),
DecodeError,
}
impl std::fmt::Display for HeaderEmail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HeaderEmail::Email(email) => f.write_str(email),
HeaderEmail::DecodeError => f.write_str("1"),
}
}
}
/// Python `bytes.splitlines()`.
fn bytes_splitlines(data: &[u8]) -> Vec<&[u8]> {
let mut lines = Vec::new();
let (mut start, mut i) = (0, 0);
while i < data.len() {
match data[i] {
b'\n' => {
lines.push(&data[start..i]);
start = i + 1;
}
b'\r' => {
lines.push(&data[start..i]);
if data.get(i + 1) == Some(&b'\n') {
i += 1;
}
start = i + 1;
}
_ => {}
}
i += 1;
}
if start < data.len() {
lines.push(&data[start..]);
}
lines
}
/// The `<email>` of a header line, under upstream's bounds.
fn header_email(line: &[u8], target: &[u8]) -> Option<Result<String, ()>> {
let spos = line.iter().position(|b| *b == b'<')?;
let epos = line.iter().position(|b| *b == b'>')?;
if spos > target.len() && epos > spos && epos + 1 < line.len() {
Some(String::from_utf8(line[spos + 1..epos].to_vec()).map_err(|_| ()))
} else {
None
}
}
fn extract_header(message: &[u8], target: &[u8], what: &str) -> HeaderEmail {
for line in bytes_splitlines(message) {
if line.is_empty() {
break;
}
if line.starts_with(target) {
match header_email(line, target) {
Some(Ok(email)) => return HeaderEmail::Email(email),
Some(Err(())) => {
println!("Error while determining {what} from signed commit");
return HeaderEmail::DecodeError;
}
None => {}
}
}
}
HeaderEmail::Email(String::new())
}
/// `extract_commit_author`.
pub fn extract_commit_author(message: &[u8]) -> HeaderEmail {
extract_header(message, b"author ", "author")
}
/// `extract_commit_committer`.
pub fn extract_commit_committer(message: &[u8]) -> HeaderEmail {
extract_header(message, b"committer ", "committer")
}
/// `extract_commit_tagger`: `(tagger, is_tag)`, or `None` where upstream
/// returns the int 1 after a decode failure.
pub fn extract_commit_tagger(message: &[u8]) -> Option<(String, bool)> {
let mut is_tag = false;
for line in bytes_splitlines(message) {
if line.is_empty() {
break;
} else if line.starts_with(b"tag ") {
is_tag = true;
} else if line.starts_with(b"tagger ") && is_tag {
match header_email(line, b"tagger ") {
Some(Ok(email)) => return Some((email, is_tag)),
Some(Err(())) => {
println!("Error while determining tagger from signed commit");
return None;
}
None => {}
}
}
}
Some((String::new(), is_tag))
}
/// `RNS.hexrep(value, delimit=False)` for an unpacked value; `Err` is the
/// exception upstream raises.
fn hexrep_value(value: &Value) -> Result<String, String> {
fn byte(value: &Value) -> Result<String, String> {
match value {
Value::Integer(i) => Ok(match i.as_i64() {
Some(n) if n < 0 => format!("-{:x}", n.unsigned_abs()),
_ => format!("{:02x}", i.as_u64().unwrap_or_default()),
}),
Value::Boolean(b) => Ok(format!("{:02x}", u8::from(*b))),
Value::Nil => Err(
"TypeError: unsupported format string passed to NoneType.__format__".to_string(),
),
other => Err(format!(
"ValueError: Unknown format code 'x' for object of type '{}'",
rsg::py_type_name(other)
)),
}
}
match value {
Value::Binary(b) => Ok(hex::encode(b)),
Value::String(s) if s.as_str().is_some_and(|s| !s.is_empty()) => {
Err("ValueError: Unknown format code 'x' for object of type 'str'".to_string())
}
Value::String(_) => Ok(String::new()),
Value::Array(items) => items.iter().map(byte).collect(),
Value::Map(entries) => entries.iter().map(|(k, _)| byte(k)).collect(),
other => byte(other),
}
}
// ---------------------------------------------------------------------------
// Command line, as upstream's argparse parser with parse_known_args
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Opt {
Help,
Op,
Namespace,
Keyfile,
Principal,
Sigfile,
SshOption,
}
const OPTION_STRINGS: [(&str, Opt); 8] = [
("-h", Opt::Help),
("--help", Opt::Help),
("-Y", Opt::Op),
("-n", Opt::Namespace),
("-f", Opt::Keyfile),
("-I", Opt::Principal),
("-s", Opt::Sigfile),
("-O", Opt::SshOption),
];
impl Opt {
fn lookup(option: &str) -> Option<Opt> {
OPTION_STRINGS
.iter()
.find(|(s, _)| *s == option)
.map(|(_, o)| *o)
}
fn name(self) -> &'static str {
match self {
Opt::Help => "-h/--help",
Opt::Op => "-Y",
Opt::Namespace => "-n",
Opt::Keyfile => "-f",
Opt::Principal => "-I",
Opt::Sigfile => "-s",
Opt::SshOption => "-O",
}
}
}
#[derive(Debug, Default)]
struct Args {
op: Option<String>,
keyfile: Option<String>,
principal: Option<String>,
sigfile: Option<String>,
file: Option<String>,
extras: Vec<String>,
}
enum ParseExit {
Help,
Error(String),
}
struct OptionTuple {
action: Option<Opt>,
option_string: String,
sep: Option<&'static str>,
explicit: Option<String>,
}
fn tuple(
action: Option<Opt>,
option_string: &str,
sep: Option<&'static str>,
explicit: Option<&str>,
) -> OptionTuple {
OptionTuple {
action,
option_string: option_string.to_string(),
sep,
explicit: explicit.map(str::to_string),
}
}
fn partition(arg: &str) -> (&str, Option<&'static str>, Option<&str>) {
match arg.split_once('=') {
Some((prefix, rest)) => (prefix, Some("="), Some(rest)),
None => (arg, None, None),
}
}
/// `ArgumentParser._parse_optional`; `None` is a positional.
fn parse_optional(arg: &str) -> Option<Vec<OptionTuple>> {
if !arg.starts_with('-') {
return None;
}
if let Some(action) = Opt::lookup(arg) {
return Some(vec![tuple(Some(action), arg, None, None)]);
}
if arg.chars().count() == 1 {
return None;
}
let (prefix, sep, explicit) = partition(arg);
if sep.is_some()
&& let Some(action) = Opt::lookup(prefix)
{
return Some(vec![tuple(Some(action), prefix, sep, explicit)]);
}
let mut result = Vec::new();
if arg.starts_with("--") {
for (option, action) in OPTION_STRINGS {
if option.starts_with(prefix) {
result.push(tuple(Some(action), option, sep, explicit));
}
}
} else {
let split = arg.char_indices().nth(2).map_or(arg.len(), |(i, _)| i);
let (short_prefix, short_explicit) = arg.split_at(split);
for (option, action) in OPTION_STRINGS {
if option == short_prefix {
result.push(tuple(Some(action), option, Some(""), Some(short_explicit)));
} else if option.starts_with(prefix) {
result.push(tuple(Some(action), option, sep, explicit));
}
}
}
if !result.is_empty() {
return Some(result);
}
let digits = &arg[1..];
let negative_number = (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()))
|| digits.split_once('.').is_some_and(|(int, frac)| {
int.chars().all(|c| c.is_ascii_digit())
&& !frac.is_empty()
&& frac.chars().all(|c| c.is_ascii_digit())
});
if negative_number || arg.contains(' ') {
return None;
}
Some(vec![tuple(None, arg, None, None)])
}
fn take_option(args: &mut Args, action: Opt, values: &[String]) -> Result<(), ParseExit> {
let value = values.first().cloned();
match action {
Opt::Help => return Err(ParseExit::Help),
Opt::Op => {
let value = value.unwrap_or_default();
if !OPERATIONS.contains(&value.as_str()) {
return Err(ParseExit::Error(format!(
"argument -Y: invalid choice: {} (choose from {})",
py_str_repr(&value),
OPERATIONS.join(", ")
)));
}
args.op = Some(value);
}
Opt::Namespace | Opt::SshOption => {}
Opt::Keyfile => args.keyfile = value,
Opt::Principal => args.principal = value,
Opt::Sigfile => args.sigfile = value,
}
Ok(())
}
/// `ArgumentParser.parse_known_args` for upstream's parser.
fn parse_args(argv: &[String]) -> Result<Args, ParseExit> {
let mut args = Args::default();
let mut options: Vec<Option<Vec<OptionTuple>>> = Vec::with_capacity(argv.len());
let mut pattern: Vec<char> = Vec::with_capacity(argv.len());
let mut after_dashes = false;
for arg in argv {
if after_dashes {
options.push(None);
pattern.push('A');
} else if arg == "--" {
after_dashes = true;
options.push(None);
pattern.push('-');
} else {
let tuples = parse_optional(arg);
pattern.push(if tuples.is_some() { 'O' } else { 'A' });
options.push(tuples);
}
}
let error = |action: Option<Opt>, message: String| {
ParseExit::Error(match action {
Some(action) => format!("argument {}: {message}", action.name()),
None => message,
})
};
let mut file_pending = true;
let mut consume_positionals = |args: &mut Args, start: usize| -> usize {
if !file_pending {
return start;
}
let mut end = start;
while pattern.get(end) == Some(&'-') {
end += 1;
}
if pattern.get(end) == Some(&'A') {
end += 1;
}
while pattern.get(end) == Some(&'-') {
end += 1;
}
if end == start && pattern.get(end) == Some(&'O') {
return start;
}
let mut values: Vec<&String> = argv[start..end].iter().collect();
if let Some(i) = pattern[start..end].iter().position(|c| *c == '-') {
values.remove(i);
}
args.file = values.first().map(|v| v.to_string());
file_pending = false;
end
};
let max_option = pattern.iter().rposition(|c| *c == 'O');
let mut start = 0usize;
while max_option.is_some_and(|max| start <= max) {
let max = max_option.expect("checked");
let mut next_option = start;
while next_option <= max && pattern[next_option] != 'O' {
next_option += 1;
}
if start != next_option {
let end = consume_positionals(&mut args, start);
if end > start {
start = end;
continue;
}
}
if pattern.get(start) != Some(&'O') {
args.extras.extend(argv[start..next_option].iter().cloned());
start = next_option;
}
let tuples = options[start].as_ref().expect("an option");
if tuples.len() > 1 {
let matches: Vec<&str> = tuples.iter().map(|t| t.option_string.as_str()).collect();
return Err(error(
None,
format!(
"ambiguous option: {} could match {}",
argv[start],
matches.join(", ")
),
));
}
let first = &tuples[0];
let (mut action, mut option_string) = (first.action, first.option_string.clone());
let (mut sep, mut explicit) = (first.sep, first.explicit.clone());
let mut actions: Vec<(Opt, Vec<String>)> = Vec::new();
let stop;
loop {
let Some(current) = action else {
args.extras.push(argv[start].clone());
stop = start + 1;
break;
};
let arg_count = usize::from(current != Opt::Help);
if let Some(value) = explicit.clone() {
let short = !option_string[1..].starts_with('-');
if arg_count == 0 && short && !value.is_empty() {
if sep == Some("=") || value.starts_with('-') {
return Err(error(
Some(current),
format!("ignored explicit argument {}", py_str_repr(&value)),
));
}
actions.push((current, Vec::new()));
let mut chars = value.chars();
let flag = chars.next().expect("non-empty");
let rest = chars.as_str();
option_string = format!("-{flag}");
if let Some(next) = Opt::lookup(&option_string) {
action = Some(next);
if rest.is_empty() {
sep = None;
explicit = None;
} else if let Some(stripped) = rest.strip_prefix('=') {
sep = Some("=");
explicit = Some(stripped.to_string());
} else {
sep = Some("");
explicit = Some(rest.to_string());
}
} else {
args.extras.push(format!("-{value}"));
stop = start + 1;
break;
}
} else if arg_count == 1 {
actions.push((current, vec![value]));
stop = start + 1;
break;
} else {
return Err(error(
Some(current),
format!("ignored explicit argument {}", py_str_repr(&value)),
));
}
} else {
if arg_count == 1 && pattern.get(start + 1) != Some(&'A') {
return Err(error(Some(current), "expected one argument".to_string()));
}
actions.push((current, argv[start + 1..start + 1 + arg_count].to_vec()));
stop = start + 1 + arg_count;
break;
}
}
for (action, values) in actions {
take_option(&mut args, action, &values)?;
}
start = stop;
}
let stop = consume_positionals(&mut args, start);
args.extras.extend(argv[stop..].iter().cloned());
if args.op.is_none() {
return Err(error(
None,
"the following arguments are required: -Y".to_string(),
));
}
Ok(args)
}
// ---------------------------------------------------------------------------
// Operations
// ---------------------------------------------------------------------------
/// `RNS.Identity.from_file`, plus the Rust identity envelope rnid-rs reads.
fn load_identity(path: &str) -> Option<Identity> {
let data = std::fs::read(path).ok()?;
if data.len() == 64 {
return Identity::from_private_key(&data).ok();
}
Identity::from_file(Path::new(path)).ok()
}
/// `open(path, "r").read()`: UTF-8 with universal newlines.
fn read_text(path: &str) -> Result<String, String> {
let data = std::fs::read(path).map_err(|e| py_os_error(&e, path))?;
let text =
String::from_utf8(data).map_err(|e| py_utf8_error(e.as_bytes()).unwrap_or_default())?;
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
}
fn read_stdin() -> Vec<u8> {
let mut message = Vec::new();
let _ = std::io::stdin().lock().read_to_end(&mut message);
message
}
fn is_file(path: Option<&str>) -> bool {
path.is_some_and(|path| !path.is_empty() && Path::new(path).is_file())
}
fn read_signature(path: &str) -> Result<SshSignature, String> {
parse_ssh_signature(&unarmor_ssh_signature(&read_text(path)?)?)
}
fn sign(args: &Args) -> u8 {
let keyfile = args.keyfile.as_deref();
if !is_file(keyfile) {
eprintln!("Identity file not found: {}", keyfile.unwrap_or("None"));
return 1;
}
let Some(identity) =
load_identity(keyfile.unwrap_or_default()).filter(Identity::has_private_key)
else {
eprintln!("Error: Could not load identity or identity has no private key");
return 1;
};
let (message, sig_file) = match args.file.as_deref() {
Some(file) if is_file(Some(file)) => match std::fs::read(file) {
Ok(message) => (message, Some(format!("{file}.sig"))),
Err(e) => {
eprintln!("{}", py_os_error(&e, file));
return 1;
}
},
_ => (read_stdin(), None),
};
let rsg = match rsg::create_rsg(&identity, &message[..], false, None) {
Ok(rsg) => rsg,
Err(e) => {
eprintln!("Error creating signature: {e}");
return 1;
}
};
let blob = create_ssh_signature(
&get_pubkey_wire_format(&identity),
NAMESPACE_GIT,
RESERVED_EMPTY,
HASH_ALGORITHM,
&rsg,
);
let armored = armor_ssh_signature(&blob);
match sig_file {
Some(path) => {
if let Err(e) = std::fs::write(&path, &armored) {
eprintln!("Error writing signature file: {}", py_os_error(&e, &path));
return 1;
}
}
None => {
print!("{armored}");
let _ = std::io::stdout().flush();
}
}
0
}
fn find_principals(args: &Args) -> u8 {
let sigfile = args.sigfile.as_deref();
if !is_file(sigfile) {
eprintln!("Error: Signature file not found");
return 1;
}
let armored = match read_text(sigfile.unwrap_or_default()) {
Ok(text) => text,
Err(e) => {
eprintln!("Error reading signature file: {e}");
return 1;
}
};
let ssh_sig = match unarmor_ssh_signature(&armored).and_then(|raw| parse_ssh_signature(&raw)) {
Ok(sig) => sig,
Err(e) => {
eprintln!("Error parsing SSH signature: {e}");
return 1;
}
};
if ssh_sig.namespace != NAMESPACE_GIT {
eprintln!(
"Error: Namespace mismatch: {}",
py_bytes_repr(&ssh_sig.namespace)
);
return 1;
}
let envelope = rsg::extract_signed_rsg_data(&ssh_sig.signature_data).unwrap_or(Value::Nil);
let signer =
match rsg::py_index(&envelope, "meta").and_then(|meta| rsg::py_index(meta, "signer")) {
Ok(signer) => signer,
Err(e) => {
eprintln!("Could not determine signer identity: {e}");
return 1;
}
};
match hexrep_value(signer) {
Ok(hex) => {
println!("{hex}");
0
}
Err(e) => {
eprintln!("{e}");
1
}
}
}
fn check_novalidate(args: &Args) -> u8 {
if !is_file(args.sigfile.as_deref()) {
return 1;
}
match read_signature(args.sigfile.as_deref().unwrap_or_default()) {
Ok(ssh_sig) if ssh_sig.namespace == NAMESPACE_GIT => {
match rsg::extract_signed_rsg_data(&ssh_sig.signature_data) {
Some(signed_data) if rsg::py_truthy(&signed_data) => 0,
_ => 1,
}
}
_ => 1,
}
}
fn verify(args: &Args) -> u8 {
let sigfile = args.sigfile.as_deref();
if !is_file(sigfile) {
eprintln!("Error: Signature file not found");
return 1;
}
let message = read_stdin();
let ssh_sig = match read_signature(sigfile.unwrap_or_default()) {
Ok(sig) => sig,
Err(e) => {
eprintln!("Error parsing signature: {e}");
return 1;
}
};
let mut author = extract_commit_author(&message);
extract_commit_committer(&message);
let Some((tagger, is_tag)) = extract_commit_tagger(&message) else {
eprintln!("TypeError: cannot unpack non-iterable int object");
return 1;
};
if ssh_sig.namespace != NAMESPACE_GIT {
eprintln!("Invalid commit signature namespace");
return 1;
}
let message_value = Value::Binary(message);
let valid = match rsg::validate_rsg(
&ssh_sig.signature_data,
Message::Unpacked(&message_value),
None,
) {
Ok(valid) => valid,
Err(e) => {
eprintln!("{e}");
return 1;
}
};
let Some(Valid { signer_hash, .. }) = valid else {
eprintln!("Invalid signature");
return 1;
};
if is_tag {
author = HeaderEmail::Email(tagger);
}
let signer_hash = hex::encode(signer_hash);
if author != HeaderEmail::Email(signer_hash.clone()) {
println!("Commit not signed by author <{author}>");
return 1;
}
if let Some(principal) = args.principal.as_deref().filter(|p| !p.is_empty())
&& principal != signer_hash
{
eprintln!("Principal mismatch");
return 1;
}
println!(
"Good \"git\" signature for commit, signed with Reticulum Identity key <{signer_hash}>"
);
0
}
/// Run `rngcs-rs` with the process arguments.
pub fn main() -> ExitCode {
let argv: Vec<String> = std::env::args().skip(1).collect();
ExitCode::from(run(&argv))
}
fn run(argv: &[String]) -> u8 {
let args = match parse_args(argv) {
Ok(args) => args,
Err(ParseExit::Help) => {
print!("{HELP}");
return 0;
}
Err(ParseExit::Error(message)) => {
let usage = HELP.split("\n\n").next().unwrap_or_default();
eprint!("{usage}\n{PROG}: error: {message}\n");
return 2;
}
};
if let Some(unknown) = args.extras.iter().find(|arg| !arg.starts_with("-O")) {
eprintln!("Error: Unknown argument: {unknown}");
return 1;
}
match args.op.as_deref() {
Some("sign") => sign(&args),
Some("find-principals") => find_principals(&args),
Some("check-novalidate") => check_novalidate(&args),
_ => verify(&args),
}
}
+20
View File
@@ -0,0 +1,20 @@
usage: rngcs-rs [-h] -Y {sign,find-principals,check-novalidate,verify}
[-n NAMESPACE] [-f KEYFILE] [-I PRINCIPAL] [-s SIGFILE]
[-O SSH_OPTIONS]
[file]
Git commit signer and validator
positional arguments:
file File to sign (for signing)
options:
-h, --help show this help message and exit
-Y {sign,find-principals,check-novalidate,verify}
Operation to perform
-n NAMESPACE Namespace
-f KEYFILE Key file (for signing) or allowed signers file (for
verification)
-I PRINCIPAL Principal identity (for verification)
-s SIGFILE Signature file
-O SSH_OPTIONS SSH options (for git compatibility, ignored)
+4
View File
@@ -0,0 +1,4 @@
//! Git over Reticulum: a port of `RNS/Utilities/rngit` from Reticulum 1.6.0.
pub mod commitsigs;
pub mod util;
+49
View File
@@ -0,0 +1,49 @@
//! Request validators from `RNS/Utilities/rngit/util.py@1.6.0`.
use rns_tools::rsg::pyfmt::py_fromhex;
/// Python `san_ref` (`util.py:36-63`): the ref when it passes upstream's
/// subset of `git check-ref-format`. A ref without `/` (`HEAD`, `main`) and
/// any character below `(` are rejected, as upstream does.
pub fn san_ref(reference: &str) -> Option<&str> {
let r = reference;
if r.starts_with('-') || r.starts_with('/') || r.ends_with('/') || r.ends_with('.') {
return None;
}
if [" ", "..", "/.", "//", "\\"].iter().any(|s| r.contains(s)) || !r.contains('/') {
return None;
}
if r.split('/').any(|component| component.ends_with(".lock")) {
return None;
}
if r.chars().any(|c| (c as u32) < 40) {
return None;
}
if ["\x7f", "~", "^", ":", "?", "*", "[", "@{"]
.iter()
.any(|s| r.contains(s))
|| r == "@"
{
return None;
}
Some(reference)
}
/// Python `san_refs` (`util.py:65-70`) for a list: the list when every ref
/// passes [`san_ref`]. Upstream returns an empty list unchanged, which its
/// callers then treat as a failure because it is falsy.
pub fn san_refs<S: AsRef<str>>(refs: &[S]) -> Option<&[S]> {
refs.iter()
.all(|r| san_ref(r.as_ref()).is_some())
.then_some(refs)
}
/// Python `san_sha` (`util.py:73-77`): at least 40 characters that
/// `bytes.fromhex` accepts. There is no upper bound, and `fromhex` skips
/// whitespace between byte pairs.
pub fn san_sha(sha: &str) -> Option<&str> {
if sha.chars().count() < 40 {
return None;
}
py_fromhex(sha).ok().map(|_| sha)
}
+319 -32
View File
@@ -1,6 +1,6 @@
//! RNode over Android USB host access through JNI to `UsbManager`. The
//! driver supports a single CDC-ACM function or CP2102-compatible USB UART
//! (`10c4:ea60`), with bulk IN and OUT endpoints on the same data interface.
//! RNode, Serial and KISS over Android USB host access through JNI to
//! `UsbManager`. Supported adapters: a single CDC-ACM function, CP2102
//! (`10c4:ea60`), and the FTDI and CH34x drivers of usbserial4a.
//! Setup requires successful 8N1 configuration and matched DTR/RTS assertion,
//! defaulting to 115200 baud; enumeration alone does not establish compatibility.
@@ -14,16 +14,17 @@ use bytes::Bytes;
use tokio::sync::{mpsc, watch};
use crate::android_usb_lifecycle::{
OwnedUsbIo, UsbApplicationQueue, UsbConnectionCleanup, UsbConnectionLifecycle,
OwnedUsbIo, PortIoAction, UsbApplicationQueue, UsbConnectionCleanup, UsbConnectionLifecycle,
UsbDeviceCandidate, UsbDeviceResolutionError, UsbDeviceSelector, UsbInboundOutcome,
UsbInboundState, UsbIoEvent, UsbLeaseTable, UsbRNodeCapabilityStartupError,
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, usb_bulk_read_size,
UsbTxGate, UsbTxPumpExit, UsbWritePhase, UsbWriterBackend, drain_usb_reader_tail,
forward_usb_read_chunk, port_io_action, resolve_usb_device, run_usb_rnode_capability_startup,
run_usb_rnode_startup, run_usb_tx_pump, spawn_owned_usb_io, usb_bulk_read_size,
};
use crate::android_usb_setup::{
UsbEndpointDescriptor, UsbInterfaceDescriptor, configure_serial_port, select_serial_port,
UsbEndpointDescriptor, UsbInterfaceDescriptor, UsbSerialKind, UsbSerialLine,
configure_serial_port, select_serial_port, strip_ftdi_status, usb_read_timeout_ms,
};
#[cfg(test)]
use crate::kiss;
@@ -42,7 +43,6 @@ pub const BAUD_RATE: u32 = 115_200;
const USB_WRITE_QUEUE: usize = 64;
const USB_READ_QUEUE: usize = 64;
const USB_WRITE_TIMEOUT_MS: i32 = 1_000;
const USB_READ_TIMEOUT_MS: i32 = 100;
const USB_DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_millis(USB_WRITE_TIMEOUT_MS as u64);
const USB_STARTUP_ACK_DEADLINE: Duration = Duration::from_secs(2);
const USB_CAPABILITY_RESPONSE_DEADLINE: Duration = Duration::from_secs(5);
@@ -250,10 +250,10 @@ pub struct AndroidUsbConfig {
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
@@ -680,6 +680,9 @@ struct JniUsbReader {
attached: Arc<AtomicBool>,
idle_polls: u8,
read_size: i32,
read_timeout_ms: i32,
/// FTDI prefixes each bulk IN packet of this size with two status bytes.
ftdi_packet_size: Option<usize>,
}
struct PendingAndroidUsbOpen {
@@ -958,14 +961,31 @@ impl UsbReaderBackend for JniUsbReader {
JValue::Object(endpoint.as_obj()),
JValue::Object(buffer.into()),
JValue::Int(read_size),
JValue::Int(USB_READ_TIMEOUT_MS),
JValue::Int(self.read_timeout_ms),
],
)
.map_err(|error| jni_failure(env, "USB bulk read", error))?;
let read = value
.i()
.map_err(|error| jni_failure(env, "USB bulk read result", error))?;
if read <= 0 {
if read > read_size {
return Err(format!(
"USB bulk read returned invalid length {read} (capacity {read_size})"
));
}
let data = if read > 0 {
let bytes = env
.convert_byte_array(buffer)
.map_err(|error| jni_failure(env, "USB read buffer conversion", error))?;
let bytes = &bytes[..read as usize];
match self.ftdi_packet_size {
Some(packet) => strip_ftdi_status(bytes, packet),
None => bytes.to_vec(),
}
} else {
Vec::new()
};
if data.is_empty() {
self.idle_polls = self.idle_polls.saturating_add(1);
if self.idle_polls >= 10 {
self.idle_polls = 0;
@@ -1009,15 +1029,7 @@ impl UsbReaderBackend for JniUsbReader {
return Ok(UsbReadResult::Idle);
}
self.idle_polls = 0;
if read > read_size {
return Err(format!(
"USB bulk read returned invalid length {read} (capacity {read_size})"
));
}
let bytes = env
.convert_byte_array(buffer)
.map_err(|error| jni_failure(env, "USB read buffer conversion", error))?;
Ok(UsbReadResult::Data(bytes[..read as usize].to_vec()))
Ok(UsbReadResult::Data(data))
})
}
}
@@ -1155,7 +1167,7 @@ fn cleanup_failed_android_usb_open(owner: JniUsbConnectionOwner, setup_error: St
fn open_usb_serial_attached(
dev_name: &str,
baud_rate: u32,
line: &UsbSerialLine,
) -> Result<(JniUsbConnectionOwner, JniUsbWriter, JniUsbReader), String> {
let result = with_env(|env| {
let ctx = ensure_app_context(env)?;
@@ -1242,7 +1254,7 @@ fn open_usb_serial_attached(
attached: attached.clone(),
};
let setup = (|| -> Result<(GlobalRef, GlobalRef, i32), String> {
let setup = (|| -> Result<(GlobalRef, GlobalRef, i32, i32, Option<usize>), String> {
let vendor_id = usb_int_property(env, device, "getVendorId")?;
let product_id = usb_int_property(env, device, "getProductId")?;
let iface_count = usb_int_property(env, device, "getInterfaceCount")?;
@@ -1324,7 +1336,7 @@ fn open_usb_serial_attached(
owner.claimed_interfaces.push(reference);
}
configure_serial_port(&port, baud_rate, |request| {
configure_serial_port(&port, line, |request| {
let payload = env
.byte_array_from_slice(request.payload)
.map_err(|error| jni_failure(env, "USB setup payload", error))?;
@@ -1376,13 +1388,16 @@ fn open_usb_serial_attached(
input_endpoint,
output_endpoint,
usb_bulk_read_size(max_packet_size),
usb_read_timeout_ms(vendor_id, product_id),
(port.kind == UsbSerialKind::Ftdi).then_some(max_packet_size.max(3) as usize),
))
})();
let (input_endpoint, output_endpoint, read_size) = match setup {
Ok(endpoints) => endpoints,
Err(error) => return Err(cleanup_failed_android_usb_open(owner, error)),
};
let (input_endpoint, output_endpoint, read_size, read_timeout_ms, ftdi_packet_size) =
match setup {
Ok(endpoints) => endpoints,
Err(error) => return Err(cleanup_failed_android_usb_open(owner, error)),
};
let connection = match owner.connection.as_ref() {
Some(connection) => connection.clone(),
None => {
@@ -1409,6 +1424,8 @@ fn open_usb_serial_attached(
attached,
idle_polls: 0,
read_size,
read_timeout_ms,
ftdi_packet_size,
},
))
});
@@ -1433,7 +1450,8 @@ async fn open_usb_serial(
let panic_device_name = dev_name.clone();
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
let _open_task = tokio::task::spawn_blocking(move || {
let result = open_usb_serial_attached(&dev_name, baud_rate).map(PendingAndroidUsbOpen::new);
let result = open_usb_serial_attached(&dev_name, &UsbSerialLine::eight_n_one(baud_rate))
.map(PendingAndroidUsbOpen::new);
let _ = result_tx.send(result);
});
let pending = result_rx
@@ -1461,6 +1479,240 @@ async fn open_usb_serial(
Ok((io, online))
}
#[cfg(feature = "serial")]
/// The open USB session behind [`AndroidUsbSerialPort`] clones. The last clone
/// releases the interfaces and closes the connection.
struct AndroidUsbSerialSession {
reader: Mutex<Option<JniUsbReader>>,
writer: Mutex<Option<JniUsbWriter>>,
owner: Mutex<Option<JniUsbConnectionOwner>>,
pending: Mutex<Vec<u8>>,
name: String,
}
#[cfg(feature = "serial")]
impl Drop for AndroidUsbSerialSession {
fn drop(&mut self) {
drop(
self.reader
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take(),
);
drop(
self.writer
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take(),
);
let owner = self
.owner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(owner) = owner
&& let UsbConnectionCleanup::Unclosed { owner, .. } = owner.release_and_close()
{
owner.retain_quarantined();
}
}
}
#[cfg(feature = "serial")]
/// A USB serial adapter opened through Android's `UsbManager`, exposed as a
/// `serialport::SerialPort` so the Serial, KISS and AX.25 KISS drivers run
/// over it unchanged (Python's Android interfaces use usbserial4a here).
#[derive(Clone)]
struct AndroidUsbSerialPort(Arc<AndroidUsbSerialSession>);
#[cfg(feature = "serial")]
impl std::io::Read for AndroidUsbSerialPort {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut pending = self
.0
.pending
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if pending.is_empty() {
let mut reader = self
.0
.reader
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let reader = reader
.as_mut()
.ok_or_else(|| std::io::Error::other("USB serial reader released"))?;
match reader.read().map_err(std::io::Error::other)? {
UsbReadResult::Data(bytes) => *pending = bytes,
UsbReadResult::Idle => {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"USB serial read timed out",
));
}
}
}
let n = buf.len().min(pending.len());
buf[..n].copy_from_slice(&pending[..n]);
pending.drain(..n);
Ok(n)
}
}
#[cfg(feature = "serial")]
impl std::io::Write for AndroidUsbSerialPort {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut writer = self
.0
.writer
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let writer = writer
.as_mut()
.ok_or_else(|| std::io::Error::other("USB serial writer released"))?;
match writer.transfer(buf, USB_DEFAULT_WRITE_TIMEOUT) {
Ok(n) if n > 0 => Ok(n as usize),
Ok(n) => Err(std::io::Error::other(format!(
"USB bulk write returned {n}"
))),
Err(error) => Err(std::io::Error::other(format!("{error:?}"))),
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(feature = "serial")]
impl serialport::SerialPort for AndroidUsbSerialPort {
fn name(&self) -> Option<String> {
Some(self.0.name.clone())
}
fn baud_rate(&self) -> serialport::Result<u32> {
Ok(0)
}
fn data_bits(&self) -> serialport::Result<serialport::DataBits> {
Ok(serialport::DataBits::Eight)
}
fn flow_control(&self) -> serialport::Result<serialport::FlowControl> {
Ok(serialport::FlowControl::None)
}
fn parity(&self) -> serialport::Result<serialport::Parity> {
Ok(serialport::Parity::None)
}
fn stop_bits(&self) -> serialport::Result<serialport::StopBits> {
Ok(serialport::StopBits::One)
}
fn timeout(&self) -> Duration {
Duration::ZERO
}
fn set_baud_rate(&mut self, _: u32) -> serialport::Result<()> {
Ok(())
}
fn set_data_bits(&mut self, _: serialport::DataBits) -> serialport::Result<()> {
Ok(())
}
fn set_flow_control(&mut self, _: serialport::FlowControl) -> serialport::Result<()> {
Ok(())
}
fn set_parity(&mut self, _: serialport::Parity) -> serialport::Result<()> {
Ok(())
}
fn set_stop_bits(&mut self, _: serialport::StopBits) -> serialport::Result<()> {
Ok(())
}
fn set_timeout(&mut self, _: Duration) -> serialport::Result<()> {
Ok(())
}
fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
Ok(())
}
fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
Ok(())
}
fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
Ok(true)
}
fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
Ok(true)
}
fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
Ok(false)
}
fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
Ok(true)
}
fn bytes_to_read(&self) -> serialport::Result<u32> {
Ok(0)
}
fn bytes_to_write(&self) -> serialport::Result<u32> {
Ok(0)
}
fn clear(&self, _: serialport::ClearBuffer) -> serialport::Result<()> {
Ok(())
}
fn try_clone(&self) -> serialport::Result<Box<dyn serialport::SerialPort>> {
Ok(Box::new(self.clone()))
}
fn set_break(&self) -> serialport::Result<()> {
Ok(())
}
fn clear_break(&self) -> serialport::Result<()> {
Ok(())
}
}
/// Opener for Serial and KISS interfaces whose `port` names an Android USB
/// device, as in Python's `Android/SerialInterface.py` and
/// `Android/KISSInterface.py` (`usb.get_usb_device(self.port)`).
#[cfg(feature = "serial")]
pub(crate) fn usb_serial_opener(
port: &str,
baud_rate: u32,
data_bits: serialport::DataBits,
parity: serialport::Parity,
stop_bits: serialport::StopBits,
) -> crate::serial_io::PortOpener {
use crate::android_usb_setup::UsbParity;
let device_name = port
.strip_prefix("androidusb://")
.unwrap_or(port)
.to_string();
let line = UsbSerialLine {
baud_rate,
data_bits: match data_bits {
serialport::DataBits::Five => 5,
serialport::DataBits::Six => 6,
serialport::DataBits::Seven => 7,
serialport::DataBits::Eight => 8,
},
parity: match parity {
serialport::Parity::Even => UsbParity::Even,
serialport::Parity::Odd => UsbParity::Odd,
serialport::Parity::None => UsbParity::None,
},
stop_bits: match stop_bits {
serialport::StopBits::Two => 2,
serialport::StopBits::One => 1,
},
};
Arc::new(move || {
reserve_android_usb_opening(&device_name).map_err(std::io::Error::other)?;
let (owner, writer, reader) =
open_usb_serial_attached(&device_name, &line).map_err(std::io::Error::other)?;
Ok(
Box::new(AndroidUsbSerialPort(Arc::new(AndroidUsbSerialSession {
reader: Mutex::new(Some(reader)),
writer: Mutex::new(Some(writer)),
owner: Mutex::new(Some(owner)),
pending: Mutex::new(Vec::new()),
name: device_name.clone(),
}))) as crate::serial_io::Port,
)
})
}
/// Explicitly quiesce and release an Android USB session that failed before
/// publication. Strict capability rejection must never fall through
/// `OwnedUsbIo::drop`, whose only safe fallback is permanent quarantine.
@@ -1791,6 +2043,9 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
let mut drain_reader_tail = false;
let mut terminal_reason = RNodeRuntimeReason::ConnectionLost;
let mut configuration_rejected = None;
let mut port_unresponsive = false;
let mut last_read = std::time::Instant::now();
let mut port_io_check = tokio::time::interval(Duration::from_millis(250));
loop {
tokio::select! {
@@ -1859,6 +2114,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
break;
}
Some(UsbIoEvent::Read(bytes)) => {
last_read = std::time::Instant::now();
let forwarding = forward_usb_read_chunk(
&mut inbound,
&bytes,
@@ -1929,6 +2185,33 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
None => break,
}
}
_ = port_io_check.tick() => {
let last_io = last_read.max(usb.writer.last_write());
match port_io_action(last_io.elapsed()) {
PortIoAction::None => {}
PortIoAction::Detect => {
let writer = usb.writer.clone();
tokio::spawn(async move {
let _ = writer
.request_before(
UsbWritePhase::Detect,
rnode::build_detect_sequence(),
USB_DEFAULT_WRITE_TIMEOUT,
)
.await;
});
}
PortIoAction::Unresponsive => {
tracing::error!(
name = %read_name,
"Connected port became unresponsive, the interface is offline"
);
port_unresponsive = true;
drain_reader_tail = true;
break;
}
}
}
}
}
@@ -2028,7 +2311,11 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report));
return;
}
publisher.connection_lost();
if port_unresponsive {
publisher.connection_failed();
} else {
publisher.connection_lost();
}
snapshot_publisher = Some(publisher);
last_report = Some(report);
tracing::info!(name = %read_name, "Android USB RNode reconnecting");
@@ -2152,7 +2439,7 @@ mod tests {
));
config = AndroidUsbConfig::new("validated", "device");
config.lt_alock = Some(f32::INFINITY);
config.lt_alock = Some(f64::INFINITY);
assert!(matches!(
config.validate(),
Err(rnode::RNodeConfigValidationError::NonFinite {
@@ -32,6 +32,27 @@ const MIN_TRANSFER_TIMEOUT: Duration = Duration::from_millis(1);
const USB_READER_BOUNDARY_POLL_INTERVAL: Duration = Duration::from_millis(1);
const USB_PACKET_WRITE_DEADLINE: Duration = Duration::from_secs(2);
pub(crate) const USB_PROTOCOL_READINESS_DEADLINE: Duration = Duration::from_secs(10);
/// Python Android `RNodeInterface.PORT_IO_TIMEOUT`.
pub(crate) const PORT_IO_TIMEOUT: Duration = Duration::from_secs(3);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PortIoAction {
None,
Detect,
Unresponsive,
}
/// Python Android `RNodeInterface.readLoop`: past one timeout without port
/// I/O it sends DETECT, past three it treats the port as unresponsive.
pub(crate) fn port_io_action(idle: Duration) -> PortIoAction {
if idle > PORT_IO_TIMEOUT * 3 {
PortIoAction::Unresponsive
} else if idle > PORT_IO_TIMEOUT {
PortIoAction::Detect
} else {
PortIoAction::None
}
}
/// Stable identity retained across Android's transient `/dev/bus/usb` names.
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -582,6 +603,7 @@ struct UsbWriteQueueInner {
state: Mutex<UsbWriteQueueState>,
wake: Condvar,
slots: Arc<Semaphore>,
last_write: Mutex<Instant>,
}
#[derive(Clone)]
@@ -601,6 +623,7 @@ impl UsbWriteQueue {
worker_closed: false,
}),
wake: Condvar::new(),
last_write: Mutex::new(Instant::now()),
slots: Arc::new(Semaphore::new(capacity)),
}),
}
@@ -1218,6 +1241,13 @@ where
} else {
write_request(&mut backend, &request, default_timeout)
};
if result.is_ok() {
*queue
.inner
.last_write
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Instant::now();
}
if result.is_ok()
&& let Some(background) = &request.background
{
@@ -1334,6 +1364,17 @@ pub(crate) struct UsbWriterHandle {
}
impl UsbWriterHandle {
/// When the last write request completed, Python's `last_port_io` stamp
/// in `write_mux`.
pub(crate) fn last_write(&self) -> Instant {
*self
.queue
.inner
.last_write
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) async fn request_before(
&self,
phase: UsbWritePhase,
@@ -2503,6 +2544,37 @@ mod tests {
}
}
#[test]
fn idle_port_sends_detect_then_fails_as_unresponsive() {
assert_eq!(port_io_action(Duration::from_secs(3)), PortIoAction::None);
assert_eq!(
port_io_action(Duration::from_millis(3_001)),
PortIoAction::Detect
);
assert_eq!(port_io_action(Duration::from_secs(9)), PortIoAction::Detect);
assert_eq!(
port_io_action(Duration::from_millis(9_001)),
PortIoAction::Unresponsive
);
}
#[tokio::test]
async fn completed_writes_refresh_the_port_io_stamp() {
let events = Arc::new(Mutex::new(Vec::new()));
let io = test_io(ScriptedWriter::new(vec![Ok(4)]), events);
let before = io.writer.last_write();
tokio::time::sleep(Duration::from_millis(20)).await;
io.writer
.request_before(
UsbWritePhase::Detect,
vec![1, 2, 3, 4],
Duration::from_secs(1),
)
.await
.expect("scripted write completes");
assert!(io.writer.last_write() > before);
}
fn test_io(
writer: ScriptedWriter,
events: Arc<Mutex<Vec<&'static str>>>,
+669 -30
View File
@@ -19,6 +19,345 @@ pub(crate) struct UsbInterfaceDescriptor {
pub(crate) enum UsbSerialKind {
Cp210x,
CdcAcm,
Ftdi,
Ch34x,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(feature = "serial"), allow(dead_code))]
pub(crate) enum UsbParity {
None,
Even,
Odd,
}
/// Serial line settings the Android Serial and KISS interfaces pass to
/// usbserial4a: speed, data bits, parity `N`/`E`/`O` and stop bits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct UsbSerialLine {
pub baud_rate: u32,
pub data_bits: u8,
pub parity: UsbParity,
pub stop_bits: u8,
}
impl UsbSerialLine {
pub(crate) const fn eight_n_one(baud_rate: u32) -> Self {
Self {
baud_rate,
data_bits: 8,
parity: UsbParity::None,
stop_bits: 1,
}
}
}
/// usbserial4a 0.4.0 `vidpid4a.FTDI_VID_PID_GROUP`: FTDI chips under other vendors.
const FTDI_VID_PID_GROUP: &[(i32, i32)] = &[
(0x03eb, 0x2109),
(0x0456, 0xf000),
(0x0456, 0xf001),
(0x04d8, 0x000a),
(0x0584, 0xb020),
(0x0647, 0x0100),
(0x06ce, 0x8311),
(0x06d3, 0x0284),
(0x0856, 0xac01),
(0x0856, 0xac02),
(0x0856, 0xac03),
(0x0856, 0xac11),
(0x0856, 0xac12),
(0x0856, 0xac16),
(0x0856, 0xac17),
(0x0856, 0xac18),
(0x0856, 0xac19),
(0x0856, 0xac25),
(0x0856, 0xac26),
(0x0856, 0xac27),
(0x0856, 0xac33),
(0x0856, 0xac34),
(0x0856, 0xac49),
(0x0856, 0xac50),
(0x0856, 0xba02),
(0x093c, 0x0601),
(0x093c, 0x0701),
(0x0acd, 0x0300),
(0x0b39, 0x0103),
(0x0b39, 0x0421),
(0x0c26, 0x0004),
(0x0c26, 0x0018),
(0x0c26, 0x0009),
(0x0c26, 0x000a),
(0x0c26, 0x000b),
(0x0c26, 0x000c),
(0x0c26, 0x000d),
(0x0c26, 0x0010),
(0x0c26, 0x0011),
(0x0c26, 0x0012),
(0x0c26, 0x0013),
(0x0c33, 0x0010),
(0x0c52, 0x2101),
(0x0c52, 0x2102),
(0x0c52, 0x2103),
(0x0c52, 0x2104),
(0x0c52, 0x9020),
(0x0c52, 0x2211),
(0x0c52, 0x2221),
(0x0c52, 0x2212),
(0x0c52, 0x2222),
(0x0c52, 0x2213),
(0x0c52, 0x2223),
(0x0c52, 0x2411),
(0x0c52, 0x2421),
(0x0c52, 0x2431),
(0x0c52, 0x2441),
(0x0c52, 0x2412),
(0x0c52, 0x2422),
(0x0c52, 0x2432),
(0x0c52, 0x2442),
(0x0c52, 0x2413),
(0x0c52, 0x2423),
(0x0c52, 0x2433),
(0x0c52, 0x2443),
(0x0c52, 0x2811),
(0x0c52, 0x2821),
(0x0c52, 0x2831),
(0x0c52, 0x2841),
(0x0c52, 0x2851),
(0x0c52, 0x2861),
(0x0c52, 0x2871),
(0x0c52, 0x2881),
(0x0c52, 0x2812),
(0x0c52, 0x2822),
(0x0c52, 0x2832),
(0x0c52, 0x2842),
(0x0c52, 0x2852),
(0x0c52, 0x2862),
(0x0c52, 0x2872),
(0x0c52, 0x2882),
(0x0c52, 0x2813),
(0x0c52, 0x2823),
(0x0c52, 0x2833),
(0x0c52, 0x2843),
(0x0c52, 0x2853),
(0x0c52, 0x2863),
(0x0c52, 0x2873),
(0x0c52, 0x2883),
(0x0c52, 0xa02a),
(0x0c52, 0xa02b),
(0x0c52, 0xa02c),
(0x0c52, 0xa02d),
(0x0c6c, 0x04b2),
(0x0c7d, 0x0005),
(0x0d3a, 0x0300),
(0x0d46, 0x2020),
(0x0d46, 0x2021),
(0x0dcd, 0x0001),
(0x0f94, 0x0001),
(0x0f94, 0x0005),
(0x0fd8, 0x0001),
(0x103e, 0x03e8),
(0x104d, 0x3000),
(0x104d, 0x3002),
(0x104d, 0x3006),
(0x1209, 0x1002),
(0x1209, 0x1006),
(0x128d, 0x0001),
(0x1342, 0x0202),
(0x1457, 0x5118),
(0x15ba, 0x0003),
(0x15ba, 0x002b),
(0x1781, 0x0c30),
(0x2100, 0x9001),
(0x2100, 0x9e50),
(0x2100, 0x9e51),
(0x2100, 0x9e52),
(0x2100, 0x9e53),
(0x2100, 0x9e54),
(0x2100, 0x9e55),
(0x2100, 0x9e56),
(0x2100, 0x9e57),
(0x2100, 0x9e58),
(0x2100, 0x9e59),
(0x2100, 0x9e5a),
(0x2100, 0x9e5b),
(0x2100, 0x9e5c),
(0x2100, 0x9e5d),
(0x2100, 0x9e5e),
(0x2100, 0x9e5f),
(0x2100, 0x9e60),
(0x2100, 0x9e61),
(0x2100, 0x9e62),
(0x2100, 0x9e63),
(0x2100, 0x9e64),
(0x2100, 0x9e65),
(0x2100, 0x9e66),
(0x2100, 0x9e67),
(0x2100, 0x9e68),
(0x2100, 0x9e69),
(0x2100, 0x9e6a),
(0x1a72, 0x1000),
(0x1a72, 0x1001),
(0x1a72, 0x1002),
(0x1a72, 0x1005),
(0x1a72, 0x1007),
(0x1a72, 0x1008),
(0x1a72, 0x1009),
(0x1a72, 0x100d),
(0x1a72, 0x100e),
(0x1a72, 0x100f),
(0x1a72, 0x1011),
(0x1a72, 0x1012),
(0x1a72, 0x1013),
(0x1a72, 0x1014),
(0x1a72, 0x1015),
(0x1a72, 0x1016),
(0x165c, 0x0002),
(0x1a79, 0x6001),
(0x1b3d, 0x0100),
(0x1b3d, 0x0101),
(0x1b3d, 0x0102),
(0x1b3d, 0x0103),
(0x1b3d, 0x0104),
(0x1b3d, 0x0105),
(0x1b3d, 0x0106),
(0x1b3d, 0x0107),
(0x1b3d, 0x0108),
(0x1b3d, 0x0109),
(0x1b3d, 0x010a),
(0x1b3d, 0x010b),
(0x1b3d, 0x010c),
(0x1b3d, 0x010d),
(0x1b3d, 0x010e),
(0x1b3d, 0x010f),
(0x1b3d, 0x0110),
(0x1b3d, 0x0111),
(0x1b3d, 0x0112),
(0x1b3d, 0x0113),
(0x1b3d, 0x0114),
(0x1b3d, 0x0115),
(0x1b3d, 0x0116),
(0x1b3d, 0x0117),
(0x1b3d, 0x0118),
(0x1b3d, 0x0119),
(0x1b3d, 0x011a),
(0x1b3d, 0x011b),
(0x1b3d, 0x011c),
(0x1b3d, 0x011d),
(0x1b3d, 0x011e),
(0x1b3d, 0x011f),
(0x1b3d, 0x0120),
(0x1b3d, 0x0121),
(0x1b3d, 0x0122),
(0x1b3d, 0x0123),
(0x1b3d, 0x0124),
(0x1b3d, 0x0125),
(0x1b3d, 0x0126),
(0x1b3d, 0x0127),
(0x1b3d, 0x0128),
(0x1b3d, 0x0129),
(0x1b3d, 0x012a),
(0x1b3d, 0x012b),
(0x1b3d, 0x012c),
(0x1b3d, 0x012e),
(0x1b3d, 0x012f),
(0x1b3d, 0x0130),
(0x1b91, 0x0064),
(0x1bc9, 0x6001),
(0x1c0c, 0x0102),
(0x1cf1, 0x0001),
(0x1cf1, 0x0041),
(0x0483, 0x3746),
(0x0483, 0x3747),
(0x5050, 0x0100),
(0x5050, 0x0101),
(0x5050, 0x0102),
(0x5050, 0x0103),
(0x5050, 0x0104),
(0x5050, 0x0105),
(0x5050, 0x0106),
(0x5050, 0x0107),
(0x5050, 0x0300),
(0x5050, 0x0301),
(0x5050, 0x0400),
(0x5050, 0x0500),
(0x5050, 0x0700),
(0x5050, 0x0800),
(0x5050, 0x0900),
(0x5050, 0x0a00),
(0x5050, 0x0b00),
(0x5050, 0x0c00),
(0x5050, 0x0d00),
(0x5050, 0x0e00),
(0x5050, 0x0f00),
(0x5050, 0x1000),
(0x5050, 0x8000),
(0x5050, 0x8001),
(0x5050, 0x8002),
(0x5050, 0x8003),
(0x5050, 0x8004),
(0x5050, 0x8005),
(0x9e88, 0x9e8f),
(0xdeee, 0x0300),
(0xdeee, 0x02ff),
(0xdeee, 0x0302),
(0xdeee, 0x0303),
(0x05d1, 0x1001),
(0x05d1, 0x1002),
(0x05d1, 0x1003),
(0x05d1, 0x1004),
(0x05d1, 0x1011),
(0x05d1, 0x1013),
(0x05d1, 0x2001),
(0x05d1, 0x2002),
(0x05d1, 0x2003),
(0x05d1, 0x2011),
(0x05d1, 0x2012),
(0x05d1, 0x2021),
(0x05d1, 0x2022),
(0x05d1, 0x2023),
(0x05d1, 0x2024),
(0x05d1, 0x3011),
(0x05d1, 0x3012),
(0x05d1, 0x5001),
(0x05d1, 0x6001),
(0x05d1, 0x7001),
(0x05d1, 0x8001),
(0x05d1, 0x8002),
(0x05d1, 0x8003),
(0x05d1, 0x8004),
(0x05d1, 0x9001),
(0x05d1, 0x9002),
(0x05d1, 0x9003),
(0x05d1, 0x9004),
(0x05d1, 0x9005),
(0x05d1, 0x9006),
(0x05d1, 0x9007),
(0x05d1, 0x9008),
];
/// usbserial4a `serial4a.get_serial_port` driver choice, with RNS's override
/// of the Qinheng `1a86:55d4` (CH9102) to the CDC driver
/// (`RNS/Interfaces/Android/KISSInterface.py` `open_port`).
fn usbserial4a_kind(vendor_id: i32, product_id: i32) -> Option<UsbSerialKind> {
if vendor_id == 0x1a86 && product_id == 0x55d4 {
None
} else if vendor_id == 0x0403 || FTDI_VID_PID_GROUP.contains(&(vendor_id, product_id)) {
Some(UsbSerialKind::Ftdi)
} else if vendor_id == 0x1a86 || (vendor_id, product_id) == (0x4348, 0x5523) {
Some(UsbSerialKind::Ch34x)
} else {
None
}
}
/// Python Android `open_port` per-chip `USB_READ_TIMEOUT_MILLIS`.
pub(crate) const fn usb_read_timeout_ms(vendor_id: i32, product_id: i32) -> i32 {
if vendor_id == 0x10c4 || (vendor_id == 0x1a86 && product_id == 0x55d4) {
12
} else {
100
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -55,6 +394,28 @@ pub(crate) fn select_serial_port(
product_id: i32,
interfaces: &[UsbInterfaceDescriptor],
) -> Result<UsbSerialPort, String> {
if let Some(kind) = usbserial4a_kind(vendor_id, product_id) {
// usbserial4a uses interface 0 for FTDI and the last interface for
// CH34x, with its bulk IN and OUT endpoints.
let data_interface = match kind {
UsbSerialKind::Ftdi => 0,
_ => interfaces
.len()
.checked_sub(1)
.ok_or("USB device has no interfaces")?,
};
let interface = &interfaces[data_interface];
let (input_endpoint, output_endpoint) = bulk_pair(interface)
.ok_or_else(|| "No USB serial interface with bulk IN and OUT endpoints".to_string())?;
return Ok(UsbSerialPort {
kind,
data_interface,
control_interface: data_interface,
control_number: interface.number,
input_endpoint,
output_endpoint,
});
}
// Heltec V3 uses the standard CP2102/CP2102N VID/PID. Do not apply
// Silicon Labs requests to every vendor-specific interface or VID.
let cp210x = vendor_id == 0x10c4 && product_id == 0xea60;
@@ -118,17 +479,26 @@ pub(crate) struct UsbControlRequest<'a> {
pub payload: &'a [u8],
}
/// Configure the UART. Device-to-host requests (request type bit 7) carry a
/// zeroed payload of the expected length; every request must transfer exactly
/// its payload length.
pub(crate) fn configure_serial_port(
port: &UsbSerialPort,
baud_rate: u32,
line: &UsbSerialLine,
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
) -> Result<(), String> {
let baud_rate = line.baud_rate;
if baud_rate == 0 {
return Err("USB serial baud rate must be nonzero".into());
}
match port.kind {
UsbSerialKind::Ftdi => return configure_ftdi(port, line, transfer),
UsbSerialKind::Ch34x => return configure_ch34x(line, transfer),
_ => {}
}
let request_type = match port.kind {
UsbSerialKind::Cp210x => 0x41,
UsbSerialKind::CdcAcm => 0x21,
_ => 0x21,
};
let mut send = |request, value, payload: &[u8]| {
let setup = UsbControlRequest {
@@ -167,20 +537,288 @@ pub(crate) fn configure_serial_port(
send(0x07, 0x0303, &[])?;
}
UsbSerialKind::CdcAcm => {
// SET_LINE_CODING: rate, stop-bit code, parity code, data bits.
let mut line_coding = [0u8; 7];
line_coding[..4].copy_from_slice(&baud_rate.to_le_bytes());
line_coding[6] = 8;
send(0x20, 0, &line_coding)?; // SET_LINE_CODING, 8N1.
send(0x22, 3, &[])?; // SET_CONTROL_LINE_STATE, DTR and RTS.
line_coding[4] = if line.stop_bits == 2 { 2 } else { 0 };
line_coding[5] = match line.parity {
UsbParity::None => 0,
UsbParity::Odd => 1,
UsbParity::Even => 2,
};
line_coding[6] = line.data_bits;
// usbserial4a `CdcAcmSerial.open`: DTR and RTS, then the coding.
send(0x22, 3, &[])?; // SET_CONTROL_LINE_STATE
send(0x20, 0, &line_coding)?;
}
UsbSerialKind::Ftdi | UsbSerialKind::Ch34x => unreachable!("handled above"),
}
Ok(())
}
fn control(
transfer: &mut impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
request_type: u8,
request: u8,
value: u16,
index: u16,
payload: &[u8],
) -> Result<(), String> {
let setup = UsbControlRequest {
request_type,
request,
value,
index,
payload,
};
let transferred = transfer(&setup)
.map_err(|error| format!("USB serial setup request 0x{request:02x}: {error}"))?;
if transferred != payload.len() as i32 {
return Err(format!(
"USB serial setup request 0x{request:02x} transferred {transferred} bytes; expected {}",
payload.len()
));
}
Ok(())
}
/// usbserial4a `FtdiSerial._reconfigure_port`: SET_BAUDRATE, SET_DATA, then
/// flow control off. wIndex carries the port (`interface id + 1`).
fn configure_ftdi(
port: &UsbSerialPort,
line: &UsbSerialLine,
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
) -> Result<(), String> {
const OUT: u8 = 0x40;
let port_index = port.control_number + 1;
let (value, index) = ftdi_baud_divisor(line.baud_rate, port_index)?;
control(&mut transfer, OUT, 0x03, value, index, &[])?;
let parity: u16 = match line.parity {
UsbParity::None => 0,
UsbParity::Odd => 1,
UsbParity::Even => 2,
};
let stop: u16 = if line.stop_bits == 2 { 2 } else { 0 };
let data = u16::from(line.data_bits & 0x0f) | (parity << 8) | (stop << 11);
control(&mut transfer, OUT, 0x04, data, port_index, &[])?;
control(&mut transfer, OUT, 0x02, 0, port_index, &[])
}
/// usbserial4a `FtdiSerial._convert_baudrate` (3 % tolerance in
/// `_set_baudrate`). usbserial4a tests `_is_legacy`, `_has_mpsse` and
/// `_is_H_series` without calling them, so all three are always true; the
/// wire values follow that.
fn ftdi_baud_divisor(baud_rate: u32, port_index: u16) -> Result<(u16, u16), String> {
const REF_BASE: u64 = 3_000_000;
const REF_HIGH: u64 = 12_000_000;
let baud = u64::from(baud_rate);
if baud < (2 * REF_BASE) / (2 * 16_384 + 1) {
return Err(format!("Invalid FTDI baud rate {baud_rate} (too low)"));
}
let (refclock, hispeed) = if baud > REF_BASE {
if baud > REF_HIGH {
return Err(format!("Invalid FTDI baud rate {baud_rate} (too high)"));
}
(REF_HIGH, true)
} else {
(REF_BASE, false)
};
const AM_ADJUST_UP: [u64; 8] = [0, 0, 0, 1, 0, 3, 2, 1];
const AM_ADJUST_DN: [u64; 8] = [0, 0, 0, 1, 0, 1, 2, 3];
const FRAC_CODE: [u64; 8] = [0, 3, 2, 4, 1, 5, 6, 7];
let mut divisor = (refclock * 8) / baud;
divisor -= AM_ADJUST_DN[(divisor & 7) as usize];
let (mut best_divisor, mut best_baud, mut best_diff) = (0, 0, 0);
for i in 0..2 {
let mut try_divisor = divisor + i;
if !hispeed {
if try_divisor <= 8 {
try_divisor = 8;
} else if try_divisor < 12 {
try_divisor = 12;
} else if divisor < 16 {
try_divisor = 16;
} else {
try_divisor += AM_ADJUST_UP[(try_divisor & 7) as usize];
try_divisor = try_divisor.min(0x1fff8);
}
}
let estimate = (refclock * 8 + try_divisor / 2) / try_divisor;
let diff = estimate.abs_diff(baud);
if i == 0 || diff < best_diff {
(best_divisor, best_baud, best_diff) = (try_divisor, estimate, diff);
if diff == 0 {
break;
}
}
}
let delta = 100.0 * best_baud.abs_diff(baud) as f64 / baud as f64;
if delta > 3.0 {
return Err(format!(
"FTDI baud rate tolerance exceeded: {delta:.2}% (wanted {baud_rate}, achievable {best_baud})"
));
}
let mut encoded = (best_divisor >> 3) | (FRAC_CODE[(best_divisor & 7) as usize] << 14);
if encoded == 1 {
encoded = 0;
} else if encoded == 0x4001 {
encoded = 1;
}
let value = (encoded & 0xffff) as u16;
let mut index = (((encoded >> 8) & 0xff00) as u16) | port_index;
if hispeed {
index |= 1 << 9;
}
Ok((value, index))
}
/// usbserial4a `Ch34xSerial._init_device` and `_reconfigure_port`.
fn configure_ch34x(
line: &UsbSerialLine,
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
) -> Result<(), String> {
const OUT: u8 = 0x40;
const IN: u8 = 0xc0;
let write = |transfer: &mut _, value, index| control(transfer, OUT, 0x9a, value, index, &[]);
let check = |transfer: &mut _| control(transfer, IN, 0x95, 0x0706, 0, &[0, 0]);
control(&mut transfer, OUT, 0xa1, 0xc29c, 0xb2b9, &[])?;
control(&mut transfer, OUT, 0xa4, 0xdf, 0, &[])?;
control(&mut transfer, OUT, 0xa4, 0x9f, 0, &[])?;
check(&mut transfer)?;
write(&mut transfer, 0x2727, 0)?;
write(&mut transfer, 0x1312, 0xb282)?;
write(&mut transfer, 0x0f2c, 0x0008)?;
write(&mut transfer, 0x2518, 0x00c3)?;
check(&mut transfer)?;
write(&mut transfer, 0x2727, 0)?;
let (index1312, index0f2c) = match line.baud_rate {
0..=300 => (0xd980, 0xeb),
301..=600 => (0x6481, 0x76),
601..=1_200 => (0xb281, 0x3b),
1_201..=2_400 => (0xd981, 0x1e),
2_401..=4_800 => (0x6482, 0x0f),
4_801..=9_600 => (0xb282, 0x08),
9_601..=19_200 => (0xd982, 0x07),
19_201..=38_400 => (0x6483, 0x07),
38_401..=57_600 => (0x9883, 0x07),
57_601..=115_200 => (0xcc83, 0x07),
115_201..=230_400 => (0xe683, 0x07),
230_401..=460_800 => (0xf383, 0x07),
460_801..=921_600 => (0xf387, 0x07),
_ => return Err(format!("CH34x baud rate {} out of range", line.baud_rate)),
};
write(&mut transfer, 0x1312, index1312)?;
write(&mut transfer, 0x0f2c, index0f2c)?;
check(&mut transfer)?;
write(&mut transfer, 0x2727, 0)?;
let mut lcr: u16 = 0x80 | 0x40;
lcr |= match line.data_bits {
5 => 0x00,
6 => 0x01,
7 => 0x02,
8 => 0x03,
bits => return Err(format!("CH34x cannot use {bits} data bits")),
};
lcr |= match line.parity {
UsbParity::None => 0,
UsbParity::Odd => 0x08,
UsbParity::Even => 0x18,
};
if line.stop_bits == 2 {
lcr |= 0x04;
}
write(&mut transfer, 0x2518, lcr)?;
check(&mut transfer)?;
write(&mut transfer, 0x2727, 0)?;
check(&mut transfer)?;
write(&mut transfer, 0x2727, 0)
}
/// usbserial4a `FtdiSerial._filterStatusBytes`: every bulk IN packet starts
/// with two modem-status bytes.
pub(crate) fn strip_ftdi_status(raw: &[u8], max_packet_size: usize) -> Vec<u8> {
let mut payload = Vec::with_capacity(raw.len());
for packet in raw.chunks(max_packet_size.max(3)) {
if packet.len() > 2 {
payload.extend_from_slice(&packet[2..]);
}
}
payload
}
#[cfg(test)]
mod tests {
use super::*;
/// Every control request usbserial4a 0.4.0 issues when upstream's Android
/// interfaces open an FTDI, CH34x or force-CDC CH9102 adapter.
#[test]
fn usb_serial_setup_matches_usbserial4a() {
let golden: serde_json::Value = serde_json::from_str(include_str!(
"../tests/fixtures/android_usb_serial/cases.json"
))
.unwrap();
assert_eq!(golden["usbserial4a_version"], "0.4.0");
for case in golden["cases"].as_array().unwrap() {
let vid = case["vid"].as_i64().unwrap() as i32;
let pid = case["pid"].as_i64().unwrap() as i32;
let descriptors: Vec<_> = match case["device"].as_str().unwrap() {
"ch340" => vec![interface(0, 0xff, 0, &[(0x80, 3), (0x80, 2), (0, 2)])],
"ch9102_forced_cdc" => vec![
interface(0, 2, 2, &[(0x80, 3)]),
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]),
],
_ => vec![interface(0, 0xff, 0, &[(0x80, 2), (0, 2)])],
};
let port = select_serial_port(vid, pid, &descriptors).expect("selectable");
let line = UsbSerialLine {
baud_rate: case["baud"].as_u64().unwrap() as u32,
data_bits: case["databits"].as_u64().unwrap() as u8,
parity: match case["parity"].as_str().unwrap() {
"E" => UsbParity::Even,
"O" => UsbParity::Odd,
_ => UsbParity::None,
},
stop_bits: case["stopbits"].as_u64().unwrap() as u8,
};
let mut requests = Vec::new();
configure_serial_port(&port, &line, |request| {
let input = request.request_type & 0x80 != 0;
requests.push(serde_json::json!([
request.request_type,
request.request,
request.value,
request.index,
if input {
String::new()
} else {
hex::encode(request.payload)
},
request.payload.len(),
]));
Ok(request.payload.len() as i32)
})
.unwrap();
assert_eq!(&requests, case["requests"].as_array().unwrap(), "{case}");
}
}
#[test]
fn ftdi_status_bytes_are_stripped_per_packet() {
let raw: Vec<u8> = [vec![0x01, 0x60], vec![7; 62], vec![0x01, 0x60], vec![9, 9]].concat();
assert_eq!(
strip_ftdi_status(&raw, 64),
[vec![7; 62], vec![9, 9]].concat()
);
assert!(strip_ftdi_status(&[0x01, 0x60], 64).is_empty());
assert_eq!(usb_read_timeout_ms(0x10c4, 0xea60), 12);
assert_eq!(usb_read_timeout_ms(0x1a86, 0x55d4), 12);
assert_eq!(usb_read_timeout_ms(0x0403, 0x6001), 100);
}
fn interface(
number: u16,
class: i32,
@@ -214,16 +852,11 @@ mod tests {
#[test]
fn cp210x_setup_is_scoped_and_uses_vendor_requests_without_reset() {
let descriptors = [interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])];
for (vid, pid) in [
(0x10c4, 0xea61),
(0x0403, 0x6001),
(0x1a86, 0x7523),
(0x303a, 0x1001),
] {
for (vid, pid) in [(0x10c4, 0xea61), (0x303a, 0x1001)] {
assert!(select_serial_port(vid, pid, &descriptors).is_err());
}
let mut requests = Vec::new();
configure_serial_port(&cp210x(), 115_200, |request| {
configure_serial_port(&cp210x(), &UsbSerialLine::eight_n_one(115_200), |request| {
requests.push((
request.request_type,
request.request,
@@ -268,7 +901,7 @@ mod tests {
assert_eq!(port.control_interface, 1);
assert_eq!((port.input_endpoint, port.output_endpoint), (1, 2));
let mut requests = Vec::new();
configure_serial_port(&port, 9_600, |request| {
configure_serial_port(&port, &UsbSerialLine::eight_n_one(9_600), |request| {
requests.push((
request.request_type,
request.request,
@@ -282,8 +915,8 @@ mod tests {
assert_eq!(
requests,
vec![
(0x21, 0x20, 0, 6, vec![0x80, 0x25, 0, 0, 0, 0, 8]),
(0x21, 0x22, 3, 6, vec![]),
(0x21, 0x20, 0, 6, vec![0x80, 0x25, 0, 0, 0, 0, 8]),
]
);
}
@@ -333,28 +966,34 @@ mod tests {
for fail_at in 0..count {
for failure in 0..4 {
let mut called = 0;
let result = configure_serial_port(&port, 115_200, |request| {
let index = called;
called += 1;
let length = request.payload.len() as i32;
if index != fail_at {
return Ok(length);
}
match failure {
0 => Err("JNI exception".into()),
1 => Ok(-1),
2 => Ok(length - 1),
_ => Ok(length + 1),
}
});
let result = configure_serial_port(
&port,
&UsbSerialLine::eight_n_one(115_200),
|request| {
let index = called;
called += 1;
let length = request.payload.len() as i32;
if index != fail_at {
return Ok(length);
}
match failure {
0 => Err("JNI exception".into()),
1 => Ok(-1),
2 => Ok(length - 1),
_ => Ok(length + 1),
}
},
);
assert!(result.is_err());
assert_eq!(called, fail_at + 1);
}
}
}
assert!(
configure_serial_port(&cp210x(), 0, |_| panic!("invalid baud must not touch USB"))
.is_err()
configure_serial_port(&cp210x(), &UsbSerialLine::eight_n_one(0), |_| panic!(
"invalid baud must not touch USB"
))
.is_err()
);
}
}
+239 -181
View File
@@ -231,12 +231,31 @@ pub fn parse_callsign_ssid(input: &str) -> Result<(String, u8), String> {
Ok((call, ssid))
}
/// Python `AX25KISSInterface.configure_device` sleeps this long after opening
/// the port, before reading and before sending the TNC configuration.
#[cfg(feature = "serial")]
const CONFIGURE_SETTLE: Duration = Duration::from_secs(2);
/// Spawn an AX.25 KISS interface. An unopenable port does not fail the spawn:
/// as in Python, the interface stays offline and the port is retried every
/// `RECONNECT_WAIT` seconds, also after a runtime port error.
#[cfg(feature = "serial")]
pub async fn spawn_ax25kiss_interface(
config: AX25KISSConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
Ok(spawn_ax25kiss_interface_observed(config, id, transport_tx)
.await?
.interface)
}
#[cfg(feature = "serial")]
pub async fn spawn_ax25kiss_interface_observed(
config: AX25KISSConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<crate::serial::SpawnedSerialInterface, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate().map_err(|e| {
@@ -245,145 +264,211 @@ pub async fn spawn_ax25kiss_interface(
let (data_bits, parity, stop_bits) =
crate::serial::serial_params_from(config.data_bits, &config.parity, config.stop_bits);
let port = crate::serial::open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(data_bits)
.parity(parity)
.stop_bits(stop_bits)
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS)),
)
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss serial open: {}", e))
})?;
rns_transport::notice!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
src_call = %config.src_call,
src_ssid = config.src_ssid,
"AX.25 KISS interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let (tx, rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let python_identity =
rns_transport::messages::InterfaceIdentity::bracketed("AX25KISSInterface", &name);
let mode = config.mode;
let flow_control = config.flow_control;
let (failures_tx, failures) = crate::serial_io::SerialFailures::channel();
let src_call_bytes: Vec<u8> = config.src_call.as_bytes().to_vec();
let dst_call_bytes: Vec<u8> = config.dst_call.as_bytes().to_vec();
let src_ssid = config.src_ssid;
let dst_ssid = config.dst_ssid;
let supervisor = crate::serial_io::Supervisor {
identity: format!("AX25KISSInterface[{name}]"),
opener: crate::serial::port_opener(
&config.port,
config.baud_rate,
data_bits,
parity,
stop_bits,
Duration::from_millis(AX25_READ_TIMEOUT_MS),
),
settle: CONFIGURE_SETTLE,
online: online.clone(),
failures: failures_tx,
};
let generation = Ax25Generation {
id,
init_frames: build_ax25_kiss_init(&config),
flow_control: config.flow_control,
src_call: config.src_call.as_bytes().to_vec(),
dst_call: config.dst_call.as_bytes().to_vec(),
src_ssid: config.src_ssid,
dst_ssid: config.dst_ssid,
rx,
background,
transport_tx,
online: online.clone(),
rxb: shared_rxb.clone(),
txb: shared_txb.clone(),
};
let read_task = tokio::spawn(supervisor.run(generation, None));
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("ax25kiss clone: {}", e)))?;
Ok(crate::serial::SpawnedSerialInterface {
interface: InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: HW_MTU as u32,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
},
failures,
})
}
{
let mut init_port = port_write.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss init clone: {}", e))
})?;
let init_seq = build_ax25_kiss_init(&config);
use std::io::Write;
let _ = init_port.write_all(&init_seq);
let _ = init_port.flush();
tracing::debug!(name = %config.name, "AX.25 KISS init commands sent");
#[cfg(feature = "serial")]
struct Ax25Generation {
id: InterfaceId,
init_frames: Vec<u8>,
flow_control: bool,
src_call: Vec<u8>,
dst_call: Vec<u8>,
src_ssid: u8,
dst_ssid: u8,
rx: mpsc::Receiver<Bytes>,
background: crate::background_announce::BackgroundAnnounceReceiver,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
txb: Arc<AtomicU64>,
}
#[cfg(feature = "serial")]
impl crate::serial_io::SerialGeneration for Ax25Generation {
fn outbound(&mut self) -> &mut mpsc::Receiver<Bytes> {
&mut self.rx
}
let ready = Arc::new(AtomicBool::new(true));
fn background(&self) -> &crate::background_announce::BackgroundAnnounceReceiver {
&self.background
}
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
let mut flow_control_locked = tokio::time::Instant::now();
let take_permit = |locked: tokio::time::Instant| {
if ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
return true;
}
if locked.elapsed() > crate::kiss_iface::FLOW_CONTROL_TIMEOUT {
tracing::warn!(
"AX.25 KISS interface is unlocking flow control due to time-out. This should not happen. Your hardware might have missed a flow-control READY command, or maybe it does not support flow-control."
);
return true;
}
false
};
loop {
if !online_w.load(Ordering::SeqCst) {
break;
}
let background_packet = if rx.is_empty() {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control || take_permit(flow_control_locked)
})
} else {
None
fn run(
&mut self,
port: crate::serial_io::Port,
) -> impl std::future::Future<Output = crate::serial_io::GenerationEnd> + Send {
use crate::serial_io::GenerationEnd;
let Self {
id,
init_frames,
flow_control,
src_call,
dst_call,
src_ssid,
dst_ssid,
rx,
background,
transport_tx,
online,
rxb,
txb,
} = self;
let (id, flow_control, src_ssid, dst_ssid) = (*id, *flow_control, *src_ssid, *dst_ssid);
async move {
let port_write = match port.try_clone() {
Ok(port) => port,
Err(e) => return GenerationEnd::ReadFailed(e.into()),
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
}
};
if flow_control && background_packet.is_none() {
while !take_permit(flow_control_locked) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
let ready = AtomicBool::new(true);
let writer = async {
// Python starts the read loop and goes online before the TNC config.
let mut port_w =
match crate::serial_io::blocking_write_all(port_write, init_frames.clone())
.await
{
Ok(p) => p,
Err(e) => return GenerationEnd::WriteFailed(e),
};
let mut flow_control_locked = tokio::time::Instant::now();
let take_permit = |locked: tokio::time::Instant| {
if ready
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
return true;
}
if locked.elapsed() > crate::kiss_iface::FLOW_CONTROL_TIMEOUT {
tracing::warn!(
"AX.25 KISS interface is unlocking flow control due to time-out. This should not happen. Your hardware might have missed a flow-control READY command, or maybe it does not support flow-control."
);
return true;
}
false
};
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
let background_packet = if rx.is_empty() {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control || take_permit(flow_control_locked)
})
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => return GenerationEnd::Closed,
Err(_) => continue,
}
};
if flow_control && background_packet.is_none() {
while !take_permit(flow_control_locked) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
}
}
if flow_control {
flow_control_locked = tokio::time::Instant::now();
}
let framed = frame_ax25_kiss(&data, dst_call, dst_ssid, src_call, src_ssid);
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
// Python counts the payload without AX.25 header or framing.
txb.fetch_add(data.len() as u64, Ordering::Relaxed);
}
Err(e) => return GenerationEnd::WriteFailed(e),
}
}
}
if flow_control {
flow_control_locked = tokio::time::Instant::now();
}
let framed =
frame_ax25_kiss(&data, &dst_call_bytes, dst_ssid, &src_call_bytes, src_ssid);
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
// Python counts the payload without AX.25 header or framing.
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
}
});
let online_r = online.clone();
let ready_r = ready;
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = kiss::KissByteDeframer::new(HW_MTU as usize + AX25_HEADER_SIZE);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
};
let reader = async {
let mut port_r = port;
let mut deframer = kiss::KissByteDeframer::new(HW_MTU as usize + AX25_HEADER_SIZE);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
let (p, b, n) = match crate::serial_io::poll_read(port_r, buf).await {
Ok(read) => read,
Err(e) => return GenerationEnd::ReadFailed(e),
};
port_r = p;
buf = b;
if n == 0 {
@@ -392,71 +477,44 @@ pub async fn spawn_ax25kiss_interface(
{
deframer.reset();
}
} else {
last_read = std::time::Instant::now();
for event in deframer.feed(&buf[..n]) {
match event {
kiss::KissEvent::Data(frame) => {
let payload = match strip_ax25_header(&frame) {
Some(p) if !p.is_empty() => p.to_vec(),
_ => continue,
};
// Python counts the frame with its AX.25 header.
rxb_r.fetch_add(frame.len() as u64, Ordering::Relaxed);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(payload),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
kiss::KissEvent::Ready => {
ready_r.store(true, Ordering::SeqCst);
tracing::debug!(id, "AX.25 KISS flow control: ready");
continue;
}
last_read = std::time::Instant::now();
for event in deframer.feed(&buf[..n]) {
match event {
kiss::KissEvent::Data(frame) => {
let payload = match strip_ax25_header(&frame) {
Some(p) if !p.is_empty() => p.to_vec(),
_ => continue,
};
// Python counts the frame with its AX.25 header.
rxb.fetch_add(frame.len() as u64, Ordering::Relaxed);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(payload),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
return GenerationEnd::Closed;
}
}
kiss::KissEvent::Ready => {
ready.store(true, Ordering::SeqCst);
tracing::debug!(id, "AX.25 KISS flow control: ready");
}
}
}
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
};
tokio::select! {
end = writer => end,
end = reader => end,
}
}
});
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: HW_MTU as u32,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
})
}
}
#[cfg(test)]
+232 -86
View File
@@ -25,7 +25,6 @@ use bytes::Bytes;
#[cfg(test)]
use futures::FutureExt;
use futures::StreamExt;
use rand::RngCore;
use tokio::sync::mpsc;
use uuid::Uuid;
@@ -74,13 +73,14 @@ pub const NUS_RX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400002_B5A3_F393_E0A9_E50
/// Device notifies the host here.
pub const NUS_TX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400003_B5A3_F393_E0A9_E50E24DCCA9E);
const RECONNECT_WAIT: u64 = 1;
/// Fast early recovery, then indefinite low-duty retries. A two-minute cap made
/// a reachable radio appear dead long after returning to range.
const RECONNECT_WAIT_MAX: u64 = 30;
/// Python `RNodeInterface.reconnect_port` sleeps a fixed 5 s between attempts.
const RECONNECT_WAIT: u64 = 5;
const RECONNECT_WAIT_MAX: u64 = RECONNECT_WAIT;
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
const MAX_RECONNECT_TRIES: Option<usize> = None;
const SCAN_TIMEOUT: u64 = 3;
/// Python `BLEConnection.SCAN_TIMEOUT`; the scan returns on the first match.
const SCAN_TIMEOUT: Duration = Duration::from_secs(2);
const SCAN_POLL: Duration = Duration::from_millis(250);
/// Bounds disable-while-offline teardown latency to ~1s.
const RUNNING_POLL: Duration = Duration::from_secs(1);
/// No CoreBluetooth or GATT operation may hold the generation owner forever.
@@ -93,8 +93,6 @@ const BLE_POST_INIT_SETTLE: Duration = Duration::from_secs(1);
/// response pacing through dependency upgrades. Increasing that size requires
/// separate radio/firmware validation even though btleplug now exposes MTU.
const BLE_DEFAULT_ATT_WRITE_PAYLOAD: usize = 20;
/// RNode's reviewed high-throughput ATT MTU is 247 (247 - 3 ATT bytes).
const BLE_RNODE_ATT_WRITE_PAYLOAD: usize = 244;
#[cfg(target_os = "linux")]
const RNODE_POST_BOND_SETTLE: Duration = Duration::from_millis(2600);
const RNODE_NATIVE_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(6);
@@ -207,22 +205,19 @@ fn reconnect_try_exhausted(tries: &mut usize) -> bool {
}
}
fn reconnect_delay_with_jitter(seconds: u64, random: u64) -> Duration {
let base = Duration::from_secs(seconds.max(1));
let jitter_cap_ms = seconds.max(1).saturating_mul(200); // 0..20%
let jitter_ms = random % jitter_cap_ms.saturating_add(1);
base + Duration::from_millis(jitter_ms)
}
fn ble_reconnect_delay(seconds: u64) -> Duration {
reconnect_delay_with_jitter(seconds, rand::rngs::OsRng.next_u64())
Duration::from_secs(seconds)
}
const fn ble_write_chunk_size() -> usize {
/// Python writes `max_write_without_response_size` bytes, the negotiated ATT
/// MTU less 3 (20 at the 23-byte default MTU).
fn ble_write_chunk_size(negotiated_mtu: u16) -> usize {
if cfg!(any(target_os = "ios", target_os = "macos")) {
BLE_DEFAULT_ATT_WRITE_PAYLOAD
} else {
BLE_RNODE_ATT_WRITE_PAYLOAD
usize::from(negotiated_mtu)
.saturating_sub(3)
.max(BLE_DEFAULT_ATT_WRITE_PAYLOAD)
}
}
@@ -1262,12 +1257,15 @@ pub struct BleRNodeConfig {
pub tx_power: u8,
pub mode: InterfaceMode,
pub flow_control: bool,
pub st_alock: Option<f32>,
pub lt_alock: Option<f32>,
pub st_alock: Option<f64>,
pub lt_alock: Option<f64>,
/// Station-ID beacon: seconds between IDs, armed by data TX
/// (Python `id_interval`/`id_callsign`, callsign max 32 bytes).
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
/// Pair an unbonded RNode on Linux instead of refusing it. Python only
/// connects to devices that are already bonded; default off.
pub pair_unbonded: bool,
}
impl BleRNodeConfig {
@@ -1287,6 +1285,7 @@ impl BleRNodeConfig {
lt_alock: None,
id_interval: None,
id_callsign: None,
pair_unbonded: false,
}
}
@@ -1484,53 +1483,65 @@ async fn resolve_ble_target(
adapter: &Adapter,
ble_uri: &str,
generation_stable_name: Option<&str>,
pair_unbonded: bool,
) -> Result<(Peripheral, BleTargetResolutionClass), InterfaceError> {
let target = ble_uri.strip_prefix("ble://").unwrap_or(ble_uri);
let target = ble_uri
.get(.."ble://".len())
.filter(|scheme| scheme.eq_ignore_ascii_case("ble://"))
.map_or(ble_uri, |_| &ble_uri["ble://".len()..]);
ble_diag(format!("[ble] resolve_ble_target target='{target}'"));
bounded_ble_operation("scan start", adapter.start_scan(ble_scan_filter()))
.await
.inspect_err(|error| ble_diag(format!("[ble] start_scan err: {error}")))?;
tokio::time::sleep(Duration::from_secs(SCAN_TIMEOUT)).await;
// Like bleak's `find_device_by_filter`, return on the first match.
let scan_deadline = tokio::time::Instant::now() + SCAN_TIMEOUT;
let selection = loop {
tokio::time::sleep(SCAN_POLL).await;
let peripherals = bounded_ble_operation("peripheral list", adapter.peripherals()).await?;
let mut candidates = Vec::with_capacity(peripherals.len());
for p in &peripherals {
let props = bounded_ble_operation("properties", p.properties())
.await
.ok()
.flatten();
let bonded = pair_unbonded || peripheral_bonded(p).await;
candidates.push(BleTargetCandidate {
id: p.id().to_string(),
name: props.as_ref().and_then(|props| props.local_name.clone()),
services: props.map(|props| props.services),
bonded,
});
}
let selection = select_ble_target(target, generation_stable_name, &candidates);
if let BleTargetSelection::Selected(index, class) = selection {
break Some((peripherals[index].clone(), class));
}
if tokio::time::Instant::now() >= scan_deadline {
ble_diag(format!(
"[ble] scan found {} peripherals",
peripherals.len()
));
if selection == BleTargetSelection::NotBonded {
bounded_ble_operation("scan stop", adapter.stop_scan())
.await
.ok();
tracing::error!(
"Can't connect to target device {target} over BLE, device is not bonded"
);
return Err(InterfaceError::SendFailed(format!(
"BLE device {target} is not bonded"
)));
}
break None;
}
};
bounded_ble_operation("scan stop", adapter.stop_scan())
.await
.ok();
let peripherals = bounded_ble_operation("peripheral list", adapter.peripherals()).await?;
ble_diag(format!(
"[ble] scan found {} peripherals",
peripherals.len()
));
if target.is_empty() {
for p in &peripherals {
if let Ok(Some(props)) = bounded_ble_operation("properties", p.properties()).await {
if props.services.contains(&NUS_SERVICE_UUID) {
return Ok((p.clone(), BleTargetResolutionClass::FirstRnode));
}
// A populated list without NUS means a different device;
// only fall back to the name on empty service lists.
if props.services.is_empty()
&& let Some(ref name) = props.local_name
&& name.starts_with("RNode ")
{
return Ok((p.clone(), BleTargetResolutionClass::FirstRnode));
}
}
}
return Err(InterfaceError::SendFailed(
"No RNode BLE device found".into(),
));
}
// `peripheral.id().to_string()` is MAC on Linux/Android, CB UUID on
// iOS/macOS — same string the scanner exposes.
for p in &peripherals {
let addr = p.id().to_string();
if addr.eq_ignore_ascii_case(target) {
ble_diag(format!("[ble] resolve matched by address: {addr}"));
return Ok((p.clone(), BleTargetResolutionClass::PrimaryId));
}
if let Some((peripheral, class)) = selection {
ble_diag(format!("[ble] resolve matched {}", class.label()));
return Ok((peripheral, class));
}
// Windows can create a peripheral from an explicit MAC even when this
@@ -1546,31 +1557,118 @@ async fn resolve_ble_target(
return Ok((peripheral, BleTargetResolutionClass::PrimaryId));
}
ble_diag(format!(
"[ble] resolve failed: no peripheral matches '{target}'"
));
if target.is_empty() {
return Err(InterfaceError::SendFailed(
"No RNode BLE device found".into(),
));
}
Err(InterfaceError::SendFailed(format!(
"BLE device not found: {target}. Ensure it is powered on and paired."
)))
}
/// One scanned peripheral as target selection sees it.
struct BleTargetCandidate {
id: String,
name: Option<String>,
/// Advertised services; `None` when the platform had no properties.
services: Option<Vec<Uuid>>,
bonded: bool,
}
#[derive(Debug, PartialEq, Eq)]
enum BleTargetSelection {
Selected(usize, BleTargetResolutionClass),
/// A named or addressed target matched only unbonded devices.
NotBonded,
None,
}
/// Python `BLEConnection.find_target_device`: only bonded devices are
/// selectable, and a configured address or name that matches an unbonded
/// device is refused rather than paired.
fn select_ble_target(
target: &str,
generation_stable_name: Option<&str>,
candidates: &[BleTargetCandidate],
) -> BleTargetSelection {
let mut unbonded_match = false;
if target.is_empty() {
for (index, candidate) in candidates.iter().enumerate() {
let Some(services) = &candidate.services else {
continue;
};
// A populated list without NUS means a different device; only
// fall back to the name on empty service lists.
let is_rnode = services.contains(&NUS_SERVICE_UUID)
|| (services.is_empty()
&& candidate
.name
.as_deref()
.is_some_and(|name| name.starts_with("RNode ")));
if is_rnode && candidate.bonded {
return BleTargetSelection::Selected(index, BleTargetResolutionClass::FirstRnode);
}
}
return BleTargetSelection::None;
}
// `peripheral.id().to_string()` is MAC on Linux/Android, CB UUID on
// iOS/macOS — same string the scanner exposes.
for (index, candidate) in candidates.iter().enumerate() {
if candidate.id.eq_ignore_ascii_case(target) {
if candidate.bonded {
return BleTargetSelection::Selected(index, BleTargetResolutionClass::PrimaryId);
}
unbonded_match = true;
}
}
// Friendly-name resolution remains a fallback behind the configured
// platform ID. After an exact first generation, its verified RNode name is
// retained in memory so a post-bond CoreBluetooth handle replacement can
// be resolved without changing the public/configured identity.
for p in &peripherals {
if let Ok(Some(props)) = bounded_ble_operation("properties", p.properties()).await
&& let Some(ref name) = props.local_name
&& let Some(resolution_class) =
ble_name_resolution_class(target, generation_stable_name, name)
for (index, candidate) in candidates.iter().enumerate() {
if let Some(name) = candidate.name.as_deref()
&& let Some(class) = ble_name_resolution_class(target, generation_stable_name, name)
{
if resolution_class == BleTargetResolutionClass::PrimaryName {
ble_diag(format!("[ble] resolve matched by name: {name}"));
} else {
ble_diag("[ble] resolve matched by generation-stable advertised name");
if candidate.bonded {
return BleTargetSelection::Selected(index, class);
}
return Ok((p.clone(), resolution_class));
unbonded_match = true;
}
}
if unbonded_match {
BleTargetSelection::NotBonded
} else {
BleTargetSelection::None
}
}
ble_diag(format!(
"[ble] resolve failed: no peripheral matches '{target}'"
));
Err(InterfaceError::SendFailed(format!(
"BLE device not found: {target}. Ensure it is powered on and paired."
)))
/// Bond state as Python `BLEConnection.device_bonded` reads it on Linux
/// (BlueZ). Other platforms report bonded: Windows needs a paired-device
/// query this crate does not build, and CoreBluetooth exposes no bond state.
#[cfg(target_os = "linux")]
async fn peripheral_bonded(peripheral: &Peripheral) -> bool {
let Ok(address) = parse_linux_ble_address(&peripheral.address().to_string()) else {
return false;
};
let Ok(session) = linux_bluer_session().await else {
return false;
};
let Ok(adapter) = session.default_adapter().await else {
return false;
};
match adapter.device(address) {
Ok(device) => device.is_paired().await.unwrap_or(false),
Err(_) => false,
}
}
#[cfg(not(target_os = "linux"))]
async fn peripheral_bonded(_peripheral: &Peripheral) -> bool {
true
}
struct BleRNodeConnection {
@@ -1742,6 +1840,7 @@ fn reduce_native_startup_bytes(
async fn connect_rnode(
adapter: &Adapter,
ble_uri: &str,
pair_unbonded: bool,
generation_stable_name: &mut Option<String>,
running: &AtomicBool,
generation_id: BleGenerationId,
@@ -1753,7 +1852,7 @@ async fn connect_rnode(
None
};
let (peripheral, resolution_class) =
match resolve_ble_target(adapter, ble_uri, alternate_name).await {
match resolve_ble_target(adapter, ble_uri, alternate_name, pair_unbonded).await {
Ok(resolved) => resolved,
Err(error) => {
trace_ble_lifecycle(generation_id, "target_resolution", "failed", None, None);
@@ -1776,7 +1875,7 @@ async fn connect_rnode(
bounded_ble_operation("adapter event stream", adapter.events()).await?;
#[cfg(target_os = "linux")]
{
if pair_unbonded {
// BlueZ needs explicit pairing before we open a btleplug GATT
// connection. If this creates a fresh bond, RNode intentionally
// disconnects shortly afterwards; wait through that before connect().
@@ -2006,7 +2105,7 @@ async fn connect_rnode(
trace_ble_lifecycle(generation_id, "subscribe", "accepted", None, None);
ble_diag("[ble] subscribe TX ok");
let write_mtu = ble_write_chunk_size();
let write_mtu = ble_write_chunk_size(peripheral.mtu());
tracing::info!(write_mtu, "BLE RNode write chunk size");
ble_diag(format!("[ble] write chunk size={write_mtu}"));
@@ -2788,6 +2887,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
let flow_control = config.flow_control;
let beacon = beacon_from_config(&config);
let ble_uri = config.ble_uri.clone();
let pair_unbonded = config.pair_unbonded;
let log_name = name.clone();
let running_task = running.clone();
@@ -2862,6 +2962,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
let mut conn = match connect_rnode(
&adapter,
&ble_uri,
pair_unbonded,
&mut generation_stable_target_name,
&running_task,
generation_id,
@@ -4941,10 +5042,52 @@ mod tests {
}
#[test]
fn ble_reconnect_jitter_stays_within_twenty_percent() {
assert_eq!(reconnect_delay_with_jitter(1, 0), Duration::from_secs(1));
assert!(reconnect_delay_with_jitter(1, u64::MAX) <= Duration::from_millis(1_200));
assert!(reconnect_delay_with_jitter(30, u64::MAX) <= Duration::from_secs(36));
fn ble_target_selection_admits_only_bonded_devices() {
let rnode = |id: &str, name: &str, bonded: bool| BleTargetCandidate {
id: id.into(),
name: Some(name.into()),
services: Some(vec![NUS_SERVICE_UUID]),
bonded,
};
let unbonded = [rnode("AA:BB:CC:DD:EE:01", "RNode 1111", false)];
assert_eq!(
select_ble_target("", None, &unbonded),
BleTargetSelection::None
);
assert_eq!(
select_ble_target("AA:BB:CC:DD:EE:01", None, &unbonded),
BleTargetSelection::NotBonded
);
assert_eq!(
select_ble_target("RNode 1111", None, &unbonded),
BleTargetSelection::NotBonded
);
let mixed = [
rnode("AA:BB:CC:DD:EE:01", "RNode 1111", false),
rnode("AA:BB:CC:DD:EE:02", "RNode 2222", true),
];
assert_eq!(
select_ble_target("", None, &mixed),
BleTargetSelection::Selected(1, BleTargetResolutionClass::FirstRnode)
);
assert_eq!(
select_ble_target("aa:bb:cc:dd:ee:02", None, &mixed),
BleTargetSelection::Selected(1, BleTargetResolutionClass::PrimaryId)
);
assert_eq!(
select_ble_target("RNode 2222", None, &mixed),
BleTargetSelection::Selected(1, BleTargetResolutionClass::PrimaryName)
);
assert_eq!(
select_ble_target("RNode 3333", None, &mixed),
BleTargetSelection::None
);
}
#[test]
fn ble_reconnect_waits_a_fixed_five_seconds() {
assert_eq!(ble_reconnect_delay(RECONNECT_WAIT), Duration::from_secs(5));
assert_eq!(RECONNECT_WAIT_MAX, RECONNECT_WAIT);
}
#[test]
@@ -4970,16 +5113,18 @@ mod tests {
}
#[test]
fn ble_write_chunk_size_matches_platform_transport_guarantee() {
fn ble_write_chunk_follows_negotiated_mtu() {
#[cfg(any(target_os = "ios", target_os = "macos"))]
{
assert_eq!(ble_write_chunk_size(), BLE_DEFAULT_ATT_WRITE_PAYLOAD);
assert_eq!(ble_write_chunk_size(247), BLE_DEFAULT_ATT_WRITE_PAYLOAD);
assert!(matches!(ble_write_type(), WriteType::WithResponse));
}
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
{
assert_eq!(ble_write_chunk_size(), BLE_RNODE_ATT_WRITE_PAYLOAD);
assert_eq!(ble_write_chunk_size(23), 20);
assert_eq!(ble_write_chunk_size(185), 182);
assert_eq!(ble_write_chunk_size(247), 244);
assert!(matches!(ble_write_type(), WriteType::WithoutResponse));
}
}
@@ -5216,7 +5361,7 @@ mod tests {
));
cfg = BleRNodeConfig::new("validated", "ble://RNode");
cfg.st_alock = Some(f32::NAN);
cfg.st_alock = Some(f64::NAN);
assert!(matches!(
cfg.validate(),
Err(rnode::RNodeConfigValidationError::NonFinite {
@@ -6550,7 +6695,7 @@ mod tests {
"TCP write alone must neither clear nor count payload"
);
let second_ready = tokio::time::timeout(Duration::from_secs(4), async {
let second_ready = tokio::time::timeout(Duration::from_secs(RECONNECT_WAIT + 4), async {
loop {
let snapshot = snapshots
.changed()
@@ -7801,6 +7946,7 @@ mod tests {
let conn = connect_rnode(
&adapter,
"ble://",
false,
&mut generation_stable_name,
&running,
BleGenerationId::default().next(),
@@ -63,9 +63,10 @@ impl BleOperationStage {
| Self::Discovery
| Self::Subscribe
| Self::NotificationAcquisition
| Self::Detect
| Self::Capability
| Self::Configure => Duration::from_secs(10),
// Python `ble_detect_timeout`.
Self::Detect => Duration::from_secs(5),
}
}
}
+267 -221
View File
@@ -101,195 +101,275 @@ pub fn beacon_frame_payload(id_callsign: &[u8]) -> Vec<u8> {
frame
}
/// Python `KISSInterface.configure_device` sleeps this long after opening the
/// port, before reading and before sending the TNC configuration.
const CONFIGURE_SETTLE: Duration = Duration::from_secs(2);
/// Spawn a KISS interface. An unopenable port does not fail the spawn: as in
/// Python, the interface stays offline and the port is retried every
/// `RECONNECT_WAIT` seconds, also after a runtime port error.
pub async fn spawn_kiss_interface(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = crate::serial::open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(KISS_READ_TIMEOUT_MS)),
)
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e)))?;
Ok(spawn_kiss_interface_observed(config, id, transport_tx)
.await?
.interface)
}
spawn_kiss_with_port(config, id, transport_tx, port).await
pub async fn spawn_kiss_interface_observed(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<crate::serial::SpawnedSerialInterface, crate::traits::InterfaceError> {
spawn_kiss_with_port(config, id, transport_tx, None).await
}
async fn spawn_kiss_with_port(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
port: Box<dyn serialport::SerialPort>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
port: Option<crate::serial_io::Port>,
) -> Result<crate::serial::SpawnedSerialInterface, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
rns_transport::notice!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
"KISS interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let (tx, rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let python_identity =
rns_transport::messages::InterfaceIdentity::bracketed("KISSInterface", &name);
let mode = config.mode;
let flow_control = config.flow_control;
let (failures_tx, failures) = crate::serial_io::SerialFailures::channel();
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("kiss clone: {}", e)))?;
// Push TNC tuning before main loops so they take effect before first frame.
{
let mut init_port = port_write.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("kiss init clone: {}", e))
})?;
let init_frames = build_kiss_init(
config.txdelay,
config.txtail,
config.persistence,
config.slottime,
);
use std::io::Write;
init_port
.write_all(&init_frames)
.and_then(|()| init_port.flush())
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("kiss configure: {}", e))
})?;
}
let ready = Arc::new(AtomicBool::new(true));
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
let supervisor = crate::serial_io::Supervisor {
identity: format!("KISSInterface[{name}]"),
opener: crate::serial::port_opener(
&config.port,
config.baud_rate,
config.data_bits,
config.parity,
config.stop_bits,
Duration::from_millis(KISS_READ_TIMEOUT_MS),
),
settle: CONFIGURE_SETTLE,
online: online.clone(),
failures: failures_tx,
};
let beacon = config
.id_interval
.zip(config.id_callsign.clone())
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
let writer = tokio::spawn(async move {
let mut port_w = port_write;
// Python first_tx semantics: armed by the first data TX after a
// beacon; cleared when the beacon goes out.
let mut first_tx: Option<tokio::time::Instant> = None;
let mut flow_control_locked = tokio::time::Instant::now();
let take_permit = |locked: tokio::time::Instant| {
if ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
return true;
}
if locked.elapsed() > FLOW_CONTROL_TIMEOUT {
tracing::warn!(
"KISS interface is unlocking flow control due to time-out. This should not happen. Your hardware might have missed a flow-control READY command, or maybe it does not support flow-control."
);
return true;
}
false
};
loop {
if !online_w.load(Ordering::SeqCst) {
break;
}
let background_packet = if rx.is_empty() {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control || take_permit(flow_control_locked)
})
} else {
None
let generation = KissGeneration {
id,
init_frames: build_kiss_init(
config.txdelay,
config.txtail,
config.persistence,
config.slottime,
),
flow_control: config.flow_control,
beacon,
rx,
background,
transport_tx,
online: online.clone(),
rxb: shared_rxb.clone(),
txb: shared_txb.clone(),
};
let read_task = tokio::spawn(supervisor.run(generation, port));
Ok(crate::serial::SpawnedSerialInterface {
interface: InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
},
failures,
})
}
struct KissGeneration {
id: InterfaceId,
init_frames: Vec<u8>,
flow_control: bool,
beacon: Option<(Duration, Bytes)>,
rx: mpsc::Receiver<Bytes>,
background: crate::background_announce::BackgroundAnnounceReceiver,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
txb: Arc<AtomicU64>,
}
impl crate::serial_io::SerialGeneration for KissGeneration {
fn outbound(&mut self) -> &mut mpsc::Receiver<Bytes> {
&mut self.rx
}
fn background(&self) -> &crate::background_announce::BackgroundAnnounceReceiver {
&self.background
}
fn run(
&mut self,
port: crate::serial_io::Port,
) -> impl std::future::Future<Output = crate::serial_io::GenerationEnd> + Send {
use crate::serial_io::GenerationEnd;
let Self {
id,
init_frames,
flow_control,
beacon,
rx,
background,
transport_tx,
online,
rxb,
txb,
} = self;
let flow_control = *flow_control;
let id = *id;
async move {
let port_write = match port.try_clone() {
Ok(port) => port,
Err(e) => return GenerationEnd::ReadFailed(e.into()),
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else if let Some((interval, ref callsign)) = beacon {
match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => {
let due = first_tx.is_some_and(|t| t.elapsed() >= interval);
if !due {
continue;
// Python process_queue: a new generation starts with the radio ready.
let ready = AtomicBool::new(true);
let writer = async {
// Python starts the read loop and goes online before the TNC config.
let mut port_w =
match crate::serial_io::blocking_write_all(port_write, init_frames.clone())
.await
{
Ok(p) => p,
Err(e) => return GenerationEnd::WriteFailed(e),
};
// Python first_tx semantics: armed by the first data TX after a
// beacon; cleared when the beacon goes out.
let mut first_tx: Option<tokio::time::Instant> = None;
let mut flow_control_locked = tokio::time::Instant::now();
let take_permit = |locked: tokio::time::Instant| {
if ready
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
return true;
}
if locked.elapsed() > FLOW_CONTROL_TIMEOUT {
tracing::warn!(
"KISS interface is unlocking flow control due to time-out. This should not happen. Your hardware might have missed a flow-control READY command, or maybe it does not support flow-control."
);
return true;
}
false
};
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
let background_packet = if rx.is_empty() {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control || take_permit(flow_control_locked)
})
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else if let Some((interval, callsign)) = beacon.as_ref() {
match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => return GenerationEnd::Closed,
Err(_) => {
let due = first_tx.is_some_and(|t| t.elapsed() >= *interval);
if !due {
continue;
}
tracing::debug!("KISS transmitting station-ID beacon");
first_tx = None;
Bytes::from(beacon_frame_payload(callsign))
}
}
tracing::debug!("KISS transmitting station-ID beacon");
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => return GenerationEnd::Closed,
Err(_) => continue,
}
};
// Python compares against the unpadded callsign, so a padded beacon re-arms.
let is_beacon = beacon
.as_ref()
.is_some_and(|(_, callsign)| data == *callsign);
if is_beacon {
first_tx = None;
Bytes::from(beacon_frame_payload(callsign))
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
if flow_control && background_packet.is_none() {
while !take_permit(flow_control_locked) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
}
}
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
if flow_control {
flow_control_locked = tokio::time::Instant::now();
}
let framed = kiss::frame(&data);
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
// Python counts the unframed payload here (KISSInterface.py:275).
txb.fetch_add(data.len() as u64, Ordering::Relaxed);
}
Err(e) => return GenerationEnd::WriteFailed(e),
}
}
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
}
};
// Python compares against the unpadded callsign, so a padded beacon re-arms.
let is_beacon = beacon
.as_ref()
.is_some_and(|(_, callsign)| data == *callsign);
if is_beacon {
first_tx = None;
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
if flow_control && background_packet.is_none() {
while !take_permit(flow_control_locked) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
let reader = async {
let mut port_r = port;
let mut deframer = kiss::KissByteDeframer::new(HW_MTU);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
}
}
if !online_w.load(Ordering::SeqCst) {
break;
}
if flow_control {
flow_control_locked = tokio::time::Instant::now();
}
let framed = kiss::frame(&data);
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
// Python counts the unframed payload here (KISSInterface.py:275).
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
}
Err(e) => {
tracing::warn!(error = %e, "KISS write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
}
});
let online_r = online.clone();
let ready_r = ready;
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
// The writer lives and dies with the read task that teardown aborts.
let _writer = AbortOnDrop(writer);
let mut port_r = port;
let mut deframer = kiss::KissByteDeframer::new(HW_MTU);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
let (p, b, n) = match crate::serial_io::poll_read(port_r, buf).await {
Ok(read) => read,
Err(e) => return GenerationEnd::ReadFailed(e),
};
port_r = p;
buf = b;
if n == 0 {
@@ -298,76 +378,38 @@ async fn spawn_kiss_with_port(
{
deframer.reset();
}
} else {
last_read = std::time::Instant::now();
for event in deframer.feed(&buf[..n]) {
match event {
kiss::KissEvent::Data(frame) => {
rxb_r.fetch_add(
frame.len() as u64,
std::sync::atomic::Ordering::Relaxed,
);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
kiss::KissEvent::Ready => {
ready_r.store(true, Ordering::SeqCst);
tracing::debug!(id, "KISS flow control: ready");
continue;
}
last_read = std::time::Instant::now();
for event in deframer.feed(&buf[..n]) {
match event {
kiss::KissEvent::Data(frame) => {
rxb.fetch_add(frame.len() as u64, Ordering::Relaxed);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
return GenerationEnd::Closed;
}
}
kiss::KissEvent::Ready => {
ready.store(true, Ordering::SeqCst);
tracing::debug!(id, "KISS flow control: ready");
}
}
}
}
Err(e) => {
tracing::warn!(error = %e, "KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
};
tokio::select! {
end = writer => end,
end = reader => end,
}
}
});
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
})
}
struct AbortOnDrop(tokio::task::JoinHandle<()>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
@@ -438,12 +480,16 @@ mod tests {
// inject the already-open pair into the same production driver.
// A macOS pty slave drains only as the master reads, so read the
// configuration frames while the driver is still starting.
let spawning = tokio::spawn(spawn_kiss_with_port(config, 1, inbound, Box::new(slave)));
let driver = spawn_kiss_with_port(config, 1, inbound, Some(Box::new(slave)))
.await
.unwrap()
.interface;
master.set_timeout(CONFIGURE_SETTLE * 2).unwrap();
let init = build_kiss_init(None, None, None, None);
let mut actual_init = vec![0; init.len()];
master.read_exact(&mut actual_init).unwrap();
assert_eq!(actual_init, init);
let driver = spawning.await.unwrap().unwrap();
master.set_timeout(Duration::from_millis(300)).unwrap();
driver.owner.mark_registered();
// The initial permit goes to the first packet; later ones wait for READY.
driver.tx.send(Bytes::from_static(b"first")).await.unwrap();
+22 -22
View File
@@ -1078,7 +1078,7 @@ impl RNodeSnapshotPublisher {
self.session_lost(false);
}
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
pub(crate) fn connection_failed(&self) {
self.session_lost(true);
}
@@ -2964,10 +2964,10 @@ pub struct RNodeConfig {
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Station-ID beacon: seconds between IDs, armed by data TX
/// (Python `id_interval`/`id_callsign`, callsign max 32 bytes).
pub id_interval: Option<u64>,
@@ -3018,7 +3018,7 @@ pub enum RNodeConfigValidationError {
maximum: f64,
},
#[error("must be finite, got {value}")]
NonFinite { field: RNodeConfigField, value: f32 },
NonFinite { field: RNodeConfigField, value: f64 },
}
impl RNodeConfigValidationError {
@@ -3097,7 +3097,7 @@ where
fn validate_airtime(
field: RNodeConfigField,
value: Option<f32>,
value: Option<f64>,
) -> Result<(), RNodeConfigValidationError> {
let Some(value) = value else {
return Ok(());
@@ -3108,7 +3108,7 @@ fn validate_airtime(
if !(0.0..=100.0).contains(&value) {
return Err(RNodeConfigValidationError::OutOfRange {
field,
value: f64::from(value),
value,
minimum: 0.0,
maximum: 100.0,
});
@@ -3158,20 +3158,20 @@ pub(crate) fn build_persist_bluetooth_enabled_sequence() -> Vec<u8> {
build_command_stage(CMD_BT_CTRL, &[0x01])
}
/// Airtime-lock commands. Percent is encoded as `(percent * 100)` big-endian u16.
/// Airtime-lock command word: Python `int(percent * 100)` in double
/// precision, truncated toward zero, sent as a big-endian u16.
pub fn airtime_lock_word(percent: f64) -> u16 {
(percent * 100.0) as u16
}
/// Airtime-lock commands, one `CMD_ST_ALOCK`/`CMD_LT_ALOCK` frame per limit.
pub fn build_airtime_sequence(config: &RNodeConfig) -> Vec<u8> {
let mut out = Vec::with_capacity(16);
if let Some(st) = config.st_alock {
let at = (st * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(CMD_ST_ALOCK, &[c1, c2], &mut out);
kiss::frame_with_command_into(CMD_ST_ALOCK, &airtime_lock_word(st).to_be_bytes(), &mut out);
}
if let Some(lt) = config.lt_alock {
let at = (lt * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(CMD_LT_ALOCK, &[c1, c2], &mut out);
kiss::frame_with_command_into(CMD_LT_ALOCK, &airtime_lock_word(lt).to_be_bytes(), &mut out);
}
out
}
@@ -3263,13 +3263,13 @@ pub(crate) fn build_ble_radio_reassertion_stages(config: &RNodeConfig) -> Vec<Ve
if let Some(st) = config.st_alock {
stages.push(build_command_stage(
CMD_ST_ALOCK,
&((st * 100.0) as u16).to_be_bytes(),
&airtime_lock_word(st).to_be_bytes(),
));
}
if let Some(lt) = config.lt_alock {
stages.push(build_command_stage(
CMD_LT_ALOCK,
&((lt * 100.0) as u16).to_be_bytes(),
&airtime_lock_word(lt).to_be_bytes(),
));
}
@@ -5050,21 +5050,21 @@ mod tests {
assert_invalid_config_field(&config, RNodeConfigField::TxPower);
config.tx_power = 14;
config.st_alock = Some(-f32::EPSILON);
config.st_alock = Some(-f64::EPSILON);
assert_invalid_config_field(&config, RNodeConfigField::ShortTermAirtime);
config.st_alock = Some(100.0 + f32::EPSILON * 100.0);
config.st_alock = Some(100.0 + f64::EPSILON * 100.0);
assert_invalid_config_field(&config, RNodeConfigField::ShortTermAirtime);
config.st_alock = None;
config.lt_alock = Some(-f32::EPSILON);
config.lt_alock = Some(-f64::EPSILON);
assert_invalid_config_field(&config, RNodeConfigField::LongTermAirtime);
config.lt_alock = Some(100.0 + f32::EPSILON * 100.0);
config.lt_alock = Some(100.0 + f64::EPSILON * 100.0);
assert_invalid_config_field(&config, RNodeConfigField::LongTermAirtime);
}
#[test]
fn test_rnode_config_validation_rejects_non_finite_airtime() {
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let mut config = RNodeConfig::new("rnode0", "/dev/ttyACM0");
config.st_alock = Some(invalid);
assert_invalid_config_field(&config, RNodeConfigField::ShortTermAirtime);
+12 -10
View File
@@ -102,9 +102,9 @@ pub struct SubInterfaceConfig {
pub flow_control: bool,
pub outgoing: bool,
/// Short-term airtime cap, percent of duty cycle.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime cap, percent of duty cycle.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
}
impl SubInterfaceConfig {
@@ -227,16 +227,18 @@ pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec<u8
kiss::frame_with_command_into(rnode::CMD_CR, &[config.coding_rate], &mut out);
kiss::frame_with_command_into(rnode::CMD_TXPOWER, &[config.tx_power as u8], &mut out);
if let Some(st) = config.st_alock {
let at = (st * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(rnode::CMD_ST_ALOCK, &[c1, c2], &mut out);
kiss::frame_with_command_into(
rnode::CMD_ST_ALOCK,
&rnode::airtime_lock_word(st).to_be_bytes(),
&mut out,
);
}
if let Some(lt) = config.lt_alock {
let at = (lt * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(rnode::CMD_LT_ALOCK, &[c1, c2], &mut out);
kiss::frame_with_command_into(
rnode::CMD_LT_ALOCK,
&rnode::airtime_lock_word(lt).to_be_bytes(),
&mut out,
);
}
kiss::frame_with_command_into(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON], &mut out);
kiss::frame_with_command_into(
+210 -123
View File
@@ -13,6 +13,8 @@ use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub use crate::serial_io::SerialFailures;
pub const DEFAULT_BAUD: u32 = 9600;
const SERIAL_READ_TIMEOUT_MS: u64 = 100;
@@ -90,95 +92,210 @@ pub fn serial_params_from(
(data, parity, stop)
}
/// Seconds Python `SerialInterface.configure_device` sleeps before reading.
const CONFIGURE_SETTLE: Duration = Duration::from_millis(500);
/// The opener for a serial-family port. On Android the port names a USB
/// device (optionally `androidusb://`-prefixed), opened through `UsbManager`
/// as Python's Android interfaces do with usbserial4a; elsewhere it is a tty.
pub(crate) fn port_opener(
port: &str,
baud_rate: u32,
data_bits: serialport::DataBits,
parity: serialport::Parity,
stop_bits: serialport::StopBits,
read_timeout: Duration,
) -> crate::serial_io::PortOpener {
#[cfg(target_os = "android")]
{
let _ = read_timeout;
crate::android_usb::usb_serial_opener(port, baud_rate, data_bits, parity, stop_bits)
}
#[cfg(not(target_os = "android"))]
{
let builder = serialport::new(port, baud_rate)
.data_bits(data_bits)
.parity(parity)
.stop_bits(stop_bits)
.timeout(read_timeout);
Arc::new(move || open_port(builder.clone()).map_err(std::io::Error::from))
}
}
/// A serial-family interface handle paired with its runtime failure count.
#[non_exhaustive]
pub struct SpawnedSerialInterface {
pub interface: InterfaceHandle,
pub failures: SerialFailures,
}
/// Spawn a serial interface. An unopenable port does not fail the spawn: as in
/// Python, the interface stays offline and the port is retried every
/// `RECONNECT_WAIT` seconds, also after a runtime port error.
pub async fn spawn_serial_interface(
config: SerialConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
Ok(spawn_serial_interface_observed(config, id, transport_tx)
.await?
.interface)
}
pub async fn spawn_serial_interface_observed(
config: SerialConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<SpawnedSerialInterface, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let port = open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(SERIAL_READ_TIMEOUT_MS)),
)
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial open: {}", e)))?;
tracing::info!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
"serial interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let (tx, rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let python_identity =
rns_transport::messages::InterfaceIdentity::bracketed("SerialInterface", &name);
let mode = config.mode;
let (failures_tx, failures) = crate::serial_io::SerialFailures::channel();
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial clone: {}", e)))?;
let supervisor = crate::serial_io::Supervisor {
identity: format!("SerialInterface[{name}]"),
opener: port_opener(
&config.port,
config.baud_rate,
config.data_bits,
config.parity,
config.stop_bits,
Duration::from_millis(SERIAL_READ_TIMEOUT_MS),
),
settle: CONFIGURE_SETTLE,
online: online.clone(),
failures: failures_tx,
};
let generation = SerialGeneration {
id,
rx,
background,
transport_tx,
online: online.clone(),
rxb: shared_rxb.clone(),
txb: shared_txb.clone(),
};
let read_task = tokio::spawn(supervisor.run(generation, None));
let online_w = online.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
loop {
if !online_w.load(Ordering::SeqCst) {
break;
}
let background_packet = if rx.is_empty() {
background.try_start(rns_transport::now_f64())
} else {
None
Ok(SpawnedSerialInterface {
interface: InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: config.baud_rate as u64,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
},
failures,
})
}
struct SerialGeneration {
id: InterfaceId,
rx: mpsc::Receiver<Bytes>,
background: crate::background_announce::BackgroundAnnounceReceiver,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
txb: Arc<AtomicU64>,
}
impl crate::serial_io::SerialGeneration for SerialGeneration {
fn outbound(&mut self) -> &mut mpsc::Receiver<Bytes> {
&mut self.rx
}
fn background(&self) -> &crate::background_announce::BackgroundAnnounceReceiver {
&self.background
}
fn run(
&mut self,
port: crate::serial_io::Port,
) -> impl std::future::Future<Output = crate::serial_io::GenerationEnd> + Send {
use crate::serial_io::GenerationEnd;
let Self {
id,
rx,
background,
transport_tx,
online,
rxb,
txb,
} = self;
async move {
let port_write = match port.try_clone() {
Ok(port) => port,
Err(e) => return GenerationEnd::ReadFailed(e.into()),
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
let writer = async {
let mut port_w = port_write;
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
let background_packet = if rx.is_empty() {
background.try_start(rns_transport::now_f64())
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => return GenerationEnd::Closed,
Err(_) => continue,
}
};
let framed = hdlc::frame(&data);
let framed_len = framed.len() as u64;
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
txb.fetch_add(framed_len, Ordering::Relaxed);
}
Err(e) => return GenerationEnd::WriteFailed(e),
}
}
};
let framed = hdlc::frame(&data);
let framed_len = framed.len() as u64;
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
txb_w.fetch_add(framed_len, std::sync::atomic::Ordering::Relaxed);
}
Err(e) => {
tracing::warn!(error = %e, "serial write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
}
});
let online_r = online.clone();
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = hdlc::HdlcByteDeframer::new(HW_MTU);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
let reader = async {
let mut port_r = port;
let mut deframer = hdlc::HdlcByteDeframer::new(HW_MTU);
let mut buf = [0u8; 1024];
let mut last_read = std::time::Instant::now();
loop {
if !online.load(Ordering::SeqCst) {
return GenerationEnd::Closed;
}
let (p, b, n) = match crate::serial_io::poll_read(port_r, buf).await {
Ok(read) => read,
Err(e) => return GenerationEnd::ReadFailed(e),
};
port_r = p;
buf = b;
if n == 0 {
@@ -187,64 +304,34 @@ pub async fn spawn_serial_interface(
{
deframer.reset();
}
} else {
last_read = std::time::Instant::now();
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
rxb_r.fetch_add(
frame.len() as u64,
std::sync::atomic::Ordering::Relaxed,
);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
continue;
}
last_read = std::time::Instant::now();
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
rxb.fetch_add(frame.len() as u64, Ordering::Relaxed);
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: *id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
return GenerationEnd::Closed;
}
}
}
Err(e) => {
tracing::warn!(error = %e, "serial read error");
online_r.store(false, Ordering::SeqCst);
return;
}
};
tokio::select! {
end = writer => end,
end = reader => end,
}
}
});
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: config.baud_rate as u64,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: Some(
rns_transport::messages::InterfaceInspectionSource::identified(python_identity),
),
tx,
read_task,
})
}
}
#[cfg(test)]
+142
View File
@@ -41,3 +41,145 @@ where
Err(join_err) => Err(std::io::Error::other(join_err)),
}
}
#[cfg(feature = "serial")]
pub use supervisor::*;
/// Python's serial-family lifecycle (`SerialInterface`, `KISSInterface`,
/// `AX25KISSInterface`): open, settle, go online, run until an error, then
/// retry every `RECONNECT_WAIT` seconds while dropping outbound packets.
#[cfg(feature = "serial")]
mod supervisor {
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use bytes::Bytes;
use tokio::sync::{mpsc, watch};
use crate::background_announce::BackgroundAnnounceReceiver;
pub(crate) type Port = Box<dyn serialport::SerialPort>;
/// Opens the configured port; called again for every reconnect attempt.
pub(crate) type PortOpener = Arc<dyn Fn() -> std::io::Result<Port> + Send + Sync>;
/// Why one open-port generation ended.
pub(crate) enum GenerationEnd {
/// The read loop failed: Python's unrecoverable-error path.
ReadFailed(std::io::Error),
/// A write failed; the port is reopened like after a read error.
WriteFailed(std::io::Error),
/// The interface or the transport went away.
Closed,
}
pub(crate) trait SerialGeneration: Send {
fn outbound(&mut self) -> &mut mpsc::Receiver<Bytes>;
fn background(&self) -> &BackgroundAnnounceReceiver;
fn run(&mut self, port: Port) -> impl Future<Output = GenerationEnd> + Send;
}
/// Count of runtime port failures, which Python answers with `RNS.panic()`
/// when `panic_on_interface_error` is set.
#[derive(Clone)]
pub struct SerialFailures(watch::Receiver<u64>);
impl SerialFailures {
pub(crate) fn channel() -> (watch::Sender<u64>, Self) {
let (tx, rx) = watch::channel(0);
(tx, Self(rx))
}
pub fn total(&self) -> u64 {
*self.0.borrow()
}
/// Wait for the next failure. `None` means the driver has ended.
pub async fn changed(&mut self) -> Option<u64> {
self.0.changed().await.ok()?;
Some(self.total())
}
}
pub(crate) struct Supervisor {
pub identity: String,
pub opener: PortOpener,
pub settle: Duration,
pub online: Arc<AtomicBool>,
pub failures: watch::Sender<u64>,
}
/// Drop outbound packets for `duration`, as Python's `process_outgoing`
/// does while offline. False once the outbound channel has closed.
async fn drop_outbound_for(rx: &mut mpsc::Receiver<Bytes>, duration: Duration) -> bool {
let deadline = tokio::time::Instant::now() + duration;
loop {
tokio::select! {
packet = rx.recv() => if packet.is_none() { return false },
_ = tokio::time::sleep_until(deadline) => return true,
}
}
}
async fn open_with(opener: &PortOpener) -> std::io::Result<Port> {
let opener = opener.clone();
tokio::task::spawn_blocking(move || opener())
.await
.unwrap_or_else(|error| Err(std::io::Error::other(error)))
}
impl Supervisor {
pub(crate) async fn run<G: SerialGeneration>(self, mut generation: G, first: Option<Port>) {
let reconnect_wait = Duration::from_secs(crate::rnode::RECONNECT_WAIT);
let mut next = first;
loop {
let port = match next.take() {
Some(port) => Some(port),
None => match open_with(&self.opener).await {
Ok(port) => Some(port),
Err(error) => {
tracing::error!(
interface = %self.identity,
%error,
"Could not open serial port, Reticulum will attempt to bring up this interface periodically"
);
None
}
},
};
if let Some(port) = port {
if !drop_outbound_for(generation.outbound(), self.settle).await {
return;
}
self.online.store(true, Ordering::SeqCst);
rns_transport::notice!(interface = %self.identity, "serial port is now open");
let end = generation.run(port).await;
self.online.store(false, Ordering::SeqCst);
generation.background().retire_generation();
match end {
GenerationEnd::Closed => return,
GenerationEnd::ReadFailed(error) => {
tracing::error!(
interface = %self.identity,
%error,
"The interface experienced an unrecoverable error and is now offline. Reticulum will attempt to reconnect the interface periodically."
);
self.failures.send_modify(|total| *total += 1);
}
GenerationEnd::WriteFailed(error) => {
tracing::error!(
interface = %self.identity,
%error,
"serial write failed, the interface is offline and will be reconnected periodically"
);
}
}
}
if !drop_outbound_for(generation.outbound(), reconnect_wait).await {
return;
}
}
}
}
}
@@ -0,0 +1,23 @@
{
"generator": "crates/rns-interface/tests/fixtures/android_usb_serial/generate.py",
"usbserial4a_version": "0.4.0",
"request_fields": ["request_type", "request", "value", "index", "payload_hex", "length"],
"cases": [
{"device":"ftdi_ft232r","vid":1027,"pid":24577,"bcd":1536,"driver":"FtdiSerial","baud":115200,"databits":8,"parity":"N","stopbits":1,"requests":[[64,3,26,1,"",0],[64,4,8,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft232r","vid":1027,"pid":24577,"bcd":1536,"driver":"FtdiSerial","baud":9600,"databits":8,"parity":"N","stopbits":1,"requests":[[64,3,16696,1,"",0],[64,4,8,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft232r","vid":1027,"pid":24577,"bcd":1536,"driver":"FtdiSerial","baud":57600,"databits":7,"parity":"E","stopbits":2,"requests":[[64,3,49204,1,"",0],[64,4,4615,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft232r","vid":1027,"pid":24577,"bcd":1536,"driver":"FtdiSerial","baud":1200,"databits":8,"parity":"O","stopbits":1,"requests":[[64,3,2500,1,"",0],[64,4,264,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft2232h","vid":1027,"pid":24592,"bcd":1792,"driver":"FtdiSerial","baud":115200,"databits":8,"parity":"N","stopbits":1,"requests":[[64,3,26,1,"",0],[64,4,8,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft2232h","vid":1027,"pid":24592,"bcd":1792,"driver":"FtdiSerial","baud":9600,"databits":8,"parity":"N","stopbits":1,"requests":[[64,3,16696,1,"",0],[64,4,8,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft2232h","vid":1027,"pid":24592,"bcd":1792,"driver":"FtdiSerial","baud":57600,"databits":7,"parity":"E","stopbits":2,"requests":[[64,3,49204,1,"",0],[64,4,4615,1,"",0],[64,2,0,1,"",0]]},
{"device":"ftdi_ft2232h","vid":1027,"pid":24592,"bcd":1792,"driver":"FtdiSerial","baud":1200,"databits":8,"parity":"O","stopbits":1,"requests":[[64,3,2500,1,"",0],[64,4,264,1,"",0],[64,2,0,1,"",0]]},
{"device":"ch340","vid":6790,"pid":29987,"bcd":1536,"driver":"Ch34xSerial","baud":115200,"databits":8,"parity":"N","stopbits":1,"requests":[[64,161,49820,45753,"",0],[64,164,223,0,"",0],[64,164,159,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45698,"",0],[64,154,3884,8,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,52355,"",0],[64,154,3884,7,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0]]},
{"device":"ch340","vid":6790,"pid":29987,"bcd":1536,"driver":"Ch34xSerial","baud":9600,"databits":8,"parity":"N","stopbits":1,"requests":[[64,161,49820,45753,"",0],[64,164,223,0,"",0],[64,164,159,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45698,"",0],[64,154,3884,8,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45698,"",0],[64,154,3884,8,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0]]},
{"device":"ch340","vid":6790,"pid":29987,"bcd":1536,"driver":"Ch34xSerial","baud":57600,"databits":7,"parity":"E","stopbits":2,"requests":[[64,161,49820,45753,"",0],[64,164,223,0,"",0],[64,164,159,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45698,"",0],[64,154,3884,8,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,39043,"",0],[64,154,3884,7,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,9496,222,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0]]},
{"device":"ch340","vid":6790,"pid":29987,"bcd":1536,"driver":"Ch34xSerial","baud":1200,"databits":8,"parity":"O","stopbits":1,"requests":[[64,161,49820,45753,"",0],[64,164,223,0,"",0],[64,164,159,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45698,"",0],[64,154,3884,8,"",0],[64,154,9496,195,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,4882,45697,"",0],[64,154,3884,59,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[64,154,9496,203,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0],[192,149,1798,0,"",2],[64,154,10023,0,"",0]]},
{"device":"ch9102_forced_cdc","vid":6790,"pid":21972,"bcd":1536,"driver":"CdcAcmSerial","baud":115200,"databits":8,"parity":"N","stopbits":1,"requests":[[33,34,3,0,"",0],[33,32,0,0,"00c20100000008",7]]},
{"device":"ch9102_forced_cdc","vid":6790,"pid":21972,"bcd":1536,"driver":"CdcAcmSerial","baud":9600,"databits":8,"parity":"N","stopbits":1,"requests":[[33,34,3,0,"",0],[33,32,0,0,"80250000000008",7]]},
{"device":"ch9102_forced_cdc","vid":6790,"pid":21972,"bcd":1536,"driver":"CdcAcmSerial","baud":57600,"databits":7,"parity":"E","stopbits":2,"requests":[[33,34,3,0,"",0],[33,32,0,0,"00e10000020207",7]]},
{"device":"ch9102_forced_cdc","vid":6790,"pid":21972,"bcd":1536,"driver":"CdcAcmSerial","baud":1200,"databits":8,"parity":"O","stopbits":1,"requests":[[33,34,3,0,"",0],[33,32,0,0,"b0040000000108",7]]}
]
}
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""USB serial setup golden from usbserial4a 0.4.0, the driver library upstream
RNS 1.6.0 uses for Android USB serial (RNS/Interfaces/Android/*Interface.py,
`from usbserial4a import serial4a`). Each driver is opened against a stubbed
Android USB stack and every controlTransfer it issues is recorded.
The usbserial4a tree is RATSPEAK_USBSERIAL4A_DIR if set; otherwise the sdist
is fetched with pip into a temporary directory.
Run: python3 generate.py [out.json] (default: cases.json next to this file)
"""
import json, os, subprocess, sys, tarfile, tempfile, types
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "cases.json")
VERSION = "0.4.0"
src = os.environ.get("RATSPEAK_USBSERIAL4A_DIR")
if not src:
tmp = tempfile.mkdtemp()
subprocess.check_call([sys.executable, "-m", "pip", "download", "-q", "--no-deps", "--no-binary", ":all:",
"-d", tmp, f"usbserial4a=={VERSION}"])
with tarfile.open(os.path.join(tmp, f"usbserial4a-{VERSION}.tar.gz")) as t:
t.extractall(tmp, filter="data")
src = os.path.join(tmp, f"usbserial4a-{VERSION}")
class UsbConstants:
USB_DIR_IN = 0x80; USB_DIR_OUT = 0x00; USB_TYPE_VENDOR = 0x40; USB_TYPE_CLASS = 0x20
USB_ENDPOINT_XFER_BULK = 2; USB_ENDPOINT_XFER_INT = 3; USB_CLASS_COMM = 2; USB_CLASS_CDC_DATA = 0x0A
class Endpoint:
def __init__(s, d, t, mps=64): s.d, s.t, s.mps = d, t, mps
def getDirection(s): return s.d
def getType(s): return s.t
def getMaxPacketSize(s): return s.mps
class Interface:
def __init__(s, number, cls, eps): s.number, s.cls, s.eps = number, cls, eps
def getId(s): return s.number
def getInterfaceClass(s): return s.cls
def getEndpointCount(s): return len(s.eps)
def getEndpoint(s, i): return s.eps[i]
class Device:
def __init__(s, vid, pid, ifaces, bcd=0x0600): s.vid, s.pid, s.ifaces, s.bcd = vid, pid, ifaces, bcd
def getVendorId(s): return s.vid
def getProductId(s): return s.pid
def getInterfaceCount(s): return len(s.ifaces)
def getInterface(s, i): return s.ifaces[i]
class Connection:
def __init__(s, device): s.device = device; s.log = []
def getRawDescriptors(s):
d = bytearray(18); d[12] = s.device.bcd & 0xFF; d[13] = s.device.bcd >> 8; return d
def claimInterface(s, iface, force): return True
def controlTransfer(s, rt, req, value, index, buf, length, timeout):
# jnius hands Java an int; usbserial4a passes a float SET_BAUDDIV value.
s.log.append([rt, req, int(value) & 0xFFFF, index & 0xFFFF, bytes(buf[:length]).hex() if buf is not None and not rt & 0x80 else "", length])
if rt & 0x80:
if req == 0x95 and value == 0x0706: buf[0:2] = bytes([0x9F, 0xEE])
return length
return 0 if length == 0 else length
def close(s): pass
CURRENT = {}
usb = types.ModuleType("usb4a.usb")
usb.UsbConstants = UsbConstants
usb.USB_RECIPIENT_DEVICE = 0x00
usb.build_usb_control_request_type = lambda d, t, r: d | t | r
usb.get_usb_device = lambda name: CURRENT["device"]
usb.has_usb_permission = lambda d: True
usb.get_usb_manager = lambda: types.SimpleNamespace(openDevice=lambda d: CURRENT.setdefault("conn", Connection(d)))
usb.USBError = IOError
pkg = types.ModuleType("usb4a"); pkg.usb = usb
sys.modules["usb4a"] = pkg; sys.modules["usb4a.usb"] = usb
sys.path.insert(0, src)
from usbserial4a import serial4a, __version__
from usbserial4a.cdcacmserial4a import CdcAcmSerial
assert __version__ == VERSION, __version__
BULK = lambda: [Endpoint(0x80, 2), Endpoint(0x00, 2)]
DEVICES = {
"ftdi_ft232r": lambda: Device(0x0403, 0x6001, [Interface(0, 0xFF, BULK())], bcd=0x0600),
"ftdi_ft2232h": lambda: Device(0x0403, 0x6010, [Interface(0, 0xFF, BULK())], bcd=0x0700),
"ch340": lambda: Device(0x1A86, 0x7523, [Interface(0, 0xFF, [Endpoint(0x80, 3)] + BULK())]),
"ch9102_forced_cdc": lambda: Device(0x1A86, 0x55D4, [Interface(0, 2, [Endpoint(0x80, 3)]), Interface(1, 0x0A, BULK())]),
}
# Line settings the Android interfaces pass: speed, databits, parity "N"/"E"/"O", stopbits.
LINES = [(115200, 8, "N", 1), (9600, 8, "N", 1), (57600, 7, "E", 2), (1200, 8, "O", 1)]
cases = []
for name, make in DEVICES.items():
for baud, bits, parity, stop in LINES:
CURRENT.clear(); CURRENT["device"] = make()
# Upstream forces the CDC driver for 1a86:55d4 (Android/*Interface.py open_port).
cls = CdcAcmSerial if name == "ch9102_forced_cdc" else serial4a.get_serial_port
try:
port = cls("dev", baudrate=baud, bytesize=bits, parity=parity, stopbits=stop,
xonxoff=False, rtscts=False, timeout=None, dsrdtr=False)
cases.append({"device": name, "vid": CURRENT["device"].vid, "pid": CURRENT["device"].pid,
"bcd": CURRENT["device"].bcd, "driver": type(port).__name__,
"baud": baud, "databits": bits, "parity": parity, "stopbits": stop,
"requests": CURRENT["conn"].log})
except Exception as e:
cases.append({"device": name, "baud": baud, "databits": bits, "parity": parity, "stopbits": stop, "error": str(e)})
head = {"generator": "crates/rns-interface/tests/fixtures/android_usb_serial/generate.py", "usbserial4a_version": VERSION,
"request_fields": ["request_type", "request", "value", "index", "payload_hex", "length"]}
with open(OUT, "w") as f:
f.write("{\n" + ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in head.items()))
f.write(',\n "cases": [\n' + ",\n".join(" " + json.dumps(c, separators=(",", ":")) for c in cases) + "\n ]\n}\n")
print("wrote", len(cases), "cases")
+92 -24
View File
@@ -53,6 +53,8 @@ pub const PROCESSING_GRACE: f64 = 1.0;
pub const PART_TIMEOUT_FACTOR: f64 = 4.0;
pub const PART_TIMEOUT_FACTOR_AFTER_RTT: f64 = 2.0;
pub const PROOF_TIMEOUT_FACTOR: f64 = 3.0;
/// Proof-cache queries a sender makes before giving up (Resource.py:1106).
pub const PROOF_CACHE_QUERIES: usize = 3;
pub const RETRY_GRACE_TIME: f64 = 0.25;
pub const PER_RETRY_DELAY: f64 = 0.5;
/// HMU-wait multiplier in the watchdog timeout (Python `Resource.HMU_WAIT_FACTOR`).
@@ -1446,6 +1448,31 @@ pub enum TransferAction {
Failed(String),
/// `ICL` (initiator cancel) or `RCL` (receiver cancel), plus resource hash.
SendCancel(CancelType, [u8; 32]),
/// Sender found no proof in time: ask the transport for the cached proof
/// whose data is `resource_hash || expected_proof`, as Python
/// `Transport.cache_request` (see [`resource_proof_packet_hash`]).
QueryProofCache(Vec<u8>),
}
/// Packet hash of the RESOURCE_PRF packet a receiver sends on `link_id`
/// with `proof_data`, the key a CACHE_REQUEST names (Resource.py:670-673).
pub fn resource_proof_packet_hash(link_id: &[u8; 16], proof_data: &[u8]) -> [u8; 32] {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Proof,
},
hops: 0,
transport_id: None,
destination_hash: *link_id,
context: rns_wire::context::PacketContext::ResourcePrf,
};
let mut raw = header.pack();
raw.extend_from_slice(proof_data);
rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header1)
}
/// Cancel message types.
@@ -1481,6 +1508,8 @@ pub struct OutboundTransfer {
// requests and local polling are not Resource progress.
last_progress: Instant,
last_request_parts: usize,
/// Proof-cache queries left before the sender gives up (Resource.py:1106).
proof_queries_left: usize,
/// Advertisement wait per attempt before PROCESSING_GRACE; `None` uses
/// `rtt * TRAFFIC_TIMEOUT_FACTOR`, as Resource does without a timeout.
pub advertisement_timeout: Option<Duration>,
@@ -1547,6 +1576,7 @@ impl OutboundTransfer {
req_hashlist: HashSet::new(),
last_progress: Instant::now(),
last_request_parts: 0,
proof_queries_left: PROOF_CACHE_QUERIES,
advertisement_timeout: None,
advertisement_mdu: rns_wire::constants::LINK_MDU,
}
@@ -1612,19 +1642,13 @@ impl OutboundTransfer {
// dormant merely because it is no longer Advertised.
return TransferAction::Failed("transfer failed".to_string());
}
if matches!(
self.resource.state,
ResourceState::Transferring | ResourceState::AwaitingProof
) {
let timeout = self.progress_timeout();
if self.last_progress.elapsed() > timeout {
let reason = if self.resource.state == ResourceState::AwaitingProof {
"resource proof timed out"
} else {
"resource part requests timed out"
};
if self.resource.state == ResourceState::AwaitingProof {
return self.check_proof_timeout();
}
if self.resource.state == ResourceState::Transferring {
if self.last_progress.elapsed() > self.progress_timeout() {
self.resource.state = ResourceState::Failed;
return TransferAction::Failed(reason.to_string());
return TransferAction::Failed("resource part requests timed out".to_string());
}
return TransferAction::None;
}
@@ -1674,13 +1698,47 @@ impl OutboundTransfer {
),
))
}
ResourceState::Transferring | ResourceState::AwaitingProof => {
Some((self.last_progress, self.progress_timeout()))
}
ResourceState::Transferring => Some((self.last_progress, self.progress_timeout())),
ResourceState::AwaitingProof => Some((
self.proof_wait_started(),
self.proof_wait()
.saturating_mul(self.proof_queries_left.saturating_add(1) as u32),
)),
_ => None,
}
}
/// Python's AWAITING_PROOF watchdog (Resource.py:656-675).
fn check_proof_timeout(&mut self) -> TransferAction {
if self.proof_wait_started().elapsed() <= self.proof_wait() {
return TransferAction::None;
}
if self.proof_queries_left == 0 {
self.resource.state = ResourceState::Failed;
return TransferAction::Failed("resource proof timed out".to_string());
}
self.proof_queries_left -= 1;
self.last_part_sent = Some(Instant::now());
let mut proof_data = self.resource.resource_hash.to_vec();
proof_data.extend_from_slice(&self.resource.expected_proof);
TransferAction::QueryProofCache(proof_data)
}
fn proof_wait_started(&self) -> Instant {
self.last_part_sent.unwrap_or(self.last_progress)
}
fn proof_wait(&self) -> Duration {
self.rtt
.saturating_mul(PROOF_TIMEOUT_FACTOR as u32)
.saturating_add(Duration::from_secs_f64(SENDER_GRACE_TIME))
}
fn enter_awaiting_proof(&mut self) {
self.resource.state = ResourceState::AwaitingProof;
self.proof_queries_left = PROOF_CACHE_QUERIES;
}
/// Consume the receiver-feedback format paired with
/// [`InboundTransfer::create_hmu`]. It is distinct from the normal
/// sender-to-receiver RESOURCE_HMU map update.
@@ -1785,8 +1843,7 @@ impl OutboundTransfer {
self.window_cursor = self.cursor;
self.awaiting_hmu = false;
// Transition to awaiting proof
self.resource.state = ResourceState::AwaitingProof;
self.enter_awaiting_proof();
self.resource.window.grow(0);
}
}
@@ -1975,11 +2032,11 @@ impl OutboundTransfer {
self.last_request_parts = sent_count;
self.retries = 0;
}
self.resource.state = if self.sent_parts == self.resource.num_parts() {
ResourceState::AwaitingProof
if self.sent_parts == self.resource.num_parts() {
self.enter_awaiting_proof();
} else {
ResourceState::Transferring
};
self.resource.state = ResourceState::Transferring;
}
}
actions
@@ -3688,9 +3745,20 @@ mod tests {
let (received, proof) = receiver.complete(None).unwrap();
assert_eq!(received, data);
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 = ago_or_skip!(sender.progress_timeout() + Duration::from_secs(1));
// Receiver has delivered, but its proof is lost. The sender queries
// the proof cache three times, then fails; it never infers success.
let mut expected_query = sender.resource.resource_hash.to_vec();
expected_query.extend_from_slice(&sender.resource.expected_proof);
for _ in 0..PROOF_CACHE_QUERIES {
sender.last_part_sent =
Some(ago_or_skip!(sender.proof_wait() + Duration::from_secs(1)));
assert_eq!(
sender.tick(),
TransferAction::QueryProofCache(expected_query.clone())
);
assert_eq!(sender.tick(), TransferAction::None);
}
sender.last_part_sent = Some(ago_or_skip!(sender.proof_wait() + Duration::from_secs(1)));
assert_eq!(
sender.tick(),
TransferAction::Failed("resource proof timed out".to_string())
+254 -95
View File
@@ -121,10 +121,10 @@ pub struct RNodeInterfaceConfig {
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
pub id_callsign: Option<String>,
@@ -188,13 +188,16 @@ pub struct BleRNodeInterfaceConfig {
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
pub id_callsign: Option<String>,
/// Rust-only `ble_auto_pair`: pair an unbonded RNode on Linux. Python
/// only connects to bonded devices, so the default is off.
pub pair_unbonded: bool,
}
#[derive(Debug, Clone)]
@@ -259,8 +262,8 @@ pub struct RNodeSubInterfaceConfig {
/// The subsection's own key only; Python has no parent fallback.
pub flow_control: bool,
pub outgoing: bool,
pub st_alock: Option<f32>,
pub lt_alock: Option<f32>,
pub st_alock: Option<f64>,
pub lt_alock: Option<f64>,
}
/// AX.25-framed packets carried over a KISS serial TNC, with a configured
@@ -648,11 +651,33 @@ pub fn synthesize_interface(
"TCPClientInterface" => synthesize_tcp_client(name, section, mode),
"TCPServerInterface" => synthesize_tcp_server(name, section, mode),
"UDPInterface" => synthesize_udp(name, section, mode),
#[cfg(all(feature = "serial", not(target_os = "android")))]
"SerialInterface" | "KISSInterface" | "AX25KISSInterface"
if section
.get("port")
.is_some_and(|port| port.starts_with("androidusb://")) =>
{
Err(InterfaceFactoryError::Disabled(format!(
"{iface_type} '{name}' uses an Android USB-OTG port on a non-Android build"
)))
}
#[cfg(feature = "serial")]
"SerialInterface" => synthesize_serial(name, section, mode),
#[cfg(feature = "serial")]
"KISSInterface" => synthesize_kiss_serial(name, section, mode),
"AutoInterface" => synthesize_auto(name, section, mode),
#[cfg(target_os = "android")]
"RNodeInterface" if !section.has("port") => match android_rnode_port(name, section)? {
Some(port) => {
let mut section = section.clone();
section.set("port", &port);
synthesize_interface(name, &section)
}
None => Err(InterfaceFactoryError::MissingField {
name: name.to_string(),
field: "port".to_string(),
}),
},
"RNodeInterface" => {
let port = section
.get("port")
@@ -660,7 +685,10 @@ pub fn synthesize_interface(
name: name.to_string(),
field: "port".to_string(),
})?;
if port.starts_with("ble://") {
if port
.get(.."ble://".len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("ble://"))
{
#[cfg(feature = "ble")]
{
return synthesize_ble_rnode(name, section, mode);
@@ -895,6 +923,29 @@ fn synthesize_udp(
Ok(InterfaceConfig::Udp(config))
}
/// Python `int(c[key]) if key in c else default` for the serial line keys of
/// Serial, KISS and AX.25 KISS; the first present key of `keys` is used.
#[cfg(feature = "serial")]
fn parse_serial_line_value<T: TryFrom<i64>>(
name: &str,
section: &ConfigSection,
keys: &[&str],
default: T,
) -> Result<T, InterfaceFactoryError> {
let Some((key, raw)) = keys
.iter()
.find_map(|key| section.get(key).map(|value| (*key, value)))
else {
return Ok(default);
};
let invalid = |message: String| InterfaceFactoryError::InvalidValue {
field: format!("{name}.{key}"),
message,
};
let value = python_int(raw).ok_or_else(|| invalid(format!("'{raw}' is not an integer")))?;
T::try_from(value).map_err(|_| invalid(format!("{value} is out of range")))
}
#[cfg(feature = "serial")]
fn synthesize_serial(
name: &str,
@@ -909,22 +960,10 @@ fn synthesize_serial(
})?
.to_string();
let baud_rate = section
.get_uint("speed")
.or_else(|| section.get_uint("baud_rate"))
.unwrap_or(9600) as u32;
let data_bits = section
.get_uint("databits")
.or_else(|| section.get_uint("data_bits"))
.unwrap_or(8) as u8;
let baud_rate = parse_serial_line_value(name, section, &["speed", "baud_rate"], 9600u32)?;
let data_bits = parse_serial_line_value(name, section, &["databits", "data_bits"], 8u8)?;
let parity = section.get("parity").unwrap_or("N").to_string();
let stop_bits = section
.get_uint("stopbits")
.or_else(|| section.get_uint("stop_bits"))
.unwrap_or(1) as u8;
let stop_bits = parse_serial_line_value(name, section, &["stopbits", "stop_bits"], 1u8)?;
Ok(InterfaceConfig::Serial(SerialInterfaceConfig {
name: name.to_string(),
@@ -937,6 +976,43 @@ fn synthesize_serial(
}))
}
/// Python's Android `RNodeInterface` has no `port` URI schemes: it selects
/// BLE from `force_ble`, `ble_name` or `ble_addr` and TCP from `force_tcp` or
/// `tcp_host`, and Bluetooth Classic from `allow_bluetooth`. Map those to the
/// `ble://` and `tcp://` ports the shared RNode path understands.
#[cfg(any(target_os = "android", test))]
fn android_rnode_port(
name: &str,
section: &ConfigSection,
) -> Result<Option<String>, InterfaceFactoryError> {
// Upstream reads force_ble/force_tcp without as_bool, so any value is set.
let force_ble = section.has("force_ble");
let force_tcp = section.has("force_tcp");
let ble_target = section.get("ble_addr").or_else(|| section.get("ble_name"));
if force_ble || ble_target.is_some() {
return Ok(Some(format!("ble://{}", ble_target.unwrap_or(""))));
}
if force_tcp || section.has("tcp_host") {
return Ok(Some(format!(
"tcp://{}",
section.get("tcp_host").unwrap_or("")
)));
}
if section.get_bool("allow_bluetooth") == Some(true) {
return Err(InterfaceFactoryError::Disabled(format!(
"RNodeInterface '{name}' uses Bluetooth Classic (allow_bluetooth), which is not supported"
)));
}
Ok(None)
}
/// Python's Android `KISSInterface` names the station-ID keys
/// `beacon_interval`/`beacon_data`; the desktop class uses `id_*`.
#[cfg(all(feature = "serial", target_os = "android"))]
const KISS_BEACON_KEYS: (&str, &str) = ("beacon_interval", "beacon_data");
#[cfg(all(feature = "serial", not(target_os = "android")))]
const KISS_BEACON_KEYS: (&str, &str) = ("id_interval", "id_callsign");
#[cfg(feature = "serial")]
fn synthesize_kiss_serial(
name: &str,
@@ -951,10 +1027,7 @@ fn synthesize_kiss_serial(
})?
.to_string();
let baud_rate = section
.get_uint("speed")
.or_else(|| section.get_uint("baud_rate"))
.unwrap_or(9600) as u32;
let baud_rate = parse_serial_line_value(name, section, &["speed", "baud_rate"], 9600u32)?;
// Python KISSInterface.py:86-97 — TNC timing defaults 350/20/64/20,
// serial 8N1, flow_control off, optional station-ID beacon.
@@ -963,17 +1036,27 @@ fn synthesize_kiss_serial(
name: name.to_string(),
port,
baud_rate,
data_bits: section.get_uint("databits").unwrap_or(8) as u8,
data_bits: parse_serial_line_value(name, section, &["databits"], 8u8)?,
parity: section.get("parity").unwrap_or("N").to_string(),
stop_bits: section.get_uint("stopbits").unwrap_or(1) as u8,
stop_bits: parse_serial_line_value(name, section, &["stopbits"], 1u8)?,
mode,
preamble_ms: u32::from(tnc.preamble_ms),
txtail_ms: u32::from(tnc.txtail_ms),
persistence: tnc.persistence,
slottime_ms: u32::from(tnc.slottime_ms),
flow_control: section.get_bool("flow_control").unwrap_or(false),
id_interval: section.get_uint("id_interval"),
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
id_interval: match section.get(KISS_BEACON_KEYS.0) {
None => None,
Some(raw) => Some(
python_int(raw)
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
field: format!("{name}.{}", KISS_BEACON_KEYS.0),
message: format!("'{raw}' is not an integer"),
})?
.max(0) as u64,
),
},
id_callsign: section.get(KISS_BEACON_KEYS.1).map(|s| s.to_string()),
}))
}
@@ -1054,6 +1137,7 @@ fn synthesize_rnode(
require_generic_rnode_radio_params(name, section)?;
let (flow_control, st_alock, lt_alock) = parse_generic_rnode_airtime(name, section)?;
let (id_interval, id_callsign) = parse_rnode_station_id(name, section)?;
let usb_vendor_id = parse_optional_u16(name, section, "usb_vendor_id")?;
let usb_product_id = parse_optional_u16(name, section, "usb_product_id")?;
if usb_vendor_id.is_some() != usb_product_id.is_some() {
@@ -1079,8 +1163,8 @@ fn synthesize_rnode(
flow_control,
st_alock,
lt_alock,
id_interval: section.get_uint("id_interval"),
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
id_interval,
id_callsign,
};
// Report invalid user configuration here with its exact section field.
// The lower driver repeats this check before any endpoint I/O so manually
@@ -1252,11 +1336,16 @@ where
Ok(value)
}
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android"
))]
fn parse_generic_rnode_airtime(
name: &str,
section: &ConfigSection,
) -> Result<(bool, Option<f32>, Option<f32>), InterfaceFactoryError> {
) -> Result<(bool, Option<f64>, Option<f64>), InterfaceFactoryError> {
let flow_control = section.get_bool("flow_control").unwrap_or(false);
let st_alock =
parse_generic_rnode_airtime_value(name, section, &["airtime_limit_short", "st_alock"])?;
@@ -1265,21 +1354,27 @@ fn parse_generic_rnode_airtime(
Ok((flow_control, st_alock, lt_alock))
}
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
/// Python `float(c[key])`, kept in double precision for the lock word.
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android"
))]
fn parse_generic_rnode_airtime_value(
name: &str,
section: &ConfigSection,
keys: &[&str],
) -> Result<Option<f32>, InterfaceFactoryError> {
) -> Result<Option<f64>, InterfaceFactoryError> {
let Some((key, raw)) = keys
.iter()
.find_map(|key| section.get(key).map(|value| (*key, value)))
else {
return Ok(None);
};
let value = raw
.parse::<f64>()
.map_err(|_| InterfaceFactoryError::InvalidValue {
let value = section
.get_float(key)
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
field: format!("{name}.{key}"),
message: format!("'{raw}' is not a valid percentage"),
})?;
@@ -1289,7 +1384,45 @@ fn parse_generic_rnode_airtime_value(
message: format!("{value} must be finite and within 0..=100 percent"),
});
}
Ok(Some(value as f32))
Ok(Some(value))
}
/// Station ID as Python `RNodeInterface`/`RNodeMultiInterface` read it:
/// `int(id_interval)` raises on a malformed value, and a callsign longer than
/// `CALLSIGN_MAX_LEN` UTF-8 bytes makes the configuration invalid when both
/// keys are set. A negative interval behaves as zero upstream.
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android"
))]
fn parse_rnode_station_id(
name: &str,
section: &ConfigSection,
) -> Result<(Option<u64>, Option<String>), InterfaceFactoryError> {
let id_interval = match section.get("id_interval") {
None => None,
Some(raw) => Some(
python_int(raw).ok_or_else(|| InterfaceFactoryError::InvalidValue {
field: format!("{name}.id_interval"),
message: format!("'{raw}' is not an integer"),
})?,
),
};
let id_callsign = section.get("id_callsign").map(str::to_string);
if let (Some(_), Some(callsign)) = (id_interval, id_callsign.as_ref())
&& callsign.len() > rns_interface::rnode::CALLSIGN_MAX_LEN
{
return Err(InterfaceFactoryError::InvalidValue {
field: format!("{name}.id_callsign"),
message: format!(
"the encoded ID callsign exceeds the max length of {} bytes",
rns_interface::rnode::CALLSIGN_MAX_LEN
),
});
}
Ok((id_interval.map(|v| v.max(0) as u64), id_callsign))
}
/// Radio parameters are deliberately required: Python errors when they are
@@ -1336,42 +1469,6 @@ fn require_rnode_radio_params(
))
}
/// Shared RNode airtime/flow-control parsing. Python `RNodeInterface.py:156-160`:
/// `flow_control` defaults off, `airtime_limit_short`/`airtime_limit_long` are
/// duty-cycle percentages validated to 0..=100.
#[cfg(feature = "ble")]
fn parse_rnode_airtime(
name: &str,
section: &ConfigSection,
) -> Result<(bool, Option<f32>, Option<f32>), InterfaceFactoryError> {
let flow_control = section.get_bool("flow_control").unwrap_or(false);
let st_alock = section
.get_float("airtime_limit_short")
.or_else(|| section.get_float("st_alock"))
.map(|v| v as f32);
let lt_alock = section
.get_float("airtime_limit_long")
.or_else(|| section.get_float("lt_alock"))
.map(|v| v as f32);
if let Some(v) = st_alock
&& !(0.0..=100.0).contains(&v)
{
return Err(InterfaceFactoryError::InvalidValue {
field: format!("{name}.airtime_limit_short"),
message: format!("{v} is outside 0..=100 percent"),
});
}
if let Some(v) = lt_alock
&& !(0.0..=100.0).contains(&v)
{
return Err(InterfaceFactoryError::InvalidValue {
field: format!("{name}.airtime_limit_long"),
message: format!("{v} is outside 0..=100 percent"),
});
}
Ok((flow_control, st_alock, lt_alock))
}
#[cfg(feature = "ble")]
fn synthesize_ble_rnode(
name: &str,
@@ -1389,7 +1486,8 @@ fn synthesize_ble_rnode(
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
require_rnode_radio_params(name, section)?;
let (flow_control, st_alock, lt_alock) = parse_rnode_airtime(name, section)?;
let (flow_control, st_alock, lt_alock) = parse_generic_rnode_airtime(name, section)?;
let (id_interval, id_callsign) = parse_rnode_station_id(name, section)?;
Ok(InterfaceConfig::BleRNode(BleRNodeInterfaceConfig {
name: name.to_string(),
@@ -1403,8 +1501,9 @@ fn synthesize_ble_rnode(
flow_control,
st_alock,
lt_alock,
id_interval: section.get_uint("id_interval"),
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
id_interval,
id_callsign,
pair_unbonded: parse_bool_strict(name, "ble_auto_pair", section, false)?,
}))
}
@@ -1514,6 +1613,8 @@ fn synthesize_rnode_multi(
.or_else(|| section.get_uint("baud_rate"))
.unwrap_or(115200) as u32;
let (id_interval, id_callsign) = parse_rnode_station_id(name, section)?;
let mut subinterfaces = Vec::new();
let mut seen_vports = std::collections::HashSet::new();
for (sub_name, sub_section) in &section.subsections {
@@ -1564,14 +1665,16 @@ fn synthesize_rnode_multi(
require_rnode_radio_params(&sub_full_name, sub_section)?;
let flow_control = sub_section.get_bool("flow_control").unwrap_or(false);
let outgoing = sub_section.get_bool("outgoing").unwrap_or(true);
let st_alock = sub_section
.get_float("airtime_limit_short")
.or_else(|| sub_section.get_float("st_alock"))
.map(|v| v as f32);
let lt_alock = sub_section
.get_float("airtime_limit_long")
.or_else(|| sub_section.get_float("lt_alock"))
.map(|v| v as f32);
let st_alock = parse_generic_rnode_airtime_value(
sub_name,
sub_section,
&["airtime_limit_short", "st_alock"],
)?;
let lt_alock = parse_generic_rnode_airtime_value(
sub_name,
sub_section,
&["airtime_limit_long", "lt_alock"],
)?;
let parsed = RNodeSubInterfaceConfig {
name: sub_name.clone(),
@@ -1616,8 +1719,8 @@ fn synthesize_rnode_multi(
baud_rate,
subinterfaces,
mode,
id_interval: section.get_uint("id_interval"),
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
id_interval,
id_callsign,
}))
}
@@ -1699,10 +1802,7 @@ fn synthesize_ax25kiss(
})?
.to_string();
let baud_rate = section
.get_uint("speed")
.or_else(|| section.get_uint("baud_rate"))
.unwrap_or(9600) as u32;
let baud_rate = parse_serial_line_value(name, section, &["speed", "baud_rate"], 9600u32)?;
// Python AX25KISSInterface requires an explicit 0..=15 SSID
// (default -1 fails validation, AX25KISSInterface.py:138-139).
@@ -1732,9 +1832,9 @@ fn synthesize_ax25kiss(
name: name.to_string(),
port,
baud_rate,
data_bits: section.get_uint("databits").unwrap_or(8) as u8,
data_bits: parse_serial_line_value(name, section, &["databits"], 8u8)?,
parity: section.get("parity").unwrap_or("N").to_string(),
stop_bits: section.get_uint("stopbits").unwrap_or(1) as u8,
stop_bits: parse_serial_line_value(name, section, &["stopbits"], 1u8)?,
callsign,
ssid,
preamble,
@@ -2033,6 +2133,65 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
#[cfg(test)]
mod tests {
#[cfg(feature = "serial")]
#[test]
fn android_usb_serial_ports_are_refused_off_android() {
for kind in ["SerialInterface", "KISSInterface", "AX25KISSInterface"] {
let mut s = ConfigSection::new();
for (k, v) in [
("type", kind),
("enabled", "yes"),
("port", "androidusb:///dev/bus/usb/001/002"),
("callsign", "N0CALL"),
("ssid", "0"),
] {
s.set(k, v);
}
let parsed = synthesize_interface("usb", &s);
assert!(
matches!(parsed, Err(InterfaceFactoryError::Disabled(_))),
"{kind}: {parsed:?}"
);
}
}
#[test]
fn android_rnode_keys_select_the_transport_like_upstream() {
let section = |keys: &[(&str, &str)]| {
let mut s = ConfigSection::new();
for (k, v) in keys {
s.set(k, v);
}
s
};
let port = |keys: &[(&str, &str)]| android_rnode_port("rn", &section(keys)).unwrap();
assert_eq!(
port(&[("ble_name", "RNode A1B2")]),
Some("ble://RNode A1B2".into())
);
assert_eq!(
port(&[
("ble_name", "RNode A1B2"),
("ble_addr", "AA:BB:CC:DD:EE:FF")
]),
Some("ble://AA:BB:CC:DD:EE:FF".into())
);
assert_eq!(port(&[("force_ble", "no")]), Some("ble://".into()));
assert_eq!(
port(&[("tcp_host", "10.0.0.2")]),
Some("tcp://10.0.0.2".into())
);
assert_eq!(
port(&[("tcp_host", "10.0.0.2"), ("ble_name", "RNode A1B2")]),
Some("ble://RNode A1B2".into())
);
assert_eq!(port(&[]), None);
assert!(matches!(
android_rnode_port("rn", &section(&[("allow_bluetooth", "yes")])),
Err(InterfaceFactoryError::Disabled(_))
));
}
use super::*;
/// Fixtures are enabled unless a test says otherwise; upstream skips a
+13
View File
@@ -5708,6 +5708,19 @@ impl LinkManager {
rns_wire::flags::PacketType::Data,
)
}
TransferAction::QueryProofCache(proof_data) => {
return Self::stage_link_control(
transport_tx,
pending_link_control,
TransportMessage::CacheRequest {
packet_hash: rns_protocol::resource::resource_proof_packet_hash(
link_id,
&proof_data,
),
destination_hash: *link_id,
},
);
}
TransferAction::None | TransferAction::Complete | TransferAction::Failed(_) => {
return false;
}
+14 -1
View File
@@ -2327,6 +2327,18 @@ async fn send_resource_action(
rns_wire::flags::PacketType::Data,
)
}
TransferAction::QueryProofCache(proof_data) => {
return transport_tx
.send(TransportMessage::CacheRequest {
packet_hash: rns_protocol::resource::resource_proof_packet_hash(
&link.link_id,
&proof_data,
),
destination_hash: link.link_id,
})
.await
.map_err(|_| LinkSessionResourceError::TransportUnavailable);
}
TransferAction::None | TransferAction::Complete | TransferAction::Failed(_) => {
return Ok(());
}
@@ -3510,7 +3522,8 @@ async fn handle_inbound_resource_part(
TransferAction::None
| TransferAction::SendAdvertisement(_)
| TransferAction::SendPart(_, _)
| TransferAction::SendProof(_) => {}
| TransferAction::SendProof(_)
| TransferAction::QueryProofCache(_) => {}
}
if complete {
complete_inbound_segment(
+58 -21
View File
@@ -4802,19 +4802,22 @@ struct OwnedInterfaceHandle {
/// `panic_on_interface_error` is set.
#[derive(Clone)]
enum HardwareFailureWatch {
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
RNode(rns_interface::rnode::RNodeDriverSubscription),
#[cfg(feature = "serial")]
RNodeMulti(rns_interface::rnode_multi::RNodeMultiFailures),
/// TCP or Backbone client teardown (TCPInterface.py:437-442).
ClientTeardown(rns_interface::tcp::ClientTeardown),
/// Serial, KISS or AX.25 KISS runtime port error (SerialInterface.py:203-210).
#[cfg(feature = "serial")]
Serial(rns_interface::serial::SerialFailures),
}
impl HardwareFailureWatch {
/// True at the first failure, false if the driver ends without one.
async fn failed(&mut self) -> bool {
match self {
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
Self::RNode(state) => loop {
if state.snapshot().hardware_failure_total > 0 {
return true;
@@ -4833,6 +4836,15 @@ impl HardwareFailureWatch {
}
},
Self::ClientTeardown(teardown) => teardown.torn_down().await,
#[cfg(feature = "serial")]
Self::Serial(failures) => loop {
if failures.total() > 0 {
return true;
}
if failures.changed().await.is_none() {
return false;
}
},
}
}
}
@@ -4846,6 +4858,16 @@ fn client_with_teardown(
}]
}
#[cfg(feature = "serial")]
fn serial_with_failures(
spawned: rns_interface::serial::SpawnedSerialInterface,
) -> Vec<OwnedInterfaceHandle> {
vec![OwnedInterfaceHandle {
hardware_failures: Some(HardwareFailureWatch::Serial(spawned.failures)),
..spawned.interface.into()
}]
}
fn spawn_interface_panic_monitor(
name: String,
mut failures: HardwareFailureWatch,
@@ -9041,10 +9063,10 @@ pub struct BleRnodeRuntimeArgs<'a> {
pub mode: rns_interface::traits::InterfaceMode,
/// Short-term airtime limit in percent (0.0..=100.0). `None` sends no
/// limit command and does not clear a limit retained on the radio.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime limit in percent (0.0..=100.0). `None` sends no
/// limit command and does not clear a limit retained on the radio.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Enable KISS flow control.
pub flow_control: bool,
}
@@ -9184,10 +9206,10 @@ pub struct RnodeRuntimeArgs<'a> {
pub mode: rns_interface::traits::InterfaceMode,
/// Short-term airtime limit in percent (0.0..=100.0). `None` sends no
/// limit command and does not clear a limit retained on the radio.
pub st_alock: Option<f32>,
pub st_alock: Option<f64>,
/// Long-term airtime limit in percent (0.0..=100.0). `None` sends no
/// limit command and does not clear a limit retained on the radio.
pub lt_alock: Option<f32>,
pub lt_alock: Option<f64>,
/// Enable KISS flow control.
pub flow_control: bool,
}
@@ -9376,6 +9398,7 @@ pub async fn spawn_ble_rnode_runtime_native_observed_with_options(
lt_alock,
id_interval: None,
id_callsign: None,
pair_unbonded: false,
},
tcp_port,
rnode_startup_options,
@@ -9405,6 +9428,7 @@ fn native_ble_driver_config(
config.flow_control = source.flow_control;
config.id_interval = source.id_interval;
config.id_callsign = source.id_callsign.map(String::into_bytes);
config.pair_unbonded = source.pair_unbonded;
config.validate().map_err(|error| {
RNodeRuntimeSpawnError::InvalidConfiguration(format!(
"invalid value for '{name}.{}': {error}",
@@ -9630,8 +9654,8 @@ pub async fn spawn_android_usb_rnode_runtime(
coding_rate: u8,
tx_power: i8,
mode: rns_interface::traits::InterfaceMode,
st_alock: Option<f32>,
lt_alock: Option<f32>,
st_alock: Option<f64>,
lt_alock: Option<f64>,
flow_control: bool,
) -> Result<u64, String> {
let spawned = spawn_android_usb_rnode_runtime_observed(
@@ -9667,8 +9691,8 @@ pub async fn spawn_android_usb_rnode_runtime_observed(
coding_rate: u8,
tx_power: i8,
mode: rns_interface::traits::InterfaceMode,
st_alock: Option<f32>,
lt_alock: Option<f32>,
st_alock: Option<f64>,
lt_alock: Option<f64>,
flow_control: bool,
) -> Result<SpawnedRNodeRuntime, String> {
spawn_android_usb_rnode_runtime_observed_with_options(
@@ -9703,8 +9727,8 @@ pub async fn spawn_android_usb_rnode_runtime_observed_with_options(
coding_rate: u8,
tx_power: i8,
mode: rns_interface::traits::InterfaceMode,
st_alock: Option<f32>,
lt_alock: Option<f32>,
st_alock: Option<f64>,
lt_alock: Option<f64>,
flow_control: bool,
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
) -> Result<SpawnedRNodeRuntime, RNodeRuntimeSpawnError> {
@@ -9985,9 +10009,9 @@ async fn spawn_interface_with_rnode_startup_options(
serial_config.data_bits = data;
serial_config.parity = parity;
serial_config.stop_bits = stop;
rns_interface::serial::spawn_serial_interface(serial_config, id, transport_tx)
rns_interface::serial::spawn_serial_interface_observed(serial_config, id, transport_tx)
.await
.map(|h| vec![h.into()])
.map(serial_with_failures)
.map_err(|e| format!("Serial: {e}"))
}
#[cfg(feature = "serial")]
@@ -10010,9 +10034,9 @@ async fn spawn_interface_with_rnode_startup_options(
kiss_config.flow_control = c.flow_control;
kiss_config.id_interval = c.id_interval;
kiss_config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
rns_interface::kiss_iface::spawn_kiss_interface(kiss_config, id, transport_tx)
rns_interface::kiss_iface::spawn_kiss_interface_observed(kiss_config, id, transport_tx)
.await
.map(|h| vec![h.into()])
.map(serial_with_failures)
.map_err(|e| format!("KISS: {e}"))
}
interface_factory::InterfaceConfig::Auto(c) => {
@@ -10079,7 +10103,13 @@ async fn spawn_interface_with_rnode_startup_options(
rnode_startup_options,
)
.await
.map(|spawned| vec![spawned.into()])
.map(|spawned| {
let failures = HardwareFailureWatch::RNode(spawned.driver.watch());
vec![OwnedInterfaceHandle {
hardware_failures: Some(failures),
..spawned.into()
}]
})
.map_err(|error| format!("Android USB RNode: {error}"));
}
@@ -10268,10 +10298,14 @@ async fn spawn_interface_with_rnode_startup_options(
ax25_config.slottime = c.slottime as u16;
ax25_config.flow_control = c.flow_control;
ax25_config.mode = c.mode;
rns_interface::ax25kiss::spawn_ax25kiss_interface(ax25_config, id, transport_tx)
.await
.map(|h| vec![h.into()])
.map_err(|e| format!("AX25KISS: {e}"))
rns_interface::ax25kiss::spawn_ax25kiss_interface_observed(
ax25_config,
id,
transport_tx,
)
.await
.map(serial_with_failures)
.map_err(|e| format!("AX25KISS: {e}"))
}
#[cfg(feature = "ble")]
interface_factory::InterfaceConfig::BleRNode(c) => {
@@ -10287,6 +10321,7 @@ async fn spawn_interface_with_rnode_startup_options(
config.lt_alock = c.lt_alock;
config.id_interval = c.id_interval;
config.id_callsign = c.id_callsign.as_ref().map(|s| s.as_bytes().to_vec());
config.pair_unbonded = c.pair_unbonded;
rns_interface::ble_rnode::spawn_ble_rnode_interface_with_driver_and_options(
config,
id,
@@ -11908,6 +11943,7 @@ mod tests {
lt_alock: Some(3.25),
id_interval: Some(900),
id_callsign: Some("N0CALL".into()),
pair_unbonded: false,
})
.expect("valid typed native BLE config");
@@ -16888,6 +16924,7 @@ listen_port = 5556
lt_alock: Some(3.25),
id_interval: Some(900),
id_callsign: Some("N0CALL".into()),
pair_unbonded: false,
},
)
};
+16 -1
View File
@@ -1209,6 +1209,19 @@ async fn send_transfer_action(
return Ok(());
}
if let TransferAction::QueryProofCache(proof_data) = action {
return transport_tx
.send(TransportMessage::CacheRequest {
packet_hash: rns_protocol::resource::resource_proof_packet_hash(
&link_id,
&proof_data,
),
destination_hash: link_id,
})
.await
.map_err(|_| RncpError::TransportUnavailable);
}
let (context, body) = match action {
TransferAction::SendAdvertisement(adv) => {
let encrypted = link
@@ -1255,7 +1268,9 @@ async fn send_transfer_action(
};
(context, Bytes::from(encrypted))
}
TransferAction::SendProof(_) => unreachable!("proof handled before data-packet match"),
TransferAction::SendProof(_) | TransferAction::QueryProofCache(_) => {
unreachable!("handled before data-packet match")
}
TransferAction::None | TransferAction::Complete => return Ok(()),
TransferAction::Failed(reason) => return Err(RncpError::ResourceFailed(reason)),
};
+12
View File
@@ -67,3 +67,15 @@ path = "src/bin/rnodeconf-rs.rs"
[[bin]]
name = "rnsh-rs"
path = "src/bin/rnsh-rs.rs"
[[bin]]
name = "rnir-rs"
path = "src/bin/rnir-rs.rs"
[[bin]]
name = "rnpkg-rs"
path = "src/bin/rnpkg-rs.rs"
[[bin]]
name = "rnx-rs"
path = "src/bin/rnx-rs.rs"
+6
View File
@@ -0,0 +1,6 @@
#[path = "../commands/rnir.rs"]
mod rnir;
fn main() {
rnir::main()
}
+6
View File
@@ -0,0 +1,6 @@
#[path = "../commands/rnpkg.rs"]
mod rnpkg;
fn main() {
rnpkg::main()
}
+6
View File
@@ -0,0 +1,6 @@
#[path = "../commands/rnx.rs"]
mod rnx;
fn main() {
rnx::main()
}
+70 -102
View File
@@ -39,12 +39,11 @@ fn expand_tilde(p: &str) -> PathBuf {
use rns_identity::identity::Identity;
use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
use rns_runtime::platform::StoragePaths;
use rns_runtime::reticulum::{InstanceMode, ReticulumHandle, SharedInstanceRpcEndpoint};
use rns_runtime::reticulum::ReticulumHandle;
use rns_runtime::rncp::{
DEFAULT_RNCP_APP_NAME, RncpError, RncpEvent, RncpFetchRequest, RncpListenerConfig,
RncpSendRequest, default_rncp_app_name, rncp_fetch_file, rncp_send_file, spawn_rncp_listener,
};
use rns_runtime::rpc::{RpcRequest, RpcResponse};
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
use rns_tools::RS_RETICULUM_VERSION;
@@ -162,7 +161,11 @@ const SYMS: [char; 7] = ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'];
/// rncp.py:54-68 (`prepare_identity`): `-i` is used as given, and an identity
/// that cannot be saved is still used for this run.
fn prepare_identity(identity_path: Option<&str>, default_dir: &std::path::Path) -> Identity {
async fn prepare_identity(
handle: &ReticulumHandle,
identity_path: Option<&str>,
default_dir: &std::path::Path,
) -> Identity {
let path = match identity_path {
Some(p) => PathBuf::from(p),
None => default_dir.join("rncp"),
@@ -175,7 +178,7 @@ fn prepare_identity(identity_path: Option<&str>, default_dir: &std::path::Path)
"Could not load identity for rncp. The identity file at \"{}\" may be corrupt or unreadable.",
path.display()
);
process::exit(2);
rns_tools::exit(handle, 2).await;
}
}
}
@@ -498,14 +501,14 @@ async fn wait_for_path(
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
_ = interrupt.wait() => {
println!();
process::exit(0);
rns_tools::exit(handle, 0).await;
}
}
}
}
if !has_path().await {
ui.finish("Path not found", &format!("{ERASE}Path not found"));
process::exit(1);
rns_tools::exit(handle, 1).await;
}
ui.step(
&format!("Establishing link with {h}"),
@@ -557,7 +560,8 @@ async fn run_fetch(args: Args) -> ! {
let handle = start_interruptible(args.config.as_deref(), &interrupt).await;
handle.wants_destination_type(DEFAULT_RNCP_APP_NAME).await;
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = prepare_identity(args.identity_path.as_deref(), &paths.identity_dir);
let identity =
prepare_identity(&handle, args.identity_path.as_deref(), &paths.identity_dir).await;
let ui = Ui::new(args.silent, true);
let h = pretty_hex_rep(&dest_hash);
@@ -612,23 +616,17 @@ async fn run_fetch(args: Args) -> ! {
let _ = progress_task.await;
let fail = |line: &str, code: i32| -> ! {
ui.finish(line, &format!("{ERASE}{line}"));
process::exit(code);
};
let link_failed = || -> ! {
fail(&format!("Could not establish link with {h}"), 1);
};
let transfer_failed = |preface: &str| -> ! {
let fail = |line: &str| ui.finish(line, &format!("{ERASE}{line}"));
let transfer_failed = |preface: &str| {
println!("{preface}");
fail("The transfer failed", 1);
fail("The transfer failed");
};
// rncp.py:543-567: every answered request failure exits 0.
match result {
Err(RncpError::Interrupted) => {
println!();
process::exit(0);
rns_tools::exit(&handle, 0).await;
}
Err(
RncpError::PathTimeout
@@ -637,11 +635,14 @@ async fn run_fetch(args: Args) -> ! {
| RncpError::HandshakeFailed(_)
| RncpError::ProofInvalid(_)
| RncpError::RequestDispatch(_),
) => link_failed(),
) => {
fail(&format!("Could not establish link with {h}"));
rns_tools::exit(&handle, 1).await;
}
_ => {}
}
show_requesting();
match result {
let code = match result {
Ok(outcome) => {
let total = resource_total_size(outcome.bytes as u64, &outcome.file_name);
let line = {
@@ -662,38 +663,49 @@ async fn run_fetch(args: Args) -> ! {
print!("{ERASE}Transfer complete {line} ");
println!("\n{path_arg} fetched from {h}");
}
process::exit(0);
0
}
Err(RncpError::Denied) => fail(
&format!(
Err(RncpError::Denied) => {
fail(&format!(
"Fetch request failed, fetching the file {path_arg} was not allowed by the remote"
),
0,
),
Err(RncpError::NotFound) => fail(
&format!("Fetch request failed, the file {path_arg} was not found on the remote"),
0,
),
Err(RncpError::RemoteError) => fail(
"Fetch request failed due to an error on the remote system",
0,
),
Err(RncpError::RequestFailed) => fail(
"Fetch request failed due to an unknown error (probably not authorised)",
0,
),
));
0
}
Err(RncpError::NotFound) => {
fail(&format!(
"Fetch request failed, the file {path_arg} was not found on the remote"
));
0
}
Err(RncpError::RemoteError) => {
fail("Fetch request failed due to an error on the remote system");
0
}
Err(RncpError::RequestFailed) => {
fail("Fetch request failed due to an unknown error (probably not authorised)");
0
}
Err(RncpError::ResourceFailed(reason)) if reason == "invalid data received" => {
transfer_failed("Invalid data received, ignoring resource")
transfer_failed("Invalid data received, ignoring resource");
1
}
Err(RncpError::ResourceFailed(_)) => {
transfer_failed("Resource failed");
1
}
Err(RncpError::Io(e)) => {
transfer_failed(&format!(
"An error occurred while saving received resource: {e}"
));
1
}
Err(RncpError::ResourceFailed(_)) => transfer_failed("Resource failed"),
Err(RncpError::Io(e)) => transfer_failed(&format!(
"An error occurred while saving received resource: {e}"
)),
Err(e) => {
tracing::debug!("Fetch failed: {e}");
fail("The transfer failed", 1)
fail("The transfer failed");
1
}
}
};
rns_tools::exit(&handle, code).await;
}
async fn run_send(args: Args) -> ! {
@@ -730,7 +742,8 @@ async fn run_send(args: Args) -> ! {
let handle = start_interruptible(args.config.as_deref(), &interrupt).await;
handle.wants_destination_type(DEFAULT_RNCP_APP_NAME).await;
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = prepare_identity(args.identity_path.as_deref(), &paths.identity_dir);
let identity =
prepare_identity(&handle, args.identity_path.as_deref(), &paths.identity_dir).await;
let ui = Ui::new(args.silent, false);
let h = pretty_hex_rep(&dest_hash);
@@ -743,7 +756,7 @@ async fn run_send(args: Args) -> ! {
&format!("Could not start transfer: {e}"),
&format!("Could not start transfer: {e}"),
);
process::exit(1);
rns_tools::exit(&handle, 1).await;
}
};
let data_size = file.metadata().map(|m| m.len()).unwrap_or(0);
@@ -802,10 +815,7 @@ async fn run_send(args: Args) -> ! {
let _ = progress_task.await;
let fail = |line: &str| -> ! {
ui.finish(line, &format!("{ERASE}{line}"));
process::exit(1);
};
let fail = |line: &str| ui.finish(line, &format!("{ERASE}{line}"));
match result {
Ok(_) => {
@@ -826,14 +836,14 @@ async fn run_send(args: Args) -> ! {
print!("{ERASE}Transfer complete {line} ");
println!("\n{path} copied to {h}");
}
process::exit(0);
rns_tools::exit(&handle, 0).await;
}
Err(RncpError::Interrupted) => {
println!();
process::exit(0);
rns_tools::exit(&handle, 0).await;
}
Err(RncpError::PathTimeout | RncpError::NoIdentity) => {
fail(&format!("No path found to {h}"))
fail(&format!("No path found to {h}"));
}
Err(
RncpError::Timeout(_)
@@ -844,13 +854,14 @@ async fn run_send(args: Args) -> ! {
Err(RncpError::ResourceCreate(e)) => fail(&format!("Could not start transfer: {e}")),
Err(e) if !transferring.load(Ordering::SeqCst) => {
tracing::debug!("Transfer failed: {e}");
fail(&format!("File was not accepted by {h}"))
fail(&format!("File was not accepted by {h}"));
}
Err(e) => {
tracing::debug!("Transfer failed: {e}");
fail("The transfer failed")
fail("The transfer failed");
}
}
rns_tools::exit(&handle, 1).await;
}
async fn run_listen(args: Args) -> ! {
@@ -893,7 +904,8 @@ async fn run_listen(args: Args) -> ! {
};
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = prepare_identity(args.identity_path.as_deref(), &paths.identity_dir);
let identity =
prepare_identity(&handle, args.identity_path.as_deref(), &paths.identity_dir).await;
let announce_identity = identity
.get_private_key()
.and_then(|key| Identity::from_private_key(&*key).ok());
@@ -1009,7 +1021,7 @@ async fn run_listen(args: Args) -> ! {
}
listener.shutdown().await;
process::exit(0);
rns_tools::exit(&handle, 0).await;
}
fn spawn_listen_announcer(
@@ -1154,7 +1166,7 @@ async fn start_interruptible(
/// `max(-w, reticulum.get_medium_path_timeout())` (rncp.py:405, 662).
async fn path_timeout(handle: &ReticulumHandle, timeout: f64) -> Duration {
let medium = medium_path_timeout(handle).await;
let medium = rns_tools::medium_path_timeout(handle).await;
let secs = if timeout.is_finite() {
timeout.max(medium)
} else {
@@ -1163,50 +1175,6 @@ async fn path_timeout(handle: &ReticulumHandle, timeout: f64) -> Duration {
Duration::try_from_secs_f64(secs.max(0.0)).unwrap_or(Duration::MAX)
}
/// Reticulum.get_medium_path_timeout (Reticulum.py:2011-2029): ask the shared
/// instance, or compute Transport.medium_path_timeout (Transport.py:3550-3553)
/// from the lowest online interface bitrate. 0 when unknown or on error.
async fn medium_path_timeout(handle: &ReticulumHandle) -> f64 {
if handle.instance_mode == InstanceMode::Client {
let Some(rpc_key) = handle.config.rpc_key.as_deref() else {
return 0.0;
};
let request = RpcRequest::GetMediumPathTimeout;
let timeout = Duration::from_secs(5);
let response = match handle.config.shared_rpc_endpoint(&handle.socket_base) {
SharedInstanceRpcEndpoint::Tcp(port) => {
rns_runtime::rpc::connect_and_request(port, rpc_key, &request, timeout).await
}
SharedInstanceRpcEndpoint::Unix(path) => {
rns_runtime::rpc::connect_unix_and_request(&path, rpc_key, &request, timeout).await
}
};
return match response {
Ok(RpcResponse::FloatResult(Some(v))) if v.is_finite() => v,
_ => 0.0,
};
}
let lowest = match handle
.query_transport(rns_transport::messages::TransportQuery::GetInterfaceStats)
.await
{
Some(rns_transport::messages::TransportQueryResponse::InterfaceStats(entries)) => entries
.iter()
.filter(|entry| entry.online && entry.bitrate > 0)
.map(|entry| entry.bitrate)
.min(),
_ => None,
};
match lowest {
Some(bitrate) => {
let bits = (rns_wire::constants::MTU * 8) as f64;
2.0 * (bits / bitrate.max(rns_runtime::constants::MINIMUM_BITRATE) as f64)
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT
}
None => 0.0,
}
}
async fn start_reticulum(
config_dir: Option<&str>,
shutdown: ShutdownSignal,
+2 -41
View File
@@ -3,12 +3,6 @@
//! Port of `RNS/Utilities/rnid.py` from Reticulum 1.6.0: operation order,
//! exit codes and the text printed on stdout follow the Python tool.
mod b256;
mod meta;
mod pyfmt;
mod pyre;
mod rsg;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::process::ExitCode;
@@ -34,6 +28,8 @@ mod hw_commands;
use rns_tools::RS_RETICULUM_VERSION;
use rns_tools::format::pretty_size;
use rns_tools::rsg::pyfmt::{self, py_fromhex, py_os_error};
use rns_tools::rsg::{self, b256, meta};
const DEFAULT_ASPECTS: &str = "rns.id";
const NO_MESSAGE: &str = "\u{1}";
@@ -527,41 +523,6 @@ fn is_file(path: &str) -> bool {
Path::new(path).is_file()
}
/// Python `str(OSError)` for a failed file operation.
fn py_os_error(error: &std::io::Error, path: &str) -> String {
match error.raw_os_error() {
Some(code) => format!(
"[Errno {code}] {}: {}",
nix::errno::Errno::from_raw(code).desc(),
pyfmt::py_str_repr(path)
),
None => error.to_string(),
}
}
/// `bytes.fromhex`.
fn py_fromhex(text: &str) -> Result<Vec<u8>, String> {
let chars: Vec<char> = text.chars().collect();
let err =
|pos: usize| format!("non-hexadecimal number found in fromhex() arg at position {pos}");
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
if matches!(chars[i], ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r') {
i += 1;
continue;
}
let hi = chars[i].to_digit(16).ok_or_else(|| err(i))?;
let lo = chars
.get(i + 1)
.and_then(|c| c.to_digit(16))
.ok_or_else(|| err(i + 1))?;
out.push((hi * 16 + lo) as u8);
i += 2;
}
Ok(out)
}
/// `base64.b32decode` (strict alphabet and padding).
fn py_b32decode(text: &str) -> Option<Vec<u8>> {
if !text.is_ascii() || !text.len().is_multiple_of(8) {
+60
View File
@@ -0,0 +1,60 @@
//! rnir-rs — Reticulum Distributed Identity Resolver (RNS/Utilities/rnir.py): starts Reticulum and exits 0.
use clap::Parser;
use rns_runtime::lifecycle::ShutdownSignal;
use rns_tools::RS_RETICULUM_VERSION;
#[derive(Parser)]
#[command(
name = "rnir-rs",
about = "Reticulum Distributed Identity Resolver",
disable_version_flag = true
)]
struct Args {
/// path to alternative Reticulum config directory
#[arg(long)]
config: Option<String>,
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbose: u8,
#[arg(short = 'q', long = "quiet", action = clap::ArgAction::Count)]
quiet: u8,
/// print version and exit
#[arg(long)]
version: bool,
}
#[tokio::main]
pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rnir-rs {RS_RETICULUM_VERSION}");
return;
}
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
let configured = rns_runtime::config::Config::from_file(&config_dir.join("config"))
.ok()
.and_then(|c| c.section("logging")?.get_int("loglevel"));
let level = rns_tools::Utility::Rnir.loglevel(configured, args.verbose, args.quiet, false);
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stdout,
);
let foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
match rns_runtime::reticulum::init(
args.config.as_deref(),
None,
ShutdownSignal::new(),
foreground,
)
.await
{
Ok(handle) => rns_tools::exit(&handle, 0).await,
Err(e) => {
eprintln!("failed to start reticulum: {e}");
std::process::exit(1);
}
}
}
+29 -11
View File
@@ -197,32 +197,46 @@ pub(crate) async fn main() -> ExitCode {
Ok(ctx) => ctx,
Err(code) => return code,
};
// rnpath.py:108-110
let registration = rns_tools::RpcRegistration::want(
ctx.endpoint.clone(),
ctx.rpc_key.clone(),
&[MGMT_APP, BLACKHOLE_APP],
LOCAL_RPC_TIMEOUT,
)
.await;
let code = dispatch_local(&args, &ctx, destination).await;
registration.release().await;
code
}
async fn dispatch_local(args: &Args, ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
// Dispatch order of rnpath.py:132-490.
if args.blackholed {
return show_blackholed(&ctx, destination).await;
return show_blackholed(ctx, destination).await;
}
if args.blackhole {
return do_blackhole(&ctx, destination, args.duration, args.reason.clone()).await;
return do_blackhole(ctx, destination, args.duration, args.reason.clone()).await;
}
if args.unblackhole {
return do_unblackhole(&ctx, destination).await;
return do_unblackhole(ctx, destination).await;
}
if args.table {
return show_path_table(&ctx, destination, args.max, args.json, args.usage).await;
return show_path_table(ctx, destination, args.max, args.json, args.usage).await;
}
if args.rates {
return show_rate_table(&ctx, destination, args.json).await;
return show_rate_table(ctx, destination, args.json).await;
}
if args.drop_announces {
return drop_announces(&ctx).await;
return drop_announces(ctx).await;
}
if args.drop {
return drop_path(&ctx, destination).await;
return drop_path(ctx, destination).await;
}
if args.drop_via {
return drop_all_via(&ctx, destination).await;
return drop_all_via(ctx, destination).await;
}
query_path(&ctx, destination, args.timeout).await
query_path(ctx, destination, args.timeout).await
}
/// rnpath.py:249-255 and its copies: a 32-character hex destination.
@@ -1065,7 +1079,7 @@ fn now_epoch() -> f64 {
/// Start the runtime used for `-R` and `-p`, as rnpath.py:108 does.
async fn start_runtime(args: &Args) -> Result<ReticulumHandle, ExitCode> {
init(
let handle = init(
args.config.as_deref(),
None,
ShutdownSignal::new(),
@@ -1075,7 +1089,11 @@ async fn start_runtime(args: &Args) -> Result<ReticulumHandle, ExitCode> {
.map_err(|e| {
eprintln!("rnpath-rs: failed to initialize Reticulum runtime: {e:?}");
ExitCode::from(1)
})
})?;
// rnpath.py:108-110
handle.wants_destination_type(MGMT_APP).await;
handle.wants_destination_type(BLACKHOLE_APP).await;
Ok(handle)
}
async fn stop_runtime(handle: ReticulumHandle, code: ExitCode) -> ExitCode {
+70
View File
@@ -0,0 +1,70 @@
//! rnpkg-rs — Reticulum Meta Package Manager (RNS/Utilities/rnpkg.py): starts Reticulum and exits 0.
use clap::Parser;
use rns_runtime::lifecycle::ShutdownSignal;
use rns_tools::RS_RETICULUM_VERSION;
/// `__example_rnpkg_config__` (rnpkg.py:76-77).
const EXAMPLE_CONFIG: &str = "# This is an example package manager configuration file.\n";
#[derive(Parser)]
#[command(
name = "rnpkg-rs",
about = "Reticulum Meta Package Manager",
disable_version_flag = true
)]
struct Args {
/// path to alternative Reticulum config directory
#[arg(long)]
config: Option<String>,
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbose: u8,
#[arg(short = 'q', long = "quiet", action = clap::ArgAction::Count)]
quiet: u8,
/// print verbose configuration example to stdout and exit
#[arg(long)]
exampleconfig: bool,
/// print version and exit
#[arg(long)]
version: bool,
}
#[tokio::main]
pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rnpkg-rs {RS_RETICULUM_VERSION}");
return;
}
if args.exampleconfig {
println!("{EXAMPLE_CONFIG}");
return;
}
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
let configured = rns_runtime::config::Config::from_file(&config_dir.join("config"))
.ok()
.and_then(|c| c.section("logging")?.get_int("loglevel"));
let level = rns_tools::Utility::Rnpkg.loglevel(configured, args.verbose, args.quiet, false);
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stdout,
);
let foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
match rns_runtime::reticulum::init(
args.config.as_deref(),
None,
ShutdownSignal::new(),
foreground,
)
.await
{
Ok(handle) => rns_tools::exit(&handle, 0).await,
Err(e) => {
eprintln!("failed to start reticulum: {e}");
std::process::exit(1);
}
}
}
+3 -1
View File
@@ -267,7 +267,7 @@ async fn stop_reticulum(
runtime_shutdown: &ShutdownSignal,
) {
runtime_shutdown.trigger();
let _ = tokio::time::timeout(Duration::from_secs(5), handle.shutdown_and_wait()).await;
rns_tools::shut_down(handle).await;
}
async fn run_initiator(args: Args, config_dir: PathBuf) -> ExitCode {
@@ -367,6 +367,8 @@ async fn run_initiator(args: Args, config_dir: PathBuf) -> ExitCode {
progress_tx: Some(progress_tx),
};
// initiator.py:156
handle.wants_destination_type(APP_NAME).await;
let result = rnsh_client_execute(handle.transport_tx.clone(), cfg).await;
terminate_task.abort();
let _ = progress_task.await;
+53 -7
View File
@@ -18,7 +18,7 @@ use rns_runtime::lifecycle::ShutdownSignal;
use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_runtime::platform::StoragePaths;
use rns_runtime::platform::resolve_config_dir;
use rns_runtime::reticulum::{ReticulumConfig, SharedInstanceRpcEndpoint, init};
use rns_runtime::reticulum::{ReticulumConfig, ReticulumHandle, SharedInstanceRpcEndpoint, init};
use rns_runtime::rpc::{self, RpcRequest, RpcResponse};
use rns_tools::{format, hash};
use rns_transport::discovery::{DiscoveredInterface, DiscoveryStatus, DiscoveryStore};
@@ -175,7 +175,22 @@ async fn run_monitor(args: Args) -> ExitCode {
} else {
None
};
let registration = match session {
Some(_) => None,
None => local_registration(&args).await,
};
let interrupt = ShutdownSignal::new();
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(interrupt.clone());
loop {
if interrupt.is_triggered() {
if let Some(session) = &session {
rns_tools::shut_down(&session.handle).await;
}
if let Some(registration) = registration {
registration.release().await;
}
return ExitCode::SUCCESS;
}
let started = std::time::Instant::now();
print!("\x1b[2J\x1b[H");
let exit = match &session {
@@ -184,11 +199,17 @@ async fn run_monitor(args: Args) -> ExitCode {
};
if exit != ExitCode::SUCCESS {
if let Some(session) = &session {
session.shutdown.trigger();
rns_tools::shut_down(&session.handle).await;
}
if let Some(registration) = registration {
registration.release().await;
}
return exit;
}
tokio::time::sleep(monitor_sleep(args.monitor_interval, started.elapsed())).await;
tokio::select! {
_ = tokio::time::sleep(monitor_sleep(args.monitor_interval, started.elapsed())) => {}
_ = interrupt.wait() => {}
}
}
}
@@ -198,7 +219,30 @@ fn monitor_sleep(interval_secs: f64, elapsed: Duration) -> Duration {
}
async fn run_local(args: Args) -> ExitCode {
run_local_once(&args).await
let registration = local_registration(&args).await;
let exit = run_local_once(&args).await;
if let Some(registration) = registration {
registration.release().await;
}
exit
}
/// The type registration upstream rnstatus makes on the shared instance it
/// reads (rnstatus.py:174, 928); released again before the tool exits.
async fn local_registration(args: &Args) -> Option<rns_tools::RpcRegistration> {
let config_dir = resolve_config_dir(args.config.as_deref());
let config = Config::from_file(&config_dir.join("config")).ok()?;
let rc = ReticulumConfig::from_config(&config);
let rpc_key = local_rpc_key(&config_dir, &rc)?;
Some(
rns_tools::RpcRegistration::want(
rc.shared_rpc_endpoint(&std::env::temp_dir()),
rpc_key,
&[MGMT_APP],
Duration::from_secs(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)),
)
.await,
)
}
async fn run_local_once(args: &Args) -> ExitCode {
@@ -1220,7 +1264,7 @@ async fn run_remote(args: Args) -> ExitCode {
Err(code) => return code,
};
let exit = session.query_and_print(&args).await;
session.shutdown.trigger();
rns_tools::shut_down(&session.handle).await;
exit
}
@@ -1229,7 +1273,7 @@ async fn run_remote(args: Args) -> ExitCode {
struct RemoteSession {
remote_hash: [u8; 16],
client: LinkClient,
shutdown: ShutdownSignal,
handle: ReticulumHandle,
timeout: Duration,
}
@@ -1272,10 +1316,12 @@ impl RemoteSession {
}
};
// rnstatus.py:174, 928
handle.wants_destination_type(MGMT_APP).await;
Ok(Self {
remote_hash,
client: LinkClient::new(handle.transport_tx.clone(), identity),
shutdown,
handle,
timeout: Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS)),
})
}
+674
View File
@@ -0,0 +1,674 @@
//! rnx-rs — Reticulum remote execution (RNS/Utilities/rnx.py).
//!
//! `-l` listens on `rnx.execute` and runs `command` requests from allowed
//! identities; with a destination and a command it executes remotely. Exit
//! codes follow rnx: 240-249 for client failures, `-m` mirrors the remote code.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};
use clap::Parser;
use tokio::sync::mpsc;
use rns_identity::destination::{AllowPolicy, DestType, Destination, Direction};
use rns_identity::identity::Identity;
use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
use rns_runtime::link_manager::{LinkManager, LinkManagerCommand, RequestOutcome};
use rns_runtime::link_session::{LinkSession, LinkSessionError, RequestOptions};
use rns_runtime::platform::StoragePaths;
use rns_runtime::reticulum::{LinkConnectOptions, ReticulumHandle};
use rns_tools::RS_RETICULUM_VERSION;
use rns_tools::rnx::{
APP_NAME, COMMAND_PATH, CommandRequest, REMOTE_EXEC_GRACE, Timeout, TransferStats,
};
use rns_transport::messages::{PathRequestOptions, TransportMessage};
#[derive(Parser)]
#[command(
name = "rnx-rs",
about = "Reticulum Remote Execution Utility",
disable_version_flag = true
)]
struct Args {
/// hexadecimal hash of the listener
destination: Option<String>,
/// command to be execute
command: Option<String>,
/// path to alternative Reticulum config directory
#[arg(long, value_name = "path")]
config: Option<String>,
/// increase verbosity
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbose: u8,
/// decrease verbosity
#[arg(short = 'q', long = "quiet", action = clap::ArgAction::Count)]
quiet: u8,
/// print identity and destination info and exit
#[arg(short = 'p', long = "print-identity")]
print_identity: bool,
/// listen for incoming commands
#[arg(short = 'l', long = "listen")]
listen: bool,
/// path to identity to use
#[arg(short = 'i', value_name = "identity")]
identity: Option<PathBuf>,
/// enter interactive mode
#[arg(short = 'x', long = "interactive")]
interactive: bool,
/// don't announce at program start
#[arg(short = 'b', long = "no-announce")]
no_announce: bool,
/// accept from this identity
#[arg(short = 'a', value_name = "allowed_hash")]
allowed: Vec<String>,
/// accept commands from anyone
#[arg(short = 'n', long = "noauth")]
noauth: bool,
/// don't identify to listener
#[arg(short = 'N', long = "noid")]
noid: bool,
/// show detailed result output
#[arg(short = 'd', long = "detailed")]
detailed: bool,
/// mirror exit code of remote command
#[arg(short = 'm')]
mirror: bool,
/// connect and request timeout before giving up
#[arg(short = 'w', value_name = "seconds")]
w: Option<f64>,
/// max result download time
#[arg(short = 'W', value_name = "seconds")]
result_timeout: Option<f64>,
/// pass input to stdin
#[arg(long)]
stdin: Option<String>,
/// max size in bytes of returned stdout
#[arg(long)]
stdout: Option<i64>,
/// max size in bytes of returned stderr
#[arg(long)]
stderr: Option<i64>,
/// print version and exit
#[arg(long)]
version: bool,
}
#[tokio::main]
pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rnx-rs {RS_RETICULUM_VERSION}");
return;
}
let level = rns_tools::Utility::Rnx.loglevel(None, args.verbose, args.quiet, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stdout,
);
let interrupt = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(interrupt.clone());
if args.listen || args.print_identity {
listen(&args, &interrupt).await;
}
let Some(destination) = args.destination.clone() else {
print_help();
};
if args.command.is_none() && !args.interactive {
print_help();
}
let destination_hash = match rns_tools::rnx::parse_hash_arg(&destination) {
Ok(hash) => hash,
Err(e) => {
println!("{e}");
std::process::exit(241);
}
};
let handle = start(&args, &interrupt).await;
let code = tokio::select! {
biased;
_ = interrupt.wait() => {
println!();
0
}
code = run_client(&args, &handle, destination_hash) => code,
};
rns_tools::exit(&handle, code).await;
}
fn print_help() -> ! {
println!();
let _ = <Args as clap::CommandFactory>::command().print_help();
println!();
std::process::exit(0);
}
/// Start Reticulum on its own shutdown signal, so an interrupt still leaves
/// the runtime able to deregister from the shared instance.
async fn start(args: &Args, interrupt: &ShutdownSignal) -> ReticulumHandle {
let foreground = Arc::new(AtomicBool::new(true));
tokio::select! {
biased;
_ = interrupt.wait() => {
println!();
std::process::exit(0);
}
handle = rns_runtime::reticulum::init(args.config.as_deref(), None, ShutdownSignal::new(), foreground) => match handle {
Ok(handle) => handle,
Err(e) => {
eprintln!("failed to start reticulum: {e}");
std::process::exit(1);
}
},
}
}
/// `prepare_identity` (rnx.py:50-61): load the identity file or write a new one there.
fn prepare_identity(path: Option<&Path>, handle: &ReticulumHandle) -> Identity {
let path = path.map(Path::to_path_buf).unwrap_or_else(|| {
StoragePaths::from_config_dir(&handle.config_dir)
.identity_dir
.join("rnx")
});
if path.is_file()
&& let Ok(identity) = Identity::from_file(&path)
{
return identity;
}
tracing::info!("No valid saved identity found, creating new...");
let identity = Identity::new();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Err(e) = identity.to_file(&path) {
tracing::error!("could not save identity to {}: {e}", path.display());
}
identity
}
async fn listen(args: &Args, interrupt: &ShutdownSignal) -> ! {
let handle = start(args, interrupt).await;
let identity = prepare_identity(args.identity.as_deref(), &handle);
let destination = Destination::new(Some(&identity), Direction::In, DestType::Single, APP_NAME)
.expect("rnx.execute is a valid SINGLE destination name");
let destination_hash = destination.hash;
if args.print_identity {
println!("Identity : <{}>", hex::encode(identity.hash));
println!("Listening on : <{}>", hex::encode(destination_hash));
rns_tools::exit(&handle, 0).await;
}
let mut allowed: Vec<[u8; 16]> = Vec::new();
if !args.noauth {
for a in &args.allowed {
match rns_tools::rnx::parse_hash_arg(a) {
Ok(hash) => allowed.push(hash),
Err(e) => {
println!("{e}");
rns_tools::exit(&handle, 1).await;
}
}
}
let home = std::env::var_os("HOME").map(PathBuf::from);
let file = rns_tools::rnx::allowed_identity_files(home.as_deref())
.into_iter()
.find(|f| f.is_file());
if let Some(file) = file {
match std::fs::read_to_string(&file)
.map_err(|e| e.to_string())
.and_then(|text| rns_tools::rnx::parse_allowed_identities(&text))
{
Ok(hashes) => allowed.extend(hashes),
Err(e) => {
println!("{e}");
rns_tools::exit(&handle, 1).await;
}
}
}
}
if allowed.is_empty() && !args.noauth {
println!("Warning: No allowed identities configured, rncx will not accept any commands!");
}
let (dest_tx, dest_rx) = mpsc::channel(256);
let mut manager = LinkManager::with_destination(
handle.transport_tx.clone(),
dest_rx,
&identity,
APP_NAME,
identity.get_signing_key(),
);
manager.set_link_endpoint_dispatch_handle(handle.link_endpoint_dispatch_handle());
manager.set_use_implicit_proof(handle.should_use_implicit_proof());
if !args.noauth {
let gate = allowed.clone();
manager.set_link_identity_gate(move |link_id, identity_hash| {
let ok = gate.contains(&identity_hash);
if !ok {
tracing::info!(
target: rns_tools::NOTICE_TARGET,
"Identity <{}> not allowed, tearing down link <{}>",
hex::encode(identity_hash),
hex::encode(link_id)
);
}
ok
});
}
let (allow, allowed_list) = if args.noauth {
(AllowPolicy::AllowAll, None)
} else {
(AllowPolicy::AllowList, Some(allowed))
};
let registered = manager.register_deferred_request_handler(
COMMAND_PATH,
allow,
allowed_list,
true,
64 * 1024 * 1024,
|request, responder| {
// Upstream raises on a malformed request and sends nothing.
let Some(command) = CommandRequest::from_value(&request.value) else {
return;
};
let requestor = request.remote_identity.as_ref().map_or_else(
|| "unknown requestor".to_string(),
|id| format!("<{}>", hex::encode(id.hash)),
);
tokio::spawn(async move {
tracing::info!(target: rns_tools::NOTICE_TARGET, "Executing command [{}] for {requestor}", command.command);
let result = rns_tools::rnx::execute(&command).await;
tracing::info!(target: rns_tools::NOTICE_TARGET, "Delivering result of command [{}] to {requestor}", command.command);
if let Err(e) = responder.respond(RequestOutcome::ReplyValue(result.to_msgpack())) {
tracing::warn!("could not deliver result of command [{}]: {e}", command.command);
}
});
},
);
if !registered {
eprintln!("rnx-rs: could not register the command handler");
rns_tools::exit(&handle, 1).await;
}
let send = |message| handle.transport_tx.send(message);
if send(TransportMessage::RegisterDestination {
hash: destination_hash,
app_name: APP_NAME.to_string(),
delivery_tx: Some(dest_tx),
})
.await
.is_err()
|| send(TransportMessage::SetLocalDestinationKey {
hash: destination_hash,
public_key: identity.get_public_key(),
})
.await
.is_err()
{
eprintln!("rnx-rs: transport is unavailable");
rns_tools::exit(&handle, 1).await;
}
let (command_tx, command_rx) = mpsc::channel(16);
let manager_task = tokio::spawn(manager.run_with_commands(command_rx));
tracing::info!(
target: rns_tools::NOTICE_TARGET,
"rnx listening for commands on <{}>",
hex::encode(destination_hash)
);
if !args.no_announce {
let _ = command_tx.send(LinkManagerCommand::Announce).await;
}
interrupt.wait().await;
println!();
drop(command_tx);
let _ = tokio::time::timeout(Duration::from_secs(5), manager_task).await;
let _ = handle
.transport_tx
.send(TransportMessage::DeregisterDestination {
hash: destination_hash,
})
.await;
rns_tools::exit(&handle, 0).await;
}
/// `spin` (rnx.py:254-272): an animated message on stdout while `until` runs.
async fn spin<F: std::future::Future>(msg: &str, until: F) -> F::Output {
const SYMS: [char; 7] = ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'];
let mut out = std::io::stdout();
let _ = write!(out, "{msg} ");
let _ = out.flush();
tokio::pin!(until);
let mut tick = tokio::time::interval_at(
tokio::time::Instant::now() + Duration::from_millis(100),
Duration::from_millis(100),
);
let mut i = 0;
let result = loop {
tokio::select! {
result = &mut until => break result,
_ = tick.tick() => {
let _ = write!(out, "\x08\x08{} ", SYMS[i]);
let _ = out.flush();
i = (i + 1) % SYMS.len();
}
}
};
let _ = write!(out, "\r{} \r", " ".repeat(msg.chars().count()));
let _ = out.flush();
result
}
fn secs(seconds: f64) -> Duration {
Duration::try_from_secs_f64(seconds.max(0.0)).unwrap_or(Duration::MAX)
}
async fn run_client(args: &Args, handle: &ReticulumHandle, destination_hash: [u8; 16]) -> i32 {
// rnx.py:345
handle.wants_destination_type(APP_NAME).await;
let identity = prepare_identity(args.identity.as_deref(), handle);
let mut client = Client {
handle,
identity,
destination_hash,
session: None,
};
let timeout = args.w.map_or(Timeout::Default, Timeout::Given);
let code = run_commands(args, &mut client, timeout).await;
if let Some((session, _)) = client.session.take() {
session.handle.close().await;
}
code
}
async fn run_commands(args: &Args, client: &mut Client<'_>, timeout: Timeout) -> i32 {
if let Some(command) = args.command.as_deref() {
match client
.execute(
args,
command,
args.stdin.as_deref(),
timeout,
args.interactive,
)
.await
{
Outcome::Exit(code) => return code,
Outcome::Done(_) if !args.interactive => unreachable!("one-shot runs exit"),
Outcome::Done(_) => {}
}
}
interactive(args, client, timeout).await
}
/// The interactive loop (rnx.py:613-666).
async fn interactive(args: &Args, client: &mut Client<'_>, timeout: Timeout) -> i32 {
let (line_tx, mut line_rx) = mpsc::channel::<Option<String>>(1);
std::thread::spawn(move || {
let stdin = std::io::stdin();
loop {
let mut line = String::new();
let read = stdin.read_line(&mut line);
let line = match read {
Ok(0) | Err(_) => None,
Ok(_) => Some(line.trim_end_matches(['\n', '\r']).to_string()),
};
let end = line.is_none();
if line_tx.blocking_send(line).is_err() || end {
break;
}
}
});
let mut code: Option<i64> = None;
loop {
let prompt = match code {
Some(c) if c != 0 => format!("{c}> "),
_ => "> ".to_string(),
};
print!("{prompt}");
let _ = std::io::stdout().flush();
let Some(Some(command)) = line_rx.recv().await else {
return 0;
};
let lower = command.to_lowercase();
if lower == "exit" || lower == "quit" {
return 0;
}
if lower == "clear" {
print!("\x1bc");
continue;
}
match client.execute(args, &command, None, timeout, true).await {
Outcome::Exit(code) => return code,
Outcome::Done(c) => code = c,
}
}
}
enum Outcome {
/// Leave the process with this code.
Exit(i32),
/// An interactive command finished; the code shown in the next prompt.
Done(Option<i64>),
}
struct Client<'a> {
handle: &'a ReticulumHandle,
identity: Identity,
destination_hash: [u8; 16],
session: Option<(LinkSession, f64)>,
}
impl Client<'_> {
/// Ensure a path, as `execute` does before linking (rnx.py:350-354).
async fn ensure_path(&self, timeout: Timeout) -> bool {
let handle = self.handle;
let hash = self.destination_hash;
if handle.has_path(hash).await.unwrap_or(false) {
return true;
}
let _ = handle
.request_path(hash, PathRequestOptions::default())
.await;
let wait = timeout
.seconds()
.max(rns_tools::medium_path_timeout(handle).await);
let msg = format!("Path to <{}> requested", hex::encode(hash));
let found = spin(&msg, async {
loop {
if handle.has_path(hash).await.unwrap_or(false) {
return true;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
tokio::time::timeout(secs(wait), found).await.is_ok()
}
/// Open the Link with `max(-w, establishment timeout)` (rnx.py:366-376).
/// Returns the session and its measured round trip.
async fn connect(&self, noid: bool, timeout: Timeout) -> Option<(LinkSession, f64)> {
let handle = self.handle;
let hash = self.destination_hash;
let hops = handle.hops_to(hash).await.unwrap_or(1);
let first_hop = handle
.first_hop_timeout(hash)
.await
.map_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT, |d| {
d.as_secs_f64()
});
let establishment =
first_hop + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(hops.max(1));
let options = LinkConnectOptions {
path_timeout: secs(timeout.seconds()),
establishment_timeout: Some(secs(timeout.seconds().max(establishment))),
client_label: "rnx".to_string(),
identify: !noid,
track_phy_stats: false,
..LinkConnectOptions::default()
};
let msg = format!("Establishing link with <{}>", hex::encode(hash));
let started = Instant::now();
let connected = spin(
&msg,
handle.connect_link(hash, self.identity.clone(), options),
)
.await;
match connected {
Ok(mut session) => {
let rtt = started.elapsed().as_secs_f64();
let events = std::mem::replace(&mut session.events, mpsc::channel(1).1);
tokio::spawn(drain(events));
Some((session, rtt))
}
Err(e) => {
tracing::debug!("link establishment failed: {e}");
None
}
}
}
async fn execute(
&mut self,
args: &Args,
command: &str,
stdin: Option<&str>,
timeout: Timeout,
interactive: bool,
) -> Outcome {
let fail = |msg: &str, code: i32| {
println!("{msg}");
if interactive {
Outcome::Done(None)
} else {
Outcome::Exit(code)
}
};
if !self.ensure_path(timeout).await {
println!("Path not found");
return Outcome::Exit(242);
}
if self.session.is_none() {
match self.connect(args.noid, timeout).await {
Some(session) => self.session = Some(session),
None => {
println!(
"Could not establish link with <{}>",
hex::encode(self.destination_hash)
);
return Outcome::Exit(243);
}
}
}
let (session, rtt) = self.session.as_ref().expect("connected above");
let data = rns_tools::rnx::request_value(command, timeout, args.stdout, args.stderr, stdin);
let request_size = packed_request_size(&data);
let rexec_timeout = timeout.seconds() + rtt * 4.0 + REMOTE_EXEC_GRACE;
let request = session.handle.request_with_options(
COMMAND_PATH,
data,
RequestOptions {
timeout: Some(secs(rexec_timeout)),
..RequestOptions::default()
},
);
let result = match args.result_timeout {
Some(w) => tokio::time::timeout(secs(rexec_timeout + w), request)
.await
.ok(),
None => Some(request.await),
};
let response = match result {
None => return fail("Receiving result failed", 246),
Some(Ok(response)) => response,
Some(Err(LinkSessionError::SessionClosed | LinkSessionError::LinkNotActive)) => {
self.session = None;
println!("Could not request remote execution, link was closed");
return Outcome::Exit(244);
}
Some(Err(
LinkSessionError::RequestResourceFailed(_)
| LinkSessionError::ResponseRejected { .. },
)) => return fail("Receiving result failed", 246),
Some(Err(_)) => return fail("Could not request remote execution", 244),
};
let stats = match (
response.response_size,
response.started_at,
response.response_concluded_at,
) {
(Some(response_size), Some(sent), Some(concluded)) => Some(TransferStats {
request_size: Some(request_size),
response_size,
elapsed: concluded.saturating_duration_since(sent).as_secs_f64(),
}),
_ => None,
};
let (rendered, parsed, code) = rns_tools::rnx::client_result(
&response.value,
args.detailed,
args.mirror,
args.stdout,
args.stderr,
stats,
);
let Some(parsed) = parsed else {
let _ = std::io::stdout().write_all(&rendered.stdout);
return if interactive {
Outcome::Done(None)
} else {
Outcome::Exit(code)
};
};
write_split(&parsed, &rendered);
if !interactive {
if let Some((session, _)) = self.session.take() {
session.handle.close().await;
}
return Outcome::Exit(code);
}
Outcome::Done(if args.mirror { parsed.retcode } else { None })
}
}
/// Write remote output first, then the trailer lines, as rnx.py:461-520 orders them.
fn write_split(parsed: &rns_tools::rnx::Response, rendered: &rns_tools::rnx::Rendered) {
let remote_out = parsed.stdout.as_deref().map_or(0, <[u8]>::len);
let (out, trailer) = rendered
.stdout
.split_at(remote_out.min(rendered.stdout.len()));
let mut stdout = std::io::stdout();
let mut stderr = std::io::stderr();
let _ = stdout.write_all(out);
let _ = stderr.write_all(&rendered.stderr);
let _ = stdout.flush();
let _ = stderr.flush();
let _ = stdout.write_all(trailer);
let _ = stdout.flush();
}
/// `len(umsgpack.packb([time.time(), path_hash, data]))` (Link.py:573-574).
fn packed_request_size(data: &rmpv::Value) -> u64 {
let request = rmpv::Value::Array(vec![
rmpv::Value::F64(0.0),
rmpv::Value::Binary(vec![0; 16]),
data.clone(),
]);
let mut out = Vec::new();
let _ = rmpv::encode::write_value(&mut out, &request);
out.len() as u64
}
async fn drain(mut events: mpsc::Receiver<rns_runtime::link_session::LinkSessionEvent>) {
while events.recv().await.is_some() {}
}
+142 -1
View File
@@ -2,6 +2,13 @@
pub mod format;
pub mod hash;
pub mod rnx;
pub mod rsg;
use std::time::Duration;
use rns_runtime::reticulum::{InstanceMode, ReticulumHandle, SharedInstanceRpcEndpoint};
use rns_runtime::rpc::{RpcRequest, RpcResponse};
/// rsReticulum package version printed by CLI `--version` output.
pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -119,6 +126,9 @@ pub enum Utility {
Rnid,
Rnsh,
Lxmd,
Rnx,
Rnir,
Rnpkg,
}
impl Utility {
@@ -145,8 +155,12 @@ impl Utility {
Utility::Lxmd => configured
.unwrap_or(LogLevel::Notice as i64)
.saturating_add(delta),
// rnir and rnpkg pass `verbosity`, which only offsets a configured loglevel.
Utility::Rnir | Utility::Rnpkg => {
configured.map_or(LogLevel::Notice as i64, |level| level.saturating_add(delta))
}
Utility::Rnprobe => 2 + delta,
Utility::Rnstatus | Utility::Rnpath | Utility::Rncp => 3 + delta,
Utility::Rnstatus | Utility::Rnpath | Utility::Rncp | Utility::Rnx => 3 + delta,
Utility::Rnid | Utility::Rnsh => 4 + delta,
};
LogLevel::clamped(level)
@@ -173,3 +187,130 @@ where
registry.with(layer.without_time()).try_init()
};
}
/// Longest a tool waits for its runtime to shut down before exiting.
const EXIT_SHUTDOWN_DEADLINE: Duration = Duration::from_secs(10);
/// Shut the runtime down as Python's exit handler does before the process
/// ends (Reticulum.py:186-195): a shared-instance client first deregisters its
/// destination types, so no registration outlives the tool run.
pub async fn shut_down(handle: &ReticulumHandle) {
let _ = tokio::time::timeout(EXIT_SHUTDOWN_DEADLINE, handle.shutdown_and_wait()).await;
}
/// [`shut_down`], then exit the process with `code`.
pub async fn exit(handle: &ReticulumHandle, code: i32) -> ! {
shut_down(handle).await;
std::process::exit(code)
}
/// Destination types a tool that talks to the shared instance over RPC alone
/// registers there, with its own requester hash, as upstream's tools do
/// through `Reticulum.wants_destination_type` (Reticulum.py:2224-2267).
pub struct RpcRegistration {
endpoint: SharedInstanceRpcEndpoint,
rpc_key: Vec<u8>,
requester: [u8; 16],
timeout: Duration,
}
impl RpcRegistration {
/// Register `full_names`. Failures are ignored, as upstream ignores them.
pub async fn want(
endpoint: SharedInstanceRpcEndpoint,
rpc_key: Vec<u8>,
full_names: &[&str],
timeout: Duration,
) -> Self {
let registration = Self {
endpoint,
rpc_key,
requester: rns_identity::identity::Identity::new().hash,
timeout,
};
for full_name in full_names {
registration
.request(&RpcRequest::WantsDestinationType {
full_name: (*full_name).to_string(),
requester: registration.requester.to_vec(),
signature: None,
})
.await;
}
registration
}
/// Deregister every type, as the exit handler's `unwants_all_destination_types`.
pub async fn release(self) {
self.request(&RpcRequest::UnwantsAllDestinationTypes {
requester: self.requester.to_vec(),
signature: None,
})
.await;
}
async fn request(&self, request: &RpcRequest) {
let result = match &self.endpoint {
SharedInstanceRpcEndpoint::Tcp(port) => {
rns_runtime::rpc::connect_and_request(*port, &self.rpc_key, request, self.timeout)
.await
}
SharedInstanceRpcEndpoint::Unix(path) => {
rns_runtime::rpc::connect_unix_and_request(
path,
&self.rpc_key,
request,
self.timeout,
)
.await
}
};
if let Err(error) = result {
tracing::debug!(%error, "shared instance RPC failed while setting destination type filters");
}
}
}
/// Reticulum.get_medium_path_timeout (Reticulum.py:2011-2029): ask the shared
/// instance, or compute Transport.medium_path_timeout (Transport.py:3550-3553)
/// from the lowest online interface bitrate. 0 when unknown or on error.
pub async fn medium_path_timeout(handle: &ReticulumHandle) -> f64 {
if handle.instance_mode == InstanceMode::Client {
let Some(rpc_key) = handle.config.rpc_key.as_deref() else {
return 0.0;
};
let request = RpcRequest::GetMediumPathTimeout;
let timeout = Duration::from_secs(5);
let response = match handle.config.shared_rpc_endpoint(&handle.socket_base) {
SharedInstanceRpcEndpoint::Tcp(port) => {
rns_runtime::rpc::connect_and_request(port, rpc_key, &request, timeout).await
}
SharedInstanceRpcEndpoint::Unix(path) => {
rns_runtime::rpc::connect_unix_and_request(&path, rpc_key, &request, timeout).await
}
};
return match response {
Ok(RpcResponse::FloatResult(Some(v))) if v.is_finite() => v,
_ => 0.0,
};
}
let lowest = match handle
.query_transport(rns_transport::messages::TransportQuery::GetInterfaceStats)
.await
{
Some(rns_transport::messages::TransportQueryResponse::InterfaceStats(entries)) => entries
.iter()
.filter(|entry| entry.online && entry.bitrate > 0)
.map(|entry| entry.bitrate)
.min(),
_ => None,
};
match lowest {
Some(bitrate) => {
let bits = (rns_wire::constants::MTU * 8) as f64;
2.0 * (bits / bitrate.max(rns_runtime::constants::MINIMUM_BITRATE) as f64)
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT
}
None => 0.0,
}
}
+600
View File
@@ -0,0 +1,600 @@
//! The `rnx` remote execution protocol (RNS/Utilities/rnx.py): request and
//! result arrays, command execution on the listener and result rendering on
//! the client.
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use rmpv::Value;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// Destination aspects `rnx.execute` (rnx.py:70).
pub const APP_NAME: &str = "rnx.execute";
/// Request handler path (rnx.py:115-122).
pub const COMMAND_PATH: &str = "command";
/// `remote_exec_grace` (rnx.py:325).
pub const REMOTE_EXEC_GRACE: f64 = 2.0;
/// `RNS.Transport.PATH_REQUEST_TIMEOUT`, the default `-w`, sent as an integer.
pub const DEFAULT_TIMEOUT: i64 = 15;
/// The client's `-w`: the integer default, or the float a user gave.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Timeout {
Default,
Given(f64),
}
impl Timeout {
pub fn seconds(self) -> f64 {
match self {
Timeout::Default => DEFAULT_TIMEOUT as f64,
Timeout::Given(seconds) => seconds,
}
}
fn value(self) -> Value {
match self {
Timeout::Default => Value::from(DEFAULT_TIMEOUT),
Timeout::Given(seconds) => Value::F64(seconds),
}
}
}
/// `request_data` as `execute` builds it (rnx.py:379-385).
pub fn request_value(
command: &str,
timeout: Timeout,
stdout_limit: Option<i64>,
stderr_limit: Option<i64>,
stdin: Option<&str>,
) -> Value {
let limit = |l: Option<i64>| l.map_or(Value::Nil, Value::from);
Value::Array(vec![
Value::Binary(command.as_bytes().to_vec()),
timeout.value(),
limit(stdout_limit),
limit(stderr_limit),
stdin.map_or(Value::Nil, |s| Value::Binary(s.as_bytes().to_vec())),
])
}
/// A decoded request as `execute_received_command` reads it (rnx.py:156-160).
#[derive(Debug, Clone, PartialEq)]
pub struct CommandRequest {
pub command: String,
pub timeout: Option<f64>,
pub stdout_limit: Option<i64>,
pub stderr_limit: Option<i64>,
pub stdin: Option<Vec<u8>>,
}
impl CommandRequest {
/// `None` where the upstream handler raises before answering.
pub fn from_value(value: &Value) -> Option<Self> {
let items = value.as_array()?;
let command = match items.first()? {
Value::Binary(bytes) => String::from_utf8(bytes.clone()).ok()?,
_ => return None,
};
let number = |v: Option<&Value>| -> Option<Option<f64>> {
match v? {
Value::Nil => Some(None),
Value::F32(f) => Some(Some(f64::from(*f))),
Value::F64(f) => Some(Some(*f)),
Value::Integer(i) => Some(Some(i.as_f64()?)),
_ => None,
}
};
let limit = |v: Option<&Value>| -> Option<Option<i64>> {
match v? {
Value::Nil => Some(None),
Value::Integer(i) => Some(Some(i.as_i64()?)),
_ => None,
}
};
let stdin = match items.get(4)? {
Value::Nil => None,
Value::Binary(bytes) => Some(bytes.clone()),
_ => return None,
};
Some(Self {
command,
timeout: number(items.get(1))?,
stdout_limit: limit(items.get(2))?,
stderr_limit: limit(items.get(3))?,
stdin,
})
}
}
/// The result array (rnx.py:170-179).
#[derive(Debug, Clone, PartialEq)]
pub struct CommandResult {
pub executed: bool,
pub retcode: Option<i64>,
pub stdout: Option<Vec<u8>>,
pub stderr: Option<Vec<u8>>,
pub stdout_len: Option<u64>,
pub stderr_len: Option<u64>,
pub started: f64,
pub concluded: Option<f64>,
}
impl CommandResult {
fn not_executed(started: f64) -> Self {
Self {
executed: false,
retcode: None,
stdout: None,
stderr: None,
stdout_len: None,
stderr_len: None,
started,
concluded: None,
}
}
pub fn to_value(&self) -> Value {
let bin = |b: &Option<Vec<u8>>| b.clone().map_or(Value::Nil, Value::Binary);
let int = |i: Option<i64>| i.map_or(Value::Nil, Value::from);
Value::Array(vec![
Value::Boolean(self.executed),
int(self.retcode),
bin(&self.stdout),
bin(&self.stderr),
int(self.stdout_len.map(|n| n as i64)),
int(self.stderr_len.map(|n| n as i64)),
Value::F64(self.started),
self.concluded.map_or(Value::Nil, Value::F64),
])
}
/// Packed result, the response value the listener returns.
pub fn to_msgpack(&self) -> Vec<u8> {
let mut out = Vec::new();
rmpv::encode::write_value(&mut out, &self.to_value()).expect("encoding to a Vec");
out
}
}
fn now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |d| d.as_secs_f64())
}
/// `out[0:limit]` with Python slice semantics, applied only when
/// `len(out) > limit` (rnx.py:225-238).
pub fn truncate(out: &[u8], limit: Option<i64>) -> Vec<u8> {
let len = out.len() as i64;
match limit {
Some(limit) if len > limit => {
let end = if limit < 0 {
(len + limit).max(0)
} else {
limit
};
out[..end as usize].to_vec()
}
_ => out.to_vec(),
}
}
/// `execute_received_command` (rnx.py:155-252): run the command without a
/// shell, feed stdin, SIGTERM it once the timeout passes, truncate output.
pub async fn execute(request: &CommandRequest) -> CommandResult {
let started = now();
let Some(argv) = rns_interface::pipe::split_command(&request.command) else {
return CommandResult::not_executed(started);
};
let Some((program, args)) = argv.split_first() else {
return CommandResult::not_executed(started);
};
let mut child = match tokio::process::Command::new(program)
.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
{
Ok(child) => child,
Err(_) => return CommandResult::not_executed(started),
};
let mut stdin = child.stdin.take();
let stdin_data = request.stdin.clone();
let writer = tokio::spawn(async move {
if let (Some(pipe), Some(data)) = (stdin.as_mut(), stdin_data) {
let _ = pipe.write_all(&data).await;
}
drop(stdin);
});
let mut stdout_pipe = child.stdout.take().expect("piped stdout");
let mut stderr_pipe = child.stderr.take().expect("piped stderr");
let out_reader = tokio::spawn(async move {
let mut buf = Vec::new();
let _ = stdout_pipe.read_to_end(&mut buf).await;
buf
});
let err_reader = tokio::spawn(async move {
let mut buf = Vec::new();
let _ = stderr_pipe.read_to_end(&mut buf).await;
buf
});
let deadline = request.timeout.map(|t| {
Duration::try_from_secs_f64((started + t - now()).max(0.0)).unwrap_or(Duration::MAX)
});
let mut killed = false;
let status = match deadline {
Some(deadline) => match tokio::time::timeout(deadline, child.wait()).await {
Ok(status) => status,
Err(_) => {
killed = true;
tracing::info!(target: crate::NOTICE_TARGET, "Command [{}] timed out and is being killed...", request.command);
if let Some(pid) = child.id() {
// SAFETY: signals the child this task still owns.
unsafe {
nix::libc::kill(pid as i32, nix::libc::SIGTERM);
}
}
child.wait().await
}
},
None => child.wait().await,
};
let _ = writer.await;
let stdout = out_reader.await.unwrap_or_default();
let stderr = err_reader.await.unwrap_or_default();
// Upstream kills only once the deadline has passed, so a killed command never concludes.
let concluded = request
.timeout
.filter(|_| !killed)
.and_then(|t| (now() < started + t).then(now));
let retcode = status.ok().and_then(|s| {
use std::os::unix::process::ExitStatusExt;
s.code().or_else(|| s.signal().map(|n| -n)).map(i64::from)
});
CommandResult {
executed: true,
retcode,
stdout: Some(truncate(&stdout, request.stdout_limit)),
stderr: Some(truncate(&stderr, request.stderr_limit)),
stdout_len: Some(stdout.len() as u64),
stderr_len: Some(stderr.len() as u64),
started,
concluded,
}
}
/// A response as the client indexes it (rnx.py:438-452).
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
pub executed: bool,
pub retcode: Option<i64>,
pub stdout: Option<Vec<u8>>,
pub stderr: Option<Vec<u8>>,
pub stdout_len: Option<u64>,
pub stderr_len: Option<u64>,
pub started: Option<f64>,
pub concluded: Option<f64>,
}
fn truthy(value: &Value) -> bool {
match value {
Value::Nil => false,
Value::Boolean(b) => *b,
Value::Integer(i) => i.as_i64() != Some(0) && i.as_u64() != Some(0),
Value::F32(f) => *f != 0.0,
Value::F64(f) => *f != 0.0,
Value::String(s) => !s.as_bytes().is_empty(),
Value::Binary(b) => !b.is_empty(),
Value::Array(a) => !a.is_empty(),
Value::Map(m) => !m.is_empty(),
Value::Ext(..) => true,
}
}
/// How the client reads a response.
#[derive(Debug, Clone, PartialEq)]
pub enum ResponseKind {
/// `"No response"`, 249.
Missing,
/// `"Received invalid result"`, 247.
Invalid,
Result(Response),
}
impl ResponseKind {
pub fn from_value(value: &Value) -> Self {
let Some(items) = value.as_array() else {
return if value.is_nil() {
Self::Missing
} else {
Self::Invalid
};
};
if items.len() < 8 {
return Self::Invalid;
}
let bin = |v: &Value| match v {
Value::Binary(b) => Some(b.clone()),
Value::String(s) => Some(s.as_bytes().to_vec()),
_ => None,
};
let float = |v: &Value| match v {
Value::F64(f) => Some(*f),
Value::F32(f) => Some(f64::from(*f)),
Value::Integer(i) => i.as_f64(),
_ => None,
};
Self::Result(Response {
executed: truthy(&items[0]),
retcode: items[1].as_i64(),
stdout: bin(&items[2]),
stderr: bin(&items[3]),
stdout_len: items[4].as_u64(),
stderr_len: items[5].as_u64(),
started: float(&items[6]),
concluded: float(&items[7]),
})
}
}
/// Request and response sizes and times for the `-d` transfer line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransferStats {
pub request_size: Option<u64>,
pub response_size: u64,
/// `response_concluded_at - sent_at`, in seconds.
pub elapsed: f64,
}
/// Text the client writes for an executed result (rnx.py:461-520).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rendered {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
/// Render an executed result. `stdout_limit`/`stderr_limit` are the
/// client's own `--stdout`/`--stderr`.
pub fn render(
response: &Response,
detailed: bool,
stdout_limit: Option<i64>,
stderr_limit: Option<i64>,
stats: Option<TransferStats>,
) -> Rendered {
let mut r = Rendered::default();
let stdout = response.stdout.as_deref();
let stderr = response.stderr.as_deref();
if let Some(out) = stdout.filter(|o| !o.is_empty()) {
r.stdout.extend_from_slice(out);
}
if let Some(err) = stderr.filter(|e| !e.is_empty()) {
r.stderr.extend_from_slice(err);
}
let mut line = |s: String| {
r.stdout.extend_from_slice(s.as_bytes());
r.stdout.push(b'\n');
};
if detailed {
line("\n--- End of remote output, rnx done ---".into());
if let (Some(started), Some(concluded)) = (response.started, response.concluded) {
let cmd_duration = py_round(concluded - started, 3);
line(format!(
"Remote command execution took {} seconds",
py_float(cmd_duration)
));
if let Some(stats) = stats {
let total = stats.response_size + stats.request_size.unwrap_or(0);
let td = py_round(stats.elapsed - cmd_duration, 3);
let tdstr = if td == 1.0 {
" in 1 second".to_string()
} else if td < 10.0 {
format!(" in {} seconds", py_float(td))
} else {
format!(" in {}", pretty_time(td))
};
let spdstr = if td != 0.0 {
format!(", effective rate {}ps", size_str(total as f64 / td, 'b'))
} else {
String::new()
};
line(format!(
"Transferred {}{tdstr}{spdstr}",
size_str(total as f64, 'B')
));
}
}
let wrote = |name: &str, out: Option<&[u8]>, total: Option<u64>| {
let (Some(out), Some(total)) = (out, total) else {
return None;
};
let shown = if (out.len() as u64) < total {
format!(", {} bytes displayed", out.len())
} else {
String::new()
};
Some(format!("Remote wrote {total} bytes to {name}{shown}"))
};
if let Some(l) = wrote("stdout", stdout, response.stdout_len) {
line(l);
}
if let Some(l) = wrote("stderr", stderr, response.stderr_len) {
line(l);
}
} else {
let shorter = |out: Option<&[u8]>, total: Option<u64>| {
(out.map_or(0, <[u8]>::len) as u64) < total.unwrap_or(0)
};
let out_short = shorter(stdout, response.stdout_len);
let err_short = shorter(stderr, response.stderr_len);
if (stdout_limit != Some(0) && out_short) || (stderr_limit != Some(0) && err_short) {
line("\nOutput truncated before being returned:".into());
if stdout.is_some_and(|o| !o.is_empty()) && out_short {
line(format!(
" stdout truncated to {} bytes",
stdout.map_or(0, <[u8]>::len)
));
}
if stderr.is_some_and(|e| !e.is_empty()) && err_short {
line(format!(
" stderr truncated to {} bytes",
stderr.map_or(0, <[u8]>::len)
));
}
}
}
r
}
/// The process status for `-m` (rnx.py:536-540): the remote code as Python's
/// `exit()` passes it to the OS, or 240 without one.
pub fn mirrored_exit_code(retcode: Option<i64>) -> i32 {
retcode.map_or(240, |code| (code & 0xff) as i32)
}
/// Python `round(x, digits)`.
pub fn py_round(x: f64, digits: usize) -> f64 {
format!("{x:.digits$}").parse().unwrap_or(x)
}
/// Python `str(float)` for values without exponent notation.
pub fn py_float(x: f64) -> String {
if x.is_finite() && x.fract() == 0.0 && x.abs() < 1e16 {
format!("{x:.1}")
} else {
format!("{x}")
}
}
/// `size_str` (rnx.py:680-697).
pub fn size_str(num: f64, suffix: char) -> String {
let mut num = if suffix == 'b' { num * 8.0 } else { num };
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] {
if num.abs() < 1000.0 {
return if unit.is_empty() {
format!("{num:.0} {unit}{suffix}")
} else {
format!("{num:.2} {unit}{suffix}")
};
}
num /= 1000.0;
}
format!("{num:.2}Y{suffix}")
}
/// `pretty_time` without `verbose` (rnx.py:699-739).
pub fn pretty_time(time: f64) -> String {
let days = (time / 86400.0).floor() as i64;
let time = time.rem_euclid(86400.0);
let hours = (time / 3600.0).floor() as i64;
let time = time.rem_euclid(3600.0);
let minutes = (time / 60.0).floor() as i64;
let seconds = py_round(time.rem_euclid(60.0), 2);
let mut components = Vec::new();
if days > 0 {
components.push(format!("{days}d"));
}
if hours > 0 {
components.push(format!("{hours}h"));
}
if minutes > 0 {
components.push(format!("{minutes}m"));
}
if seconds > 0.0 {
components.push(format!("{}s", py_float(seconds)));
}
let mut out = String::new();
let n = components.len();
for (i, c) in components.iter().enumerate() {
if i > 0 {
out.push_str(if i + 1 < n { ", " } else { " and " });
}
out.push_str(c);
}
out
}
/// The allowed-identities files the listener reads, first existing wins
/// (rnx.py:94-101).
pub fn allowed_identity_files(home: Option<&Path>) -> Vec<PathBuf> {
let mut files = vec![PathBuf::from("/etc/rnx/allowed_identities")];
if let Some(home) = home {
files.push(home.join(".config/rnx/allowed_identities"));
files.push(home.join(".rnx/allowed_identities"));
}
files
}
/// Parse an allowed-identities file: only lines of exactly 32 characters
/// count, and one that is not hex fails (rnx.py:102-108).
pub fn parse_allowed_identities(text: &str) -> Result<Vec<[u8; 16]>, String> {
let mut allowed = Vec::new();
for line in text.replace('\r', "").split('\n') {
if line.chars().count() != 32 {
continue;
}
let mut hash = [0u8; 16];
hex::decode_to_slice(line, &mut hash).map_err(|_| {
let position = line
.char_indices()
.find(|(_, c)| !c.is_ascii_hexdigit())
.map_or(0, |(i, _)| i);
format!("non-hexadecimal number found in fromhex() arg at position {position}")
})?;
allowed.push(hash);
}
Ok(allowed)
}
/// Validate a 32-character hash argument with upstream's messages
/// (rnx.py:80-93, 328-336).
pub fn parse_hash_arg(value: &str) -> Result<[u8; 16], String> {
if value.chars().count() != 32 {
return Err(
"Allowed destination length is invalid, must be 32 hexadecimal characters (16 bytes)."
.into(),
);
}
let mut hash = [0u8; 16];
hex::decode_to_slice(value, &mut hash)
.map_err(|_| "Invalid destination entered. Check your input.".to_string())?;
Ok(hash)
}
/// A one-shot client's output and exit code for a received response value
/// (rnx.py:437-549).
pub fn client_result(
value: &Value,
detailed: bool,
mirror: bool,
stdout_limit: Option<i64>,
stderr_limit: Option<i64>,
stats: Option<TransferStats>,
) -> (Rendered, Option<Response>, i32) {
let message = |text: &str, code| {
let mut r = Rendered::default();
r.stdout.extend_from_slice(text.as_bytes());
r.stdout.push(b'\n');
(r, None, code)
};
let response = match ResponseKind::from_value(value) {
ResponseKind::Missing => return message("No response", 249),
ResponseKind::Invalid => return message("Received invalid result", 247),
ResponseKind::Result(response) => response,
};
if !response.executed {
return message("Remote could not execute command", 248);
}
let rendered = render(&response, detailed, stdout_limit, stderr_limit, stats);
let code = if mirror {
mirrored_exit_code(response.retcode)
} else {
0
};
(rendered, Some(response), code)
}
@@ -3,6 +3,11 @@
//! Validation follows Python's control flow, including which malformed
//! envelopes are "invalid" and which raise (rnid exits 254 for those).
pub mod b256;
pub mod meta;
pub mod pyfmt;
mod pyre;
use std::io::{Cursor, Read};
use rmpv::Value;
@@ -32,7 +37,7 @@ pub fn create_rsg<R: Read>(
message.read_to_end(&mut data).map_err(|e| e.to_string())?;
(rns_crypto::sha::sha256(&data), Some(data))
} else {
(sha256_reader(message).map_err(|e| e.to_string())?, None)
(get_rsg_hash(message).map_err(|e| e.to_string())?, None)
};
let mut meta_entries = vec![
@@ -88,10 +93,57 @@ pub fn is_legacy_format(rsg_data: &[u8]) -> bool {
/// Python `umsgpack.unpackb`: one object, trailing bytes ignored; invalid
/// UTF-8 strings, unhashable or duplicate map keys fail.
pub fn unpackb(data: &[u8]) -> Option<Value> {
no_reserved_code(data, 0, rmpv::decode::MAX_DEPTH)?;
let value = rmpv::decode::read_value(&mut Cursor::new(data)).ok()?;
umsgpack_acceptable(&value).then_some(value)
}
/// The end of the object at `at`, or `None` where umsgpack raises
/// `ReservedCodeException` for 0xc1 (rmpv reads it as nil), the data ends, or
/// nesting passes rmpv's depth limit (upstream hits its recursion limit).
fn no_reserved_code(data: &[u8], at: usize, depth: usize) -> Option<usize> {
let depth = depth.checked_sub(1)?;
let marker = *data.get(at)?;
let be = |n: usize| -> Option<usize> {
let bytes = data.get(at + 1..at + 1 + n)?;
Some(
bytes
.iter()
.fold(0usize, |acc, b| (acc << 8) | usize::from(*b)),
)
};
let skip = |header: usize, len: usize| at.checked_add(header)?.checked_add(len);
let items = |start: usize, count: usize| -> Option<usize> {
(0..count).try_fold(start, |pos, _| no_reserved_code(data, pos, depth))
};
match marker {
0x00..=0x7f | 0xc0 | 0xc2 | 0xc3 | 0xe0..=0xff => Some(at + 1),
0x80..=0x8f => items(at + 1, usize::from(marker & 0x0f) * 2),
0x90..=0x9f => items(at + 1, usize::from(marker & 0x0f)),
0xa0..=0xbf => skip(1, usize::from(marker & 0x1f)),
0xc1 => None,
0xc4 | 0xd9 => skip(2, be(1)?),
0xc5 | 0xda => skip(3, be(2)?),
0xc6 | 0xdb => skip(5, be(4)?),
0xc7 => skip(3, be(1)?),
0xc8 => skip(4, be(2)?),
0xc9 => skip(6, be(4)?),
0xca | 0xce | 0xd2 => Some(at + 5),
0xcb | 0xcf | 0xd3 => Some(at + 9),
0xcc | 0xd0 => Some(at + 2),
0xcd | 0xd1 => Some(at + 3),
0xd4 => Some(at + 3),
0xd5 => Some(at + 4),
0xd6 => Some(at + 6),
0xd7 => Some(at + 10),
0xd8 => Some(at + 18),
0xdc => items(at + 3, be(2)?),
0xdd => items(at + 5, be(4)?),
0xde => items(at + 3, be(2)?.checked_mul(2)?),
0xdf => items(at + 5, be(4)?.checked_mul(2)?),
}
}
fn umsgpack_acceptable(value: &Value) -> bool {
match value {
Value::String(s) => s.as_str().is_some(),
@@ -254,7 +306,7 @@ pub fn validate_rsg(
return Err("No message specified for rsg validation".to_string());
}
let rsg_hash: Vec<u8> = match message {
Message::File(reader) => sha256_reader(reader).map_err(|e| e.to_string())?.to_vec(),
Message::File(reader) => get_rsg_hash(reader).map_err(|e| e.to_string())?.to_vec(),
Message::Unpacked(Value::Binary(b)) => rns_crypto::sha::sha256(b).to_vec(),
Message::Unpacked(Value::String(s)) if s.as_str().is_some() => {
rns_crypto::sha::sha256(s.as_bytes()).to_vec()
@@ -293,20 +345,21 @@ pub fn validate_rsg(
return Ok(None);
}
// `None` stands for an identity whose public key failed to load.
let signing_identity: Option<Identity> = match required_signer {
Some(RequiredSigner::Identity(identity)) => Some(identity.clone()),
_ => {
let Ok(pubkey) = py_index(meta, "pubkey") else {
return Ok(None);
};
match pubkey {
Value::Binary(b) if b.len() == 64 => Identity::from_public_key(b).ok(),
_ => None,
}
}
let signing_key = match required_signer {
Some(RequiredSigner::Identity(identity)) => SigningKey::Loaded {
hash: identity.hash,
identity: Some(Box::new(identity.clone())),
},
_ => match py_index(meta, "pubkey") {
Ok(Value::Binary(pubkey)) => SigningKey::load(pubkey),
Ok(_) => SigningKey::None,
Err(_) => return Ok(None),
},
};
let signing_hash = match &signing_key {
SigningKey::Loaded { hash, .. } => Some(hash.to_vec()),
_ => None,
};
let signing_hash = signing_identity.as_ref().map(|i| i.hash.to_vec());
let required_hash = match required_signer {
Some(RequiredSigner::Identity(identity)) => Some(identity.hash.to_vec()),
Some(RequiredSigner::Hash(hash)) => Some(hash.to_vec()),
@@ -318,21 +371,59 @@ pub fn validate_rsg(
if !matches!(py_index(&signed_data, "hash")?, Value::Binary(h) if *h == rsg_hash) {
return Ok(None);
}
let Some(identity) = signing_identity else {
return Err(
"'Signature validation failed because identity does not hold a public key'".to_string(),
);
let (hash, identity) = match signing_key {
SigningKey::None => {
return Err(
"'Signature validation failed because identity does not hold a public key'"
.to_string(),
);
}
SigningKey::NoEd25519 => return Ok(None),
SigningKey::Loaded { hash, identity } => (hash, identity),
};
if !identity.verify(envelope, &signature) {
if !identity.is_some_and(|identity| identity.verify(envelope, &signature)) {
return Ok(None);
}
Ok(Some(Valid {
signed_data,
signer_hash: identity.hash,
signer_hash: hash,
}))
}
fn sha256_reader<R: Read>(mut reader: R) -> std::io::Result<[u8; 32]> {
/// The state `Identity.load_public_key` leaves a public-only identity in
/// (`RNS/Identity.py:1136-1156@1.6.0`).
enum SigningKey {
/// The X25519 key did not load: `validate` raises.
None,
/// The X25519 key loaded but the Ed25519 key did not: no hash, and
/// `validate` returns False.
NoEd25519,
/// Both keys loaded. Upstream accepts any 32 Ed25519 bytes; `identity` is
/// `None` when they are not a curve point, and such a key never validates.
Loaded {
hash: [u8; 16],
identity: Option<Box<Identity>>,
},
}
impl SigningKey {
fn load(pubkey: &[u8]) -> Self {
let half = pubkey.len().min(32);
if half != 32 {
return SigningKey::None;
}
if pubkey.len() != 64 {
return SigningKey::NoEd25519;
}
SigningKey::Loaded {
hash: rns_crypto::sha::truncated_hash(pubkey),
identity: Identity::from_public_key(pubkey).ok().map(Box::new),
}
}
}
/// Python `get_rsg_hash` for bytes, text (as its UTF-8 bytes) or a file.
pub fn get_rsg_hash<R: Read>(mut reader: R) -> std::io::Result<[u8; 32]> {
let mut hasher = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
loop {
@@ -345,6 +436,86 @@ fn sha256_reader<R: Read>(mut reader: R) -> std::io::Result<[u8; 32]> {
Ok(hasher.finalize().into())
}
/// Outcome of `check_release_rsm_structure` when it does not raise.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RsmStructure {
/// Upstream returns `True`.
Valid,
/// Upstream returns this failure string.
Invalid(&'static str),
}
/// Python `check_release_rsm_structure` (`RNS/Utilities/rnid.py:588-600@1.6.0`)
/// over the signed data of a valid manifest. `Err` is the exception text.
pub fn check_release_rsm_structure(signed_data: &Value) -> Result<RsmStructure, String> {
let release_meta = py_get(signed_data, "meta")?;
if !release_meta.is_some_and(py_truthy) {
return Ok(RsmStructure::Invalid("No release metadata in manifest"));
}
let release_meta = release_meta.unwrap_or(&Value::Nil);
let name = py_get(release_meta, "name")?;
let version = py_get(release_meta, "version")?;
let origin = py_get(release_meta, "origin")?;
let path = py_get(release_meta, "path")?;
let truthy = |v: Option<&Value>| v.is_some_and(py_truthy);
if !truthy(name) || !truthy(version) {
return Ok(RsmStructure::Invalid("Incomplete package data in manifest"));
}
if !truthy(origin) || !truthy(path) {
return Ok(RsmStructure::Invalid(
"Incomplete release origin data in manifest",
));
}
if py_contains(name, "/")? || py_contains(version, "/")? {
return Ok(RsmStructure::Invalid("Invalid data in release manifest"));
}
let origin = origin.unwrap_or(&Value::Nil);
if py_len(origin)? != 16 {
return Ok(RsmStructure::Invalid(
"Invalid origin hash length in manifest",
));
}
if !matches!(origin, Value::Binary(_)) {
return Ok(RsmStructure::Invalid("Invalid origin hash in manifest"));
}
Ok(RsmStructure::Valid)
}
/// Python `container.get(key, None)`; only a dict has `get`.
fn py_get<'a>(container: &'a Value, key: &str) -> Result<Option<&'a Value>, String> {
match container {
Value::Map(entries) => Ok(entries
.iter()
.find(|(k, _)| k.as_str() == Some(key))
.map(|(_, v)| v)),
other => Err(format!(
"'{}' object has no attribute 'get'",
py_class_name(other)
)),
}
}
/// Python `len(value)`.
fn py_len(value: &Value) -> Result<usize, String> {
match value {
Value::String(s) => Ok(s.as_str().map_or(s.as_bytes().len(), |s| s.chars().count())),
Value::Binary(b) => Ok(b.len()),
Value::Array(a) => Ok(a.len()),
Value::Map(m) => Ok(m.len()),
other => Err(format!(
"object of type '{}' has no len()",
py_class_name(other)
)),
}
}
fn py_class_name(value: &Value) -> &'static str {
match value {
Value::Ext(_, _) => "Ext",
other => py_type_name(other),
}
}
pub fn pretty_hash(hash: &[u8]) -> String {
format!("<{}>", hex::encode(hash))
}
@@ -364,6 +535,16 @@ mod tests {
Identity::from_private_key(&hex::decode(FIXTURE_PRV_HEX).unwrap()).unwrap()
}
#[test]
fn deeply_nested_envelope_is_rejected_without_overflowing() {
let mut data = vec![0x91u8; 200_000];
data.push(0x00);
assert!(unpackb(&data).is_none());
let mut data = vec![0x91u8; 100];
data.push(0x00);
assert!(unpackb(&data).is_some());
}
#[test]
fn created_containers_are_byte_exact_with_upstream() {
let identity = fixture_identity();
File renamed without changes.
@@ -437,7 +437,35 @@ fn parse_config(content: &[u8]) -> Result<Tree, String> {
std::str::from_utf8(raw).map_err(|_| pyfmt::py_utf8_error(raw).unwrap_or_default())?;
lines.push(text.trim_end_matches(['\r', '\n']).to_string());
}
parse_lines(lines)
}
/// Python `str.splitlines()`.
fn py_splitlines(text: &str) -> Vec<String> {
let mut lines = Vec::new();
let mut current = String::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\n' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{85}' | '\u{2028}'
| '\u{2029}' => lines.push(std::mem::take(&mut current)),
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
}
lines.push(std::mem::take(&mut current));
}
other => current.push(other),
}
}
if !current.is_empty() {
lines.push(current);
}
lines
}
/// `ConfigObj._parse` over a list of decoded lines.
fn parse_lines(lines: Vec<String>) -> Result<Tree, String> {
let p = Patterns::new();
let mut tree = Tree::new();
let mut errors: Vec<ParseErr> = Vec::new();
@@ -1248,6 +1276,23 @@ pub fn rsg_meta_from_file(
parsed.dict(0)
}
/// `rsg_meta_from_str(meta, spec)`: the text is split with `str.splitlines`
/// and, unlike a file, a leading BOM is kept.
pub fn rsg_meta_from_str(meta: &str, spec: Option<&str>) -> Result<Vec<(String, Obj)>, String> {
let spec = spec
.filter(|spec| !spec.is_empty())
.map(|spec| parse_lines(py_splitlines(spec)))
.transpose()?;
let mut parsed = parse_lines(py_splitlines(meta))?;
if let Some(spec) = spec {
parsed.nodes[0].configspec = Some(0);
if !validate(&mut parsed, &spec, 0)? {
return Err("Metadata did not pass spec validation".to_string());
}
}
parsed.dict(0)
}
/// Pack a metadata object as umsgpack would; errors are umsgpack's text.
pub fn to_msgpack(obj: &Obj) -> Result<Value, String> {
Ok(match obj {
@@ -1,5 +1,6 @@
//! Python `str()`/`repr()` rendering of msgpack values, as printed by
//! `rnid -V <file>.rsm --meta` (`RNS/Utilities/rnid.py:697-723@1.6.0`).
//! `rnid -V <file>.rsm --meta` (`RNS/Utilities/rnid.py:697-723@1.6.0`),
//! and of the exceptions the rsg tools print.
use rmpv::Value;
@@ -150,6 +151,41 @@ pub fn py_float(value: f64) -> String {
}
}
/// `bytes.fromhex`.
pub fn py_fromhex(text: &str) -> Result<Vec<u8>, String> {
let chars: Vec<char> = text.chars().collect();
let err =
|pos: usize| format!("non-hexadecimal number found in fromhex() arg at position {pos}");
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
if matches!(chars[i], ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r') {
i += 1;
continue;
}
let hi = chars[i].to_digit(16).ok_or_else(|| err(i))?;
let lo = chars
.get(i + 1)
.and_then(|c| c.to_digit(16))
.ok_or_else(|| err(i + 1))?;
out.push((hi * 16 + lo) as u8);
i += 2;
}
Ok(out)
}
/// Python `str(OSError)` for a failed file operation.
pub fn py_os_error(error: &std::io::Error, path: &str) -> String {
match error.raw_os_error() {
Some(code) => format!(
"[Errno {code}] {}: {}",
nix::errno::Errno::from_raw(code).desc(),
py_str_repr(path)
),
None => error.to_string(),
}
}
/// Text of the `UnicodeDecodeError` CPython raises for `data.decode("utf-8")`.
pub fn py_utf8_error(data: &[u8]) -> Option<String> {
let err = std::str::from_utf8(data).err()?;
File renamed without changes.
+11 -2
View File
@@ -244,8 +244,17 @@ async fn answer_stats_request(
rpc::write_mp_frame(stream, &rpc::compute_python_auth_response(rpc_key, message)).await?;
assert_eq!(rpc::read_mp_frame(stream, 256).await?, WELCOME);
let request = rpc::decode_request(&rpc::read_mp_frame(stream, 4096).await?)?;
assert!(matches!(request, rpc::RpcRequest::GetInterfaceStats));
let answer = rpc::encode_response(&rpc::RpcResponse::InterfaceStats(stats.to_vec()))?;
// rnstatus registers its destination type around the stats request.
let answer = match request {
rpc::RpcRequest::WantsDestinationType { .. }
| rpc::RpcRequest::UnwantsAllDestinationTypes { .. } => {
rpc::encode_response(&rpc::RpcResponse::BoolResult(true))?
}
rpc::RpcRequest::GetInterfaceStats => {
rpc::encode_response(&rpc::RpcResponse::InterfaceStats(stats.to_vec()))?
}
other => panic!("unexpected request {other:?}"),
};
rpc::write_mp_frame(stream, &answer).await
}
+55 -19
View File
@@ -2,15 +2,15 @@ use super::*;
use crate::announce_validation::{CachedAnnounce, InvalidAnnounce, ValidatedAnnounce};
use crate::now_f64;
/// Where an inbound packet comes from. Python re-injects held and cached
/// announces with `ifac_handled=True` (Interface.py:296, Transport.py:3119),
/// Where an inbound packet comes from. Python re-injects held announces and
/// cached packets with `ifac_handled=True` (Interface.py:296, Transport.py:3460),
/// and its byte counters live in the interface drivers, so neither passes
/// IFAC or counts as received traffic again.
#[derive(Clone, Copy, PartialEq, Eq)]
enum InboundOrigin {
Wire,
HeldAnnounce,
CachedAnnounce,
CachedPacket,
}
/// A transit link proof's verdict; only a bad signature is a protocol
@@ -122,15 +122,22 @@ impl TransportActor {
}
}
pub(super) fn on_cached_announce(&mut self, packet: crate::messages::InboundPacket) {
if packet.raw.len() > 500
|| !rns_wire::header::PacketHeader::unpack(&packet.raw).is_ok_and(|(header, _)| {
header.flags.packet_type == rns_wire::flags::PacketType::Announce
})
{
/// Python `Transport.inbound(cached.raw, cached.receiving_interface)`
/// for a locally cached packet; a sent packet has no receiving interface.
pub(super) fn replay_cached_packet(&mut self, raw: Bytes) {
if raw.len() > 500 {
return;
}
self.on_inbound_inner(packet, InboundOrigin::CachedAnnounce);
self.on_inbound_inner(
crate::messages::InboundPacket {
raw,
interface_id: 0,
rssi: None,
snr: None,
q: None,
},
InboundOrigin::CachedPacket,
);
}
fn on_inbound_inner(&mut self, packet: crate::messages::InboundPacket, origin: InboundOrigin) {
@@ -147,7 +154,7 @@ impl TransportActor {
}
// Upstream bounds the frame only after IFAC (Transport.py:2014,
// HW_MTU + ifac_size, the default IFAC size without IFAC).
let clear_limit = if origin == InboundOrigin::CachedAnnounce {
let clear_limit = if origin == InboundOrigin::CachedPacket {
500
} else {
let Some(entry) = self.interfaces.get(&packet.interface_id) else {
@@ -349,7 +356,6 @@ impl TransportActor {
snr: packet.snr,
q: packet.q,
};
self.record_packet_metrics(pkt_hash, packet_metrics);
self.record_interface_signal(packet.interface_id, packet_metrics);
// On shared media (e.g. LoRa) we overhear our own forwards and link
@@ -377,7 +383,7 @@ impl TransportActor {
}
}
if origin != InboundOrigin::CachedAnnounce {
if origin != InboundOrigin::CachedPacket {
self.count_rx_packet();
}
@@ -399,6 +405,8 @@ impl TransportActor {
if check_hashlist {
self.packet_hashlist.insert(pkt_hash);
}
// Python records PHY stats in `_inbound`, after the packet filter (Transport.py:2192-2209).
self.record_packet_metrics(pkt_hash, packet_metrics);
parsed.hops = self.adjusted_inbound_hops(parsed.hops, packet.interface_id);
@@ -995,15 +1003,37 @@ impl TransportActor {
}
let app_data_for_handlers = announce_app_data;
// The desiring interface is unused: the response rebroadcasts once
// everywhere through the announce table (Transport.py:2626-2648).
if is_from_local_client
&& header.context == rns_wire::context::PacketContext::PathResponse
&& let Some(waiting_interface) = self
&& self
.pending_local_path_requests
.remove(&header.destination_hash)
&& let Some(response) =
self.path_response_from_cached_announce(raw, header.destination_hash, header.hops)
.is_some()
{
self.send_to_interface(waiting_interface, &response);
let now = now_f64();
let rebroadcast_raw = self.transport_announce_from_raw(
raw,
header.destination_hash,
header.hops,
rns_wire::context::PacketContext::None,
);
self.announce_table.insert(
header.destination_hash,
crate::announce::AnnounceEntry {
timestamp: now,
retransmit_timeout: now,
retries: PATHFINDER_R,
received_from: header.transport_id.unwrap_or(header.destination_hash),
hops: header.hops,
packet_raw: rebroadcast_raw,
local_rebroadcasts: 0,
block_rebroadcast: false,
attached_interface: None,
source_interface: Some(interface_id),
},
);
}
self.send_announce_to_local_clients(
@@ -1166,8 +1196,14 @@ impl TransportActor {
return;
}
if header.context == rns_wire::context::PacketContext::CacheRequest {
self.handle_cache_request(raw, header, interface_id);
if header.context == rns_wire::context::PacketContext::CacheRequest
&& self.handle_cache_request(
raw,
header,
interface_id,
self.is_transport_enabled || from_local_client || to_local_client,
)
{
return;
}
@@ -289,6 +289,11 @@ impl TransportActor {
self.traffic.record_tx(0, request.raw.len() as u64);
let packet_hash = rns_wire::hash::packet_hash(&request.raw, header.flags.header_type);
self.packet_hashlist.insert(packet_hash);
if header.flags.packet_type == rns_wire::flags::PacketType::Proof
&& header.context == rns_wire::context::PacketContext::ResourcePrf
{
self.cache_proof(packet_hash, request.raw.clone());
}
if interface_id != LOCAL_LINK_INITIATOR_INTERFACE
&& interface_id != LOCAL_LINK_RESPONDER_INTERFACE
+78 -251
View File
@@ -123,10 +123,11 @@ pub struct TransportActor {
pub traffic: TrafficCounter,
/// Python's interface traffic count and top-level stats counters.
traffic_count: rpc::TrafficCount,
/// Optional driver observations keyed by packet hash. Actor insertion keeps
/// at most 512 entries; metrics are not normalized or independently validated.
pub packet_metrics: HashMap<[u8; 32], PacketMetrics>,
pub packet_metrics_order: VecDeque<[u8; 32]>,
/// Python's `local_client_rssi_cache`, `_snr_cache` and `_q_cache`: one
/// 512-entry list per metric, first match wins (Transport.py:320-324).
pub packet_rssi_cache: VecDeque<([u8; 32], f32)>,
pub packet_snr_cache: VecDeque<([u8; 32], f32)>,
pub packet_q_cache: VecDeque<([u8; 32], f32)>,
pub receipt_table: HashMap<[u8; 16], PacketReceipt>,
/// Truncated packet hash to caller-supplied message ID for proof notifications.
@@ -147,6 +148,12 @@ pub struct TransportActor {
pub local_destination_keys: HashMap<[u8; 16], [u8; 64]>,
pub destination_channels:
HashMap<[u8; 16], mpsc::Sender<crate::link_messages::DestinationEvent>>,
/// App names of registered destinations; link-id channel aliases are not here.
registered_destination_names: HashMap<[u8; 16], String>,
/// RESOURCE_PRF packets this instance sent, which Python force-caches
/// (Resource.py:775-777), with the time each was stored.
proof_cache: HashMap<[u8; 32], (Bytes, f64)>,
proof_cache_order: VecDeque<[u8; 32]>,
/// Duplex routes for Links whose initiator and responder are registered
/// on this same transport actor. Keeping both endpoints here avoids the
/// single `destination_channels[link_id]` slot aliasing one side over the
@@ -510,8 +517,9 @@ impl TransportActor {
blackhole_table: BlackholeTable::new(),
traffic: TrafficCounter::new(),
traffic_count: rpc::TrafficCount::default(),
packet_metrics: HashMap::new(),
packet_metrics_order: VecDeque::new(),
packet_rssi_cache: VecDeque::new(),
packet_snr_cache: VecDeque::new(),
packet_q_cache: VecDeque::new(),
receipt_table: HashMap::new(),
receipt_msg_ids: HashMap::new(),
receipt_proof_txs: HashMap::new(),
@@ -520,6 +528,9 @@ impl TransportActor {
local_destinations: HashSet::new(),
local_destination_keys: HashMap::new(),
destination_channels: HashMap::new(),
registered_destination_names: HashMap::new(),
proof_cache: HashMap::new(),
proof_cache_order: VecDeque::new(),
local_link_routes: HashMap::new(),
pending_local_link_requests: HashMap::new(),
pending_local_link_hops: HashMap::new(),
@@ -888,11 +899,9 @@ impl TransportActor {
let mut packet_receipt = PacketReceipt::new(
registration.full_hash,
registration.truncated_hash,
Some(
registration
.timeout
.unwrap_or(std::time::Duration::from_secs(180)),
),
Some(registration.timeout.unwrap_or_else(|| {
self.default_receipt_timeout(&registration.destination_hash)
})),
);
packet_receipt.set_destination_identity(
registration.destination_hash,
@@ -961,6 +970,8 @@ impl TransportActor {
self.local_destinations.insert(hash);
if let Some(tx) = delivery_tx {
self.destination_channels.insert(hash, tx.clone());
self.registered_destination_names
.insert(hash, app_name.clone());
// On a shared-instance connection, the destination is
// brand new to the shared peer; fire an announce so it
// learns the path immediately instead of waiting for the
@@ -993,53 +1004,7 @@ impl TransportActor {
TransportMessage::CacheRequest {
packet_hash,
destination_hash,
} => {
// Serve straight from the disk announce cache, then replay
// through our own inbound path on the interface the file
// names (Transport.py:3083-3087, :3119). Id 0, which no
// interface registers, stands for Python's missing interface.
if let Some(cached) = self.cached_announce(&packet_hash) {
debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local hit, replaying");
let interface_id = cached
.interface_reference
.as_deref()
.and_then(|name| self.replay_interface(name))
.unwrap_or(0);
let inbound = crate::messages::InboundPacket {
raw: Bytes::from(cached.raw_packet),
interface_id,
rssi: None,
snr: None,
q: None,
};
self.on_cached_announce(inbound);
self.process_background_starts();
return;
}
// Local miss: only transport nodes forward the request
// outward — a leaf can't usefully relay a cache query.
if self.is_transport_enabled {
debug!(hash = %hex::encode(&packet_hash[..8]), "cache request: local miss, querying network");
let flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Data,
};
let header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash,
context: rns_wire::context::PacketContext::CacheRequest,
};
let mut raw = header.pack();
raw.extend_from_slice(&packet_hash);
self.broadcast_on_interfaces(&raw, None);
}
}
} => self.send_cache_request(packet_hash, destination_hash),
TransportMessage::RequestPath { destination_hash } => {
self.on_path_request(destination_hash);
}
@@ -1283,7 +1248,9 @@ impl TransportActor {
let mut receipt = PacketReceipt::new(
full_hash,
truncated_hash,
Some(timeout.unwrap_or(std::time::Duration::from_secs(180))),
Some(
timeout.unwrap_or_else(|| self.default_receipt_timeout(&destination_hash)),
),
);
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
self.receipt_table.insert(truncated_hash, receipt);
@@ -1306,7 +1273,9 @@ impl TransportActor {
let mut receipt = PacketReceipt::new(
full_hash,
truncated_hash,
Some(timeout.unwrap_or(std::time::Duration::from_secs(180))),
Some(
timeout.unwrap_or_else(|| self.default_receipt_timeout(&destination_hash)),
),
);
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
self.receipt_table.insert(truncated_hash, receipt);
@@ -1389,16 +1358,6 @@ impl TransportActor {
.is_some_and(|entry| entry.role == InterfaceRole::LocalClient)
}
/// The registered interface a cached packet names, as Python matches
/// `str(interface)` against the cache file's interface reference. An
/// accepted client's name may belong to another peer by now.
fn replay_interface(&self, name: &str) -> Option<InterfaceId> {
self.interfaces
.iter()
.find(|(_, entry)| !entry.accepted && entry.name == name)
.map(|(&id, _)| id)
}
fn allocate_announce_handler_id(&mut self) -> crate::messages::AnnounceHandlerId {
loop {
let id = crate::messages::AnnounceHandlerId(self.next_announce_handler_id);
@@ -1514,8 +1473,9 @@ impl TransportActor {
self.pending_path_entries.clear();
self.path_requests.clear();
self.path_states.clear();
self.packet_metrics.clear();
self.packet_metrics_order.clear();
self.packet_rssi_cache.clear();
self.packet_snr_cache.clear();
self.packet_q_cache.clear();
self.receipt_proof_txs.clear();
self.discovery_path_requests.clear();
self.pending_local_path_requests.clear();
@@ -1571,32 +1531,45 @@ impl TransportActor {
}
fn record_packet_metrics(&mut self, packet_hash: [u8; 32], metrics: PacketMetrics) {
if metrics.rssi.is_none() && metrics.snr.is_none() && metrics.q.is_none() {
return;
}
if !self.packet_metrics.contains_key(&packet_hash) {
self.packet_metrics_order.push_back(packet_hash);
}
self.packet_metrics.insert(packet_hash, metrics);
while self.packet_metrics_order.len() > LOCAL_CLIENT_CACHE_MAXSIZE {
if let Some(old_hash) = self.packet_metrics_order.pop_front() {
self.packet_metrics.remove(&old_hash);
for (cache, value) in [
(&mut self.packet_rssi_cache, metrics.rssi),
(&mut self.packet_snr_cache, metrics.snr),
(&mut self.packet_q_cache, metrics.q),
] {
if let Some(value) = value {
cache.push_back((packet_hash, value));
while cache.len() > LOCAL_CLIENT_CACHE_MAXSIZE {
cache.pop_front();
}
}
}
}
/// Python `shared_connection_reappeared`: each registered destination
/// announces as a path response (Transport.py:4203-4207); owners of
/// non-SINGLE destinations refuse to build an announce.
fn request_announces_from_local_destinations(&mut self) {
let destinations: Vec<(
[u8; 16],
String,
mpsc::Sender<crate::link_messages::DestinationEvent>,
)> = self
.destination_channels
.registered_destination_names
.iter()
.map(|(hash, tx)| (*hash, tx.clone()))
.filter_map(|(hash, app_name)| {
self.destination_channels
.get(hash)
.map(|tx| (*hash, app_name.clone(), tx.clone()))
})
.collect();
for (hash, tx) in destinations {
for (hash, app_name, tx) in destinations {
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::AnnounceRequested(
crate::link_messages::AnnounceRequest::normal(String::new()),
crate::link_messages::AnnounceRequest {
app_name,
path_response: true,
tag: None,
attached_interface: None,
},
)) {
self.channel_drops += 1;
warn!(dest = hex::encode(hash), drops = self.channel_drops, err = %e,
@@ -1732,33 +1705,13 @@ impl TransportActor {
}
}
/// Send `false` to any waiter that has been parked longer than
/// `PATH_WAITER_TIMEOUT`, so a caller that lost its chance to race with
/// a learned path doesn't wait forever.
fn expire_path_waiters(&mut self, now: f64) {
const PATH_WAITER_TIMEOUT: f64 = 15.0;
// Remove-then-reinsert dodges the simultaneous mutable borrow that
// would otherwise happen when partitioning in place.
let keys: Vec<[u8; 16]> = self.path_waiters.keys().copied().collect();
for dest in keys {
if let Some(waiters) = self.path_waiters.remove(&dest) {
let mut kept = Vec::new();
for (reply, created_at) in waiters {
if reply.is_closed() {
continue;
}
if now - created_at >= PATH_WAITER_TIMEOUT {
let _ = reply.send(false);
} else {
kept.push((reply, created_at));
}
}
if !kept.is_empty() {
self.path_waiters.insert(dest, kept);
}
}
}
/// Reap waiters whose caller gave up. The caller owns the deadline, as
/// Python `await_path(timeout)` does (Transport.py:3666-3683).
fn expire_path_waiters(&mut self, _now: f64) {
self.path_waiters.retain(|_, waiters| {
waiters.retain(|(reply, _)| !reply.is_closed());
!waiters.is_empty()
});
}
/// Drop `id` from the interface table and unwind tunnels + paths bound
@@ -1898,6 +1851,7 @@ impl TransportActor {
self.local_destinations.remove(&hash);
self.local_destination_keys.remove(&hash);
self.destination_channels.remove(&hash);
self.registered_destination_names.remove(&hash);
if self.local_link_routes.remove(&hash).is_some() {
self.terminate_link_endpoints_for_link(
hash,
@@ -5885,7 +5839,7 @@ mod tests {
});
assert!(actor.packet_hashlist.is_empty());
assert!(actor.packet_metrics.is_empty());
assert!(actor.packet_rssi_cache.is_empty());
assert!(actor.path_table.is_empty());
}
@@ -9306,138 +9260,6 @@ mod tests {
assert!(tunnel.tunnel_paths.contains_key(&dest_hash));
}
#[test]
fn test_cache_request_handler() {
let dir = std::env::temp_dir().join("rns_cache_request_handler");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (mut actor, _tx) = TransportActor::new();
actor.is_transport_enabled = true; // cache request broadcast requires transport
actor.storage_dir = Some(dir.clone()); // announce receive writes the disk cache
// Register an outbound interface to receive the replayed announce
let (iface, mut rx) = make_test_interface("out1");
actor.interfaces.insert(1, iface);
// Create and inject a valid announce
let (announce_raw, dest_hash) = make_valid_announce("test.cache", 0);
// Compute the packet hash (this is what the cache request will contain)
let packet_hash =
rns_wire::hash::packet_hash(&announce_raw, rns_wire::flags::HeaderType::Header1);
// Process the announce through inbound — populates path_table + recent_announces
let inbound = crate::messages::InboundPacket {
raw: announce_raw.clone(),
interface_id: 1,
rssi: None,
snr: None,
q: None,
};
actor.on_inbound(inbound);
// Verify metadata cached and raw bytes written to the disk announce cache
assert_eq!(actor.recent_announces.len(), 1);
let cached = actor
.recent_announces
.get(&dest_hash)
.expect("announce should be cached under its dest_hash");
assert_eq!(cached.packet_hash, Some(packet_hash));
let on_disk = crate::persistence::load_python_cached_announce(
&dir.join("cache").join("announces"),
&packet_hash,
)
.unwrap()
.expect("announce receive should write the disk cache file");
assert_eq!(on_disk.raw_packet, announce_raw.to_vec());
// Verify path_table has the packet_hash
let path_entry = actor.path_table.get(&dest_hash);
assert!(path_entry.is_some());
assert_eq!(path_entry.unwrap().packet_hash, Some(packet_hash));
// Build a CacheRequest: Data packet with context=CacheRequest, payload=32-byte packet hash
let cr_flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Data,
};
let cr_header = rns_wire::header::PacketHeader {
flags: cr_flags,
hops: 0,
transport_id: None,
destination_hash: [0x00; 16], // CacheRequest dest doesn't matter for lookup
context: rns_wire::context::PacketContext::CacheRequest,
};
let mut cr_raw = cr_header.pack();
cr_raw.extend_from_slice(&packet_hash); // 32-byte payload
// Process the cache request
actor.handle_cache_request(&cr_raw, &cr_header, 1);
actor.flush_announce_queues();
// The output interface should have received the replayed announce
let replayed = rx.try_recv();
assert!(
replayed.is_ok(),
"expected replayed announce on output interface"
);
assert_eq!(replayed.unwrap(), announce_raw);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_cache_request_miss() {
let (mut actor, _tx) = TransportActor::new();
let cr_flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Data,
};
let cr_header = rns_wire::header::PacketHeader {
flags: cr_flags,
hops: 0,
transport_id: None,
destination_hash: [0x00; 16],
context: rns_wire::context::PacketContext::CacheRequest,
};
let mut cr_raw = cr_header.pack();
cr_raw.extend_from_slice(&[0xFF; 32]);
actor.handle_cache_request(&cr_raw, &cr_header, 1);
}
#[test]
fn test_cache_request_invalid_payload_length() {
let (mut actor, _tx) = TransportActor::new();
let cr_flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Data,
};
let cr_header = rns_wire::header::PacketHeader {
flags: cr_flags,
hops: 0,
transport_id: None,
destination_hash: [0x00; 16],
context: rns_wire::context::PacketContext::CacheRequest,
};
let mut cr_raw = cr_header.pack();
cr_raw.extend_from_slice(&[0xFF; 16]);
actor.handle_cache_request(&cr_raw, &cr_header, 1);
}
#[test]
fn load_state_drops_expired_paths_and_stages_others() {
let dir = std::env::temp_dir().join("rns_load_drop_expired");
@@ -10993,6 +10815,7 @@ mod tests {
let (mut shared, _rx) = make_test_interface("shared_server");
shared.role = InterfaceRole::SharedServer;
shared.packet_capacity = crate::InterfacePacketCapacity::new(500, 500, true);
actor.interfaces.insert(5, shared);
match actor.handle_query(TransportQuery::GetNextHopIfName { dest }) {
TransportQueryResponse::StringResult(name) => {
@@ -12586,15 +12409,19 @@ mod tests {
q: None,
});
assert!(
external_rx.try_recv().is_err(),
"the path response is not sent straight to the requester"
);
assert!(!actor.pending_local_path_requests.contains_key(&dest));
actor.last_announces_check = 0.0;
actor.on_tick();
let response = external_rx
.try_recv()
.expect("local-client path response should be returned to the external requester");
.expect("the announce table rebroadcasts the local-client path response");
let (header, _) = rns_wire::header::PacketHeader::unpack(&response).unwrap();
assert_eq!(header.destination_hash, dest);
assert_eq!(
header.context,
rns_wire::context::PacketContext::PathResponse
);
assert_eq!(header.context, rns_wire::context::PacketContext::None);
assert_eq!(
header.flags.header_type,
rns_wire::flags::HeaderType::Header2
+133 -69
View File
@@ -1,6 +1,9 @@
use super::*;
use crate::now_f64;
/// Bound on the in-memory resource proof cache; Python keeps one file per proof.
const PROOF_CACHE_MAX_ENTRIES: usize = 1024;
/// Path-request lengths (Transport.py:3975-3980).
pub(super) const PR_LEGACY_LENGTH: usize = 32;
pub(super) const PR_LENGTH: usize = 48;
@@ -159,15 +162,13 @@ impl TransportActor {
.recent_announces
.get(&request.destination_hash)
.and_then(|announce| announce.public_key);
let receipt_timeout = self.default_receipt_timeout(&request.destination_hash);
match self.receipt_table.entry(trunc_hash) {
std::collections::hash_map::Entry::Vacant(entry) => {
let full_hash =
rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
let mut receipt = PacketReceipt::new(
full_hash,
trunc_hash,
Some(std::time::Duration::from_secs(180)),
);
let mut receipt =
PacketReceipt::new(full_hash, trunc_hash, Some(receipt_timeout));
receipt
.set_destination_identity(request.destination_hash, destination_public_key);
entry.insert(receipt);
@@ -502,80 +503,122 @@ impl TransportActor {
Some(true)
}
/// Payload is a 32-byte packet hash identifying a cached announce. Look
/// up the destination via `path_table.packet_hash`, fetch the stored raw
/// announce in `recent_announces`, and rebroadcast it so the requester
/// can resume an interrupted route.
/// Python's packet cache holds only the resource proofs this instance
/// sent; files expire after `PATH_TIMEOUT` (Reticulum.py:1438-1446).
pub(super) fn cache_proof(&mut self, packet_hash: [u8; 32], raw: Bytes) {
if self
.proof_cache
.insert(packet_hash, (raw, now_f64()))
.is_none()
{
self.proof_cache_order.push_back(packet_hash);
}
while self.proof_cache_order.len() > PROOF_CACHE_MAX_ENTRIES {
if let Some(oldest) = self.proof_cache_order.pop_front() {
self.proof_cache.remove(&oldest);
}
}
}
/// Python `Transport.get_cached_packet(packet_hash)` (Transport.py:3398-3437).
fn cached_proof(&self, packet_hash: &[u8; 32]) -> Option<Bytes> {
self.proof_cache
.get(packet_hash)
.filter(|(_, stored)| now_f64() - stored <= PATHFINDER_E as f64)
.map(|(raw, _)| raw.clone())
}
fn bound_link_role(&self, link_id: &[u8; 16]) -> Option<crate::messages::LinkEndpointRole> {
use crate::messages::LinkEndpointRole;
[LinkEndpointRole::Initiator, LinkEndpointRole::Responder]
.into_iter()
.find(|role| self.link_endpoints.contains_key(&(*link_id, *role)))
}
/// A CACHE_REQUEST for one of our established Links is answered by
/// re-sending the cached packet's data on that Link, and dropped on a
/// miss (Transport.py:2845-2855). Any other request replays a cache hit
/// through inbound when transport handling applies, and otherwise returns
/// false so normal processing continues (Transport.py:2271-2287, :3439-3452).
pub(super) fn handle_cache_request(
&mut self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
_interface_id: InterfaceId,
) {
let payload_start = match self.data_payload_offset(raw, header) {
Some(offset) => offset,
None => {
trace!("cache request: packet too short for header");
return;
}
interface_id: InterfaceId,
transport_handling: bool,
) -> bool {
let requested = self
.data_payload_offset(raw, header)
.and_then(|offset| <[u8; 32]>::try_from(&raw[offset..]).ok());
let link_id = header.destination_hash;
let local_link = (header.flags.destination_type == rns_wire::flags::DestinationType::Link)
.then(|| self.bound_link_role(&link_id))
.flatten();
let Some(role) = local_link else {
let Some(cached) = requested
.filter(|_| transport_handling)
.and_then(|hash| self.cached_proof(&hash))
else {
return false;
};
self.replay_cached_packet(cached);
return true;
};
let payload = &raw[payload_start..];
if payload.len() != 32 {
trace!(
len = payload.len(),
"cache request: payload is not 32 bytes (expected packet hash), ignoring"
);
return;
if self.link_packet_on_unbound_interface(header, interface_id) {
return true;
}
let mut requested_hash = [0u8; 32];
requested_hash.copy_from_slice(payload);
let dest_and_hops: Option<([u8; 16], u8)> = self
.path_table
.iter()
.find(|(_, entry)| entry.packet_hash == Some(requested_hash))
.map(|(dest, entry)| (*dest.as_bytes(), entry.hops));
let Some((dest, cached_hops)) = dest_and_hops else {
trace!(
hash = %hex::encode(requested_hash),
"cache request miss — no path entry with matching packet hash"
);
return;
let Some(cached) = requested.and_then(|hash| self.cached_proof(&hash)) else {
trace!(link_id = %hex::encode(link_id), "cache request miss");
return true;
};
let Some(cached_raw) = self.cached_announce_raw(&requested_hash) else {
trace!(
dest = %hex::encode(dest),
"cache request: path entry found but no cached announce on disk"
);
return;
let Ok((cached_header, offset)) = rns_wire::header::PacketHeader::unpack(&cached) else {
return true;
};
// Python 1.3.8 Transport.py:2164: a cached packet that fails to unpack
// (incl. hops >= PATHFINDER_M, Packet.py:247-248) is a miss — never
// replay the raw bytes.
if rns_wire::header::PacketHeader::unpack(&cached_raw)
.map_or(true, |(h, _)| h.hops >= PATHFINDER_M)
{
trace!(
dest = %hex::encode(dest),
"cache request: cached announce failed to parse, treating as miss"
);
return;
}
debug!(
dest = %hex::encode(dest),
hops = cached_hops,
hash = %hex::encode(requested_hash),
"cache request hit — replaying cached announce"
let mut answer = link_packet_header(
link_id,
cached_header.flags.packet_type,
cached_header.context,
)
.pack();
answer.extend_from_slice(&cached[offset..]);
debug!(link_id = %hex::encode(link_id), "cache request hit, re-sending cached packet");
self.send_link_endpoint(
link_id,
role,
crate::messages::OutboundRequest {
raw: Bytes::from(answer),
destination_hash: link_id,
},
);
if self.is_transport_enabled {
self.broadcast_announce_on_interfaces(&cached_raw, None);
true
}
/// Python `Transport.cache_request`: replay a local hit, otherwise send
/// a CACHE_REQUEST to the destination (Transport.py:3455-3464).
pub(super) fn send_cache_request(&mut self, packet_hash: [u8; 32], destination_hash: [u8; 16]) {
if let Some(cached) = self.cached_proof(&packet_hash) {
self.replay_cached_packet(cached);
return;
}
let Some(role) = self.bound_link_role(&destination_hash) else {
trace!(dest = %hex::encode(destination_hash), "cache request for an unbound Link");
return;
};
let mut raw = link_packet_header(
destination_hash,
rns_wire::flags::PacketType::Data,
rns_wire::context::PacketContext::CacheRequest,
)
.pack();
raw.extend_from_slice(&packet_hash);
self.send_link_endpoint(
destination_hash,
role,
crate::messages::OutboundRequest {
raw: Bytes::from(raw),
destination_hash,
},
);
}
pub(super) fn data_payload_offset(
@@ -1279,6 +1322,27 @@ impl TransportActor {
}
}
/// The header Python's `RNS.Packet(link, ...)` packs (Packet.py:180-190).
fn link_packet_header(
link_id: [u8; 16],
packet_type: rns_wire::flags::PacketType,
context: rns_wire::context::PacketContext,
) -> rns_wire::header::PacketHeader {
rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context,
}
}
#[cfg(test)]
mod cache_miss_tests {
use super::*;
+42 -24
View File
@@ -310,22 +310,13 @@ impl TransportActor {
TransportQueryResponse::StringResult(name)
}
TransportQuery::GetPacketRssi { packet_hash } => TransportQueryResponse::FloatResult(
self.packet_metrics
.get(&packet_hash)
.and_then(|m| m.rssi)
.map(|v| v as f64),
first_packet_metric(&self.packet_rssi_cache, &packet_hash),
),
TransportQuery::GetPacketSnr { packet_hash } => TransportQueryResponse::FloatResult(
self.packet_metrics
.get(&packet_hash)
.and_then(|m| m.snr)
.map(|v| v as f64),
first_packet_metric(&self.packet_snr_cache, &packet_hash),
),
TransportQuery::GetPacketQ { packet_hash } => TransportQueryResponse::FloatResult(
self.packet_metrics
.get(&packet_hash)
.and_then(|m| m.q)
.map(|v| v as f64),
first_packet_metric(&self.packet_q_cache, &packet_hash),
),
TransportQuery::DropPath { dest } => {
// expire() forces immediate cull — plain `remove` would leave
@@ -614,6 +605,7 @@ impl TransportActor {
.map(|e| e.interface_id)
.or_else(|| self.local_destination_interface_id(&dest))
.and_then(|id| self.interfaces.get(&id))
.filter(|iface| iface.packet_capacity.link_mtu_upgrade)
.map(|iface| i64::from(iface.mtu));
TransportQueryResponse::IntResult(mtu.unwrap_or(-1))
}
@@ -627,18 +619,7 @@ impl TransportActor {
TransportQueryResponse::IntResult(id.unwrap_or(-1))
}
TransportQuery::FirstHopTimeout { dest } => {
let timeout = self
.path_table
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.filter(|iface| iface.bitrate != 0)
.map(|iface| {
let per_byte_latency = 8.0 / iface.bitrate as f64;
rns_wire::constants::MTU as f64 * per_byte_latency
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT
})
.unwrap_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT);
TransportQueryResponse::FloatResult(Some(timeout))
TransportQueryResponse::FloatResult(Some(self.first_hop_timeout(&dest)))
}
TransportQuery::ExtraLinkProofTimeout { interface_id } => {
let timeout = self
@@ -1067,6 +1048,43 @@ fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f6
}
}
impl TransportActor {
/// Python `Transport.first_hop_timeout` (Transport.py:3539-3542).
pub(super) fn first_hop_timeout(&self, dest: &[u8; 16]) -> f64 {
self.path_table
.get_live(dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.filter(|iface| iface.bitrate != 0)
.map(|iface| {
let per_byte_latency = 8.0 / iface.bitrate as f64;
rns_wire::constants::MTU as f64 * per_byte_latency
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT
})
.unwrap_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT)
}
/// Python's receipt timeout for a non-Link destination:
/// `first_hop_timeout + TIMEOUT_PER_HOP * hops_to` (Packet.py:427-433).
pub(super) fn default_receipt_timeout(&self, dest: &[u8; 16]) -> std::time::Duration {
let hops = self
.path_table
.hops_to(dest)
.unwrap_or(crate::constants::PATHFINDER_M);
std::time::Duration::from_secs_f64(
self.first_hop_timeout(dest)
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(hops),
)
}
}
/// Python returns the first matching cache entry (Reticulum.py:2085-2093).
fn first_packet_metric(cache: &VecDeque<([u8; 32], f32)>, packet_hash: &[u8; 32]) -> Option<f64> {
cache
.iter()
.find(|(hash, _)| hash == packet_hash)
.map(|(_, value)| f64::from(*value))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -399,53 +399,3 @@ async fn announce_admission_failed_route_recovery_revokes_before_result() {
assert!(result.await.unwrap().path_dropped);
assert!(lane.try_start(now_f64()).is_none());
}
#[test]
fn announce_admission_cache_replay_reconciles_route_before_early_return() {
let directory = unique_temp_dir("announce-cache-revocation");
let (mut actor, _) = TransportActor::new();
actor.is_transport_enabled = true;
actor.transport_identity_hash = Some([0x55; 16]);
actor.storage_dir = Some(directory.clone());
let (entry, _rx) = limited();
let lane = BackgroundAnnounceReceiver::register(&entry.tx).unwrap();
actor.interfaces.insert(1, entry);
let identity = rns_identity::identity::Identity::new();
let emitted = now_f64() as u64;
let (old, dest) = make_announce_for_with_random_blob(
&identity,
"admission.cache.revocation",
1,
random_blob(1, emitted - 1),
);
actor.path_table.insert(
dest,
PathEntry::new(Some([1; 16]), 1, 1, InterfaceMode::Full),
);
actor.broadcast_announce_on_interfaces(&old, None);
actor.process_announce_queues(now_f64());
let (fresh, _) = make_announce_for_with_random_blob(
&identity,
"admission.cache.revocation",
1,
random_blob(2, emitted),
);
let packet_hash = rns_wire::hash::packet_hash(&fresh, rns_wire::flags::HeaderType::Header1);
crate::persistence::write_python_cached_announce_if_absent(
&directory.join("cache").join("announces"),
&packet_hash,
&fresh,
None,
)
.unwrap();
actor.handle_message(TransportMessage::CacheRequest {
packet_hash,
destination_hash: dest,
});
assert_eq!(
actor.path_table.get_live(&dest).unwrap().packet_hash,
Some(packet_hash)
);
assert!(lane.try_start(now_f64()).is_none());
std::fs::remove_dir_all(directory).unwrap();
}
@@ -125,29 +125,6 @@ fn a_wire_announce_without_valid_ifac_is_dropped_and_never_held() {
assert!(!actor.path_table.has_path(&unsigned_destination));
}
#[test]
fn a_replayed_cached_announce_is_not_counted_as_received_traffic() {
let (mut actor, _) = TransportActor::new();
let (entry, _rx) = make_test_interface("cache_replay");
actor.interfaces.insert(1, entry);
let (announce, destination) = make_valid_announce("held.cache.replay", 1);
actor.on_cached_announce(InboundPacket {
raw: announce,
interface_id: 1,
rssi: None,
snr: None,
q: None,
});
assert!(actor.path_table.has_path(&destination));
assert_eq!(
rx_bytes(&actor, 1),
0,
"a cached announce never crossed the wire"
);
}
/// Python's 5 s interface job re-evaluates the limiter (Transport.py:1329-1337),
/// so a burst clears on a quiet interface without another announce.
#[test]
@@ -236,82 +236,6 @@ fn an_unbound_tunnel_persists_without_an_interface_hash() {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_cache_request_replays_on_the_interface_its_cache_file_names() {
let dir = unique_temp_dir("cache-replay-interface");
let mut actor = hub();
actor.storage_dir = Some(dir.clone());
let _rx = attach(&mut actor, 3, "radio");
let (announce, dest) = make_valid_announce("cache.interface", 1);
let packet_hash = cache_announce(&dir, &announce, Some("radio"));
actor.handle_message(TransportMessage::CacheRequest {
packet_hash,
destination_hash: dest,
});
assert_eq!(
actor.path_table.get(&dest).map(|path| path.interface_id),
Some(3),
"Python replays a cached packet on its recorded interface (Transport.py:3119)"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_cache_request_never_replays_on_an_accepted_client() {
let dir = unique_temp_dir("cache-replay-child");
let mut actor = hub();
actor.storage_dir = Some(dir.clone());
let (mut entry, _rx) = make_test_interface("hub/client_3");
entry.parent_id = Some(2);
entry.accepted = true;
actor.interfaces.insert(3, entry);
let (announce, dest) = make_valid_announce("cache.child", 1);
let packet_hash = cache_announce(&dir, &announce, Some("hub/client_3"));
actor.handle_message(TransportMessage::CacheRequest {
packet_hash,
destination_hash: dest,
});
assert!(
actor.recent_announces.contains_key(&dest),
"control: the replay was processed"
);
assert_ne!(
actor.path_table.get(&dest).map(|path| path.interface_id),
Some(3),
"an accepted client's name may belong to another peer by now"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_cache_request_replay_adds_no_tunnel_path() {
let dir = unique_temp_dir("cache-replay-tunnel");
let mut actor = hub();
actor.storage_dir = Some(dir.clone());
let _rx = attach(&mut actor, 1, "hub/client_1");
let tunnel_id = [0x44; 32];
handle_tunnel(&mut actor.tunnel_table, tunnel_id, 1);
actor.deregister_interface(1);
let (announce, dest) = make_valid_announce("cache.tunnel", 1);
let packet_hash = cache_announce(&dir, &announce, None);
actor.handle_message(TransportMessage::CacheRequest {
packet_hash,
destination_hash: dest,
});
assert!(
actor.recent_announces.contains_key(&dest),
"control: the replay was processed"
);
assert!(
!carries(&actor, &tunnel_id, &dest),
"a replay without a live interface joins no tunnel"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn persisted_tunnels_load_unbound_even_when_their_interface_returns() {
let dir = unique_temp_dir("tunnels-load-unbound");
+19 -2
View File
@@ -20,13 +20,13 @@ pub enum AwaitPathError {
#[error("transport actor is not running")]
TransportDown,
/// The caller's deadline elapsed, the actor replied `false`, or the reply
/// sender was dropped. Actor maintenance expires parked waiters after
/// at least 15 seconds; this is not a guaranteed sweep completion time.
/// sender was dropped.
#[error("timed out waiting for path")]
Timeout,
}
/// Wait up to `timeout` for a cached or newly learned path to `destination_hash`.
/// A zero `timeout` means `PATH_REQUEST_TIMEOUT`, as Python's `await_path` (Transport.py:3678).
/// The deadline includes waiting to submit the command, not just its reply.
/// Success reflects actor path state and does not probe the remote application.
///
@@ -56,6 +56,11 @@ pub async fn await_path(
}
};
let timeout = if timeout.is_zero() {
Duration::from_secs_f64(crate::constants::PATH_REQUEST_TIMEOUT)
} else {
timeout
};
match tokio::time::timeout(timeout, operation).await {
Ok(result) => result,
// The deadline covers both actor-channel admission and the reply.
@@ -113,6 +118,18 @@ mod tests {
assert_eq!(out, Err(AwaitPathError::Timeout));
}
#[tokio::test(start_paused = true)]
async fn zero_timeout_waits_for_the_default_path_request_timeout() {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(4);
tokio::spawn(async move {
if let Some(TransportMessage::AwaitPath { reply, .. }) = rx.recv().await {
tokio::time::sleep(Duration::from_secs(14)).await;
let _ = reply.send(true);
}
});
assert!(await_path(&tx, [0x77; 16], Duration::ZERO).await.is_ok());
}
#[tokio::test]
async fn transport_down_when_channel_closed() {
let (tx, rx) = mpsc::channel::<TransportMessage>(1);
+3 -3
View File
@@ -761,9 +761,9 @@ pub enum TransportMessage {
id: AnnounceHandlerId,
result_tx: Option<tokio::sync::oneshot::Sender<bool>>,
},
/// Replay a matching packet from the local on-disk announce cache when
/// available. On a miss, a network CacheRequest is emitted only when transport
/// is enabled. This command has no success reply.
/// Python `Transport.cache_request`: replay a locally cached resource proof,
/// otherwise send a CACHE_REQUEST on the bound Link `destination_hash`.
/// This command has no success reply.
CacheRequest {
packet_hash: [u8; 32],
destination_hash: [u8; 16],