libdav/
sd.rs

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
// Copyright 2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

//! Service discovery helpers.
//!
//! Service discovery allows finding the exact location of a CalDAV or CardDAV server. The process
//! involves a few steps:
//!
//! - Find the exact server using SRV Service Labels. See [`resolve_srv_record`].
//! - Find the context path via TXT records or the well-known URI. See [`find_context_url`]
//! - Find the current user's principal resource. See [`WebDavClient::find_current_user_principal`].
//!
//! # See also
//!
//! - [`crate::CalDavClient::new_via_bootstrap`]
//! - [`crate::CardDavClient::new_via_bootstrap`]
//! - <https://www.rfc-editor.org/rfc/rfc6764>

use std::io;

use domain::{
    base::{
        name::LongChainError, wire::ParseError, Name, Question, RelativeName, Rtype, ToRelativeName,
    },
    rdata::Txt,
    resolv::{lookup::srv::SrvError, StubResolver},
};
use http::{
    uri::{InvalidUri, PathAndQuery, Scheme},
    Response, Uri,
};
use hyper::body::Incoming;
use log::warn;
use tower::Service;

use crate::{
    common::{check_support, ServiceForUrlError},
    dav::WebDavClient,
    CheckSupportError,
};

/// Error type for [`find_context_url`].
#[derive(thiserror::Error, Debug)]
pub enum ContextUrlError {
    #[error("missing host in input URL")]
    MissingHost,

    #[error("host in input URL is not a valid domain: {0}")]
    InvalidDomain(domain::base::name::FromStrError),

    #[error("error resolving DNS SRV records: {0}")]
    DnsError(#[from] SrvError),

    #[error("error resolving context path via TXT records: {0}")]
    TxtError(#[from] TxtError),

    /// The service is decidedly not available.
    ///
    /// See <https://www.rfc-editor.org/rfc/rfc2782>, page 4
    #[error("the service is decidedly not available")]
    NotAvailable,

    #[error("SRV records returned domain/port pair that could not be parsed: {0}")]
    UnusableSrv(http::Error),
}

/// Error type for [`crate::CalDavClient::new_via_bootstrap`] and [`crate::CardDavClient::new_via_bootstrap`].
#[derive(thiserror::Error, Debug)]
pub enum BootstrapError {
    #[error("cannot determine service for this url: {0}")]
    ServiceForUrl(#[from] ServiceForUrlError),

    #[error("error discovering context url: {0}")]
    ContextUrl(#[from] ContextUrlError),
}

/// Find a CalDAV or CardDAV context path via client bootstrap sequence.
///
/// Determines the server's real host and the context path of the resources for a server,
/// following the discovery mechanism described in [rfc6764].
///
/// [rfc6764]: https://www.rfc-editor.org/rfc/rfc6764
///
/// This resolves from "user friendly" URLs to the real URL where the CalDAV or CardDAV server is
/// advertised as running. For example, a user may understand their CalDAV server as being
/// `https://example.com` but bootstrapping would reveal it to actually run under
/// `https://instance31.example.com/users/john@example.com/calendars/`.
///
/// # Errors
///
/// If any of the underlying DNS or HTTP requests fail, or if any of the responses fail to
/// parse.
///
/// Does not return an error if DNS records are missing, only if they contain invalid data.
pub async fn find_context_url<C>(
    client: &WebDavClient<C>,
    service: DiscoverableService,
) -> Result<Option<Uri>, ContextUrlError>
where
    C: Service<http::Request<String>, Response = Response<Incoming>> + Sync + Send,
    <C as Service<http::Request<String>>>::Error: std::error::Error + Send + Sync,
{
    let domain = client.base_url.host().ok_or(ContextUrlError::MissingHost)?;
    let port = client.base_url.port_u16().unwrap_or(service.default_port());

    let dname = Name::bytes_from_str(domain).map_err(ContextUrlError::InvalidDomain)?;
    let host_candidates = resolve_srv_record(service, &dname, port)
        .await?
        .ok_or(ContextUrlError::NotAvailable)?;

    if let Some(path) = find_context_path_via_txt_records(service, &dname).await? {
        for candidate in &host_candidates {
            let test_uri = Uri::builder()
                .scheme(service.scheme())
                .authority(format!("{}:{}", candidate.0, candidate.1))
                .path_and_query(path.clone())
                .build()
                .map_err(ContextUrlError::UnusableSrv)?;

            match check_support(client, &test_uri, service.access_field()).await {
                Ok(()) | Err(CheckSupportError::NotAdvertised) => {
                    // NotAdvertised implies that the server does not advertise support for this
                    // protocol. We ignore this because NextCloud reports a lack of support for
                    // CalDav and CardDav. See https://github.com/nextcloud/server/issues/37374
                    return Ok(Some(test_uri));
                }
                Err(_) => {
                    warn!("Found path that doesn't report {service} capabilities: {test_uri}");
                    continue;
                }
            };
        }
    }
    for candidate in host_candidates {
        if let Ok(Some(url)) = client
            .find_context_path(service, &candidate.0, candidate.1)
            .await
        {
            return Ok(Some(url));
        }
    }

    Ok(None)
}

/// Services for which automatic discovery is possible.
#[derive(Debug, Clone, Copy)]
pub enum DiscoverableService {
    /// Caldav over HTTPS.
    CalDavs,
    /// Caldav over plain-text HTTP.
    CalDav,
    /// Carddav over HTTPS.
    CardDavs,
    /// Carddav over plain-text HTTP.
    CardDav,
}

impl DiscoverableService {
    /// Relative domain suitable for querying this service type.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn relative_domain(self) -> &'static RelativeName<[u8]> {
        match self {
            DiscoverableService::CalDavs => RelativeName::from_slice(b"\x08_caldavs\x04_tcp"),
            DiscoverableService::CalDav => RelativeName::from_slice(b"\x07_caldav\x04_tcp"),
            DiscoverableService::CardDavs => RelativeName::from_slice(b"\x09_carddavs\x04_tcp"),
            DiscoverableService::CardDav => RelativeName::from_slice(b"\x08_carddav\x04_tcp"),
        }
        .expect("well known relative prefix is valid")
    }

    /// The scheme for this service type (e.g.: HTTP or HTTPS).
    #[must_use]
    pub fn scheme(self) -> Scheme {
        match self {
            DiscoverableService::CalDavs | DiscoverableService::CardDavs => Scheme::HTTPS,
            DiscoverableService::CalDav | DiscoverableService::CardDav => Scheme::HTTP,
        }
    }

    /// The well-known path for context-path discovery.
    #[must_use]
    pub fn well_known_path(self) -> &'static str {
        match self {
            DiscoverableService::CalDavs | DiscoverableService::CalDav => "/.well-known/caldav",
            DiscoverableService::CardDavs | DiscoverableService::CardDav => "/.well-known/carddav",
        }
    }

    /// Default port to use if no port is explicitly provided.
    #[must_use]
    pub fn default_port(self) -> u16 {
        match self {
            DiscoverableService::CalDavs | DiscoverableService::CardDavs => 443,
            DiscoverableService::CalDav | DiscoverableService::CardDav => 80,
        }
    }

    /// Value that must be present in the `DAV:` header when checking for support.
    ///
    /// # See also
    ///
    /// - <https://www.rfc-editor.org/rfc/rfc4791#section-5.1>
    /// - <https://www.rfc-editor.org/rfc/rfc6352#section-6.1>
    #[must_use]
    pub fn access_field(self) -> &'static str {
        match self {
            DiscoverableService::CalDavs | DiscoverableService::CardDavs => "calendar-access",
            DiscoverableService::CalDav | DiscoverableService::CardDav => "addressbook",
        }
    }
}

impl std::fmt::Display for DiscoverableService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DiscoverableService::CalDavs => write!(f, "caldavs"),
            DiscoverableService::CalDav => write!(f, "caldav"),
            DiscoverableService::CardDavs => write!(f, "carddavs"),
            DiscoverableService::CardDav => write!(f, "carddav"),
        }
    }
}

