fritz-sim 0.2.2

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
//! Fixtures: devices recorded with `fritz capture` and anonymized.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use serde_json::Value;
use tr064::{DeviceDescription, Scpd};

/// The files of the fixtures that come with this crate, embedded by
/// `build.rs`, by path like `fritzbox-7690/8.25/tr64desc.xml`.
static BUNDLED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/bundled.rs"));

/// Why a fixture cannot be loaded.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("cannot read {}", path.display())]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
    #[error("{} is not valid: {reason}", path.display())]
    Invalid { path: PathBuf, reason: String },
    #[error("no fixture {0} comes with fritz-sim")]
    Unknown(String),
}

/// A recorded answer to an action call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
    /// The output arguments by name.
    Ok(BTreeMap<String, String>),
    /// A UPnP error.
    Fault { code: u16, description: String },
}

/// The recorded answers to one action: to a call without index, or to the
/// calls with each index.
#[derive(Debug, Clone, Default)]
pub(crate) struct Recording {
    pub(crate) once: Option<Answer>,
    pub(crate) indexed: BTreeMap<u32, Answer>,
}

/// A device as recorded in a fixture directory:
///
/// ```text
/// tr64desc.xml
/// scpd/<file>.xml
/// responses/<service>/<action>[@<index>].json
/// lists/<name>.<xml|json>
/// api/<path>.json
/// data/<page>.json
/// homeauto/<ain>.xml
/// ```
///
/// A list document `lists/devicehostlist.xml` is served at the path
/// `/devicehostlist.lua` that an action like `X_AVM-DE_GetHostListPath`
/// returns. A document `api/v0/smarthome/overview.json` of the REST API is
/// served at `/api/v0/smarthome/overview`. A page `data/ecoStat.json` of the
/// web interface answers a form with `page=ecoStat` posted to `/data.lua`.
/// The statistics `homeauto/116300000001.xml` answer the command
/// `getbasicdevicestats` of the Smart Home HTTP interface for the device
/// `11630 0000001`.
#[derive(Debug, Clone)]
pub struct Fixture {
    pub(crate) description_xml: String,
    pub(crate) description: DeviceDescription,
    /// The service descriptions by file name, like `hostsSCPD.xml`.
    pub(crate) scpds: HashMap<String, (String, Scpd)>,
    /// The recorded answers by service, like `Hosts1`, and action.
    pub(crate) recordings: HashMap<(String, String), Recording>,
    /// The list documents by name, like `devicehostlist`.
    pub(crate) lists: HashMap<String, String>,
    /// The documents of the REST API by path, like
    /// `/api/v0/smarthome/overview`.
    pub(crate) api: HashMap<String, String>,
    /// The pages of `/data.lua` by path, like `/ecoStat`.
    pub(crate) pages: HashMap<String, String>,
    /// The statistics of Smart Home devices by AIN without spaces.
    pub(crate) stats: HashMap<String, String>,
}

impl Fixture {
    /// Loads a fixture that comes with this crate, by name like
    /// `fritzbox-7690/8.25`. The fixtures are part of the crate, so this
    /// reads no files. See [`Fixture::bundled_names`].
    ///
    /// # Errors
    ///
    /// [`Error::Unknown`] if no fixture has the name.
    pub fn bundled(name: &str) -> Result<Self, Error> {
        if !Self::bundled_names().iter().any(|n| n == name) {
            return Err(Error::Unknown(name.to_owned()));
        }
        Self::read(Source::Bundled, Path::new(name))
    }

    /// The names of the fixtures that come with this crate, sorted, like
    /// `fritzbox-7690/8.25`. Tests can run against each of them.
    pub fn bundled_names() -> Vec<String> {
        let mut names: Vec<String> = BUNDLED
            .iter()
            .filter_map(|(path, _)| {
                let mut parts = path.splitn(3, '/');
                Some(format!("{}/{}", parts.next()?, parts.next()?))
            })
            .collect();
        names.dedup();
        names
    }

    /// Loads the fixture in `dir`.
    ///
    /// # Errors
    ///
    /// The errors of reading the files, and [`Error::Invalid`] if one of
    /// them cannot be parsed.
    pub fn load(dir: impl AsRef<Path>) -> Result<Self, Error> {
        Self::read(Source::Disk, dir.as_ref())
    }

