Skip to main content

s2_kit/connect/
discovery.rs

1//! Finding S2 Connect endpoints on the local network, and being found.
2//!
3//! `S2C §DNS-SD based discovery`: endpoints advertise `_s2connect._tcp`, with the subtype
4//! `_cem` or `_rm` for each role they host, and a TXT record that carries the URLs a
5//! pairing client needs. That is all discovery does — it produces a *candidate*, and
6//! nothing about a candidate is trustworthy until the pairing HMAC has spoken.
7//!
8//! ```text
9//!   _s2connect._tcp.local.                      the service
10//!   _rm._sub._s2connect._tcp.local.             hosts a Resource Manager
11//!   TXT  txtver=1                               this version of the specification
12//!        e_name=EVSE1038                        what to show the user
13//!        pairingUrl=https://EVSE1038.local/     where to pair (no version: the index says)
14//! ```
15//!
16//! The record model, including which TXT keys are mandatory and why both spellings of the
17//! version key are accepted, is [`proto::dnssd`](crate::connect::proto::dnssd); this
18//! module is the daemon that puts it on the wire.
19//!
20//! # Pure Rust, and why that matters here
21//!
22//! `mdns-sd` speaks mDNS itself rather than binding to Avahi or Bonjour. The alternative
23//! makes a Resource Manager's firmware depend on a system daemon that constrained Linux
24//! images routinely do not ship — and S2 Connect explicitly designs for nodes that are
25//! "purely an HTTPS client".
26
27use alloc::string::{String, ToString};
28use alloc::vec::Vec;
29
30use crate::connect::proto::Role;
31use crate::connect::proto::dnssd::ServiceRecord;
32
33/// The fully-qualified service type, as DNS-SD writes it.
34pub const SERVICE_FQDN: &str = "_s2connect._tcp.local.";
35
36/// An endpoint someone is advertising.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Discovered {
39    /// The instance name, which is what a user would recognise in a list.
40    pub instance: String,
41    /// The host it answers on, without the trailing dot.
42    pub host: String,
43    /// The port.
44    pub port: u16,
45    /// Every address it resolved to.
46    pub addresses: Vec<core::net::IpAddr>,
47    /// What the TXT record said.
48    pub record: ServiceRecord,
49}
50
51impl Discovered {
52    /// The base URL of the pairing API, if this endpoint offers one.
53    ///
54    /// Taken from the TXT record rather than assembled from the host and port: the
55    /// specification carries `pairingUrl` precisely so that an endpoint can serve the API
56    /// from a path, a different port, or a different name than the one it advertises.
57    #[must_use]
58    pub fn pairing_url(&self) -> Option<&str> {
59        self.record.pairing_url.as_deref()
60    }
61
62    /// The base URL of the long-polling API, for an endpoint that runs no HTTPS server.
63    #[must_use]
64    pub fn longpolling_url(&self) -> Option<&str> {
65        self.record.longpolling_url.as_deref()
66    }
67
68    /// Whether this endpoint hosts a node of the given role.
69    ///
70    /// `None` when the subtype was not visible — some resolvers do not report it — in
71    /// which case the only way to know is to ask `GET /v1/nodes`.
72    #[must_use]
73    pub fn hosts(&self, role: Role) -> Option<bool> {
74        if self.record.roles.is_empty() {
75            None
76        } else {
77            Some(self.record.roles.contains(&role))
78        }
79    }
80}
81
82/// Errors from the mDNS daemon.
83#[derive(Debug, thiserror::Error)]
84#[non_exhaustive]
85pub enum Error {
86    /// The daemon could not be started, or a record could not be registered.
87    #[error("mDNS: {0}")]
88    Mdns(String),
89    /// The record is not one S2 Connect allows — no URL, or a version we do not speak.
90    #[error("the service record is not a usable S2 Connect record")]
91    Record,
92}
93
94impl From<mdns_sd::Error> for Error {
95    fn from(e: mdns_sd::Error) -> Self {
96        Error::Mdns(e.to_string())
97    }
98}
99
100/// Advertises this endpoint, and browses for others.
101///
102/// One daemon per process is plenty; it is cheap to clone and each clone shares the same
103/// socket.
104#[derive(Clone)]
105pub struct Discovery {
106    daemon: mdns_sd::ServiceDaemon,
107}
108
109impl core::fmt::Debug for Discovery {
110    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
111        f.write_str("Discovery { .. }")
112    }
113}
114
115impl Discovery {
116    /// Start the daemon.
117    pub fn new() -> Result<Self, Error> {
118        Ok(Self {
119            daemon: mdns_sd::ServiceDaemon::new()?,
120        })
121    }
122
123    /// Advertise an endpoint.
124    ///
125    /// `instance` is the name a user sees; `host` is the `.local` name this machine
126    /// answers on, without the trailing dot. The record must carry at least one of
127    /// `pairingUrl` and `longpollingUrl`, or there is nothing for a client to do with it.
128    ///
129    /// ```no_run
130    /// use s2_kit::connect::discovery::Discovery;
131    /// use s2_kit::connect::proto::Role;
132    /// use s2_kit::connect::proto::dnssd::ServiceRecord;
133    ///
134    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
135    /// let discovery = Discovery::new()?;
136    /// discovery.advertise(
137    ///     "EVSE1038",
138    ///     "EVSE1038.local",
139    ///     443,
140    ///     &ServiceRecord {
141    ///         endpoint_name: Some("Acme charger".into()),
142    ///         pairing_url: Some("https://EVSE1038.local/".into()),
143    ///         roles: vec![Role::Rm],
144    ///         ..ServiceRecord::default()
145    ///     },
146    /// )?;
147    /// # Ok(())
148    /// # }
149    /// ```
150    pub fn advertise(
151        &self,
152        instance: &str,
153        host: &str,
154        port: u16,
155        record: &ServiceRecord,
156    ) -> Result<(), Error> {
157        // "It is mandatory to provide a value for at least one of the properties
158        // pairingUrl and longpollingUrl." Advertising without one wastes every browser's
159        // time and produces a candidate nothing can act on.
160        if record.pairing_url.is_none() && record.longpolling_url.is_none() {
161            return Err(Error::Record);
162        }
163        let properties: std::collections::HashMap<String, String> = record
164            .txt_pairs()
165            .into_iter()
166            .map(|(k, v)| (k.to_string(), v))
167            .collect();
168
169        // `S2C §DNS-SD based discovery`: "`_cem` and `_rm` are both used when the endpoint
170        // contains both CEM and RM nodes". `mdns-sd` cannot express that — a `ServiceInfo`
171        // holds one `Option<String>` of subtype, and the daemon keys registrations by
172        // *fullname*, which carries no subtype, so two registrations of one instance
173        // collide rather than adding a second subtype.
174        //
175        // A dual-role endpoint is therefore advertised on the **plain** service type: it
176        // stays discoverable by an unfiltered browse, its TXT record is unchanged, and
177        // `Discovered::hosts` answers `None` for "the subtype was not visible, ask
178        // `GET /v1/nodes`". Losing the filter beats losing half the audience (D44).
179        let subtypes = record.subtypes();
180        let ty = match subtypes.as_slice() {
181            [] => SERVICE_FQDN.to_string(),
182            [only] => alloc::format!("{only}._sub.{SERVICE_FQDN}"),
183            _ => {
184                crate::trace::event!(
185                    warn,
186                    instance = instance,
187                    "an endpoint hosting both roles is advertised on the plain service \
188                     type: mdns-sd cannot put one instance under two DNS-SD subtypes"
189                );
190                SERVICE_FQDN.to_string()
191            }
192        };
193
194        let info = mdns_sd::ServiceInfo::new(
195            &ty,
196            instance,
197            &alloc::format!("{}.", host.trim_end_matches('.')),
198            "",
199            port,
200            properties,
201        )?
202        // Let the daemon fill in this machine's addresses; hard-coding them is how a
203        // device ends up advertising an address it lost at the last DHCP lease.
204        .enable_addr_auto();
205        self.daemon.register(info)?;
206        Ok(())
207    }
208
209    /// Stop advertising an instance.
210    pub fn withdraw(&self, instance: &str) -> Result<(), Error> {
211        self.daemon
212            .unregister(&alloc::format!("{instance}.{SERVICE_FQDN}"))?;
213        Ok(())
214    }
215
216    /// Browse for endpoints, optionally only those hosting a particular role.
217    ///
218    /// Returns a channel of [`Discovered`]. Records that are not usable S2 Connect
219    /// records — a version we do not speak, no URL at all — are dropped rather than
220    /// surfaced, because there is nothing a caller could do with them.
221    ///
222    /// Browsing never ends on its own: a device that appears ten minutes from now is as
223    /// interesting as one that is there already. Drop the receiver to stop.
224    pub fn browse(&self, role: Option<Role>) -> Result<Browse, Error> {
225        let ty = match role {
226            Some(role) => alloc::format!("{}._sub.{SERVICE_FQDN}", role.service_subtype()),
227            None => SERVICE_FQDN.to_string(),
228        };
229        Ok(Browse {
230            events: self.daemon.browse(&ty)?,
231        })
232    }
233
234    /// Shut the daemon down, withdrawing everything it advertises.
235    pub fn shutdown(&self) -> Result<(), Error> {
236        self.daemon.shutdown()?;
237        Ok(())
238    }
239
240    /// The underlying daemon, for anything this wrapper does not expose.
241    #[must_use]
242    pub fn daemon(&self) -> &mdns_sd::ServiceDaemon {
243        &self.daemon
244    }
245}
246
247/// A running browse.
248pub struct Browse {
249    events: mdns_sd::Receiver<mdns_sd::ServiceEvent>,
250}
251
252impl core::fmt::Debug for Browse {
253    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
254        f.write_str("Browse { .. }")
255    }
256}
257
258impl Browse {
259    /// The next endpoint, waiting for one if necessary.
260    ///
261    /// `None` when the daemon has shut down.
262    pub async fn next(&self) -> Option<Discovered> {
263        loop {
264            let event = self.events.recv_async().await.ok()?;
265            if let Some(found) = resolve(event) {
266                return Some(found);
267            }
268        }
269    }
270
271    /// The next endpoint, or `None` if none is waiting right now.
272    pub fn try_next(&self) -> Option<Discovered> {
273        loop {
274            let event = self.events.try_recv().ok()?;
275            if let Some(found) = resolve(event) {
276                return Some(found);
277            }
278        }
279    }
280}
281
282/// Turn a resolution into a candidate, or discard it.
283fn resolve(event: mdns_sd::ServiceEvent) -> Option<Discovered> {
284    let mdns_sd::ServiceEvent::ServiceResolved(service) = event else {
285        // `ServiceFound` has no TXT record yet and `ServiceRemoved` is not a candidate.
286        return None;
287    };
288    let pairs: Vec<(String, String)> = service
289        .txt_properties
290        .iter()
291        .map(|p| (p.key().to_string(), p.val_str().to_string()))
292        .collect();
293    let borrowed: Vec<(&str, &str)> = pairs
294        .iter()
295        .map(|(k, v)| (k.as_str(), v.as_str()))
296        .collect();
297    // Refuses a record from a future version of the specification, and one with no URL.
298    let mut record = ServiceRecord::from_txt(borrowed)?;
299
300    // The subtype, when the resolver reported one, says which role is hosted.
301    if let Some(sub) = &service.sub_ty_domain {
302        if sub.starts_with("_cem.") {
303            record.roles = alloc::vec![Role::Cem];
304        } else if sub.starts_with("_rm.") {
305            record.roles = alloc::vec![Role::Rm];
306        }
307    }
308
309    Some(Discovered {
310        instance: service
311            .fullname
312            .split_once('.')
313            .map_or_else(|| service.fullname.clone(), |(name, _)| name.to_string()),
314        host: service.host.trim_end_matches('.').to_string(),
315        port: service.port,
316        addresses: service
317            .addresses
318            .iter()
319            .map(mdns_sd::ScopedIp::to_ip_addr)
320            .collect(),
321        record,
322    })
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn two_subtypes_cannot_share_one_instance_and_that_is_why_we_do_not_try() {
331        // `S2C §DNS-SD based discovery` requires a dual-role endpoint to advertise both
332        // `_cem` and `_rm`. `mdns-sd` cannot: its registrations are keyed by *fullname*,
333        // and a fullname is `<instance>.<service>.<domain>` with no subtype in it. So
334        // registering one instance twice does not advertise two subtypes — the second
335        // silently replaces the first, and the endpoint is discoverable under whichever
336        // role came last.
337        //
338        // This is asserted against the library rather than remembered in a comment,
339        // because the day `mdns-sd` grows multi-subtype support is the day this test
340        // fails and the workaround in `advertise` can go.
341        let of = |sub: &str| {
342            mdns_sd::ServiceInfo::new(
343                &alloc::format!("{sub}._sub.{SERVICE_FQDN}"),
344                "EVSE1038",
345                "EVSE1038.local.",
346                "127.0.0.1",
347                443,
348                None,
349            )
350            .expect("a legal service info")
351        };
352        let cem = of("_cem");
353        let rm = of("_rm");
354        assert_ne!(
355            cem.get_subtype(),
356            rm.get_subtype(),
357            "two different subtypes"
358        );
359        assert_eq!(
360            cem.get_fullname(),
361            rm.get_fullname(),
362            "…that collide on the key the daemon stores them under"
363        );
364    }
365
366    fn record() -> ServiceRecord {
367        ServiceRecord {
368            endpoint_name: Some("Acme charger".into()),
369            endpoint_logo_url: None,
370            pairing_url: Some("https://EVSE1038.local/".into()),
371            longpolling_url: None,
372            roles: alloc::vec![Role::Rm],
373        }
374    }
375
376    #[test]
377    fn the_service_type_is_the_one_the_specification_registers() {
378        use crate::connect::proto::dnssd::{PROTOCOL, SERVICE_TYPE};
379        assert_eq!(
380            SERVICE_FQDN,
381            alloc::format!("{SERVICE_TYPE}.{PROTOCOL}.local.")
382        );
383        assert_eq!(Role::Cem.service_subtype(), "_cem");
384        assert_eq!(Role::Rm.service_subtype(), "_rm");
385    }
386
387    #[test]
388    fn a_record_with_no_url_is_refused_before_it_reaches_the_network() {
389        let Ok(discovery) = Discovery::new() else {
390            // No multicast in this environment; the check below does not need a daemon.
391            return;
392        };
393        let useless = ServiceRecord {
394            roles: alloc::vec![Role::Rm],
395            ..ServiceRecord::default()
396        };
397        assert!(matches!(
398            discovery.advertise("EVSE1038", "EVSE1038.local", 443, &useless),
399            Err(Error::Record)
400        ));
401        let _ = discovery.shutdown();
402    }
403
404    #[test]
405    fn a_discovered_endpoint_reports_what_it_can_and_admits_what_it_cannot() {
406        let found = Discovered {
407            instance: "EVSE1038".into(),
408            host: "EVSE1038.local".into(),
409            port: 443,
410            addresses: Vec::new(),
411            record: record(),
412        };
413        assert_eq!(found.pairing_url(), Some("https://EVSE1038.local/"));
414        assert_eq!(found.longpolling_url(), None);
415        assert_eq!(found.hosts(Role::Rm), Some(true));
416        assert_eq!(found.hosts(Role::Cem), Some(false));
417
418        // A resolver that did not report the subtype leaves the role unknown, and saying
419        // "no" would be a lie that hides the endpoint from a browse.
420        let unknown = Discovered {
421            record: ServiceRecord {
422                roles: Vec::new(),
423                ..record()
424            },
425            ..found
426        };
427        assert_eq!(unknown.hosts(Role::Rm), None);
428    }
429
430    #[test]
431    fn the_txt_record_carries_what_a_client_needs() {
432        let pairs = record().txt_pairs();
433        assert_eq!(pairs[0], ("txtver", "1".to_string()));
434        let keys: Vec<&str> = pairs.iter().map(|(k, _)| *k).collect();
435        assert!(keys.contains(&"pairingUrl"));
436        assert!(keys.contains(&"e_name"));
437    }
438}