Skip to main content

fritz_core/
discover.rs

1//! Finds FRITZ! routers and repeaters on the local network: at the
2//! addresses of the configured host and the default gateway, through an
3//! SSDP search, and at well-known default addresses.
4//!
5//! Every candidate is verified by its device description, which needs no
6//! login: only FRITZ! devices with TR-064 are listed, and a device found in
7//! several ways is listed once. Nothing goes to addresses outside the local
8//! network, and every step ends after a fixed time.
9//!
10//! The name resolution, the default gateway and SSDP are behind the traits
11//! [`Resolver`], [`Gateway`] and [`Ssdp`], so that tests can give the
12//! answers, see [`Fixed`].
13
14use std::fmt;
15use std::future::Future;
16use std::io;
17use std::net::{IpAddr, Ipv4Addr, SocketAddr};
18use std::time::Duration;
19
20use serde::Serialize;
21use tokio::net::UdpSocket;
22use tokio::task::JoinSet;
23use tr064::{Client, DeviceDescription, Url};
24
25use crate::connection::HTTP_PORT;
26
27/// The device type of the root device of TR-064 devices, which FRITZ!
28/// routers and repeaters announce over SSDP.
29pub const ROOT_DEVICE: &str = "urn:dslforum-org:device:InternetGatewayDevice:1";
30
31/// The device types an SSDP search asks for: the root device, and the LAN
32/// device that routers and repeaters embed.
33pub const SEARCH_TARGETS: [&str; 2] = [ROOT_DEVICE, "urn:dslforum-org:device:LANDevice:1"];
34
35/// The address and port of SSDP.
36pub const SSDP_ADDRESS: SocketAddr =
37    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(239, 255, 255, 250)), 1900);
38
39/// The addresses FRITZ!Boxes have by default: the usual one of the home
40/// network and the fallback address that is always reachable over LAN.
41pub const DEFAULT_ADDRESSES: [IpAddr; 2] = [
42    IpAddr::V4(Ipv4Addr::new(192, 168, 178, 1)),
43    IpAddr::V4(Ipv4Addr::new(169, 254, 1, 1)),
44];
45
46/// How the devices were found, in the order of preference of their
47/// addresses.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum Source {
51    /// An address of the configured host.
52    Config,
53    /// The default gateway of this machine.
54    Gateway,
55    /// An answer to the SSDP search.
56    Ssdp,
57    /// A well-known default address.
58    Default,
59}
60
61impl fmt::Display for Source {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(match self {
64            Self::Config => "config",
65            Self::Gateway => "gateway",
66            Self::Ssdp => "ssdp",
67            Self::Default => "default",
68        })
69    }
70}
71
72/// What a device does in the network.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
74#[serde(rename_all = "lowercase")]
75pub enum Role {
76    /// It has a WAN device: a FRITZ!Box.
77    Router,
78    /// It has none: a repeater or another device of the mesh.
79    Repeater,
80}
81
82impl fmt::Display for Role {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(match self {
85            Self::Router => "router",
86            Self::Repeater => "repeater",
87        })
88    }
89}
90
91/// A verified device. The texts come from the network and are untrusted.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct Device {
94    /// The IP address, with the port if it is not the TR-064 port 49000.
95    pub address: String,
96    /// The host for `--host` and a profile: the IP address, which means
97    /// HTTPS on port 49443, or an `http` address for another port.
98    pub host: String,
99    /// The manufacturer.
100    pub manufacturer: Option<String>,
101    /// The model, like `FRITZ!Box 7690`.
102    pub model: Option<String>,
103    /// The FRITZ!OS version, like `8.25`, if the description has it.
104    pub firmware: Option<String>,
105    /// Router or repeater.
106    pub role: Role,
107    /// How it was found, in the order of [`Source`].
108    pub found_by: Vec<Source>,
109    /// The unique device name, to merge the same device at several
110    /// addresses.
111    #[serde(skip)]
112    udn: Option<String>,
113}
114
115/// The result of a discovery.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
117pub struct Report {
118    /// The configured host.
119    pub host: String,
120    /// The addresses it resolves to.
121    pub addresses: Vec<IpAddr>,
122    /// Whether it resolves only to addresses of the local network.
123    pub local: bool,
124    /// The default gateway of this machine.
125    pub gateway: Option<IpAddr>,
126    /// The verified devices, routers first.
127    pub devices: Vec<Device>,
128}
129
130/// Resolves host names.
131pub trait Resolver {
132    /// The addresses of `host`, empty if it does not resolve.
133    fn resolve(&self, host: &str) -> impl Future<Output = Vec<IpAddr>> + Send;
134}
135
136/// Finds the default gateway.
137pub trait Gateway {
138    /// The default gateway of this machine, if it has one.
139    fn gateway(&self) -> impl Future<Output = Option<IpAddr>> + Send;
140}
141
142/// Sends an SSDP search and collects the answers.
143pub trait Ssdp {
144    /// The `LOCATION` URLs of the answers to a search for `targets` that
145    /// arrive within `time`.
146    fn search(&self, targets: &[&str], time: Duration) -> impl Future<Output = Vec<String>> + Send;
147}
148
149/// The name resolution and the routing table of the system.
150#[derive(Debug, Clone, Copy, Default)]
151pub struct System;
152
153impl Resolver for System {
154    async fn resolve(&self, host: &str) -> Vec<IpAddr> {
155        let host = host.trim_start_matches('[').trim_end_matches(']');
156        let found = tokio::net::lookup_host((host, 0)).await;
157        let found = found.inspect_err(|error| tracing::debug!(host, %error, "cannot resolve"));
158        let mut addresses: Vec<IpAddr> = found.into_iter().flatten().map(|a| a.ip()).collect();
159        addresses.sort();
160        addresses.dedup();
161        addresses
162    }
163}
164
165impl Gateway for System {
166    async fn gateway(&self) -> Option<IpAddr> {
167        tokio::task::spawn_blocking(default_gateway)
168            .await
169            .ok()
170            .flatten()
171    }
172}
173
174/// The default gateway from `/proc/net/route`.
175#[cfg(target_os = "linux")]
176fn default_gateway() -> Option<IpAddr> {
177    linux_gateway(&std::fs::read_to_string("/proc/net/route").ok()?)
178}
179
180/// The default gateway from `route print`.
181#[cfg(windows)]
182fn default_gateway() -> Option<IpAddr> {
183    let output = route(&["print", "-4", "0.0.0.0"])?;
184    windows_gateway(&output)
185}
186
187/// The default gateway from `route get`, on macOS and the BSDs.
188#[cfg(not(any(target_os = "linux", windows)))]
189fn default_gateway() -> Option<IpAddr> {
190    bsd_gateway(&route(&["-n", "get", "default"])?)
191}
192
193/// The output of the system's `route` command.
194#[cfg(not(target_os = "linux"))]
195fn route(args: &[&str]) -> Option<String> {
196    let output = std::process::Command::new("route")
197        .args(args)
198        .output()
199        .ok()?;
200    Some(String::from_utf8_lossy(&output.stdout).into_owned())
201}
202
203/// The gateway of the default route in `/proc/net/route`, where addresses
204/// are hex numbers in the byte order of the machine.
205#[cfg(any(target_os = "linux", test))]
206fn linux_gateway(table: &str) -> Option<IpAddr> {
207    table.lines().skip(1).find_map(|line| {
208        let fields: Vec<&str> = line.split_whitespace().collect();
209        let (destination, gateway) = (fields.get(1)?, fields.get(2)?);
210        let gateway = u32::from_str_radix(gateway, 16).ok()?;
211        (*destination == "00000000" && gateway != 0)
212            .then(|| IpAddr::V4(Ipv4Addr::from(gateway.to_le_bytes())))
213    })
214}
215
216/// The gateway in the output of `route -n get default`.
217#[cfg(any(not(any(target_os = "linux", windows)), test))]
218fn bsd_gateway(output: &str) -> Option<IpAddr> {
219    output.lines().find_map(|line| {
220        let value = line.trim().strip_prefix("gateway:")?;
221        value.trim().parse().ok()
222    })
223}
224
225/// The gateway of the default route in the output of `route print`.
226#[cfg(any(windows, test))]
227fn windows_gateway(output: &str) -> Option<IpAddr> {
228    output.lines().find_map(
229        |line| match line.split_whitespace().collect::<Vec<_>>()[..] {
230            ["0.0.0.0", "0.0.0.0", gateway, ..] => gateway.parse().ok(),
231            _ => None,
232        },
233    )
234}
235
236/// SSDP over UDP: a search sent to [`SSDP_ADDRESS`], or to another
237/// address for tests.
238#[derive(Debug, Clone, Copy)]
239pub struct Multicast {
240    /// Where the search goes.
241    pub target: SocketAddr,
242}
243
244impl Default for Multicast {
245    fn default() -> Self {
246        Self {
247            target: SSDP_ADDRESS,
248        }
249    }
250}
251
252impl Ssdp for Multicast {
253    async fn search(&self, targets: &[&str], time: Duration) -> Vec<String> {
254        let found = self.try_search(targets, time).await;
255        found
256            .inspect_err(|error| tracing::debug!(%error, "SSDP search failed"))
257            .unwrap_or_default()
258    }
259}
260
261impl Multicast {
262    async fn try_search(&self, targets: &[&str], time: Duration) -> io::Result<Vec<String>> {
263        let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
264        // Only to the local network.
265        socket.set_multicast_ttl_v4(1)?;
266        let deadline = tokio::time::Instant::now() + time;
267        for target in targets {
268            let request = format!(
269                "M-SEARCH * HTTP/1.1\r\nHOST: {}\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: {target}\r\n\r\n",
270                self.target
271            );
272            socket.send_to(request.as_bytes(), self.target).await?;
273        }
274        let mut buffer = [0; 2048];
275        let mut locations = Vec::new();
276        while let Ok(answer) =
277            tokio::time::timeout_at(deadline, socket.recv_from(&mut buffer)).await
278        {
279            let (length, _) = answer?;
280            if let Some(location) = location(&buffer[..length])
281                && !locations.contains(&location)
282            {
283                locations.push(location);
284            }
285        }
286        Ok(locations)
287    }
288}
289
290/// The `LOCATION` header of an SSDP answer.
291fn location(answer: &[u8]) -> Option<String> {
292    String::from_utf8_lossy(answer).lines().find_map(|line| {
293        let (name, value) = line.split_once(':')?;
294        name.trim()
295            .eq_ignore_ascii_case("location")
296            .then(|| value.trim().to_owned())
297    })
298}
299
300/// Answers given in advance, for tests.
301#[derive(Debug, Clone, Default)]
302pub struct Fixed {
303    /// What every host resolves to.
304    pub addresses: Vec<IpAddr>,
305    /// The default gateway.
306    pub gateway: Option<IpAddr>,
307    /// The `LOCATION` URLs of the SSDP answers.
308    pub locations: Vec<String>,
309}
310
311impl Resolver for Fixed {
312    fn resolve(&self, _host: &str) -> impl Future<Output = Vec<IpAddr>> + Send {
313        std::future::ready(self.addresses.clone())
314    }
315}
316
317impl Gateway for Fixed {
318    fn gateway(&self) -> impl Future<Output = Option<IpAddr>> + Send {
319        std::future::ready(self.gateway)
320    }
321}
322
323impl Ssdp for Fixed {
324    fn search(
325        &self,
326        _targets: &[&str],
327        _time: Duration,
328    ) -> impl Future<Output = Vec<String>> + Send {
329        std::future::ready(self.locations.clone())
330    }
331}
332
333/// Where and how long to look.
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct Options {
336    /// The port of the device descriptions at the addresses of the
337    /// configured host, the gateway and the defaults.
338    pub port: u16,
339    /// The well-known addresses to try.
340    pub defaults: Vec<IpAddr>,
341    /// How long to collect SSDP answers.
342    pub search_time: Duration,
343    /// How long to wait for a device description.
344    pub timeout: Duration,
345}
346
347impl Default for Options {
348    /// Port 49000, [`DEFAULT_ADDRESSES`], and two seconds each.
349    fn default() -> Self {
350        Self {
351            port: HTTP_PORT,
352            defaults: DEFAULT_ADDRESSES.to_vec(),
353            search_time: Duration::from_secs(2),
354            timeout: Duration::from_secs(2),
355        }
356    }
357}
358
359/// A discovery with its sources: `network` resolves names and finds the
360/// gateway, `ssdp` searches.
361#[derive(Debug, Clone, Default)]
362pub struct Discovery<N, S> {
363    /// The name resolution and the default gateway.
364    pub network: N,
365    /// The SSDP search.
366    pub ssdp: S,
367    /// Where and how long to look.
368    pub options: Options,
369}
370
371impl Discovery<System, Multicast> {
372    /// A discovery on the network of this machine.
373    pub fn system() -> Self {
374        Self::default()
375    }
376}
377
378impl<N: Resolver + Gateway, S: Ssdp> Discovery<N, S> {
379    /// Looks for devices, with the configured `host` as the first
380    /// candidate if it is on the local network. Its description is asked
381    /// for at `port`, else at the port of the options. The name resolution
382    /// gets the timeout of the options, and gives no address after it.
383    pub async fn run(&self, host: &str, port: Option<u16>) -> Report {
384        let options = &self.options;
385        let resolve = tokio::time::timeout(options.timeout, self.network.resolve(host));
386        let (addresses, gateway, locations) = tokio::join!(
387            async { resolve.await.unwrap_or_default() },
388            self.network.gateway(),
389            self.ssdp.search(&SEARCH_TARGETS, options.search_time),
390        );
391        let mut candidates: Vec<(Url, Vec<Source>)> = Vec::new();
392        let at = |ip: IpAddr| probe(ip).then(|| base(SocketAddr::new(ip, options.port)));
393        let port = port.unwrap_or(options.port);
394        let found = (addresses
395            .iter()
396            .filter(|ip| probe(**ip))
397            .map(|ip| (base(SocketAddr::new(*ip, port)), Source::Config)))
398        .chain(gateway.and_then(at).map(|url| (url, Source::Gateway)))
399        .chain(
400            locations
401                .iter()
402                .filter_map(|l| location_base(l))
403                .map(|url| (url, Source::Ssdp)),
404        )
405        .chain(
406            options
407                .defaults
408                .iter()
409                .filter_map(|ip| at(*ip))
410                .map(|url| (url, Source::Default)),
411        );
412        for (url, source) in found {
413            match candidates.iter_mut().find(|(known, _)| *known == url) {
414                Some((_, sources)) if sources.contains(&source) => {}
415                Some((_, sources)) => sources.push(source),
416                None => candidates.push((url, vec![source])),
417            }
418        }
419        let mut tasks = JoinSet::new();
420        for (url, found_by) in candidates {
421            let timeout = options.timeout;
422            tasks.spawn(async move {
423                let device = verify(url, timeout).await?;
424                Some(Device { found_by, ..device })
425            });
426        }
427        let mut devices = Vec::new();
428        while let Some(result) = tasks.join_next().await {
429            if let Ok(Some(device)) = result {
430                merge(&mut devices, device);
431            }
432        }
433        devices.sort_by(|a, b| {
434            (a.role, &a.found_by, &a.address).cmp(&(b.role, &b.found_by, &b.address))
435        });
436        Report {
437            host: host.to_owned(),
438            local: !addresses.is_empty() && addresses.iter().all(|ip| is_local(*ip)),
439            addresses,
440            gateway,
441            devices,
442        }
443    }
444}
445
446/// Whether the address belongs to the local network: private, link-local
447/// or loopback.
448pub fn is_local(ip: IpAddr) -> bool {
449    match ip {
450        IpAddr::V4(ip) => ip.is_private() || ip.is_link_local() || ip.is_loopback(),
451        IpAddr::V6(ip) => ip.is_unique_local() || ip.is_unicast_link_local() || ip.is_loopback(),
452    }
453}
454
455/// Whether to ask the address for a description: a local address, but no
456/// IPv6 link-local one, which needs the interface in the URL.
457fn probe(ip: IpAddr) -> bool {
458    is_local(ip) && !matches!(ip, IpAddr::V6(ip) if ip.is_unicast_link_local())
459}
460
461/// The base URL of a device description.
462fn base(address: SocketAddr) -> Url {
463    Url::parse(&format!("http://{address}/")).expect("an IP address and a port form a URL")
464}
465
466/// The base URL of the device of an SSDP `LOCATION`, if it is an `http`
467/// URL with a local IP address.
468fn location_base(location: &str) -> Option<Url> {
469    let url = Url::parse(location)
470        .ok()
471        .filter(|url| url.scheme() == "http")?;
472    let host = url
473        .host_str()?
474        .trim_start_matches('[')
475        .trim_end_matches(']');
476    let ip: IpAddr = host.parse().ok()?;
477    let port = url.port_or_known_default()?;
478    probe(ip).then(|| base(SocketAddr::new(ip, port)))
479}
480
481/// Reads the description at `base`, without login, and keeps FRITZ!
482/// devices.
483async fn verify(base: Url, timeout: Duration) -> Option<Device> {
484    let client = Client::builder(base.clone())
485        .timeout(timeout)
486        .build()
487        .ok()?;
488    let xml = client.get("/tr64desc.xml").await;
489    let xml = xml
490        .inspect_err(|error| tracing::debug!(%base, %error, "no description"))
491        .ok()?;
492    describe(&base, &xml)
493}
494
495/// The device of a description, if it is a FRITZ! device with TR-064.
496fn describe(base: &Url, xml: &str) -> Option<Device> {
497    let description = DeviceDescription::parse(xml).ok()?;
498    let root = &description.device;
499    let manufacturer = root.manufacturer.as_deref().unwrap_or_default();
500    let model = root.model_name.as_deref().unwrap_or_default();
501    let fritz = manufacturer.contains("AVM")
502        || manufacturer.contains("FRITZ!")
503        || model.starts_with("FRITZ!");
504    if root.device_type != ROOT_DEVICE || !fritz {
505        return None;
506    }
507    let router = description
508        .devices()
509        .any(|device| device.device_type.contains(":WANDevice:"));
510    let host = base.host_str().unwrap_or_default();
511    let (address, host) = if base.port() == Some(HTTP_PORT) {
512        (host.to_owned(), host.to_owned())
513    } else {
514        let address = base
515            .as_str()
516            .trim_start_matches("http://")
517            .trim_end_matches('/');
518        (address.to_owned(), format!("http://{address}"))
519    };
520    Some(Device {
521        address,
522        host,
523        manufacturer: root.manufacturer.clone(),
524        model: root.model_name.clone(),
525        firmware: firmware(xml),
526        role: if router { Role::Router } else { Role::Repeater },
527        found_by: Vec::new(),
528        udn: root.udn.clone(),
529    })
530}
531
532/// The FRITZ!OS version of `<systemVersion><Display>`, like `8.25` of
533/// `285.08.25`, without the hardware number in front.
534fn firmware(xml: &str) -> Option<String> {
535    let document = roxmltree::Document::parse(xml).ok()?;
536    let display = child(child(document.root_element(), "systemVersion")?, "Display")?.text()?;
537    let (_, version) = display.trim().split_once('.')?;
538    Some(version.strip_prefix('0').unwrap_or(version).to_owned())
539}
540
541/// The first child element of `node` named `name`.
542fn child<'a, 'input>(
543    node: roxmltree::Node<'a, 'input>,
544    name: &str,
545) -> Option<roxmltree::Node<'a, 'input>> {
546    node.children().find(|child| child.has_tag_name(name))
547}
548
549/// Adds the device, or merges it into the same device found at another
550/// address, which keeps the address that was found the preferred way.
551fn merge(devices: &mut Vec<Device>, device: Device) {
552    let same = |known: &&mut Device| match (&known.udn, &device.udn) {
553        (Some(a), Some(b)) => a == b && known.model == device.model,
554        _ => known.address == device.address,
555    };
556    let Some(known) = devices.iter_mut().find(same) else {
557        devices.push(device);
558        return;
559    };
560    if device.found_by < known.found_by {
561        known.address.clone_from(&device.address);
562        known.host.clone_from(&device.host);
563    }
564    known.found_by.extend(device.found_by);
565    known.found_by.sort();
566    known.found_by.dedup();
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572
573    #[test]
574    fn finds_the_default_gateway_in_the_routing_tables() {
575        let linux = "Iface\tDestination\tGateway \tFlags\n\
576                     eth0\t0000A8C0\t00000000\t0001\n\
577                     eth0\t00000000\t01B2A8C0\t0003\n";
578        assert_eq!(linux_gateway(linux), Some("192.168.178.1".parse().unwrap()));
579        assert_eq!(linux_gateway("Iface\tDestination\tGateway\n"), None);
580        assert_eq!(linux_gateway("h\neth0\t00000000\t00000000\n"), None);
581
582        let bsd = "   route to: default\ndestination: default\n    gateway: 192.168.178.1\n";
583        assert_eq!(bsd_gateway(bsd), Some("192.168.178.1".parse().unwrap()));
584        assert_eq!(
585            bsd_gateway("route: writing to routing socket: not in table"),
586            None
587        );
588
589        let windows = "Active Routes:\nNetwork Destination        Netmask          Gateway       Interface  Metric\n          0.0.0.0          0.0.0.0    192.168.178.1  192.168.178.20     25\n";
590        assert_eq!(
591            windows_gateway(windows),
592            Some("192.168.178.1".parse().unwrap())
593        );
594        assert_eq!(windows_gateway("none"), None);
595    }
596
597    #[test]
598    fn reads_the_location_of_ssdp_answers() {
599        let answer = b"HTTP/1.1 200 OK\r\nST: x\r\nLocation: http://192.168.178.1:49000/tr64desc.xml\r\n\r\n";
600        assert_eq!(
601            location(answer).as_deref(),
602            Some("http://192.168.178.1:49000/tr64desc.xml")
603        );
604        assert_eq!(location(b"HTTP/1.1 200 OK\r\n\r\n"), None);
605    }
606
607    #[test]
608    fn takes_only_local_addresses() {
609        for local in [
610            "192.168.1.1",
611            "10.0.0.1",
612            "169.254.1.1",
613            "127.0.0.1",
614            "fd00::1",
615            "::1",
616            "fe80::1",
617        ] {
618            assert!(is_local(local.parse().unwrap()), "{local}");
619        }
620        for public in ["203.0.113.1", "2001:db8::1", "100.64.0.1"] {
621            assert!(!is_local(public.parse().unwrap()), "{public}");
622        }
623        assert!(!probe("fe80::1".parse().unwrap()));
624        assert_eq!(
625            location_base("http://192.168.178.30:49000/tr64desc.xml").map(String::from),
626            Some("http://192.168.178.30:49000/".to_owned())
627        );
628        assert_eq!(
629            location_base("http://[fd00::1]/igd.xml").map(String::from),
630            Some("http://[fd00::1]/".to_owned())
631        );
632        for rejected in [
633            "https://192.168.178.1:49443/tr64desc.xml",
634            "http://203.0.113.1:49000/tr64desc.xml",
635            "http://fritz.box:49000/tr64desc.xml",
636            "not a URL",
637        ] {
638            assert_eq!(location_base(rejected), None, "{rejected}");
639        }
640    }
641
642    #[test]
643    fn reads_the_firmware_without_the_hardware_number() {
644        let xml = "<root><systemVersion><Display>285.08.25</Display></systemVersion></root>";
645        assert_eq!(firmware(xml).as_deref(), Some("8.25"));
646        let xml = "<root><systemVersion><Display>285.10.01</Display></systemVersion></root>";
647        assert_eq!(firmware(xml).as_deref(), Some("10.01"));
648        assert_eq!(firmware("<root/>"), None);
649        assert_eq!(firmware("<root>"), None);
650    }
651
652    #[test]
653    fn names_sources_and_roles() {
654        let names: Vec<String> = [
655            Source::Config,
656            Source::Gateway,
657            Source::Ssdp,
658            Source::Default,
659        ]
660        .iter()
661        .map(ToString::to_string)
662        .collect();
663        assert_eq!(names, ["config", "gateway", "ssdp", "default"]);
664        assert_eq!(Role::Router.to_string(), "router");
665        assert_eq!(Role::Repeater.to_string(), "repeater");
666    }
667
668    const DESCRIPTION: &str = include_str!(concat!(
669        env!("CARGO_MANIFEST_DIR"),
670        "/../fritz-sim/fixtures/fritzbox-7690/8.25/tr64desc.xml"
671    ));
672
673    fn found(base: &str, source: Source, udn: Option<&str>) -> Device {
674        let mut device = describe(&base.parse().unwrap(), DESCRIPTION).unwrap();
675        device.found_by = vec![source];
676        device.udn = udn.map(str::to_owned);
677        device
678    }
679
680    #[test]
681    fn merges_the_same_device_found_twice() {
682        let ssdp = found("http://192.168.178.1:49000/", Source::Ssdp, Some("uuid:1"));
683        assert_eq!(
684            (ssdp.address.as_str(), ssdp.host.as_str()),
685            ("192.168.178.1", "192.168.178.1")
686        );
687        let gateway = found("http://10.0.0.1:49000/", Source::Gateway, Some("uuid:1"));
688        let other = found("http://10.0.0.2:49000/", Source::Default, Some("uuid:2"));
689        let unnamed = found("http://10.0.0.3:49000/", Source::Default, None);
690        let again = found("http://10.0.0.3:49000/", Source::Ssdp, None);
691        let mut devices = Vec::new();
692        for device in [ssdp, gateway, other, unnamed, again] {
693            merge(&mut devices, device);
694        }
695        let merged: Vec<(&str, &[Source])> = devices
696            .iter()
697            .map(|device| (device.address.as_str(), device.found_by.as_slice()))
698            .collect();
699        assert_eq!(
700            merged,
701            [
702                ("10.0.0.1", &[Source::Gateway, Source::Ssdp][..]),
703                ("10.0.0.2", &[Source::Default][..]),
704                ("10.0.0.3", &[Source::Ssdp, Source::Default][..]),
705            ]
706        );
707        assert_eq!(devices[0].host, "10.0.0.1");
708    }
709
710    #[test]
711    fn looks_on_the_local_network_by_default() {
712        let discovery = Discovery::system();
713        assert_eq!(discovery.ssdp.target, SSDP_ADDRESS);
714        assert_eq!(discovery.options.port, 49000);
715        assert_eq!(discovery.options.defaults, DEFAULT_ADDRESSES);
716    }
717}