1use serde::Serialize;
9
10use crate::generic::Error;
11use crate::lists::{self, Mesh};
12use crate::read::{Reader, Values};
13
14pub const MAX_HOSTS: u32 = 1000;
17
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct Overview {
21 pub model: Option<String>,
22 pub firmware: Option<String>,
23 pub uptime: Option<u64>,
25 pub update_available: Option<bool>,
26 pub two_factor: Option<bool>,
29 pub rights: Vec<Right>,
31 pub internet: Option<Connection>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
36pub struct Right {
37 pub area: String,
38 pub access: String,
39}
40
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
43pub struct Connection {
44 pub access_type: Option<String>,
46 pub link: Option<String>,
48 pub status: Option<String>,
50 pub external_address: Option<String>,
51 pub uptime: Option<u64>,
53}
54
55#[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 pub downstream_max: Option<u64>,
64 pub upstream_max: Option<u64>,
65 pub dsl: Option<Dsl>,
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Serialize)]
70pub struct Dsl {
71 pub status: Option<String>,
72 pub downstream_rate: Option<u64>,
74 pub upstream_rate: Option<u64>,
75 pub downstream_max: Option<u64>,
76 pub upstream_max: Option<u64>,
77 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#[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 pub interface: Option<String>,
93 pub address_source: Option<String>,
96 pub permanent_address: Option<bool>,
100 pub last_seen: Option<String>,
104 pub guest: Option<bool>,
106 pub internet_access: Option<String>,
109 pub speed: Option<u32>,
112}
113
114#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
116pub struct Hosts {
117 pub reported: u32,
120 pub hosts: Vec<Host>,
121}
122
123pub 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
151pub(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
178async 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 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
205pub 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
242fn 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#[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
265pub 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
315pub 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
334pub 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}