Skip to main content

fritz_core/
wlan.rs

1//! The wireless networks of a device: their state, whether they are the
2//! guest network, and, when asked for, their clients and details, and what
3//! a device needs to [join](join) one.
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 std::collections::HashMap;
9
10use serde::Serialize;
11
12use crate::generic::Error;
13use crate::lists;
14use crate::read::{Reader, Values};
15use crate::status;
16
17mod details;
18pub mod join;
19
20pub use details::{Details, Hint, Night, Radio, Security, Statistics, Wps};
21
22/// The most clients of a network read one call per client, as a guard
23/// against a device that never ends the list.
24pub const MAX_CLIENTS: u32 = 1000;
25
26/// What to read besides the state of each network.
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28pub struct Views {
29    /// The connected clients of each network.
30    pub clients: bool,
31    /// The security settings, radio, WPS, night time switch-off and
32    /// statistics of each network, with hints on weak settings.
33    pub details: bool,
34}
35
36/// A wireless network.
37#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
38pub struct Wlan {
39    /// The service, like `WLANConfiguration1`.
40    pub service: String,
41    pub ssid: Option<String>,
42    /// Like `2.4 GHz`.
43    pub band: Option<String>,
44    pub channel: Option<u32>,
45    /// Like `ax` or `be`.
46    pub standard: Option<String>,
47    pub enabled: Option<bool>,
48    /// Like `Up` or `Disabled`.
49    pub status: Option<String>,
50    /// Whether the device reports this network as its guest network.
51    pub guest: bool,
52    /// The number of connected clients.
53    pub client_count: Option<u32>,
54    /// The connected clients, only if [asked for](Views::clients).
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub clients: Option<Vec<Client>>,
57    /// The details, only if [asked for](Views::details).
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub details: Option<Details>,
60}
61
62/// A network with the answers that its details are made of.
63struct Read {
64    wlan: Wlan,
65    info: Values,
66    ext: Option<Values>,
67}
68
69/// A client connected to a wireless network.
70#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
71pub struct Client {
72    /// The name in the host table.
73    pub name: Option<String>,
74    pub ip: Option<String>,
75    pub mac: Option<String>,
76    /// The signal strength, in percent.
77    pub signal: Option<u8>,
78    /// The speed of the connection, in Mbit/s.
79    pub rate: Option<u32>,
80}
81
82/// A client in the list of the clients of all networks, with what tells
83/// which network it is connected to.
84#[derive(Debug, Clone, PartialEq, Eq)]
85struct Listed {
86    client: Client,
87    channel: Option<u32>,
88    guest: Option<bool>,
89}
90
91/// Reads the wireless networks, and what `views` asks for.
92///
93/// # Errors
94///
95/// The errors of reading other than missing parts, see
96/// [`Reader::try_read`], and [`Error::InvalidDocument`] for a list of
97/// clients or a host list that cannot be parsed.
98pub async fn wlans(reader: &mut Reader, views: Views) -> Result<Vec<Wlan>, Error> {
99    let networks = networks(reader).await?;
100    with_views(reader, networks, views).await
101}
102
103/// Like [`wlans`], only the networks that `network` names: by service, like
104/// `WLANConfiguration2`, ignoring case, by its number, like `2`, or by
105/// SSID. Several networks can share an SSID, one per band.
106///
107/// # Errors
108///
109/// The errors of [`wlans`].
110pub async fn named(reader: &mut Reader, network: &str, views: Views) -> Result<Vec<Wlan>, Error> {
111    let mut networks = networks(reader).await?;
112    networks.retain(|n| is_named(&n.wlan, network));
113    with_views(reader, networks, views).await
114}
115
116/// Whether `network` names `wlan`, see [`named`].
117fn is_named(wlan: &Wlan, network: &str) -> bool {
118    let number = wlan
119        .service
120        .get("WLANConfiguration".len()..)
121        .filter(|_| wlan.service.starts_with("WLANConfiguration"));
122    wlan.service.eq_ignore_ascii_case(network)
123        || number == Some(network)
124        || wlan.ssid.as_deref() == Some(network)
125}
126
127/// Reads the state of each network.
128async fn networks(reader: &mut Reader) -> Result<Vec<Read>, Error> {
129    let mut networks = Vec::new();
130    for service in reader.services("WLANConfiguration") {
131        let Some(info) = reader.try_read(&service, "GetInfo", &[]).await? else {
132            continue;
133        };
134        let client_count = reader
135            .try_read(&service, "GetTotalAssociations", &[])
136            .await?
137            .and_then(|v| v.number("NewTotalAssociations"));
138        let ext = reader
139            .try_read(&service, "X_AVM-DE_GetWLANExtInfo", &[])
140            .await?;
141        let guest = ext
142            .as_ref()
143            .and_then(|v| v.text("NewX_AVM-DE_APType"))
144            .is_some_and(|kind| kind == "guest");
145        let wlan = Wlan {
146            band: info.get("NewX_AVM-DE_FrequencyBand").and_then(band),
147            ssid: info.text("NewSSID"),
148            channel: info.number("NewChannel"),
149            standard: info.text("NewStandard"),
150            enabled: info.flag("NewEnable"),
151            status: info.text("NewStatus"),
152            guest,
153            client_count,
154            clients: None,
155            details: None,
156            service,
157        };
158        networks.push(Read { wlan, info, ext });
159    }
160    Ok(networks)
161}
162
163/// The networks with what `views` asks for.
164async fn with_views(
165    reader: &mut Reader,
166    networks: Vec<Read>,
167    views: Views,
168) -> Result<Vec<Wlan>, Error> {
169    let mut wlans = Vec::new();
170    for Read {
171        mut wlan,
172        info,
173        ext,
174    } in networks
175    {
176        if views.details {
177            let details = details::read(reader, &wlan.service, &info, ext.as_ref()).await?;
178            wlan.details = Some(details);
179        }
180        wlans.push(wlan);
181    }
182    if views.clients {
183        add_clients(reader, &mut wlans).await?;
184    }
185    if wlans
186        .iter()
187        .any(|w| w.clients.as_ref().is_some_and(|c| !c.is_empty()))
188    {
189        let names = names(&status::hosts(reader).await?.hosts);
190        for client in wlans
191            .iter_mut()
192            .flat_map(|w| w.clients.iter_mut().flatten())
193        {
194            client.name = client
195                .mac
196                .as_deref()
197                .and_then(|mac| names.get(&lists::normal_mac(mac)))
198                .cloned();
199        }
200    }
201    Ok(wlans)
202}
203
204/// Adds the clients to each network. The device serves one list of the
205/// clients of all its networks, the same for each service; it is read once,
206/// and a client belongs to the guest network by its guest flag, or else to
207/// the network on its channel. For a network whose share of the list holds
208/// another number of clients than the device reported, or without a list,
209/// the clients are read one call per client, up to [`MAX_CLIENTS`].
210async fn add_clients(reader: &mut Reader, wlans: &mut [Wlan]) -> Result<(), Error> {
211    let mut list = None;
212    for wlan in wlans.iter() {
213        if let Some(xml) = reader
214            .document(
215                &wlan.service,
216                "X_AVM-DE_GetWLANDeviceListPath",
217                "NewX_AVM-DE_WLANDeviceListPath",
218            )
219            .await?
220        {
221            list = Some(client_list(&xml)?);
222            break;
223        }
224    }
225    for wlan in wlans.iter_mut() {
226        let listed = list
227            .as_deref()
228            .map(|list| of_network(list, wlan))
229            .filter(|clients| {
230                wlan.client_count
231                    .is_none_or(|count| count as usize == clients.len())
232            });
233        wlan.clients = Some(match listed {
234            Some(clients) => clients,
235            None => one_per_call(reader, &wlan.service).await?,
236        });
237    }
238    Ok(())
239}
240
241/// The clients in the `list` that are connected to `wlan`.
242fn of_network(list: &[Listed], wlan: &Wlan) -> Vec<Client> {
243    list.iter()
244        .filter(|l| {
245            if wlan.guest {
246                l.guest == Some(true)
247            } else {
248                l.guest != Some(true) && l.channel.is_some() && l.channel == wlan.channel
249            }
250        })
251        .map(|l| l.client.clone())
252        .collect()
253}
254
255/// Reads the clients of a network one call per client.
256async fn one_per_call(reader: &mut Reader, service: &str) -> Result<Vec<Client>, Error> {
257    let entries = reader
258        .entries(
259            service,
260            ("GetTotalAssociations", "NewTotalAssociations"),
261            ("GetGenericAssociatedDeviceInfo", "NewAssociatedDeviceIndex"),
262            MAX_CLIENTS,
263        )
264        .await?;
265    Ok(entries.map_or_else(Vec::new, |(_, entries)| {
266        entries.iter().map(client).collect()
267    }))
268}
269
270/// Parses the list of the clients of all networks, like
271/// `<List><TotalAssociations>…</TotalAssociations><Item>…</Item></List>`,
272/// where each item has the fields `AssociatedDeviceIndex`,
273/// `AssociatedDeviceMACAddress`, `AssociatedDeviceIPAddress`,
274/// `AssociatedDeviceAuthState`, `X_AVM-DE_Speed`, `X_AVM-DE_SignalStrength`,
275/// `AssociatedDeviceChannel`, `X_AVM-DE_ChannelWidth` and
276/// `AssociatedDeviceGuest`.
277fn client_list(xml: &str) -> Result<Vec<Listed>, Error> {
278    let items = lists::items(xml, "WLAN device list", "List", "Item")?;
279    Ok(items
280        .iter()
281        .map(|item| Listed {
282            client: Client {
283                name: None,
284                ip: item.text("AssociatedDeviceIPAddress"),
285                mac: item.text("AssociatedDeviceMACAddress"),
286                signal: item.number("X_AVM-DE_SignalStrength"),
287                rate: item.number("X_AVM-DE_Speed"),
288            },
289            channel: item.number("AssociatedDeviceChannel"),
290            guest: item.flag("AssociatedDeviceGuest"),
291        })
292        .collect())
293}
294
295/// A client from the answer of `GetGenericAssociatedDeviceInfo`.
296fn client(values: &Values) -> Client {
297    Client {
298        name: None,
299        ip: values.text("NewAssociatedDeviceIPAddress"),
300        mac: values.text("NewAssociatedDeviceMACAddress"),
301        signal: values.number("NewX_AVM-DE_SignalStrength"),
302        rate: values.number("NewX_AVM-DE_Speed"),
303    }
304}
305
306/// The names of the hosts by MAC address, in the form of
307/// [`lists::normal_mac`].
308fn names(hosts: &[status::Host]) -> HashMap<String, String> {
309    hosts
310        .iter()
311        .filter_map(|h| Some((lists::normal_mac(h.mac.as_deref()?), h.name.clone()?)))
312        .collect()
313}
314
315/// The frequency band in MHz as text, like `2400` as `2.4 GHz`.
316pub(crate) fn band(megahertz: &str) -> Option<String> {
317    match megahertz {
318        "2400" => Some("2.4 GHz".to_owned()),
319        "5000" => Some("5 GHz".to_owned()),
320        "6000" => Some("6 GHz".to_owned()),
321        _ => None,
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn finds_networks_by_name() {
331        let wlan = Wlan {
332            service: "WLANConfiguration2".to_owned(),
333            ssid: Some("wlan-1".to_owned()),
334            ..Wlan::default()
335        };
336        for name in ["WLANConfiguration2", "wlanconfiguration2", "2", "wlan-1"] {
337            assert!(is_named(&wlan, name), "{name}");
338        }
339        for name in ["1", "WLANConfiguration1", "wlan", ""] {
340            assert!(!is_named(&wlan, name), "{name}");
341        }
342        let other = Wlan {
343            service: "2".to_owned(),
344            ..Wlan::default()
345        };
346        assert!(is_named(&other, "2"));
347        assert!(!is_named(&Wlan::default(), "1"));
348    }
349
350    #[test]
351    fn names_bands() {
352        assert_eq!(band("2400").as_deref(), Some("2.4 GHz"));
353        assert_eq!(band("5000").as_deref(), Some("5 GHz"));
354        assert_eq!(band("6000").as_deref(), Some("6 GHz"));
355        assert_eq!(band("unknown"), None);
356    }
357
358    #[test]
359    fn parses_the_list_of_clients() {
360        let xml = "<List><TotalAssociations>1</TotalAssociations><Item>\
361                   <AssociatedDeviceIndex>0</AssociatedDeviceIndex>\
362                   <AssociatedDeviceMACAddress>AA:BB:CC:00:00:01</AssociatedDeviceMACAddress>\
363                   <AssociatedDeviceIPAddress></AssociatedDeviceIPAddress>\
364                   <X_AVM-DE_Speed>72</X_AVM-DE_Speed>\
365                   <X_AVM-DE_SignalStrength>71</X_AVM-DE_SignalStrength>\
366                   <AssociatedDeviceChannel>6</AssociatedDeviceChannel>\
367                   <AssociatedDeviceGuest>1</AssociatedDeviceGuest>\
368                   </Item></List>";
369        assert_eq!(
370            client_list(xml).unwrap(),
371            [Listed {
372                client: Client {
373                    mac: Some("AA:BB:CC:00:00:01".to_owned()),
374                    signal: Some(71),
375                    rate: Some(72),
376                    ..Client::default()
377                },
378                channel: Some(6),
379                guest: Some(true),
380            }]
381        );
382        assert!(matches!(
383            client_list("<Other/>"),
384            Err(Error::InvalidDocument { .. })
385        ));
386    }
387
388    #[test]
389    fn assigns_clients_to_networks() {
390        let listed = |mac: &str, channel: Option<u32>, guest: Option<bool>| Listed {
391            client: Client {
392                mac: Some(mac.to_owned()),
393                ..Client::default()
394            },
395            channel,
396            guest,
397        };
398        let list = [
399            listed("1", Some(6), Some(false)),
400            listed("2", Some(48), Some(false)),
401            listed("3", Some(6), Some(true)),
402            listed("4", Some(6), None),
403            listed("5", None, Some(false)),
404        ];
405        let wlan = |channel: Option<u32>, guest: bool| Wlan {
406            channel,
407            guest,
408            ..Wlan::default()
409        };
410        let macs = |wlan: &Wlan| -> Vec<String> {
411            of_network(&list, wlan)
412                .into_iter()
413                .filter_map(|c| c.mac)
414                .collect()
415        };
416        assert_eq!(macs(&wlan(Some(6), false)), ["1", "4"]);
417        assert_eq!(macs(&wlan(Some(48), false)), ["2"]);
418        assert_eq!(macs(&wlan(Some(6), true)), ["3"]);
419        assert_eq!(macs(&wlan(None, false)), [] as [String; 0]);
420    }
421
422    #[test]
423    fn finds_names_by_mac() {
424        let host = |name: Option<&str>, mac: Option<&str>| status::Host {
425            name: name.map(str::to_owned),
426            mac: mac.map(str::to_owned),
427            ..status::Host::default()
428        };
429        let names = names(&[
430            host(Some("device-1"), Some("aa:bb:cc:00:00:01")),
431            host(None, Some("AA:BB:CC:00:00:02")),
432            host(Some("device-3"), None),
433        ]);
434        assert_eq!(names.len(), 1);
435        assert_eq!(names["AABBCC000001"], "device-1");
436    }
437}