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
use ipnet::IpNet;
use once_cell::sync::OnceCell;
use std::{collections::HashSet, net::IpAddr};

/// A builder for SpamAssassin Milter configuration objects.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfigBuilder {
    milter_debug_level: i32,
    use_trusted_networks: bool,
    trusted_networks: HashSet<IpNet>,
    auth_untrusted: bool,
    spamc_args: Vec<String>,
    max_message_size: usize,
    dry_run: bool,
    reject_spam: bool,
    reply_code: String,
    reply_status_code: String,
    reply_text: String,
    preserve_headers: bool,
    preserve_body: bool,
    verbose: bool,
}

impl ConfigBuilder {
    pub fn milter_debug_level(&mut self, value: i32) -> &mut Self {
        self.milter_debug_level = value;
        self
    }

    pub fn use_trusted_networks(&mut self, value: bool) -> &mut Self {
        self.use_trusted_networks = value;
        self
    }

    pub fn trusted_network(&mut self, net: IpNet) -> &mut Self {
        self.use_trusted_networks = true;
        self.trusted_networks.insert(net);
        self
    }

    pub fn auth_untrusted(&mut self, value: bool) -> &mut Self {
        self.auth_untrusted = value;
        self
    }

    pub fn spamc_args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.spamc_args.extend(args.into_iter().map(|a| a.as_ref().to_owned()));
        self
    }

    pub fn max_message_size(&mut self, value: usize) -> &mut Self {
        self.max_message_size = value;
        self
    }

    pub fn dry_run(&mut self, value: bool) -> &mut Self {
        self.dry_run = value;
        self
    }

    pub fn reject_spam(&mut self, value: bool) -> &mut Self {
        self.reject_spam = value;
        self
    }

    pub fn reply_code(&mut self, value: String) -> &mut Self {
        self.reply_code = value;
        self
    }

    pub fn reply_status_code(&mut self, value: String) -> &mut Self {
        self.reply_status_code = value;
        self
    }

    pub fn reply_text(&mut self, value: String) -> &mut Self {
        self.reply_text = value;
        self
    }

    pub fn preserve_headers(&mut self, value: bool) -> &mut Self {
        self.preserve_headers = value;
        self
    }

    pub fn preserve_body(&mut self, value: bool) -> &mut Self {
        self.preserve_body = value;
        self
    }

    pub fn verbose(&mut self, value: bool) -> &mut Self {
        self.verbose = value;
        self
    }

    pub fn build(self) -> Config {
        // TODO These invariants are enforced in `main`. In a future revision,
        // consider replacing the assertions with a `Result` return type.
        assert!(
            self.use_trusted_networks || self.trusted_networks.is_empty(),
            "trusted networks present but not used"
        );
        assert!(
            is_valid_reply_code(&self.reply_code)
                && is_valid_reply_code(&self.reply_status_code)
                && self.reply_code.as_bytes()[0] == self.reply_status_code.as_bytes()[0],
            "invalid or incompatible reply codes"
        );

        Config {
            milter_debug_level: self.milter_debug_level,
            use_trusted_networks: self.use_trusted_networks,
            trusted_networks: self.trusted_networks,
            auth_untrusted: self.auth_untrusted,
            spamc_args: self.spamc_args,
            max_message_size: self.max_message_size,
            dry_run: self.dry_run,
            reject_spam: self.reject_spam,
            reply_code: self.reply_code,
            reply_status_code: self.reply_status_code,
            reply_text: self.reply_text,
            preserve_headers: self.preserve_headers,
            preserve_body: self.preserve_body,
            verbose: self.verbose,
        }
    }
}

fn is_valid_reply_code(s: &str) -> bool {
    s.starts_with('4') || s.starts_with('5')
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self {
            milter_debug_level: Default::default(),
            use_trusted_networks: Default::default(),
            trusted_networks: Default::default(),
            auth_untrusted: Default::default(),
            spamc_args: Default::default(),
            max_message_size: 512_000,  // same as in `spamc`
            dry_run: Default::default(),
            reject_spam: Default::default(),
            // This reply code and enhanced status code are the most appropriate
            // choices according to RFCs 5321 and 3463.
            reply_code: String::from("550"),
            reply_status_code: String::from("5.7.1"),
            // Generic reply text that makes no mention of SpamAssassin.
            reply_text: String::from("Spam message refused"),
            preserve_headers: Default::default(),
            preserve_body: Default::default(),
            verbose: Default::default(),
        }
    }
}

/// A configuration object for SpamAssassin Milter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Config {
    milter_debug_level: i32,
    use_trusted_networks: bool,
    trusted_networks: HashSet<IpNet>,
    auth_untrusted: bool,
    spamc_args: Vec<String>,
    max_message_size: usize,
    dry_run: bool,
    reject_spam: bool,
    reply_code: String,
    reply_status_code: String,
    reply_text: String,
    preserve_headers: bool,
    preserve_body: bool,
    verbose: bool,
}

impl Config {
    pub fn builder() -> ConfigBuilder {
        Default::default()
    }

    pub fn milter_debug_level(&self) -> i32 {
        self.milter_debug_level
    }

    pub fn use_trusted_networks(&self) -> bool {
        self.use_trusted_networks
    }

    pub fn is_in_trusted_networks(&self, ip: &IpAddr) -> bool {
        self.trusted_networks.iter().any(|n| n.contains(ip))
    }

    pub fn auth_untrusted(&self) -> bool {
        self.auth_untrusted
    }

    pub fn spamc_args(&self) -> &[String] {
        &self.spamc_args
    }

    pub fn max_message_size(&self) -> usize {
        self.max_message_size
    }

    pub fn dry_run(&self) -> bool {
        self.dry_run
    }

    pub fn reject_spam(&self) -> bool {
        self.reject_spam
    }

    pub fn reply_code(&self) -> &str {
        &self.reply_code
    }

    pub fn reply_status_code(&self) -> &str {
        &self.reply_status_code
    }

    pub fn reply_text(&self) -> &str {
        &self.reply_text
    }

    pub fn preserve_headers(&self) -> bool {
        self.preserve_headers
    }

    pub fn preserve_body(&self) -> bool {
        self.preserve_body
    }

    pub fn verbose(&self) -> bool {
        self.verbose
    }
}

impl Default for Config {
    fn default() -> Self {
        ConfigBuilder::default().build()
    }
}

static CONFIG: OnceCell<Config> = OnceCell::new();

pub fn init(config: Config) {
    CONFIG.set(config).expect("configuration already initialized")
}

pub fn get() -> &'static Config {
    CONFIG.get().expect("configuration not initialized")
}

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

    #[test]
    fn trusted_networks_config() {
        let mut builder = Config::builder();
        builder.trusted_network("127.0.0.1/8".parse().unwrap());
        let config = builder.build();

        assert!(config.use_trusted_networks());
        assert!(config.is_in_trusted_networks(&"127.0.0.1".parse().unwrap()));
        assert!(!config.is_in_trusted_networks(&"10.1.0.1".parse().unwrap()));
    }

    #[test]
    fn spamc_args_extends_args() {
        let mut builder = Config::builder();
        builder.spamc_args(&["-p", "3030"]);
        builder.spamc_args(&["-x"]);
        let config = builder.build();

        assert_eq!(
            config.spamc_args(),
            &[String::from("-p"), String::from("3030"), String::from("-x")],
        );
    }
}