Skip to main content

fritz_core/
connection.rs

1//! Where and how to connect: the device address, the user and the trusted
2//! certificate, from a profile and the overrides of the command line or the
3//! environment.
4
5use std::sync::Arc;
6
7use tr064::{Client, ClientBuilder, Fingerprint, Url};
8
9use crate::config::Profile;
10use crate::redact;
11
12/// The host when neither the command line nor a profile names one.
13pub const DEFAULT_HOST: &str = "fritz.box";
14
15/// The user name sent to TR-064 when none is set. Devices with only a
16/// password, like FRITZ!Repeaters or a FRITZ!Box set to log in with the
17/// password alone, use a user of their own instead of the one sent, so any
18/// name works. This one is the historic default of TR-064.
19pub const PASSWORD_ONLY_USERNAME: &str = "dslf-config";
20
21/// The TR-064 port for HTTPS.
22pub const HTTPS_PORT: u16 = 49443;
23
24/// The TR-064 port for HTTP.
25pub const HTTP_PORT: u16 = 49000;
26
27/// The connection settings are incomplete or invalid.
28#[derive(Debug, thiserror::Error)]
29pub enum Error {
30    /// The host cannot be turned into a TR-064 address.
31    #[error("{host} is not a valid host: {reason}")]
32    InvalidHost {
33        /// The host as given.
34        host: String,
35        /// What is wrong with it.
36        reason: &'static str,
37    },
38    /// The address is `https`, but no certificate is trusted for it.
39    #[error("no certificate is trusted for {0}, run `fritz tls trust`")]
40    NotTrusted(Url),
41    /// The fingerprint given as an override is not one.
42    #[error("{0} is not a SHA-256 fingerprint of 64 hex digits")]
43    InvalidFingerprint(String),
44    /// No user is set. No longer returned: without a user, the device is
45    /// taken to have only a password.
46    #[error("no user is set for {0}, pass --user or run `fritz config init --user <name>`")]
47    NoUsername(Url),
48}
49
50/// Turns a host into the TR-064 address of the device.
51///
52/// A host name or IP address, optionally with a port, means HTTPS on port
53/// 49443 unless another port is given: `fritz.box` becomes
54/// `https://fritz.box:49443`. A full `http` or `https` address is taken as
55/// is, like `http://192.168.178.1:49000` for unencrypted access.
56pub fn parse_host(host: &str) -> Result<Url, Error> {
57    let invalid = |reason| Error::InvalidHost {
58        host: host.to_owned(),
59        reason,
60    };
61    let url = if host.contains("://") {
62        let url = Url::parse(host).map_err(|_| invalid("not an address"))?;
63        if !matches!(url.scheme(), "http" | "https") {
64            return Err(invalid("the scheme is neither http nor https"));
65        }
66        url
67    } else {
68        let mut url =
69            Url::parse(&format!("https://{host}")).map_err(|_| invalid("not a host name"))?;
70        let port = url.port().unwrap_or(HTTPS_PORT);
71        // Fails only for addresses without a host, which https rules out.
72        let _ = url.set_port(Some(port));
73        url
74    };
75    if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
76        return Err(invalid("the address has a path"));
77    }
78    Ok(url)
79}
80
81/// Settings from the command line or the environment, which take precedence
82/// over the profile.
83#[derive(Debug, Default, Clone)]
84pub struct Overrides {
85    /// The host, see [`parse_host`].
86    pub host: Option<String>,
87    /// The user on the device.
88    pub username: Option<String>,
89    /// The fingerprint of the certificate to trust, as given. It is only
90    /// checked when it is used, so that a server can start without one.
91    pub fingerprint: Option<String>,
92}
93
94impl Overrides {
95    /// The fingerprint of the certificate to trust, if one is given.
96    pub fn fingerprint(&self) -> Result<Option<Fingerprint>, Error> {
97        self.fingerprint
98            .as_deref()
99            .map(|f| {
100                f.parse()
101                    .map_err(|_| Error::InvalidFingerprint(f.to_owned()))
102            })
103            .transpose()
104    }
105}
106
107/// The device to connect to, with everything but the password.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Target {
110    /// The TR-064 address.
111    pub url: Url,
112    /// The user on the device.
113    pub username: Option<String>,
114    /// The fingerprint of the trusted certificate.
115    pub fingerprint: Option<Fingerprint>,
116}
117
118impl Target {
119    /// Combines a profile with the overrides. Without either, the target is
120    /// [`DEFAULT_HOST`].
121    ///
122    /// The user of the profile applies only to the host of the profile, also
123    /// over another scheme or port; its certificate only to the same
124    /// address. Neither applies to another host given as an override.
125    pub fn resolve(profile: Option<&Profile>, overrides: &Overrides) -> Result<Self, Error> {
126        let host = overrides
127            .host
128            .as_deref()
129            .or(profile.map(|p| p.host.as_str()))
130            .unwrap_or(DEFAULT_HOST);
131        let url = parse_host(host)?;
132        let own = profile.and_then(|p| parse_host(&p.host).ok().map(|own| (p, own)));
133        let same_host = own
134            .as_ref()
135            .filter(|(_, own)| own.host_str() == url.host_str());
136        let same_address = own.as_ref().filter(|(_, own)| *own == url);
137        Ok(Self {
138            username: overrides
139                .username
140                .clone()
141                .or_else(|| same_host.and_then(|(p, _)| p.username.clone())),
142            fingerprint: overrides
143                .fingerprint()?
144                .or(same_address.and_then(|(p, _)| p.fingerprint)),
145            url,
146        })
147    }
148
149    /// The user for TR-064, or [`PASSWORD_ONLY_USERNAME`] if none is set.
150    ///
151    /// # Errors
152    ///
153    /// None; the result is kept for compatibility.
154    pub fn username(&self) -> Result<&str, Error> {
155        Ok(self.username.as_deref().unwrap_or(PASSWORD_ONLY_USERNAME))
156    }
157
158    /// The user for the login to the web interface, empty if none is set,
159    /// as the web interface expects for devices with only a password.
160    #[must_use]
161    pub fn web_username(&self) -> &str {
162        self.username.as_deref().unwrap_or_default()
163    }
164
165    /// The name of the password in the keychain: `user@host`, or the host
166    /// alone if no user is set.
167    ///
168    /// # Errors
169    ///
170    /// None; the result is kept for compatibility.
171    pub fn account(&self) -> Result<String, Error> {
172        let host = self.url.host_str().unwrap_or_default();
173        Ok(match &self.username {
174            Some(username) => format!("{username}@{host}"),
175            None => host.to_owned(),
176        })
177    }
178
179    /// The web interface of the device, which serves the session login and
180    /// the REST API: the TR-064 ports 49443 and 49000 become the default
181    /// ports of `https` and `http`, other addresses stay as they are. The
182    /// device uses the same certificate for both.
183    #[must_use]
184    pub fn web(&self) -> Self {
185        let mut url = self.url.clone();
186        let port = match (url.scheme(), url.port()) {
187            ("https", Some(HTTPS_PORT)) | ("http", Some(HTTP_PORT)) => None,
188            (_, port) => port,
189        };
190        // Fails only for addresses without a host, which parse_host rules out.
191        let _ = url.set_port(port);
192        Self {
193            url,
194            ..self.clone()
195        }
196    }
197
198    /// A client builder for the device, with the certificate pinned for
199    /// `https` and the log redacted by [`redact::Log`]. Without credentials,
200    /// which only actions need.
201    pub fn client(&self) -> Result<ClientBuilder, Error> {
202        let builder = Client::builder(self.url.clone()).redact(Arc::new(redact::Log));
203        match (self.url.scheme(), self.fingerprint) {
204            ("https", Some(fingerprint)) => Ok(builder.pin(fingerprint)),
205            ("https", None) => Err(Error::NotTrusted(self.url.clone())),
206            _ => Ok(builder),
207        }
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    fn fingerprint(byte: u8) -> Fingerprint {
216        Fingerprint::of(&[byte])
217    }
218
219    #[test]
220    fn parses_hosts() {
221        for (host, url) in [
222            ("fritz.box", "https://fritz.box:49443/"),
223            ("192.168.178.1:8443", "https://192.168.178.1:8443/"),
224            ("[fd00::1]", "https://[fd00::1]:49443/"),
225            ("http://fritz.box:49000", "http://fritz.box:49000/"),
226            ("https://fritz.box", "https://fritz.box/"),
227        ] {
228            assert_eq!(parse_host(host).unwrap().as_str(), url, "{host}");
229        }
230    }
231
232    #[test]
233    fn rejects_invalid_hosts() {
234        for (host, reason) in [
235            ("ftp://fritz.box", "the scheme is neither http nor https"),
236            ("http://", "not an address"),
237            ("fritz box", "not a host name"),
238            ("fritz.box/path", "the address has a path"),
239            ("https://fritz.box/?query", "the address has a path"),
240            ("fritz.box#top", "the address has a path"),
241        ] {
242            let error = parse_host(host).unwrap_err();
243            assert_eq!(
244                error.to_string(),
245                format!("{host} is not a valid host: {reason}")
246            );
247        }
248    }
249
250    #[test]
251    fn defaults_to_fritz_box() {
252        let target = Target::resolve(None, &Overrides::default()).unwrap();
253        assert_eq!(target.url.as_str(), "https://fritz.box:49443/");
254        assert_eq!(target.username, None);
255        assert_eq!(target.fingerprint, None);
256        // Without a user, the device is taken to have only a password.
257        assert_eq!(target.username().unwrap(), PASSWORD_ONLY_USERNAME);
258        assert_eq!(target.web_username(), "");
259        assert_eq!(target.account().unwrap(), "fritz.box");
260        assert_eq!(
261            target.client().unwrap_err().to_string(),
262            "no certificate is trusted for https://fritz.box:49443/, run `fritz tls trust`"
263        );
264    }
265
266    #[test]
267    fn takes_the_profile() {
268        let profile = Profile {
269            host: "192.168.178.1".to_owned(),
270            username: Some("agent".to_owned()),
271            fingerprint: Some(fingerprint(1)),
272            password_command: None,
273        };
274        let target = Target::resolve(Some(&profile), &Overrides::default()).unwrap();
275        assert_eq!(target.url.as_str(), "https://192.168.178.1:49443/");
276        assert_eq!(target.account().unwrap(), "agent@192.168.178.1");
277        assert_eq!(target.username().unwrap(), "agent");
278        assert_eq!(target.web_username(), "agent");
279        assert_eq!(target.fingerprint, Some(fingerprint(1)));
280        assert!(target.client().unwrap().build().is_ok());
281
282        // The same host, written differently, keeps the user and the
283        // certificate.
284        let overrides = Overrides {
285            host: Some("https://192.168.178.1:49443".to_owned()),
286            ..Overrides::default()
287        };
288        let target = Target::resolve(Some(&profile), &overrides).unwrap();
289        assert_eq!(target.username.as_deref(), Some("agent"));
290        assert_eq!(target.fingerprint, Some(fingerprint(1)));
291
292        // The same host over HTTP keeps the user, but not the certificate.
293        let overrides = Overrides {
294            host: Some("http://192.168.178.1:49000".to_owned()),
295            ..Overrides::default()
296        };
297        let target = Target::resolve(Some(&profile), &overrides).unwrap();
298        assert_eq!(target.username.as_deref(), Some("agent"));
299        assert_eq!(target.fingerprint, None);
300
301        // Another host, like a repeater, gets neither.
302        let overrides = Overrides {
303            host: Some("http://192.168.178.4:49000".to_owned()),
304            ..Overrides::default()
305        };
306        let target = Target::resolve(Some(&profile), &overrides).unwrap();
307        assert_eq!(target.username, None);
308        assert_eq!(target.fingerprint, None);
309        assert_eq!(target.account().unwrap(), "192.168.178.4");
310    }
311
312    #[test]
313    fn prefers_the_overrides() {
314        let profile = Profile {
315            host: "192.168.178.1".to_owned(),
316            username: Some("agent".to_owned()),
317            fingerprint: Some(fingerprint(1)),
318            password_command: None,
319        };
320        let overrides = Overrides {
321            host: Some("lab.example:8443".to_owned()),
322            username: Some("admin".to_owned()),
323            fingerprint: None,
324        };
325        let target = Target::resolve(Some(&profile), &overrides).unwrap();
326        assert_eq!(target.url.as_str(), "https://lab.example:8443/");
327        assert_eq!(target.account().unwrap(), "admin@lab.example");
328        // The certificate of the profile is not trusted for another host.
329        assert_eq!(target.fingerprint, None);
330
331        let overrides = Overrides {
332            fingerprint: Some(fingerprint(2).to_string()),
333            ..overrides
334        };
335        let target = Target::resolve(Some(&profile), &overrides).unwrap();
336        assert_eq!(target.fingerprint, Some(fingerprint(2)));
337
338        // An invalid fingerprint fails only when it is used.
339        let overrides = Overrides {
340            fingerprint: Some("se://docker/mcp/fritz.fingerprint".to_owned()),
341            ..overrides
342        };
343        assert_eq!(
344            Target::resolve(Some(&profile), &overrides)
345                .unwrap_err()
346                .to_string(),
347            "se://docker/mcp/fritz.fingerprint is not a SHA-256 fingerprint of 64 hex digits"
348        );
349    }
350
351    #[test]
352    fn ignores_the_certificate_for_http() {
353        let overrides = Overrides {
354            host: Some("http://127.0.0.1:49000".to_owned()),
355            fingerprint: Some(fingerprint(1).to_string()),
356            ..Overrides::default()
357        };
358        let target = Target::resolve(None, &overrides).unwrap();
359        assert!(target.client().unwrap().build().is_ok());
360    }
361
362    #[test]
363    fn derives_the_web_interface() {
364        for (host, web) in [
365            ("fritz.box", "https://fritz.box/"),
366            ("http://fritz.box:49000", "http://fritz.box/"),
367            ("fritz.box:8443", "https://fritz.box:8443/"),
368            ("http://127.0.0.1:49443", "http://127.0.0.1:49443/"),
369            ("https://fritz.box", "https://fritz.box/"),
370        ] {
371            let overrides = Overrides {
372                host: Some(host.to_owned()),
373                username: Some("agent".to_owned()),
374                fingerprint: Some(fingerprint(1).to_string()),
375            };
376            let target = Target::resolve(None, &overrides).unwrap();
377            let expected = Target {
378                url: Url::parse(web).unwrap(),
379                ..target.clone()
380            };
381            assert_eq!(target.web(), expected, "{host}");
382        }
383    }
384
385    #[test]
386    fn reports_an_invalid_profile_host() {
387        let profile = Profile {
388            host: "fritz box".to_owned(),
389            ..Profile::default()
390        };
391        assert!(Target::resolve(Some(&profile), &Overrides::default()).is_err());
392    }
393}