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
//! The SPF Milter application library.
//!
//! This library was published to facilitate integration testing of the [SPF
//! Milter application][SPF Milter]. No backwards compatibility guarantees are
//! made for the public API in this library. Please look into the application
//! instead.
//!
//! [SPF Milter]: https://crates.io/crates/spf-milter

mod auth;
mod callbacks;
mod config;
mod header;
mod resolver;
mod verify;

pub use crate::config::{
    cli_opts::{CliOptions, CliOptionsBuilder},
    model::{
        LogDestination, LogLevel, ParseLogDestinationError, ParseLogLevelError, ParseSocketError,
        ParseSyslogFacilityError, Socket, SyslogFacility,
    },
};
use crate::{
    config::{read, RuntimeConfig},
    resolver::MockResolver,
};
use indymilter::IntoListener;
use log::{error, info, LevelFilter, Log, Metadata, Record, SetLoggerError};
use std::{
    future::Future,
    io::{self, ErrorKind},
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::sync::mpsc;
use viaspf::lookup::Lookup;

/// The SPF Milter application name.
pub const MILTER_NAME: &str = "SPF Milter";

/// The SPF Milter version string.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Initial configuration read from the file system.
pub struct Config {
    cli_opts: CliOptions,
    config: config::Config,
    mock_resolver: Option<MockResolver>,
}

impl Config {
    /// Reads configuration from the file system.
    ///
    /// # Errors
    ///
    /// If no valid configuration could be read, an error is returned.
    pub async fn read(opts: CliOptions) -> io::Result<Self> {
        Self::read_internal(opts, None).await
    }

    /// Reads configuration from the file system, and sets up the supplied
    /// `Lookup` to be used for all DNS queries.
    ///
    /// This method can be used to run SPF Milter with a mock DNS resolver,
    /// especially for testing.
    ///
    /// # Errors
    ///
    /// If no valid configuration could be read, an error is returned.
    pub async fn read_with_lookup(
        opts: CliOptions,
        lookup: impl Lookup + 'static,
    ) -> io::Result<Self> {
        let mock_resolver = Some(MockResolver::new(lookup));
        Self::read_internal(opts, mock_resolver).await
    }

    async fn read_internal(
        opts: CliOptions,
        mock_resolver: Option<MockResolver>,
    ) -> io::Result<Self> {
        let config = read::read_config(&opts).await.map_err(|e| {
            io::Error::new(
                ErrorKind::Other,
                format!(
                    "failed to load configuration from {}: {}",
                    opts.config_file().display(),
                    read::focus_error(&e)
                ),
            )
        })?;

        Ok(Self {
            cli_opts: opts,
            config,
            mock_resolver,
        })
    }

    /// Returns the configured socket.
    pub fn socket(&self) -> &Socket {
        self.config.socket()
    }
}

/// Starts SPF Milter listening on the given socket using the supplied
/// configuration.
///
/// # Errors
///
/// If execution of the milter fails, an error is returned.
///
/// # Examples
///
/// ```
/// # async fn f() -> std::io::Result<()> {
/// use spf_milter::Config;
/// use std::process;
/// use tokio::{net::TcpListener, signal, sync::mpsc};
///
/// let listener = TcpListener::bind("127.0.0.1:3000").await?;
/// let opts = Default::default();
/// let config = Config::read(opts).await?;
/// let (_, reload) = mpsc::channel(1);
/// let shutdown = signal::ctrl_c();
///
/// if let Err(e) = spf_milter::run(listener, config, reload, shutdown).await {
///     eprintln!("failed to run spf-milter: {}", e);
///     process::exit(1);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn run(
    listener: impl IntoListener,
    config: Config,
    reload: mpsc::Receiver<()>,
    shutdown: impl Future,
) -> io::Result<()> {
    let Config { cli_opts, config, mock_resolver } = config;

    match config.log_destination() {
        LogDestination::Syslog => {
            syslog::init_unix(config.syslog_facility().into(), config.log_level().into())
                .map_err(|e| {
                    io::Error::new(
                        ErrorKind::Other,
                        format!("could not initialize syslog: {}", e),
                    )
                })?;
        }
        LogDestination::Stderr => {
            StderrLog::init(config.log_level()).map_err(|e| {
                io::Error::new(
                    ErrorKind::Other,
                    format!("could not initialize stderr log: {}", e),
                )
            })?;
        }
    }

    // Note: No logging until this point.

    let runtime = match mock_resolver {
        Some(resolver) => RuntimeConfig::with_mock_resolver(config, resolver),
        None => RuntimeConfig::new(config),
    };
    let runtime = Arc::new(Mutex::new(Arc::new(runtime)));

    spawn_reload_task(runtime.clone(), cli_opts, reload);

    let callbacks = callbacks::make_callbacks(runtime);

    // Override default timeout, which is too short in practice.
    let config = indymilter::Config {
        connection_timeout: Duration::from_secs(7210),
        ..Default::default()
    };

    info!("{} {} starting", MILTER_NAME, VERSION);

    let result = indymilter::run(listener, callbacks, config, shutdown).await;

    match &result {
        Ok(()) => info!("{} {} shut down", MILTER_NAME, VERSION),
        Err(e) => error!("{} {} terminated with error: {}", MILTER_NAME, VERSION, e),
    }

    result
}

fn spawn_reload_task(
    runtime: Arc<Mutex<Arc<RuntimeConfig>>>,
    opts: CliOptions,
    mut reload: mpsc::Receiver<()>,
) {
    tokio::spawn(async move {
        while let Some(()) = reload.recv().await {
            config::reload(&runtime, &opts).await;
        }
    });
}

/// A minimal log implementation that uses `eprintln!` for logging.
struct StderrLog {
    level: LevelFilter,
}

impl StderrLog {
    fn init<L: Into<LevelFilter>>(level: L) -> Result<(), SetLoggerError> {
        let level = level.into();
        log::set_boxed_logger(Box::new(Self { level }))
            .map(|_| log::set_max_level(level))
    }
}

impl Log for StderrLog {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            eprintln!("{}", record.args());
        }
    }

    fn flush(&self) {}
}