Skip to main content

spoolframe_protocol/
lan.rs

1//! How a server announces itself on the LAN (P1-13, ARCHITECTURE §18).
2//!
3//! Servers publish an mDNS record under their own service name, so the
4//! records of other Iroh apps on the network (`irohv1`) are never heard at
5//! all. The record's user data carries [`CLIENT_ALPN`] and the server's name.
6//! A record without that prefix is not a Spoolframe server and is ignored.
7//!
8//! All of it is untrusted: it says where to dial and which `EndpointId` to
9//! expect, and Iroh proves the identity on connect.
10
11use crate::CLIENT_ALPN;
12
13/// The mDNS service name: records are `<id>._spoolframe._udp.local`.
14pub const MDNS_SERVICE: &str = "spoolframe";
15
16/// The most user data an Iroh mDNS record holds (`UserData::MAX_LENGTH`).
17pub const MAX_ADVERT: usize = 245;
18
19const SEPARATOR: char = ';';
20
21/// What a server's record says about it.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Advert {
24    /// The server's name, possibly cut to fit the record.
25    pub name: String,
26}
27
28/// The user data a server called `name` publishes: the client ALPN and the
29/// name, the name cut at a character boundary to fit [`MAX_ADVERT`].
30pub fn advert(name: &str) -> String {
31    let alpn = std::str::from_utf8(CLIENT_ALPN).expect("the ALPN is ASCII");
32    let mut advert = format!("{alpn}{SEPARATOR}");
33    for c in name.chars() {
34        if advert.len() + c.len_utf8() > MAX_ADVERT {
35            break;
36        }
37        advert.push(c);
38    }
39    advert
40}
41
42/// Read a record's user data; `None` unless it is a Spoolframe server
43/// speaking this client protocol.
44pub fn parse_advert(user_data: &str) -> Option<Advert> {
45    let (alpn, name) = user_data.split_once(SEPARATOR)?;
46    (alpn.as_bytes() == CLIENT_ALPN).then(|| Advert {
47        name: name.to_owned(),
48    })
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn an_advert_reads_back_as_the_name() {
57        assert_eq!(
58            parse_advert(&advert("Home Media; upstairs")),
59            Some(Advert {
60                name: "Home Media; upstairs".into()
61            })
62        );
63    }
64
65    #[test]
66    fn a_long_name_is_cut_at_a_character_boundary() {
67        // Three bytes each: the limit falls inside one.
68        let name = "€".repeat(100);
69        let advert = advert(&name);
70        assert!(advert.len() <= MAX_ADVERT);
71        assert!(advert.len() > MAX_ADVERT - 3);
72        let read = parse_advert(&advert).unwrap();
73        assert!(name.starts_with(&read.name));
74    }
75
76    #[test]
77    fn records_of_other_apps_and_protocols_are_not_servers() {
78        for other in [
79            "",
80            "foobar",
81            "spoolframe/client/2;Home Media",
82            "spoolframe/client/1",
83        ] {
84            assert_eq!(parse_advert(other), None, "{other:?}");
85        }
86    }
87}