fritz-sim 0.2.1

Stateful fake TR-064 server built from recorded FRITZ!Box fixtures, for tests (unofficial, not affiliated with FRITZ! GmbH)
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! The simulated device: how it answers action calls, and the state that
//! writes change.
//!
//! Every argument of an action refers to a state variable of its service.
//! The state starts with the output arguments of the recorded getters.
//! Calls of other actions write their input arguments into the state.
//! Getters answer as recorded, except for the variables written since, and
//! answer from the state if they were not recorded. This makes a write
//! visible to the getters that read the same variable, without knowing
//! anything about the device.
//!
//! Recorded answers take precedence over the state because getters of the
//! same service can answer differently for the same variable: the device
//! might leave a value empty in one of them.

use std::collections::HashMap;

use tr064::{Action, Direction, Scpd, Service, StateVariable};

use crate::fixture::{Answer, Fixture, Recording};

/// A UPnP error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Fault {
    pub(crate) code: u16,
    pub(crate) description: String,
}

impl Fault {
    /// The error with the given code and its usual description.
    pub(crate) fn new(code: u16) -> Self {
        Self {
            code,
            description: description(code).to_owned(),
        }
    }
}

const INVALID_ACTION: u16 = 401;
const INVALID_ARGS: u16 = 402;
const INVALID_VALUE: u16 = 600;
const INVALID_INDEX: u16 = 713;
const NO_SUCH_ENTRY: u16 = 714;

/// The usual description of a UPnP error code, as FRITZ!Box devices send
/// it.
fn description(code: u16) -> &'static str {
    match code {
        INVALID_ACTION => "Invalid Action",
        INVALID_ARGS => "Invalid Args",
        501 => "Action Failed",
        INVALID_VALUE => "Argument Value Invalid",
        601 => "Argument Value Out of Range",
        606 => "Action not authorized",
        INVALID_INDEX => "SpecifiedArrayIndexInvalid",
        NO_SUCH_ENTRY => "NoSuchEntryInArray",
        820 => "Internal Error",
        866 => "second factor authentication required",
        867 => "second factor authentication blocked",
        868 => "second factor authentication busy",
        _ => "Unknown Error",
    }
}

/// What tests changed about the next call.
#[derive(Debug, Default)]
pub(crate) struct Hooks {
    /// The call fails with this error once its arguments are valid.
    pub(crate) fault: Option<Fault>,
    /// Writes succeed, but change nothing.
    pub(crate) discard_writes: bool,
    /// The state variables a write sets as well, with their values.
    pub(crate) side_effects: Vec<(String, String)>,
    /// The state variables that grow before a getter answers them: the
    /// variable, the step and where it wraps around.
    pub(crate) counters: Vec<(String, u64, Option<u64>)>,
}

#[derive(Debug)]
pub(crate) struct Device {
    pub(crate) fixture: Fixture,
    /// The recorded values of the state variables by service, like
    /// `Hosts1`, and variable.
    recorded: HashMap<(String, String), String>,
    /// The values written since the start, by service and variable.
    written: HashMap<(String, String), String>,
}

impl Device {
    pub(crate) fn new(fixture: Fixture) -> Self {
        let mut recorded = HashMap::new();
        for service in fixture.description.services() {
            let Some(scpd) = fixture.scpd(service) else {
                continue;
            };
            let id = short_id(service);
            for action in &scpd.actions {
                let recording = fixture
                    .recordings
                    .get(&(id.to_owned(), action.name.clone()));
                let Some(Answer::Ok(out)) = recording.and_then(|r| r.once.as_ref()) else {
                    continue;
                };
                recorded.extend(outputs(action).filter_map(|argument| {
                    let value = out.get(&argument.name)?;
                    let key = (id.to_owned(), argument.related_state_variable.clone());
                    Some((key, value.clone()))
                }));
            }
        }
        Self {
            fixture,
            recorded,
            written: HashMap::new(),
        }
    }

