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