1use 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
27pub const ROOT_DEVICE: &str = "urn:dslforum-org:device:InternetGatewayDevice:1";
30
31pub const SEARCH_TARGETS: [&str; 2] = [ROOT_DEVICE, "urn:dslforum-org:device:LANDevice:1"];
34
35pub const SSDP_ADDRESS: SocketAddr =
37 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(239, 255, 255, 250)), 1900);
38
39pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum Source {
51 Config,
53 Gateway,
55 Ssdp,
57 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
74#[serde(rename_all = "lowercase")]
75pub enum Role {
76 Router,
78 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct Device {
94 pub address: String,
96 pub host: String,
99 pub manufacturer: Option<String>,
101 pub model: Option<String>,
103 pub firmware: Option<String>,
105 pub role: Role,
107 pub found_by: Vec<Source>,
109 #[serde(skip)]
112 udn: Option<String>,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
117pub struct Report {
118 pub host: String,
120 pub addresses: Vec<IpAddr>,
122 pub local: bool,
124 pub gateway: Option<IpAddr>,
126 pub devices: Vec<Device>,
128}
129
130pub trait Resolver {
132 fn resolve(&self, host: &str) -> impl Future<Output = Vec<IpAddr>> + Send;
134}
135
136pub trait Gateway {
138 fn gateway(&self) -> impl Future<Output = Option<IpAddr>> + Send;
140}
141
142pub trait Ssdp {
144 fn search(&self, targets: &[&str], time: Duration) -> impl Future<Output = Vec<String>> + Send;
147}
148
149#[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#[cfg(target_os = "linux")]
176fn default_gateway() -> Option<IpAddr> {
177 linux_gateway(&std::fs::read_to_string("/proc/net/route").ok()?)
178}
179
180#[cfg(windows)]
182fn default_gateway() -> Option<IpAddr> {
183 let output = route(&["print", "-4", "0.0.0.0"])?;
184 windows_gateway(&output)
185}
186
187#[cfg(not(any(target_os = "linux", windows)))]
189fn default_gateway() -> Option<IpAddr> {
190 bsd_gateway(&route(&["-n", "get", "default"])?)
191}
192
193#[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#[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#[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#[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#[derive(Debug, Clone, Copy)]
239pub struct Multicast {
240 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 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
290fn 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#[derive(Debug, Clone, Default)]
302pub struct Fixed {
303 pub addresses: Vec<IpAddr>,
305 pub gateway: Option<IpAddr>,
307 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#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct Options {
336 pub port: u16,
339 pub defaults: Vec<IpAddr>,
341 pub search_time: Duration,
343 pub timeout: Duration,
345}
346
347impl Default for Options {
348 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#[derive(Debug, Clone, Default)]
362pub struct Discovery<N, S> {
363 pub network: N,
365 pub ssdp: S,
367 pub options: Options,
369}
370
371impl Discovery<System, Multicast> {
372 pub fn system() -> Self {
374 Self::default()
375 }
376}
377
378impl<N: Resolver + Gateway, S: Ssdp> Discovery<N, S> {
379 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
446pub 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
455fn probe(ip: IpAddr) -> bool {
458 is_local(ip) && !matches!(ip, IpAddr::V6(ip) if ip.is_unicast_link_local())
459}
460
461fn base(address: SocketAddr) -> Url {
463 Url::parse(&format!("http://{address}/")).expect("an IP address and a port form a URL")
464}
465
466fn 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
481async 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
495fn 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
532fn 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
541fn 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
549fn 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}