    /// The value of a state variable of the service `id`, like `Hosts1`.
    pub(crate) fn state(&self, id: &str, variable: &str) -> Option<&str> {
        let key = (id.to_owned(), variable.to_owned());
        self.written
            .get(&key)
            .or_else(|| self.recorded.get(&key))
            .map(String::as_str)
    }

    /// Makes the getter `getter` of the service `id`, like `DeviceInfo1`,
    /// answer `value` for its output argument `argument` from now on. `None`
    /// if it has no such argument.
    pub(crate) fn set_output(
        &mut self,
        id: &str,
        getter: &str,
        argument: &str,
        value: &str,
    ) -> Option<()> {
        let fixture = &self.fixture;
        let service = fixture.description.services().find(|s| short_id(s) == id)?;
        let action = fixture.scpd(service)?.action(getter)?;
        let variable = &outputs(action)
            .find(|a| a.name == argument)?
            .related_state_variable;
        let key = (id.to_owned(), variable.clone());
        self.written.insert(key, value.to_owned());
        Some(())
    }

    /// Answers a call of `action` with `arguments`: the output arguments, or
    /// the error.
    pub(crate) fn call(
        &mut self,
        service: &Service,
        action: &str,
        arguments: &[(String, String)],
        hooks: &Hooks,
    ) -> Result<Vec<(String, String)>, Fault> {
        let id = short_id(service);
        let scpd = self
            .fixture
            .scpd(service)
            .ok_or_else(|| Fault::new(INVALID_ACTION))?;
        let action = scpd
            .action(action)
            .ok_or_else(|| Fault::new(INVALID_ACTION))?;
        validate(scpd, action, arguments)?;
        if let Some(fault) = &hooks.fault {
            return Err(fault.clone());
        }
        if is_getter(&action.name) {
            for (variable, step, wrap) in &hooks.counters {
                if outputs(action).any(|a| &a.related_state_variable == variable) {
                    let key = (id.to_owned(), variable.clone());
                    let now = self.written.get(&key).or_else(|| self.recorded.get(&key));
                    let next = count(now.map(String::as_str), *step, *wrap);
                    self.written.insert(key, next);
                }
            }
        }
        let recording = self
            .fixture
            .recordings
            .get(&(id.to_owned(), action.name.clone()));
        if let Some(recording) = recording.filter(|r| !r.indexed.is_empty()) {
            return indexed(action, recording, arguments);
        }
        if recording.is_none()
            && let Some(answer) = self.host_entry(id, action, arguments)
        {
            return answer;
        }
        let out = match recording.and_then(|r| r.once.as_ref()) {
            Some(Answer::Fault { code, description }) if is_getter(&action.name) => {
                return Err(Fault {
                    code: *code,
                    description: description.clone(),
                });
            }
            Some(Answer::Ok(out)) => Some(out),
            _ => None,
        };
        if !(is_getter(&action.name) || hooks.discard_writes) {
            let written = arguments.iter().filter_map(|(name, value)| {
                let argument = action.arguments.iter().find(|a| &a.name == name)?;
                let key = (id.to_owned(), argument.related_state_variable.clone());
                Some((key, value.clone()))
            });
            self.written.extend(written);
            let side_effects = hooks
                .side_effects
                .iter()
                .map(|(variable, value)| ((id.to_owned(), variable.clone()), value.clone()));
            self.written.extend(side_effects);
        }
        Ok(outputs(action)
            .map(|argument| {
                let variable = &argument.related_state_variable;
                let key = (id.to_owned(), variable.clone());
                let value = self
                    .written
                    .get(&key)
                    .or_else(|| out.and_then(|out| out.get(&argument.name)))
                    .or_else(|| self.recorded.get(&key))
                    .or_else(|| scpd.state_variable(variable)?.default_value.as_ref());
                (argument.name.clone(), value.cloned().unwrap_or_default())
            })
            .collect())
    }

