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
/*
 * Copyright (c) 2020-2023, Stalwart Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

pub mod macros;
pub mod parse;
pub mod verify;

use std::{
    borrow::Cow,
    net::{Ipv4Addr, Ipv6Addr},
};

use crate::{is_within_pct, SpfOutput, SpfResult, Version};

/*
      "+" pass
      "-" fail
      "~" softfail
      "?" neutral
*/

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Qualifier {
    Pass,
    Fail,
    SoftFail,
    Neutral,
}

/*
   mechanism        = ( all / include
                      / a / mx / ptr / ip4 / ip6 / exists )
*/
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Mechanism {
    All,
    Include {
        macro_string: Macro,
    },
    A {
        macro_string: Macro,
        ip4_mask: u32,
        ip6_mask: u128,
    },
    Mx {
        macro_string: Macro,
        ip4_mask: u32,
        ip6_mask: u128,
    },
    Ptr {
        macro_string: Macro,
    },
    Ip4 {
        addr: Ipv4Addr,
        mask: u32,
    },
    Ip6 {
        addr: Ipv6Addr,
        mask: u128,
    },
    Exists {
        macro_string: Macro,
    },
}

/*
    directive        = [ qualifier ] mechanism
*/
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Directive {
    pub qualifier: Qualifier,
    pub mechanism: Mechanism,
}

/*
      s = <sender>
      l = local-part of <sender>
      o = domain of <sender>
      d = <domain>
      i = <ip>
      p = the validated domain name of <ip> (do not use)
      v = the string "in-addr" if <ip> is ipv4, or "ip6" if <ip> is ipv6
      h = HELO/EHLO domain
   The following macro letters are allowed only in "exp" text:

      c = SMTP client IP (easily readable format)
      r = domain name of host performing the check
      t = current timestamp
*/

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
pub enum Variable {
    Sender = 0,
    SenderLocalPart = 1,
    SenderDomainPart = 2,
    Domain = 3,
    Ip = 4,
    ValidatedDomain = 5,
    IpVersion = 6,
    HeloDomain = 7,
    SmtpIp = 8,
    HostDomain = 9,
    CurrentTime = 10,
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct Variables<'x> {
    vars: [Cow<'x, [u8]>; 11],
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Macro {
    Literal(Vec<u8>),
    Variable {
        letter: Variable,
        num_parts: u32,
        reverse: bool,
        escape: bool,
        delimiters: u64,
    },
    List(Vec<Macro>),
    None,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Spf {
    pub version: Version,
    pub directives: Vec<Directive>,
    pub exp: Option<Macro>,
    pub redirect: Option<Macro>,
    pub ra: Option<Vec<u8>>,
    pub rp: u8,
    pub rr: u8,
}

pub(crate) const RR_TEMP_PERM_ERROR: u8 = 0x01;
pub(crate) const RR_FAIL: u8 = 0x02;
pub(crate) const RR_SOFTFAIL: u8 = 0x04;
pub(crate) const RR_NEUTRAL_NONE: u8 = 0x08;

impl Directive {
    pub fn new(qualifier: Qualifier, mechanism: Mechanism) -> Self {
        Directive {
            qualifier,
            mechanism,
        }
    }
}

impl Mechanism {
    pub fn needs_ptr(&self) -> bool {
        match self {
            Mechanism::All
            | Mechanism::Ip4 { .. }
            | Mechanism::Ip6 { .. }
            | Mechanism::Ptr { .. } => false,
            Mechanism::Include { macro_string } => macro_string.needs_ptr(),
            Mechanism::A { macro_string, .. } => macro_string.needs_ptr(),
            Mechanism::Mx { macro_string, .. } => macro_string.needs_ptr(),
            Mechanism::Exists { macro_string } => macro_string.needs_ptr(),
        }
    }
}

impl TryFrom<&str> for SpfResult {
    type Error = ();

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.eq_ignore_ascii_case("pass") {
            Ok(SpfResult::Pass)
        } else if value.eq_ignore_ascii_case("fail") {
            Ok(SpfResult::Fail)
        } else if value.eq_ignore_ascii_case("softfail") {
            Ok(SpfResult::SoftFail)
        } else if value.eq_ignore_ascii_case("neutral") {
            Ok(SpfResult::Neutral)
        } else if value.eq_ignore_ascii_case("temperror") {
            Ok(SpfResult::TempError)
        } else if value.eq_ignore_ascii_case("permerror") {
            Ok(SpfResult::PermError)
        } else if value.eq_ignore_ascii_case("none") {
            Ok(SpfResult::None)
        } else {
            Err(())
        }
    }
}

impl TryFrom<String> for SpfResult {
    type Error = ();

    fn try_from(value: String) -> Result<Self, Self::Error> {
        TryFrom::try_from(value.as_str())
    }
}

impl SpfOutput {
    pub(crate) fn new(domain: String) -> Self {
        SpfOutput {
            result: SpfResult::None,
            report: None,
            explanation: None,
            domain,
        }
    }

    pub(crate) fn with_result(mut self, result: SpfResult) -> Self {
        self.result = result;
        self
    }

    pub(crate) fn with_report(mut self, spf: &Spf) -> Self {
        match &spf.ra {
            Some(ra) if is_within_pct(spf.rp) => {
                if match self.result {
                    SpfResult::Fail => (spf.rr & RR_FAIL) != 0,
                    SpfResult::SoftFail => (spf.rr & RR_SOFTFAIL) != 0,
                    SpfResult::Neutral | SpfResult::None => (spf.rr & RR_NEUTRAL_NONE) != 0,
                    SpfResult::TempError | SpfResult::PermError => {
                        (spf.rr & RR_TEMP_PERM_ERROR) != 0
                    }
                    SpfResult::Pass => false,
                } {
                    self.report = format!("{}@{}", String::from_utf8_lossy(ra), self.domain).into();
                }
            }
            _ => (),
        }
        self
    }

    pub(crate) fn with_explanation(mut self, explanation: String) -> Self {
        self.explanation = explanation.into();
        self
    }

    pub fn result(&self) -> SpfResult {
        self.result
    }

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

    pub fn explanation(&self) -> Option<&str> {
        self.explanation.as_deref()
    }

    pub fn report_address(&self) -> Option<&str> {
        self.report.as_deref()
    }
}