vomit-config 0.4.0

Shared configuration library for all Vomit project tools
Documentation
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! 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.
//!
//! ## File format
//!
//! Previously, the TOML file format was used. This is still supported, but
//! deprecated in favor of [scfg](https://codeberg.org/emersion/scfg). The
//! library will print a warning to stderr when loading a TOML file. To migrate
//! over, simply change the filename extension from `.toml` to `.scfg` and
//! convert it to the format described below.
//!
//! The standard location is `$XDG_CONFIG_DIR/vomit/config.scfg`, which usually
//! means `~/.config/vomit/config.scfg`.
//!
//! 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:
//!
//! ```scfg
//! # 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.
//! account example {
//!
//!     # `local` defaults to "~/.maildir", but is best set explicitly:
//!     local '/home/test/.mail'
//!
//!     # 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'
//!
//!     # This section defines settings relevant only for sending mail.
//!     send {
//!         # Override the mail server for sending.
//!         # Defaults to the account-level remote if not set.
//!         remote 'smtp.example.com'
//!
//!         # Some mail setups have different credentials for sending,
//!         # so those can be overridden, too.
//!         # Defaults to the account-level user if not set.
//!         user 'johndoe@example.com'
//!
//!         # See password and pass-cmd above.
//!         # If neither are set, account-level credentials will be used.
//!         #password 's3cr3t'
//!         pass-cmd 'pass show mail/smtp.example.com'
//!
//!         # The From header of outgoing emails. Defaults to the configured
//!         # user, but this will only work if the username is a valid email
//!         # address.
//!         from 'John Doe <johndoe@example.com>'
//!     }
//! }
//! ```

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

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

mod tomlcfg;

mod scfg;

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

