Skip to main content

fritz_core/
generic.rs

1//! Generic access to the services of a device: describing their actions and
2//! calling those that only read. Every call is checked against the
3//! [policy](crate::policy) before anything is sent, and its answer is
4//! [redacted](crate::redact).
5
6use tr064::{Action, Client, Scpd, Service};
7
8use crate::fault::Fault;
9use crate::policy::{self, Class};
10use crate::redact;
11
12/// Why an action was not called.
13#[derive(Debug, thiserror::Error)]
14pub enum Error {
15    #[error(transparent)]
16    Tr064(tr064::Error),
17    /// The device answered with a fault about the user, like a missing
18    /// right or a second factor.
19    #[error("{fault}")]
20    Fault { fault: Fault, description: String },
21    #[error("{service} has no action {action}")]
22    UnknownAction { service: String, action: String },
23    #[error("{action} is {class}; only actions that read are called")]
24    Refused { action: String, class: Class },
25    #[error("{action} has no input {argument}")]
26    UnknownArgument { action: String, argument: String },
27    #[error("{action} needs the input {argument}")]
28    MissingArgument { action: String, argument: String },
29    #[error("{action} got the input {argument} more than once")]
30    DuplicateArgument { action: String, argument: String },
31    #[error("the {document} of the device is not valid: {reason}")]
32    InvalidDocument {
33        document: &'static str,
34        reason: String,
35    },
36}
37
38impl From<tr064::Error> for Error {
39    fn from(error: tr064::Error) -> Self {
40        match (Fault::of(&error), error) {
41            (Some(fault), tr064::Error::Upnp { description, .. }) => {
42                if let Some(wait) = fault.retry_after() {
43                    let (status, retry_after_seconds) = (fault.status(), wait.as_secs());
44                    tracing::debug!(status, retry_after_seconds, "the device asks to wait");
45                }
46                Self::Fault { fault, description }
47            }
48            (_, error) => Self::Tr064(error),
49        }
50    }
51}
52
53/// Finds a service by any reference [`Service::matches`] accepts, and reads
54/// its SCPD. Both documents need no login.
55///
56/// # Errors
57///
58/// The errors of reading the device description and the SCPD, and of
59/// finding the service.
60pub async fn service(client: &Client, reference: &str) -> Result<(Service, Scpd), Error> {
61    let description = client.description().await?;
62    let service = description.service(reference)?.clone();
63    let scpd = client.scpd(&service).await?;
64    Ok((service, scpd))
65}
66
67/// The action of a service with the given name.
68///
69/// # Errors
70///
71/// [`Error::UnknownAction`] if the service has no such action.
72pub fn action<'a>(service: &Service, scpd: &'a Scpd, name: &str) -> Result<&'a Action, Error> {
73    scpd.action(name).ok_or_else(|| Error::UnknownAction {
74        service: service.service_id.clone(),
75        action: name.to_owned(),
76    })
77}
78
79/// Checks a call before it is made: the action only reads, and the
80/// arguments are exactly its inputs.
81///
82/// # Errors
83///
84/// [`Error::Refused`] for an action that does not only read, and
85/// [`Error::UnknownArgument`] or [`Error::MissingArgument`] if the
86/// arguments do not match the inputs.
87pub fn check(
88    service: &Service,
89    action: &Action,
90    arguments: &[(String, String)],
91) -> Result<(), Error> {
92    let class = policy::classify(service, action);
93    if !class.is_read() {
94        return Err(Error::Refused {
95            action: action.name.clone(),
96            class,
97        });
98    }
99    check_arguments(action, arguments)
100}
101
102/// Checks that the arguments are exactly the inputs of an action.
103///
104/// # Errors
105///
106/// [`Error::UnknownArgument`], [`Error::MissingArgument`] or
107/// [`Error::DuplicateArgument`] if they are
108/// not.
109pub fn check_arguments(action: &Action, arguments: &[(String, String)]) -> Result<(), Error> {
110    if let Some((name, _)) = arguments
111        .iter()
112        .find(|(name, _)| !action.inputs().any(|a| &a.name == name))
113    {
114        return Err(Error::UnknownArgument {
115            action: action.name.clone(),
116            argument: name.clone(),
117        });
118    }
119    if let Some(input) = action
120        .inputs()
121        .find(|a| !arguments.iter().any(|(name, _)| *name == a.name))
122    {
123        return Err(Error::MissingArgument {
124            action: action.name.clone(),
125            argument: input.name.clone(),
126        });
127    }
128    if let Some((_, (name, _))) = arguments
129        .iter()
130        .enumerate()
131        .find(|(i, (name, _))| arguments[..*i].iter().any(|(n, _)| n == name))
132    {
133        return Err(Error::DuplicateArgument {
134            action: action.name.clone(),
135            argument: name.clone(),
136        });
137    }
138    Ok(())
139}
140
141/// Calls an action after [checking](check) it, and returns its output
142/// arguments with secrets [hidden](redact::output).
143///
144/// # Errors
145///
146/// The errors of [`check`] and of the call.
147pub async fn call(
148    client: &Client,
149    service: &Service,
150    action: &Action,
151    arguments: &[(String, String)],
152) -> Result<Vec<(String, String)>, Error> {
153    let out = send(client, service, action, arguments).await?;
154    Ok(out
155        .into_iter()
156        .map(|(name, value)| {
157            let value = redact::output(service, &name, &value);
158            (name, value)
159        })
160        .collect())
161}
162
163/// Calls an action after [checking](check) it, and returns its output
164/// arguments as they are. Only for values that never leave the crate, like
165/// the session IDs in the paths of list documents.
166pub(crate) async fn send(
167    client: &Client,
168    service: &Service,
169    action: &Action,
170    arguments: &[(String, String)],
171) -> Result<Vec<(String, String)>, Error> {
172    check(service, action, arguments)?;
173    let arguments: Vec<(&str, &str)> = arguments
174        .iter()
175        .map(|(n, v)| (n.as_str(), v.as_str()))
176        .collect();
177    Ok(client
178        .call(service, &action.name, &arguments)
179        .await?
180        .into_iter()
181        .collect())
182}