Skip to main content

fritz_core/
capture.rs

1//! What `fritz capture` reads from a device, and what it leaves alone.
2//!
3//! The capture only ever calls getters. Of those it skips the ones that need
4//! input other than an index, the ones that could return secrets, and the
5//! ones that return personal lists unless asked for. The decision depends
6//! only on the SCPD, so the plan can be reviewed before anything is called.
7
8use std::fmt;
9
10use tr064::{Action, Client, DeviceDescription, Direction, Scpd, Service};
11
12use crate::policy::{self, Class};
13
14mod run;
15
16pub use run::{Capture, List, Options, Outcome, Response, run, write};
17
18/// What the capture does with one action.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum Decision {
21    /// A getter without input: called once.
22    Call,
23    /// A getter whose only input is an index: called for each entry.
24    Iterate { index: String },
25    /// A getter that needs other input: not called.
26    NeedsInput { inputs: Vec<String> },
27    /// A getter for personal lists like calls or contacts: only called when
28    /// asked for.
29    Personal,
30    /// A getter that could return secrets: never called.
31    Denied { reason: String },
32    /// Not a getter: never called.
33    NotGetter,
34}
35
36/// Decides what the capture does with an action of a service, following
37/// its [class](policy::classify).
38pub fn decide(service: &Service, action: &Action) -> Decision {
39    match policy::classify(service, action) {
40        Class::Read => shape(action),
41        Class::Personal => Decision::Personal,
42        Class::Secret { reason } => Decision::Denied { reason },
43        Class::Write | Class::Critical { .. } => Decision::NotGetter,
44    }
45}
46
47/// How a getter is called, depending on its inputs: [`Decision::Call`],
48/// [`Decision::Iterate`] or [`Decision::NeedsInput`].
49fn shape(action: &Action) -> Decision {
50    let inputs: Vec<String> = action
51        .arguments
52        .iter()
53        .filter(|a| a.direction == Direction::In)
54        .map(|a| a.name.clone())
55        .collect();
56    match inputs.as_slice() {
57        [] => Decision::Call,
58        [index] if index.ends_with("Index") => Decision::Iterate {
59            index: index.clone(),
60        },
61        _ => Decision::NeedsInput { inputs },
62    }
63}
64
65/// The decisions for all actions of a device, with the documents they are
66/// based on.
67#[derive(Debug)]
68pub struct Plan {
69    /// The device description as the device sent it.
70    pub description: String,
71    pub services: Vec<ServicePlan>,
72}
73
74/// The decisions for the actions of one service, or why its SCPD could not
75/// be read.
76#[derive(Debug)]
77pub struct ServicePlan {
78    pub service: Service,
79    pub scpd: Result<ServiceScpd, tr064::Error>,
80}
81
82/// The SCPD of a service and the decision for each of its actions.
83#[derive(Debug)]
84pub struct ServiceScpd {
85    /// The SCPD as the device sent it.
86    pub xml: String,
87    pub actions: Vec<(Action, Decision)>,
88}
89
90/// Reads the device description and all SCPDs and decides for each action.
91/// Calls no action. A service whose SCPD cannot be read is part of the plan
92/// with its error.
93///
94/// # Errors
95///
96/// The errors of reading and parsing the device description.
97pub async fn plan(client: &Client) -> Result<Plan, tr064::Error> {
98    let description = client.get("/tr64desc.xml").await?;
99    let parsed = DeviceDescription::parse(&description)?;
100    let mut services = Vec::new();
101    for service in parsed.services() {
102        services.push(ServicePlan {
103            service: service.clone(),
104            scpd: plan_service(client, service).await,
105        });
106    }
107    Ok(Plan {
108        description,
109        services,
110    })
111}
112
113async fn plan_service(client: &Client, service: &Service) -> Result<ServiceScpd, tr064::Error> {
114    let xml = client.get(&service.scpd_url).await?;
115    let actions = Scpd::parse(&xml)?
116        .actions
117        .into_iter()
118        .map(|action| {
119            let decision = decide(service, &action);
120            (action, decision)
121        })
122        .collect();
123    Ok(ServiceScpd { xml, actions })
124}
125
126/// The last part of the service ID, like `Hosts1`. Unique within a device.
127pub fn short_id(service: &Service) -> &str {
128    service.service_id.rsplit(':').next().unwrap_or_default()
129}
130
131/// How many actions got each decision, and how many services failed.
132#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
133pub struct Summary {
134    pub call: usize,
135    pub iterate: usize,
136    pub needs_input: usize,
137    pub personal: usize,
138    pub denied: usize,
139    pub not_getter: usize,
140    pub failed_services: usize,
141}
142
143impl Summary {
144    fn count(&mut self, decision: &Decision) {
145        let counter = match decision {
146            Decision::Call => &mut self.call,
147            Decision::Iterate { .. } => &mut self.iterate,
148            Decision::NeedsInput { .. } => &mut self.needs_input,
149            Decision::Personal => &mut self.personal,
150            Decision::Denied { .. } => &mut self.denied,
151            Decision::NotGetter => &mut self.not_getter,
152        };
153        *counter += 1;
154    }
155}
156
157impl Plan {
158    /// Counts the decisions.
159    pub fn summary(&self) -> Summary {
160        let mut summary = Summary::default();
161        for service in &self.services {
162            match &service.scpd {
163                Ok(scpd) => scpd.actions.iter().for_each(|(_, d)| summary.count(d)),
164                Err(_) => summary.failed_services += 1,
165            }
166        }
167        summary
168    }
169}
170
171impl fmt::Display for Plan {
172    /// One block per service listing the getters, followed by a summary.
173    /// Actions that are not getters are only counted.
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        for service in &self.services {
176            write_service(f, service)?;
177        }
178        let s = self.summary();
179        write!(
180            f,
181            "{} services: {} to call, {} to iterate, {} need input, {} personal, \
182             {} denied, {} not getters, {} SCPDs failed",
183            self.services.len(),
184            s.call,
185            s.iterate,
186            s.needs_input,
187            s.personal,
188            s.denied,
189            s.not_getter,
190            s.failed_services
191        )
192    }
193}
194
195fn write_service(f: &mut fmt::Formatter<'_>, plan: &ServicePlan) -> fmt::Result {
196    let service = &plan.service;
197    let id = short_id(service);
198    writeln!(f, "{}:{} ({id})", service.name(), service.version())?;
199    match &plan.scpd {
200        Ok(scpd) => {
201            let mut not_getters = 0;
202            for (action, decision) in &scpd.actions {
203                match decision {
204                    Decision::NotGetter => not_getters += 1,
205                    _ => writeln!(f, "  {}", Line(&action.name, decision))?,
206                }
207            }
208            if not_getters > 0 {
209                writeln!(f, "  never        not getters: {not_getters}")?;
210            }
211        }
212        Err(error) => writeln!(f, "  SCPD failed: {error}")?,
213    }
214    writeln!(f)
215}
216
217/// One action of the plan, like `iterate      GetGenericHostEntry (NewIndex)`.
218struct Line<'a>(&'a str, &'a Decision);
219
220impl fmt::Display for Line<'_> {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        let Line(name, decision) = self;
223        match decision {
224            Decision::Call => write!(f, "call         {name}"),
225            Decision::Iterate { index } => write!(f, "iterate      {name} ({index})"),
226            Decision::NeedsInput { inputs } => {
227                write!(f, "needs input  {name} ({})", inputs.join(", "))
228            }
229            Decision::Personal => write!(f, "personal     {name}"),
230            Decision::Denied { reason } => write!(f, "denied       {name}: {reason}"),
231            Decision::NotGetter => write!(f, "never        {name}"),
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use tr064::Argument;
239
240    use super::*;
241
242    fn service(name: &str) -> Service {
243        Service {
244            service_type: format!("urn:dslforum-org:service:{name}:1"),
245            service_id: format!("urn:{name}-com:serviceId:{}1", name.to_lowercase()),
246            control_url: "/upnp/control/x".to_owned(),
247            event_sub_url: None,
248            scpd_url: "/x.xml".to_owned(),
249        }
250    }
251
252    fn action(name: &str, inputs: &[&str], outputs: &[&str]) -> Action {
253        let argument = |direction| {
254            move |name: &&str| Argument {
255                name: (*name).to_owned(),
256                direction,
257                related_state_variable: "X".to_owned(),
258            }
259        };
260        Action {
261            name: name.to_owned(),
262            arguments: inputs
263                .iter()
264                .map(argument(Direction::In))
265                .chain(outputs.iter().map(argument(Direction::Out)))
266                .collect(),
267        }
268    }
269
270    fn decide_for(service_name: &str, a: &Action) -> Decision {
271        decide(&service(service_name), a)
272    }
273
274    #[test]
275    fn calls_getters_without_input() {
276        let get_info = action("GetInfo", &[], &["NewSerialNumber"]);
277        assert_eq!(decide_for("DeviceInfo", &get_info), Decision::Call);
278        let avm = action("X_AVM-DE_GetNumberOfEntries", &[], &[]);
279        assert_eq!(decide_for("Hosts", &avm), Decision::Call);
280    }
281
282    #[test]
283    fn iterates_getters_with_only_an_index() {
284        let entry = action("GetGenericHostEntry", &["NewIndex"], &["NewIPAddress"]);
285        assert_eq!(
286            decide_for("Hosts", &entry),
287            Decision::Iterate {
288                index: "NewIndex".to_owned()
289            }
290        );
291    }
292
293    #[test]
294    fn skips_getters_that_need_other_input() {
295        for inputs in [&["NewMACAddress"][..], &["NewIndex", "NewOther"]] {
296            let a = action("GetSpecificHostEntry", inputs, &[]);
297            assert_eq!(
298                decide_for("Hosts", &a),
299                Decision::NeedsInput {
300                    inputs: inputs.iter().map(|s| (*s).to_owned()).collect()
301                }
302            );
303        }
304    }
305
306    #[test]
307    fn never_calls_other_actions() {
308        for name in [
309            "SetEnable",
310            "Reboot",
311            "X_AVM-DE_CreateUrlSID",
312            "X_AVM-DE_SetGet",
313        ] {
314            let a = action(name, &[], &[]);
315            assert_eq!(
316                decide_for("DeviceConfig", &a),
317                Decision::NotGetter,
318                "{name}"
319            );
320        }
321    }
322
323    #[test]
324    fn denies_getters_that_could_return_secrets() {
325        let cases = [
326            (
327                "DeviceConfig",
328                action("X_AVM-DE_GetConfigFile", &["NewX_AVM-DE_Password"], &[]),
329            ),
330            ("DeviceConfig", action("GetPersistentData", &[], &[])),
331            (
332                "X_VoIP",
333                action("X_AVM-DE_GetClient3", &["NewX_AVM-DE_ClientIndex"], &[]),
334            ),
335            ("WLANConfiguration", action("GetSecurityKeys", &[], &[])),
336            (
337                "WLANConfiguration",
338                action("GetInfo", &[], &["NewSSID", "NewWEPKey0"]),
339            ),
340            (
341                "WLANConfiguration",
342                action("X_AVM-DE_GetWPSInfo", &[], &["NewX_AVM-DE_WPSClientPIN"]),
343            ),
344            (
345                "LANConfigSecurity",
346                action("X_AVM-DE_GetCurrentUser", &[], &["NewX_AVM-DE_UserRights"]),
347            ),
348        ];
349        for (service_name, a) in &cases[..6] {
350            assert!(
351                matches!(decide_for(service_name, a), Decision::Denied { .. }),
352                "{}",
353                a.name
354            );
355        }
356        let (service_name, a) = &cases[6];
357        assert_eq!(decide_for(service_name, a), Decision::Call);
358        assert_eq!(
359            decide_for("WLANConfiguration", &cases[4].1),
360            Decision::Denied {
361                reason: "returns NewWEPKey0, which points to a secret".to_owned()
362            }
363        );
364    }
365
366    #[test]
367    fn calls_getters_that_only_describe_secrets() {
368        let cases = [
369            (
370                "WLANConfiguration",
371                action(
372                    "GetInfo",
373                    &[],
374                    &["NewMinCharsPSK", "NewMaxCharsPSK", "NewAllowedCharsPSK"],
375                ),
376            ),
377            (
378                "WLANConfiguration",
379                action("GetDefaultWEPKeyIndex", &[], &["NewDefaultWEPKeyIndex"]),
380            ),
381            (
382                "UserInterface",
383                action("GetInfo", &[], &["NewPasswordRequired"]),
384            ),
385            (
386                "X_VoIP",
387                action("GetInfoEx", &[], &["NewVoIPPasswordMinChars"]),
388            ),
389            (
390                "X_AVM-DE_WANMobileConnection",
391                action("GetInfo", &[], &["NewPINFailureCount"]),
392            ),
393            (
394                "WANPPPConnection",
395                action("GetInfo", &[], &["NewMaxCharsPassword", "NewUserName"]),
396            ),
397            (
398                "ManagementServer",
399                action("GetInfo", &[], &["NewUsername", "NewParameterKey"]),
400            ),
401        ];
402        for (service_name, a) in &cases {
403            assert_eq!(
404                decide_for(service_name, a),
405                Decision::Call,
406                "{service_name} {}",
407                a.name
408            );
409        }
410    }
411
412    #[test]
413    fn marks_personal_lists() {
414        for (service_name, name) in [
415            ("X_AVM-DE_OnTel", "GetCallList"),
416            ("X_AVM-DE_OnTel", "GetPhonebookList"),
417            ("X_AVM-DE_TAM", "GetMessageList"),
418            ("DeviceInfo", "GetDeviceLog"),
419        ] {
420            let a = action(name, &[], &[]);
421            assert_eq!(decide_for(service_name, &a), Decision::Personal, "{name}");
422        }
423        let deflections = action("GetDeflections", &[], &[]);
424        assert_eq!(decide_for("X_AVM-DE_OnTel", &deflections), Decision::Call);
425    }
426
427    #[test]
428    fn renders_every_decision() {
429        let lines = [
430            (Decision::Call, "call         A"),
431            (Decision::Personal, "personal     A"),
432            (Decision::NotGetter, "never        A"),
433        ];
434        for (decision, expected) in lines {
435            assert_eq!(Line("A", &decision).to_string(), expected);
436        }
437    }
438}