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
//! 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. Users should look into the
//! application instead.
//!
//! [SPF Milter]: https://crates.io/crates/spf-milter

#![doc(html_root_url = "https://docs.rs/spf-milter/0.2.0")]

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,
        ParseSyslogFacilityError, SyslogFacility,
    },
};
use crate::{
    callbacks::*,
    config::{cli_opts, read},
    resolver::MockResolver,
};
use log::{error, info, LevelFilter, Log, Metadata, Record, SetLoggerError};
use milter::Milter;
use signal_hook::flag;
use std::sync::Arc;
use viaspf::Lookup;

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

/// The SPF Milter version string.
pub const VERSION: &str = "0.2.0";

/// Starts SPF Milter with the given CLI options.
///
/// This is a blocking call.
///
/// # Errors
///
/// If initialisation or execution of the milter fails, a `milter::Error`
/// variant is returned.
///
/// # Examples
///
/// ```no_run
/// use spf_milter::CliOptions;
/// use std::process;
///
/// let options = CliOptions::default();
///
/// if let Err(e) = spf_milter::run(options) {
///     eprintln!("failed to run spf-milter: {}", e);
///     process::exit(1);
/// }
/// ```
pub fn run(opts: CliOptions) -> milter::Result<()> {
    init_and_run(opts, None)
}

/// Starts SPF Milter with the given CLI options, using `lookup` for all DNS
/// queries.
///
/// This method can be used to run SPF Milter with a mock DNS resolver,
/// especially for testing.
///
/// This is a blocking call.
///
/// # Errors
///
/// If initialisation or execution of the milter fails, a `milter::Error`
/// variant is returned.
pub fn run_with_lookup(
    opts: CliOptions,
    lookup: impl Lookup + Send + Sync + 'static,
) -> milter::Result<()> {
    init_and_run(opts, Some(MockResolver::new(lookup)))
}

fn init_and_run(opts: CliOptions, mock_resolver: Option<MockResolver>) -> milter::Result<()> {
    init_static_config(opts, mock_resolver)?;

    let socket = {
        // Limit scope of this `Arc<Config>` so that it gets dropped before the
        // blocking call to `Milter::run` below (else we would keep a reference
        // to the initial configuration alive for the rest of the program).
        let config = config::current();
        config.socket().to_owned()
    };

    // Register the reload signal handler just before passing control to the
    // milter library.
    let reload_flag = config::get_reload_flag();
    flag::register(signal_hook::consts::SIGUSR1, Arc::clone(reload_flag))
        .map_err(|e| format!("failed to register signal handler: {}", e))?;

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

    let result = Milter::new(&socket)
        .name(MILTER_NAME)
        .on_negotiate(negotiate_callback)
        .on_connect(connect_callback)
        .on_helo(helo_callback)
        .on_mail(mail_callback)
        .on_header(header_callback)
        .on_eom(eom_callback)
        .on_abort(abort_callback)
        .on_close(close_callback)
        .remove_socket(true)
        .run();

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

    result
}

fn init_static_config(opts: CliOptions, mock_resolver: Option<MockResolver>) -> milter::Result<()> {
    // Three pieces of global data are initialised first: `CliOptions`, optional
    // `MockResolver`, and the `Mutex` with the current configuration.

    cli_opts::init(opts);
    resolver::init_mock(mock_resolver);

    let opts = cli_opts::get();

    let config = read::read_config(opts).map_err(|e| {
        format!(
            "failed to load configuration from {}: {}",
            opts.config_file().display(),
            read::focus_error(&e)
        )
    })?;

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

    // Note: No logging until this point.

    config::init(config);

    Ok(())
}

/// A minimal log implementation that uses `eprintln!` for logging.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
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) {}
}

/// Requests that the configuration be reloaded later.
///
/// Configuration reloading is asynchronous. The actual reloading from disk
/// happens only when the next new connection is opened.
pub fn reload_config() {
    config::set_reload();
}