Skip to main content

fritz_core/
host.rs

1//! One host, found by its MAC or IP address or by its name, with all the
2//! device knows about it: the entry of the host, the host list and the mesh.
3//!
4//! Addresses are checked before they are sent. Host names are untrusted
5//! strings.
6
7use std::collections::HashMap;
8use std::fmt;
9use std::net::Ipv4Addr;
10
11use serde::Serialize;
12use serde_json::Value;
13
14use crate::generic::Error;
15use crate::lists::{self, Branch};
16use crate::read::{Reader, Values};
17use crate::session::{self, Session};
18use crate::settings;
19use crate::status::{self, Host};
20
21/// What a host is looked up by: an address the device can look up itself.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Lookup {
24    /// A MAC address in capitals, separated by colons.
25    Mac(String),
26    Ip(Ipv4Addr),
27}
28
29/// An address that is not valid, refused before anything is sent.
30#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31pub enum InvalidAddress {
32    #[error("{0:?} is not a MAC address like AA:BB:CC:DD:EE:FF")]
33    Mac(String),
34    #[error("{0:?} is not an IPv4 address like 192.168.178.23")]
35    Ip(String),
36}
37
38impl Lookup {
39    /// A lookup by MAC address: six pairs of hex digits, separated by
40    /// colons or dashes, in any case.
41    ///
42    /// # Errors
43    ///
44    /// [`InvalidAddress::Mac`] for anything else.
45    pub fn mac(text: &str) -> Result<Self, InvalidAddress> {
46        let parts: Vec<&str> = text.split([':', '-']).collect();
47        let valid = parts.len() == 6
48            && parts
49                .iter()
50                .all(|p| p.len() == 2 && p.chars().all(|c| c.is_ascii_hexdigit()));
51        if valid {
52            Ok(Self::Mac(parts.join(":").to_ascii_uppercase()))
53        } else {
54            Err(InvalidAddress::Mac(text.to_owned()))
55        }
56    }
57
58    /// A lookup by IPv4 address, the only kind the device looks up.
59    ///
60    /// # Errors
61    ///
62    /// [`InvalidAddress::Ip`] for anything else.
63    pub fn ip(text: &str) -> Result<Self, InvalidAddress> {
64        text.parse()
65            .map(Self::Ip)
66            .map_err(|_| InvalidAddress::Ip(text.to_owned()))
67    }
68
69    /// Whether `host` has this address.
70    fn matches(&self, host: &Host) -> bool {
71        match self {
72            Self::Mac(mac) => host
73                .mac
74                .as_deref()
75                .is_some_and(|m| m.eq_ignore_ascii_case(mac)),
76            Self::Ip(ip) => host.ip.as_deref() == Some(ip.to_string().as_str()),
77        }
78    }
79}
80
81impl fmt::Display for Lookup {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::Mac(mac) => write!(f, "the MAC address {mac}"),
85            Self::Ip(ip) => write!(f, "the IP address {ip}"),
86        }
87    }
88}
89
90/// A host with all the device knows about it.
91#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
92pub struct Detail {
93    #[serde(flatten)]
94    pub host: Host,
95    /// The seconds until the lease of the address ends. Left out if the
96    /// device reports none.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub lease_remaining: Option<u64>,
99    /// The mesh node the host is connected to, if the mesh list names one.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub attached_to: Option<Attachment>,
102}
103
104/// How a host is connected to a node of the mesh.
105#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
106pub struct Attachment {
107    /// The name of the node.
108    pub node: Option<String>,
109    /// Like `LAN` or `WLAN`.
110    pub kind: Option<String>,
111    /// The interface the mesh list names for the link, like `AP:5G:0`.
112    pub interface: Option<String>,
113    /// The band of a wireless link, like `5 GHz`.
114    pub band: Option<String>,
115    /// The current rates towards the host and back, in kbit/s.
116    pub rate_down: Option<u64>,
117    pub rate_up: Option<u64>,
118}
119
120/// Looks up the host with an address: its item in the host list, its entry,
121/// which the device looks up by the MAC address, and its link in the mesh.
122/// For an IP address, the device first names the MAC address of the host.
123/// `None` if neither the entries nor the host list have it.
124///
125/// # Errors
126///
127/// The errors of reading other than missing parts, see
128/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a list that
129/// cannot be parsed.
130pub async fn lookup(reader: &mut Reader, lookup: &Lookup) -> Result<Option<Detail>, Error> {
131    let by_ip = match lookup {
132        Lookup::Mac(_) => None,
133        Lookup::Ip(ip) => {
134            let ip = ip.to_string();
135            let input = [("NewIPAddress", ip.as_str())];
136            reader
137                .try_read("Hosts1", "X_AVM-DE_GetSpecificHostEntryByIP", &input)
138                .await?
139        }
140    };
141    let listed = host_list(reader)
142        .await?
143        .into_iter()
144        .find(|h| lookup.matches(h));
145    let found = listed.is_some() || by_ip.is_some();
146    let mut host = listed.unwrap_or_default();
147    match lookup {
148        Lookup::Mac(mac) => host.mac = host.mac.or_else(|| Some(mac.clone())),
149        Lookup::Ip(ip) => host.ip = host.ip.or_else(|| Some(ip.to_string())),
150    }
151    let host = match &by_ip {
152        Some(by_ip) => overlay(host, by_ip),
153        None => host,
154    };
155    let entry = entry(reader, host.mac.as_deref()).await?;
156    if !found && entry.is_none() {
157        return Ok(None);
158    }
159    Ok(Some(complete(reader, host, entry.as_ref()).await?))
160}
161
162/// The details of a host from the host list: its entry, which the device
163/// looks up by its MAC address, and its link in the mesh.
164///
165/// # Errors
166///
167/// Like [`lookup`].
168pub async fn detail(reader: &mut Reader, host: Host) -> Result<Detail, Error> {
169    let entry = entry(reader, host.mac.as_deref()).await?;
170    complete(reader, host, entry.as_ref()).await
171}
172
173/// The entry of the host with the MAC address `mac`, if the device has one.
174async fn entry(reader: &mut Reader, mac: Option<&str>) -> Result<Option<Values>, Error> {
175    let Some(mac) = mac else { return Ok(None) };
176    let input = [("NewMACAddress", mac)];
177    reader
178        .try_read("Hosts1", "GetSpecificHostEntry", &input)
179        .await
180}
181
182/// The host with the values of its entry, and its link in the mesh.
183async fn complete(
184    reader: &mut Reader,
185    host: Host,
186    entry: Option<&Values>,
187) -> Result<Detail, Error> {
188    let host = match entry {
189        Some(entry) => overlay(host, entry),
190        None => host,
191    };
192    let lease_remaining = entry
193        .and_then(|e| e.number("NewLeaseTimeRemaining"))
194        .filter(|seconds| *seconds > 0);
195    let attached_to = match &host.mac {
196        Some(mac) => status::mesh(reader)
197            .await?
198            .and_then(|mesh| attachment(&mesh.tree(), mac)),
199        None => None,
200    };
201    Ok(Detail {
202        host,
203        lease_remaining,
204        attached_to,
205    })
206}
207
208/// The hosts of the host list, or none if the device has no host list.
209async fn host_list(reader: &mut Reader) -> Result<Vec<Host>, Error> {
210    let xml = reader
211        .document(
212            "Hosts1",
213            "X_AVM-DE_GetHostListPath",
214            "NewX_AVM-DE_HostListPath",
215        )
216        .await?;
217    xml.map_or_else(|| Ok(Vec::new()), |xml| lists::hosts(&xml))
218}
219
220/// The host with the values the entry has.
221fn overlay(host: Host, entry: &Values) -> Host {
222    let text = |name: &str| entry.text(name);
223    Host {
224        name: text("NewHostName").or(host.name),
225        ip: text("NewIPAddress").or(host.ip),
226        mac: text("NewMACAddress").or(host.mac),
227        active: entry.flag("NewActive").unwrap_or(host.active),
228        interface: text("NewInterfaceType").or(host.interface),
229        address_source: text("NewAddressSource").or(host.address_source),
230        permanent_address: host.permanent_address,
231        last_seen: host.last_seen,
232        guest: entry.flag("NewX_AVM-DE_Guest").or(host.guest),
233        internet_access: text("NewX_AVM-DE_WANAccess").or(host.internet_access),
234        speed: entry
235            .number("NewX_AVM-DE_Speed")
236            .filter(|speed| *speed > 0)
237            .or(host.speed),
238    }
239}
240
241/// The node above the device with the MAC address `mac` in the tree of the
242/// mesh, and the link between them.
243fn attachment(branches: &[Branch], mac: &str) -> Option<Attachment> {
244    branches.iter().find_map(|parent| {
245        parent
246            .children
247            .iter()
248            .find(|child| (child.node.mac.as_deref()).is_some_and(|m| m.eq_ignore_ascii_case(mac)))
249            .map(|child| {
250                let uplink = child.uplinks.first().cloned().unwrap_or_default();
251                Attachment {
252                    node: parent.node.name.clone(),
253                    band: uplink.interface.as_deref().and_then(band),
254                    kind: uplink.kind,
255                    interface: uplink.interface,
256                    rate_down: uplink.rate_down,
257                    rate_up: uplink.rate_up,
258                }
259            })
260            .or_else(|| attachment(&parent.children, mac))
261    })
262}
263
264/// The band of a wireless interface like `AP:5G:0`.
265fn band(interface: &str) -> Option<String> {
266    interface.split(':').find_map(|part| match part {
267        "2G" => Some("2.4 GHz".to_owned()),
268        "5G" => Some("5 GHz".to_owned()),
269        "6G" => Some("6 GHz".to_owned()),
270        _ => None,
271    })
272}
273
274/// The hosts named `name`, ignoring case: those with exactly this name, or
275/// if there are none, those whose name contains it.
276#[must_use]
277pub fn named(hosts: Vec<Host>, name: &str) -> Vec<Host> {
278    let name = name.to_lowercase();
279    let lower = |host: &Host| host.name.as_deref().map(str::to_lowercase);
280    let (exact, rest): (Vec<Host>, Vec<Host>) = hosts
281        .into_iter()
282        .partition(|h| lower(h).as_deref() == Some(name.as_str()));
283    if exact.is_empty() {
284        rest.into_iter()
285            .filter(|h| lower(h).is_some_and(|n| n.contains(&name)))
286            .collect()
287    } else {
288        exact
289    }
290}
291
292/// Whether the name, IP or MAC address of `host` contains `text`, ignoring
293/// case.
294#[must_use]
295pub fn contains(host: &Host, text: &str) -> bool {
296    let text = text.to_lowercase();
297    [&host.name, &host.ip, &host.mac]
298        .into_iter()
299        .flatten()
300        .any(|v| v.to_lowercase().contains(&text))
301}
302
303/// Adds how the `hosts` got their addresses from the LAN devices of the web
304/// interface, in one request: the address source where it is missing,
305/// whether the address is reserved for the host permanently and when the
306/// host was last connected, which TR-064 does not tell. Hosts the web
307/// interface does not list stay as they are.
308///
309/// # Errors
310///
311/// The errors of reading the module `landevice`.
312pub async fn add_addressing(session: &Session, hosts: &mut [Host]) -> Result<(), session::Error> {
313    let devices = settings::module(session, "landevice").await?;
314    addressing(&devices, hosts);
315    Ok(())
316}
317
318/// Adds the addressing of the LAN `devices`, matched by MAC address, to the
319/// `hosts`; see [`add_addressing`].
320pub fn addressing(devices: &Value, hosts: &mut [Host]) {
321    let flag = |device: &Value, name: &str| match device.get(name).and_then(Value::as_str) {
322        Some("1") => Some(true),
323        Some("0") => Some(false),
324        _ => None,
325    };
326    let by_mac: HashMap<String, &Value> = devices
327        .get("landevice")
328        .and_then(Value::as_array)
329        .into_iter()
330        .flatten()
331        .filter_map(|d| Some((d.get("mac")?.as_str()?.to_ascii_uppercase(), d)))
332        .collect();
333    for host in hosts {
334        let Some(device) = host
335            .mac
336            .as_deref()
337            .and_then(|mac| by_mac.get(&mac.to_ascii_uppercase()))
338        else {
339            continue;
340        };
341        if host.address_source.is_none() {
342            host.address_source =
343                flag(device, "dhcp").map(|dhcp| if dhcp { "DHCP" } else { "Static" }.to_owned());
344        }
345        host.permanent_address = flag(device, "static_dhcp");
346        // In seconds since the Unix epoch, 0 if the device does not know.
347        host.last_seen = device
348            .get("lastused")
349            .and_then(Value::as_str)
350            .and_then(|s| s.parse::<i64>().ok())
351            .filter(|&s| s > 0)
352            .map(utc);
353    }
354}
355
356/// The time `seconds` after the Unix epoch, in UTC, like
357/// `2026-11-20T18:05:42Z`.
358fn utc(seconds: i64) -> String {
359    let (days, time) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
360    // The civil date of a day count; see
361    // <https://howardhinnant.github.io/date_algorithms.html#civil_from_days>.
362    let z = days + 719_468;
363    let era = z.div_euclid(146_097);
364    let doe = z.rem_euclid(146_097);
365    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
366    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
367    let mp = (5 * doy + 2) / 153;
368    let day = doy - (153 * mp + 2) / 5 + 1;
369    let month = if mp < 10 { mp + 3 } else { mp - 9 };
370    let year = yoe + era * 400 + i64::from(month <= 2);
371    format!(
372        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
373        time / 3600,
374        time / 60 % 60,
375        time % 60
376    )
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    fn host(name: &str) -> Host {
384        Host {
385            name: Some(name.to_owned()),
386            ..Host::default()
387        }
388    }
389
390    #[test]
391    fn checks_addresses() {
392        assert_eq!(
393            Lookup::mac("aa-bb-cc-00-00-0f"),
394            Ok(Lookup::Mac("AA:BB:CC:00:00:0F".to_owned()))
395        );
396        for invalid in [
397            "",
398            "AA:BB:CC:00:00",
399            "AA:BB:CC:00:00:0G",
400            "AAB:B:CC:00:00:01",
401        ] {
402            assert_eq!(
403                Lookup::mac(invalid),
404                Err(InvalidAddress::Mac(invalid.to_owned()))
405            );
406        }
407        assert_eq!(
408            Lookup::ip("192.0.2.1"),
409            Ok(Lookup::Ip(Ipv4Addr::new(192, 0, 2, 1)))
410        );
411        let error = Lookup::ip("2001:db8::1").unwrap_err();
412        assert_eq!(
413            error.to_string(),
414            "\"2001:db8::1\" is not an IPv4 address like 192.168.178.23"
415        );
416        assert_eq!(
417            Lookup::mac("x").unwrap_err().to_string(),
418            "\"x\" is not a MAC address like AA:BB:CC:DD:EE:FF"
419        );
420        assert_eq!(
421            Lookup::Ip(Ipv4Addr::new(192, 0, 2, 1)).to_string(),
422            "the IP address 192.0.2.1"
423        );
424        assert_eq!(
425            Lookup::Mac("AA:BB:CC:00:00:01".to_owned()).to_string(),
426            "the MAC address AA:BB:CC:00:00:01"
427        );
428    }
429
430    #[test]
431    fn finds_hosts_by_name() {
432        let hosts = || {
433            vec![
434                host("device-1"),
435                host("Device-11"),
436                host("device-11"),
437                Host::default(),
438            ]
439        };
440        assert_eq!(named(hosts(), "DEVICE-1"), vec![host("device-1")]);
441        assert_eq!(named(hosts(), "device-11").len(), 2);
442        assert_eq!(named(hosts(), "ice-1").len(), 3);
443        assert_eq!(named(hosts(), "printer"), Vec::<Host>::new());
444    }
445
446    #[test]
447    fn searches_names_and_addresses() {
448        let host = Host {
449            name: Some("Laptop".to_owned()),
450            ip: Some("192.0.2.10".to_owned()),
451            mac: Some("AA:BB:CC:00:00:0A".to_owned()),
452            ..Host::default()
453        };
454        assert!(contains(&host, "lap"));
455        assert!(contains(&host, "2.10"));
456        assert!(contains(&host, "00:0a"));
457        assert!(!contains(&host, "phone"));
458    }
459
460    #[test]
461    fn names_bands() {
462        assert_eq!(band("AP:2G:0").as_deref(), Some("2.4 GHz"));
463        assert_eq!(band("UPLINK:6G:0").as_deref(), Some("6 GHz"));
464        assert_eq!(band("AP:5G:1").as_deref(), Some("5 GHz"));
465        assert_eq!(band("LAN:1"), None);
466    }
467
468    #[test]
469    fn formats_times_in_utc() {
470        assert_eq!(utc(0), "1970-01-01T00:00:00Z");
471        assert_eq!(utc(1_709_251_199), "2024-02-29T23:59:59Z");
472        assert_eq!(utc(1_767_225_600), "2026-01-01T00:00:00Z");
473        assert_eq!(utc(-1), "1969-12-31T23:59:59Z");
474    }
475
476    #[test]
477    fn adds_the_addressing_of_lan_devices() {
478        let with_mac = |mac: &str, source: Option<&str>| Host {
479            mac: Some(mac.to_owned()),
480            address_source: source.map(str::to_owned),
481            ..Host::default()
482        };
483        let mut hosts = [
484            with_mac("AA:BB:CC:00:00:01", None),
485            with_mac("aa:bb:cc:00:00:02", None),
486            // The entry of the host wins over the web interface.
487            with_mac("AA:BB:CC:00:00:03", Some("DHCP")),
488            // Unknown values are left out.
489            with_mac("AA:BB:CC:00:00:04", None),
490            // Not a LAN device.
491            with_mac("AA:BB:CC:00:00:05", None),
492            Host::default(),
493        ];
494        let devices = serde_json::json!({"landevice": [
495            {"mac": "aa:bb:cc:00:00:01", "dhcp": "1", "static_dhcp": "1", "lastused": "1795716342"},
496            {"mac": "AA:BB:CC:00:00:02", "dhcp": "0", "static_dhcp": "0", "lastused": "0"},
497            {"mac": "AA:BB:CC:00:00:03", "dhcp": "0", "static_dhcp": "0", "lastused": "951782400"},
498            {"mac": "AA:BB:CC:00:00:04", "dhcp": "", "static_dhcp": 1, "lastused": "x"},
499            {"name": "no MAC", "dhcp": "1"},
500        ]});
501        addressing(&devices, &mut hosts);
502        let found: Vec<_> = hosts
503            .iter()
504            .map(|h| {
505                (
506                    h.address_source.as_deref(),
507                    h.permanent_address,
508                    h.last_seen.as_deref(),
509                )
510            })
511            .collect();
512        assert_eq!(
513            found,
514            [
515                (Some("DHCP"), Some(true), Some("2026-11-26T18:05:42Z")),
516                (Some("Static"), Some(false), None),
517                (Some("DHCP"), Some(false), Some("2000-02-29T00:00:00Z")),
518                (None, None, None),
519                (None, None, None),
520                (None, None, None),
521            ]
522        );
523
524        // Without the list, nothing changes.
525        let before = hosts.clone();
526        addressing(&serde_json::json!({}), &mut hosts);
527        assert_eq!(hosts, before);
528    }
529}