/// An error that can occur while reading the config file.
#[derive(Error, Debug)]
pub enum ConfigError {
    /// Error determining the user's home directory.
    #[error("error getting default config file location")]
    DirError,
    /// IO error while trying to read the config file.
    #[error("error reading config file: {0}")]
    IOError(#[from] io::Error),
    /// Error executing the "pass-cmd".
    #[error("error executing pass-cmd: {0}")]
    PassExecError(String),
    /// An invalid UTF-8 string was encountered.
    #[error("UTF-8 error: {0}")]
    UTF8Error(#[from] std::string::FromUtf8Error),
    /// The TOML parser failed.
    #[error("error parsing config file: {0}")]
    TOMLError(#[from] toml::de::Error),
    /// The scfg parser failed.
    #[error("error parsing config file: {0}")]
    ScfgError(#[from] derpscfg::Error),
    /// Other generic error, details in the message.
    #[error("config error: {0}")]
    Error(&'static str),
}

enum AccountImpl<'a> {
    Toml(tomlcfg::TomlAccount<'a>),
    Scfg(&'a scfg::ScfgAccount),
}

/// Represents the configuration of a specific account.
pub struct Account<'a> {
    name: String,
    // Keep a copy of this, as it is potentially computed (tilde expansion)
    local: String,
    acc: AccountImpl<'a>,
}

// TODO remove TOML and rip out the level of indirection here.
enum ConfigImpl {
    Toml(tomlcfg::TomlConfig),
    Scfg(scfg::ScfgConfig),
}

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

impl Config {
    /// Returns a specific account's configuration.
    ///
    /// If `name` is some string and matches the name of a configured account
    /// returns the corresponding [`Account`]. If `name` is `None`, returns the
    /// configuration of the first account in the config file. The latter can be
    /// expected to never return `None` as loading a configuration file fails if
    /// it does not configure at least one account.
    pub fn for_account(&self, name: Option<&str>) -> Option<Account<'_>> {
        match &self.cfg {
            ConfigImpl::Toml(t) => t.for_account(name).map(|a| {
                let local = a.local().to_string();
                Account {
                    name: a.name().clone(),
                    acc: AccountImpl::Toml(a),
                    local,
                }
            }),
            ConfigImpl::Scfg(s) => s.for_account(name).map(|(n, a)| {
                let l = a.local.as_deref();
                let local = tilde(l.unwrap_or(DEFAULT_MAILDIR)).to_string();
                Account {
                    name: n.clone(),
                    acc: AccountImpl::Scfg(a),
                    local,
                }
            }),
        }
    }
}

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

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

    /// The remote IMAP server.
    pub fn remote(&self) -> Option<&str> {
        match &self.acc {
            AccountImpl::Toml(t) => t.remote(),
            AccountImpl::Scfg(s) => s.remote.as_deref(),
        }
    }

    /// The username to log in to the remote server.
    pub fn user(&self) -> Option<&str> {
        match &self.acc {
            AccountImpl::Toml(t) => t.user(),
            AccountImpl::Scfg(s) => s.user.as_deref(),
        }
    }

    /// The "From" address to use when sending mail.
    ///
    /// Can be just an email address or "Some Name <name@example.com>". Falls
    /// back to [send_user()](Self::send_user), which falls back to
    /// [user()](Self::user).
    pub fn send_from(&self) -> Option<&str> {
        match &self.acc {
            AccountImpl::Toml(t) => t.send_from(),
            AccountImpl::Scfg(s) => s
                .send
                .as_ref()
                .and_then(|s| s.from.as_ref())
                .map(|f| f.as_str())
                .or_else(|| self.send_user()),
        }
    }

    /// The username 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> {
        match &self.acc {
            AccountImpl::Toml(t) => t.send_user(),
            AccountImpl::Scfg(s) => s
                .send
                .as_ref()
                .and_then(|s| s.user.as_ref())
                .map(|u| u.as_str())
                .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> {
        match &self.acc {
            AccountImpl::Toml(t) => t.send_remote(),
            AccountImpl::Scfg(s) => s
                .send
                .as_ref()
                .and_then(|s| s.remote.as_ref())
                .map(|r| r.as_str())
                .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> {
        match &self.acc {
            AccountImpl::Toml(t) => t.password(),
            AccountImpl::Scfg(s) => {
                if let Some(p) = s.password.as_ref() {
                    Ok(Some(String::from(p)))
                } else if let Some(cmd) = s.pass_cmd.as_ref() {
                    Account::pass_cmd(cmd)
                } else {
                    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> {
        match &self.acc {
            AccountImpl::Toml(t) => t.send_password(),
            AccountImpl::Scfg(s) => {
                let pass = s.send.as_ref().and_then(|s| s.password.as_ref());
                let pcmd = s.send.as_ref().and_then(|s| s.pass_cmd.as_ref());

                if let Some(p) = pass {
                    Ok(Some(String::from(p)))
                } else if let Some(cmd) = pcmd {
                    Account::pass_cmd(cmd)
                } else {
                    self.password()
                }
            }
        }
    }
}

/// Returns the (system dependent) default path to the configuration file.
///
/// The standard location is `$XDG_CONFIG_DIR`/vomit/config.scfg (which usually
/// means `~/.config/vomit/config.scfg`). If no `$XDG_CONFIG_DIR` can be
/// determined, `~/.vomitrc` is used as fallback. Fails if the user's home
/// directory cannot be determined.
pub fn default_path() -> Result<PathBuf, ConfigError> {
    if let Some(mut path) = config_dir() {
        path.push("vomit");
        path.push("config.scfg");
        return Ok(path);
    };
    if let Some(mut path) = home_dir() {
        path.push(".vomitrc");
        return Ok(path);
    }
    Err(ConfigError::DirError)
}

fn default_path_toml() -> Result<PathBuf, ConfigError> {
    if let Some(mut path) = config_dir() {
        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.
///
/// If `path` is `None`, load it from the default location (see [default_path]).
///
/// For backwards compatibility, if `path` has a `.toml` filename extension it
/// will be parsed as TOML. If it has an extension other than `.toml` or
/// `.scfg`, or none at all, it will be parsed as both scfg and TOML, using
/// whichever one succeeds. If both fails, the returned error will be that from
/// the attempt to parse it as scfg.
pub fn load<P: AsRef<Path>>(path: Option<P>) -> Result<Config, ConfigError> {
    let ps = default_path()?;
    let pt = default_path_toml()?;
    let p = path.map(|p| p.as_ref().to_path_buf()).unwrap_or_else(|| {
        if ps.exists() {
            ps
        } else if pt.exists() {
            pt
        } else {
            // If both don't exist, at least make the error message about the desired one
            ps
        }
    });
    if let Some("scfg") = p.extension().and_then(|e| e.to_str()) {
        Ok(Config {
            cfg: ConfigImpl::Scfg(scfg::load_scfg_file(&p)?),
        })
    } else if let Some("toml") = p.extension().and_then(|e| e.to_str()) {
        eprintln!("WARNING: loading deprecated TOML config, switch to scfg: https://docs.rs/vomit-config/");
        Ok(Config {
            cfg: ConfigImpl::Toml(tomlcfg::load_toml(&p)?),
        })
    } else {
        let r = tomlcfg::load_toml(&p);
        if let Ok(t) = r {
            eprintln!("WARNING: loading deprecated TOML config, switch to scfg: https://docs.rs/vomit-config/");
            Ok(Config {
                cfg: ConfigImpl::Toml(t),
            })
        } else {
            Ok(Config {
                cfg: ConfigImpl::Scfg(scfg::load_scfg_file(&p)?),
            })
        }
    }
}

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

    #[test]
    fn test_load() {
        let d = PathBuf::from_iter([env!("CARGO_MANIFEST_DIR"), "testdata"]);

        let ext_scfg = PathBuf::from_iter([&d, &PathBuf::from("config.scfg")]);
        let r = load(Some(&ext_scfg));
        assert!(matches!(
            r,
            Ok(Config {
                cfg: ConfigImpl::Scfg(_)
            })
        ));

        let ext_toml = PathBuf::from_iter([&d, &PathBuf::from("config.toml")]);
        let r = load(Some(&ext_toml));
        assert!(matches!(
            r,
            Ok(Config {
                cfg: ConfigImpl::Toml(_)
            })
        ));

        let noext_scfg = PathBuf::from_iter([&d, &PathBuf::from("scfg.vomitrc")]);
        let r = load(Some(&noext_scfg));
        assert!(matches!(
            r,
            Ok(Config {
                cfg: ConfigImpl::Scfg(_)
            })
        ));

        let noext_toml = PathBuf::from_iter([&d, &PathBuf::from("toml.vomitrc")]);
        let r = load(Some(&noext_toml));
        assert!(matches!(
            r,
            Ok(Config {
                cfg: ConfigImpl::Toml(_)
            })
        ));
    }
}