Skip to main content

fritz_core/
status.rs

1//! The state of a device, read through actions that only read: an
2//! overview, the hosts, the mesh and the internet connection. The wireless
3//! networks are in [`crate::wlan`].
4//!
5//! Parts the device lacks, or that the user may not read, are left out
6//! instead of failing the whole read.
7
8use serde::Serialize;
9
10use crate::generic::Error;
11use crate::lists::{self, Mesh};
12use crate::read::{Reader, Values};
13
14/// The most hosts read, as a guard against a device that never ends the
15/// list.
16pub const MAX_HOSTS: u32 = 1000;
17
18/// The device, its connection and the rights of the user.
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct Overview {
21    pub model: Option<String>,
22    pub firmware: Option<String>,
23    /// Seconds since the device started.
24    pub uptime: Option<u64>,
25    pub update_available: Option<bool>,
26    /// Whether changes need a confirmation on the device, like a button
27    /// press.
28    pub two_factor: Option<bool>,
29    /// What the user may do, like `BoxAdmin: readwrite`.
30    pub rights: Vec<Right>,
31    pub internet: Option<Connection>,
32}
33
34/// An area of the device and the access of the user to it.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
36pub struct Right {
37    pub area: String,
38    pub access: String,
39}
40
41/// The connection to the internet.
42#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
43pub struct Connection {
44    /// Like `DSL`, `Ethernet` or `X_AVM-DE_Mobile`.
45    pub access_type: Option<String>,
46    /// The physical link, like `Up`.
47    pub link: Option<String>,
48    /// Like `Connected`.
49    pub status: Option<String>,
50    pub external_address: Option<String>,
51    /// Seconds since the connection was made.
52    pub uptime: Option<u64>,
53}
54
55/// The internet connection in detail.
56#[derive(Debug, Clone, Default, PartialEq, Serialize)]
57pub struct Internet {
58    #[serde(flatten)]
59    pub connection: Connection,
60    pub provider: Option<String>,
61    pub dns_servers: Vec<String>,
62    /// The speed of the physical link, in kbit/s.
63    pub downstream_max: Option<u64>,
64    pub upstream_max: Option<u64>,
65    pub dsl: Option<Dsl>,
66}
67
68/// The DSL line.
69#[derive(Debug, Clone, Default, PartialEq, Serialize)]
70pub struct Dsl {
71    pub status: Option<String>,
72    /// The synchronized and the attainable rates, in kbit/s.
73    pub downstream_rate: Option<u64>,
74    pub upstream_rate: Option<u64>,
75    pub downstream_max: Option<u64>,
76    pub upstream_max: Option<u64>,
77    /// In dB.
78    pub downstream_noise_margin: Option<f64>,
79    pub upstream_noise_margin: Option<f64>,
80    pub downstream_attenuation: Option<f64>,
81    pub upstream_attenuation: Option<f64>,
82}
83
84/// A host the device knows, active or not.
85#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
86pub struct Host {
87    pub name: Option<String>,
88    pub ip: Option<String>,
89    pub mac: Option<String>,
90    pub active: bool,
91    /// Like `Ethernet` or `802.11`.
92    pub interface: Option<String>,
93    /// Like `DHCP` or `Static`. Only in the entries, not in the host list.
94    pub address_source: Option<String>,
95    /// Whether the host is in the guest network. Only in the host list.
96    pub guest: Option<bool>,
97    /// Whether the host may use the internet: `granted`, `denied` or
98    /// `error`. Only in the host list.
99    pub internet_access: Option<String>,
100    /// The speed of the connection to the host, in Mbit/s. Only in the
101    /// host list.
102    pub speed: Option<u32>,
103}
104
105/// The hosts and how many the device reported.
106#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
107pub struct Hosts {
108    /// The number of hosts the device reported. More than the hosts if it
109    /// stopped answering before.
110    pub reported: u32,
111    pub hosts: Vec<Host>,
112}
113
114/// Reads the overview.
115///
116/// # Errors
117///
118/// The errors of reading other than missing parts, see
119/// [`Reader::try_read`].
120pub async fn overview(reader: &mut Reader) -> Result<Overview, Error> {
121    let info = reader.try_read("DeviceInfo1", "GetInfo", &[]).await?;
122    let interface = reader.try_read("UserInterface1", "GetInfo", &[]).await?;
123    let auth = reader.try_read("X_AVM-DE_Auth1", "GetInfo", &[]).await?;
124    let user = reader
125        .try_read("LANConfigSecurity1", "X_AVM-DE_GetCurrentUser", &[])
126        .await?;
127    let rights = user
128        .and_then(|u| u.text("NewX_AVM-DE_CurrentUserRights"))
129        .map_or_else(Vec::new, |xml| rights(&xml));
130    let info = info.unwrap_or_default();
131    Ok(Overview {
132        model: info.text("NewModelName"),
133        firmware: info.text("NewSoftwareVersion"),
134        uptime: info.number("NewUpTime"),
135        update_available: interface.and_then(|i| i.flag("NewUpgradeAvailable")),
136        two_factor: auth.and_then(|a| a.flag("NewEnabled")),
137        rights,
138        internet: Some(connection(reader).await?.0).filter(|c| *c != Connection::default()),
139    })
140}
141
142/// Parses rights like
143/// `<rights><path>BoxAdmin</path><access>readwrite</access></rights>`.
144pub(crate) fn rights(xml: &str) -> Vec<Right> {
145    let Ok(document) = roxmltree::Document::parse(xml) else {
146        return Vec::new();
147    };
148    let mut rights = Vec::new();
149    let mut area = None;
150    for node in document
151        .root_element()
152        .children()
153        .filter(roxmltree::Node::is_element)
154    {
155        let text = node.text().unwrap_or_default().trim().to_owned();
156        match node.tag_name().name() {
157            "path" => area = Some(text),
158            "access" => {
159                if let Some(area) = area.take() {
160                    rights.push(Right { area, access: text });
161                }
162            }
163            _ => {}
164        }
165    }
166    rights
167}
168
169/// Reads the connection, and the answer of the connection service for
170/// the details.
171async fn connection(reader: &mut Reader) -> Result<(Connection, Values), Error> {
172    let common = reader
173        .try_read("WANCommonInterfaceConfig1", "GetCommonLinkProperties", &[])
174        .await?
175        .unwrap_or_default();
176    // Connections over PPP, like most DSL lines, are in WANPPPConnection,
177    // the others in WANIPConnection.
178    let mut details = Values::default();
179    for service in ["WANPPPConnection1", "WANIPConnection1"] {
180        if let Some(values) = reader.try_read(service, "GetInfo", &[]).await? {
181            details = values;
182            break;
183        }
184    }
185    let connection = Connection {
186        access_type: common.text("NewWANAccessType"),
187        link: common.text("NewPhysicalLinkStatus"),
188        status: details.text("NewConnectionStatus"),
189        external_address: details.text("NewExternalIPAddress"),
190        uptime: details.number("NewUptime"),
191    };
192    let details = Values(common.0.into_iter().chain(details.0).collect());
193    Ok((connection, details))
194}
195
196/// Reads the internet connection.
197///
198/// # Errors
199///
200/// The errors of reading other than missing parts, see
201/// [`Reader::try_read`].
202pub async fn internet(reader: &mut Reader) -> Result<Internet, Error> {
203    let (connection, details) = connection(reader).await?;
204    let provider = reader
205        .try_read(
206            "WANCommonInterfaceConfig1",
207            "X_AVM-DE_GetActiveProvider",
208            &[],
209        )
210        .await?;
211    let dsl = reader
212        .try_read("WANDSLInterfaceConfig1", "GetInfo", &[])
213        .await?;
214    let kbits = |name| details.number::<u64>(name).map(|b| b / 1000);
215    Ok(Internet {
216        provider: provider.and_then(|p| p.text("NewX_AVM-DE_Provider")),
217        dns_servers: details.get("NewDNSServers").map_or_else(Vec::new, |s| {
218            s.split(',')
219                .map(str::trim)
220                .filter(|s| !s.is_empty())
221                .map(str::to_owned)
222                .collect()
223        }),
224        downstream_max: kbits("NewLayer1DownstreamMaxBitRate"),
225        upstream_max: kbits("NewLayer1UpstreamMaxBitRate"),
226        dsl: dsl
227            .filter(|_| connection.access_type.as_deref() == Some("DSL"))
228            .map(|d| dsl_line(&d)),
229        connection,
230    })
231}
232
233/// The DSL line from the answer of `WANDSLInterfaceConfig:GetInfo`, whose
234/// noise margins and attenuations are in tenths of a dB.
235fn dsl_line(values: &Values) -> Dsl {
236    let decibels = |name| values.number::<i64>(name).map(tenths);
237    Dsl {
238        status: values.text("NewStatus"),
239        downstream_rate: values.number("NewDownstreamCurrRate"),
240        upstream_rate: values.number("NewUpstreamCurrRate"),
241        downstream_max: values.number("NewDownstreamMaxRate"),
242        upstream_max: values.number("NewUpstreamMaxRate"),
243        downstream_noise_margin: decibels("NewDownstreamNoiseMargin"),
244        upstream_noise_margin: decibels("NewUpstreamNoiseMargin"),
245        downstream_attenuation: decibels("NewDownstreamAttenuation"),
246        upstream_attenuation: decibels("NewUpstreamAttenuation"),
247    }
248}
249
250/// A value in tenths as a decimal, like 70 as 7.0.
251#[expect(clippy::cast_precision_loss, reason = "tenths of a dB are small")]
252pub(crate) fn tenths(value: i64) -> f64 {
253    value as f64 / 10.0
254}
255
256/// Reads the hosts from the host list, in one request. Without a host list,
257/// it reads them one call per host, up to [`MAX_HOSTS`], and stops early at
258/// the first index the device has no entry for.
259///
260/// # Errors
261///
262/// The errors of reading other than missing parts, see
263/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a host list
264/// that cannot be parsed.
265pub async fn hosts(reader: &mut Reader) -> Result<Hosts, Error> {
266    if let Some(xml) = reader
267        .document(
268            "Hosts1",
269            "X_AVM-DE_GetHostListPath",
270            "NewX_AVM-DE_HostListPath",
271        )
272        .await?
273    {
274        let hosts = lists::hosts(&xml)?;
275        return Ok(Hosts {
276            reported: u32::try_from(hosts.len()).unwrap_or(u32::MAX),
277            hosts,
278        });
279    }
280    let Some((reported, entries)) = reader
281        .entries(
282            "Hosts1",
283            ("GetHostNumberOfEntries", "NewHostNumberOfEntries"),
284            ("GetGenericHostEntry", "NewIndex"),
285            MAX_HOSTS,
286        )
287        .await?
288    else {
289        return Ok(Hosts::default());
290    };
291    let hosts = entries
292        .iter()
293        .map(|entry| Host {
294            name: entry.text("NewHostName"),
295            ip: entry.text("NewIPAddress"),
296            mac: entry.text("NewMACAddress"),
297            active: entry.flag("NewActive").unwrap_or_default(),
298            interface: entry.text("NewInterfaceType"),
299            address_source: entry.text("NewAddressSource"),
300            ..Host::default()
301        })
302        .collect();
303    Ok(Hosts { reported, hosts })
304}
305
306/// Reads the mesh from the mesh list. `None` if the device has none.
307///
308/// # Errors
309///
310/// The errors of reading other than missing parts, see
311/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a mesh list
312/// that cannot be parsed.
313pub async fn mesh(reader: &mut Reader) -> Result<Option<Mesh>, Error> {
314    reader
315        .document(
316            "Hosts1",
317            "X_AVM-DE_GetMeshListPath",
318            "NewX_AVM-DE_MeshListPath",
319        )
320        .await?
321        .map(|json| lists::mesh(&json))
322        .transpose()
323}
324
325/// Adds the IP addresses of the hosts to the nodes of the `mesh`, see
326/// [`Mesh::add_addresses`]: one read of the host list, and one of the LAN
327/// settings for the address of the device itself. Returns why the mesh has
328/// no addresses of hosts, if it has none.
329pub async fn add_addresses(reader: &mut Reader, mesh: &mut Mesh) -> Option<String> {
330    let (hosts, note) = match hosts(reader).await {
331        Ok(hosts) if hosts.hosts.is_empty() => (
332            Vec::new(),
333            Some("the device has no host list, or the user may not read it".to_owned()),
334        ),
335        Ok(hosts) => (hosts.hosts, None),
336        Err(error) => (Vec::new(), Some(format!("cannot read the hosts: {error}"))),
337    };
338    let router = reader
339        .try_read("LANHostConfigManagement1", "GetIPRoutersList", &[])
340        .await
341        .ok()
342        .flatten()
343        .and_then(|v| v.text("NewIPRouters"))
344        .and_then(|v| {
345            v.split(',')
346                .map(str::trim)
347                .find(|a| !a.is_empty())
348                .map(str::to_owned)
349        });
350    mesh.add_addresses(&hosts, router.as_deref());
351    note.map(|note| format!("{note}, so the mesh shows no addresses of hosts"))
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn parses_rights() {
360        let xml = "<rights><path>BoxAdmin</path><access>readwrite</access>\
361                   <access>orphan</access><other/><path>NAS</path><access>read</access></rights>";
362        assert_eq!(
363            rights(xml),
364            [
365                Right {
366                    area: "BoxAdmin".to_owned(),
367                    access: "readwrite".to_owned()
368                },
369                Right {
370                    area: "NAS".to_owned(),
371                    access: "read".to_owned()
372                },
373            ]
374        );
375        assert_eq!(rights("<rights"), []);
376    }
377}