Skip to main content

fritz_core/
lists.rs

1//! The list documents of a device, fetched at the paths actions like
2//! `X_AVM-DE_GetHostListPath` return: the hosts as XML and the mesh as
3//! JSON.
4
5use std::collections::{HashMap, HashSet};
6use std::str::FromStr;
7
8use serde::Serialize;
9use serde_json::Value;
10
11use crate::generic::Error;
12use crate::status::Host;
13
14mod tree;
15
16pub use tree::{Branch, Uplink};
17
18/// The mesh: the devices and how they are connected.
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct Mesh {
21    pub nodes: Vec<Node>,
22    pub links: Vec<Link>,
23}
24
25/// A device in the mesh: a FRITZ! device or a host.
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
27pub struct Node {
28    /// The id of the node in the mesh list, which links refer to.
29    #[serde(skip)]
30    pub uid: String,
31    pub name: Option<String>,
32    pub model: Option<String>,
33    pub mac: Option<String>,
34    /// Like `master` for the device that leads the mesh, or `slave`.
35    pub role: Option<String>,
36    /// Whether the node is part of the mesh, rather than a host connected to
37    /// it.
38    pub meshed: bool,
39    /// The IPv4 address of the node, from the host list, or for the device
40    /// that leads the mesh from its LAN settings. `None` if unknown.
41    pub ip: Option<String>,
42    /// Whether the host the address is from is active. An inactive host
43    /// keeps its last address, which the device may give to another host.
44    /// `None` if the address is not from the host list.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub active: Option<bool>,
47    /// The MAC addresses of the node and of all its interfaces.
48    #[serde(skip)]
49    pub macs: Vec<String>,
50}
51
52/// A connection between two nodes.
53#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
54pub struct Link {
55    /// The name of a node, or its id if it has no name.
56    pub from: String,
57    pub to: String,
58    /// The ids of the nodes `from` and `to`.
59    #[serde(skip)]
60    pub from_uid: String,
61    #[serde(skip)]
62    pub to_uid: String,
63    /// Like `LAN` or `WLAN`.
64    pub kind: Option<String>,
65    /// The interface of `from`, like `AP:5G:0`.
66    pub interface: Option<String>,
67    /// Like `CONNECTED`.
68    pub state: Option<String>,
69    /// The current rates, in kbit/s.
70    pub rate_rx: Option<u64>,
71    pub rate_tx: Option<u64>,
72    /// The highest rates, in kbit/s.
73    pub max_rx: Option<u64>,
74    pub max_tx: Option<u64>,
75}
76
77impl Mesh {
78    /// Adds the IP addresses of the `hosts` to the nodes, joined by the MAC
79    /// addresses of the nodes and their interfaces, in any case and with
80    /// any separator. An active host is preferred over an inactive one. The
81    /// device that leads the mesh is rarely a host of its own; without a
82    /// host it gets the address `router`.
83    pub fn add_addresses(&mut self, hosts: &[Host], router: Option<&str>) {
84        for node in &mut self.nodes {
85            let macs: HashSet<String> = node.macs.iter().map(|m| normal_mac(m)).collect();
86            let host = hosts
87                .iter()
88                .filter(|h| h.ip.is_some())
89                .filter(|h| {
90                    h.mac
91                        .as_deref()
92                        .is_some_and(|m| macs.contains(&normal_mac(m)))
93                })
94                .reduce(|found, h| if !found.active && h.active { h } else { found });
95            if let Some(host) = host {
96                node.ip.clone_from(&host.ip);
97                node.active = Some(host.active);
98            } else if node.role.as_deref() == Some("master") {
99                node.ip = router.map(str::to_owned);
100            }
101        }
102    }
103}
104
105/// A MAC address in upper case, without separators.
106pub(crate) fn normal_mac(mac: &str) -> String {
107    mac.chars()
108        .filter(char::is_ascii_hexdigit)
109        .map(|c| c.to_ascii_uppercase())
110        .collect()
111}
112
113/// The fields of an item of an XML list, by tag name, trimmed.
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct Item(pub HashMap<String, String>);
116
117impl Item {
118    /// The text of a field, unless it is empty.
119    pub fn text(&self, name: &str) -> Option<String> {
120        self.0.get(name).filter(|v| !v.is_empty()).cloned()
121    }
122
123    /// A field as a number, if it is one.
124    pub fn number<T: FromStr>(&self, name: &str) -> Option<T> {
125        self.0.get(name).and_then(|v| v.parse().ok())
126    }
127
128    /// Whether a field is `1`, if it is there.
129    pub fn flag(&self, name: &str) -> Option<bool> {
130        self.0.get(name).map(|v| v == "1")
131    }
132}
133
134/// Parses an XML list whose root is named `root` into its items: the
135/// children named `item`, like `<List><Item><Name>…</Name></Item></List>`.
136/// Other children of the root are skipped.
137///
138/// # Errors
139///
140/// [`Error::InvalidDocument`], naming the `document`, if it is not such a
141/// list.
142pub fn items(
143    xml: &str,
144    document: &'static str,
145    root: &str,
146    item: &str,
147) -> Result<Vec<Item>, Error> {
148    let invalid = |reason: String| Error::InvalidDocument { document, reason };
149    let parsed = roxmltree::Document::parse(xml).map_err(|e| invalid(e.to_string()))?;
150    let element = parsed.root_element();
151    if element.tag_name().name() != root {
152        return Err(invalid(format!(
153            "the root is {}, not {root}",
154            element.tag_name().name()
155        )));
156    }
157    Ok(element
158        .children()
159        .filter(|n| n.has_tag_name(item))
160        .map(|node| {
161            Item(
162                node.children()
163                    .filter(roxmltree::Node::is_element)
164                    .map(|f| {
165                        let text = f.text().unwrap_or_default().trim();
166                        (f.tag_name().name().to_owned(), text.to_owned())
167                    })
168                    .collect(),
169            )
170        })
171        .collect())
172}
173
174/// Parses the host list: `<List><Item><HostName>…</HostName>…</Item></List>`.
175///
176/// # Errors
177///
178/// [`Error::InvalidDocument`] if it is not such a list.
179pub fn hosts(xml: &str) -> Result<Vec<Host>, Error> {
180    Ok(items(xml, "host list", "List", "Item")?
181        .into_iter()
182        .map(|item| Host {
183            name: item.text("HostName"),
184            ip: item.text("IPAddress"),
185            mac: item.text("MACAddress"),
186            active: item.flag("Active").unwrap_or_default(),
187            interface: item.text("InterfaceType"),
188            address_source: item.text("AddressSource"),
189            guest: item.flag("X_AVM-DE_Guest"),
190            internet_access: item.text("X_AVM-DE_WANAccess"),
191            speed: item.number("X_AVM-DE_Speed"),
192            permanent_address: None,
193            last_seen: None,
194        })
195        .collect())
196}
197
198/// Parses the mesh list: `{"nodes": [{"node_interfaces": [{"node_links":
199/// […]}]}]}`. A link is listed at both of its ends, but returned once.
200///
201/// # Errors
202///
203/// [`Error::InvalidDocument`] if it is not such a list.
204pub fn mesh(json: &str) -> Result<Mesh, Error> {
205    let invalid = |reason: String| Error::InvalidDocument {
206        document: "mesh list",
207        reason,
208    };
209    let value: Value = serde_json::from_str(json).map_err(|e| invalid(e.to_string()))?;
210    let nodes = value["nodes"]
211        .as_array()
212        .ok_or_else(|| invalid("it has no nodes".to_owned()))?;
213    let text = |value: &Value| value.as_str().filter(|v| !v.is_empty()).map(str::to_owned);
214    let interfaces = |node: &'_ Value| -> Vec<Value> {
215        node["node_interfaces"]
216            .as_array()
217            .cloned()
218            .unwrap_or_default()
219    };
220    let mut names = HashMap::new();
221    let mut interface_names = HashMap::new();
222    for node in nodes {
223        let uid = node["uid"].as_str().unwrap_or_default();
224        let name = text(&node["device_name"]).unwrap_or_else(|| uid.to_owned());
225        names.insert(uid.to_owned(), name);
226        for interface in interfaces(node) {
227            if let (Some(uid), Some(name)) = (interface["uid"].as_str(), text(&interface["name"])) {
228                interface_names.insert(uid.to_owned(), name);
229            }
230        }
231    }
232    let name = |uid: &Value| {
233        let uid = uid.as_str().unwrap_or_default();
234        names.get(uid).cloned().unwrap_or_else(|| uid.to_owned())
235    };
236    let mut seen = HashSet::new();
237    let mut links = Vec::new();
238    for node in nodes {
239        for interface in interfaces(node) {
240            for link in interface["node_links"].as_array().into_iter().flatten() {
241                if !seen.insert(link["uid"].as_str().unwrap_or_default().to_owned()) {
242                    continue;
243                }
244                links.push(Link {
245                    from: name(&link["node_1_uid"]),
246                    to: name(&link["node_2_uid"]),
247                    from_uid: link["node_1_uid"].as_str().unwrap_or_default().to_owned(),
248                    to_uid: link["node_2_uid"].as_str().unwrap_or_default().to_owned(),
249                    kind: text(&link["type"]),
250                    interface: link["node_interface_1_uid"]
251                        .as_str()
252                        .and_then(|uid| interface_names.get(uid).cloned()),
253                    state: text(&link["state"]),
254                    rate_rx: link["cur_data_rate_rx"].as_u64(),
255                    rate_tx: link["cur_data_rate_tx"].as_u64(),
256                    max_rx: link["max_data_rate_rx"].as_u64(),
257                    max_tx: link["max_data_rate_tx"].as_u64(),
258                });
259            }
260        }
261    }
262    Ok(Mesh {
263        nodes: nodes
264            .iter()
265            .map(|node| Node {
266                uid: node["uid"].as_str().unwrap_or_default().to_owned(),
267                name: text(&node["device_name"]),
268                model: text(&node["device_model"]),
269                mac: text(&node["device_mac_address"]),
270                role: text(&node["mesh_role"]),
271                meshed: node["is_meshed"].as_bool().unwrap_or_default(),
272                macs: std::iter::once(&node["device_mac_address"])
273                    .chain(interfaces(node).iter().map(|i| &i["mac_address"]))
274                    .filter_map(text)
275                    .collect(),
276                ..Node::default()
277            })
278            .collect(),
279        links,
280    })
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn parses_the_host_list() {
289        let hosts = hosts(
290            "<?xml version=\"1.0\"?>\n<List><Item><Index>1</Index>\
291             <HostName>device-1</HostName><IPAddress>192.0.2.1</IPAddress>\
292             <MACAddress></MACAddress><Active>1</Active>\
293             <X_AVM-DE_Guest>0</X_AVM-DE_Guest><X_AVM-DE_Speed>1000</X_AVM-DE_Speed>\
294             </Item><Item><X_AVM-DE_Speed>fast</X_AVM-DE_Speed></Item></List>",
295        )
296        .unwrap();
297        assert_eq!(hosts.len(), 2);
298        assert_eq!(hosts[0].name.as_deref(), Some("device-1"));
299        assert_eq!(hosts[0].ip.as_deref(), Some("192.0.2.1"));
300        assert_eq!(hosts[0].mac, None);
301        assert!(hosts[0].active);
302        assert_eq!(hosts[0].guest, Some(false));
303        assert_eq!(hosts[0].speed, Some(1000));
304        assert_eq!(hosts[1], Host::default());
305    }
306
307    #[test]
308    fn rejects_other_documents() {
309        let error = hosts("<html/>").unwrap_err();
310        assert_eq!(
311            error.to_string(),
312            "the host list of the device is not valid: the root is html, not List"
313        );
314        assert!(hosts("not xml").is_err());
315        let error = mesh("{}").unwrap_err();
316        assert_eq!(
317            error.to_string(),
318            "the mesh list of the device is not valid: it has no nodes"
319        );
320        assert!(mesh("not json").is_err());
321    }
322
323    #[test]
324    fn adds_the_addresses_of_the_hosts() {
325        let node = |uid: &str, role: Option<&str>, macs: &[&str]| Node {
326            uid: uid.to_owned(),
327            role: role.map(str::to_owned),
328            macs: macs.iter().map(|m| (*m).to_owned()).collect(),
329            ..Node::default()
330        };
331        let host = |ip: Option<&str>, mac: &str, active: bool| Host {
332            ip: ip.map(str::to_owned),
333            mac: Some(mac.to_owned()),
334            active,
335            ..Host::default()
336        };
337        let mut mesh = Mesh {
338            nodes: vec![
339                node("box", Some("master"), &["AA:BB:CC:00:00:01"]),
340                // A repeater, in the host list with the MAC of its uplink.
341                node(
342                    "repeater",
343                    Some("slave"),
344                    &["AA:BB:CC:00:00:02", "AA:BB:CC:00:00:03"],
345                ),
346                node("inactive", None, &["AA:BB:CC:00:00:04"]),
347                node("both", None, &["AA:BB:CC:00:00:05", "AA:BB:CC:00:00:06"]),
348                node("unknown", None, &["AA:BB:CC:00:00:07"]),
349                node("none", None, &[]),
350            ],
351            links: Vec::new(),
352        };
353        let hosts = [
354            host(Some("192.0.2.3"), "aa-bb-cc-00-00-03", true),
355            host(Some("192.0.2.4"), "AA:BB:CC:00:00:04", false),
356            host(Some("192.0.2.5"), "AA:BB:CC:00:00:05", false),
357            host(Some("192.0.2.6"), "aa:bb:cc:00:00:06", true),
358            host(Some("192.0.2.9"), "AA:BB:CC:00:00:05", true),
359            host(None, "AA:BB:CC:00:00:07", true),
360            Host::default(),
361        ];
362        mesh.add_addresses(&hosts, Some("192.0.2.1"));
363        let addresses: Vec<_> = mesh
364            .nodes
365            .iter()
366            .map(|n| (n.ip.as_deref(), n.active))
367            .collect();
368        assert_eq!(
369            addresses,
370            [
371                (Some("192.0.2.1"), None),
372                (Some("192.0.2.3"), Some(true)),
373                (Some("192.0.2.4"), Some(false)),
374                (Some("192.0.2.6"), Some(true)),
375                (None, None),
376                (None, None),
377            ]
378        );
379        let json = serde_json::to_value(&mesh.nodes[4]).unwrap();
380        assert_eq!(json["ip"], Value::Null);
381        assert!(json.get("active").is_none() && json.get("macs").is_none());
382        // The device itself, as a host of its own.
383        mesh.add_addresses(&[host(Some("192.0.2.8"), "AA:BB:CC:00:00:01", true)], None);
384        assert_eq!(mesh.nodes[0].ip.as_deref(), Some("192.0.2.8"));
385        let mut other = Mesh {
386            nodes: vec![node("box", Some("master"), &[])],
387            links: Vec::new(),
388        };
389        other.add_addresses(&[], None);
390        assert_eq!(other.nodes[0].ip, None);
391    }
392
393    #[test]
394    fn parses_the_mesh() {
395        let mesh = mesh(
396            r#"{"nodes": [
397                {"uid": "n-1", "device_name": "fritz.box", "device_model": "FRITZ!Box 7690",
398                 "device_mac_address": "AA:BB:CC:00:00:01",
399                 "is_meshed": true, "mesh_role": "master",
400                 "node_interfaces": [{"uid": "ni-1", "name": "AP:5G:0", "type": "WLAN",
401                   "mac_address": "AA:BB:CC:00:00:11",
402                   "node_links": [{"uid": "nl-1", "type": "WLAN", "state": "CONNECTED",
403                     "node_1_uid": "n-1", "node_2_uid": "n-2",
404                     "node_interface_1_uid": "ni-1", "node_interface_2_uid": "ni-2",
405                     "cur_data_rate_rx": 100, "cur_data_rate_tx": 200,
406                     "max_data_rate_rx": 300, "max_data_rate_tx": 400}]}]},
407                {"uid": "n-2", "device_name": "", "is_meshed": false,
408                 "node_interfaces": [{"uid": "ni-2", "name": "",
409                   "node_links": [{"uid": "nl-1", "node_1_uid": "n-1", "node_2_uid": "n-2"},
410                     {"uid": "nl-2", "node_1_uid": "n-2", "node_2_uid": "n-9"}]}]},
411                {"uid": "n-3"}
412            ]}"#,
413        )
414        .unwrap();
415        assert_eq!(mesh.nodes.len(), 3);
416        assert_eq!(mesh.nodes[0].name.as_deref(), Some("fritz.box"));
417        assert_eq!(mesh.nodes[0].role.as_deref(), Some("master"));
418        assert_eq!(
419            mesh.nodes[0].macs,
420            ["AA:BB:CC:00:00:01", "AA:BB:CC:00:00:11"]
421        );
422        assert!(mesh.nodes[0].meshed);
423        assert_eq!(
424            mesh.nodes[1],
425            Node {
426                uid: "n-2".to_owned(),
427                ..Node::default()
428            }
429        );
430        assert_eq!(
431            mesh.links,
432            [
433                Link {
434                    from: "fritz.box".to_owned(),
435                    to: "n-2".to_owned(),
436                    from_uid: "n-1".to_owned(),
437                    to_uid: "n-2".to_owned(),
438                    kind: Some("WLAN".to_owned()),
439                    interface: Some("AP:5G:0".to_owned()),
440                    state: Some("CONNECTED".to_owned()),
441                    rate_rx: Some(100),
442                    rate_tx: Some(200),
443                    max_rx: Some(300),
444                    max_tx: Some(400),
445                },
446                Link {
447                    from: "n-2".to_owned(),
448                    to: "n-9".to_owned(),
449                    from_uid: "n-2".to_owned(),
450                    to_uid: "n-9".to_owned(),
451                    ..Link::default()
452                }
453            ]
454        );
455    }
456}