Skip to main content

labstream_proto/
features.rs

1//! The feature header between two labstream peers. `docs/extensions.md`.
2//!
3//! A labstream inlet offers features in the request header
4//! `Labstream-Features`, and a labstream outlet answers the ones that it
5//! accepts. liblsl reads only the header keys that it knows, on both sides
6//! (`src/tcp_server.cpp:605-633`, `src/data_receiver.cpp:215-253`), so a
7//! liblsl peer ignores the header and the connection stays plain LSL.
8//!
9//! Both parsers cut a header line at the first `;` and convert it to
10//! lowercase (`src/tcp_server.cpp:610-613`, `crate::header`). A token is
11//! therefore lowercase, and a parameter is hexadecimal.
12
13/// The header name, as it goes on the wire.
14pub const HEADER: &str = "Labstream-Features";
15
16/// The header name, as [`crate::Headers`] stores it.
17pub const HEADER_KEY: &str = "labstream-features";
18
19/// The name of the sequence number feature. `crate::seq`.
20pub const SEQ: &str = "seq";
21
22/// The name of the resend feature. `docs/extensions.md`, section `resume`.
23///
24/// `resume` is not in [`SUPPORTED`], because its tokens carry a parameter.
25/// [`offer_resume`], [`resume_request`], and [`resume_answer`] handle it.
26pub const RESUME: &str = "resume";
27
28/// The name of the UDP transport. `docs/extensions.md`, section `dgram`.
29///
30/// `dgram` is not in [`SUPPORTED`], because its answer carries a parameter.
31/// [`offer_dgram`], [`dgram_request`], and [`dgram_answer`] handle it. It is
32/// off by default in version 1.
33pub const DGRAM: &str = "dgram";
34
35/// The name of the channel and rate selection feature (`docs/roadmap.md`, step 6).
36///
37/// `select` carries a hexadecimal parameter naming the decimation factor and
38/// optional channel index list. [`offer_select`], [`select_request`], and
39/// [`select_answer`] handle it.
40pub const SELECT: &str = "select";
41
42/// The name of the same-machine shared-memory transport (`docs/extensions.md`,
43/// section `shm`, `docs/roadmap.md`, step 9).
44///
45/// `shm` carries a 16-hex-digit segment identifier in the outlet answer.
46/// [`offer_shm`], [`shm_request`], and [`shm_answer`] handle it.
47pub const SHM: &str = "shm";
48
49/// The name of the lossless wire compression feature (`docs/extensions.md`,
50/// section `comp`, `docs/roadmap.md`, step 7).
51///
52/// `comp` applies to numeric streams only (not `Format::String`) and carries no
53/// parameter. [`offer_comp`], [`comp_request`], and [`comp_answer`] handle it.
54pub const COMP: &str = "comp";
55
56/// The name of the in-band live metadata feature (`docs/extensions.md`,
57/// section `meta`, `docs/roadmap.md`, step 16).
58pub const META: &str = "meta";
59
60/// The name of the negotiated encryption feature (`docs/extensions.md`,
61/// section `enc`, `docs/roadmap.md`, step 14).
62///
63/// Off by default. Carries a 64-hex-digit (32-byte) ephemeral X25519 public
64/// key in both the inlet offer and the outlet answer.
65pub const ENC: &str = "enc";
66
67/// The features with no parameter that this library implements, each with
68/// its versions.
69pub const SUPPORTED: &[(&str, &[u32])] = &[(SEQ, &[1]), (META, &[1])];
70
71/// One feature with a version, and an optional parameter.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Token {
74    /// The feature name: `a-z`, `0-9`, and `-`.
75    pub name: String,
76    /// The version of the feature.
77    pub version: u32,
78    /// A hexadecimal parameter, in lowercase.
79    pub param: Option<String>,
80}
81
82impl Token {
83    /// A token with no parameter.
84    pub fn new(name: &str, version: u32) -> Self {
85        Token {
86            name: name.to_string(),
87            version,
88            param: None,
89        }
90    }
91
92    /// Read one token. The result is `None` if the token does not match the
93    /// syntax.
94    pub fn parse(text: &str) -> Option<Token> {
95        let (head, param) = match text.split_once('=') {
96            Some((h, p)) => (h, Some(p)),
97            None => (text, None),
98        };
99        let (name, version) = head.split_once('/')?;
100        let name_ok = !name.is_empty()
101            && name
102                .bytes()
103                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
104        let version_ok = !version.is_empty() && version.bytes().all(|b| b.is_ascii_digit());
105        if !name_ok || !version_ok {
106            return None;
107        }
108        let param = match param {
109            Some(p)
110                if !p.is_empty() && p.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) =>
111            {
112                Some(p.to_string())
113            }
114            Some(_) => return None,
115            None => None,
116        };
117        Some(Token {
118            name: name.to_string(),
119            version: version.parse().ok()?,
120            param,
121        })
122    }
123
124    /// Write the token as it goes on the wire.
125    pub fn to_wire(&self) -> String {
126        match &self.param {
127            Some(p) => format!("{}/{}={}", self.name, self.version, p),
128            None => format!("{}/{}", self.name, self.version),
129        }
130    }
131}
132
133/// Read a header value. A token with a bad form is left out.
134pub fn parse(value: &str) -> Vec<Token> {
135    value
136        .split_ascii_whitespace()
137        .filter_map(Token::parse)
138        .collect()
139}
140
141/// Write a whole header line, with its line end.
142pub fn header_line(tokens: &[Token]) -> String {
143    let list: Vec<String> = tokens.iter().map(Token::to_wire).collect();
144    format!("{HEADER}: {}\r\n", list.join(" "))
145}
146
147/// The tokens that this process offers: each supported feature that the
148/// configuration allows, at each supported version.
149pub fn offer(allowed: &[String]) -> Vec<Token> {
150    SUPPORTED
151        .iter()
152        .filter(|(name, _)| allowed.iter().any(|a| a == name))
153        .flat_map(|(name, versions)| versions.iter().map(|v| Token::new(name, *v)))
154        .collect()
155}
156
157/// The outlet's answer to an offer.
158///
159/// The answer holds only offered tokens. For each name it holds at most one
160/// version: the highest version that both sides support. A feature that the
161/// configuration does not allow is left out. An offered token with a
162/// parameter is left out. The answer for `resume` comes from
163/// [`resume_request`].
164pub fn answer(offered: &[Token], allowed: &[String]) -> Vec<Token> {
165    let mut out: Vec<Token> = Vec::new();
166    for (name, versions) in SUPPORTED {
167        if !allowed.iter().any(|a| a == name) {
168            continue;
169        }
170        let best = offered
171            .iter()
172            .filter(|t| t.name == *name && versions.contains(&t.version) && t.param.is_none())
173            .max_by_key(|t| t.version);
174        if let Some(t) = best {
175            out.push(t.clone());
176        }
177    }
178    out
179}
180
181/// The features that are on, from what the inlet offered and what the outlet
182/// answered.
183///
184/// An answer token that was not offered is left out. A feature is on only
185/// when both sides named it. The comparison uses the name and the version.
186/// The result keeps the parameter of the answer token.
187pub fn agreed(offered: &[Token], answered: &[Token]) -> Vec<Token> {
188    let mut out: Vec<Token> = Vec::new();
189    for t in answered {
190        let was_offered = offered
191            .iter()
192            .any(|o| o.name == t.name && o.version == t.version);
193        if was_offered && !out.iter().any(|x| x.name == t.name) {
194            out.push(t.clone());
195        }
196    }
197    out
198}
199
200/// True when the list holds the feature at this version.
201pub fn has(tokens: &[Token], name: &str, version: u32) -> bool {
202    tokens
203        .iter()
204        .any(|t| t.name == name && t.version == version)
205}
206
207/// The count of hexadecimal digits of the epoch in a `resume/1` parameter.
208const EPOCH_DIGITS: usize = 16;
209
210/// The parameter of a `resume/1` token.
211///
212/// The parameter is the epoch in exactly 16 hexadecimal digits, then a
213/// sample number in 1 to 16 hexadecimal digits, with no separator. In an
214/// offer, the number is the next number that the inlet expects. In an
215/// answer, the number is the first live sample of the connection.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct ResumeParam {
218    /// The random value that identifies one run of the outlet.
219    pub epoch: u64,
220    /// A `seq` number.
221    pub number: u64,
222}
223
224impl ResumeParam {
225    /// Read a parameter. The result is `None` if the parameter has fewer
226    /// than 17 or more than 32 digits, or a digit that is not hexadecimal.
227    pub fn parse(param: &str) -> Option<ResumeParam> {
228        if param.len() <= EPOCH_DIGITS || param.len() > 2 * EPOCH_DIGITS {
229            return None;
230        }
231        // `from_str_radix` also accepts a sign, so each byte gets a check.
232        if !param
233            .bytes()
234            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
235        {
236            return None;
237        }
238        let (epoch, number) = param.split_at(EPOCH_DIGITS);
239        Some(ResumeParam {
240            epoch: u64::from_str_radix(epoch, 16).ok()?,
241            number: u64::from_str_radix(number, 16).ok()?,
242        })
243    }
244
245    /// Write the parameter as it goes on the wire.
246    pub fn to_param(&self) -> String {
247        format!("{:016x}{:x}", self.epoch, self.number)
248    }
249
250    /// A `resume/1` token with this parameter.
251    pub fn token(&self) -> Token {
252        Token {
253            name: RESUME.to_string(),
254            version: 1,
255            param: Some(self.to_param()),
256        }
257    }
258}
259
260/// What an inlet asks for with its `resume/1` token.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub enum ResumeRequest {
263    /// A token with no parameter: a first connection, or a new outlet.
264    Fresh,
265    /// A token with a parameter: a recovery to the same outlet.
266    From(ResumeParam),
267}
268
269/// True when the configuration allows `resume`. `resume` needs `seq`, so the
270/// configuration must allow both.
271fn resume_allowed(allowed: &[String]) -> bool {
272    allowed.iter().any(|a| a == SEQ) && allowed.iter().any(|a| a == RESUME)
273}
274
275/// The `resume/1` token that an inlet offers.
276///
277/// `from` is `None` on a first connection, after a recovery to a new outlet,
278/// and when the inlet has no epoch or no expected number. The result is
279/// `None` when the configuration does not allow `resume`.
280pub fn offer_resume(allowed: &[String], from: Option<ResumeParam>) -> Option<Token> {
281    if !resume_allowed(allowed) {
282        return None;
283    }
284    Some(match from {
285        Some(p) => p.token(),
286        None => Token::new(RESUME, 1),
287    })
288}
289
290/// Read the `resume/1` request of an offer, on the outlet side.
291///
292/// `answered` is the result of [`answer`] for the same offer. The result is
293/// `None` when `resume` must stay off for the connection:
294///
295/// - the configuration does not allow `resume`,
296/// - the answer does not hold `seq/1`,
297/// - the offer holds no `resume/1` token, or more than one,
298/// - the parameter does not match [`ResumeParam::parse`].
299///
300/// If the result is not `None`, the outlet adds the token of its own
301/// [`ResumeParam`] to the answer.
302pub fn resume_request(
303    offered: &[Token],
304    answered: &[Token],
305    allowed: &[String],
306) -> Option<ResumeRequest> {
307    if !resume_allowed(allowed) || !has(answered, SEQ, 1) {
308        return None;
309    }
310    let mut tokens = offered
311        .iter()
312        .filter(|t| t.name == RESUME && t.version == 1);
313    let token = tokens.next()?;
314    if tokens.next().is_some() {
315        return None;
316    }
317    match &token.param {
318        None => Some(ResumeRequest::Fresh),
319        Some(p) => ResumeParam::parse(p).map(ResumeRequest::From),
320    }
321}
322
323/// Read the `resume/1` answer of an outlet, on the inlet side.
324///
325/// `agreed` is the result of [`agreed`]. The result is `None` when `resume`
326/// is off for the connection: the features do not hold `seq/1`, or do not
327/// hold `resume/1`, or the parameter does not match [`ResumeParam::parse`].
328pub fn resume_answer(agreed: &[Token]) -> Option<ResumeParam> {
329    if !has(agreed, SEQ, 1) {
330        return None;
331    }
332    let token = agreed.iter().find(|t| t.name == RESUME && t.version == 1)?;
333    ResumeParam::parse(token.param.as_deref()?)
334}
335
336/// The parameter of a `dgram/1` answer: the UDP port of the outlet in
337/// exactly 4 hexadecimal digits, then a cookie in exactly 16 hexadecimal
338/// digits.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub struct DgramParam {
341    /// The UDP port of the outlet.
342    pub port: u16,
343    /// The random value that each datagram carries.
344    pub cookie: u64,
345}
346
347impl DgramParam {
348    /// Read a parameter. The result is `None` unless the parameter has
349    /// exactly 20 hexadecimal digits.
350    pub fn parse(param: &str) -> Option<DgramParam> {
351        if param.len() != 20
352            || !param
353                .bytes()
354                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
355        {
356            return None;
357        }
358        Some(DgramParam {
359            port: u16::from_str_radix(&param[..4], 16).ok()?,
360            cookie: u64::from_str_radix(&param[4..], 16).ok()?,
361        })
362    }
363
364    /// Write the parameter as it goes on the wire.
365    pub fn to_param(&self) -> String {
366        format!("{:04x}{:016x}", self.port, self.cookie)
367    }
368
369    /// A `dgram/1` token with this parameter.
370    pub fn token(&self) -> Token {
371        Token {
372            name: DGRAM.to_string(),
373            version: 1,
374            param: Some(self.to_param()),
375        }
376    }
377}
378
379/// True when the configuration allows `dgram`. `dgram` needs `seq` and
380/// `resume`, so the configuration must allow all three.
381fn dgram_allowed(allowed: &[String]) -> bool {
382    resume_allowed(allowed) && allowed.iter().any(|a| a == DGRAM)
383}
384
385/// The `dgram/1` token that an inlet offers, or `None` when the
386/// configuration does not allow `dgram`.
387pub fn offer_dgram(allowed: &[String]) -> Option<Token> {
388    dgram_allowed(allowed).then(|| Token::new(DGRAM, 1))
389}
390
391/// True when the outlet can answer `dgram/1`.
392///
393/// `answered` must already hold the answer tokens of `seq/1` and of
394/// `resume/1`. The offer must hold `dgram/1` with no parameter.
395/// `docs/extensions.md`, section `dgram`, negotiation rules 2 and 6.
396pub fn dgram_request(offered: &[Token], answered: &[Token], allowed: &[String]) -> bool {
397    dgram_allowed(allowed)
398        && has(answered, SEQ, 1)
399        && has(answered, RESUME, 1)
400        && offered
401            .iter()
402            .any(|t| t.name == DGRAM && t.version == 1 && t.param.is_none())
403}
404
405/// Read the `dgram/1` answer of an outlet, on the inlet side.
406///
407/// The result is `None` when `dgram` is off for the connection: the
408/// features do not hold `seq/1` and `resume/1`, or do not hold `dgram/1`,
409/// or the parameter does not match [`DgramParam::parse`].
410pub fn dgram_answer(agreed: &[Token]) -> Option<DgramParam> {
411    resume_answer(agreed)?;
412    let token = agreed.iter().find(|t| t.name == DGRAM && t.version == 1)?;
413    DgramParam::parse(token.param.as_deref()?)
414}
415
416/// The parameter of a `select/1` offer and answer (`docs/roadmap.md`, step 6).
417///
418/// Wire encoding (lowercase hex, no separator):
419/// - 8 hex digits: `decimate` as `u32` big-endian (`>= 1`; `1` = full rate)
420/// - 4 hex digits: `channels.len()` as `u16` big-endian (`0` = all channels)
421/// - `4 * channels.len()` hex digits: each 0-based channel index as `u16` big-endian
422#[derive(Debug, Clone, PartialEq, Eq)]
423pub struct SelectParam {
424    /// Integer rate decimation factor (`1` keeps the full rate, `16` reduces
425    /// 4000 Hz to 250 Hz).
426    pub decimate: u32,
427    /// Ordered 0-based channel indices to keep. Empty means every channel.
428    pub channels: Vec<u16>,
429}
430
431impl SelectParam {
432    /// Select a subset of channels at full rate.
433    pub fn channels(channels: Vec<u16>) -> Self {
434        SelectParam {
435            decimate: 1,
436            channels,
437        }
438    }
439
440    /// Decimate all channels by `factor` (clamped to `>= 1`).
441    pub fn decimate(factor: u32) -> Self {
442        SelectParam {
443            decimate: factor.max(1),
444            channels: Vec::new(),
445        }
446    }
447
448    /// True when this parameter actually narrows channels or reduces rate.
449    pub fn is_active(&self) -> bool {
450        self.decimate > 1 || !self.channels.is_empty()
451    }
452
453    /// Effective channel count for a source stream with `source_channels`.
454    pub fn output_channels(&self, source_channels: usize) -> usize {
455        if self.channels.is_empty() {
456            source_channels
457        } else {
458            self.channels.len()
459        }
460    }
461
462    /// Effective sample rate for a source stream with `source_srate`.
463    pub fn output_srate(&self, source_srate: f64) -> f64 {
464        if source_srate <= 0.0 || self.decimate <= 1 {
465            source_srate
466        } else {
467            source_srate / self.decimate as f64
468        }
469    }
470
471    /// Read a `select/1` parameter from its lowercase hexadecimal string.
472    pub fn parse(param: &str) -> Option<SelectParam> {
473        if param.len() < 12
474            || (param.len() - 12) % 4 != 0
475            || !param
476                .bytes()
477                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
478        {
479            return None;
480        }
481        let decimate = u32::from_str_radix(&param[..8], 16).ok()?;
482        if decimate == 0 {
483            return None;
484        }
485        let count = u16::from_str_radix(&param[8..12], 16).ok()? as usize;
486        if param.len() != 12 + count * 4 {
487            return None;
488        }
489        let mut channels = Vec::with_capacity(count);
490        for i in 0..count {
491            let start = 12 + i * 4;
492            channels.push(u16::from_str_radix(&param[start..start + 4], 16).ok()?);
493        }
494        Some(SelectParam { decimate, channels })
495    }
496
497    /// Encode this parameter as lowercase hexadecimal.
498    pub fn to_param(&self) -> String {
499        let mut s = format!(
500            "{:08x}{:04x}",
501            self.decimate.max(1),
502            self.channels.len() as u16
503        );
504        for &ch in &self.channels {
505            s.push_str(&format!("{ch:04x}"));
506        }
507        s
508    }
509
510    /// Build the `select/1=<hex>` wire token.
511    pub fn token(&self) -> Token {
512        Token {
513            name: SELECT.to_string(),
514            version: 1,
515            param: Some(self.to_param()),
516        }
517    }
518}
519
520/// True when the configuration allows `select`.
521fn select_allowed(allowed: &[String]) -> bool {
522    allowed.iter().any(|a| a == SELECT)
523}
524
525/// Build the `select/1` offer token when selection is active and allowed.
526pub fn offer_select(allowed: &[String], param: Option<&SelectParam>) -> Option<Token> {
527    if !select_allowed(allowed) {
528        return None;
529    }
530    let p = param?;
531    if !p.is_active() || p.channels.len() > u16::MAX as usize {
532        return None;
533    }
534    Some(p.token())
535}
536
537/// Validate an inlet's `select/1` offer against the outlet's stream metadata.
538///
539/// Rejects out-of-range channel indices, decimation on irregular or string
540/// streams, duplicate tokens, or inactive requests.
541pub fn select_request(
542    offered: &[Token],
543    allowed: &[String],
544    source_channels: usize,
545    source_srate: f64,
546    is_string: bool,
547) -> Option<SelectParam> {
548    if !select_allowed(allowed) {
549        return None;
550    }
551    let mut tokens = offered
552        .iter()
553        .filter(|t| t.name == SELECT && t.version == 1);
554    let token = tokens.next()?;
555    if tokens.next().is_some() {
556        return None;
557    }
558    let param = SelectParam::parse(token.param.as_deref()?)?;
559    if !param.is_active() {
560        return None;
561    }
562    if param.decimate > 1 && (is_string || source_srate <= 0.0 || !source_srate.is_finite()) {
563        return None;
564    }
565    if param
566        .channels
567        .iter()
568        .any(|&ch| (ch as usize) >= source_channels)
569    {
570        return None;
571    }
572    Some(param)
573}
574
575/// Read the outlet's confirmed `select/1` answer on the inlet side.
576pub fn select_answer(agreed: &[Token]) -> Option<SelectParam> {
577    let token = agreed.iter().find(|t| t.name == SELECT && t.version == 1)?;
578    let param = SelectParam::parse(token.param.as_deref()?)?;
579    param.is_active().then_some(param)
580}
581
582/// The parameter of a `shm/1` answer: a 64-bit random segment identifier
583/// encoded as exactly 16 lowercase hexadecimal digits (`docs/extensions.md`,
584/// section `shm`).
585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
586pub struct ShmParam {
587    /// Random 64-bit identifier naming the shared-memory segment.
588    pub id: u64,
589}
590
591impl ShmParam {
592    /// Read a `shm/1` parameter. Returns `None` unless the string holds
593    /// exactly 16 lowercase hexadecimal digits.
594    pub fn parse(param: &str) -> Option<ShmParam> {
595        if param.len() != 16
596            || !param
597                .bytes()
598                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
599        {
600            return None;
601        }
602        Some(ShmParam {
603            id: u64::from_str_radix(param, 16).ok()?,
604        })
605    }
606
607    /// Encode this parameter as 16 lowercase hexadecimal digits.
608    pub fn to_param(&self) -> String {
609        format!("{:016x}", self.id)
610    }
611
612    /// Build the `shm/1=<id>` wire token.
613    pub fn token(&self) -> Token {
614        Token {
615            name: SHM.to_string(),
616            version: 1,
617            param: Some(self.to_param()),
618        }
619    }
620}
621
622/// True when the configuration allows `shm`.
623fn shm_allowed(allowed: &[String]) -> bool {
624    allowed.iter().any(|a| a == SHM)
625}
626
627/// The `shm/1` token that an inlet offers, or `None` when `shm` is disabled.
628pub fn offer_shm(allowed: &[String]) -> Option<Token> {
629    shm_allowed(allowed).then(|| Token::new(SHM, 1))
630}
631
632/// True when the outlet can answer `shm/1` for this request.
633pub fn shm_request(offered: &[Token], allowed: &[String]) -> bool {
634    shm_allowed(allowed)
635        && offered
636            .iter()
637            .any(|t| t.name == SHM && t.version == 1 && t.param.is_none())
638}
639
640/// Read the outlet's `shm/1=<id>` answer on the inlet side.
641pub fn shm_answer(agreed: &[Token]) -> Option<ShmParam> {
642    let token = agreed.iter().find(|t| t.name == SHM && t.version == 1)?;
643    ShmParam::parse(token.param.as_deref()?)
644}
645
646/// True when the configuration allows `comp`.
647fn comp_allowed(allowed: &[String]) -> bool {
648    allowed.iter().any(|a| a == COMP)
649}
650
651/// The `comp/1` token that an inlet offers for a numeric stream, or `None`
652/// when `comp` is disabled or the stream carries strings.
653pub fn offer_comp(allowed: &[String], is_string: bool) -> Option<Token> {
654    (!is_string && comp_allowed(allowed)).then(|| Token::new(COMP, 1))
655}
656
657/// True when the outlet can answer `comp/1` for this request.
658pub fn comp_request(offered: &[Token], allowed: &[String], is_string: bool) -> bool {
659    !is_string
660        && comp_allowed(allowed)
661        && offered
662            .iter()
663            .any(|t| t.name == COMP && t.version == 1 && t.param.is_none())
664}
665
666/// True when `comp/1` is active in the agreed feature list.
667pub fn comp_answer(agreed: &[Token]) -> bool {
668    agreed
669        .iter()
670        .any(|t| t.name == COMP && t.version == 1 && t.param.is_none())
671}
672
673/// The parameter of an `enc/1` offer or answer: a 32-byte X25519 ephemeral
674/// public key encoded as 64 lowercase hexadecimal digits (`docs/extensions.md`,
675/// section `enc`).
676#[derive(Debug, Clone, Copy, PartialEq, Eq)]
677pub struct EncParam {
678    /// 32-byte X25519 public key.
679    pub pubkey: [u8; 32],
680}
681
682impl EncParam {
683    /// Parse 64 lowercase hexadecimal digits into a 32-byte public key.
684    pub fn parse(param: &str) -> Option<EncParam> {
685        if param.len() != 64
686            || !param
687                .bytes()
688                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
689        {
690            return None;
691        }
692        let mut pubkey = [0u8; 32];
693        for (i, slot) in pubkey.iter_mut().enumerate() {
694            *slot = u8::from_str_radix(&param[i * 2..i * 2 + 2], 16).ok()?;
695        }
696        Some(EncParam { pubkey })
697    }
698
699    /// Encode this public key as 64 lowercase hexadecimal digits.
700    pub fn to_param(&self) -> String {
701        let mut out = String::with_capacity(64);
702        for b in self.pubkey {
703            out.push_str(&format!("{b:02x}"));
704        }
705        out
706    }
707
708    /// Build the `enc/1=<64-hex>` wire token.
709    pub fn token(&self) -> Token {
710        Token {
711            name: ENC.to_string(),
712            version: 1,
713            param: Some(self.to_param()),
714        }
715    }
716}
717
718/// Build the `enc/1=<pubkey>` offer token for an inlet.
719pub fn offer_enc(pubkey: [u8; 32]) -> Token {
720    EncParam { pubkey }.token()
721}
722
723/// Extract the inlet's `enc/1=<pubkey>` offer on the outlet side.
724pub fn enc_request(offered: &[Token]) -> Option<EncParam> {
725    let mut tokens = offered.iter().filter(|t| t.name == ENC && t.version == 1);
726    let token = tokens.next()?;
727    if tokens.next().is_some() {
728        return None;
729    }
730    EncParam::parse(token.param.as_deref()?)
731}
732
733/// Extract the outlet's `enc/1=<pubkey>` answer on the inlet side.
734pub fn enc_answer(agreed: &[Token]) -> Option<EncParam> {
735    let token = agreed.iter().find(|t| t.name == ENC && t.version == 1)?;
736    EncParam::parse(token.param.as_deref()?)
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    fn all() -> Vec<String> {
744        vec![SEQ.to_string()]
745    }
746
747    fn with_resume() -> Vec<String> {
748        vec![SEQ.to_string(), RESUME.to_string()]
749    }
750
751    const P: ResumeParam = ResumeParam {
752        epoch: 0x9c3e_51a0_d2b7_f4e8,
753        number: 0x1f4a0,
754    };
755
756    #[test]
757    fn a_token_reads_back_as_it_was_written() {
758        for text in ["seq/1", "shm/1=0a1b2c", "x-y2/10"] {
759            assert_eq!(Token::parse(text).unwrap().to_wire(), text);
760        }
761    }
762
763    #[test]
764    fn a_bad_token_is_left_out() {
765        let got = parse("seq/1 SEQ/1 seq/ /1 seq/x shm/1=XYZ shm/1= seq/2");
766        assert_eq!(got, vec![Token::new("seq", 1), Token::new("seq", 2)]);
767    }
768
769    #[test]
770    fn the_header_line_is_lowercase_safe_and_has_no_semicolon() {
771        let line = header_line(&[Token::new("seq", 1)]);
772        assert_eq!(line, "Labstream-Features: seq/1\r\n");
773        // Both parsers cut the line at `;` and convert it to lowercase. The
774        // value must read the same after that.
775        let value = line.split_once(':').unwrap().1.trim();
776        assert!(!value.contains(';'));
777        assert_eq!(parse(&value.to_ascii_lowercase()), parse(value));
778    }
779
780    #[test]
781    fn the_answer_holds_only_offered_and_allowed_features() {
782        let offered = parse("seq/1 seq/7 shm/1=00ff");
783        assert_eq!(answer(&offered, &all()), vec![Token::new("seq", 1)]);
784        assert!(answer(&offered, &[]).is_empty());
785        assert!(answer(&parse("shm/1"), &all()).is_empty());
786        assert!(answer(&parse("seq/9"), &all()).is_empty());
787    }
788
789    #[test]
790    fn a_feature_is_on_only_when_both_sides_name_it() {
791        let offered = offer(&all());
792        assert_eq!(offered, vec![Token::new("seq", 1)]);
793        assert!(has(&agreed(&offered, &parse("seq/1")), SEQ, 1));
794        assert!(agreed(&offered, &parse("seq/2")).is_empty());
795        assert!(agreed(&offered, &[]).is_empty());
796        assert!(agreed(&[], &parse("seq/1")).is_empty());
797        assert_eq!(agreed(&offered, &parse("seq/1 seq/1")).len(), 1);
798    }
799
800    #[test]
801    fn the_configuration_can_turn_every_feature_off() {
802        assert!(offer(&[]).is_empty());
803    }
804
805    #[test]
806    fn a_resume_parameter_reads_back_as_it_was_written() {
807        assert_eq!(P.to_param(), "9c3e51a0d2b7f4e81f4a0");
808        assert_eq!(ResumeParam::parse("9c3e51a0d2b7f4e81f4a0"), Some(P));
809        // A small epoch keeps its leading zeros, so the split stays at 16.
810        let small = ResumeParam {
811            epoch: 1,
812            number: 0,
813        };
814        assert_eq!(small.to_param(), "00000000000000010");
815        assert_eq!(ResumeParam::parse(&small.to_param()), Some(small));
816        let max = ResumeParam {
817            epoch: u64::MAX,
818            number: u64::MAX,
819        };
820        assert_eq!(max.to_param().len(), 32);
821        assert_eq!(ResumeParam::parse(&max.to_param()), Some(max));
822    }
823
824    #[test]
825    fn a_resume_parameter_with_a_bad_length_or_digit_is_refused() {
826        // 16 digits: an epoch and no number.
827        assert_eq!(ResumeParam::parse("9c3e51a0d2b7f4e8"), None);
828        // 33 digits: the number does not fit in 64 bits.
829        assert_eq!(ResumeParam::parse(&"1".repeat(33)), None);
830        assert_eq!(ResumeParam::parse(""), None);
831        assert_eq!(ResumeParam::parse("9c3e51a0d2b7f4e8+1"), None);
832        assert_eq!(ResumeParam::parse("9C3E51A0D2B7F4E81"), None);
833    }
834
835    #[test]
836    fn the_resume_token_goes_through_the_header_syntax() {
837        let line = header_line(&[Token::new(SEQ, 1), P.token()]);
838        let value = line.split_once(':').unwrap().1.trim();
839        assert_eq!(value, "seq/1 resume/1=9c3e51a0d2b7f4e81f4a0");
840        assert_eq!(parse(&value.to_ascii_lowercase()), parse(value));
841        assert_eq!(parse(value)[1], P.token());
842    }
843
844    #[test]
845    fn an_inlet_offers_resume_only_with_seq() {
846        assert_eq!(
847            offer_resume(&with_resume(), None),
848            Some(Token::new(RESUME, 1))
849        );
850        assert_eq!(offer_resume(&with_resume(), Some(P)), Some(P.token()));
851        assert_eq!(offer_resume(&all(), Some(P)), None);
852        assert_eq!(offer_resume(&[RESUME.to_string()], None), None);
853        assert_eq!(offer_resume(&[], None), None);
854    }
855
856    #[test]
857    fn the_plain_answer_leaves_resume_out() {
858        let offered = parse("seq/1 resume/1 resume/1=9c3e51a0d2b7f4e81f4a0");
859        assert_eq!(answer(&offered, &with_resume()), vec![Token::new(SEQ, 1)]);
860    }
861
862    #[test]
863    fn an_outlet_reads_the_resume_request() {
864        let req = |text: &str, allowed: &[String]| {
865            let offered = parse(text);
866            let answered = answer(&offered, allowed);
867            resume_request(&offered, &answered, allowed)
868        };
869        let a = with_resume();
870        assert_eq!(req("seq/1 resume/1", &a), Some(ResumeRequest::Fresh));
871        assert_eq!(
872            req("seq/1 resume/1=9c3e51a0d2b7f4e81f4a0", &a),
873            Some(ResumeRequest::From(P))
874        );
875        // Another version of resume is not this request.
876        assert_eq!(req("seq/1 resume/2", &a), None);
877        assert_eq!(
878            req("seq/1 resume/2 resume/1", &a),
879            Some(ResumeRequest::Fresh)
880        );
881    }
882
883    #[test]
884    fn an_outlet_keeps_resume_off_for_a_bad_request() {
885        let req = |text: &str, allowed: &[String]| {
886            let offered = parse(text);
887            let answered = answer(&offered, allowed);
888            resume_request(&offered, &answered, allowed)
889        };
890        let a = with_resume();
891        // Without seq on the connection.
892        assert_eq!(req("resume/1", &a), None);
893        assert_eq!(req("seq/1 resume/1", &[RESUME.to_string()]), None);
894        // Not allowed by the configuration.
895        assert_eq!(req("seq/1 resume/1", &all()), None);
896        // A parameter of 16 or 33 digits.
897        assert_eq!(req("seq/1 resume/1=9c3e51a0d2b7f4e8", &a), None);
898        let long = format!("seq/1 resume/1={}", "1".repeat(33));
899        assert_eq!(req(&long, &a), None);
900        // Two resume/1 tokens, with the same or a different parameter.
901        assert_eq!(req("seq/1 resume/1 resume/1", &a), None);
902        assert_eq!(
903            req(
904                "seq/1 resume/1=9c3e51a0d2b7f4e81f4a0 resume/1=9c3e51a0d2b7f4e82",
905                &a
906            ),
907            None
908        );
909        // No resume token.
910        assert_eq!(req("seq/1", &a), None);
911    }
912
913    #[test]
914    fn an_inlet_reads_the_resume_answer() {
915        let offered = parse("seq/1 resume/1");
916        let on = agreed(&offered, &[Token::new(SEQ, 1), P.token()]);
917        assert_eq!(resume_answer(&on), Some(P));
918        // The answer has no parameter.
919        let bare = agreed(&offered, &parse("seq/1 resume/1"));
920        assert_eq!(resume_answer(&bare), None);
921        // The answer has a bad parameter.
922        let bad = agreed(&offered, &parse("seq/1 resume/1=9c3e51a0d2b7f4e8"));
923        assert_eq!(resume_answer(&bad), None);
924        // The answer has resume and no seq.
925        let lone = agreed(&offered, &[P.token()]);
926        assert_eq!(resume_answer(&lone), None);
927        // The inlet did not offer resume.
928        let unasked = agreed(&parse("seq/1"), &[Token::new(SEQ, 1), P.token()]);
929        assert_eq!(resume_answer(&unasked), None);
930        assert!(has(&unasked, SEQ, 1));
931    }
932
933    fn with_dgram() -> Vec<String> {
934        vec![SEQ.to_string(), RESUME.to_string(), DGRAM.to_string()]
935    }
936
937    const G: DgramParam = DgramParam {
938        port: 0xc35b,
939        cookie: 0x9f2e_81d0_4a77_13c6,
940    };
941
942    #[test]
943    fn a_dgram_parameter_reads_back_as_it_was_written() {
944        assert_eq!(G.to_param(), "c35b9f2e81d04a7713c6");
945        assert_eq!(DgramParam::parse("c35b9f2e81d04a7713c6"), Some(G));
946        let small = DgramParam { port: 1, cookie: 2 };
947        assert_eq!(small.to_param().len(), 20);
948        assert_eq!(DgramParam::parse(&small.to_param()), Some(small));
949        assert_eq!(DgramParam::parse("c35b9f2e81d04a7713c"), None);
950        assert_eq!(DgramParam::parse("c35b9f2e81d04a7713c60"), None);
951        assert_eq!(DgramParam::parse("+35b9f2e81d04a7713c6"), None);
952    }
953
954    #[test]
955    fn an_inlet_offers_dgram_only_with_seq_and_resume() {
956        assert_eq!(offer_dgram(&with_dgram()), Some(Token::new(DGRAM, 1)));
957        assert_eq!(offer_dgram(&with_resume()), None);
958        assert_eq!(offer_dgram(&[SEQ.to_string(), DGRAM.to_string()]), None);
959        assert_eq!(offer_dgram(&[DGRAM.to_string()]), None);
960    }
961
962    #[test]
963    fn an_outlet_answers_dgram_only_with_seq_and_resume_in_the_answer() {
964        let offered = parse("seq/1 resume/1 dgram/1");
965        let full = vec![Token::new(SEQ, 1), P.token()];
966        assert!(dgram_request(&offered, &full, &with_dgram()));
967        // Not allowed here.
968        assert!(!dgram_request(&offered, &full, &with_resume()));
969        // No resume in the answer.
970        assert!(!dgram_request(
971            &offered,
972            &[Token::new(SEQ, 1)],
973            &with_dgram()
974        ));
975        // No offer, or an offer with a parameter.
976        assert!(!dgram_request(
977            &parse("seq/1 resume/1"),
978            &full,
979            &with_dgram()
980        ));
981        assert!(!dgram_request(
982            &parse("seq/1 resume/1 dgram/1=00"),
983            &full,
984            &with_dgram()
985        ));
986        // The plain answer leaves dgram out.
987        assert_eq!(answer(&offered, &with_dgram()), vec![Token::new(SEQ, 1)]);
988    }
989
990    #[test]
991    fn comp_negotiates_on_numeric_streams_and_skips_strings() {
992        let allowed = vec![SEQ.to_string(), COMP.to_string()];
993        assert_eq!(offer_comp(&allowed, false), Some(Token::new(COMP, 1)));
994        assert_eq!(offer_comp(&allowed, true), None);
995        assert_eq!(offer_comp(&all(), false), None);
996
997        let offered = parse("seq/1 comp/1");
998        assert!(comp_request(&offered, &allowed, false));
999        assert!(!comp_request(&offered, &allowed, true));
1000        assert!(!comp_request(&parse("seq/1 comp/1=01"), &allowed, false));
1001        assert!(!comp_request(&offered, &all(), false));
1002
1003        let on = agreed(&offered, &[Token::new(SEQ, 1), Token::new(COMP, 1)]);
1004        assert!(comp_answer(&on));
1005        assert!(!comp_answer(&agreed(&offered, &[Token::new(SEQ, 1)])));
1006    }
1007
1008    #[test]
1009    fn an_inlet_reads_the_dgram_answer() {
1010        let offered = parse("seq/1 resume/1 dgram/1");
1011        let on = agreed(&offered, &[Token::new(SEQ, 1), P.token(), G.token()]);
1012        assert_eq!(dgram_answer(&on), Some(G));
1013        // No resume on the connection.
1014        let lone = agreed(&offered, &[Token::new(SEQ, 1), G.token()]);
1015        assert_eq!(dgram_answer(&lone), None);
1016        // No parameter, or a bad one.
1017        let bare = agreed(
1018            &offered,
1019            &parse("seq/1 resume/1=9c3e51a0d2b7f4e81f4a0 dgram/1"),
1020        );
1021        assert_eq!(dgram_answer(&bare), None);
1022        let bad = agreed(
1023            &offered,
1024            &parse("seq/1 resume/1=9c3e51a0d2b7f4e81f4a0 dgram/1=00ff"),
1025        );
1026        assert_eq!(dgram_answer(&bad), None);
1027        // The inlet did not offer dgram.
1028        let unasked = agreed(
1029            &parse("seq/1 resume/1"),
1030            &[Token::new(SEQ, 1), P.token(), G.token()],
1031        );
1032        assert_eq!(dgram_answer(&unasked), None);
1033    }
1034
1035    #[test]
1036    fn shm_token_round_trips_and_negotiates() {
1037        let p = ShmParam {
1038            id: 0x00ab_cd12_34ef_5678,
1039        };
1040        assert_eq!(p.to_param(), "00abcd1234ef5678");
1041        assert_eq!(ShmParam::parse(&p.to_param()), Some(p));
1042        assert_eq!(ShmParam::parse("00abcd1234ef567"), None);
1043        assert_eq!(ShmParam::parse("00ABCD1234EF5678"), None);
1044
1045        let allowed = vec![SEQ.to_string(), SHM.to_string()];
1046        assert_eq!(offer_shm(&allowed), Some(Token::new(SHM, 1)));
1047        assert_eq!(offer_shm(&all()), None);
1048
1049        let offered = parse("seq/1 shm/1");
1050        assert!(shm_request(&offered, &allowed));
1051        assert!(!shm_request(&offered, &all()));
1052        assert!(!shm_request(
1053            &parse("seq/1 shm/1=00abcd1234ef5678"),
1054            &allowed
1055        ));
1056
1057        let on = agreed(&offered, &[Token::new(SEQ, 1), p.token()]);
1058        assert_eq!(shm_answer(&on), Some(p));
1059        assert_eq!(shm_answer(&agreed(&parse("seq/1"), &[p.token()])), None);
1060    }
1061}