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

use std::ops::Deref;

use http::Response;
use hyper::body::Incoming;
use hyper::Uri;
use tower_service::Service;

use crate::common::{check_support, parse_find_multiple_collections, ServiceForUrlError};
use crate::dav::{check_status, FoundCollection, WebDavError};
use crate::dav::{extract_multi_prop, WebDavClient};
use crate::sd::{find_context_url, BootstrapError, DiscoverableService};
use crate::xmlutils::escape_xml_entities;
use crate::{names, Depth, FindHomeSetError};
use crate::{CheckSupportError, FetchedResource};

/// Client to communicate with a CalDAV server.
///
/// Instances are usually created via [`CalDavClient::new`]:
///
/// ```rust
/// # use libdav::CalDavClient;
/// # use libdav::dav::WebDavClient;
/// use http::Uri;
/// use hyper_rustls::HttpsConnectorBuilder;
/// use hyper_util::{client::legacy::Client, rt::TokioExecutor};
/// use tower_http::auth::AddAuthorization;
///
/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
/// let uri = Uri::try_from("https://example.com").unwrap();
///
/// let https_connector = HttpsConnectorBuilder::new()
///     .with_native_roots()
///     .unwrap()
///     .https_or_http()
///     .enable_http1()
///     .build();
/// let https_client = Client::builder(TokioExecutor::new()).build(https_connector);
/// let https_client = AddAuthorization::basic(https_client, "user", "secret");
/// let webdav = WebDavClient::new(uri, https_client);
/// let client = CalDavClient::new(webdav);
/// # })
/// ```
///
/// If the real CalDAV server needs to be resolved via automated service discovery, use
/// [`CalDavClient::bootstrap_via_service_discovery`].
///
/// For setting the `Authorization` header or applying other changes to outgoing requests, see the
/// documentation on [`WebDavClient`].
#[derive(Debug)]
pub struct CalDavClient<C>
where
    C: Service<http::Request<String>, Response = Response<Incoming>> + Sync + Send + 'static,
{
    /// A WebDAV client used to send requests.
    pub webdav_client: WebDavClient<C>,
}

impl<C> Deref for CalDavClient<C>
where
    C: Service<http::Request<String>, Response = Response<Incoming>> + Sync + Send,
{
    type Target = WebDavClient<C>;

    fn deref(&self) -> &Self::Target {
        &self.webdav_client
    }
}

