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/v1/  where to pair
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/v1/".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        // One registration per role, because DNS-SD subtypes are advertised that way: an
170        // endpoint hosting both a CEM and an RM is discoverable under both.
171        let subtypes = record.subtypes();
172        let types: Vec<String> = if subtypes.is_empty() {
173            alloc::vec![SERVICE_FQDN.to_string()]
174        } else {
175            subtypes
176                .iter()
177                .map(|sub| alloc::format!("{sub}._sub.{SERVICE_FQDN}"))
178                .collect()
179        };
180
181        for ty in types {
182            let info = mdns_sd::ServiceInfo::new(
183                &ty,
184                instance,
185                &alloc::format!("{}.", host.trim_end_matches('.')),
186                "",
187                port,
188                properties.clone(),
189            )?
190            // Let the daemon fill in this machine's addresses; hard-coding them is how a
191            // device ends up advertising an address it lost at the last DHCP lease.
192            .enable_addr_auto();
193            self.daemon.register(info)?;
194        }
195        Ok(())
196    }
197
198    /// Stop advertising an instance.
199    pub fn withdraw(&self, instance: &str) -> Result<(), Error> {
200        self.daemon
201            .unregister(&alloc::format!("{instance}.{SERVICE_FQDN}"))?;
202        Ok(())
203    }
204
205    /// Browse for endpoints, optionally only those hosting a particular role.
206    ///
207    /// Returns a channel of [`Discovered`]. Records that are not usable S2 Connect
208    /// records — a version we do not speak, no URL at all — are dropped rather than
209    /// surfaced, because there is nothing a caller could do with them.
210    ///
211    /// Browsing never ends on its own: a device that appears ten minutes from now is as
212    /// interesting as one that is there already. Drop the receiver to stop.
213    pub fn browse(&self, role: Option<Role>) -> Result<Browse, Error> {
214        let ty = match role {
215            Some(role) => alloc::format!("{}._sub.{SERVICE_FQDN}", role.service_subtype()),
216            None => SERVICE_FQDN.to_string(),
217        };
218        Ok(Browse {
219            events: self.daemon.browse(&ty)?,
220        })
221    }
222
223    /// Shut the daemon down, withdrawing everything it advertises.
224    pub fn shutdown(&self) -> Result<(), Error> {
225        self.daemon.shutdown()?;
226        Ok(())
227    }
228
229    /// The underlying daemon, for anything this wrapper does not expose.
230    #[must_use]
231    pub fn daemon(&self) -> &mdns_sd::ServiceDaemon {
232        &self.daemon
233    }
234}
235
236/// A running browse.
237pub struct Browse {
238    events: mdns_sd::Receiver<mdns_sd::ServiceEvent>,
239}
240
241impl core::fmt::Debug for Browse {
242    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
243        f.write_str("Browse { .. }")
244    }
245}
246
247impl Browse {
248    /// The next endpoint, waiting for one if necessary.
249    ///
250    /// `None` when the daemon has shut down.
251    pub async fn next(&self) -> Option<Discovered> {
252        loop {
253            let event = self.events.recv_async().await.ok()?;
254            if let Some(found) = resolve(event) {
255                return Some(found);
256            }
257        }
258    }
259
260    /// The next endpoint, or `None` if none is waiting right now.
261    pub fn try_next(&self) -> Option<Discovered> {
262        loop {
263            let event = self.events.try_recv().ok()?;
264            if let Some(found) = resolve(event) {
265                return Some(found);
266            }
267        }
268    }
269}
270
271/// Turn a resolution into a candidate, or discard it.
272fn resolve(event: mdns_sd::ServiceEvent) -> Option<Discovered> {
273    let mdns_sd::ServiceEvent::ServiceResolved(service) = event else {
274        // `ServiceFound` has no TXT record yet and `ServiceRemoved` is not a candidate.
275        return None;
276    };
277    let pairs: Vec<(String, String)> = service
278        .txt_properties
279        .iter()
280        .map(|p| (p.key().to_string(), p.val_str().to_string()))
281        .collect();
282    let borrowed: Vec<(&str, &str)> = pairs
283        .iter()
284        .map(|(k, v)| (k.as_str(), v.as_str()))
285        .collect();
286    // Refuses a record from a future version of the specification, and one with no URL.
287    let mut record = ServiceRecord::from_txt(borrowed)?;
288
289    // The subtype, when the resolver reported one, says which role is hosted.
290    if let Some(sub) = &service.sub_ty_domain {
291        if sub.starts_with("_cem.") {
292            record.roles = alloc::vec![Role::Cem];
293        } else if sub.starts_with("_rm.") {
294            record.roles = alloc::vec![Role::Rm];
295        }
296    }
297
298    Some(Discovered {
299        instance: service
300            .fullname
301            .split_once('.')
302            .map_or_else(|| service.fullname.clone(), |(name, _)| name.to_string()),
303        host: service.host.trim_end_matches('.').to_string(),
304        port: service.port,
305        addresses: service
306            .addresses
307            .iter()
308            .map(mdns_sd::ScopedIp::to_ip_addr)
309            .collect(),
310        record,
311    })
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    fn record() -> ServiceRecord {
319        ServiceRecord {
320            endpoint_name: Some("Acme charger".into()),
321            endpoint_logo_url: None,
322            pairing_url: Some("https://EVSE1038.local/v1/".into()),
323            longpolling_url: None,
324            roles: alloc::vec![Role::Rm],
325        }
326    }
327
328    #[test]
329    fn the_service_type_is_the_one_the_specification_registers() {
330        use crate::connect::proto::dnssd::{PROTOCOL, SERVICE_TYPE};
331        assert_eq!(
332            SERVICE_FQDN,
333            alloc::format!("{SERVICE_TYPE}.{PROTOCOL}.local.")
334        );
335        assert_eq!(Role::Cem.service_subtype(), "_cem");
336        assert_eq!(Role::Rm.service_subtype(), "_rm");
337    }
338
339    #[test]
340    fn a_record_with_no_url_is_refused_before_it_reaches_the_network() {
341        let Ok(discovery) = Discovery::new() else {
342            // No multicast in this environment; the check below does not need a daemon.
343            return;
344        };
345        let useless = ServiceRecord {
346            roles: alloc::vec![Role::Rm],
347            ..ServiceRecord::default()
348        };
349        assert!(matches!(
350            discovery.advertise("EVSE1038", "EVSE1038.local", 443, &useless),
351            Err(Error::Record)
352        ));
353        let _ = discovery.shutdown();
354    }
355
356    #[test]
357    fn a_discovered_endpoint_reports_what_it_can_and_admits_what_it_cannot() {
358        let found = Discovered {
359            instance: "EVSE1038".into(),
360            host: "EVSE1038.local".into(),
361            port: 443,
362            addresses: Vec::new(),
363            record: record(),
364        };
365        assert_eq!(found.pairing_url(), Some("https://EVSE1038.local/v1/"));
366        assert_eq!(found.longpolling_url(), None);
367        assert_eq!(found.hosts(Role::Rm), Some(true));
368        assert_eq!(found.hosts(Role::Cem), Some(false));
369
370        // A resolver that did not report the subtype leaves the role unknown, and saying
371        // "no" would be a lie that hides the endpoint from a browse.
372        let unknown = Discovered {
373            record: ServiceRecord {
374                roles: Vec::new(),
375                ..record()
376            },
377            ..found
378        };
379        assert_eq!(unknown.hosts(Role::Rm), None);
380    }
381
382    #[test]
383    fn the_txt_record_carries_what_a_client_needs() {
384        let pairs = record().txt_pairs();
385        assert_eq!(pairs[0], ("txtver", "1".to_string()));
386        let keys: Vec<&str> = pairs.iter().map(|(k, _)| *k).collect();
387        assert!(keys.contains(&"pairingUrl"));
388        assert!(keys.contains(&"e_name"));
389    }
390}