diff --git a/Cargo.lock b/Cargo.lock index 15fa110..94d68f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1255,6 +1255,7 @@ dependencies = [ "serde", "sha2", "subtle", + "tempfile", "thiserror 2.0.18", "tokio", "tracing", diff --git a/crates/lxmf-core/src/constants.rs b/crates/lxmf-core/src/constants.rs index f0de96b..0e4c636 100644 --- a/crates/lxmf-core/src/constants.rs +++ b/crates/lxmf-core/src/constants.rs @@ -176,7 +176,7 @@ pub const PATH_REQUEST_WAIT: u64 = 7; pub const MAX_PATHLESS_TRIES: u32 = 1; /// Maximum link inactivity before teardown (seconds). pub const LINK_MAX_INACTIVITY: u64 = 10 * 60; -/// Python propagation-link inactivity limit, in seconds; retained as a reference value. +/// Inbound propagation links with no data for this long are torn down (seconds). pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60; pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60; pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60; diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 5e0f1ba..76a3006 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -48,10 +48,12 @@ use lxmf_core::router::{ AutopeerCandidate, DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, DirectRouteSnapshot, LxmRouter, OutboundAction, plan_direct_delivery, }; -use lxmf_tools::daemon::{DaemonConfig, create_router_with_transport, persist_inbound_and_execute}; +use lxmf_tools::daemon::{ + DaemonConfig, PythonLxmdConfig, create_router_with_transport, persist_inbound_and_execute, +}; use lxmf_tools::lxmd_cli::{ - Args, example_config, load_hash_list, normalize_hash_hex, parse_destination_hash, - parse_send_fields_json, + Args, default_config_file_text, example_config, load_hash_list, normalize_hash_hex, + parse_destination_hash, parse_send_fields_json, }; use lxmf_tools::lxmd_control::{ CONTROL_APP_NAME, ControlCommandKind, ControlResponse, decode_control_response, @@ -877,20 +879,94 @@ fn handle_pn_offer_request( } /// Python `lxmd.program_setup`/`_remote_init`: the daemon starts from its own -/// config's `loglevel` (a missing file is the default config it writes first); -/// control commands never read it and start at Notice. -fn setup_logging(args: &Args, config_dir: &Path, rns_config_dir: &Path, control_command: bool) { - let configured = if control_command { - None - } else { - rns_runtime::config::Config::from_file(&config_dir.join("config")) - .or_else(|_| rns_runtime::config::Config::parse(example_config())) - .ok() - .and_then(|c| c.section("logging")?.get_int("loglevel")) - }; +/// config's `loglevel` and logs to `/logfile` in service mode; +/// control commands never read the config and start at Notice on stdout. +fn setup_logging( + args: &Args, + configured: Option, + service_log_dir: Option<&Path>, + rns_config_dir: &Path, +) { let level = rns_tools::Utility::Lxmd.loglevel(configured, args.verbose, args.quiet, false); let timestamps = rns_tools::config_log_timestamps(rns_config_dir); - rns_tools::init_tracing(level, timestamps, true, std::io::stdout); + match service_log_dir { + Some(dir) => { + let path = dir.join("logfile"); + rns_tools::init_tracing(level, timestamps, false, move || { + PythonLogFile(path.clone()) + }); + } + None => rns_tools::init_tracing(level, timestamps, true, std::io::stdout), + } +} + +/// Python `RNS.log` with `LOG_FILE`: append each line, rotate to +/// `logfile.1` past `LOG_MAXSIZE`, and fall back to the console on error. +struct PythonLogFile(PathBuf); + +impl std::io::Write for PythonLogFile { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + const LOG_MAXSIZE: u64 = 5 * 1024 * 1024; + let written = (|| { + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&self.0)?; + file.write_all(buf)?; + if file.metadata()?.len() > LOG_MAXSIZE { + let previous = self.0.with_file_name("logfile.1"); + let _ = std::fs::remove_file(&previous); + std::fs::rename(&self.0, previous)?; + } + std::io::Result::Ok(()) + })(); + match written { + Ok(()) => Ok(buf.len()), + Err(_) => std::io::stdout().write(buf), + } + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Python `program_setup`: write the default config on first run, and +/// `RNS.panic()` when the file cannot be parsed. Returns whether it was created. +fn load_or_create_daemon_config(config_dir: &Path) -> (rns_runtime::config::Config, bool) { + let config_path = config_dir.join("config"); + let created = !config_path.is_file(); + if created { + let written = std::fs::create_dir_all(config_dir) + .and_then(|()| std::fs::write(&config_path, default_config_file_text())); + if let Err(error) = written { + println!( + "Could not create the default configuration file at {}: {error}", + config_path.display() + ); + std::process::exit(1); + } + } + match rns_runtime::config::Config::from_file(&config_path) { + Ok(config) => (config, created), + Err(_) => { + println!( + "Could not parse the configuration at {}", + config_path.display() + ); + println!("Check your configuration file for errors!"); + std::process::exit(255); + } + } +} + +/// Python adds the timeout to `time.time()`; an infinite or NaN timeout never expires. +fn control_timeout(args: &Args) -> f64 { + match args.timeout { + Some(timeout) if timeout != 0.0 => timeout, + _ if args.status || args.peers => 5.0, + _ => 10.0, + } } fn now_f64() -> f64 { @@ -1845,10 +1921,10 @@ impl LxmdRunner { let identity_path = paths.preferred_identity_path().to_path_buf(); let identity = if identity_path.exists() { - tracing::info!("Loading identity from {}", identity_path.display()); + rns_transport::notice!("Loading identity from {}", identity_path.display()); Identity::from_file(&identity_path)? } else { - tracing::info!("No identity found, generating new one"); + rns_transport::notice!("No identity found, generating new one"); let id = Identity::new(); id.to_file(&paths.identity_path)?; id @@ -1863,7 +1939,7 @@ impl LxmdRunner { let control_dest_hash = Destination::hash_from_name_and_identity(CONTROL_APP_NAME, Some(&identity.hash)); - tracing::info!( + rns_transport::notice!( "Identity: {} (LXMF: {})", &identity_hash[..16], &hex::encode(lxmf_dest_hash)[..16], @@ -2118,6 +2194,10 @@ impl LxmdRunner { )?; prop_link_mgr.set_accounting_event_channel(prop_accounting_tx); prop_link_mgr.set_resource_strategy(rns_runtime::prelude::ResourceStrategy::AcceptApp); + // LXMRouter.clean_links: idle propagation links are torn down. + prop_link_mgr.set_data_inactivity_timeout(Some(std::time::Duration::from_secs( + lxmf_core::constants::P_LINK_MAX_INACTIVITY, + ))); let pn_for_handler = pn.clone(); let offer_path_hash = rns_crypto::sha::truncated_hash( @@ -5782,15 +5862,62 @@ pub(crate) async fn main() { let args = Args::parse(); if args.exampleconfig { - print!("{}", example_config()); + println!("{}", example_config()); return; } let (config_dir, rns_config_dir) = resolve_config_dirs(args.config.as_deref(), args.rnsconfig.as_deref()); + // Python tests the strings for truth, so an empty hash starts the daemon. + let sync_hash = args.sync.as_deref().filter(|hash| !hash.is_empty()); + let unpeer_hash = args.unpeer.as_deref().filter(|hash| !hash.is_empty()); let is_control_command = - args.status || args.peers || args.sync.is_some() || args.unpeer.is_some(); - setup_logging(&args, &config_dir, &rns_config_dir, is_control_command); + args.status || args.peers || sync_hash.is_some() || unpeer_hash.is_some(); + + let daemon_setup = if is_control_command || args.migrate_propagation_store { + None + } else { + // Python creates the storage directories before it reads the config. + if let Err(error) = initialize_storage_namespace(&config_dir) { + println!("Failed to establish private daemon storage namespace: {error}"); + std::process::exit(1); + } + let (config, created) = load_or_create_daemon_config(&config_dir); + let loaded = DaemonConfig::from_config(&config).and_then(|daemon_config| { + Ok(( + daemon_config, + PythonLxmdConfig::from_config(&config)?.target_loglevel, + )) + }); + match loaded { + Ok((daemon_config, loglevel)) => Some((daemon_config, loglevel, created)), + Err(error) => { + println!( + "Could not apply LXM Daemon configuration. The contained exception was: {error}" + ); + std::process::exit(1); + } + } + }; + setup_logging( + &args, + daemon_setup.as_ref().and_then(|(_, loglevel, _)| *loglevel), + daemon_setup + .as_ref() + .filter(|_| args.service) + .map(|_| config_dir.as_path()), + &rns_config_dir, + ); + if daemon_setup + .as_ref() + .is_some_and(|(_, _, created)| *created) + { + tracing::info!("Could not load config file, creating default configuration file..."); + tracing::info!( + "Default config file created. Make any necessary changes in {} and restart lxmd if needed.", + config_dir.join("config").display() + ); + } if args.migrate_propagation_store { let result = (|| -> std::io::Result<()> { @@ -5850,7 +5977,7 @@ pub(crate) async fn main() { let peer_hash = if args.status || args.peers { None } else { - args.sync.as_deref().or(args.unpeer.as_deref()) + sync_hash.or(unpeer_hash) }; match preflight_control_command( &config_dir, @@ -5868,33 +5995,9 @@ pub(crate) async fn main() { None }; - if !is_control_command && let Err(error) = initialize_storage_namespace(&config_dir) { - tracing::error!(%error, "Failed to establish private daemon storage namespace"); - std::process::exit(1); - } - let config_path = config_dir.join("config"); - let config = match rns_runtime::config::Config::from_file(&config_path) { - Ok(c) => c, - Err(e) => { - tracing::warn!( - "Could not load config from {}: {}", - config_path.display(), - e - ); - tracing::info!("Using default configuration"); - rns_runtime::config::Config::parse(rns_runtime::config::Config::default_config()) - .expect("default config must parse") - } - }; - - let mut daemon_config = match DaemonConfig::from_config(&config) { - Ok(daemon_config) => daemon_config, - Err(error) => { - tracing::error!("Could not apply LXM Daemon configuration: {error}"); - eprintln!("Could not apply LXM Daemon configuration: {error}"); - std::process::exit(3); - } - }; + let mut daemon_config = daemon_setup + .map(|(daemon_config, _, _)| daemon_config) + .unwrap_or_default(); if args.propagation_node { daemon_config.propagation_enabled = true; } @@ -5902,13 +6005,15 @@ pub(crate) async fn main() { daemon_config.on_inbound_command = Some(on_inbound.clone()); } - tracing::info!("LXMF Daemon starting"); - if let Some(ref name) = daemon_config.display_name { - tracing::info!("Display name: {}", name); + if !is_control_command { + rns_transport::notice!("LXMF Daemon starting"); + if let Some(ref name) = daemon_config.display_name { + tracing::info!("Display name: {}", name); + } } - if daemon_config.propagation_enabled { - tracing::info!( + if !is_control_command && daemon_config.propagation_enabled { + rns_transport::notice!( "Propagation node enabled (stamp_cost={}, max_peers={}, autopeer={})", daemon_config.propagation_stamp_cost, daemon_config.max_peers, @@ -5937,7 +6042,7 @@ pub(crate) async fn main() { .await { Ok(h) => { - tracing::info!( + tracing::debug!( "RNS initialized: mode={:?}, interfaces={}", h.instance_mode, h.interface_configs.len(), @@ -5946,7 +6051,13 @@ pub(crate) async fn main() { } Err(e) => { tracing::error!("Failed to initialize RNS: {e:?}"); - return; + if let rns_runtime::reticulum::ReticulumError::Config( + rns_runtime::config::ConfigError::Parse { .. }, + ) = e + { + std::process::exit(255); + } + std::process::exit(1); } }; rns_handle @@ -5975,14 +6086,11 @@ pub(crate) async fn main() { std::process::exit(4); } }; - let timeout = args - .timeout - .unwrap_or(if args.status || args.peers { 5.0 } else { 10.0 }) - .max(0.0); - if !wait_for_online_interface(&rns_handle, Duration::from_secs_f64(timeout.min(5.0))).await - { - println!("No online Reticulum interface became available, exiting now"); - std::process::exit(200); + let timeout = control_timeout(&args); + // Python's TCP client interfaces finish their initial connect (up to 5 s) + // inside `RNS.Reticulum()`, before the control timeout starts. + if !rns_handle.interface_configs.is_empty() { + wait_for_online_interface(&rns_handle, Duration::from_secs(5)).await; } let target_identity_hash = match preflight.remote_hash { Some(remote_hash) => { @@ -6028,7 +6136,7 @@ pub(crate) async fn main() { return; } - if args.sync.is_some() { + if sync_hash.is_some() { let peer_hash = preflight .peer_hash .expect("sync preflight should include peer hash"); @@ -6051,7 +6159,7 @@ pub(crate) async fn main() { return; } - if args.unpeer.is_some() { + if unpeer_hash.is_some() { let peer_hash = preflight .peer_hash .expect("unpeer preflight should include peer hash"); @@ -6075,6 +6183,18 @@ pub(crate) async fn main() { } } + // Python `program_setup` exits 4 when an existing identity file cannot be loaded. + let identity_path = LxmdPaths::new(&config_dir) + .preferred_identity_path() + .to_path_buf(); + if identity_path.is_file() && Identity::from_file(&identity_path).is_err() { + tracing::error!( + "Could not load the Primary Identity from {}", + identity_path.display() + ); + std::process::exit(4); + } + let mut runner = match LxmdRunner::new( daemon_config.clone(), &config_dir, @@ -6134,7 +6254,7 @@ pub(crate) async fn main() { runner.refresh_control_state(); - tracing::info!("LXMF router initialized"); + rns_transport::notice!("LXMF router initialized"); // Python's enable_propagation() always announces the node, independent of // the deferred start jobs. @@ -6382,7 +6502,7 @@ pub(crate) async fn main() { } if !shutdown.is_triggered() { - tracing::info!("LXMF Daemon running. Press Ctrl+C to stop."); + rns_transport::notice!("LXMF Daemon running. Press Ctrl+C to stop."); } // Event-driven for inbound, periodic for outbound and maintenance. @@ -6479,7 +6599,7 @@ pub(crate) async fn main() { } } - tracing::info!("LXMF Daemon shutting down"); + rns_transport::notice!("LXMF Daemon shutting down"); runner.close_announce_subscriptions().await; runner.prop_get_workers.close_and_join().await; // Revoke new packet admission, then retain and join every already admitted diff --git a/crates/lxmf-tools/src/commands/lxmd_pn.rs b/crates/lxmf-tools/src/commands/lxmd_pn.rs index 5d1b593..f9bcc5a 100644 --- a/crates/lxmf-tools/src/commands/lxmd_pn.rs +++ b/crates/lxmf-tools/src/commands/lxmd_pn.rs @@ -720,6 +720,7 @@ mod tests { LinkManagerAccountingEvent::ResourceCompletion(ResourceCompletion { link_id, resource_hash: resource_id, + last_segment_hash: resource_id, data, metadata: None, }) diff --git a/crates/lxmf-tools/src/daemon.rs b/crates/lxmf-tools/src/daemon.rs index ee7f5c2..ad96b18 100644 --- a/crates/lxmf-tools/src/daemon.rs +++ b/crates/lxmf-tools/src/daemon.rs @@ -56,6 +56,26 @@ pub enum DaemonConfigError { key: &'static str, value: String, }, + /// Python `as_int` raises and lxmd exits. + #[error("[{section}] {key} = {value:?} is not an integer")] + NotAnInteger { + section: &'static str, + key: &'static str, + value: String, + }, + /// Python `as_bool` raises and lxmd exits. + #[error("[{section}] {key} = {value:?} is not a boolean")] + NotABoolean { + section: &'static str, + key: &'static str, + value: String, + }, + /// Python `bytes.fromhex` or the `LXMRouter` length check raises. + #[error("[propagation] static_peers entry {0:?} is not a 16-byte hexadecimal destination hash")] + InvalidStaticPeer(String), + /// `LXMRouter` raises on a negative peer limit. + #[error("[propagation] max_peers = {0} must not be negative")] + NegativeMaxPeers(i64), /// Stamps at this cost cannot be generated (`STAMP_COST_CAP`). #[error("[{section}] {key} = {value} must be a finite cost below 100")] CostOutOfRange { @@ -120,10 +140,19 @@ impl PythonLxmdConfig { let propagation = config.section("propagation"); let logging = config.section("logging"); - let propagation_transfer_max_accepted_size = propagation - .and_then(|sec| sec.get_float("propagation_message_max_accepted_size")) - .map(|v| v.max(0.38)) - .unwrap_or(256.0); + // The legacy key is still parsed (and can raise) before the new one overwrites it. + get_cost( + propagation, + "propagation", + "propagation_transfer_max_accepted_size", + )?; + let propagation_transfer_max_accepted_size = get_float_or_floor( + propagation, + "propagation", + "propagation_message_max_accepted_size", + 256.0, + 0.38, + )?; let peer_stamp_cost = generated_cost( floored_cost(lxmf, "lxmf", "stamp_cost", 1.0, 12.0)?, @@ -167,85 +196,175 @@ impl PythonLxmdConfig { MAX_PEERING_COST, )?; + // Parsed so a malformed value aborts as in Python; the throttle time itself is fixed. + get_cost(propagation, "propagation", "propagation_stamp_throttle")?; + let static_peers = get_list(propagation, "static_peers"); + for peer in &static_peers { + parse_static_peer(peer)?; + } + let max_peers = get_int(propagation, "propagation", "max_peers")?; + if let Some(value) = max_peers.filter(|value| *value < 0) { + return Err(DaemonConfigError::NegativeMaxPeers(value)); + } + Ok(Self { display_name: lxmf .and_then(|sec| sec.get("display_name")) .unwrap_or("Anonymous Peer") .to_string(), - peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false), - peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60), + peer_announce_at_start: get_bool_or(lxmf, "lxmf", "announce_at_start", false)?, + peer_announce_interval: get_int(lxmf, "lxmf", "announce_interval")? + .map(|v| v.saturating_mul(60)), peer_stamp_cost, delivery_transfer_max_accepted_size: get_float_or_floor( lxmf, + "lxmf", "delivery_transfer_max_accepted_size", 1.0, 0.38, - ), + )?, on_inbound: lxmf .and_then(|sec| sec.get("on_inbound")) .map(ToString::to_string), - enable_propagation_node: get_bool_or(propagation, "enable_node", false), + enable_propagation_node: get_bool_or(propagation, "propagation", "enable_node", false)?, node_name: propagation .and_then(|sec| sec.get("node_name")) .map(ToString::to_string), - auth_required: get_bool_or(propagation, "auth_required", false), - node_announce_at_start: get_bool_or(propagation, "announce_at_start", false), - autopeer: get_bool_or(propagation, "autopeer", true), - autopeer_maxdepth: get_int(propagation, "autopeer_maxdepth"), + auth_required: get_bool_or(propagation, "propagation", "auth_required", false)?, + node_announce_at_start: get_bool_or( + propagation, + "propagation", + "announce_at_start", + false, + )?, + autopeer: get_bool_or(propagation, "propagation", "autopeer", true)?, + autopeer_maxdepth: get_int(propagation, "propagation", "autopeer_maxdepth")?, sequential_pn_stamp_validation: get_bool_or( propagation, + "propagation", "sequential_pn_stamp_validation", true, - ), + )?, static_peers_bypass_sequential: get_bool_or( propagation, + "propagation", "static_peers_bypass_sequential", true, - ), - max_inbound_syncs: get_int(propagation, "max_inbound_syncs") + )?, + max_inbound_syncs: get_int(propagation, "propagation", "max_inbound_syncs")? .map(|value| value.max(PN_MIN_MAX_INBOUND_SYNCS as i64)) .unwrap_or(PN_DEFAULT_MAX_INBOUND_SYNCS as i64), - node_announce_interval: get_int(propagation, "announce_interval").map(|v| v * 60), + node_announce_interval: get_int(propagation, "propagation", "announce_interval")? + .map(|v| v.saturating_mul(60)), message_storage_limit: get_float_or_floor( propagation, + "propagation", "message_storage_limit", 500.0, 0.005, - ), + )?, propagation_transfer_max_accepted_size, propagation_sync_max_accepted_size: get_float_or_floor( propagation, + "propagation", "propagation_sync_max_accepted_size", 256.0 * 40.0, 0.38, - ), + )?, propagation_stamp_cost_target, propagation_stamp_cost_flexibility, peering_cost, remote_peering_cost_max, prioritised_lxmf_destinations: get_list(propagation, "prioritise_destinations"), control_allowed_identities: get_list(propagation, "control_allowed"), - static_peers: get_list(propagation, "static_peers"), - max_peers: get_int(propagation, "max_peers"), - from_static_only: get_bool_or(propagation, "from_static_only", false), - target_loglevel: get_int(logging, "loglevel"), + static_peers, + max_peers, + from_static_only: get_bool_or(propagation, "propagation", "from_static_only", false)?, + target_loglevel: get_int(logging, "logging", "loglevel")?, }) } } -fn get_bool_or(section: Option<&ConfigSection>, key: &str, default: bool) -> bool { - section.and_then(|sec| sec.get_bool(key)).unwrap_or(default) +/// A key that is present but not a scalar string fails every ConfigObj `as_*`. +fn raw_value(section: Option<&ConfigSection>, key: &str) -> Option { + let sec = section?; + sec.has(key) + .then(|| sec.get(key).map(ToString::to_string).unwrap_or_default()) } -fn get_int(section: Option<&ConfigSection>, key: &str) -> Option { - section.and_then(|sec| sec.get_int(key)) -} - -fn get_float_or_floor(section: Option<&ConfigSection>, key: &str, default: f64, floor: f64) -> f64 { +/// ConfigObj `as_bool`; `None` when absent. +fn get_bool( + section: Option<&ConfigSection>, + section_name: &'static str, + key: &'static str, +) -> Result, DaemonConfigError> { + let Some(raw) = raw_value(section, key) else { + return Ok(None); + }; section - .and_then(|sec| sec.get_float(key)) - .map(|value| value.max(floor)) - .unwrap_or(default) + .and_then(|sec| sec.get_bool(key)) + .map(Some) + .ok_or(DaemonConfigError::NotABoolean { + section: section_name, + key, + value: raw, + }) +} + +fn get_bool_or( + section: Option<&ConfigSection>, + section_name: &'static str, + key: &'static str, + default: bool, +) -> Result { + Ok(get_bool(section, section_name, key)?.unwrap_or(default)) +} + +/// ConfigObj `as_int`, which is Python `int()`; `None` when absent. +fn get_int( + section: Option<&ConfigSection>, + section_name: &'static str, + key: &'static str, +) -> Result, DaemonConfigError> { + let Some(raw) = raw_value(section, key) else { + return Ok(None); + }; + parse_python_int(&raw) + .map(Some) + .ok_or(DaemonConfigError::NotAnInteger { + section: section_name, + key, + value: raw, + }) +} + +/// Python `int(str)`: optional sign, decimal digits, single underscores between digits. +fn parse_python_int(raw: &str) -> Option { + let s = raw.trim(); + let digits = s.strip_prefix(['+', '-']).unwrap_or(s); + let bytes = digits.as_bytes(); + let well_formed = !bytes.is_empty() + && bytes.iter().enumerate().all(|(i, &b)| { + b.is_ascii_digit() + || (b == b'_' + && i > 0 + && bytes[i - 1].is_ascii_digit() + && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)) + }); + if !well_formed { + return None; + } + s.replace('_', "").parse().ok() +} + +fn get_float_or_floor( + section: Option<&ConfigSection>, + section_name: &'static str, + key: &'static str, + default: f64, + floor: f64, +) -> Result { + Ok(get_cost(section, section_name, key)?.map_or(default, |value| value.max(floor))) } fn get_list(section: Option<&ConfigSection>, key: &str) -> Vec { @@ -254,6 +373,28 @@ fn get_list(section: Option<&ConfigSection>, key: &str) -> Vec { .unwrap_or_default() } +/// Python `bytes.fromhex` followed by the `LXMRouter` static peer length check. +fn parse_static_peer(raw: &str) -> Result<[u8; 16], DaemonConfigError> { + let invalid = || DaemonConfigError::InvalidStaticPeer(raw.to_string()); + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(16); + let mut i = 0; + while i < bytes.len() { + if bytes[i].is_ascii_whitespace() { + i += 1; + continue; + } + let pair = bytes.get(i..i + 2).ok_or_else(invalid)?; + if !pair.iter().all(u8::is_ascii_hexdigit) { + return Err(invalid()); + } + let pair = std::str::from_utf8(pair).map_err(|_| invalid())?; + out.push(u8::from_str_radix(pair, 16).map_err(|_| invalid())?); + i += 2; + } + out.try_into().map_err(|_| invalid()) +} + /// Daemon configuration parsed from an INI config file. #[derive(Debug, Clone)] pub struct DaemonConfig { @@ -389,7 +530,8 @@ impl DaemonConfig { .max_peers .and_then(|value| usize::try_from(value).ok()) .unwrap_or(MAX_PEERS), - autopeer: py.autopeer, + // Python compares hops against a negative depth and never autopeers. + autopeer: py.autopeer && py.autopeer_maxdepth.is_none_or(|depth| depth >= 0), autopeer_maxdepth: py .autopeer_maxdepth .and_then(|value| usize::try_from(value).ok()) diff --git a/crates/lxmf-tools/src/lxmd_cli.rs b/crates/lxmf-tools/src/lxmd_cli.rs index 17ce8c4..fceadde 100644 --- a/crates/lxmf-tools/src/lxmd_cli.rs +++ b/crates/lxmf-tools/src/lxmd_cli.rs @@ -31,7 +31,8 @@ impl SendMethod { name = "lxmd-rs", bin_name = "lxmd-rs", about = "LXMF Propagation Daemon", - version + version, + infer_long_args = true )] pub struct Args { /// Path to configuration directory. @@ -181,78 +182,16 @@ pub fn parse_destination_hash(raw: &str) -> Result<[u8; 16], String> { Ok(hash) } +/// Python `lxmd.__default_lxmd_config__` (LXMF 1.3.0), printed by +/// `--exampleconfig` and written on first run. pub fn example_config() -> &'static str { - r#"# This is an example LXM Daemon config file. -[propagation] + include_str!("lxmd_default_config.txt") +} -enable_node = no - -# control_allowed = 7d7e542829b40f32364499b27438dba8, 437229f8e29598b2282b88bad5e44698 - -# node_name = Anonymous Propagation Node - -announce_interval = 360 - -announce_at_start = yes - -autopeer = yes - -autopeer_maxdepth = 6 - -# Validate inbound propagation stamp batches sequentially by default. -# sequential_pn_stamp_validation = yes - -# Let configured static peers bypass sequential validation and inbound limits. -# static_peers_bypass_sequential = yes - -# Threshold for new inbound propagation sync offers. Already accepted offers -# and static-peer bypass can exceed this value. -# max_inbound_syncs = 3 - -# message_storage_limit = 500 - -# propagation_message_max_accepted_size = 256 - -# propagation_sync_max_accepted_size = 10240 - -# propagation_stamp_cost_target = 16 - -# propagation_stamp_cost_flexibility = 3 - -# peering_cost = 18 - -# remote_peering_cost_max = 26 - -# max_peers = 20 - -# static_peers = e17f833c4ddf8890dd3a79a6fea8161d, 5a2d0029b6e5ec87020abaea0d746da4 - -# prioritise_destinations = 4a594a8cced4a8f6adf23a8ac67b4011 - -# from_static_only = True - -auth_required = no - - -[lxmf] - -display_name = Anonymous Peer - -announce_at_start = no - -# announce_interval = 360 - -# stamp_cost = 12 - -delivery_transfer_max_accepted_size = 1 - -# on_inbound = /path/to/handler - - -[logging] - -loglevel = 4 -"# +/// The file Python `create_default_config` writes: ConfigObj drops the +/// trailing blank line of the default text. +pub fn default_config_file_text() -> String { + format!("{}\n", example_config().trim_end_matches('\n')) } /// Parse a plaintext destination-hash list: one 16-byte hex value per line. diff --git a/crates/lxmf-tools/src/lxmd_control.rs b/crates/lxmf-tools/src/lxmd_control.rs index d6283a7..c081bce 100644 --- a/crates/lxmf-tools/src/lxmd_control.rs +++ b/crates/lxmf-tools/src/lxmd_control.rs @@ -64,11 +64,23 @@ pub async fn query_control( path, encode_control_payload(payload), 0, - Duration::from_secs_f64(timeout_secs.max(0.0)), + control_deadline(timeout_secs), ) .await } +/// Python adds the timeout to `time.time()`: a negative one has already +/// expired, and an infinite or NaN one never does. +fn control_deadline(timeout_secs: f64) -> Duration { + const NEVER: Duration = Duration::from_secs(u32::MAX as u64); + if timeout_secs.is_nan() { + return NEVER; + } + Duration::try_from_secs_f64(timeout_secs.max(0.0)) + .unwrap_or(NEVER) + .min(NEVER) +} + fn encode_control_payload(payload: Vec) -> Vec { // LinkClient accepts an encoded MessagePack value. Raw hash bytes can // themselves form a complete value (e.g. 0xaf followed by 15 bytes), so @@ -869,6 +881,16 @@ fn encode_value(value: &Value) -> Vec { mod tests { use super::*; + #[test] + fn control_deadline_accepts_every_python_float_timeout() { + assert_eq!(control_deadline(-1.0), Duration::ZERO); + assert_eq!(control_deadline(1.5), Duration::from_millis(1500)); + let never = Duration::from_secs(u32::MAX as u64); + for timeout in [f64::INFINITY, f64::NAN, 1e300] { + assert_eq!(control_deadline(timeout), never, "{timeout}"); + } + } + #[test] fn control_payload_preserves_every_peer_hash_prefix_as_binary() { for prefix in 0..=u8::MAX { diff --git a/crates/lxmf-tools/src/lxmd_default_config.txt b/crates/lxmf-tools/src/lxmd_default_config.txt new file mode 100644 index 0000000..8411432 --- /dev/null +++ b/crates/lxmf-tools/src/lxmd_default_config.txt @@ -0,0 +1,233 @@ +# This is an example LXM Daemon config file. +# You should probably edit it to suit your +# intended usage. + +[propagation] + +# Whether to enable propagation node + +enable_node = no + +# You can specify identity hashes for remotes +# that are allowed to control and query status +# for this propagation node. + +# control_allowed = 7d7e542829b40f32364499b27438dba8, 437229f8e29598b2282b88bad5e44698 + +# An optional name for this node, included +# in announces. + +# node_name = Anonymous Propagation Node + +# Automatic announce interval in minutes. +# 6 hours by default. + +announce_interval = 360 + +# Whether to announce when the node starts. + +announce_at_start = yes + +# Wheter to automatically peer with other +# propagation nodes on the network. + +autopeer = yes + +# The maximum peering depth (in hops) for +# automatically peered nodes. + +autopeer_maxdepth = 6 + +# The maximum amount of storage to use for +# the LXMF Propagation Node message store, +# specified in megabytes. When this limit +# is reached, LXMF will periodically remove +# messages in its message store. By default, +# LXMF prioritises keeping messages that are +# new and small. Large and old messages will +# be removed first. This setting is optional +# and defaults to 500 megabytes. + +# message_storage_limit = 500 + +# The maximum accepted transfer size per in- +# coming propagation message, in kilobytes. +# This sets the upper limit for the size of +# single messages accepted onto this node. + +# propagation_message_max_accepted_size = 256 + +# The maximum accepted transfer size per in- +# coming propagation node sync. +# +# If a node wants to propagate a larger number +# of messages to this node, than what can fit +# within this limit, it will prioritise sending +# the smallest messages first, and try again +# with any remaining messages at a later point. + +# propagation_sync_max_accepted_size = 10240 + +# You can configure the target stamp cost +# required to deliver messages via this node. + +# propagation_stamp_cost_target = 16.0 + +# If set higher than 0, the stamp cost flexi- +# bility option will make this node accept +# messages with a lower stamp cost than the +# target from other propagation nodes (but +# not from peers directly). This allows the +# network to gradually adjust stamp cost. + +# propagation_stamp_cost_flexibility = 3.0 + +# If a peer delivers messages with stamp costs +# not conforming to this node's targets, it'll +# be throttled, by default for 5 minutes. You +# can configure the throttle period, and for +# constrained nodes, it may be a good idea to +# set a much higher throttle time. Real LXMF +# propagation nodes will never deliver messages +# with lower stamp values than required by the +# receiving node. + +# propagation_stamp_throttle = 5 + +# The peering_cost option configures the target +# value required for a remote node to peer with +# and deliver messages to this node. + +# peering_cost = 18.0 + +# You can configure the maximum peering cost +# of remote nodes that this node will peer with. +# Setting this to a higher number will allow +# this node to peer with other nodes requiring +# a higher peering key value, but will require +# more computation time during initial peering +# when generating the peering key. + +# remote_peering_cost_max = 26.0 + +# You can tell the LXMF message router to +# prioritise storage for one or more +# destinations. If the message store reaches +# the specified limit, LXMF will prioritise +# keeping messages for destinations specified +# with this option. This setting is optional, +# and generally you do not need to use it. + +# prioritise_destinations = 41d20c727598a3fbbdf9106133a3a0ed, d924b81822ca24e68e2effea99bcb8cf + +# You can configure the maximum number of other +# propagation nodes that this node will peer +# with automatically. The default is 20. + +# max_peers = 20 + +# You can configure a list of static propagation +# node peers, that this node will always be +# peered with, by specifying a list of +# destination hashes. + +# static_peers = e17f833c4ddf8890dd3a79a6fea8161d, 5a2d0029b6e5ec87020abaea0d746da4 + +# You can configure the propagation node to +# only accept incoming propagation messages +# from configured static peers. + +# from_static_only = True + +# By default, stamp validation jobs for PN +# sync batches will run sequentially. If +# a peer offers messages while another batch +# is already processing, it will receive a +# throttle response to indicate that it can +# retry later. If you have a fast system, you +# can disable this to accept and validate +# everything as soon as it is offered. + +# sequential_pn_stamp_validation = yes + +# You can configure whether static peers are +# allowed have their PN syncs processed as +# soon as they are offered, regardless of +# whether another batch is already validating. + +# static_peers_bypass_sequential = yes + +# You can configure how many concurrent inbound +# propagation sync transfers will be accepted. +# Once this number is reached, nodes offering +# messages will receive a throttle response to +# indicate that they can retry later. On a slow +# system, it's a good idea to change this to 1. + +# max_inbound_syncs = 3 + +# By default, any destination is allowed to +# connect and download messages, but you can +# optionally restrict this. If you enable +# authentication, you must provide a list of +# allowed identity hashes in the a file named +# "allowed" in the lxmd config directory. + +auth_required = no + + +[lxmf] + +# The LXM Daemon will create an LXMF destination +# that it can receive messages on. This option sets +# the announced display name for this destination. + +display_name = Anonymous Peer + +# It is possible to announce the internal LXMF +# destination when the LXM Daemon starts up. + +announce_at_start = no + +# You can also announce the delivery destination +# at a specified interval. This is not enabled by +# default. + +# announce_interval = 360 + +# You can configure the required stamp cost for +# incoming messages. + +# stamp_cost = 12 + +# The maximum accepted unpacked size for mes- +# sages received directly from other peers, +# specified in kilobytes. Messages larger than +# this will be rejected before the transfer +# begins. + +delivery_transfer_max_accepted_size = 1 + +# You can configure an external program to be run +# every time a message is received. The program +# will receive as an argument the full path to the +# message saved as a file. The example below will +# simply result in the message getting deleted as +# soon as it has been received. + +# on_inbound = rm + + +[logging] +# Valid log levels are 0 through 7: +# 0: Log only critical information +# 1: Log errors and lower log levels +# 2: Log warnings and lower log levels +# 3: Log notices and lower log levels +# 4: Log info and lower (this is the default) +# 5: Verbose logging +# 6: Debug logging +# 7: Extreme logging + +loglevel = 4 + diff --git a/crates/lxmf-tools/src/lxmd_runtime.rs b/crates/lxmf-tools/src/lxmd_runtime.rs index 534c1e6..0a42a0a 100644 --- a/crates/lxmf-tools/src/lxmd_runtime.rs +++ b/crates/lxmf-tools/src/lxmd_runtime.rs @@ -276,6 +276,16 @@ pub fn preflight_control_command( .to_string(), }); } + // Python `_remote_init` loads the identity before the remote hash is parsed. + if rns_identity::identity::Identity::from_file(&identity_path).is_err() { + return Err(ControlPreflightError { + exit_code: 4, + message: format!( + "Could not load the Primary Identity from {}", + identity_path.display() + ), + }); + } let remote_hash = match remote_hash { Some(raw) => Some(parse_python_control_hash(raw, "remote")?), @@ -553,6 +563,12 @@ mod tests { let identity = temp.join("identity"); std::fs::write(&identity, b"identity").unwrap(); + let unloadable = preflight_control_command(&temp, None, None, Some("zz")).unwrap_err(); + assert_eq!(unloadable.exit_code, 4); + + rns_identity::identity::Identity::new() + .to_file(&identity) + .unwrap(); let invalid_remote = preflight_control_command(&temp, None, None, Some("zz")).unwrap_err(); assert_eq!(invalid_remote.exit_code, 203); assert!( diff --git a/crates/lxmf-tools/tests/lxmd_cli.rs b/crates/lxmf-tools/tests/lxmd_cli.rs index 612a944..8895dfe 100644 --- a/crates/lxmf-tools/tests/lxmd_cli.rs +++ b/crates/lxmf-tools/tests/lxmd_cli.rs @@ -284,7 +284,7 @@ fn clap_requires_send_argument() { } #[test] -fn status_and_peers_fail_before_link_without_an_online_interface() { +fn status_and_peers_time_out_without_a_reachable_node() { let lxmf_dir = TestDir::new("lxmf"); let rns_dir = TestDir::new("rns"); write_rust_identity(&lxmf_dir.path().join("identity")); @@ -303,6 +303,8 @@ discover_interfaces = No ) .expect("write no-interface Reticulum config"); + // Python `if not args.timeout` turns 0 into the 5 s default. + let started = std::time::Instant::now(); let output = Command::new(env!("CARGO_BIN_EXE_lxmd-rs")) .arg("--config") .arg(lxmf_dir.path()) @@ -312,38 +314,28 @@ discover_interfaces = No .arg("--peers") .arg("--timeout") .arg("0") + .arg("-v") .output() .expect("lxmd-rs subprocess should run"); assert_eq!( output.status.code(), Some(200), - "expected interface-readiness failure, got:\n{}", + "expected the control query to time out, got:\n{}", combined_output(&output) ); - assert!( - combined_output(&output) - .contains("No online Reticulum interface became available, exiting now"), - "expected specific interface-readiness error, got:\n{}", - combined_output(&output) + assert_eq!( + stdout(&output), + "Getting lxmd statistics timed out, exiting now\n", + "control commands print only the result on stdout" ); assert!( - lxmf_dir.path().join("identity").is_file(), - "--config should use the configured lxmd identity path" + (4..9).contains(&started.elapsed().as_secs()), + "--timeout 0 must fall back to the default" ); assert!( - !lxmf_dir.path().join("storage").exists(), - "--status/--peers should not start local daemon state" - ); - - let logs = combined_output(&output); - assert!( - logs.contains("Using default configuration"), - "missing LXMF config should fall back to defaults, got logs:\n{logs}" - ); - assert!( - logs.contains("interfaces=0"), - "test config should avoid live Reticulum interfaces, got logs:\n{logs}" + !lxmf_dir.path().join("storage").exists() && !lxmf_dir.path().join("config").exists(), + "--status/--peers must not start local daemon state" ); }