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
362
363
364
365
366
367
368
369
370
371
372
//! # Login parameters.

use std::fmt;

use anyhow::{ensure, Result};

use crate::constants::{DC_LP_AUTH_FLAGS, DC_LP_AUTH_NORMAL, DC_LP_AUTH_OAUTH2};
use crate::context::Context;
use crate::provider::Socket;
use crate::provider::{get_provider_by_id, Provider};
use crate::socks::Socks5Config;

#[derive(Copy, Clone, Debug, Display, FromPrimitive, ToPrimitive, PartialEq, Eq)]
#[repr(u32)]
#[strum(serialize_all = "snake_case")]
pub enum CertificateChecks {
    /// Same as AcceptInvalidCertificates if stored in the database
    /// as `configured_{imap,smtp}_certificate_checks`.
    ///
    /// Previous Delta Chat versions stored this in `configured_*`
    /// if Automatic configuration
    /// was selected, configuration with strict TLS checks failed
    /// and configuration without strict TLS checks succeeded.
    ///
    /// Currently Delta Chat stores only
    /// `Strict` or `AcceptInvalidCertificates` variants
    /// in `configured_*` settings.
    ///
    /// `Automatic` in `{imap,smtp}_certificate_checks`
    /// means that provider database setting should be taken.
    /// If there is no provider database setting for certificate checks,
    /// `Automatic` is the same as `Strict`.
    Automatic = 0,

    Strict = 1,

    /// Same as AcceptInvalidCertificates
    /// Previously known as AcceptInvalidHostnames, now deprecated.
    AcceptInvalidCertificates2 = 2,

    AcceptInvalidCertificates = 3,
}

impl Default for CertificateChecks {
    fn default() -> Self {
        Self::Automatic
    }
}

/// Login parameters for a single server, either IMAP or SMTP
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct ServerLoginParam {
    pub server: String,
    pub user: String,
    pub password: String,
    pub port: u16,
    pub security: Socket,
    pub oauth2: bool,

    /// TLS options: whether to allow invalid certificates and/or
    /// invalid hostnames
    pub certificate_checks: CertificateChecks,
}

#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct LoginParam {
    pub addr: String,
    pub imap: ServerLoginParam,
    pub smtp: ServerLoginParam,
    pub provider: Option<&'static Provider>,
    pub socks5_config: Option<Socks5Config>,
}

impl LoginParam {
    /// Load entered (candidate) account settings
    pub async fn load_candidate_params(context: &Context) -> Result<Self> {
        let mut param = Self::load_candidate_params_unchecked(context).await?;
        ensure!(!param.addr.is_empty(), "Missing email address.");

        // Only check for IMAP password, SMTP password is an "advanced" setting.
        ensure!(!param.imap.password.is_empty(), "Missing (IMAP) password.");
        if param.smtp.password.is_empty() {
            param.smtp.password = param.imap.password.clone()
        }
        Ok(param)
    }

    /// Load entered (candidate) account settings without validation.
    ///
    /// This will result in a potentially invalid [`LoginParam`] struct as the values are
    /// not validated.  Only use this if you want to show this directly to the user e.g. in
    /// [`Context::get_info`].
    pub async fn load_candidate_params_unchecked(context: &Context) -> Result<Self> {
        LoginParam::from_database(context, "").await
    }

    /// Load configured (working) account settings
    pub async fn load_configured_params(context: &Context) -> Result<Self> {
        LoginParam::from_database(context, "configured_").await
    }

    /// Read the login parameters from the database.
    async fn from_database(context: &Context, prefix: &str) -> Result<Self> {
        let sql = &context.sql;

        let key = &format!("{prefix}addr");
        let addr = sql
            .get_raw_config(key)
            .await?
            .unwrap_or_default()
            .trim()
            .to_string();

        let key = &format!("{prefix}mail_server");
        let mail_server = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}mail_port");
        let mail_port = sql.get_raw_config_int(key).await?.unwrap_or_default();

