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

//! Builder types used for both caldav and carddav clients.
//!
//! The main type here is [`ClientBuilder`].
use std::marker::PhantomData;

use domain::base::Dname;
use email_address::EmailAddress;
use http::Uri;
use hyper::client::connect::Connect;

use crate::{
    auth::{Auth, Password},
    common::{find_home_set, Rfc6764Protocol},
    dav::WebDavClient,
    dns::{find_context_path_via_txt_records, resolve_srv_record},
    BootstrapError, InvalidUrl,
};

pub struct NeedsUri(());
pub struct NeedsAuth {
    uri: Uri,
}
pub struct NeedsPassword {
    uri: Uri,
    username: String,
}
pub struct PendingDiscovery {
    pub(crate) uri: Uri,
    pub(crate) auth: Auth,
}
// Hint: This state is required to have generic without_discovery and with_home_set functions.
pub struct Ready<C>
where
    C: Connect + Clone + Sync + Send + 'static,
{
    pub(crate) dav_client: WebDavClient<C>,
    pub(crate) home_set: Option<Uri>,
}

/// A builder for clients.
///
/// Use [`CalDavClient::builder`] and [`CardDavClient::builder`] to create a new builder instance.
///
/// [`CalDavClient::builder`]: `super::CalDavClient::builder`
/// [`CardDavClient::builder`]: `super::CardDavClient::builder`
///
/// # Example
///
///```no_run
/// # use http::Uri;
/// use libdav::CardDavClient;
/// use libdav::auth::Auth;
/// use hyper_rustls::HttpsConnectorBuilder;
/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
/// # let base_url = Uri::try_from("https://example.com").unwrap();
/// # let username = "test".to_string();
/// # let password = "test".to_string().into();
///
/// let https = HttpsConnectorBuilder::new()
///     .with_native_roots()
///     .unwrap()
///     .https_or_http()
///     .enable_http1()
///     .build();
/// let carddav_client = CardDavClient::builder()
///     .with_uri(base_url)
///     .with_auth(Auth::Basic {
///         username,
///         password: Some(password),
///     })
///     .bootstrap(https)
///     .await
///     .unwrap()
///     .build();
/// # })
///```
#[allow(clippy::module_name_repetitions)]
pub struct ClientBuilder<ClientType, State> {
    state: State,
    phantom: PhantomData<ClientType>,
}

#[derive(thiserror::Error, Debug)]
pub enum WithEmailError {
    #[error("failed to build Uri from host portion")]
    Invalidhost(#[from] http::uri::InvalidUri),
}

impl<ClientType> ClientBuilder<ClientType, NeedsUri> {
    pub(crate) fn new() -> ClientBuilder<ClientType, NeedsUri> {
        ClientBuilder {
            state: NeedsUri(()),
            phantom: PhantomData,
        }
    }

    /// Sets the host and port from a `Uri`.
    ///
    /// # Example
    ///
    /// ```
    /// use hyper::client::HttpConnector;
    /// use hyper_rustls::HttpsConnector;
    /// use libdav::CalDavClient;
    /// use libdav::CardDavClient;
    ///
    /// CardDavClient::<HttpsConnector<HttpConnector>>::builder()
    ///     .with_uri("https://example.com".parse().unwrap());
    ///
    /// CalDavClient::<HttpsConnector<HttpConnector>>::builder()
    ///     .with_uri("caldavs://example.com".parse().unwrap());
    /// ```
    ///
    /// # Caveats
    ///
    /// Using a `mailto` Uri here is currently not possible due to [this bug in hyper].
    ///
    /// [this bug in hyper]: https://github.com/hyperium/http/issues/596
    pub fn with_uri(self, uri: Uri) -> ClientBuilder<ClientType, NeedsAuth> {
        ClientBuilder {
            state: NeedsAuth { uri },
            phantom: self.phantom,
        }
    }

