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`. In the entries, not in the host list; see
94    /// [`crate::host::add_addressing`] for all hosts at once.
95    pub address_source: Option<String>,
96    /// Whether the device always gives the host the same IPv4 address
97    /// ("permanent assignment"). Only from the web interface, see
98    /// [`crate::host::add_addressing`].
99    pub permanent_address: Option<bool>,
100    /// When the host was last connected, in UTC, like
101    /// `2026-11-20T18:05:42Z`. Only from the web interface, see
102    /// [`crate::host::add_addressing`]. The device forgets it after a while.
103    pub last_seen: Option<String>,
104    /// Whether the host is in the guest network. Only in the host list.
105    pub guest: Option<bool>,
106    /// Whether the host may use the internet: `granted`, `denied` or
107    /// `error`. Only in the host list.
108    pub internet_access: Option<String>,
109    /// The speed of the connection to the host, in Mbit/s. Only in the
110    /// host list.
111    pub speed: Option<u32>,
112}
113
114/// The hosts and how many the device reported.
115#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
116pub struct Hosts {
117    /// The number of hosts the device reported. More than the hosts if it
118    /// stopped answering before.
119    pub reported: u32,
120    pub hosts: Vec<Host>,
121}
122
123/// Reads the overview.
124///
125/// # Errors
126///
127/// The errors of reading other than missing parts, see
128/// [`Reader::try_read`].
129pub async fn overview(reader: &mut Reader) -> Result<Overview, Error> {
130    let info = reader.try_read("DeviceInfo1", "GetInfo", &[]).await?;
131    let interface = reader.try_read("UserInterface1", "GetInfo", &[]).await?;
132    let auth = reader.try_read("X_AVM-DE_Auth1", "GetInfo", &[]).await?;
133    let user = reader
134        .try_read("LANConfigSecurity1", "X_AVM-DE_GetCurrentUser", &[])
135        .await?;
136    let rights = user
137        .and_then(|u| u.text("NewX_AVM-DE_CurrentUserRights"))
138        .map_or_else(Vec::new, |xml| rights(&xml));
139    let info = info.unwrap_or_default();
140    Ok(Overview {
141        model: info.text("NewModelName"),
142        firmware: info.text("NewSoftwareVersion"),
143        uptime: info.number("NewUpTime"),
144        update_available: interface.and_then(|i| i.flag("NewUpgradeAvailable")),
145        two_factor: auth.and_then(|a| a.flag("NewEnabled")),
146        rights,
147        internet: Some(connection(reader).await?.0).filter(|c| *c != Connection::default()),
148    })
149}
150
151/// Parses rights like
152/// `<rights><path>BoxAdmin</path><access>readwrite</access></rights>`.
153pub(crate) fn rights(xml: &str) -> Vec<Right> {
154    let Ok(document) = roxmltree::Document::parse(xml) else {
155        return Vec::new();
156    };
157    let mut rights = Vec::new();
158    let mut area = None;
159    for node in document
160        .root_element()
161        .children()
162        .filter(roxmltree::Node::is_element)
163    {
164        let text = node.text().unwrap_or_default().trim().to_owned();
165        match node.tag_name().name() {
166            "path" => area = Some(text),
167            "access" => {
168                if let Some(area) = area.take() {
169                    rights.push(Right { area, access: text });
170                }
171            }
172            _ => {}
173        }
174    }
175    rights
176}
177
178/// Reads the connection, and the answer of the connection service for
179/// the details.
180async fn connection(reader: &mut Reader) -> Result<(Connection, Values), Error> {
181    let common = reader
182        .try_read("WANCommonInterfaceConfig1", "GetCommonLinkProperties", &[])
183        .await?
184        .unwrap_or_default();
185    // Connections over PPP, like most DSL lines, are in WANPPPConnection,
186    // the others in WANIPConnection.
187    let mut details = Values::default();
188    for service in ["WANPPPConnection1", "WANIPConnection1"] {
189        if let Some(values) = reader.try_read(service, "GetInfo", &[]).await? {
190            details = values;
191            break;
192        }
193    }
194    let connection = Connection {
195        access_type: common.text("NewWANAccessType"),
196        link: common.text("NewPhysicalLinkStatus"),
197        status: details.text("NewConnectionStatus"),
198        external_address: details.text("NewExternalIPAddress"),
199        uptime: details.number("NewUptime"),
200    };
201    let details = Values(common.0.into_iter().chain(details.0).collect());
202    Ok((connection, details))
203}
204
205/// Reads the internet connection.
206///
207/// # Errors
208///
209/// The errors of reading other than missing parts, see
210/// [`Reader::try_read`].
211pub async fn internet(reader: &mut Reader) -> Result<Internet, Error> {
212    let (connection, details) = connection(reader).await?;
213    let provider = reader
214        .try_read(
215            "WANCommonInterfaceConfig1",
216            "X_AVM-DE_GetActiveProvider",
217            &[],
218        )
219        .await?;
220    let dsl = reader
221        .try_read("WANDSLInterfaceConfig1", "GetInfo", &[])
222        .await?;
223    let kbits = |name| details.number::<u64>(name).map(|b| b / 1000);
224    Ok(Internet {
225        provider: provider.and_then(|p| p.text("NewX_AVM-DE_Provider")),
226        dns_servers: details.get("NewDNSServers").map_or_else(Vec::new, |s| {
227            s.split(',')
228                .map(str::trim)
229                .filter(|s| !s.is_empty())
230                .map(str::to_owned)
231                .collect()
232        }),
233        downstream_max: kbits("NewLayer1DownstreamMaxBitRate"),
234        upstream_max: kbits("NewLayer1UpstreamMaxBitRate"),
235        dsl: dsl
236            .filter(|_| connection.access_type.as_deref() == Some("DSL"))
237            .map(|d| dsl_line(&d)),
238        connection,
239    })
240}
241
242/// The DSL line from the answer of `WANDSLInterfaceConfig:GetInfo`, whose
243/// noise margins and attenuations are in tenths of a dB.
244fn dsl_line(values: &Values) -> Dsl {
245    let decibels = |name| values.number::<i64>(name).map(tenths);
246    Dsl {
247        status: values.text("NewStatus"),
248        downstream_rate: values.number("NewDownstreamCurrRate"),
249        upstream_rate: values.number("NewUpstreamCurrRate"),
250        downstream_max: values.number("NewDownstreamMaxRate"),
251        upstream_max: values.number("NewUpstreamMaxRate"),
252        downstream_noise_margin: decibels("NewDownstreamNoiseMargin"),
253        upstream_noise_margin: decibels("NewUpstreamNoiseMargin"),
254        downstream_attenuation: decibels("NewDownstreamAttenuation"),
255        upstream_attenuation: decibels("NewUpstreamAttenuation"),
256    }
257}
258
259/// A value in tenths as a decimal, like 70 as 7.0.
260#[expect(clippy::cast_precision_loss, reason = "tenths of a dB are small")]
261pub(crate) fn tenths(value: i64) -> f64 {
262    value as f64 / 10.0
263}
264
265/// Reads the hosts from the host list, in one request. Without a host list,
266/// it reads them one call per host, up to [`MAX_HOSTS`], and stops early at
267/// the first index the device has no entry for.
268///
269/// # Errors
270///
271/// The errors of reading other than missing parts, see
272/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a host list
273/// that cannot be parsed.
274pub async fn hosts(reader: &mut Reader) -> Result<Hosts, Error> {
275    if let Some(xml) = reader
276        .document(
277            "Hosts1",
278            "X_AVM-DE_GetHostListPath",
279            "NewX_AVM-DE_HostListPath",
280        )
281        .await?
282    {
283        let hosts = lists::hosts(&xml)?;
284        return Ok(Hosts {
285            reported: u32::try_from(hosts.len()).unwrap_or(u32::MAX),
286            hosts,
287        });
288    }
289    let Some((reported, entries)) = reader
290        .entries(
291            "Hosts1",
292            ("GetHostNumberOfEntries", "NewHostNumberOfEntries"),
293            ("GetGenericHostEntry", "NewIndex"),
294            MAX_HOSTS,
295        )
296        .await?
297    else {
298        return Ok(Hosts::default());
299    };
300    let hosts = entries
301        .iter()
302        .map(|entry| Host {
303            name: entry.text("NewHostName"),
304            ip: entry.text("NewIPAddress"),
305            mac: entry.text("NewMACAddress"),
306            active: entry.flag("NewActive").unwrap_or_default(),
307            interface: entry.text("NewInterfaceType"),
308            address_source: entry.text("NewAddressSource"),
309            ..Host::default()
310        })
311        .collect();
312    Ok(Hosts { reported, hosts })
313}
314
315/// Reads the mesh from the mesh list. `None` if the device has none.
316///
317/// # Errors
318///
319/// The errors of reading other than missing parts, see
320/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a mesh list
321/// that cannot be parsed.
322pub async fn mesh(reader: &mut Reader) -> Result<Option<Mesh>, Error> {
323    reader
324        .document(
325            "Hosts1",
326            "X_AVM-DE_GetMeshListPath",
327            "NewX_AVM-DE_MeshListPath",
328        )
329        .await?
330        .map(|json| lists::mesh(&json))
331        .transpose()
332}
333
334/// Adds the IP addresses of the hosts to the nodes of the `mesh`, see
335/// [`Mesh::add_addresses`]: one read of the host list, and one of the LAN
336/// settings for the address of the device itself. Returns why the mesh has
337/// no addresses of hosts, if it has none.
338pub async fn add_addresses(reader: &mut Reader, mesh: &mut Mesh) -> Option<String> {
339    let (hosts, note) = match hosts(reader).await {
340        Ok(hosts) if hosts.hosts.is_empty() => (
341            Vec::new(),
342            Some("the device has no host list, or the user may not read it".to_owned()),
343        ),
344        Ok(hosts) => (hosts.hosts, None),
345        Err(error) => (Vec::new(), Some(format!("cannot read the hosts: {error}"))),
346    };
347    let router = reader
348        .try_read("LANHostConfigManagement1", "GetIPRoutersList", &[])
349        .await
350        .ok()
351        .flatten()
352        .and_then(|v| v.text("NewIPRouters"))
353        .and_then(|v| {
354            v.split(',')
355                .map(str::trim)
356                .find(|a| !a.is_empty())
357                .map(str::to_owned)
358        });
359    mesh.add_addresses(&hosts, router.as_deref());
360    note.map(|note| format!("{note}, so the mesh shows no addresses of hosts"))
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn parses_rights() {
369        let xml = "<rights><path>BoxAdmin</path><access>readwrite</access>\
370                   <access>orphan</access><other/><path>NAS</path><access>read</access></rights>";
371        assert_eq!(
372            rights(xml),
373            [
374                Right {
375                    area: "BoxAdmin".to_owned(),
376                    access: "readwrite".to_owned()
377                },
378                Right {
379                    area: "NAS".to_owned(),
380                    access: "read".to_owned()
381                },
382            ]
383        );
384        assert_eq!(rights("<rights"), []);
385    }
386}