impl<C> CalDavClient<C>
where
    C: Service<http::Request<String>, Response = Response<Incoming>> + Sync + Send,
    <C as Service<http::Request<String>>>::Error: std::error::Error + Send + Sync,
{
    /// Create a new client instance.
    ///
    /// # See also
    ///
    /// [`CalDavClient::bootstrap_via_service_discovery`].
    pub fn new(webdav_client: WebDavClient<C>) -> CalDavClient<C> {
        CalDavClient { webdav_client }
    }

    /// Automatically bootstrap a new client instance using service discovery.
    ///
    /// Creates a new client, with its `base_url` set to the context path retrieved using service
    /// discovery via [`find_context_url`].
    ///
    /// # Errors
    ///
    /// - [`BootstrapError::ServiceForUrl`] if the webdav client uses a URL with an invalid schema.
    /// - [`BootstrapError::ContextUrl`] if underlying call to [`find_context_url`] returns an error.
    pub async fn bootstrap_via_service_discovery(
        mut webdav_client: WebDavClient<C>,
    ) -> Result<CalDavClient<C>, BootstrapError> {
        let service = service_for_url(&webdav_client.base_url)?;
        match find_context_url(&webdav_client, service).await {
            crate::sd::FindContextUrlResult::BaseUrl => {}
            crate::sd::FindContextUrlResult::Found(url) => webdav_client.base_url = url,
            crate::sd::FindContextUrlResult::NoneFound => return Err(BootstrapError::NoUsableUrl),
            crate::sd::FindContextUrlResult::Error(err) => return Err(err.into()),
        }
        Ok(CalDavClient { webdav_client })
    }

    /// Queries the server for the calendar home set.
    ///
    /// See: <https://www.rfc-editor.org/rfc/rfc4791#section-6.2.1>
    ///
    /// # Errors
    ///
    /// If there are any network errors or the response could not be parsed.
    pub async fn find_calendar_home_set(
        &self,
        principal: &Uri,
    ) -> Result<Vec<Uri>, FindHomeSetError> {
        // If obtaining a principal fails, the specification says we should query the user. This
        // tries to use the `base_url` first, since the user might have provided it for a reason.
        self.find_home_sets(principal, &names::CALENDAR_HOME_SET)
            .await
            .map_err(FindHomeSetError)
    }

    /// Find calendars collections under the given `url`.
    ///
    /// If `url` is not specified, this client's current `base_url` shall be used instead.  When
    /// using a client bootstrapped via automatic discovery, passing `None` will usually yield the
    /// expected results.
    ///
    /// # Errors
    ///
    /// If the HTTP call fails or parsing the XML response fails.
    pub async fn find_calendars(
        &self,
        calendar_home_set: &Uri,
    ) -> Result<Vec<FoundCollection>, WebDavError> {
        let props = [
            &names::RESOURCETYPE,
            &names::GETETAG,
            &names::SUPPORTED_REPORT_SET,
        ];
        let (head, body) = self.propfind(calendar_home_set, &props, Depth::One).await?;
        check_status(head.status)?;

        parse_find_multiple_collections(&body, &names::CALENDAR)
    }

    /// Fetches existing icalendar resources.
    ///
    /// If the `getetag` property is missing for an item, it will be reported as
    /// [`http::StatusCode::NOT_FOUND`]. This should not be an actual issue with in practice, since
    /// support for `getetag` is mandatory for CalDAV implementations.
    ///
    /// # Errors
    ///
    /// If there are any network errors or the response could not be parsed.
    pub async fn get_calendar_resources(
        &self,
        calendar_href: &str,
        hrefs: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Vec<FetchedResource>, WebDavError> {
        let mut body = String::from(
            r#"
            <C:calendar-multiget xmlns="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
                <prop>
                    <getetag/>
                    <C:calendar-data/>
                </prop>"#,
        );
        for href in hrefs {
            body.push_str("<href>");
            body.push_str(&escape_xml_entities(href.as_ref()));
            body.push_str("</href>");
        }
        body.push_str("</C:calendar-multiget>");

        self.multi_get(calendar_href.as_ref(), body, &names::CALENDAR_DATA)
            .await
    }

    /// Checks that the given URI advertises caldav support.
    ///
    /// See: <https://www.rfc-editor.org/rfc/rfc4791#section-5.1>
    ///
    /// # Known Issues
    ///
    /// - Nextcloud's implementation seems broken. [Bug report][nextcloud].
    ///
    /// [nextcloud]: https://github.com/nextcloud/server/issues/37374
    ///
    /// # Errors
    ///
    /// If there are any network issues or if the server does not explicitly advertise caldav
    /// support.
    pub async fn check_support(&self, url: &Uri) -> Result<(), CheckSupportError> {
        check_support(&self.webdav_client, url, "calendar-access").await
    }

    /// Create an calendar collection.
    ///
    /// # Errors
    ///
    /// Returns an error in case of network errors or if the server returns a failure status code.
    pub async fn create_calendar(&self, href: &str) -> Result<(), WebDavError> {
        self.webdav_client
            .create_collection(href, &[&names::CALENDAR])
            .await
    }

    /// Returns the addresses for a given principal.
    ///
    /// This set typically includes at least email address in the format
    /// `mailto:alice@example.com`.
    ///
    /// # Errors
    ///
    /// Returns an error in case of network errors or if the server returns a failure status code.
    pub async fn get_user_address_set(&self, principal: &Uri) -> Result<Vec<String>, WebDavError> {
        let (head, body) = self
            .propfind(principal, &[&names::CALENDAR_USER_ADDRESS_SET], Depth::Zero)
            .await?;
        check_status(head.status)?;

        extract_multi_prop(&body, &names::CALENDAR_USER_ADDRESS_SET)
    }
}

/// Return the service type based on a URL's scheme.
///
/// # Errors
///
/// If `url` is missing a scheme or has a scheme invalid for CalDAV usage.
pub fn service_for_url(url: &Uri) -> Result<DiscoverableService, ServiceForUrlError> {
    match url
        .scheme()
        .ok_or(ServiceForUrlError::MissingScheme)?
        .as_ref()
    {
        "https" | "caldavs" => Ok(DiscoverableService::CalDavs),
        "http" | "caldav" => Ok(DiscoverableService::CalDav),
        _ => Err(ServiceForUrlError::UnknownScheme),
    }
}