    /// Answers the lookup of one host by MAC address,
    /// `GetSpecificHostEntry`, or by IP address,
    /// `X_AVM-DE_GetSpecificHostEntryByIP`, from the recorded entries of
    /// `GetGenericHostEntry`: the entry whose address matches, ignoring
    /// case, with the values written since, or the error 714. `None` for
    /// other actions, and without recorded entries.
    fn host_entry(
        &self,
        id: &str,
        action: &Action,
        arguments: &[(String, String)],
    ) -> Option<Result<Vec<(String, String)>, Fault>> {
        let key = match action.name.as_str() {
            "GetSpecificHostEntry" => "NewMACAddress",
            "X_AVM-DE_GetSpecificHostEntryByIP" => "NewIPAddress",
            _ => return None,
        };
        let entries = self
            .fixture
            .recordings
            .get(&(id.to_owned(), "GetGenericHostEntry".to_owned()))?;
        let (_, wanted) = arguments.iter().find(|(name, _)| name == key)?;
        let found = entries.indexed.values().find_map(|answer| {
            let Answer::Ok(out) = answer else { return None };
            let matches = out.get(key).is_some_and(|v| v.eq_ignore_ascii_case(wanted));
            matches.then_some(out)
        });
        let Some(out) = found else {
            return Some(Err(Fault::new(NO_SUCH_ENTRY)));
        };
        let outputs = outputs(action).map(|argument| {
            let key = (id.to_owned(), argument.related_state_variable.clone());
            let value = self
                .written
                .get(&key)
                .or_else(|| out.get(&argument.name))
                .cloned()
                .unwrap_or_default();
            (argument.name.clone(), value)
        });
        Some(Ok(outputs.collect()))
    }
}

/// A counter with the value `now`, or 0 if it is none, after adding
/// `step`, wrapped around at `wrap`, else at 2^64.
fn count(now: Option<&str>, step: u64, wrap: Option<u64>) -> String {
    let now: u64 = now.and_then(|v| v.parse().ok()).unwrap_or_default();
    let next = u128::from(now) + u128::from(step);
    let next = next % wrap.map_or(1 << 64, u128::from);
    next.to_string()
}

impl Fixture {
    /// The service description of a service.
    pub(crate) fn scpd(&self, service: &Service) -> Option<&Scpd> {
        let name = service.scpd_url.rsplit('/').next().unwrap_or_default();
        self.scpds.get(name).map(|(_, scpd)| scpd)
    }
}

/// The last part of the service ID, like `Hosts1`. Unique within a device.
pub(crate) fn short_id(service: &Service) -> &str {
    service.service_id.rsplit(':').next().unwrap_or_default()
}

fn is_getter(action: &str) -> bool {
    action.starts_with("Get") || action.starts_with("X_AVM-DE_Get")
}

fn outputs(action: &Action) -> impl Iterator<Item = &tr064::Argument> {
    action
        .arguments
        .iter()
        .filter(|a| a.direction == Direction::Out)
}

/// The recorded answer for the index in the only input argument.
fn indexed(
    action: &Action,
    recording: &Recording,
    arguments: &[(String, String)],
) -> Result<Vec<(String, String)>, Fault> {
    let answer = arguments
        .first()
        .and_then(|(_, index)| index.parse().ok())
        .and_then(|index| recording.indexed.get(&index))
        .ok_or_else(|| Fault::new(INVALID_INDEX))?;
    match answer {
        Answer::Ok(out) => Ok(outputs(action)
            .map(|a| {
                let value = out.get(&a.name).cloned().unwrap_or_default();
                (a.name.clone(), value)
            })
            .collect()),
        Answer::Fault { code, description } => Err(Fault {
            code: *code,
            description: description.clone(),
        }),
    }
}

/// Checks the arguments of a call against the service description: every
/// input argument must be there, nothing else, and each value must fit its
/// state variable.
fn validate(scpd: &Scpd, action: &Action, arguments: &[(String, String)]) -> Result<(), Fault> {
    let inputs: Vec<_> = action
        .arguments
        .iter()
        .filter(|a| a.direction == Direction::In)
        .collect();
    let given = |name: &str| arguments.iter().any(|(n, _)| n == name);
    let known = |name: &str| inputs.iter().any(|a| a.name == name);
    if !inputs.iter().all(|a| given(&a.name)) || !arguments.iter().all(|(n, _)| known(n)) {
        return Err(Fault::new(INVALID_ARGS));
    }
    let variables = arguments.iter().filter_map(|(name, value)| {
        let argument = inputs.iter().find(|a| &a.name == name)?;
        Some((
            scpd.state_variable(&argument.related_state_variable)?,
            value,
        ))
    });
    for (variable, value) in variables {
        check(variable, value).map_err(Fault::new)?;
    }
    Ok(())
}

