Skip to main content

fritz_core/capture/
run.rs

1//! Calling the planned getters and storing their answers.
2
3use std::fmt;
4use std::fs;
5use std::io;
6use std::path::Path;
7use std::time::Duration;
8
9use serde_json::{Map, Value, json};
10use tr064::{Action, Client, Error, Service};
11
12use super::{Decision, Plan, shape, short_id};
13use crate::fault::Fault;
14use crate::redact;
15
16/// The getters that return the path of a list document: the action, the
17/// output with the path, and the file the document is stored in.
18const LISTS: [(&str, &str, &str); 2] = [
19    (
20        "X_AVM-DE_GetHostListPath",
21        "NewX_AVM-DE_HostListPath",
22        "devicehostlist.xml",
23    ),
24    (
25        "X_AVM-DE_GetMeshListPath",
26        "NewX_AVM-DE_MeshListPath",
27        "meshlist.json",
28    ),
29];
30
31/// How a capture runs.
32#[derive(Debug, Clone)]
33pub struct Options {
34    /// Also call the getters of personal lists.
35    pub include_personal: bool,
36    /// The most entries read of each indexed getter.
37    pub max_entries: u32,
38    /// The pause before each call, to keep the load on the device low.
39    pub delay: Duration,
40}
41
42impl Default for Options {
43    fn default() -> Self {
44        Self {
45            include_personal: false,
46            max_entries: 50,
47            delay: Duration::from_millis(100),
48        }
49    }
50}
51
52/// The answer to one call.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Response {
55    /// The [short ID](super::short_id) of the service.
56    pub service: String,
57    pub action: String,
58    /// The index for an indexed getter.
59    pub index: Option<u32>,
60    pub outcome: Outcome,
61}
62
63/// What a call returned. Values that could be secrets are already masked.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum Outcome {
66    /// The output arguments.
67    Ok(Vec<(String, String)>),
68    /// A UPnP error, for example 606 when the user lacks the right.
69    Fault { code: u16, description: String },
70    /// Another error that only concerns this call.
71    Failed(String),
72}
73
74/// A list document, fetched at the path a getter returned.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct List {
77    /// The file name, like `devicehostlist.xml`.
78    pub name: &'static str,
79    /// The document, or why it could not be fetched.
80    pub outcome: Result<String, String>,
81}
82
83/// The answers of a capture run.
84#[derive(Debug, Default)]
85pub struct Capture {
86    pub responses: Vec<Response>,
87    pub lists: Vec<List>,
88    /// The error that ended the run early, if any.
89    pub stopped: Option<Error>,
90}
91
92/// Calls the getters the plan decided to call, one after the other, and
93/// reports each answer to `progress`. An indexed getter is called with
94/// rising indexes until it fails or [`Options::max_entries`] is reached.
95/// The host and mesh lists are fetched at the paths their getters return.
96///
97/// Errors that concern a single call are recorded. The run stops at errors
98/// that would recur on every call or put the account at risk: missing or
99/// rejected credentials, a locked account, a failed connection or an
100/// unexpected certificate.
101pub async fn run(
102    client: &Client,
103    plan: &Plan,
104    options: &Options,
105    mut progress: impl FnMut(&Response),
106) -> Capture {
107    let mut capture = Capture::default();
108    let mut caller = Caller {
109        client,
110        options,
111        capture: &mut capture,
112        progress: &mut progress,
113    };
114    if let Err(error) = caller.all(plan).await {
115        capture.stopped = Some(error);
116    }
117    capture
118}
119
120struct Caller<'a, P> {
121    client: &'a Client,
122    options: &'a Options,
123    capture: &'a mut Capture,
124    progress: &'a mut P,
125}
126
127impl<P: FnMut(&Response)> Caller<'_, P> {
128    async fn all(&mut self, plan: &Plan) -> Result<(), Error> {
129        for service in &plan.services {
130            let Ok(scpd) = &service.scpd else { continue };
131            for (action, decision) in &scpd.actions {
132                self.action(&service.service, action, decision).await?;
133            }
134        }
135        Ok(())
136    }
137
138    async fn action(
139        &mut self,
140        service: &Service,
141        action: &Action,
142        decision: &Decision,
143    ) -> Result<(), Error> {
144        let decision = match decision {
145            Decision::Personal if self.options.include_personal => shape(action),
146            other => other.clone(),
147        };
148        match decision {
149            Decision::Call => {
150                self.call(service, action, None).await?;
151            }
152            Decision::Iterate { index } => {
153                for i in 0..self.options.max_entries {
154                    if !self.call(service, action, Some((&index, i))).await? {
155                        break;
156                    }
157                }
158            }
159            _ => {}
160        }
161        Ok(())
162    }
163
164    /// Calls the action and records the answer. Whether it succeeded, or the
165    /// error that ends the run.
166    async fn call(
167        &mut self,
168        service: &Service,
169        action: &Action,
170        index: Option<(&str, u32)>,
171    ) -> Result<bool, Error> {
172        tokio::time::sleep(self.options.delay).await;
173        let value = index.map(|(_, i)| i.to_string());
174        let arguments: Vec<(&str, &str)> = index
175            .iter()
176            .zip(&value)
177            .map(|((name, _), value)| (*name, value.as_str()))
178            .collect();
179        let mut list = None;
180        let outcome = match self.client.call(service, &action.name, &arguments).await {
181            Ok(out) => {
182                list = list_path(&action.name, |n| out.get(n));
183                Outcome::Ok(
184                    out.into_iter()
185                        .map(|(n, v)| {
186                            let v = redact::value(&n, &v);
187                            (n, v)
188                        })
189                        .collect(),
190                )
191            }
192            Err(error) if stops(&error) => return Err(error),
193            Err(Error::Upnp { code, description }) => Outcome::Fault { code, description },
194            Err(error) => Outcome::Failed(error.to_string()),
195        };
196        let ok = matches!(outcome, Outcome::Ok(_));
197        let response = Response {
198            service: short_id(service).to_owned(),
199            action: action.name.clone(),
200            index: index.map(|(_, i)| i),
201            outcome,
202        };
203        (self.progress)(&response);
204        self.capture.responses.push(response);
205        if let Some((name, path)) = list {
206            self.fetch(name, &path).await?;
207        }
208        Ok(ok)
209    }
210
211    /// Fetches a list document and records it, or the error that ends the
212    /// run.
213    async fn fetch(&mut self, name: &'static str, path: &str) -> Result<(), Error> {
214        tokio::time::sleep(self.options.delay).await;
215        let outcome = match self.client.get(path).await.map_err(redact::error) {
216            Ok(document) => Ok(document),
217            Err(error) if stops(&error) => return Err(error),
218            Err(error) => Err(error.to_string()),
219        };
220        self.capture.lists.push(List { name, outcome });
221        Ok(())
222    }
223}
224
225/// The file name and path of the list document whose path the action
226/// returned, if it is one of the [lists](LISTS). `out` gives the value of
227/// an output.
228fn list_path<'a>(
229    action: &str,
230    out: impl Fn(&str) -> Option<&'a str>,
231) -> Option<(&'static str, String)> {
232    let (_, output, name) = LISTS.iter().find(|(a, ..)| *a == action)?;
233    let path = out(output).filter(|p| !p.is_empty())?;
234    Some((name, path.to_owned()))
235}
236
237/// Whether an error ends the run instead of only the call.
238fn stops(error: &Error) -> bool {
239    matches!(
240        error,
241        Error::CredentialsRequired
242            | Error::AuthenticationFailed
243            | Error::UnsupportedAuth(_)
244            | Error::Http(_)
245            | Error::CertificateMismatch { .. }
246    ) || Fault::of(error) == Some(Fault::Blocked)
247}
248
249impl Capture {
250    /// How many calls succeeded, ended with a UPnP error, or failed otherwise.
251    pub fn counts(&self) -> (usize, usize, usize) {
252        let mut counts = (0, 0, 0);
253        for response in &self.responses {
254            match response.outcome {
255                Outcome::Ok(_) => counts.0 += 1,
256                Outcome::Fault { .. } => counts.1 += 1,
257                Outcome::Failed(_) => counts.2 += 1,
258            }
259        }
260        counts
261    }
262}
263
264impl fmt::Display for Capture {
265    /// A summary like `12 calls: 9 ok, 2 faults, 1 failed, 2 of 2 lists`,
266    /// without the lists if there were none.
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        let (ok, faults, failed) = self.counts();
269        let fetched = self.lists.iter().filter(|l| l.outcome.is_ok()).count();
270        let lists = match self.lists.len() {
271            0 => String::new(),
272            n => format!(", {fetched} of {n} lists"),
273        };
274        write!(
275            f,
276            "{} calls: {ok} ok, {faults} faults, {failed} failed{lists}",
277            self.responses.len()
278        )
279    }
280}
281
282impl Response {
283    /// The file name of the answer, like `GetInfo.json` or
284    /// `GetGenericHostEntry@3.json`.
285    fn file_name(&self) -> String {
286        match self.index {
287            Some(index) => format!("{}@{index}.json", self.action),
288            None => format!("{}.json", self.action),
289        }
290    }
291
292    fn to_json(&self) -> Value {
293        match &self.outcome {
294            Outcome::Ok(out) => {
295                let out: Map<String, Value> = out
296                    .iter()
297                    .map(|(n, v)| (n.clone(), Value::String(v.clone())))
298                    .collect();
299                json!({ "status": "ok", "out": out })
300            }
301            Outcome::Fault { code, description } => {
302                json!({ "status": "fault", "code": code, "description": description })
303            }
304            Outcome::Failed(error) => json!({ "status": "failed", "error": error }),
305        }
306    }
307}
308
309impl fmt::Display for Response {
310    /// A line like `Hosts1 GetGenericHostEntry@3: fault 713 SpecifiedArrayIndexInvalid`.
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        write!(f, "{} {}", self.service, self.action)?;
313        if let Some(index) = self.index {
314            write!(f, "@{index}")?;
315        }
316        match &self.outcome {
317            Outcome::Ok(out) => write!(f, ": ok, {} values", out.len()),
318            Outcome::Fault { code, description } => write!(f, ": fault {code} {description}"),
319            Outcome::Failed(error) => write!(f, ": failed, {error}"),
320        }
321    }
322}
323
324/// Writes the documents of the plan and the answers of the capture into the
325/// existing directory `dir`:
326///
327/// ```text
328/// tr64desc.xml
329/// scpd/<file>.xml
330/// responses/<service>/<action>.json
331/// responses/<service>/<action>@<index>.json
332/// lists/<name>
333/// ```
334///
335/// # Errors
336///
337/// The errors of writing the files.
338pub fn write(plan: &Plan, capture: &Capture, dir: &Path) -> io::Result<()> {
339    fs::write(dir.join("tr64desc.xml"), &plan.description)?;
340    let scpd_dir = dir.join("scpd");
341    fs::create_dir_all(&scpd_dir)?;
342    for service in &plan.services {
343        if let Ok(scpd) = &service.scpd {
344            let name = service
345                .service
346                .scpd_url
347                .rsplit('/')
348                .next()
349                .unwrap_or_default();
350            fs::write(scpd_dir.join(name), &scpd.xml)?;
351        }
352    }
353    for response in &capture.responses {
354        let service_dir = dir.join("responses").join(&response.service);
355        fs::create_dir_all(&service_dir)?;
356        let mut json = serde_json::to_string_pretty(&response.to_json())?;
357        json.push('\n');
358        fs::write(service_dir.join(response.file_name()), json)?;
359    }
360    for list in &capture.lists {
361        if let Ok(document) = &list.outcome {
362            let lists_dir = dir.join("lists");
363            fs::create_dir_all(&lists_dir)?;
364            fs::write(lists_dir.join(list.name), document)?;
365        }
366    }
367    Ok(())
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn finds_the_paths_of_lists() {
376        let out = |path: &'static str| {
377            move |name: &str| (name == "NewX_AVM-DE_HostListPath").then_some(path)
378        };
379        assert_eq!(
380            list_path("X_AVM-DE_GetHostListPath", out("/devicehostlist.lua?sid=1")),
381            Some(("devicehostlist.xml", "/devicehostlist.lua?sid=1".to_owned()))
382        );
383        assert_eq!(list_path("X_AVM-DE_GetHostListPath", out("")), None);
384        assert_eq!(list_path("X_AVM-DE_GetMeshListPath", out("/x")), None);
385        assert_eq!(list_path("GetInfo", out("/x")), None);
386    }
387
388    #[test]
389    fn stops_only_at_errors_that_recur() {
390        let locked = Error::Upnp {
391            code: 867,
392            description: "second factor authentication blocked".to_owned(),
393        };
394        let unauthorized = Error::Upnp {
395            code: 606,
396            description: "Action not authorized".to_owned(),
397        };
398        assert!(stops(&locked));
399        assert!(stops(&Error::AuthenticationFailed));
400        assert!(!stops(&unauthorized));
401        assert!(!stops(&Error::InvalidResponse("x".to_owned())));
402    }
403}