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

//! Service discovery helpers to perform automated client bootstrapping.
//!
//! Tools in this module 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::bootstrap_via_service_discovery`]
//! - [`crate::CardDavClient::bootstrap_via_service_discovery`]
//! - <https://www.rfc-editor.org/rfc/rfc6764>

use std::io;

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

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

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

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

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

    /// DNS error resolving TXT record.
    #[error("error resolving context path via TXT records: {0}")]
    TxtError(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,

    /// The SRV record returned domain/port pairs that are unusable to build an [`Uri`].
    #[error("SRV records returned domain/port pair that could not be parsed: {0}")]
    UnusableSrv(http::Error),
}

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

    /// Failed to discovery context URL.
    #[error("error discovering context url: {0}")]
    ContextUrl(#[from] ContextUrlError),

    /// No usable context URL was found for this service.
    #[error("no usable URL found for service")]
    NoUsableUrl,
}

/// Return type for the [`find_context_url`] function.
pub enum FindContextUrlResult {
    /// The WebDAV client's `base_url` is a valid context url for the given service.
    BaseUrl,
    /// Found a usable URL via service discovery.
    Found(Uri),
    /// No usable URL found for this service.
    NoneFound,
    /// Non-recoverable error occurred.
    Error(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,
) -> FindContextUrlResult
where
    C: Service<http::Request<String>, Response = Response<Incoming>> + Sync + Send,
    <C as Service<http::Request<String>>>::Error: std::error::Error + Send + Sync,
{
    // If the initially provided URL reports that it supports CalDAV, use that one.
    match check_support(client, &client.base_url, service.access_field()).await {
        Ok(()) => return FindContextUrlResult::BaseUrl,
        Err(err) => info!("Original URL does not report {service} capabilities: {err}"),
    };

    let Some(domain) = client.base_url.host() else {
        return FindContextUrlResult::Error(ContextUrlError::MissingHost);
    };
    let port = client.base_url.port_u16().unwrap_or(service.default_port());

    let dname = match Name::bytes_from_str(domain) {
        Ok(d) => d,
        Err(err) => return FindContextUrlResult::Error(ContextUrlError::InvalidDomain(err)),
    };
    let host_candidates = match resolve_srv_record(service, &dname, port).await {
        Ok(Some(hc)) => hc,
        Ok(None) => return FindContextUrlResult::Error(ContextUrlError::NotAvailable),
        Err(err) => return FindContextUrlResult::Error(ContextUrlError::DnsError(err)),
    };

    let txt_record = match find_context_path_via_txt_records(service, &dname).await {
        Ok(record) => record,
        Err(err) => return FindContextUrlResult::Error(ContextUrlError::TxtError(err)),
    };
    for candidate in &host_candidates {
        if let Some(ref path) = txt_record {
            let test_uri = match Uri::builder()
                .scheme(service.scheme())
                .authority(format!("{}:{}", candidate.0, candidate.1))
                .path_and_query(path.clone())
                .build()
            {
                Ok(uri) => uri,
                Err(err) => return FindContextUrlResult::Error(ContextUrlError::UnusableSrv(err)),
            };

            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 FindContextUrlResult::Found(test_uri);
                }
                Err(_) => {
                    warn!("Found path that doesn't report {service} capabilities: {test_uri}");
                }
            };
        } else if let Ok(Some(url)) = client
            .find_context_path(service, &candidate.0, candidate.1)
            .await
        {
            return FindContextUrlResult::Found(url);
        }
    }

    FindContextUrlResult::NoneFound
}

/// 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: &impl ToName,
    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 {
    /// I/O error performing DNS request.
    #[error("I/O error performing DNS request: {0}")]
    Network(#[from] io::Error),

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

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

    /// DNS response contained data invalid for building a URL path.
    #[error("invalid data in response: {0}")]
    InvalidData(#[from] InvalidUri),

    /// DNS response is missing the expected prefix `path=`.
    #[error("missing expected prefix path= from TXT record.")]
    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: impl ToName,
) -> 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()
}