    /// Reads the fixture in `dir` of `source`.
    fn read(source: Source, dir: &Path) -> Result<Self, Error> {
        let read = |path: &Path| source.read(path);
        let entries = |dir: &Path| source.entries(dir);
        let path = dir.join("tr64desc.xml");
        let description_xml = read(&path)?;
        let description = DeviceDescription::parse(&description_xml).map_err(invalid(&path))?;
        let mut scpds = HashMap::new();
        for (name, path) in entries(&dir.join("scpd"))? {
            let xml = read(&path)?;
            let scpd = Scpd::parse(&xml).map_err(invalid(&path))?;
            scpds.insert(name, (xml, scpd));
        }
        let mut recordings: HashMap<_, Recording> = HashMap::new();
        for (service, service_dir) in entries(&dir.join("responses"))? {
            for (name, path) in entries(&service_dir)? {
                let Some(stem) = name.strip_suffix(".json") else {
                    continue;
                };
                let (action, index) = match stem.split_once('@') {
                    Some((action, index)) => {
                        let index = index.parse().map_err(invalid(&path))?;
                        (action, Some(index))
                    }
                    None => (stem, None),
                };
                let Some(answer) = answer(&read(&path)?).map_err(invalid(&path))? else {
                    continue;
                };
                let recording = recordings
                    .entry((service.clone(), action.to_owned()))
                    .or_default();
                match index {
                    Some(index) => {
                        recording.indexed.insert(index, answer);
                    }
                    None => recording.once = Some(answer),
                }
            }
        }
        let lists = by_stem(source, &dir.join("lists"))?;
        let stats = by_stem(source, &dir.join("homeauto"))?;
        let api = tree(source, &dir.join("api"), "/api")?;
        let pages = tree(source, &dir.join("data"), "")?;
        Ok(Self {
            description_xml,
            description,
            scpds,
            recordings,
            lists,
            api,
            pages,
            stats,
        })
    }

    /// The device description.
    pub fn description(&self) -> &DeviceDescription {
        &self.description
    }

    /// The recorded answer to a call of `action` of the service `service`,
    /// like `Hosts1`, with the given index or without one.
    pub fn answer(&self, service: &str, action: &str, index: Option<u32>) -> Option<&Answer> {
        let recording = self
            .recordings
            .get(&(service.to_owned(), action.to_owned()))?;
        match index {
            Some(index) => recording.indexed.get(&index),
            None => recording.once.as_ref(),
        }
    }

    /// Records `answer` for calls of `action` of the service `service`,
    /// like `Hosts1`, with the given index or without one, in place of a
    /// recorded answer. For tests of answers the fixture lacks.
    #[must_use]
    pub fn with_answer(
        mut self,
        service: &str,
        action: &str,
        index: Option<u32>,
        answer: Answer,
    ) -> Self {
        let recording = self
            .recordings
            .entry((service.to_owned(), action.to_owned()))
            .or_default();
        match index {
            Some(index) => {
                recording.indexed.insert(index, answer);
            }
            None => recording.once = Some(answer),
        }
        self
    }

    /// Serves `json` as the page `name` of `/data.lua`, like `log`, in
    /// place of the page of the fixture. For tests of pages the fixture
    /// lacks.
    #[must_use]
    pub fn with_page(mut self, name: &str, json: impl Into<String>) -> Self {
        self.pages.insert(format!("/{name}"), json.into());
        self
    }

    /// Serves `json` at `path` of the REST API, like
    /// `/api/v0/generic/vpn`, in place of the document of the fixture. For
    /// tests of documents the fixture lacks.
    #[must_use]
    pub fn with_api(mut self, path: &str, json: impl Into<String>) -> Self {
        self.api.insert(path.to_owned(), json.into());
        self
    }
}

/// Parses a recorded answer: `{"status": "ok", "out": {…}}` or
/// `{"status": "fault", "code": 714, "description": "…"}`. Calls that failed
/// without an answer, `{"status": "failed", …}`, count as not recorded.
fn answer(json: &str) -> Result<Option<Answer>, String> {
    let value: Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
    match value["status"].as_str() {
        Some("ok") => {
            let out = value["out"].as_object().ok_or("no output arguments")?;
            out.iter()
                .map(|(name, value)| {
                    let value = value.as_str().ok_or(format!("{name} is not a string"))?;
                    Ok((name.clone(), value.to_owned()))
                })
                .collect::<Result<_, String>>()
                .map(|out| Some(Answer::Ok(out)))
        }
        Some("fault") => {
            let code = value["code"].as_u64().and_then(|c| u16::try_from(c).ok());
            Ok(Some(Answer::Fault {
                code: code.ok_or("no error code")?,
                description: value["description"].as_str().unwrap_or_default().to_owned(),
            }))
        }
        Some("failed") => Ok(None),
        _ => Err("unknown status".to_owned()),
    }
}

/// The files in `dir`, if it exists, by their names without the extension.
fn by_stem(source: Source, dir: &Path) -> Result<HashMap<String, String>, Error> {
    let mut found = HashMap::new();
    if source.is_dir(dir) {
        for (name, path) in source.entries(dir)? {
            let name = name.split_once('.').map_or(name.as_str(), |(stem, _)| stem);
            found.insert(name.to_owned(), source.read(&path)?);
        }
    }
    Ok(found)
}

