Skip to main content

fritz_core/wlan/
details.rs

1//! The security settings, the radio, WPS, the night time switch-off and the
2//! statistics of a wireless network, with hints on weak settings.
3//!
4//! Only plain getters are called. `GetSecurityKeys` and other getters that
5//! return keys are never called, so no passphrase is read.
6
7use std::fmt;
8
9use serde::Serialize;
10
11use crate::generic::Error;
12use crate::read::{Reader, Values};
13
14/// The details of a wireless network. A field is `None` if the device does
15/// not report it.
16#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
17pub struct Details {
18    pub security: Security,
19    pub radio: Radio,
20    pub wps: Wps,
21    pub night: Night,
22    pub statistics: Statistics,
23    /// Weak settings, as hints rather than errors.
24    pub hints: Vec<Hint>,
25}
26
27/// How a network is secured.
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
29pub struct Security {
30    /// As the device names it, like `11i` or `11iandWPA3`.
31    pub beacon_type: Option<String>,
32    /// The beacon type as text, like `WPA2/WPA3 mixed, AES`.
33    pub encryption: Option<String>,
34    /// The beacon types the device offers.
35    pub possible_beacon_types: Option<Vec<String>>,
36    /// The encryption of the beacon type `Basic`, like `WEPEncryption`.
37    pub basic_encryption: Option<String>,
38    /// The authentication of the beacon type `Basic`.
39    pub basic_authentication: Option<String>,
40    /// Whether the SSID is not advertised.
41    pub hidden: Option<bool>,
42    /// Whether only known MAC addresses may connect.
43    pub mac_filter: Option<bool>,
44    /// Whether the clients cannot reach each other, as on a guest network.
45    pub user_isolation: Option<bool>,
46}
47
48/// The radio of a network.
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
50pub struct Radio {
51    pub channel: Option<u32>,
52    /// Whether the device chooses the channel.
53    pub auto_channel: Option<bool>,
54    /// The channels the device offers.
55    pub possible_channels: Option<Vec<u32>>,
56    pub bssid: Option<String>,
57    /// Like `Auto`.
58    pub max_bit_rate: Option<String>,
59    /// Whether the network is optimized for IPTV.
60    pub iptv_optimized: Option<bool>,
61}
62
63/// Wi-Fi Protected Setup.
64#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
65pub struct Wps {
66    /// Whether WPS is on, by its status; `None` if the status, like
67    /// `err_common`, does not tell.
68    pub enabled: Option<bool>,
69    /// Like `stop` or `pbc`.
70    pub mode: Option<String>,
71    /// Like `off`, `inactive` or `active`.
72    pub status: Option<String>,
73}
74
75/// The night time switch-off of the wireless function.
76#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
77pub struct Night {
78    /// The schedule as the device reports it; `None` without one.
79    pub schedule: Option<String>,
80    /// Whether the wireless function stays on while clients are connected.
81    pub no_forced_off: Option<bool>,
82}
83
84/// The packets since the last restart.
85#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
86pub struct Statistics {
87    pub packets_sent: Option<u64>,
88    pub packets_received: Option<u64>,
89}
90
91/// A weak setting of a network.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
93#[serde(rename_all = "snake_case")]
94pub enum Hint {
95    /// No encryption.
96    OpenNetwork,
97    /// WEP, which is broken.
98    Wep,
99    /// WPA with TKIP, which is broken, is allowed.
100    TkipAllowed,
101    WpsEnabled,
102    HiddenSsid,
103}
104
105impl fmt::Display for Hint {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.write_str(match self {
108            Self::OpenNetwork => "open network",
109            Self::Wep => "WEP",
110            Self::TkipAllowed => "TKIP allowed",
111            Self::WpsEnabled => "WPS enabled",
112            Self::HiddenSsid => "hidden SSID",
113        })
114    }
115}
116
117/// Reads the details of the network of `service`, whose answers to
118/// `GetInfo` and `X_AVM-DE_GetWLANExtInfo` are `info` and `ext`. Getters the
119/// device lacks leave their fields `None`.
120///
121/// # Errors
122///
123/// The errors of [`Reader::try_read`].
124pub(super) async fn read(
125    reader: &mut Reader,
126    service: &str,
127    info: &Values,
128    ext: Option<&Values>,
129) -> Result<Details, Error> {
130    let channel = reader.try_read(service, "GetChannelInfo", &[]).await?;
131    let advertised = reader
132        .try_read(service, "GetBeaconAdvertisement", &[])
133        .await?
134        .and_then(|v| v.flag("NewBeaconAdvertisementEnabled"));
135    let wps = reader.try_read(service, "X_AVM-DE_GetWPSInfo", &[]).await?;
136    let night = reader
137        .try_read(service, "X_AVM-DE_GetNightControl", &[])
138        .await?;
139    let mut statistics = reader.try_read(service, "GetStatistics", &[]).await?;
140    if statistics.is_none() {
141        statistics = reader.try_read(service, "GetPacketStatistics", &[]).await?;
142    }
143    let iptv = reader
144        .try_read(service, "X_AVM-DE_GetIPTVOptimized", &[])
145        .await?
146        .and_then(|v| v.flag("NewX_AVM-DE_IPTVoptimize"));
147
148    let beacon_type = info.text("NewBeaconType");
149    let basic_encryption = info.text("NewBasicEncryptionModes");
150    let security = Security {
151        encryption: beacon_type
152            .as_deref()
153            .and_then(|b| encryption(b, basic_encryption.as_deref()))
154            .map(str::to_owned),
155        possible_beacon_types: info
156            .text("NewX_AVM-DE_PossibleBeaconTypes")
157            .map(|t| list(&t)),
158        basic_authentication: info.text("NewBasicAuthenticationMode"),
159        hidden: advertised.map(|a| !a),
160        mac_filter: info.flag("NewMACAddressControlEnabled"),
161        user_isolation: ext.and_then(|e| e.flag("NewX_AVM-DE_UserIsolation")),
162        beacon_type,
163        basic_encryption,
164    };
165    let radio = Radio {
166        channel: channel
167            .as_ref()
168            .and_then(|c| c.number("NewChannel"))
169            .or_else(|| info.number("NewChannel")),
170        auto_channel: channel
171            .as_ref()
172            .and_then(|c| c.flag("NewX_AVM-DE_AutoChannelEnabled")),
173        possible_channels: channel
174            .as_ref()
175            .and_then(|c| c.text("NewPossibleChannels"))
176            .map(|c| list(&c).iter().filter_map(|n| n.parse().ok()).collect()),
177        bssid: info.text("NewBSSID"),
178        max_bit_rate: info.text("NewMaxBitRate"),
179        iptv_optimized: iptv,
180    };
181    let wps_status = wps.as_ref().and_then(|w| w.text("NewX_AVM-DE_WPSStatus"));
182    let wps = Wps {
183        enabled: wps_status.as_deref().and_then(wps_enabled),
184        mode: wps.as_ref().and_then(|w| w.text("NewX_AVM-DE_WPSMode")),
185        status: wps_status,
186    };
187    let night = Night {
188        schedule: night.as_ref().and_then(|n| n.text("NewNightControl")),
189        no_forced_off: night
190            .as_ref()
191            .and_then(|n| n.flag("NewNightTimeControlNoForcedOff")),
192    };
193    let statistics = Statistics {
194        packets_sent: statistics
195            .as_ref()
196            .and_then(|s| s.number("NewTotalPacketsSent")),
197        packets_received: statistics
198            .as_ref()
199            .and_then(|s| s.number("NewTotalPacketsReceived")),
200    };
201    let mut details = Details {
202        security,
203        radio,
204        wps,
205        night,
206        statistics,
207        hints: Vec::new(),
208    };
209    details.hints = hints(&details);
210    Ok(details)
211}
212
213/// The beacon type as text, with the encryption of `Basic` beacons, like
214/// `WEPEncryption`.
215fn encryption(beacon_type: &str, basic: Option<&str>) -> Option<&'static str> {
216    Some(match beacon_type {
217        "Basic" if basic.is_some_and(|b| b.contains("WEP")) => "WEP",
218        "None" | "Basic" => "none",
219        "WPA" => "WPA, TKIP",
220        "11i" => "WPA2, AES",
221        "WPAand11i" => "WPA/WPA2 mixed, TKIP and AES",
222        "11iandWPA3" => "WPA2/WPA3 mixed, AES",
223        "WPA3" => "WPA3, AES",
224        "OWE" => "Enhanced Open (OWE)",
225        "OWETrans" => "Enhanced Open (OWE), transition mode",
226        _ => return None,
227    })
228}
229
230/// Whether WPS is on, by its status: `off` is off, `inactive` is on but not
231/// running, `active` and `success` are on. Errors do not tell.
232fn wps_enabled(status: &str) -> Option<bool> {
233    match status {
234        "off" => Some(false),
235        "inactive" | "active" | "success" => Some(true),
236        _ => None,
237    }
238}
239
240/// The weak settings of a network.
241fn hints(details: &Details) -> Vec<Hint> {
242    let security = &details.security;
243    let mut hints = Vec::new();
244    match security.encryption.as_deref() {
245        Some("none") => hints.push(Hint::OpenNetwork),
246        Some("WEP") => hints.push(Hint::Wep),
247        _ => {}
248    }
249    if matches!(security.beacon_type.as_deref(), Some("WPA" | "WPAand11i")) {
250        hints.push(Hint::TkipAllowed);
251    }
252    if details.wps.enabled == Some(true) {
253        hints.push(Hint::WpsEnabled);
254    }
255    if security.hidden == Some(true) {
256        hints.push(Hint::HiddenSsid);
257    }
258    hints
259}
260
261/// The items of a comma-separated list, without empty ones.
262fn list(text: &str) -> Vec<String> {
263    text.split(',')
264        .map(str::trim)
265        .filter(|i| !i.is_empty())
266        .map(str::to_owned)
267        .collect()
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn names_the_encryption() {
276        assert_eq!(encryption("None", None), Some("none"));
277        assert_eq!(encryption("Basic", Some("WEPEncryption")), Some("WEP"));
278        assert_eq!(encryption("Basic", Some("None")), Some("none"));
279        assert_eq!(encryption("WPA", None), Some("WPA, TKIP"));
280        assert_eq!(encryption("11i", None), Some("WPA2, AES"));
281        assert_eq!(
282            encryption("WPAand11i", None),
283            Some("WPA/WPA2 mixed, TKIP and AES")
284        );
285        assert_eq!(encryption("11iandWPA3", None), Some("WPA2/WPA3 mixed, AES"));
286        assert_eq!(encryption("WPA3", None), Some("WPA3, AES"));
287        assert_eq!(encryption("OWE", None), Some("Enhanced Open (OWE)"));
288        assert_eq!(
289            encryption("OWETrans", None),
290            Some("Enhanced Open (OWE), transition mode")
291        );
292        assert_eq!(encryption("Other", None), None);
293    }
294
295    #[test]
296    fn tells_whether_wps_is_on() {
297        assert_eq!(wps_enabled("off"), Some(false));
298        assert_eq!(wps_enabled("inactive"), Some(true));
299        assert_eq!(wps_enabled("active"), Some(true));
300        assert_eq!(wps_enabled("success"), Some(true));
301        assert_eq!(wps_enabled("err_common"), None);
302    }
303
304    #[test]
305    fn finds_weak_settings() {
306        let details = |beacon: &str, basic: Option<&str>, wps: Option<bool>, hidden| Details {
307            security: Security {
308                beacon_type: Some(beacon.to_owned()),
309                encryption: encryption(beacon, basic).map(str::to_owned),
310                hidden,
311                ..Security::default()
312            },
313            wps: Wps {
314                enabled: wps,
315                ..Wps::default()
316            },
317            ..Details::default()
318        };
319        assert_eq!(
320            hints(&details("11iandWPA3", None, Some(false), Some(false))),
321            []
322        );
323        assert_eq!(hints(&details("11i", None, None, None)), []);
324        assert_eq!(
325            hints(&details("None", None, Some(true), Some(true))),
326            [Hint::OpenNetwork, Hint::WpsEnabled, Hint::HiddenSsid]
327        );
328        assert_eq!(
329            hints(&details("Basic", Some("WEPEncryption"), None, None)),
330            [Hint::Wep]
331        );
332        assert_eq!(
333            hints(&details("WPA", None, None, None)),
334            [Hint::TkipAllowed]
335        );
336        assert_eq!(
337            hints(&details("WPAand11i", None, None, None)),
338            [Hint::TkipAllowed]
339        );
340        let text: Vec<String> = [
341            Hint::OpenNetwork,
342            Hint::Wep,
343            Hint::TkipAllowed,
344            Hint::WpsEnabled,
345            Hint::HiddenSsid,
346        ]
347        .iter()
348        .map(ToString::to_string)
349        .collect();
350        assert_eq!(
351            text,
352            [
353                "open network",
354                "WEP",
355                "TKIP allowed",
356                "WPS enabled",
357                "hidden SSID"
358            ]
359        );
360    }
361
362    #[test]
363    fn splits_lists() {
364        assert_eq!(list("None, 11i,,WPA3"), ["None", "11i", "WPA3"]);
365        assert_eq!(list(""), [] as [String; 0]);
366    }
367}