Skip to main content

fritz_core/
read.rs

1//! Reading a device: calls of actions that only read, through
2//! [`generic::call`], with the service descriptions read once.
3
4use std::collections::HashMap;
5use std::str::FromStr;
6
7use tr064::{Client, DeviceDescription, Scpd, Service, Url};
8
9use crate::generic::{self, Error};
10use crate::redact;
11
12/// Reads a device through a client with credentials.
13#[derive(Debug)]
14pub struct Reader {
15    client: Client,
16    description: DeviceDescription,
17    scpds: HashMap<String, Scpd>,
18}
19
20impl Reader {
21    /// Reads the device description.
22    ///
23    /// # Errors
24    ///
25    /// The errors of reading the device description.
26    pub async fn new(client: Client) -> Result<Self, Error> {
27        let description = client.description().await?;
28        Ok(Self {
29            client,
30            description,
31            scpds: HashMap::new(),
32        })
33    }
34
35    /// Calls an action that only reads, and returns its output with secrets
36    /// hidden.
37    ///
38    /// # Errors
39    ///
40    /// The errors of finding the service and the action, of
41    /// [`generic::check`], and of the call.
42    pub async fn read(
43        &mut self,
44        reference: &str,
45        name: &str,
46        arguments: &[(&str, &str)],
47    ) -> Result<Values, Error> {
48        let output = self.output(reference, name, arguments).await?;
49        let (service, _) = self.service(reference).await?;
50        Ok(Values(
51            output
52                .into_iter()
53                .map(|(name, value)| {
54                    let value = redact::output(&service, &name, &value);
55                    (name, value)
56                })
57                .collect(),
58        ))
59    }
60
61    /// Fetches a document whose path an action without inputs returns, like
62    /// the host list at the path `X_AVM-DE_GetHostListPath` returns in
63    /// `NewX_AVM-DE_HostListPath`. The path holds a session ID, which never
64    /// leaves this function. `None` if the device has no such action, or
65    /// answers it with a fault or without a path, like
66    /// [`try_read`](Self::try_read).
67    ///
68    /// # Errors
69    ///
70    /// The other errors of the call, and the errors of fetching the
71    /// document.
72    pub async fn document(
73        &mut self,
74        reference: &str,
75        name: &str,
76        output: &str,
77    ) -> Result<Option<String>, Error> {
78        self.document_with(reference, (name, &[]), output, "").await
79    }
80
81    /// Like [`document`](Self::document), for an action with inputs, like
82    /// `GetPhonebook` with `NewPhonebookID`, and with `query` added to the
83    /// query of the path, like `max=10`. An action can return a full URL,
84    /// like the call list on the address of the device; only its path and
85    /// query are fetched, from the device of this reader.
86    ///
87    /// # Errors
88    ///
89    /// The errors of [`document`](Self::document).
90    pub async fn document_with(
91        &mut self,
92        reference: &str,
93        (name, arguments): (&str, &[(&str, &str)]),
94        output: &str,
95        query: &str,
96    ) -> Result<Option<String>, Error> {
97        let values = match self.output(reference, name, arguments).await {
98            Ok(values) => values,
99            Err(error) if is_missing(&error) => return Ok(None),
100            Err(error) => return Err(error),
101        };
102        let Some((_, location)) = values.iter().find(|(n, v)| n == output && !v.is_empty()) else {
103            return Ok(None);
104        };
105        let path = local(location, query);
106        Ok(Some(self.client.get(&path).await.map_err(redact::error)?))
107    }
108
109    /// Calls an action that only reads, and returns its output as it is,
110    /// without redaction: for values that must stay verbatim, like the SSID
111    /// in [`wlan::join`](crate::wlan::join), never to show or log.
112    pub(crate) async fn output(
113        &mut self,
114        reference: &str,
115        name: &str,
116        arguments: &[(&str, &str)],
117    ) -> Result<Vec<(String, String)>, Error> {
118        let (service, _) = self.service(reference).await?;
119        let scpd = &self.scpds[&service.service_id];
120        let action = generic::action(&service, scpd, name)?;
121        let arguments: Vec<(String, String)> = arguments
122            .iter()
123            .map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
124            .collect();
125        generic::send(&self.client, &service, action, &arguments).await
126    }
127
128    /// Like [`read`](Self::read), but `None` if the device has no such
129    /// service or action, or answers with a fault, like 606 for missing
130    /// rights.
131    ///
132    /// # Errors
133    ///
134    /// The other errors of [`read`](Self::read), like failed logins and
135    /// connections.
136    pub async fn try_read(
137        &mut self,
138        reference: &str,
139        name: &str,
140        arguments: &[(&str, &str)],
141    ) -> Result<Option<Values>, Error> {
142        match self.read(reference, name, arguments).await {
143            Ok(values) => Ok(Some(values)),
144            Err(error) if is_missing(&error) => Ok(None),
145            Err(error) => Err(error),
146        }
147    }
148
149    /// Reads a list the device gives one entry per call: the number of
150    /// entries from the output `count` of the action `counter`, then the
151    /// entries from `getter` with each index as its input `index`, up to
152    /// `max`. Stops early at the first index the device has no entry for.
153    /// Returns the number the device reported and the entries, or `None`
154    /// like [`try_read`](Self::try_read) if it has no such list.
155    ///
156    /// # Errors
157    ///
158    /// The other errors of [`read`](Self::read).
159    pub async fn entries(
160        &mut self,
161        reference: &str,
162        (counter, count): (&str, &str),
163        (getter, index): (&str, &str),
164        max: u32,
165    ) -> Result<Option<(u32, Vec<Values>)>, Error> {
166        let Some(values) = self.try_read(reference, counter, &[]).await? else {
167            return Ok(None);
168        };
169        let reported: u32 = values.number(count).unwrap_or_default();
170        let mut entries = Vec::new();
171        for i in 0..reported.min(max) {
172            let i = i.to_string();
173            let Some(entry) = self.try_read(reference, getter, &[(index, &i)]).await? else {
174                break;
175            };
176            entries.push(entry);
177        }
178        Ok(Some((reported, entries)))
179    }
180
181    /// The client, for the one call of a secret getter in
182    /// [`wlan::join`](crate::wlan::join), which does not pass
183    /// [`generic::check`].
184    pub(crate) fn client(&self) -> &Client {
185        &self.client
186    }
187
188    /// The device description.
189    pub fn description(&self) -> &DeviceDescription {
190        &self.description
191    }
192
193    /// A service and its description, which is read once.
194    ///
195    /// # Errors
196    ///
197    /// The errors of finding the service and of reading its description.
198    pub async fn service(&mut self, reference: &str) -> Result<(Service, &Scpd), Error> {
199        let service = self.description.service(reference)?.clone();
200        if !self.scpds.contains_key(&service.service_id) {
201            let scpd = self.client.scpd(&service).await?;
202            self.scpds.insert(service.service_id.clone(), scpd);
203        }
204        let scpd = &self.scpds[&service.service_id];
205        Ok((service, scpd))
206    }
207
208    /// The short ids of the services whose name is `name`, like
209    /// `WLANConfiguration1` and `WLANConfiguration2`, in order.
210    pub fn services(&self, name: &str) -> Vec<String> {
211        self.description
212            .services()
213            .filter(|s| s.name() == name)
214            .map(|s| crate::capture::short_id(s).to_owned())
215            .collect()
216    }
217}
218
219/// The path and query of `location`, a path or a full URL, with `query`
220/// added.
221fn local(location: &str, query: &str) -> String {
222    let path = match Url::parse(location) {
223        Ok(url) => match url.query() {
224            Some(q) => format!("{}?{q}", url.path()),
225            None => url.path().to_owned(),
226        },
227        Err(_) => location.to_owned(),
228    };
229    match (query.is_empty(), path.contains('?')) {
230        (true, _) => path,
231        (false, true) => format!("{path}&{query}"),
232        (false, false) => format!("{path}?{query}"),
233    }
234}
235
236/// Whether the error says that the device lacks something, or keeps it from
237/// this user, rather than that it could not be asked. Blocked and busy
238/// confirmations are failures: the device holds back the next calls too.
239pub(crate) fn is_missing(error: &Error) -> bool {
240    match error {
241        Error::UnknownAction { .. } => true,
242        Error::Fault { fault, .. } => !fault.is_temporary(),
243        Error::Tr064(error) => {
244            error.upnp_code().is_some() || matches!(error, tr064::Error::UnknownService(_))
245        }
246        _ => false,
247    }
248}
249
250/// Values from pairs of names and values, for tests.
251#[cfg(test)]
252pub(crate) fn values(pairs: &[(&str, &str)]) -> Values {
253    Values(
254        pairs
255            .iter()
256            .map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
257            .collect(),
258    )
259}
260
261/// The output arguments of a call.
262#[derive(Debug, Clone, Default, PartialEq, Eq)]
263pub struct Values(pub Vec<(String, String)>);
264
265impl Values {
266    /// The value of an argument.
267    pub fn get(&self, name: &str) -> Option<&str> {
268        self.0
269            .iter()
270            .find(|(n, _)| n == name)
271            .map(|(_, v)| v.as_str())
272    }
273
274    /// The value of an argument, unless it is empty.
275    pub fn text(&self, name: &str) -> Option<String> {
276        self.get(name).filter(|v| !v.is_empty()).map(str::to_owned)
277    }
278
279    /// The value of an argument as a number, if it is one.
280    pub fn number<T: FromStr>(&self, name: &str) -> Option<T> {
281        self.get(name).and_then(|v| v.trim().parse().ok())
282    }
283
284    /// The value of a boolean argument: `1` or `0`.
285    pub fn flag(&self, name: &str) -> Option<bool> {
286        match self.get(name)? {
287            "1" | "true" => Some(true),
288            "0" | "false" => Some(false),
289            _ => None,
290        }
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn reads_values() {
300        let values = Values(vec![
301            ("NewName".to_owned(), "box".to_owned()),
302            ("NewEmpty".to_owned(), String::new()),
303            ("NewCount".to_owned(), " 42".to_owned()),
304            ("NewOn".to_owned(), "1".to_owned()),
305            ("NewOff".to_owned(), "false".to_owned()),
306        ]);
307        assert_eq!(values.get("NewName"), Some("box"));
308        assert_eq!(values.get("NewOther"), None);
309        assert_eq!(values.text("NewName").as_deref(), Some("box"));
310        assert_eq!(values.text("NewEmpty"), None);
311        assert_eq!(values.number::<u32>("NewCount"), Some(42));
312        assert_eq!(values.number::<u32>("NewName"), None);
313        assert_eq!(values.flag("NewOn"), Some(true));
314        assert_eq!(values.flag("NewOff"), Some(false));
315        assert_eq!(values.flag("NewName"), None);
316        assert_eq!(values.flag("NewOther"), None);
317    }
318
319    #[test]
320    fn keeps_the_path_of_a_location() {
321        assert_eq!(local("/list.lua?sid=1", ""), "/list.lua?sid=1");
322        assert_eq!(local("/list.lua?sid=1", "max=5"), "/list.lua?sid=1&max=5");
323        assert_eq!(local("/list.lua", "max=5"), "/list.lua?max=5");
324        assert_eq!(
325            local("https://192.0.2.1:49443/calllist.lua?sid=1", ""),
326            "/calllist.lua?sid=1"
327        );
328        assert_eq!(
329            local("http://192.0.2.1/phonebook.lua", ""),
330            "/phonebook.lua"
331        );
332    }
333
334    #[test]
335    fn tells_missing_things_from_failures() {
336        let unknown = Error::UnknownAction {
337            service: "Hosts1".to_owned(),
338            action: "Nothing".to_owned(),
339        };
340        assert!(is_missing(&unknown));
341        let service = Error::Tr064(tr064::Error::UnknownService("Nothing1".to_owned()));
342        assert!(is_missing(&service));
343        assert!(!is_missing(&Error::Tr064(
344            tr064::Error::AuthenticationFailed
345        )));
346        for (code, missing) in [
347            (606, true),
348            (713, true),
349            (866, true),
350            (867, false),
351            (868, false),
352        ] {
353            let error = Error::from(tr064::Error::Upnp {
354                code,
355                description: String::new(),
356            });
357            assert_eq!(is_missing(&error), missing, "{code}");
358        }
359        let refused = Error::MissingArgument {
360            action: "GetGenericHostEntry".to_owned(),
361            argument: "NewIndex".to_owned(),
362        };
363        assert!(!is_missing(&refused));
364    }
365}