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
#[macro_use]
extern crate log;

mod lookup;

use self::lookup::*;
use samotop_core::{
    common::*,
    mail::{AcceptsDispatch, DispatchError, DispatchResult, MailDispatch, MailSetup},
    smtp::{SmtpPath, SmtpSession},
};
pub use viaspf::Config;
use viaspf::{evaluate_sender, SpfResult};

/// enables checking for SPF records
#[derive(Clone, Debug)]
pub struct Spf;

impl Spf {
    /// use viaspf config
    pub fn with_config(self, config: Config) -> SpfWithConfig {
        SpfWithConfig {
            config: Arc::new(config),
        }
    }
}

#[derive(Clone, Debug)]
pub struct SpfWithConfig {
    config: Arc<Config>,
}

impl<T: AcceptsDispatch> MailSetup<T> for SpfWithConfig {
    fn setup(self, config: &mut T) {
        config.add_last_dispatch(self)
    }
}
impl<T: AcceptsDispatch> MailSetup<T> for Spf {
    fn setup(self, config: &mut T) {
        config.add_last_dispatch(Spf.with_config(Config::default()))
    }
}

impl MailDispatch for SpfWithConfig {
    fn open_mail_body<'a, 's, 'f>(
        &'a self,
        session: &'s mut SmtpSession,
    ) -> S1Fut<'f, DispatchResult>
    where
        'a: 'f,
        's: 'f,
    {
        let peer_addr = match session.connection.peer_addr.as_str().parse() {
            Err(_) => std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
            Ok(ip) => ip,
        };
        let peer_name = session.peer_name.clone().unwrap_or_default();
        let sender = match session.transaction.mail.as_ref().map(|m| m.sender()) {
            None | Some(SmtpPath::Null) | Some(SmtpPath::Postmaster) => String::new(),
            Some(SmtpPath::Mailbox { host, .. }) => host.domain(),
        };
        let fut = async move {
            // TODO: improve privacy - a) encrypt DNS, b) do DNS servers need to know who is receiving mail from whom?
            let resolver = match new_resolver().await {
                Err(e) => {
                    error!("Could not crerate resolver! {:?}", e);
                    return Err(DispatchError::Temporary);
                }
                Ok(resolver) => resolver,
            };
            let evaluation = evaluate_sender(
                &resolver,
                &self.config,
                peer_addr,
                &sender.parse().map_err(|e| {
                    error!("Could not parse sender {:?}, {}", sender, e);
                    DispatchError::Temporary
                })?,
                Some(&peer_name.parse().map_err(|e| {
                    error!("Could not parse peer domain {:?}, {}", peer_name, e);
                    DispatchError::Temporary
                })?),
            )
            .await;
            match evaluation.spf_result {
                SpfResult::Fail(explanation) => {
                    info!("mail rejected due to SPF fail: {}", explanation);
                    Err(DispatchError::Permanent)
                }
                result => {
                    debug!("mail OK with SPF result: {}", result);
                    session
                        .transaction
                        .extra_headers
                        .push_str(format!("X-Samotop-SPF: {}\r\n", result).as_str());
                    Ok(())
                }
            }
        };

        Box::pin(fut)
    }
}

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

    #[test]
    fn default_mail_fut_is_sync() {
        let mut sess = SmtpSession::default();
        let cfg = Config::default();
        let sut = Spf.with_config(cfg);
        let fut = sut.open_mail_body(&mut sess);
        is_send(fut);
    }

    #[test]
    fn config_is_sync() {
        let cfg = Config::default();
        is_sync(cfg);
    }

    fn is_sync<T: Sync>(_subject: T) {}
    fn is_send<T: Send>(_subject: T) {}
}