/// Checks a value against the data type and the allowed values of a state
/// variable. The allowed range is not checked, because devices don't
/// either: an index beyond the range of its variable gets the error 713
/// like any other index without an entry, and clients rely on that to find
/// the end of a list.
fn check(variable: &StateVariable, value: &str) -> Result<(), u16> {
    let allowed =
        variable.allowed_values.is_empty() || variable.allowed_values.iter().any(|v| v == value);
    if has_type(&variable.data_type, value) && allowed {
        Ok(())
    } else {
        Err(INVALID_VALUE)
    }
}

fn has_type(data_type: &str, value: &str) -> bool {
    match data_type {
        "ui1" => value.parse::<u8>().is_ok(),
        "ui2" => value.parse::<u16>().is_ok(),
        "ui4" => value.parse::<u32>().is_ok(),
        "i1" => value.parse::<i8>().is_ok(),
        "i2" => value.parse::<i16>().is_ok(),
        "i4" => value.parse::<i32>().is_ok(),
        "boolean" => matches!(value, "0" | "1" | "true" | "false" | "yes" | "no"),
        _ => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tr064::AllowedRange;

    fn variable(data_type: &str) -> StateVariable {
        let xml = format!(
            "<scpd><serviceStateTable><stateVariable><name>V</name>\
             <dataType>{data_type}</dataType></stateVariable></serviceStateTable></scpd>"
        );
        Scpd::parse(&xml).unwrap().state_variables.remove(0)
    }

    #[test]
    fn checks_data_types() {
        for (data_type, valid, invalid) in [
            ("ui1", "255", "256"),
            ("ui2", "65535", "-1"),
            ("ui4", "4294967295", "x"),
            ("i1", "-128", "128"),
            ("i2", "-32768", "1.5"),
            ("i4", "-1", ""),
            ("boolean", "yes", "2"),
        ] {
            assert_eq!(check(&variable(data_type), valid), Ok(()), "{data_type}");
            assert_eq!(
                check(&variable(data_type), invalid),
                Err(INVALID_VALUE),
                "{data_type}"
            );
        }
        assert_eq!(check(&variable("string"), "anything"), Ok(()));
    }

    #[test]
    fn checks_allowed_values_but_not_ranges() {
        let mut status = variable("string");
        status.allowed_values = vec!["Up".to_owned(), "Disabled".to_owned()];
        assert_eq!(check(&status, "Up"), Ok(()));
        assert_eq!(check(&status, "Down"), Err(INVALID_VALUE));

        let mut index = variable("ui2");
        index.allowed_range = Some(AllowedRange {
            minimum: Some("0".to_owned()),
            maximum: Some("4".to_owned()),
            step: None,
        });
        assert_eq!(check(&index, "5"), Ok(()));
    }

    #[test]
    fn counts_and_wraps_around() {
        assert_eq!(count(Some("5"), 2, None), "7");
        assert_eq!(count(None, 2, None), "2");
        assert_eq!(count(Some("x"), 2, Some(10)), "2");
        assert_eq!(count(Some("9"), 3, Some(10)), "2");
        assert_eq!(count(Some(&u64::MAX.to_string()), 1, None), "0");
    }

    #[test]
    fn describes_faults() {
        let codes = [
            401, 402, 501, 600, 601, 606, 713, 714, 820, 866, 867, 868, 999,
        ];
        let mut descriptions: Vec<_> = codes.iter().map(|&c| Fault::new(c).description).collect();
        descriptions.sort();
        descriptions.dedup();
        assert_eq!(descriptions.len(), codes.len());
    }
}