/// Adds the JSON documents in `dir` and its subdirectories to `found`, by
/// their path under `prefix` without the extension.
/// The documents below `dir`, if it exists, by their paths after `prefix`,
/// like `/api/v0/smarthome/overview` for `prefix` `/api`.
fn tree(source: Source, dir: &Path, prefix: &str) -> Result<HashMap<String, String>, Error> {
    let mut found = HashMap::new();
    if source.is_dir(dir) {
        documents(source, dir, prefix, &mut found)?;
    }
    Ok(found)
}

fn documents(
    source: Source,
    dir: &Path,
    prefix: &str,
    found: &mut HashMap<String, String>,
) -> Result<(), Error> {
    for (name, path) in source.entries(dir)? {
        if source.is_dir(&path) {
            documents(source, &path, &format!("{prefix}/{name}"), found)?;
        } else if let Some(stem) = name.strip_suffix(".json") {
            found.insert(format!("{prefix}/{stem}"), source.read(&path)?);
        }
    }
    Ok(())
}

/// Where the files of a fixture come from.
#[derive(Debug, Clone, Copy)]
enum Source {
    /// The file system.
    Disk,
    /// The fixtures embedded in the crate, with paths relative to them.
    Bundled,
}

impl Source {
    fn read(self, path: &Path) -> Result<String, Error> {
        match self {
            Self::Disk => fs::read_to_string(path).map_err(|source| Error::Io {
                path: path.to_owned(),
                source,
            }),
            Self::Bundled => Ok(bundled(path).next().map_or("", |(_, c)| c).to_owned()),
        }
    }

    fn is_dir(self, path: &Path) -> bool {
        match self {
            Self::Disk => path.is_dir(),
            Self::Bundled => bundled(path).any(|(p, _)| p != path),
        }
    }

    /// The entries of a directory by name, without hidden ones like
    /// `.DS_Store`.
    fn entries(self, dir: &Path) -> Result<Vec<(String, PathBuf)>, Error> {
        let mut entries = Vec::new();
        match self {
            Self::Disk => {
                let io_error = |source| Error::Io {
                    path: dir.to_owned(),
                    source,
                };
                for entry in fs::read_dir(dir).map_err(io_error)? {
                    let entry = entry.map_err(io_error)?;
                    let name = entry.file_name().to_string_lossy().into_owned();
                    if !name.starts_with('.') {
                        entries.push((name, entry.path()));
                    }
                }
            }
            Self::Bundled => {
                let below = |(path, _): (&'static Path, _)| path.strip_prefix(dir).ok();
                for first in bundled(dir)
                    .filter_map(below)
                    .filter_map(|p| p.iter().next())
                {
                    let name = first.to_string_lossy().into_owned();
                    if !entries.iter().any(|(n, _)| *n == name) {
                        entries.push((name.clone(), dir.join(name)));
                    }
                }
            }
        }
        Ok(entries)
    }
}

/// The embedded files at or below `path`, with their paths.
fn bundled(path: &Path) -> impl Iterator<Item = (&'static Path, &'static str)> {
    BUNDLED
        .iter()
        .map(|(p, content)| (Path::new(*p), *content))
        .filter(move |(p, _)| p.starts_with(path))
}

fn invalid<E: ToString>(path: &Path) -> impl FnOnce(E) -> Error {
    let path = path.to_owned();
    move |error| Error::Invalid {
        path,
        reason: error.to_string(),
    }
}

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

    #[test]
    fn parses_answers() {
        assert_eq!(
            answer(r#"{"status": "ok", "out": {"NewEnable": "1"}}"#),
            Ok(Some(Answer::Ok(BTreeMap::from([(
                "NewEnable".to_owned(),
                "1".to_owned()
            )]))))
        );
        assert_eq!(
            answer(r#"{"status": "fault", "code": 714}"#),
            Ok(Some(Answer::Fault {
                code: 714,
                description: String::new()
            }))
        );
        assert_eq!(
            answer(r#"{"status": "failed", "error": "timeout"}"#),
            Ok(None)
        );
        for (json, error) in [
            ("{", "EOF while parsing an object at line 1 column 1"),
            (r#"{"status": "ok"}"#, "no output arguments"),
            (
                r#"{"status": "ok", "out": {"NewEnable": 1}}"#,
                "NewEnable is not a string",
            ),
            (r#"{"status": "fault", "code": 70000}"#, "no error code"),
            (r#"{"status": "skipped"}"#, "unknown status"),
        ] {
            assert_eq!(answer(json), Err(error.to_owned()), "{json}");
        }
    }
}