Skip to main content

labstream_net/
lib.rs

1//! Sockets, timers, and interfaces for LSL.
2//!
3//! This is the only crate in the workspace that touches the operating system.
4//! Every protocol rule lives in `labstream-proto` and `labstream-wire`, which hold no input
5//! and no output.
6//!
7//! The split matters for testing. A protocol rule gets a unit test with a byte
8//! slice. Only this crate needs a network, and only its tests are allowed to be
9//! slow.
10
11// One function in this crate needs a system call that the standard library
12// does not expose. `clock()` must return the same value as `lsl_local_clock()`
13// on the same machine, and that is `CLOCK_MONOTONIC`. See the note there.
14#![deny(unsafe_code)]
15#![deny(missing_docs)]
16
17pub mod clock;
18pub mod config;
19pub mod desc;
20pub mod info;
21pub mod inlet;
22pub mod outlet;
23pub mod queue;
24pub mod resolver;
25pub mod xpath;
26
27pub use clock::{ClockState, LiveSource};
28pub use config::Config;
29pub use desc::Node;
30pub use info::StreamInfo;
31pub use inlet::{build_property_query, read_fullinfo, resolve, Inlet};
32pub use outlet::Outlet;
33pub use queue::{Fanout, SampleQueue};
34pub use resolver::ContinuousResolver;
35
36/// The session that a stream belongs to, when no file names another.
37///
38/// `src/api_config.cpp:297` reads `lab.SessionID` and falls back to this word.
39/// A resolver query always tests this field, so two machines with different
40/// values never see each other. Read the live value from
41/// [`config::get`], which honours the file.
42pub const SESSION_ID: &str = "default";
43
44/// The default base port. `src/api_config.cpp:170`.
45pub const BASE_PORT: u16 = 16572;
46/// The default port range. `src/api_config.cpp:171`.
47pub const PORT_RANGE: u16 = 32;
48
49/// The port that carries a multicast or broadcast query.
50///
51/// `src/api_config.cpp:169`. This port sits **outside** the unicast range that
52/// starts at `BASE_PORT`. A resolver sends a multicast query here and a unicast
53/// query to the range, so an outlet that listens only on the range never
54/// answers a multicast query.
55pub const MULTICAST_PORT: u16 = 16571;
56
57/// The clock that LSL timestamps use.
58///
59/// liblsl returns `steady_clock::now().time_since_epoch()` in seconds
60/// (`src/common.cpp:20`). On Linux that is `CLOCK_MONOTONIC`, whose origin is
61/// the moment the machine booted.
62///
63/// # Why this is not `Instant`
64///
65/// The origin has to match. Two liblsl processes on one machine read the same
66/// clock, and an application can push a timestamp from `lsl_local_clock()`
67/// that a consumer on the same machine reads directly. No post-processing runs
68/// by default (`include/lsl/common.h:103`), so nothing corrects a difference.
69///
70/// A first version of this function measured from the start of the process.
71/// Every value was then wrong by the age of the machine. A live test against a
72/// real liblsl outlet measured the error at 31,426 seconds.
73///
74/// `std::time::Instant` uses this same clock and keeps its value private, and
75/// `/proc/uptime` counts a different one: it includes time spent suspended, so
76/// it read 66,567 on a machine where `CLOCK_MONOTONIC` read 31,492. The system
77/// call is the only source that agrees.
78///
79/// Each platform reads its own clock. `machine_clock` gives the note for the
80/// platform.
81pub fn clock() -> f64 {
82    if let Some(seconds) = machine_clock() {
83        return seconds;
84    }
85    // A platform with no clock above falls back to the process clock.
86    // Timestamps then carry the wrong origin, and only a peer that applies the
87    // clock correction reads them correctly.
88    use std::sync::OnceLock;
89    use std::time::Instant;
90    static START: OnceLock<Instant> = OnceLock::new();
91    START.get_or_init(Instant::now).elapsed().as_secs_f64()
92}
93
94/// The clock of the machine, in seconds, or `None` where there is none.
95///
96/// Unix reads `CLOCK_MONOTONIC`, which is what `steady_clock` reads there.
97#[cfg(unix)]
98fn machine_clock() -> Option<f64> {
99    #[allow(unsafe_code)]
100    {
101        let mut ts = libc::timespec {
102            tv_sec: 0,
103            tv_nsec: 0,
104        };
105        // SAFETY: `clock_gettime` writes a `timespec` through the pointer and
106        // reads nothing else. The value is stack-allocated and initialized.
107        let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
108        if rc == 0 {
109            return Some(ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9);
110        }
111    }
112    None
113}
114
115/// The clock of the machine, in seconds, or `None` where there is none.
116///
117/// # Why Windows needs its own arithmetic
118///
119/// Windows has no `clock_gettime`. MSVC builds `steady_clock` on the
120/// performance counter, and liblsl reads `steady_clock` (`src/common.cpp:20`),
121/// so this function reads the same counter. The counter starts when the
122/// machine starts, and every process on the machine reads one value.
123///
124/// MSVC divides before it multiplies, which keeps a large counter inside an
125/// `i64`:
126///
127/// ```text
128/// whole = (counter / frequency) * 1_000_000_000
129/// part  = (counter % frequency) * 1_000_000_000 / frequency
130/// ```
131///
132/// This function keeps that order. It holds the whole seconds and the
133/// nanoseconds apart, because `f64` carries 53 bits and a machine that ran for
134/// 104 days has more nanoseconds than that. liblsl divides the same way and
135/// gives the reason (`src/common.cpp:46-48`).
136///
137/// The multiplication uses `i128`. A counter frequency above 9.2 GHz overflows
138/// an `i64` here, and an overflow stops a program in a debug build. No counter
139/// runs that fast. The wider type costs nothing and removes the case.
140#[cfg(windows)]
141fn machine_clock() -> Option<f64> {
142    #[allow(unsafe_code)]
143    {
144        let mut frequency: i64 = 0;
145        let mut counter: i64 = 0;
146        // SAFETY: each call writes one `i64` through the pointer and reads
147        // nothing else. Both values are stack-allocated and initialized.
148        let ok = unsafe {
149            QueryPerformanceFrequency(&mut frequency) != 0
150                && QueryPerformanceCounter(&mut counter) != 0
151        };
152        // Windows XP and every later version always answer. A zero frequency
153        // would divide by zero, so this checks it.
154        if ok && frequency > 0 {
155            return Some(counter_seconds(counter, frequency));
156        }
157    }
158    None
159}
160
161/// Seconds from a performance counter and its frequency.
162///
163/// Only Windows calls this. Every platform compiles it, so a test of the
164/// arithmetic runs everywhere. Windows is the one platform that this
165/// repository does not measure against liblsl.
166///
167/// The caller must give a frequency above zero.
168#[cfg_attr(not(windows), allow(dead_code))]
169fn counter_seconds(counter: i64, frequency: i64) -> f64 {
170    let seconds = counter / frequency;
171    let rest = (counter % frequency) as i128;
172    let nanoseconds = (rest * 1_000_000_000 / frequency as i128) as f64;
173    seconds as f64 + nanoseconds * 1e-9
174}
175
176/// The clock of the machine, in seconds, or `None` where there is none.
177#[cfg(not(any(unix, windows)))]
178fn machine_clock() -> Option<f64> {
179    None
180}
181
182// `QueryPerformanceCounter` counts from the moment the machine started, and
183// `QueryPerformanceFrequency` gives the counts in one second. The frequency
184// does not change while the machine runs.
185#[cfg(windows)]
186#[allow(unsafe_code)]
187#[link(name = "kernel32")]
188extern "system" {
189    fn QueryPerformanceCounter(count: *mut i64) -> i32;
190    fn QueryPerformanceFrequency(frequency: *mut i64) -> i32;
191}
192
193/// Build a stream instance identifier.
194///
195/// liblsl writes a UUID. The value is random and it changes on every restart,
196/// so no test compares it. SPEC.md 12.
197pub fn make_uid() -> String {
198    let b = random_bytes();
199    format!(
200        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
201        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
202        b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]
203    )
204}
205
206/// Build an opaque discovery token.
207///
208/// liblsl builds this from `std::hash`, whose value differs between standard
209/// libraries. Any value works, because the token only travels out and back.
210/// SPEC.md 2.3.
211pub fn make_query_id() -> String {
212    let b = random_bytes();
213    let mut s = String::with_capacity(16);
214    for x in b.iter().take(8) {
215        s.push_str(&format!("{x:02x}"));
216    }
217    s
218}
219
220fn random_bytes() -> [u8; 16] {
221    // The operating system supplies the bytes. This value never needs to be
222    // reproducible, and it must not repeat across two processes that start at
223    // the same moment.
224    //
225    // Read an exact count. A read to the end of this file never returns,
226    // because the file never ends.
227    use std::io::Read;
228    let mut out = [0u8; 16];
229    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
230        if f.read_exact(&mut out).is_ok() {
231            return out;
232        }
233    }
234    // A fallback that mixes the clock with the process identifier.
235    let t = std::time::SystemTime::now()
236        .duration_since(std::time::UNIX_EPOCH)
237        .map(|d| d.as_nanos() as u64)
238        .unwrap_or(0);
239    let p = std::process::id() as u64;
240    let mut x = t ^ (p << 32) ^ 0x9E3779B97F4A7C15;
241    for b in out.iter_mut() {
242        x ^= x << 13;
243        x ^= x >> 7;
244        x ^= x << 17;
245        *b = (x & 0xFF) as u8;
246    }
247    out
248}
249
250/// Every local IPv4 address on this machine.
251///
252/// A multicast join names an interface by its address. Joining with the
253/// unspecified address lets the kernel pick one, and it can pick the loopback,
254/// which carries no multicast. An outlet is then invisible to a resolver that
255/// sends on a real interface.
256///
257/// liblsl reads the interface list with `getifaddrs`
258/// (`src/netinterfaces.cpp`). This reads the routing table instead, which needs
259/// no unsafe code. A machine with no readable table returns an empty list, and
260/// the caller falls back to the unspecified address.
261pub fn local_ipv4_addresses() -> Vec<std::net::Ipv4Addr> {
262    let mut out = Vec::new();
263    let text = match std::fs::read_to_string("/proc/net/fib_trie") {
264        Ok(t) => t,
265        Err(_) => return out,
266    };
267    let lines: Vec<&str> = text.lines().collect();
268    for (i, line) in lines.iter().enumerate() {
269        // A local address appears as a `/32 host LOCAL` entry, one line below
270        // the address itself.
271        if !line.contains("host LOCAL") {
272            continue;
273        }
274        if i == 0 {
275            continue;
276        }
277        let prev = lines[i - 1];
278        let addr = prev.rsplit(&[' ', '|', '-'][..]).find(|t| {
279            t.split('.').count() == 4 && t.chars().all(|c| c.is_ascii_digit() || c == '.')
280        });
281        if let Some(a) = addr.and_then(|a| a.parse::<std::net::Ipv4Addr>().ok()) {
282            if !a.is_broadcast() && !out.contains(&a) {
283                out.push(a);
284            }
285        }
286    }
287    out
288}
289
290/// The index of every interface on this machine, with zero at the front.
291///
292/// An IPv6 multicast join names an interface by index rather than by address
293/// (`src/udp_server.cpp:78`, which reads `scope_id`). Index zero lets the
294/// operating system pick one, and that choice can be the loopback, which
295/// carries no multicast. Every real index is therefore tried as well.
296///
297/// The list comes from `/proc/net/if_inet6`, whose fourth column is the index
298/// in hexadecimal. A machine with no readable file returns only zero.
299pub fn local_interface_indexes() -> Vec<u32> {
300    let mut out = vec![0u32];
301    if let Ok(text) = std::fs::read_to_string("/proc/net/if_inet6") {
302        for line in text.lines() {
303            let mut parts = line.split_whitespace();
304            // address, index, prefix length, scope, flags, name
305            let index = parts.nth(1).and_then(|v| u32::from_str_radix(v, 16).ok());
306            if let Some(i) = index {
307                if i != 0 && !out.contains(&i) {
308                    out.push(i);
309                }
310            }
311        }
312    }
313    out
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn the_interface_list_holds_the_choice_of_the_system() {
322        let idx = local_interface_indexes();
323        assert_eq!(idx[0], 0, "index zero must come first");
324        println!("interface indexes: {idx:?}");
325    }
326
327    #[test]
328    fn a_uid_has_the_shape_that_the_predicate_wants() {
329        let u = make_uid();
330        let parts: Vec<&str> = u.split('-').collect();
331        assert_eq!(parts.len(), 5);
332        assert_eq!(
333            [
334                parts[0].len(),
335                parts[1].len(),
336                parts[2].len(),
337                parts[3].len(),
338                parts[4].len()
339            ],
340            [8, 4, 4, 4, 12]
341        );
342        assert!(u.chars().all(|c| c.is_ascii_hexdigit() || c == '-'));
343    }
344
345    #[test]
346    fn two_uids_differ() {
347        assert_ne!(make_uid(), make_uid());
348    }
349
350    #[test]
351    fn the_clock_moves_forward() {
352        let a = clock();
353        std::thread::sleep(std::time::Duration::from_millis(5));
354        assert!(clock() > a);
355    }
356}
357
358/// The arithmetic of the Windows clock. SPEC.md 3.0.
359///
360/// Only Windows runs `counter_seconds`, and no measurement compares this
361/// library against liblsl on Windows. These tests are therefore the only check
362/// of that arithmetic, and they run on every platform.
363#[cfg(test)]
364mod counter {
365    use super::counter_seconds;
366
367    /// 10 MHz is the frequency of most machines. MSVC holds a separate branch
368    /// for it that multiplies the counter by 100 to get nanoseconds. The two
369    /// branches must give one answer.
370    const TEN_MHZ: i64 = 10_000_000;
371
372    #[test]
373    fn a_whole_number_of_seconds_carries_no_remainder() {
374        assert_eq!(counter_seconds(TEN_MHZ * 7, TEN_MHZ), 7.0);
375        assert_eq!(counter_seconds(0, TEN_MHZ), 0.0);
376    }
377
378    #[test]
379    fn a_part_of_a_second_reads_as_a_fraction() {
380        // A quarter of a second at 10 MHz is 2,500,000 counts.
381        assert_eq!(counter_seconds(2_500_000, TEN_MHZ), 0.25);
382        // One microsecond is 10 counts.
383        let one_microsecond = counter_seconds(10, TEN_MHZ);
384        assert!((one_microsecond - 1e-6).abs() < 1e-15);
385    }
386
387    #[test]
388    fn the_ten_megahertz_branch_of_the_source_agrees() {
389        // MSVC returns `counter * 100` nanoseconds at this frequency. The
390        // general form must give the same seconds.
391        for counter in [1_i64, 999, 12_345_678, 8_985_600_000_000] {
392            let theirs = (counter * 100) as f64 * 1e-9;
393            let ours = counter_seconds(counter, TEN_MHZ);
394            assert!(
395                (ours - theirs).abs() < 1e-9,
396                "counter {counter}: {ours} against {theirs}"
397            );
398        }
399    }
400
401    /// A machine that ran for 104 days holds more nanoseconds than an `f64`
402    /// carries. liblsl keeps the whole seconds apart from the rest for that
403    /// reason (`src/common.cpp:46-48`), and this function does the same.
404    ///
405    /// The whole second must stay exact, and the rest must stay inside a
406    /// nanosecond. A later change that divides a whole nanosecond count by 1e9
407    /// loses the second one first.
408    #[test]
409    fn a_long_uptime_keeps_the_microseconds() {
410        let days_104 = 104 * 24 * 60 * 60; // 8,985,600 seconds
411        let counter = TEN_MHZ * days_104 + 25; // and 2.5 microseconds
412        let seconds = counter_seconds(counter, TEN_MHZ);
413        assert_eq!(seconds.trunc(), days_104 as f64);
414        // An `f64` at 8.9 million holds about 2 nanoseconds in its last bit,
415        // so this is the resolution that remains after 104 days.
416        let rest = seconds - days_104 as f64;
417        assert!(
418            (rest - 2.5e-6).abs() < 1e-8,
419            "the rest reads {rest}, and 2.5 microseconds was pushed"
420        );
421    }
422
423    /// A frequency that is not 10 MHz has to work as well. 3,579,545 Hz is the
424    /// frequency of an older machine.
425    #[test]
426    fn an_odd_frequency_gives_the_right_second() {
427        let frequency = 3_579_545;
428        assert_eq!(counter_seconds(frequency * 3, frequency), 3.0);
429        let half = counter_seconds(frequency / 2, frequency);
430        assert!((half - 0.5).abs() < 1e-6, "half a second read {half}");
431    }
432}
433
434#[cfg(test)]
435mod clock_origin {
436    /// The clock must share its origin with liblsl.
437    ///
438    /// liblsl reads `CLOCK_MONOTONIC` (`src/common.cpp:20`). A test that only
439    /// checks the value moves forward would pass with any origin, and an origin
440    /// that differs makes every timestamp wrong for a peer that applies no
441    /// correction.
442    #[test]
443    fn the_clock_agrees_with_the_system_monotonic_clock() {
444        let ours = super::clock();
445        let uptime = std::fs::read_to_string("/proc/uptime").unwrap_or_default();
446        let boottime: f64 = uptime
447            .split_whitespace()
448            .next()
449            .and_then(|v| v.parse().ok())
450            .unwrap_or(0.0);
451        // The two differ by the time the machine spent suspended, so this only
452        // checks the order of magnitude. The value must be an age of the
453        // machine and not an age of this process.
454        assert!(
455            ours > 1.0,
456            "the clock reads {ours}, which looks like a process age"
457        );
458        if boottime > 0.0 {
459            assert!(
460                ours <= boottime + 1.0,
461                "the clock reads {ours}, past the boot clock {boottime}"
462            );
463        }
464        println!("clock {ours:.3}, boot clock {boottime:.3}");
465    }
466}