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>,
95 pub guest: Option<bool>,
97 pub internet_access: Option<String>,
100 pub speed: Option<u32>,
103}
104
105#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
107pub struct Hosts {
108 pub reported: u32,
111 pub hosts: Vec<Host>,
112}
113
114pub 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
142pub(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
169async 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 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
196pub 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
233fn 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#[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
256pub 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
306pub 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
325pub 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}