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