Skip to main content

labstream_net/
config.rs

1//! The configuration file.
2//!
3//! liblsl reads one file at the first call that needs it, keeps the result for
4//! the life of the process, and never reads another
5//! (`src/api_config.cpp:326-337`). Every port, every multicast group, and
6//! every tuning value below comes from that file or from a default.
7//!
8//! A site that changes `lsl_api.cfg` changes the wire. Two libraries that read
9//! the file differently cannot see each other, and no test of the protocol
10//! finds that, because both sides are correct on their own defaults.
11
12use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14
15/// A file in the format that liblsl reads.
16///
17/// The rules come from `src/util/inireader.cpp`:
18///
19/// * A line that starts with `;` is a comment. **A `#` is not.**
20/// * A blank line is skipped.
21/// * `[section]` opens a section. The key is then `section.Key`.
22/// * A line with no `=` is an error, and one error throws the whole file away.
23/// * A repeated key is an error.
24/// * The key and the value lose the space around them.
25#[derive(Debug, Default, Clone)]
26pub struct Ini {
27    values: HashMap<String, String>,
28}
29
30impl Ini {
31    /// Read a file. An error names the line.
32    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    /// The text of a key, or a default.
69    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    /// A whole number, read the way `std::istream` reads one.
77    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    /// A number with a fraction.
85    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    /// A yes or no value.
93    ///
94    /// **Only the text `1` means yes.** `src/util/inireader.hpp` reads a
95    /// boolean with `from_string<bool>`, and `src/util/cast.hpp:10` defines
96    /// that as `str == "1"`. A file that says `true` therefore means no.
97    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    /// A set of the form `{a, b, c}`.
105    ///
106    /// Anything that does not start with `{` and end with `}` is an empty set
107    /// (`src/api_config.cpp:40-46`).
108    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
122/// Read the longest leading run that looks like a number.
123fn 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/// Every value that changes what travels on the wire.
141///
142/// The names follow `src/api_config.cpp:168-322`. A value that this
143/// implementation does not act on yet is left out rather than read and
144/// ignored.
145#[derive(Debug, Clone)]
146pub struct Config {
147    /// The port for a multicast or broadcast query. `ports.MulticastPort`.
148    pub multicast_port: u16,
149    /// The first port of the unicast range. `ports.BasePort`.
150    pub base_port: u16,
151    /// How many ports the range holds. `ports.PortRange`.
152    pub port_range: u16,
153    /// The session that a stream belongs to. `lab.SessionID`.
154    pub session_id: String,
155    /// Addresses that a resolver always sends to. `lab.KnownPeers`.
156    pub known_peers: Vec<String>,
157    /// The groups that a query goes to, for the chosen scope.
158    pub multicast_addresses: Vec<String>,
159    /// The hop count for a multicast query.
160    pub multicast_ttl: u32,
161    /// How long a quiet source stays connected. `tuning.WatchdogTimeThreshold`.
162    pub watchdog_time_threshold: f64,
163    /// How often the clock is measured. `tuning.TimeUpdateInterval`.
164    pub time_update_interval: f64,
165    /// How many probes an estimate needs. `tuning.TimeUpdateMinProbes`.
166    pub time_update_min_probes: u32,
167    /// How many probes one burst sends. `tuning.TimeProbeCount`.
168    pub time_probe_count: u32,
169    /// The gap between two probes. `tuning.TimeProbeInterval`.
170    pub time_probe_interval: f64,
171    /// How long a burst waits for answers. `tuning.TimeProbeMaxRTT`.
172    pub time_probe_max_rtt: f64,
173    /// The half-time of the smoothing filter. `tuning.SmoothingHalftime`.
174    pub smoothing_halftime: f32,
175    /// When true, every pushed timestamp is replaced by the current clock.
176    /// `tuning.ForceDefaultTimestamps`.
177    pub force_default_timestamps: bool,
178    /// The gap between two waves of a background resolver.
179    /// `tuning.ContinuousResolveInterval`.
180    pub continuous_resolve_interval: f64,
181    /// The shortest time a multicast wave waits. `tuning.MulticastMinRTT`.
182    pub multicast_min_rtt: f64,
183    /// The shortest time a unicast wave waits. `tuning.UnicastMinRTT`.
184    pub unicast_min_rtt: f64,
185    /// The protocol version that an outlet writes. `tuning.UseProtocolVersion`.
186    pub use_protocol_version: i32,
187    /// True when an outlet binds an IPv4 stack. `ports.IPv6`.
188    pub allow_ipv4: bool,
189    /// True when an outlet binds an IPv6 stack. `ports.IPv6`.
190    pub allow_ipv6: bool,
191    /// Where the values came from, for a report.
192    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    /// Read a configuration out of a file that was already parsed.
203    pub fn from_ini(ini: &Ini, source: &str) -> Config {
204        // The scope decides which groups a query reaches, and the hop count.
205        // `src/api_config.cpp:211-247`.
206        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            // liblsl throws here, which throws the whole file away.
214            _ => 2,
215        };
216        let level = rank(&scope);
217        // Each scope adds an IPv6 group as well, built from one suffix and the
218        // prefix of that scope (`src/api_config.cpp:191-247`).
219        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        // `ports.IPv6` names which stacks an outlet binds
257        // (`src/api_config.cpp:172-185`). A word outside the list makes liblsl
258        // throw, which throws the whole file away, so the defaults apply.
259        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
297/// A file name that an application set before the first use.
298static FILENAME: Mutex<Option<String>> = Mutex::new(None);
299/// Text that an application set before the first use.
300static CONTENT: Mutex<Option<String>> = Mutex::new(None);
301static LOADED: OnceLock<Config> = OnceLock::new();
302
303/// Name the file to read. Call this before anything else.
304///
305/// `lsl_set_config_filename`. A call after the configuration is read has no
306/// effect, on either implementation.
307pub fn set_filename(path: &str) {
308    *FILENAME.lock().unwrap() = Some(path.to_string());
309}
310
311/// Give the configuration as text. Call this before anything else.
312///
313/// `lsl_set_config_content`. liblsl uses the text once and then drops it
314/// (`src/api_config.cpp:57-70`).
315pub fn set_content(text: &str) {
316    *CONTENT.lock().unwrap() = Some(text.to_string());
317}
318
319/// The configuration of this process.
320///
321/// The file is read once. Every later call returns the same values, which is
322/// what liblsl does with `std::call_once` (`src/api_config.cpp:326`).
323pub fn get() -> &'static Config {
324    LOADED.get_or_init(load)
325}
326
327/// Where liblsl looks, in order. `src/api_config.cpp:70-110`.
328fn 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    // The environment takes precedence over the name that an application set.
336    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            // A file that does not parse leaves the defaults in place.
354            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        // `src/util/inireader.cpp:13` tests for `;` and nothing else. A `#`
382        // makes the line a key with no `=`, which throws the file away.
383        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        // `src/util/cast.hpp:10` defines this as `str == "1"`.
390        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}