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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! This crate provides a unified config file for all tools that are part of the [Vomit project](https://sr.ht/~bitfehler/vomit).
//!
//! It aims to provide configuration options for various aspects of email accounts. Most tools will only need a subset of the
//! available options, but once an account is fully configured, all tools will be able to work with it.
//!
//! While written for the Vomit project, this is essentially a generic email account configuration library. If you think it
//! might be useful for you feel free to use outside of Vomit.
//!
//! The standard location is `$XDG_CONFIG_DIR`/vomit/config.toml, which usually means `~/.config/vomit/config.toml`.
//!
//! Projects using this will have their own documentation about which values they require. Here is a sample with
//! all available options (though some commented out), including comments on their usage:
//!
//! ```toml
//! ## This section defines one account named "example". Most tools
//! ## support multiple accounts. If not specified, tools should default
//! ## to the first account in the config file.
//! [example]
//! ## `local` defaults to "~/.maildir", but can be set explicitly:
//! local = '/home/test/.maildir'
//! ## The mail server. Must support IMAPS
//! remote = 'imap.example.com'
//! ## Login name for the mail server
//! user = 'johndoe'
//! ## Password for the mail server. Can be set explicitly:
//! #password = 'hunter1'
//! ## but that's not great for security. Instead use a command,
//! ## e.g. to interact with your password manager
//! pass-cmd = 'pass show mail/example.com'
//! ## If sending mail is handled by a different server (i.e. a dedicated
//! ## SMTP server), override it like this:
//! send.remote = 'smtp.example.com'
//! ## Some mail setups even have different credentials for sending mail,
//! ## So those can be overridden, too:
//! send.user = 'johndoe@example.com'
//! ## See password and pass-cmd above:
//! #send.password = 's3cr3t'
//! send.pass-cmd = 'pass show mail/smtp.example.com'
//! ```

use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

use dirs::{config_dir, home_dir};
use shellexpand::tilde;
use thiserror::Error;

const DEFAULT_MAILDIR: &str = "~/.maildir";

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("error getting default config file location")]
    DirError,
    #[error("error reading config file: {0}")]
    IOError(#[from] io::Error),
    #[error("error executing pass-cmd: {0}")]
    PassExecError(String),
    #[error("UTF-8 error: {0}")]
    UTF8Error(#[from] std::string::FromUtf8Error),
    #[error("error parsing config file: {0}")]
    TOMLError(#[from] toml::de::Error),
    #[error("config error: {0}")]
    Error(&'static str),
}

/// Represents the configuration of a specific account
pub struct Account<'a> {
    name: String,
    settings: &'a toml::value::Table,
    // Keep a copy of this, as it is potentially computed (tilde expansion)
    maildir_: String,
}

/// Represents a complete config file, which can hold multiple [Accounts](Account)
pub struct Config {
    cfg: toml::value::Table,
}

impl Config {
    /// Returns a specific account's configuration
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the account. If `None`, returns the configuration of the first account in the config file.
    pub fn for_account(&self, name: Option<String>) -> Option<Account> {
        let name = match &name {
            Some(n) => n,
            // Leaving this a .expect() as load() already checks that there is an account
            None => self.cfg.keys().next().expect("no account found"),
        };

        if let Some(a) = self.cfg.get(name) {
            if let Some(t) = a.as_table() {
                // Compute the local maildir
                let mut path = DEFAULT_MAILDIR;
                if let Some(l) = t.get("local") {
                    if let Some(p) = l.as_str() {
                        path = p
                    }
                };

                return Some(Account {
                    name: String::from(name),
                    settings: t,
                    maildir_: tilde(path).into_owned(),
                });
            }
        }
        None
    }
}

impl Account<'_> {
    /// The name of the account
    pub fn name(&self) -> &String {
        &self.name
    }

    /// The directory where mail is stored locally in maildir format
    pub fn maildir(&self) -> &str {
        &self.maildir_
    }

    /// The remote IMAP server
    pub fn remote(&self) -> Option<&str> {
        return self.settings.get("remote").and_then(|v| v.as_str());
    }

    /// The user name to log in to the remote server
    pub fn user(&self) -> Option<&str> {
        return self.settings.get("user").and_then(|v| v.as_str());
    }

    /// The user name to log in when sending mail
    ///
    /// If not explicitly configured, this returns the value of [user()](Account::user).
    pub fn send_user(&self) -> Option<&str> {
        let v = self
            .settings
            .get("send")
            .and_then(|v| v.as_table())
            .and_then(|v| v.get("user"))
            .and_then(|v| v.as_str());
        v.or_else(|| self.user())
    }

    /// The remote SMTP server
    ///
    /// If not explicitly configured, this returns the value of [remote()](Account::remote).
    pub fn send_remote(&self) -> Option<&str> {
        let v = self
            .settings
            .get("send")
            .and_then(|v| v.as_table())
            .and_then(|v| v.get("remote"))
            .and_then(|v| v.as_str());
        v.or_else(|| self.remote())
    }

    fn pass_cmd(cmd: &str) -> Result<Option<String>, ConfigError> {
        let out = Command::new("sh").arg("-c").arg(cmd).output();
        match out {
            Ok(mut output) => {
                let newline: u8 = 10;
                if Some(&newline) == output.stdout.last() {
                    _ = output.stdout.pop(); // remove trailing newline
                }
                Ok(Some(String::from_utf8(output.stdout)?))
            }
            Err(e) => Err(ConfigError::PassExecError(e.to_string())),
        }
    }

    /// The password to log in to the remote server
    ///
    /// Potentially executes a configured command to retrieve the password.
    /// Returns an error if the password command has to be executed and fails. Can return `Ok(None)` if neither
    /// a password nor a password command are configured. Otherwise, returns the password.
    pub fn password(&self) -> Result<Option<String>, ConfigError> {
        if let Some(p) = self.settings.get("password").and_then(|v| v.as_str()) {
            return Ok(Some(String::from(p)));
        } else if let Some(cmd) = self.settings.get("pass-cmd").and_then(|v| v.as_str()) {
            return Account::pass_cmd(cmd);
        }
        Ok(None)
    }

    /// The password to log in to the remote server for sending mail
    ///
    /// Potentially executes a configured command to retrieve the password.
    /// Returns an error if the password command has to be executed and fails. Can return `Ok(None)` if neither
    /// a password nor a password command are configured. Otherwise, returns the password.
    ///
    /// Unless explicitly configured by the user, this returns the value of [password()](Account::password).
    pub fn send_password(&self) -> Result<Option<String>, ConfigError> {
        let pass = self
            .settings
            .get("send")
            .and_then(|v| v.as_table())
            .and_then(|v| v.get("password"))
            .and_then(|v| v.as_str());
        if let Some(p) = pass {
            return Ok(Some(String::from(p)));
        }

        let pcmd = self
            .settings
            .get("send")
            .and_then(|v| v.as_table())
            .and_then(|v| v.get("pass-cmd"))
            .and_then(|v| v.as_str());
        if let Some(cmd) = pcmd {
            return Account::pass_cmd(cmd);
        }
        self.password()
    }
}

/// Returns the (system dependent) default path to the configuration file
///
/// Can fail if the user's home directory cannot be determined.
pub fn default_path() -> Result<PathBuf, ConfigError> {
    if let Some(mut path) = config_dir() {
        // let mut cfg = PathBuf::from(path);
        path.push("vomit");
        path.push("config.toml");
        return Ok(path);
    };
    if let Some(mut path) = home_dir() {
        path.push(".vomitrc");
        return Ok(path);
    }
    Err(ConfigError::DirError)
}

/// Load a configuration file
///
/// # Arguments
///
/// * `path` - the path to load the file from. If `None`, load it from the default location.
///
/// See [default_path] for the default location.
pub fn load<P: AsRef<Path>>(path: Option<P>) -> Result<Config, ConfigError> {
    let contents = match path {
        Some(p) => fs::read_to_string(p)?,
        None => fs::read_to_string(default_path()?)?,
    };

    let value = contents.parse::<toml::Value>()?;
    let table: toml::value::Table = value.try_into()?;

    if table.is_empty() {
        Err(ConfigError::Error("no accounts found"))
    } else {
        Ok(Config { cfg: table })
    }
}

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

    #[test]
    fn test_simple() {
        let table: toml::value::Table = toml::from_str(
            r#"
            [example]
            local = '/home/test/.maildir'
            remote = 'mx.example.com'
            user = 'johndoe'
            password = 'hunter1'
        "#,
        )
        .unwrap();

        let config = Config { cfg: table };

        let acc = config.for_account(None).expect("no account found");

        assert_eq!(acc.user(), Some("johndoe"));
        assert_eq!(acc.remote(), Some("mx.example.com"));
        assert_eq!(
            acc.password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
        assert_eq!(acc.send_user(), Some("johndoe"));
        assert_eq!(acc.send_remote(), Some("mx.example.com"));
        assert_eq!(
            acc.send_password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
    }

    #[test]
    fn test_send() {
        let table: toml::value::Table = toml::from_str(
            r#"
            [example]
            local = '/home/test/.maildir'
            remote = 'imap.example.com'
            user = 'johndoe'
            password = 'hunter1'
            send.remote = 'smtp.example.com'
            send.user = 'johndoe@example.com'
            send.password = 's3cr3t'
        "#,
        )
        .unwrap();

        let config = Config { cfg: table };

        let acc = config.for_account(None).expect("no account found");

        assert_eq!(acc.user(), Some("johndoe"));
        assert_eq!(acc.remote(), Some("imap.example.com"));
        assert_eq!(
            acc.password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
        assert_eq!(acc.send_user(), Some("johndoe@example.com"));
        assert_eq!(acc.send_remote(), Some("smtp.example.com"));
        assert_eq!(
            acc.send_password().expect("failed to get password"),
            Some(String::from("s3cr3t"))
        );
    }

    #[test]
    fn test_simple_cmd() {
        let table: toml::value::Table = toml::from_str(
            r#"
            [example]
            local = '/home/test/.maildir'
            remote = 'mx.example.com'
            user = 'johndoe'
            pass-cmd = 'echo hunter1'
        "#,
        )
        .unwrap();

        let config = Config { cfg: table };

        let acc = config.for_account(None).expect("no account found");

        assert_eq!(acc.user(), Some("johndoe"));
        assert_eq!(acc.remote(), Some("mx.example.com"));
        assert_eq!(
            acc.password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
        assert_eq!(acc.send_user(), Some("johndoe"));
        assert_eq!(acc.send_remote(), Some("mx.example.com"));
        assert_eq!(
            acc.send_password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
    }

    #[test]
    fn test_send_cmd() {
        let table: toml::value::Table = toml::from_str(
            r#"
            [example]
            local = '/home/test/.maildir'
            remote = 'imap.example.com'
            user = 'johndoe'
            pass-cmd = 'echo hunter1'
            send.remote = 'smtp.example.com'
            send.user = 'johndoe@example.com'
            send.pass-cmd = 'echo s3cr3t'
        "#,
        )
        .unwrap();

        let config = Config { cfg: table };

        let acc = config.for_account(None).expect("no account found");

        assert_eq!(acc.user(), Some("johndoe"));
        assert_eq!(acc.remote(), Some("imap.example.com"));
        assert_eq!(
            acc.password().expect("failed to get password"),
            Some(String::from("hunter1"))
        );
        assert_eq!(acc.send_user(), Some("johndoe@example.com"));
        assert_eq!(acc.send_remote(), Some("smtp.example.com"));
        assert_eq!(
            acc.send_password().expect("failed to get password"),
            Some(String::from("s3cr3t"))
        );
    }
}