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 text(&self, key: &str, default: &str) -> String {
70 self.values
71 .get(key)
72 .cloned()
73 .unwrap_or_else(|| default.to_string())
74 }
75
76 pub fn int(&self, key: &str, default: i64) -> i64 {
78 match self.values.get(key) {
79 Some(v) => leading_number(v).unwrap_or(0.0) as i64,
80 None => default,
81 }
82 }
83
84 pub fn float(&self, key: &str, default: f64) -> f64 {
86 match self.values.get(key) {
87 Some(v) => leading_number(v).unwrap_or(0.0),
88 None => default,
89 }
90 }
91
92 pub fn flag(&self, key: &str, default: bool) -> bool {
98 match self.values.get(key) {
99 Some(v) => v == "1",
100 None => default,
101 }
102 }
103
104 pub fn set(&self, key: &str, default: &str) -> Vec<String> {
109 let text = self.text(key, default);
110 let t = text.trim();
111 if t.len() <= 2 || !t.starts_with('{') || !t.ends_with('}') {
112 return Vec::new();
113 }
114 t[1..t.len() - 1]
115 .split(',')
116 .map(|s| s.trim().to_string())
117 .filter(|s| !s.is_empty())
118 .collect()
119 }
120}
121
122fn leading_number(text: &str) -> Option<f64> {
124 let t = text.trim();
125 let mut end = 0;
126 for (i, c) in t.char_indices() {
127 let keep = c.is_ascii_digit()
128 || (i == 0 && (c == '-' || c == '+'))
129 || c == '.'
130 || c == 'e'
131 || c == 'E';
132 if !keep {
133 break;
134 }
135 end = i + c.len_utf8();
136 }
137 t[..end].parse().ok()
138}
139
140#[derive(Debug, Clone)]
146pub struct Config {
147 pub multicast_port: u16,
149 pub base_port: u16,
151 pub port_range: u16,
153 pub session_id: String,
155 pub known_peers: Vec<String>,
157 pub multicast_addresses: Vec<String>,
159 pub multicast_ttl: u32,
161 pub watchdog_time_threshold: f64,
163 pub time_update_interval: f64,
165 pub time_update_min_probes: u32,
167 pub time_probe_count: u32,
169 pub time_probe_interval: f64,
171 pub time_probe_max_rtt: f64,
173 pub smoothing_halftime: f32,
175 pub force_default_timestamps: bool,
178 pub continuous_resolve_interval: f64,
181 pub multicast_min_rtt: f64,
183 pub unicast_min_rtt: f64,
185 pub use_protocol_version: i32,
187 pub allow_ipv4: bool,
189 pub allow_ipv6: bool,
191 pub source: String,
193}
194
195impl Default for Config {
196 fn default() -> Config {
197 Config::from_ini(&Ini::default(), "the defaults")
198 }
199}
200
201impl Config {
202 pub fn from_ini(ini: &Ini, source: &str) -> Config {
204 let scope = ini.text("multicast.ResolveScope", "site");
207 let rank = |s: &str| match s {
208 "machine" => 0,
209 "link" => 1,
210 "site" => 2,
211 "organization" => 3,
212 "global" => 4,
213 _ => 2,
215 };
216 let level = rank(&scope);
217 let v6 = ini.text(
220 "multicast.IPv6MulticastGroup",
221 "113D:6FDD:2C17:A643:FFE2:1BD1:3CD2",
222 );
223 let mut addresses = ini.set("multicast.MachineAddresses", "{127.0.0.1}");
224 let mut ttl = 0;
225 if level >= 1 {
226 addresses.extend(ini.set(
227 "multicast.LinkAddresses",
228 "{255.255.255.255, 224.0.0.1, 224.0.0.183}",
229 ));
230 addresses.push(format!("FF02:{v6}"));
231 ttl = 1;
232 }
233 if level >= 2 {
234 addresses.extend(ini.set("multicast.SiteAddresses", "{239.255.172.215}"));
235 addresses.push(format!("FF05:{v6}"));
236 ttl = 24;
237 }
238 if level >= 3 {
239 addresses.extend(ini.set("multicast.OrganizationAddresses", "{}"));
240 addresses.push(format!("FF08:{v6}"));
241 ttl = 32;
242 }
243 if level >= 4 {
244 addresses.extend(ini.set("multicast.GlobalAddresses", "{}"));
245 addresses.push(format!("FF0E:{v6}"));
246 ttl = 255;
247 }
248 let ttl_override = ini.int("multicast.TTLOverride", -1);
249 if ttl_override >= 0 {
250 ttl = ttl_override as u32;
251 }
252 let address_override = ini.set("multicast.AddressesOverride", "{}");
253 if !address_override.is_empty() {
254 addresses = address_override;
255 }
256 let (allow_ipv4, allow_ipv6) = match ini.text("ports.IPv6", "allow").as_str() {
260 "disabled" | "disable" => (true, false),
261 "forced" | "force" => (false, true),
262 _ => (true, true),
263 };
264 addresses.retain(|a| match a.parse::<std::net::IpAddr>() {
265 Ok(std::net::IpAddr::V4(_)) => allow_ipv4,
266 Ok(std::net::IpAddr::V6(_)) => allow_ipv6,
267 Err(_) => false,
268 });
269
270 Config {
271 multicast_port: ini.int("ports.MulticastPort", 16571) as u16,
272 base_port: ini.int("ports.BasePort", 16572) as u16,
273 port_range: ini.int("ports.PortRange", 32) as u16,
274 session_id: ini.text("lab.SessionID", "default"),
275 known_peers: ini.set("lab.KnownPeers", "{}"),
276 multicast_addresses: addresses,
277 multicast_ttl: ttl,
278 watchdog_time_threshold: ini.float("tuning.WatchdogTimeThreshold", 15.0),
279 time_update_interval: ini.float("tuning.TimeUpdateInterval", 2.0),
280 time_update_min_probes: ini.int("tuning.TimeUpdateMinProbes", 6) as u32,
281 time_probe_count: ini.int("tuning.TimeProbeCount", 8) as u32,
282 time_probe_interval: ini.float("tuning.TimeProbeInterval", 0.064),
283 time_probe_max_rtt: ini.float("tuning.TimeProbeMaxRTT", 0.128),
284 smoothing_halftime: ini.float("tuning.SmoothingHalftime", 90.0) as f32,
285 force_default_timestamps: ini.flag("tuning.ForceDefaultTimestamps", false),
286 continuous_resolve_interval: ini.float("tuning.ContinuousResolveInterval", 0.5),
287 multicast_min_rtt: ini.float("tuning.MulticastMinRTT", 0.5),
288 unicast_min_rtt: ini.float("tuning.UnicastMinRTT", 0.75),
289 use_protocol_version: (ini.int("tuning.UseProtocolVersion", 110) as i32).min(110),
290 allow_ipv4,
291 allow_ipv6,
292 source: source.to_string(),
293 }
294 }
295}
296
297static FILENAME: Mutex<Option<String>> = Mutex::new(None);
299static CONTENT: Mutex<Option<String>> = Mutex::new(None);
301static LOADED: OnceLock<Config> = OnceLock::new();
302
303pub fn set_filename(path: &str) {
308 *FILENAME.lock().unwrap() = Some(path.to_string());
309}
310
311pub fn set_content(text: &str) {
316 *CONTENT.lock().unwrap() = Some(text.to_string());
317}
318
319pub fn get() -> &'static Config {
324 LOADED.get_or_init(load)
325}
326
327fn candidates() -> Vec<String> {
329 let mut out: Vec<String> = Vec::new();
330 if let Some(name) = FILENAME.lock().unwrap().clone() {
331 if std::fs::File::open(&name).is_ok() {
332 out.push(name);
333 }
334 }
335 if let Ok(env) = std::env::var("LSLAPICFG") {
337 if std::fs::File::open(&env).is_ok() {
338 out.insert(0, env);
339 }
340 }
341 out.push("lsl_api.cfg".to_string());
342 if let Ok(home) = std::env::var("HOME") {
343 out.push(format!("{home}/lsl_api/lsl_api.cfg"));
344 }
345 out.push("/etc/lsl_api/lsl_api.cfg".to_string());
346 out
347}
348
349fn load() -> Config {
350 if let Some(text) = CONTENT.lock().unwrap().take() {
351 match Ini::parse(&text) {
352 Ok(ini) => return Config::from_ini(&ini, "the text that the application gave"),
353 Err(_) => return Config::default(),
355 }
356 }
357 for name in candidates() {
358 if let Ok(text) = std::fs::read_to_string(&name) {
359 return match Ini::parse(&text) {
360 Ok(ini) => Config::from_ini(&ini, &name),
361 Err(_) => Config::default(),
362 };
363 }
364 }
365 Config::default()
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 #[test]
373 fn a_section_becomes_part_of_the_key() {
374 let ini = Ini::parse("[ports]\nBasePort = 17000\n").expect("a file");
375 assert_eq!(ini.int("ports.BasePort", 16572), 17000);
376 assert_eq!(ini.int("BasePort", 16572), 16572);
377 }
378
379 #[test]
380 fn only_a_semicolon_starts_a_comment() {
381 assert!(Ini::parse("; a note\n[lab]\nSessionID = x\n").is_ok());
384 assert!(Ini::parse("# a note\n[lab]\nSessionID = x\n").is_err());
385 }
386
387 #[test]
388 fn only_the_digit_one_means_yes() {
389 let ini = Ini::parse("[tuning]\nA = 1\nB = true\nC = 0\n").expect("a file");
391 assert!(ini.flag("tuning.A", false));
392 assert!(!ini.flag("tuning.B", false));
393 assert!(!ini.flag("tuning.C", true));
394 assert!(ini.flag("tuning.Missing", true));
395 }
396
397 #[test]
398 fn a_repeated_key_throws_the_file_away() {
399 assert!(Ini::parse("[lab]\nSessionID = a\nSessionID = b\n").is_err());
400 }
401
402 #[test]
403 fn a_line_with_no_equals_sign_throws_the_file_away() {
404 assert!(Ini::parse("[lab]\nSessionID\n").is_err());
405 }
406
407 #[test]
408 fn a_set_needs_both_braces() {
409 let ini = Ini::parse("[lab]\nA = {x, y}\nB = x, y\nC = {}\n").expect("a file");
410 assert_eq!(ini.set("lab.A", "{}"), vec!["x", "y"]);
411 assert!(ini.set("lab.B", "{}").is_empty());
412 assert!(ini.set("lab.C", "{}").is_empty());
413 }
414
415 #[test]
416 fn the_space_around_a_key_and_a_value_is_dropped() {
417 let ini = Ini::parse("[lab]\n SessionID = my lab \n").expect("a file");
418 assert_eq!(ini.text("lab.SessionID", ""), "my lab");
419 }
420
421 #[test]
422 fn the_defaults_match_the_values_in_the_source() {
423 let c = Config::default();
424 assert_eq!(c.multicast_port, 16571);
425 assert_eq!(c.base_port, 16572);
426 assert_eq!(c.port_range, 32);
427 assert_eq!(c.session_id, "default");
428 assert_eq!(c.watchdog_time_threshold, 15.0);
429 assert_eq!(c.time_update_interval, 2.0);
430 assert_eq!(c.time_update_min_probes, 6);
431 assert_eq!(c.time_probe_count, 8);
432 assert_eq!(c.time_probe_interval, 0.064);
433 assert_eq!(c.time_probe_max_rtt, 0.128);
434 assert_eq!(c.smoothing_halftime, 90.0);
435 assert!(!c.force_default_timestamps);
436 assert_eq!(c.use_protocol_version, 110);
437 }
438
439 #[test]
440 fn the_scope_decides_the_groups_and_the_hop_count() {
441 let of = |scope: &str| {
442 let ini =
443 Ini::parse(&format!("[multicast]\nResolveScope = {scope}\n")).expect("a file");
444 Config::from_ini(&ini, "test")
445 };
446 let machine = of("machine");
447 assert_eq!(machine.multicast_addresses, vec!["127.0.0.1"]);
448 assert_eq!(machine.multicast_ttl, 0);
449
450 let link = of("link");
451 assert!(link
452 .multicast_addresses
453 .contains(&"224.0.0.183".to_string()));
454 assert!(!link
455 .multicast_addresses
456 .contains(&"239.255.172.215".to_string()));
457 assert_eq!(link.multicast_ttl, 1);
458
459 let site = of("site");
460 assert!(site
461 .multicast_addresses
462 .contains(&"239.255.172.215".to_string()));
463 assert_eq!(site.multicast_ttl, 24);
464 }
465
466 #[test]
467 fn an_address_override_replaces_the_whole_list() {
468 let ini =
469 Ini::parse("[multicast]\nAddressesOverride = {10.0.0.1, 10.0.0.2}\n").expect("a file");
470 let c = Config::from_ini(&ini, "test");
471 assert_eq!(c.multicast_addresses, vec!["10.0.0.1", "10.0.0.2"]);
472 }
473
474 #[test]
475 fn a_hop_count_override_wins() {
476 let ini = Ini::parse("[multicast]\nTTLOverride = 7\n").expect("a file");
477 assert_eq!(Config::from_ini(&ini, "test").multicast_ttl, 7);
478 }
479
480 #[test]
481 fn the_protocol_version_never_rises_above_the_one_this_library_speaks() {
482 let ini = Ini::parse("[tuning]\nUseProtocolVersion = 200\n").expect("a file");
483 assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 110);
484 let ini = Ini::parse("[tuning]\nUseProtocolVersion = 100\n").expect("a file");
485 assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 100);
486 }
487}