summaryrefslogtreecommitdiff
path: root/crates/utils/src/config/mod.rs
blob: 217354a2cfb890a83e0360fa2c1b004d13a3c7b4 (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
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
/*
 * Copyright (c) 2023 Stalwart Labs Ltd.
 *
 * This file is part of Stalwart Mail Server.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * in the LICENSE file at the top-level directory of this distribution.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can be released from the requirements of the AGPLv3 license by
 * purchasing a commercial license. Please contact licensing@stalw.art
 * for more details.
*/

pub mod certificate;
pub mod dynvalue;
pub mod listener;
pub mod parser;
pub mod utils;

use std::{
    borrow::Cow,
    collections::BTreeMap,
    fmt::Display,
    net::{IpAddr, Ipv4Addr, SocketAddr},
    time::Duration,
};

use rustls::ServerConfig;
use tokio::net::TcpSocket;

use crate::{failed, UnwrapFailure};

use self::utils::ParseValue;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    pub keys: BTreeMap<String, String>,
}

#[derive(Debug, Default)]
pub struct Server {
    pub id: String,
    pub internal_id: u16,
    pub hostname: String,
    pub data: String,
    pub protocol: ServerProtocol,
    pub listeners: Vec<Listener>,
    pub tls: Option<ServerConfig>,
    pub tls_implicit: bool,
    pub max_connections: u64,
}

pub struct Servers {
    pub inner: Vec<Server>,
}

#[derive(Debug)]
pub struct Listener {
    pub socket: TcpSocket,
    pub addr: SocketAddr,
    pub ttl: Option<u32>,
    pub backlog: Option<u32>,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum ServerProtocol {
    #[default]
    Smtp,
    Lmtp,
    Jmap,
    Imap,
    Http,
    ManageSieve,
}

#[derive(Debug, Clone)]
pub enum DynValue<T: ParseValue> {
    String(String),
    Position(usize),
    Key(T),
    List(Vec<DynValue<T>>),
}

pub trait KeyLookup {
    type Key: ParseValue;

    fn key(&self, key: &Self::Key) -> Cow<'_, str>;
    fn key_as_int(&self, key: &Self::Key) -> i32;
    fn key_as_ip(&self, key: &Self::Key) -> IpAddr;
}

impl KeyLookup for () {
    type Key = String;

    fn key(&self, _: &Self::Key) -> Cow<'_, str> {
        "".into()
    }

    fn key_as_int(&self, _: &Self::Key) -> i32 {
        0
    }

    fn key_as_ip(&self, _: &Self::Key) -> IpAddr {
        IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))
    }
}

#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct Rate {
    pub requests: u64,
    pub period: Duration,
}

impl Display for ServerProtocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServerProtocol::Smtp => write!(f, "smtp"),
            ServerProtocol::Lmtp => write!(f, "lmtp"),
            ServerProtocol::Jmap => write!(f, "jmap"),
            ServerProtocol::Imap => write!(f, "imap"),
            ServerProtocol::Http => write!(f, "http"),
            ServerProtocol::ManageSieve => write!(f, "managesieve"),
        }
    }
}

pub type Result<T> = std::result::Result<T, String>;

impl Config {
    pub fn init() -> Self {
        let mut config_path = None;
        let mut found_param = false;

        for arg in std::env::args().skip(1) {
            if let Some((key, value)) = arg.split_once('=') {
                if key.starts_with("--config") {
                    config_path = value.trim().to_string().into();
                    break;
                } else {
                    failed(&format!("Invalid command line argument: {key}"));
                }
            } else if found_param {
                config_path = arg.into();
                break;
            } else if arg.starts_with("--config") {
                found_param = true;
            } else {
                failed(&format!("Invalid command line argument: {arg}"));
            }
        }

        Config::parse(
            &std::fs::read_to_string(
                config_path.failed("Missing parameter --config=<path-to-config>."),
            )
            .failed("Could not read configuration file"),
        )
        .failed("Invalid configuration file")
    }
}