/// Resolves SRV to locate the caldav server.
///
/// If the query is successful and the service is available, returns `Ok(Some(_))` with a `Vec` of
/// host/ports, in the order in which they should be tried.
///
/// If the query is successful but the service is decidedly not available, returns `Ok(None)`.
///
/// # Errors
///
/// If the underlying DNS request fails or the SRV record cannot be parsed.
///
/// # See also
///
/// - <https://www.rfc-editor.org/rfc/rfc2782>
/// - <https://www.rfc-editor.org/rfc/rfc6764>
pub async fn resolve_srv_record(
    service: DiscoverableService,
    domain: &Name<impl AsRef<[u8]>>,
    fallback_port: u16,
) -> Result<Option<Vec<(String, u16)>>, SrvError> {
    Ok(StubResolver::new()
        .lookup_srv(service.relative_domain(), domain, fallback_port)
        .await?
        .map(|found| {
            found
                .into_srvs()
                .map(|entry| (entry.target().to_string(), entry.port()))
                .collect()
        }))
}

/// Error returned by [`find_context_path_via_txt_records`].
#[derive(thiserror::Error, Debug)]
pub enum TxtError {
    #[error("I/O error performing DNS request: {0}")]
    Network(#[from] io::Error),

    #[error("the domain name is too long and cannot be queried: {0}")]
    DomainTooLong(#[from] LongChainError),

    #[error("error parsing DNS response: {0}")]
    ParseError(#[from] ParseError),

    #[error("invalid data in response: {0}")]
    InvalidData(#[from] InvalidUri),

    #[error("data in txt record does no have the expected syntax")]
    BadTxt,
}

/// Resolves a context path via TXT records.
///
/// This returns a path where the default context path should be used for a given domain.
/// The domain provided should be in the format of `example.com` or `posteo.de`.
///
/// Returns an empty list of no relevant record was found.
///
/// # Errors
///
/// See [`TxtError`]
///
/// # See also
///
/// <https://www.rfc-editor.org/rfc/rfc6764>
pub async fn find_context_path_via_txt_records(
    service: DiscoverableService,
    domain: &Name<impl AsRef<[u8]>>,
) -> Result<Option<PathAndQuery>, TxtError> {
    let resolver = StubResolver::new();
    let full_domain = service.relative_domain().chain(domain)?;
    let question = Question::new_in(full_domain, Rtype::TXT);

    let response = resolver.query(question).await?;
    let Some(record) = response.answer()?.next() else {
        return Ok(None);
    };
    let Some(parsed_record) = record?.into_record::<Txt<_>>()? else {
        return Ok(None);
    };

    let path_result = parsed_record
        .data()
        .text::<Vec<u8>>()
        .strip_prefix(b"path=")
        .ok_or(TxtError::BadTxt)
        .map(PathAndQuery::try_from)?
        .map_err(TxtError::InvalidData);
    Some(path_result).transpose()
}