1use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14
15#[derive(Debug, Default, Clone)]
26pub struct Ini {
27 values: HashMap<String, String>,
28}
29
30impl Ini {
31 pub fn parse(text: &str) -> Result<Ini, String> {
33 let mut values: HashMap<String, String> = HashMap::new();
34 let mut section = String::new();
35 for (k, raw) in text.lines().enumerate() {
36 let line = raw.trim_end_matches('\r');
37 let number = k + 1;
38 if line.starts_with(';') || line.trim().is_empty() {
39 continue;
40 }
41 if line.starts_with('[') {
42 let close = line
43 .find(']')
44 .ok_or_else(|| format!("No closing bracket ] found in line {number}"))?;
45 section = format!("{}.", &line[1..close]);
46 continue;
47 }
48 let eq = line
49 .find('=')
50 .ok_or_else(|| format!("No Key-Value pair in line {number}"))?;
51 let key = line[..eq].trim();
52 let value = line[eq + 1..].trim();
53 if key.is_empty() {
54 return Err(format!("Empty key in line {number}"));
55 }
56 if value.is_empty() {
57 return Err(format!("Empty value in line {number}"));
58 }
59 let full = format!("{section}{key}");
60 if values.contains_key(&full) {
61 return Err(format!("Duplicate key {full}"));
62 }
63 values.insert(full, value.to_string());
64 }
65 Ok(Ini { values })
66 }
67
68 pub fn contains_key(&self, key: &str) -> bool {
70 self.values.contains_key(key)
71 }
72
73 pub fn text(&self, key: &str, default: &str) -> String {
75 self.values
76 .get(key)
77 .cloned()
78 .unwrap_or_else(|| default.to_string())
79 }
80
81 pub fn int(&self, key: &str, default: i64) -> i64 {
83 match self.values.get(key) {
84 Some(v) => leading_number(v).unwrap_or(0.0) as i64,
85 None => default,
86 }
87 }
88
89 pub fn float(&self, key: &str, default: f64) -> f64 {
91 match self.values.get(key) {
92 Some(v) => leading_number(v).unwrap_or(0.0),
93 None => default,
94 }
95 }
96
97 pub fn flag(&self, key: &str, default: bool) -> bool {
103 match self.values.get(key) {
104 Some(v) => v == "1",
105 None => default,
106 }
107 }
108
109 pub fn set(&self, key: &str, default: &str) -> Vec<String> {
114 let text = self.text(key, default);
115 let t = text.trim();
116 if t.len() <= 2 || !t.starts_with('{') || !t.ends_with('}') {
117 return Vec::new();
118 }
119 t[1..t.len() - 1]
120 .split(',')
121 .map(|s| s.trim().to_string())
122 .filter(|s| !s.is_empty())
123 .collect()
124 }
125}
126
127fn leading_number(text: &str) -> Option<f64> {
129 let t = text.trim();
130 let mut end = 0;
131 for (i, c) in t.char_indices() {
132 let keep = c.is_ascii_digit()
133 || (i == 0 && (c == '-' || c == '+'))
134 || c == '.'
135 || c == 'e'
136 || c == 'E';
137 if !keep {
138 break;
139 }
140 end = i + c.len_utf8();
141 }
142 t[..end].parse().ok()
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum FallbackDiscovery {
149 Auto,
151 Off,
153 Subnet,
155}
156
157impl FallbackDiscovery {
158 pub fn as_str(self) -> &'static str {
160 match self {
161 FallbackDiscovery::Auto => "auto",
162 FallbackDiscovery::Off => "off",
163 FallbackDiscovery::Subnet => "subnet",
164 }
165 }
166
167 fn parse(text: &str) -> FallbackDiscovery {
168 match text.trim().to_ascii_lowercase().as_str() {
169 "off" | "0" | "false" | "none" => FallbackDiscovery::Off,
170 "subnet" | "always" | "on" => FallbackDiscovery::Subnet,
171 _ => FallbackDiscovery::Auto,
172 }
173 }
174}
175
176#[derive(Debug, Clone)]
182pub struct Config {
183 pub multicast_port: u16,
185 pub base_port: u16,
187 pub port_range: u16,
189 pub session_id: String,
191 pub known_peers: Vec<String>,
193 pub multicast_addresses: Vec<String>,
195 pub multicast_ttl: u32,
197 pub watchdog_time_threshold: f64,
199 pub time_update_interval: f64,
201 pub time_update_min_probes: u32,
203 pub time_probe_count: u32,
205 pub time_probe_interval: f64,
207 pub time_probe_max_rtt: f64,
209 pub smoothing_halftime: f32,
211 pub force_default_timestamps: bool,
214 pub continuous_resolve_interval: f64,
217 pub multicast_min_rtt: f64,
219 pub unicast_min_rtt: f64,
221 pub use_protocol_version: i32,
223 pub allow_ipv4: bool,
225 pub allow_ipv6: bool,
227 pub features: Vec<String>,
231 pub resume_seconds: f64,
236 pub resume_memory_mib: f64,
239 pub resume_disk_mib: f64,
243 pub resume_disk_path: Option<String>,
246 pub fallback_discovery: FallbackDiscovery,
249 pub require_encryption: bool,
252 pub encryption_key: Option<String>,
255 pub source: String,
257}
258
259impl Default for Config {
260 fn default() -> Config {
261 Config::from_ini(&Ini::default(), "the defaults")
262 }
263}
264
265impl Config {
266 pub fn history_limits(&self) -> crate::history::HistoryLimits {
270 let bytes = self.resume_memory_mib * (1u64 << 20) as f64;
271 let disk_bytes = self.resume_disk_mib * (1u64 << 20) as f64;
272 crate::history::HistoryLimits {
273 seconds: self.resume_seconds,
274 bytes: if bytes >= usize::MAX as f64 {
275 usize::MAX
276 } else {
277 bytes as usize
278 },
279 disk_bytes: if disk_bytes >= u64::MAX as f64 {
280 u64::MAX
281 } else {
282 disk_bytes as u64
283 },
284 disk_dir: self.resume_disk_path.as_ref().map(std::path::PathBuf::from),
285 }
286 }
287
288 pub fn from_ini(ini: &Ini, source: &str) -> Config {
290 let scope = ini.text("multicast.ResolveScope", "site");
293 let rank = |s: &str| match s {
294 "machine" => 0,
295 "link" => 1,
296 "site" => 2,
297 "organization" => 3,
298 "global" => 4,
299 _ => 2,
301 };
302 let level = rank(&scope);
303 let v6 = ini.text(
306 "multicast.IPv6MulticastGroup",
307 "113D:6FDD:2C17:A643:FFE2:1BD1:3CD2",
308 );
309 let mut addresses = ini.set("multicast.MachineAddresses", "{127.0.0.1}");
310 let mut ttl = 0;
311 if level >= 1 {
312 addresses.extend(ini.set(
313 "multicast.LinkAddresses",
314 "{255.255.255.255, 224.0.0.1, 224.0.0.183}",
315 ));
316 addresses.push(format!("FF02:{v6}"));
317 ttl = 1;
318 }
319 if level >= 2 {
320 addresses.extend(ini.set("multicast.SiteAddresses", "{239.255.172.215}"));
321 addresses.push(format!("FF05:{v6}"));
322 ttl = 24;
323 }
324 if level >= 3 {
325 addresses.extend(ini.set("multicast.OrganizationAddresses", "{}"));
326 addresses.push(format!("FF08:{v6}"));
327 ttl = 32;
328 }
329 if level >= 4 {
330 addresses.extend(ini.set("multicast.GlobalAddresses", "{}"));
331 addresses.push(format!("FF0E:{v6}"));
332 ttl = 255;
333 }
334 let ttl_override = ini.int("multicast.TTLOverride", -1);
335 if ttl_override >= 0 {
336 ttl = ttl_override as u32;
337 }
338 let address_override = ini.set("multicast.AddressesOverride", "{}");
339 if !address_override.is_empty() {
340 addresses = address_override;
341 }
342 let (allow_ipv4, allow_ipv6) = match ini.text("ports.IPv6", "allow").as_str() {
346 "disabled" | "disable" => (true, false),
347 "forced" | "force" => (false, true),
348 _ => (true, true),
349 };
350 addresses.retain(|a| match a.parse::<std::net::IpAddr>() {
351 Ok(std::net::IpAddr::V4(_)) => allow_ipv4,
352 Ok(std::net::IpAddr::V6(_)) => allow_ipv6,
353 Err(_) => false,
354 });
355
356 let resume_disk_mib = ini.float("labstream.ResumeDisk", 0.0).max(0.0);
357 let resume_disk_path_raw = ini.text("labstream.ResumeDiskPath", "");
358 let resume_disk_path = if resume_disk_path_raw.is_empty() {
359 None
360 } else {
361 Some(resume_disk_path_raw)
362 };
363 let resume_seconds =
367 if resume_disk_mib > 0.0 && !ini.contains_key("labstream.ResumeSeconds") {
368 f64::INFINITY
369 } else {
370 ini.float("labstream.ResumeSeconds", 30.0).max(0.0)
371 };
372
373 let encryption_key_raw = ini.text("labstream.EncryptionKey", "");
374 let encryption_key = if encryption_key_raw.is_empty() {
375 None
376 } else {
377 Some(encryption_key_raw)
378 };
379 let require_encryption = ini.flag("labstream.RequireEncryption", false);
380
381 Config {
382 multicast_port: ini.int("ports.MulticastPort", 16571) as u16,
383 base_port: ini.int("ports.BasePort", 16572) as u16,
384 port_range: ini.int("ports.PortRange", 32) as u16,
385 session_id: ini.text("lab.SessionID", "default"),
386 known_peers: ini.set("lab.KnownPeers", "{}"),
387 features: ini.set(
388 "labstream.Features",
389 "{seq, resume, dgram, select, shm, comp, meta}",
390 ),
391 resume_seconds,
392 resume_memory_mib: ini.float("labstream.ResumeMemory", 64.0).max(0.0),
393 resume_disk_mib,
394 resume_disk_path,
395 fallback_discovery: FallbackDiscovery::parse(
396 &ini.text("labstream.FallbackDiscovery", "auto"),
397 ),
398 require_encryption,
399 encryption_key,
400 multicast_addresses: addresses,
401 multicast_ttl: ttl,
402 watchdog_time_threshold: ini.float("tuning.WatchdogTimeThreshold", 15.0),
403 time_update_interval: ini.float("tuning.TimeUpdateInterval", 2.0),
404 time_update_min_probes: ini.int("tuning.TimeUpdateMinProbes", 6) as u32,
405 time_probe_count: ini.int("tuning.TimeProbeCount", 8) as u32,
406 time_probe_interval: ini.float("tuning.TimeProbeInterval", 0.064),
407 time_probe_max_rtt: ini.float("tuning.TimeProbeMaxRTT", 0.128),
408 smoothing_halftime: ini.float("tuning.SmoothingHalftime", 90.0) as f32,
409 force_default_timestamps: ini.flag("tuning.ForceDefaultTimestamps", false),
410 continuous_resolve_interval: ini.float("tuning.ContinuousResolveInterval", 0.5),
411 multicast_min_rtt: ini.float("tuning.MulticastMinRTT", 0.5),
412 unicast_min_rtt: ini.float("tuning.UnicastMinRTT", 0.75),
413 use_protocol_version: (ini.int("tuning.UseProtocolVersion", 110) as i32).min(110),
414 allow_ipv4,
415 allow_ipv6,
416 source: source.to_string(),
417 }
418 }
419}
420
421static FILENAME: Mutex<Option<String>> = Mutex::new(None);
423static CONTENT: Mutex<Option<String>> = Mutex::new(None);
425static LOADED: OnceLock<Config> = OnceLock::new();
426
427pub fn set_filename(path: &str) {
432 *FILENAME.lock().unwrap() = Some(path.to_string());
433}
434
435pub fn set_content(text: &str) {
440 *CONTENT.lock().unwrap() = Some(text.to_string());
441}
442
443pub fn get() -> &'static Config {
448 LOADED.get_or_init(load)
449}
450
451fn candidates() -> Vec<String> {
453 let mut out: Vec<String> = Vec::new();
454 if let Some(name) = FILENAME.lock().unwrap().clone() {
455 if std::fs::File::open(&name).is_ok() {
456 out.push(name);
457 }
458 }
459 if let Ok(env) = std::env::var("LSLAPICFG") {
461 if std::fs::File::open(&env).is_ok() {
462 out.insert(0, env);
463 }
464 }
465 out.push("lsl_api.cfg".to_string());
466 if let Ok(home) = std::env::var("HOME") {
467 out.push(format!("{home}/lsl_api/lsl_api.cfg"));
468 }
469 out.push("/etc/lsl_api/lsl_api.cfg".to_string());
470 out
471}
472
473fn load() -> Config {
474 if let Some(text) = CONTENT.lock().unwrap().take() {
475 match Ini::parse(&text) {
476 Ok(ini) => return Config::from_ini(&ini, "the text that the application gave"),
477 Err(_) => return Config::default(),
479 }
480 }
481 for name in candidates() {
482 if let Ok(text) = std::fs::read_to_string(&name) {
483 return match Ini::parse(&text) {
484 Ok(ini) => Config::from_ini(&ini, &name),
485 Err(_) => Config::default(),
486 };
487 }
488 }
489 Config::default()
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495
496 #[test]
497 fn a_section_becomes_part_of_the_key() {
498 let ini = Ini::parse("[ports]\nBasePort = 17000\n").expect("a file");
499 assert_eq!(ini.int("ports.BasePort", 16572), 17000);
500 assert_eq!(ini.int("BasePort", 16572), 16572);
501 }
502
503 #[test]
504 fn only_a_semicolon_starts_a_comment() {
505 assert!(Ini::parse("; a note\n[lab]\nSessionID = x\n").is_ok());
508 assert!(Ini::parse("# a note\n[lab]\nSessionID = x\n").is_err());
509 }
510
511 #[test]
512 fn only_the_digit_one_means_yes() {
513 let ini = Ini::parse("[tuning]\nA = 1\nB = true\nC = 0\n").expect("a file");
515 assert!(ini.flag("tuning.A", false));
516 assert!(!ini.flag("tuning.B", false));
517 assert!(!ini.flag("tuning.C", true));
518 assert!(ini.flag("tuning.Missing", true));
519 }
520
521 #[test]
522 fn a_repeated_key_throws_the_file_away() {
523 assert!(Ini::parse("[lab]\nSessionID = a\nSessionID = b\n").is_err());
524 }
525
526 #[test]
527 fn a_line_with_no_equals_sign_throws_the_file_away() {
528 assert!(Ini::parse("[lab]\nSessionID\n").is_err());
529 }
530
531 #[test]
532 fn a_set_needs_both_braces() {
533 let ini = Ini::parse("[lab]\nA = {x, y}\nB = x, y\nC = {}\n").expect("a file");
534 assert_eq!(ini.set("lab.A", "{}"), vec!["x", "y"]);
535 assert!(ini.set("lab.B", "{}").is_empty());
536 assert!(ini.set("lab.C", "{}").is_empty());
537 }
538
539 #[test]
540 fn the_space_around_a_key_and_a_value_is_dropped() {
541 let ini = Ini::parse("[lab]\n SessionID = my lab \n").expect("a file");
542 assert_eq!(ini.text("lab.SessionID", ""), "my lab");
543 }
544
545 #[test]
546 fn the_defaults_match_the_values_in_the_source() {
547 let c = Config::default();
548 assert_eq!(c.multicast_port, 16571);
549 assert_eq!(c.base_port, 16572);
550 assert_eq!(c.port_range, 32);
551 assert_eq!(c.session_id, "default");
552 assert_eq!(c.watchdog_time_threshold, 15.0);
553 assert_eq!(c.time_update_interval, 2.0);
554 assert_eq!(c.time_update_min_probes, 6);
555 assert_eq!(c.time_probe_count, 8);
556 assert_eq!(c.time_probe_interval, 0.064);
557 assert_eq!(c.time_probe_max_rtt, 0.128);
558 assert_eq!(c.smoothing_halftime, 90.0);
559 assert!(!c.force_default_timestamps);
560 assert_eq!(c.use_protocol_version, 110);
561 }
562
563 #[test]
564 fn the_resume_limits_have_defaults_and_a_file_sets_them() {
565 let c = Config::from_ini(&Ini::default(), "test");
566 assert_eq!(c.history_limits(), crate::history::HistoryLimits::DEFAULT);
567 let set =
568 Ini::parse("[labstream]\nResumeSeconds = 2.5\nResumeMemory = 1\n").expect("a file");
569 let limits = Config::from_ini(&set, "test").history_limits();
570 assert_eq!(limits.seconds, 2.5);
571 assert_eq!(limits.bytes, 1 << 20);
572 let off = Ini::parse("[labstream]\nResumeSeconds = 0\n").expect("a file");
573 assert!(!Config::from_ini(&off, "test")
574 .history_limits()
575 .allow_history());
576 let negative = Ini::parse("[labstream]\nResumeMemory = -5\n").expect("a file");
577 assert!(!Config::from_ini(&negative, "test")
578 .history_limits()
579 .allow_history());
580 let disk = Ini::parse("[labstream]\nResumeDisk = 512\nResumeDiskPath = /tmp/spool\n")
581 .expect("a file");
582 let dlimits = Config::from_ini(&disk, "test").history_limits();
583 assert_eq!(dlimits.disk_bytes, 512 << 20);
584 assert_eq!(
585 dlimits.disk_dir.as_deref(),
586 Some(std::path::Path::new("/tmp/spool"))
587 );
588 assert!(dlimits.seconds.is_infinite());
589 }
590
591 #[test]
592 fn the_labstream_features_are_on_by_default_and_a_file_turns_them_off() {
593 let c = Config::from_ini(&Ini::default(), "test");
594 assert_eq!(
595 c.features,
596 vec![
597 "seq".to_string(),
598 "resume".to_string(),
599 "dgram".to_string(),
600 "select".to_string(),
601 "shm".to_string(),
602 "comp".to_string(),
603 "meta".to_string()
604 ]
605 );
606 let off = Ini::parse("[labstream]\nFeatures = {}\n").expect("a file");
607 assert!(Config::from_ini(&off, "test").features.is_empty());
608 }
609
610 #[test]
611 fn the_scope_decides_the_groups_and_the_hop_count() {
612 let of = |scope: &str| {
613 let ini =
614 Ini::parse(&format!("[multicast]\nResolveScope = {scope}\n")).expect("a file");
615 Config::from_ini(&ini, "test")
616 };
617 let machine = of("machine");
618 assert_eq!(machine.multicast_addresses, vec!["127.0.0.1"]);
619 assert_eq!(machine.multicast_ttl, 0);
620
621 let link = of("link");
622 assert!(link
623 .multicast_addresses
624 .contains(&"224.0.0.183".to_string()));
625 assert!(!link
626 .multicast_addresses
627 .contains(&"239.255.172.215".to_string()));
628 assert_eq!(link.multicast_ttl, 1);
629
630 let site = of("site");
631 assert!(site
632 .multicast_addresses
633 .contains(&"239.255.172.215".to_string()));
634 assert_eq!(site.multicast_ttl, 24);
635 }
636
637 #[test]
638 fn an_address_override_replaces_the_whole_list() {
639 let ini =
640 Ini::parse("[multicast]\nAddressesOverride = {10.0.0.1, 10.0.0.2}\n").expect("a file");
641 let c = Config::from_ini(&ini, "test");
642 assert_eq!(c.multicast_addresses, vec!["10.0.0.1", "10.0.0.2"]);
643 }
644
645 #[test]
646 fn a_hop_count_override_wins() {
647 let ini = Ini::parse("[multicast]\nTTLOverride = 7\n").expect("a file");
648 assert_eq!(Config::from_ini(&ini, "test").multicast_ttl, 7);
649 }
650
651 #[test]
652 fn the_protocol_version_never_rises_above_the_one_this_library_speaks() {
653 let ini = Ini::parse("[tuning]\nUseProtocolVersion = 200\n").expect("a file");
654 assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 110);
655 let ini = Ini::parse("[tuning]\nUseProtocolVersion = 100\n").expect("a file");
656 assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 100);
657 }
658
659 #[test]
660 fn fallback_discovery_defaults_to_auto_and_parses_modes() {
661 let def = Config::default();
662 assert_eq!(def.fallback_discovery, FallbackDiscovery::Auto);
663 let off = Ini::parse("[labstream]\nFallbackDiscovery = off\n").expect("a file");
664 assert_eq!(
665 Config::from_ini(&off, "test").fallback_discovery,
666 FallbackDiscovery::Off
667 );
668 let sub = Ini::parse("[labstream]\nFallbackDiscovery = subnet\n").expect("a file");
669 assert_eq!(
670 Config::from_ini(&sub, "test").fallback_discovery,
671 FallbackDiscovery::Subnet
672 );
673 }
674}