    /// Sets the host and username from an email.
    ///
    /// # Errors
    ///
    /// If building the `base_uri` fails with the host extracted from the email address.
    pub fn with_email(
        self,
        email: &EmailAddress,
    ) -> Result<ClientBuilder<ClientType, NeedsPassword>, WithEmailError> {
        Ok(ClientBuilder {
            state: NeedsPassword {
                uri: Uri::try_from(email.domain())?,
                // TODO: rfc6764 says "clients MUST first use the "mailbox" portion of the calendar
                // user address provided by the user in the case of a "mailto:" address and, if
                // that results in an authentication failure, SHOULD fall back to using the "local-
                // part" extracted from the "mailto:" address."
                //
                // To implement this, the builder needs to be aware of this variation, and `build`
                // needs to be async.
                username: email.to_string(),
            },
            phantom: self.phantom,
        })
    }
}

impl<ClientType> ClientBuilder<ClientType, NeedsAuth> {
    /// Sets the authentication type and credentials.
    pub fn with_auth(self, auth: Auth) -> ClientBuilder<ClientType, PendingDiscovery> {
        ClientBuilder {
            state: PendingDiscovery {
                uri: self.state.uri,
                auth,
            },
            phantom: self.phantom,
        }
    }
}

impl<ClientType> ClientBuilder<ClientType, NeedsPassword> {
    /// Sets the password.
    ///
    /// Passing a `String` works, but using the `Password` type is recommended.
    pub fn with_password<P: Into<Password>>(
        self,
        password: P,
    ) -> ClientBuilder<ClientType, PendingDiscovery> {
        ClientBuilder {
            state: PendingDiscovery {
                uri: self.state.uri,
                auth: Auth::Basic {
                    username: self.state.username,
                    password: Some(password.into()),
                },
            },
            phantom: self.phantom,
        }
    }

    /// Sets no password.
    pub fn without_password(self) -> ClientBuilder<ClientType, PendingDiscovery> {
        ClientBuilder {
            state: PendingDiscovery {
                uri: self.state.uri,
                auth: Auth::Basic {
                    username: self.state.username,
                    password: None,
                },
            },
            phantom: self.phantom,
        }
    }
}

impl<ClientType: Rfc6764Protocol> ClientBuilder<ClientType, PendingDiscovery> {
    /// Perform 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
    ///
    /// # 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 as missing, only if they contain invalid data.
    pub async fn bootstrap<C>(
        self,
        connector: C,
    ) -> Result<ClientBuilder<ClientType, Ready<C>>, BootstrapError>
    where
        C: Connect + Clone + Sync + Send,
    {
        let service = ClientType::service(&self.state.uri)?;
        let home_set_prop = ClientType::home_set_property();

        let domain = self.state.uri.host().ok_or(InvalidUrl::MissingHost)?;
        let port = self.state.uri.port_u16().unwrap_or(service.default_port());

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

        let mut dav_client = WebDavClient::new(self.state.uri, self.state.auth, connector);
        if let Some(path) = find_context_path_via_txt_records(service, &dname).await? {
            let candidate = &host_candidates[0];

            // TODO: check `DAV:` capabilities here.
            dav_client.base_url = Uri::builder()
                .scheme(service.scheme())
                .authority(format!("{}:{}", candidate.0, candidate.1))
                .path_and_query(path)
                .build()
                .map_err(BootstrapError::UnusableSrv)?;
        } else {
            for candidate in host_candidates {
                if let Ok(Some(url)) = dav_client
                    .find_context_path(service, &candidate.0, candidate.1)
                    .await
                {
                    dav_client.base_url = url;
                    break;
                }
            }
        }

        dav_client.principal = dav_client.find_current_user_principal().await?;
        let home_set = find_home_set(&dav_client, home_set_prop).await?;

        Ok(ClientBuilder {
            state: Ready {
                dav_client,
                home_set,
            },
            phantom: self.phantom,
        })
    }

    /// Create a client without any discovery.
    ///
    /// This constructor is recommended only for situations where DNS-based discovery is
    /// unavailable or undesirable.
    ///
    /// When in doubt, use [`ClientBuilder::build`].
    // TODO: normalise wording; we mix "discovery" and "bootstrap" in some places.
    pub fn without_discovery<C>(self, connector: C) -> ClientBuilder<ClientType, Ready<C>>
    where
        C: Connect + Clone + Sync + Send + 'static,
    {
        ClientBuilder {
            state: Ready {
                dav_client: WebDavClient::new(self.state.uri, self.state.auth, connector),
                home_set: None,
            },
            phantom: self.phantom,
        }
    }

    pub fn with_home_set<C>(
        self,
        connector: C,
        home_set: Uri,
    ) -> ClientBuilder<ClientType, Ready<C>>
    where
        C: Connect + Clone + Sync + Send + 'static,
    {
        ClientBuilder {
            state: Ready {
                dav_client: WebDavClient::new(self.state.uri, self.state.auth, connector),
                home_set: Some(home_set),
            },
            phantom: self.phantom,
        }
    }
}

impl<ClientType: Rfc6764Protocol, C> ClientBuilder<ClientType, Ready<C>>
where
    C: Connect + Clone + Sync + Send,
{
    /// Returns a webdav client and the discovered home set.
    pub(crate) fn into_parts(self) -> (WebDavClient<C>, Option<Uri>) {
        (self.state.dav_client, self.state.home_set)
    }
}