aboutsummaryrefslogtreecommitdiff
path: root/src/configuration.rs
blob: 1c8741d71b96490feb0d286aa9621a4451a73b5b (plain)
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
//! # Configuration
//!
//! This module defines the configuration used to initialize both proxies.

use log::error;
use std::env;
use std::fmt::Debug;
use std::sync::Arc;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("Environment variable {0} not set.")]
    MissingEnvVar(String),
    #[error("Failed to parse {0}.")]
    ParseError(String),
}

/// Configuration for any proxy
#[derive(Debug)]
pub struct Proxy {
    pub local_port: u16,
    pub bind_address: String,
    pub remote_host: String,
    pub remote_port: u16,
    pub protocol: &'static str,
}

/// Aggregated configuration for both proxies, already in a reference counter.
pub struct Configuration {
    pub imap_configuration: Arc<Proxy>,
    pub smtp_configuration: Arc<Proxy>,
}

impl Configuration {
    /// Creates a new configuration object by reading the environment
    /// variables. Exits if the right ones aren't found.
    pub fn new() -> Result<Self, Error> {
        Ok(Configuration {
            imap_configuration: Arc::new(Proxy {
                local_port: get_env_number("LOCAL_IMAP_PORT", 143)?,
                bind_address: get_env_var("LOCAL_IMAP_BIND_ADDRESS", Some("0.0.0.0".to_string()))?,
                remote_host: get_env_var("REMOTE_IMAP_HOST", None)?,
                remote_port: get_env_number("REMOTE_IMAP_PORT", 993)?,
                protocol: "IMAP",
            }),
            smtp_configuration: Arc::new(Proxy {
                local_port: get_env_number("LOCAL_SMTP_PORT", 25)?,
                bind_address: get_env_var("LOCAL_SMTP_BIND_ADDRESS", Some("0.0.0.0".to_string()))?,
                remote_host: get_env_var("REMOTE_SMTP_HOST", None)?,
                remote_port: get_env_number("REMOTE_SMTP_PORT", 465)?,
                protocol: "SMTP",
            }),
        })
    }
}

/// Get an environment variable or return an error.
fn get_env_var(name: &str, default: Option<String>) -> Result<String, Error> {
    match env::var(name) {
        Ok(value) => Ok(value),
        Err(_) => match default {
            Some(default_value) => Ok(default_value),
            None => Err(Error::MissingEnvVar(name.to_string())),
        },
    }
}

/// Get an environment variable and parse it as a number. Return a default
/// if not set.
fn get_env_number(name: &str, default: u16) -> Result<u16, Error> {
    match env::var(name) {
        Ok(value) => value
            .parse()
            .map_err(|_| Error::ParseError(name.to_string())),
        Err(_) => Ok(default),
    }
}