        let key = &format!("{prefix}mail_user");
        let mail_user = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}mail_pw");
        let mail_pw = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}mail_security");
        let mail_security = sql
            .get_raw_config_int(key)
            .await?
            .and_then(num_traits::FromPrimitive::from_i32)
            .unwrap_or_default();

        let key = &format!("{prefix}imap_certificate_checks");
        let imap_certificate_checks =
            if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
                num_traits::FromPrimitive::from_i32(certificate_checks).unwrap()
            } else {
                Default::default()
            };

        let key = &format!("{prefix}send_server");
        let send_server = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}send_port");
        let send_port = sql.get_raw_config_int(key).await?.unwrap_or_default();

        let key = &format!("{prefix}send_user");
        let send_user = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}send_pw");
        let send_pw = sql.get_raw_config(key).await?.unwrap_or_default();

        let key = &format!("{prefix}send_security");
        let send_security = sql
            .get_raw_config_int(key)
            .await?
            .and_then(num_traits::FromPrimitive::from_i32)
            .unwrap_or_default();

        let key = &format!("{prefix}smtp_certificate_checks");
        let smtp_certificate_checks =
            if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
                num_traits::FromPrimitive::from_i32(certificate_checks).unwrap_or_default()
            } else {
                Default::default()
            };

        let key = &format!("{prefix}server_flags");
        let server_flags = sql.get_raw_config_int(key).await?.unwrap_or_default();
        let oauth2 = matches!(server_flags & DC_LP_AUTH_FLAGS, DC_LP_AUTH_OAUTH2);

        let key = &format!("{prefix}provider");
        let provider = sql
            .get_raw_config(key)
            .await?
            .and_then(|provider_id| get_provider_by_id(&provider_id));

        let socks5_config = Socks5Config::from_database(&context.sql).await?;

        Ok(LoginParam {
            addr,
            imap: ServerLoginParam {
                server: mail_server,
                user: mail_user,
                password: mail_pw,
                port: mail_port as u16,
                security: mail_security,
                oauth2,
                certificate_checks: imap_certificate_checks,
            },
            smtp: ServerLoginParam {
                server: send_server,
                user: send_user,
                password: send_pw,
                port: send_port as u16,
                security: send_security,
                oauth2,
                certificate_checks: smtp_certificate_checks,
            },
            provider,
            socks5_config,
        })
    }

    /// Save this loginparam to the database.
    pub async fn save_as_configured_params(&self, context: &Context) -> Result<()> {
        let prefix = "configured_";
        let sql = &context.sql;

        context.set_primary_self_addr(&self.addr).await?;

        let key = &format!("{prefix}mail_server");
        sql.set_raw_config(key, Some(&self.imap.server)).await?;

        let key = &format!("{prefix}mail_port");
        sql.set_raw_config_int(key, i32::from(self.imap.port))
            .await?;

        let key = &format!("{prefix}mail_user");
        sql.set_raw_config(key, Some(&self.imap.user)).await?;

        let key = &format!("{prefix}mail_pw");
        sql.set_raw_config(key, Some(&self.imap.password)).await?;

        let key = &format!("{prefix}mail_security");
        sql.set_raw_config_int(key, self.imap.security as i32)
            .await?;

        let key = &format!("{prefix}imap_certificate_checks");
        sql.set_raw_config_int(key, self.imap.certificate_checks as i32)
            .await?;

        let key = &format!("{prefix}send_server");
        sql.set_raw_config(key, Some(&self.smtp.server)).await?;

        let key = &format!("{prefix}send_port");
        sql.set_raw_config_int(key, i32::from(self.smtp.port))
            .await?;

        let key = &format!("{prefix}send_user");
        sql.set_raw_config(key, Some(&self.smtp.user)).await?;

        let key = &format!("{prefix}send_pw");
        sql.set_raw_config(key, Some(&self.smtp.password)).await?;

        let key = &format!("{prefix}send_security");
        sql.set_raw_config_int(key, self.smtp.security as i32)
            .await?;

        let key = &format!("{prefix}smtp_certificate_checks");
        sql.set_raw_config_int(key, self.smtp.certificate_checks as i32)
            .await?;

        // The OAuth2 flag is either set for both IMAP and SMTP or not at all.
        let key = &format!("{prefix}server_flags");
        let server_flags = match self.imap.oauth2 {
            true => DC_LP_AUTH_OAUTH2,
            false => DC_LP_AUTH_NORMAL,
        };
        sql.set_raw_config_int(key, server_flags).await?;

        if let Some(provider) = self.provider {
            let key = &format!("{prefix}provider");
            sql.set_raw_config(key, Some(provider.id)).await?;
        }

        Ok(())
    }
}

impl fmt::Display for LoginParam {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let unset = "0";
        let pw = "***";

        write!(
            f,
            "{} imap:{}:{}:{}:{}:{}:cert_{}:{} smtp:{}:{}:{}:{}:{}:cert_{}:{}",
            unset_empty(&self.addr),
            unset_empty(&self.imap.user),
            if !self.imap.password.is_empty() {
                pw
            } else {
                unset
            },
            unset_empty(&self.imap.server),
            self.imap.port,
            self.imap.security,
            self.imap.certificate_checks,
            if self.imap.oauth2 {
                "OAUTH2"
            } else {
                "AUTH_NORMAL"
            },
            unset_empty(&self.smtp.user),
            if !self.smtp.password.is_empty() {
                pw
            } else {
                unset
            },
            unset_empty(&self.smtp.server),
            self.smtp.port,
            self.smtp.security,
            self.smtp.certificate_checks,
            if self.smtp.oauth2 {
                "OAUTH2"
            } else {
                "AUTH_NORMAL"
            },
        )
    }
}

fn unset_empty(s: &str) -> &str {
    if s.is_empty() {
        "unset"
    } else {
        s
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::TestContext;

    #[test]
    fn test_certificate_checks_display() {
        use std::string::ToString;

        assert_eq!(
            "accept_invalid_certificates".to_string(),
            CertificateChecks::AcceptInvalidCertificates.to_string()
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_save_load_login_param() -> Result<()> {
        let t = TestContext::new().await;

        let param = LoginParam {
            addr: "alice@example.org".to_string(),
            imap: ServerLoginParam {
                server: "imap.example.com".to_string(),
                user: "alice".to_string(),
                password: "foo".to_string(),
                port: 123,
                security: Socket::Starttls,
                oauth2: false,
                certificate_checks: CertificateChecks::Strict,
            },
            smtp: ServerLoginParam {
                server: "smtp.example.com".to_string(),
                user: "alice@example.org".to_string(),
                password: "bar".to_string(),
                port: 456,
                security: Socket::Ssl,
                oauth2: false,
                certificate_checks: CertificateChecks::AcceptInvalidCertificates,
            },
            provider: get_provider_by_id("example.com"),
            // socks5_config is not saved by `save_to_database`, using default value
            socks5_config: None,
        };

        param.save_as_configured_params(&t).await?;
        let loaded = LoginParam::load_configured_params(&t).await?;

        assert_eq!(param, loaded);
        Ok(())
    }
}