libdav/carddav.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
// 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::WebDavClient;
use crate::dav::{check_status, FoundCollection, WebDavError};
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 CardDAV server.
///
/// Instances are usually created via [`CardDavClient::new`]:
///
/// ```rust
/// # use libdav::CardDavClient;
/// # 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 = CardDavClient::new(webdav);
/// # })
/// ```
///
/// If the real CardDAV server needs to be resolved via automated service discovery, use
/// [`CardDavClient::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 CardDavClient<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 CardDavClient<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> CardDavClient<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
///
/// [`CardDavClient::bootstrap_via_service_discovery`].
pub fn new(webdav_client: WebDavClient<C>) -> CardDavClient<C> {
CardDavClient { webdav_client }
}
/// Automatically bootstrap a new client instance.
///
/// Creates a new client, with its `base_url` set to the context path retrieved using service
/// discovery via [`find_context_url`].
///
/// # Errors
///
/// Returns an error if:
///
/// - The URL has an invalid schema.
/// - The underlying call to [`find_context_url`] returns an error.
pub async fn bootstrap_via_service_discovery(
mut webdav_client: WebDavClient<C>,
) -> Result<CardDavClient<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(CardDavClient { webdav_client })
}
/// Queries the server for the address book 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_address_book_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::ADDRESSBOOK_HOME_SET)
.await
.map_err(FindHomeSetError)
}
/// Find address book 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_addressbooks(
&self,
address_book_home_set: &Uri,
) -> Result<Vec<FoundCollection>, WebDavError> {
let props = [
&names::RESOURCETYPE,
&names::GETETAG,
&names::SUPPORTED_REPORT_SET,
];
let (head, body) = self
.propfind(address_book_home_set, &props, Depth::One)
.await?;
check_status(head.status)?;
parse_find_multiple_collections(&body, &names::ADDRESSBOOK)
}
/// Fetches existing vcard 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_address_book_resources(
&self,
addressbook_href: &str,
hrefs: impl IntoIterator<Item = impl AsRef<str>>,
) -> Result<Vec<FetchedResource>, WebDavError> {
let mut body = String::from(
r#"
<C:addressbook-multiget xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav">
<D:prop>
<D:getetag/>
<C:address-data/>
</D:prop>"#,
);
for href in hrefs {
body.push_str("<D:href>");
body.push_str(&escape_xml_entities(href.as_ref()));
body.push_str("</D:href>");
}
body.push_str("</C:addressbook-multiget>");
self.multi_get(addressbook_href.as_ref(), body, &names::ADDRESS_DATA)
.await
}
/// Checks that the given URI advertises carddav support.
///
/// See: <https://www.rfc-editor.org/rfc/rfc6352#section-6.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 carddav
/// support.
pub async fn check_support(&self, url: &Uri) -> Result<(), CheckSupportError> {
check_support(&self.webdav_client, url, "addressbook").await
}
/// Create an address book collection.
///
/// # Errors
///
/// Returns an error in case of network errors or if the server returns a failure status code.
pub async fn create_addressbook(&self, href: &str) -> Result<(), WebDavError> {
self.webdav_client
.create_collection(href, &[&names::ADDRESSBOOK])
.await
}
}
/// Return the service type based on a URL's scheme.
///
/// # Errors
///
/// If `url` is missing a scheme or has a scheme invalid for CardDAV usage.
pub fn service_for_url(url: &Uri) -> Result<DiscoverableService, ServiceForUrlError> {
match url
.scheme()
.ok_or(ServiceForUrlError::MissingScheme)?
.as_ref()
{
"https" | "carddavs" => Ok(DiscoverableService::CardDavs),
"http" | "carddav" => Ok(DiscoverableService::CardDav),
_ => Err(ServiceForUrlError::UnknownScheme),
}
}