crymap 2.0.1

A simple, secure IMAP server with encrypted data at rest
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
//-
// Copyright (c) 2023, 2024, Jason Lingle
//
// This file is part of Crymap.
//
// Crymap is free software: you can  redistribute it and/or modify it under the
// terms of  the GNU General Public  License as published by  the Free Software
// Foundation, either version  3 of the License, or (at  your option) any later
// version.
//
// Crymap is distributed  in the hope that  it will be useful,  but WITHOUT ANY
// WARRANTY; without  even the implied  warranty of MERCHANTABILITY  or FITNESS
// FOR  A PARTICULAR  PURPOSE.  See the  GNU General  Public  License for  more
// details.
//
// You should have received a copy of the GNU General Public License along with
// Crymap. If not, see <http://www.gnu.org/licenses/>.

//! An interpreter for the esoteric programming language known as "Sender
//! Policy Framework".
//!
//! Without the DNS query count limit and DNS name size limits, it would almost
//! be Turing-complete: If there were a way to "pop" an element off a list, a
//! Turing machine would be easy to implement with chains of `redirect` using
//! `%{d}`.

use std::borrow::Cow;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::rc::Rc;

use chrono::prelude::*;
use itertools::Itertools;

use super::syntax as s;
use crate::support::dns;

// RFC 7208 § 4.6.4
/// The maximum number of directives which trigger DNS queries which may be
/// processed.
///
/// If this limit is reached without finding a conclusive result, return error.
const MAX_DNS_DIRECTIVES: u32 = 10;
/// The maximum number of names returned by an MX query. If this limit is
/// exceeded, return error.
const MAX_MX_SIZE: usize = 10;
/// The maximum number of names returned by a PTR query. If this limit is
/// exceeded, ignore the extra names.
const MAX_PTR_SIZE: usize = 10;

/// The fundamental SPF result types.
///
/// RFC 7208 § 2.6
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpfResult {
    None,
    Neutral,
    Pass,
    Fail,
    SoftFail,
    TempError,
    PermError,
}

impl fmt::Display for SpfResult {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = match *self {
            Self::None => "none",
            Self::Neutral => "neutral",
            Self::Pass => "pass",
            Self::Fail => "fail",
            Self::SoftFail => "softfail",
            Self::TempError => "temperror",
            Self::PermError => "permerror",
        };
        write!(f, "{s}")
    }
}

/// The "explanation" string which can be produced on failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Explanation {
    /// There is definitely no explanation. Either SPF didn't fail, or the
    /// failing record does not issue an explanation.
    None,
    /// There might be an explanation in the future, but it is pending on
    /// fetching more DNS records.
    NotReady,
    /// The given explanation was generated.
    Some(String),
}

/// The (possibly, see `skipped_directive`) conclusive result of evaluating an
/// SPF record.
struct ResultInfo {
    /// The SPF result itself.
    result: SpfResult,

    /// The `spf_domain` where the conclusion was reached.
    spf_domain: Rc<dns::Name>,
    /// The TXT record where the conclusion was reached. This can later be used
    /// to generate an explanation.
    spf_txt: Option<Rc<str>>,
}

/// Immutable context used during the evaluation of an SPF record.
pub struct Context<'a> {
    /// The full sender email address; i.e., from the `MAIL FROM` line.
    ///
    /// If `None`, the implicit "postmaster@{domain}" value is supplied by the
    /// evaluator.
    pub sender: Option<Cow<'a, str>>,
    /// The local part of the sender email address.
    ///
    /// If `None`, the implicit "postmaster" value is supplied by the
    /// evaluator.
    pub sender_local: Option<Cow<'a, str>>,
    /// The `HELO` domain or domain part of the `MAIL FROM`.
    pub sender_domain: Cow<'a, str>,
    /// The parsed representation of `sender_domain`.
    pub sender_domain_parsed: Rc<dns::Name>,
    /// The `HELO` domain.
    pub helo_domain: Cow<'a, str>,
    /// The sender IP address.
    ///
    /// This should not be an IPv6-encapsulated IPv4 address. Such addresses
    /// should be converted to IPv4 first.
    pub ip: IpAddr,
    /// The receiver host.
    pub receiver_host: Cow<'a, str>,
    /// The current time.
    pub now: DateTime<Utc>,
}

/// Internal state carried through a single SPF evaluation pass.
#[derive(Default)]
struct EvaluatorState {
    /// The number of DNS directives triggered so far (not including
    /// sub-queries from `ptr` or `mx` directives).
    dns_directives: u32,
    /// Whether a `ptr` directive has been executed.
    ///
    /// If `false`, the `%{p}` macro does nothing. If `true`, the `%{p}` macro
    /// repeats the `ptr` logic to find its expansion value.
    ///
    /// RFC 7208 § 7.3 is unclear as to whether `%{p}` itself should trigger
    /// the PTR queries. For now, we assume it does not, as allowing macros to
    /// initiate DNS queries makes the code more complicated, use of this macro
    /// is already both esoteric and deprecated, and SPF authors need to be
    /// prepared for the PTR query to fail anyway.
    has_ptr: bool,
    /// Set to `true` when the evaluator skipped processing a directive because
    /// it required a DNS query that has not yet completed, in order to
    /// discover new DNS queries further down the line.
    skipped_directive: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DirectiveError {
    TempFail,
    PermFail,
    NotReady,
    SyntaxError(s::Error),
}

/// Performs full evaluation of SPF starting with `ctx.sender_domain`.
///
/// Returns `Some` once a conclusive result is available; i.e., at the point
/// where no further DNS information is needed to determine the SPF result. If
/// `Explanation` is `NotReady`, more DNS information is needed to generate the
/// explanation.
///
/// If this returns `None`, `New` entries may be added to `dns::Cache`. The
/// driver must arrange to perform these queries (changing them to `NotReady`)
/// and re-run `eval` when more data is available.
pub fn eval(
    ctx: &Context<'_>,
    dns_cache: &mut dns::Cache,
) -> Option<(SpfResult, Explanation)> {
    let mut evaluator = EvaluatorState::default();
    let result = evaluator
        .eval_spf_chain(ctx, dns_cache, Rc::clone(&ctx.sender_domain_parsed))
        .unwrap_or_else(|| ResultInfo {
            result: SpfResult::Neutral,
            spf_domain: Rc::clone(&ctx.sender_domain_parsed),
            spf_txt: None,
        });

    if evaluator.skipped_directive {
        // If we skipped any directives before coming to a conclusion, we're
        // not ready to give an actual result.
        None
    } else {
        let explanation = match result {
            ResultInfo {
                result: SpfResult::Fail,
                spf_domain,
                spf_txt: Some(spf_txt),
            } => evaluator.explain(ctx, dns_cache, &spf_domain, &spf_txt),
            _ => Explanation::None,
        };

        Some((result.result, explanation))
    }
}

impl EvaluatorState {
    /// Evaluates a complete SPF chain (i.e. following redirects) starting from
    /// `spf_domain`.
    ///
    /// Returns `None` if no conclusive result is available, or `Some` if there
    /// may be a conclusive result. `Some` results are bogus if
    /// `skipped_directive` is true.
    fn eval_spf_chain(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        mut spf_domain: Rc<dns::Name>,
    ) -> Option<ResultInfo> {
        for i in 0.. {
            match self.eval_one_spf(ctx, dns_cache, Rc::clone(&spf_domain)) {
                Ok(mut result) => {
                    if i != 0 {
                        // "None" result on redirect => permanent error
                        if result.result == SpfResult::None {
                            result.result = SpfResult::PermError;
                        }
                    }

                    return Some(result);
                },

                // Inconclusive because the TXT record isn't available yet.
                // Therefore, also inconclusive here.
                Err(None) => return None,

                Err(Some(txt)) => {
                    // Inconclusive, but look for a redirect to continue
                    // evaluation. If no redirect, this step is also
                    // inconclusive.
                    let redirect = txt
                        .split(' ')
                        .map(s::Term::parse)
                        .find_map(|r| match r {
                            Ok(s::Term::Modifier(s::Modifier::Redirect(s))) => {
                                Some(s)
                            },
                            _ => None,
                        })?;

                    // Redirect counts as a DNS directive. This is also the
                    // only thing preventing us from evaluating a self-redirect
                    // infinitely.
                    if self.incr_dns_directive().is_err() {
                        return Some(ResultInfo {
                            result: SpfResult::PermError,
                            spf_domain,
                            spf_txt: Some(txt),
                        });
                    }

                    // Expanding and parsing the domain can only fail if %{p}
                    // is pending, or the expanded domain is invalid. For the
                    // latter, we've necessarily already saved
                    // skipped_directive from the ptr directive which enabled
                    // %{p}, so we can treat any error here as a hard error
                    let Ok(new_domain) = self.expand_and_parse_domain(
                        ctx,
                        dns_cache,
                        &spf_domain,
                        Some(redirect),
                    ) else {
                        return Some(ResultInfo {
                            result: SpfResult::PermError,
                            spf_domain,
                            spf_txt: Some(txt),
                        });
                    };

                    spf_domain = new_domain;
                },
            }
        }

        // Unreachable
        None
    }

    /// Run the SPF evaluation process on the SPF record at `spf_domain`.
    ///
    /// If a conclusive result is available, returns that result. The result
    /// will be bogus if `self.skipped_directive` is true; in this case, the
    /// evaluator carried on solely to discover additional DNS queries.
    ///
    /// Returns `Err` if inconclusive, along with the TXT record (if
    /// available).
    fn eval_one_spf(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: Rc<dns::Name>,
    ) -> Result<ResultInfo, Option<Rc<str>>> {
        let txt_records = match dns::look_up(&mut dns_cache.txt, &spf_domain) {
            Ok(records) => records,
            Err(dns::CacheError::NotFound) => {
                return Ok(ResultInfo {
                    result: SpfResult::None,
                    spf_domain,
                    spf_txt: None,
                })
            },
            Err(dns::CacheError::Error) => {
                return Ok(ResultInfo {
                    result: SpfResult::TempError,
                    spf_domain,
                    spf_txt: None,
                })
            },
            Err(dns::CacheError::NotReady) => {
                self.skipped_directive = true;
                return Err(None);
            },
        };

        const PREFIX: &str = "v=spf1";
        let Some(spf_txt) = txt_records
            .iter()
            .find(|r| {
                r.get(..PREFIX.len())
                    .is_some_and(|s| s.eq_ignore_ascii_case(PREFIX))
            })
            .cloned()
        else {
            return Ok(ResultInfo {
                result: SpfResult::None,
                spf_domain,
                spf_txt: None,
            });
        };

        for word in spf_txt.split(' ') {
            if word.is_empty() {
                continue;
            }

            match s::Term::parse(word) {
                Err(_) => {
                    return Ok(ResultInfo {
                        result: SpfResult::PermError,
                        spf_domain,
                        spf_txt: Some(spf_txt),
                    })
                },

                Ok(s::Term::Modifier(..)) => {},

                Ok(s::Term::Directive(directive)) => {
                    match self.eval_directive(
                        ctx,
                        dns_cache,
                        &spf_domain,
                        directive,
                    ) {
                        Ok(None) => {},
                        Ok(Some(q)) => {
                            let result = match q {
                                s::Qualifier::Pass => SpfResult::Pass,
                                s::Qualifier::Fail => SpfResult::Fail,
                                s::Qualifier::SoftFail => SpfResult::SoftFail,
                                s::Qualifier::Neutral => SpfResult::Neutral,
                            };

                            return Ok(ResultInfo {
                                result,
                                spf_domain,
                                spf_txt: Some(spf_txt),
                            });
                        },
                        Err(DirectiveError::TempFail) => {
                            return Ok(ResultInfo {
                                result: SpfResult::TempError,
                                spf_domain,
                                spf_txt: Some(spf_txt),
                            })
                        },
                        Err(
                            DirectiveError::PermFail
                            | DirectiveError::SyntaxError(..),
                        ) => {
                            return Ok(ResultInfo {
                                result: SpfResult::PermError,
                                spf_domain,
                                spf_txt: Some(spf_txt),
                            });
                        },
                        Err(DirectiveError::NotReady) => {
                            self.skipped_directive = true;
                        },
                    }
                },
            }
        }

        Err(Some(spf_txt))
    }

    fn eval_directive(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        directive: s::Directive,
    ) -> Result<Option<s::Qualifier>, DirectiveError> {
        if self.eval_mechanism(
            ctx,
            dns_cache,
            spf_domain,
            directive.mechanism,
        )? {
            Ok(Some(directive.qualifier))
        } else {
            Ok(None)
        }
    }

    fn eval_mechanism(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        mechanism: s::Mechanism,
    ) -> Result<bool, DirectiveError> {
        use super::syntax::Mechanism as M;

        match mechanism {
            M::All => Ok(true),
            M::Include(target) => {
                self.eval_include(ctx, dns_cache, spf_domain, target)
            },
            M::A(domain, ipv4_cidr_len, ipv6_cidr_len) => self.eval_a(
                ctx,
                dns_cache,
                spf_domain,
                domain,
                ipv4_cidr_len,
                ipv6_cidr_len,
            ),
            M::Mx(domain, ipv4_cidr_len, ipv6_cidr_len) => self.eval_mx(
                ctx,
                dns_cache,
                spf_domain,
                domain,
                ipv4_cidr_len,
                ipv6_cidr_len,
            ),
            M::Ptr(domain) => self.eval_ptr(ctx, dns_cache, spf_domain, domain),
            M::Ip4(addr, cidr_len) => self.eval_ip4(ctx, addr, cidr_len),
            M::Ip6(addr, cidr_len) => self.eval_ip6(ctx, addr, cidr_len),
            M::Exists(target) => {
                self.eval_exists(ctx, dns_cache, spf_domain, target)
            },
        }
    }

    fn eval_a(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: Option<s::MacroString<'_>>,
        ipv4_cidr_len: Option<u32>,
        ipv6_cidr_len: Option<u32>,
    ) -> Result<bool, DirectiveError> {
        self.incr_dns_directive()?;
        let domain =
            self.expand_and_parse_domain(ctx, dns_cache, spf_domain, domain)?;

        self.eval_a_or_mx_domain(
            ctx,
            &mut dns_cache.a,
            &mut dns_cache.aaaa,
            domain,
            ipv4_cidr_len,
            ipv6_cidr_len,
        )
    }

    fn eval_mx(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: Option<s::MacroString<'_>>,
        ipv4_cidr_len: Option<u32>,
        ipv6_cidr_len: Option<u32>,
    ) -> Result<bool, DirectiveError> {
        self.incr_dns_directive()?;
        let domain =
            self.expand_and_parse_domain(ctx, dns_cache, spf_domain, domain)?;

        let mx_records =
            top_level_error_map(dns::look_up(&mut dns_cache.mx, domain))?
                .map(|v| v.as_slice())
                .unwrap_or_default();

        if mx_records.len() >= MAX_MX_SIZE {
            return Err(DirectiveError::PermFail);
        }

        let mut not_ready = false;
        let mut temp_fail = false;
        for &(ref record, _) in mx_records {
            match self.eval_a_or_mx_domain(
                ctx,
                &mut dns_cache.a,
                &mut dns_cache.aaaa,
                Rc::clone(record),
                ipv4_cidr_len,
                ipv6_cidr_len,
            ) {
                Ok(true) => return Ok(true),
                Ok(false) => {},
                // Remember temporary DNS errors but keep looking in case a
                // later record succeeds.
                Err(DirectiveError::TempFail) => temp_fail = true,
                // Keep going if the current one is pending. We do all the
                // lookups in parallel this way.
                Err(DirectiveError::NotReady) => not_ready = true,
                // The other error cases shouldn't happen, but default to
                // passing them through.
                Err(e) => return Err(e),
            }
        }

        if not_ready {
            Err(DirectiveError::NotReady)
        } else if temp_fail {
            Err(DirectiveError::TempFail)
        } else {
            Ok(false)
        }
    }

    fn eval_a_or_mx_domain(
        &self,
        ctx: &Context<'_>,
        dns_cache_a: &mut dns::CacheMap<Vec<Ipv4Addr>>,
        dns_cache_aaaa: &mut dns::CacheMap<Vec<Ipv6Addr>>,
        domain: Rc<dns::Name>,
        ipv4_cidr_len: Option<u32>,
        ipv6_cidr_len: Option<u32>,
    ) -> Result<bool, DirectiveError> {
        Ok(match ctx.ip {
            IpAddr::V4(ip) => {
                top_level_error_map(dns::look_up(dns_cache_a, domain))?
                    .map(|v| v.as_slice())
                    .unwrap_or_default()
                    .iter()
                    .any(|&a| ipv4_addr_matches(ip, a, ipv4_cidr_len))
            },

            IpAddr::V6(ip) => {
                top_level_error_map(dns::look_up(dns_cache_aaaa, domain))?
                    .map(|v| v.as_slice())
                    .unwrap_or_default()
                    .iter()
                    .any(|&a| ipv6_addr_matches(ip, a, ipv6_cidr_len))
            },
        })
    }

    fn eval_ptr(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: Option<s::MacroString<'_>>,
    ) -> Result<bool, DirectiveError> {
        self.incr_dns_directive()?;
        self.has_ptr = true;
        let domain =
            self.expand_and_parse_domain(ctx, dns_cache, spf_domain, domain)?;
        find_validated_name(dns_cache, ctx, &domain).map(|o| o.is_some())
    }

    fn eval_ip4(
        &self,
        ctx: &Context<'_>,
        a: Ipv4Addr,
        cidr_len: Option<u32>,
    ) -> Result<bool, DirectiveError> {
        match ctx.ip {
            IpAddr::V4(v4) => Ok(ipv4_addr_matches(v4, a, cidr_len)),
            IpAddr::V6(_) => Ok(false),
        }
    }

    fn eval_ip6(
        &self,
        ctx: &Context<'_>,
        a: Ipv6Addr,
        cidr_len: Option<u32>,
    ) -> Result<bool, DirectiveError> {
        match ctx.ip {
            IpAddr::V4(_) => Ok(false),
            IpAddr::V6(v6) => Ok(ipv6_addr_matches(v6, a, cidr_len)),
        }
    }

    fn eval_exists(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: s::MacroString<'_>,
    ) -> Result<bool, DirectiveError> {
        self.incr_dns_directive()?;
        let domain = self.expand_and_parse_domain(
            ctx,
            dns_cache,
            spf_domain,
            Some(domain),
        )?;
        Ok(top_level_error_map(dns::look_up(&mut dns_cache.a, domain))?
            .map(|v| !v.is_empty())
            .unwrap_or_default())
    }

    fn eval_include(
        &mut self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: s::MacroString<'_>,
    ) -> Result<bool, DirectiveError> {
        // This is the only thing enforcing any kind of recursion limit.
        self.incr_dns_directive()?;
        let domain = self.expand_and_parse_domain(
            ctx,
            dns_cache,
            spf_domain,
            Some(domain),
        )?;

        match self
            .eval_spf_chain(ctx, dns_cache, domain)
            .map(|r| r.result)
        {
            // RFC 7208 § 5.2
            None => Ok(false), // Basically "neutral" (or not known yet)
            Some(SpfResult::Pass) => Ok(true),
            Some(
                SpfResult::Fail | SpfResult::SoftFail | SpfResult::Neutral,
            ) => Ok(false),
            Some(SpfResult::TempError) => Err(DirectiveError::TempFail),
            Some(SpfResult::PermError | SpfResult::None) => {
                Err(DirectiveError::PermFail)
            },
        }
    }

    fn incr_dns_directive(&mut self) -> Result<(), DirectiveError> {
        if self.dns_directives >= MAX_DNS_DIRECTIVES {
            return Err(DirectiveError::PermFail);
        }

        self.dns_directives += 1;
        Ok(())
    }

    fn expand_and_parse_domain(
        &self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &Rc<dns::Name>,
        domain: Option<s::MacroString<'_>>,
    ) -> Result<Rc<dns::Name>, DirectiveError> {
        match domain {
            None => Ok(Rc::clone(spf_domain)),
            Some(domain) => {
                let domain = self.expand_macro_string(
                    ctx, dns_cache, spf_domain, false, domain,
                )?;
                dns_cache
                    .intern_domain(domain)
                    .map_err(|_| DirectiveError::PermFail)
            },
        }
    }

    /// Generate the failure explanation from the given SPF record.
    fn explain(
        &self,
        ctx: &Context<'_>,
        dns_cache: &mut dns::Cache,
        spf_domain: &dns::Name,
        spf_txt: &str,
    ) -> Explanation {
        let Some(explain_domain) =
            spf_txt.split(' ').find_map(|r| match s::Term::parse(r) {
                Ok(s::Term::Modifier(s::Modifier::Explanation(s))) => Some(s),
                _ => None,
            })
        else {
            return Explanation::None;
        };

        let Ok(explain_domain) = self.expand_macro_string(
            ctx,
            dns_cache,
            spf_domain,
            true,
            explain_domain,
        ) else {
            return Explanation::None;
        };

        let Ok(explain_domain) = dns_cache.intern_domain(explain_domain) else {
            return Explanation::None;
        };

        let txt_records =
            match dns::look_up(&mut dns_cache.txt, &explain_domain) {
                Ok(r) => r,
                Err(dns::CacheError::NotFound | dns::CacheError::Error) => {
                    return Explanation::None
                },
                Err(dns::CacheError::NotReady) => return Explanation::NotReady,
            };

        let Some(txt_record) = txt_records.first() else {
            return Explanation::None;
        };

        let txt_record = Rc::clone(txt_record);

        // We don't need to consider the possibility of NotReady here, as that
        // can only come from %{p}, but %{p} is always ready if we have a
        // conclusive result.
        let Ok(explanation) = self.expand_macro_string(
            ctx,
            dns_cache,
            spf_domain,
            true,
            s::MacroString::new(&txt_record),
        ) else {
            return Explanation::None;
        };

        Explanation::Some(explanation.into_owned())
    }

    fn expand_macro_string<'s>(
        &self,
        ctx: &'s Context<'s>,
        dns_cache: &mut dns::Cache,
        spf_domain: &dns::Name,
        in_exp: bool,
        ms: s::MacroString<'s>,
    ) -> Result<Cow<'s, str>, DirectiveError> {
        let mut ret = Cow::Borrowed("");
        for e in ms {
            let expansion = match e {
                Ok(s::MacroElement::Literal(s)) => Cow::Borrowed(s),

                Ok(s::MacroElement::Expand(me)) => {
                    if !in_exp && me.kind.is_exp_only() {
                        return Err(DirectiveError::PermFail);
                    }

                    let expansion = self.basic_macro_expansion(
                        ctx, dns_cache, spf_domain, me.kind,
                    )?;
                    let effective_delimiters = if me.delimiters.is_empty() {
                        "."
                    } else {
                        me.delimiters
                    };
                    let is_delimiter =
                        |c: char| effective_delimiters.chars().any(|d| d == c);
                    let keep_parts = me.keep_parts.unwrap_or(usize::MAX);

                    // Per RFC 7208 § 7.3, splitting is done naïvely, with no
                    // special handling for adjacent delimiters or delimiters
                    // at the start/end of the string.
                    if me.reverse {
                        let it = expansion.rsplit(is_delimiter);
                        let parts = it.clone().count();
                        Cow::Owned(
                            it.skip(parts.saturating_sub(keep_parts)).join("."),
                        )
                    } else if me.keep_parts.is_some()
                        || !me.delimiters.is_empty()
                    {
                        let it = expansion.split(is_delimiter);
                        let parts = it.clone().count();
                        Cow::Owned(
                            it.skip(parts.saturating_sub(keep_parts)).join("."),
                        )
                    } else {
                        expansion
                    }
                },

                Err(e) => return Err(DirectiveError::SyntaxError(e)),
            };

            if ret.is_empty() {
                ret = expansion;
            } else {
                ret.to_mut().push_str(&expansion);
            }
        }

        Ok(ret)
    }

    fn basic_macro_expansion<'s>(
        &self,
        ctx: &'s Context<'s>,
        dns_cache: &mut dns::Cache,
        spf_domain: &dns::Name,
        kind: s::Macro,
    ) -> Result<Cow<'s, str>, DirectiveError> {
        // RFC 7208 § 7.2, 7.3

        use super::syntax::Macro as M;

        let expansion = match kind {
            M::Sender => match ctx.sender {
                None => Cow::Owned(format!("postmaster@{}", ctx.sender_domain)),
                Some(ref s) => Cow::Borrowed(&**s),
            },

            M::SenderLocalPart => match ctx.sender_local {
                None => Cow::Borrowed("postmaster"),
                Some(ref s) => Cow::Borrowed(&**s),
            },

            M::SenderDomain => Cow::Borrowed(&*ctx.sender_domain),
            M::Domain => Cow::Owned(spf_domain.to_ascii()),

            M::Ip => match ctx.ip {
                IpAddr::V4(ip) => Cow::Owned(ip.to_string()),
                IpAddr::V6(ip) => {
                    // The obsolete dotted-hex format is required. RFC 7208 §
                    // 7.4 shows an example where it is, indeed, 32 hexadecimal
                    // nybbles.
                    let octets = ip.octets();
                    let mut s = String::with_capacity(63);
                    for (i, octet) in octets.into_iter().enumerate() {
                        let octet = u32::from(octet);
                        if 0 != i {
                            s.push('.');
                        }
                        s.push(char::from_digit(octet >> 4, 16).unwrap());
                        s.push('.');
                        s.push(char::from_digit(octet & 0xF, 16).unwrap());
                    }
                    Cow::Owned(s)
                },
            },

            M::Ptr => {
                let validated_name = if self.has_ptr {
                    find_validated_name(dns_cache, ctx, spf_domain)?
                } else {
                    None
                };

                match validated_name {
                    None => Cow::Borrowed("unknown"),
                    Some(name) => Cow::Owned(name.to_ascii()),
                }
            },

            M::IpVersion => match ctx.ip {
                IpAddr::V4(_) => Cow::Borrowed("in-addr"),
                IpAddr::V6(_) => Cow::Borrowed("ip6"),
            },

            M::HeloDomain => Cow::Borrowed(&*ctx.helo_domain),
            M::SmtpClientIp => Cow::Owned(ctx.ip.to_string()),
            M::ReceivingHost => Cow::Borrowed(&*ctx.receiver_host),
            M::CurrentTimestamp => Cow::Owned(ctx.now.timestamp().to_string()),
        };

        Ok(expansion)
    }
}

/// Identifies the "validated name" for the given context.
///
/// This is the process described in RFC 7208 § 5.5
fn find_validated_name<'d>(
    dns_cache: &'d mut dns::Cache,
    ctx: &Context<'_>,
    target_domain: &dns::Name,
) -> Result<Option<&'d Rc<dns::Name>>, DirectiveError> {
    let ptr = match dns::ptr(&mut dns_cache.ptr, ctx.ip) {
        Ok(ptr) => ptr,
        Err(dns::CacheError::NotFound) => return Ok(None),
        // > If a DNS error occurs while doing the PTR RR lookup, then [ptr]
        // > fails to match.
        Err(dns::CacheError::Error) => return Ok(None),
        Err(dns::CacheError::NotReady) => return Err(DirectiveError::NotReady),
    };

    // Prefer an exact match on the sender domain, then look at subdomains. If
    // we exceed the limit, just ignore the rest.
    let candidates = ptr
        .iter()
        .find(|n| *target_domain == ***n)
        .into_iter()
        .chain(
            ptr.iter()
                .filter(|n| *target_domain != ***n && target_domain.zone_of(n)),
        )
        .take(MAX_PTR_SIZE);

    for candidate in candidates {
        let matches = match ctx.ip {
            IpAddr::V4(ip) => dns::look_up(&mut dns_cache.a, candidate)
                .map(|records| records.contains(&ip)),

            IpAddr::V6(ip) => dns::look_up(&mut dns_cache.aaaa, candidate)
                .map(|records| records.contains(&ip)),
        };

        match matches {
            Ok(false) => {},
            Ok(true) => return Ok(Some(candidate)),
            // > If a DNS error occurs while doing an A RR lookup, then that
            // > domain name is skipped and the search continues.
            Err(dns::CacheError::NotFound | dns::CacheError::Error) => {},
            Err(dns::CacheError::NotReady) => {
                // In order to be fully deterministic, we stop looking at
                // entries once we find one still in flight. This does make
                // this part of the process effectively sequential, but that's
                // probably preferable for the sake of DNS load anyway.
                return Err(DirectiveError::NotReady);
            },
        }
    }

    Ok(None)
}

/// Performs the error mapping used for top-level DNS queries.
///
/// Defined by RFC 7208 § 5
fn top_level_error_map<T>(
    r: Result<T, dns::CacheError>,
) -> Result<Option<T>, DirectiveError> {
    match r {
        Ok(t) => Ok(Some(t)),
        Err(dns::CacheError::NotReady) => Err(DirectiveError::NotReady),
        Err(dns::CacheError::Error) => Err(DirectiveError::TempFail),
        Err(dns::CacheError::NotFound) => Ok(None),
    }
}

fn ipv4_addr_matches(a: Ipv4Addr, b: Ipv4Addr, cidr_len: Option<u32>) -> bool {
    if let Some(mask) = cidr_len.and_then(|l| u32::MAX.checked_shl(l)) {
        let a = u32::from_be_bytes(a.octets());
        let b = u32::from_be_bytes(b.octets());
        (a & mask) == (b & mask)
    } else {
        a == b
    }
}

fn ipv6_addr_matches(a: Ipv6Addr, b: Ipv6Addr, cidr_len: Option<u32>) -> bool {
    if let Some(mask) = cidr_len.and_then(|l| u128::MAX.checked_shl(l)) {
        let a = u128::from_be_bytes(a.octets());
        let b = u128::from_be_bytes(b.octets());
        (a & mask) == (b & mask)
    } else {
        a == b
    }
}

#[cfg(test)]
mod test {
    use std::cell::RefCell;

    use super::*;

    fn example_context() -> Context<'static> {
        Context {
            sender: Some(Cow::Borrowed("strong-bad@email.example.com")),
            sender_local: Some(Cow::Borrowed("strong-bad")),
            sender_domain: Cow::Borrowed("email.example.com"),
            sender_domain_parsed: rdn("email.example.com"),
            helo_domain: Cow::Borrowed("email.example.com"),
            ip: Ipv4Addr::new(192, 0, 2, 3).into(),
            receiver_host: Cow::Borrowed("unused"),
            now: Utc::now(),
        }
    }

    fn dn(s: &str) -> dns::Name {
        dns::Name::from_ascii(s).unwrap()
    }

    fn rdn(s: &str) -> Rc<dns::Name> {
        Rc::new(dn(s))
    }

    fn put_dns<T>(cache: &mut dns::CacheMap<T>, k: &str, v: dns::Entry<T>) {
        let k = rdn(k);
        if let Some(existing) = cache.iter_mut().find(|e| k == e.0) {
            existing.1 = v;
        } else {
            cache.push((k, v));
        }
    }

    #[test]
    fn test_find_validated_name() {
        let ctx = example_context();
        let mut dns_cache = dns::Cache::default();

        assert_matches!(
            Err(DirectiveError::NotReady),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );
        dns_cache.ptr.insert(ctx.ip, dns::Entry::NotFound);
        assert_matches!(
            Ok(None),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );
        dns_cache.ptr.insert(ctx.ip, dns::Entry::Error);
        assert_matches!(
            Ok(None),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );

        dns_cache.ptr.insert(
            ctx.ip,
            dns::Entry::Ok(vec![
                rdn("unrelated.site"),
                rdn("sub.email.example.com"),
                rdn("email.example.com"),
            ]),
        );
        assert_matches!(
            Err(DirectiveError::NotReady),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );

        // The subdomain resolving first doesn't make it ready, because we need
        // to validate the main domain first.
        put_dns(
            &mut dns_cache.a,
            "sub.email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 0, 2, 3)]),
        );
        assert_matches!(
            Err(DirectiveError::NotReady),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );

        // Failure => fall through
        put_dns(&mut dns_cache.a, "email.example.com", dns::Entry::NotFound);
        assert_eq!(
            Some(&rdn("sub.email.example.com")),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            )
            .unwrap(),
        );
        put_dns(&mut dns_cache.a, "email.example.com", dns::Entry::Error);
        assert_eq!(
            Some(&rdn("sub.email.example.com")),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            )
            .unwrap(),
        );
        // IP address mismatch => fall through
        put_dns(
            &mut dns_cache.a,
            "email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 1, 1, 1)]),
        );
        assert_eq!(
            Some(&rdn("sub.email.example.com")),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            )
            .unwrap(),
        );
        // We prefer the main site over the subdomain
        put_dns(
            &mut dns_cache.a,
            "email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 0, 2, 3)]),
        );
        assert_eq!(
            Some(&rdn("email.example.com")),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            )
            .unwrap(),
        );
        // If nothing matches, we give up rather than consulting the unrelated
        // domain.
        put_dns(
            &mut dns_cache.a,
            "email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 1, 1, 1)]),
        );
        put_dns(
            &mut dns_cache.a,
            "sub.email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 1, 1, 1)]),
        );
        assert_matches!(
            Ok(None),
            find_validated_name(
                &mut dns_cache,
                &ctx,
                &ctx.sender_domain_parsed
            ),
        );
    }

    #[test]
    fn macro_expand_rfc7208_74_examples() {
        let ctx = RefCell::new(example_context());
        let eval = EvaluatorState::default();
        let mut dns_cache = dns::Cache::default();

        let mut expand = |ms: &str| {
            eval.expand_macro_string(
                &ctx.borrow(),
                &mut dns_cache,
                &rdn("email.example.com"),
                false,
                s::MacroString::new(ms),
            )
            .unwrap()
            .into_owned()
        };

        assert_eq!("strong-bad@email.example.com", expand("%{s}"));
        assert_eq!("email.example.com", expand("%{o}"));
        assert_eq!("email.example.com", expand("%{d}"));
        assert_eq!("email.example.com", expand("%{d4}"));
        assert_eq!("email.example.com", expand("%{d3}"));
        assert_eq!("example.com", expand("%{d2}"));
        assert_eq!("com", expand("%{d1}"));
        assert_eq!("com.example.email", expand("%{dr}"));
        assert_eq!("example.email", expand("%{d2r}"));
        assert_eq!("strong-bad", expand("%{l}"));
        assert_eq!("strong.bad", expand("%{l-}"));
        assert_eq!("strong-bad", expand("%{lr}"));
        assert_eq!("bad.strong", expand("%{lr-}"));
        assert_eq!("strong", expand("%{l1r-}"));

        assert_eq!(
            "3.2.0.192.in-addr._spf.example.com",
            expand("%{ir}.%{v}._spf.%{d2}"),
        );
        assert_eq!(
            "bad.strong.lp._spf.example.com",
            expand("%{lr-}.lp._spf.%{d2}"),
        );
        assert_eq!(
            "bad.strong.lp.3.2.0.192.in-addr._spf.example.com",
            expand("%{lr-}.lp.%{ir}.%{v}._spf.%{d2}"),
        );
        assert_eq!(
            "3.2.0.192.in-addr.strong.lp._spf.example.com",
            expand("%{ir}.%{v}.%{l1r-}.lp._spf.%{d2}"),
        );
        assert_eq!(
            "example.com.trusted-domains.example.net",
            expand("%{d2}.trusted-domains.example.net"),
        );

        ctx.borrow_mut().ip = "2001:db8::cb01".parse().unwrap();
        assert_eq!(
            // A truly spectacular DNS name
            "1.0.b.c.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6._spf.example.com",
            expand("%{ir}.%{v}._spf.%{d2}"),
        );
    }

    #[test]
    fn macro_expand_p() {
        let ms = s::MacroString::new("%{p}");
        let ctx = example_context();
        let mut eval = EvaluatorState::default();
        let mut dns_cache = dns::Cache::default();

        // With having seen a `ptr` directive, we don't even try.
        assert_eq!(
            Ok(Cow::Borrowed("unknown")),
            eval.expand_macro_string(
                &ctx,
                &mut dns_cache,
                &dn("email.example.com"),
                false,
                ms
            ),
        );

        // With `ptr`, we try to do the lookup.
        eval.has_ptr = true;
        assert_eq!(
            Err(DirectiveError::NotReady),
            eval.expand_macro_string(
                &ctx,
                &mut dns_cache,
                &dn("email.example.com"),
                false,
                ms
            ),
        );
        // Failure => unknown
        dns_cache.ptr.insert(ctx.ip, dns::Entry::NotFound);
        assert_eq!(
            Ok(Cow::Borrowed("unknown")),
            eval.expand_macro_string(
                &ctx,
                &mut dns_cache,
                &dn("email.example.com"),
                false,
                ms
            ),
        );
        // Success => expansion
        dns_cache
            .ptr
            .insert(ctx.ip, dns::Entry::Ok(vec![rdn("sub.email.example.com")]));
        put_dns(
            &mut dns_cache.a,
            "sub.email.example.com",
            dns::Entry::Ok(vec![Ipv4Addr::new(192, 0, 2, 3)]),
        );
        assert_eq!(
            Ok(Cow::Borrowed("sub.email.example.com")),
            eval.expand_macro_string(
                &ctx,
                &mut dns_cache,
                &dn("email.example.com"),
                false,
                ms
            ),
        );
        // %{p} uses the SPF domain and not the sender domain, so if we use
        // something else, it fails.
        assert_eq!(
            Ok(Cow::Borrowed("unknown")),
            eval.expand_macro_string(
                &ctx,
                &mut dns_cache,
                &dn("example.net"),
                false,
                ms
            ),
        );
    }

    #[test]
    fn macro_expand_all_simple() {
        let ctx = RefCell::new(Context {
            sender: Some(Cow::Borrowed("john@example.com")),
            sender_local: Some(Cow::Borrowed("john")),
            sender_domain: Cow::Borrowed("example.com"),
            sender_domain_parsed: rdn("example.com"),
            helo_domain: Cow::Borrowed("helo.example.com"),
            ip: "dead::beef".parse().unwrap(),
            receiver_host: Cow::Borrowed("receiver.example.net"),
            now: DateTime::from_timestamp(42, 0).unwrap(),
        });
        let mut dns_cache = dns::Cache::default();
        let eval = EvaluatorState::default();

        let mut expand = |ms: &str| {
            eval.expand_macro_string(
                &ctx.borrow(),
                &mut dns_cache,
                &dn("domain.example.org"),
                true,
                s::MacroString::new(ms),
            )
            .unwrap()
            .into_owned()
        };

        assert_eq!("john@example.com", expand("%{s}"));
        assert_eq!("john", expand("%{l}"));
        assert_eq!("example.com", expand("%{o}"));
        assert_eq!("domain.example.org", expand("%{d}"));
        assert_eq!(
            "d.e.a.d.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.b.e.e.f",
            expand("%{i}"),
        );
        assert_eq!("ip6", expand("%{v}"));
        assert_eq!("helo.example.com", expand("%{h}"));
        assert_eq!("dead::beef", expand("%{c}"));
        assert_eq!("receiver.example.net", expand("%{r}"));
        assert_eq!("42", expand("%{t}"));

        ctx.borrow_mut().sender = None;
        ctx.borrow_mut().sender_local = None;

        assert_eq!("postmaster@example.com", expand("%{s}"));
        assert_eq!("postmaster", expand("%{l}"));
    }

    fn parse_a_addrs(addrs: &[&str]) -> Vec<Ipv4Addr> {
        addrs
            .iter()
            .map(|a| a.parse::<Ipv4Addr>().unwrap())
            .collect()
    }

    fn parse_aaaa_addrs(addrs: &[&str]) -> Vec<Ipv6Addr> {
        addrs
            .iter()
            .map(|a| a.parse::<Ipv6Addr>().unwrap())
            .collect()
    }

    fn parse_names(names: &[&str]) -> Vec<Rc<dns::Name>> {
        names.iter().map(|s| rdn(s)).collect()
    }

    fn make_txts(txts: &[&str]) -> Vec<Rc<str>> {
        txts.iter().map(|s| Rc::from(s.to_owned())).collect()
    }

    macro_rules! dns_cache {
        ($($domain:expr => {
            $($field:ident : $value:tt,)*
        },)*) => {{
            let mut dns_cache = dns::Cache::default();
            $(
                let domain = rdn($domain);
                $(
                    dns_cache!(@$field, dns_cache, domain, $value);
                )*
            )*
            dns_cache
        }};

        (@a, $dns_cache:ident, $domain:ident, NotFound) => {
            $dns_cache.a.push((Rc::clone(&$domain), dns::Entry::NotFound));
        };
        (@a, $dns_cache:ident, $domain:ident, Error) => {
            $dns_cache.a.push((Rc::clone(&$domain), dns::Entry::Error));
        };
        (@a, $dns_cache:ident, $domain:ident, $addrs:expr) => {
            $dns_cache.a.push((Rc::clone(&$domain), dns::Entry::Ok(
                parse_a_addrs(&$addrs),
            )));
        };

        (@aaaa, $dns_cache:ident, $domain:ident, NotFound) => {
            $dns_cache.aaaa.push((Rc::clone(&$domain), dns::Entry::NotFound));
        };
        (@aaaa, $dns_cache:ident, $domain:ident, Error) => {
            $dns_cache.aaaa.push((Rc::clone(&$domain), dns::Entry::Error));
        };
        (@aaaa, $dns_cache:ident, $domain:ident, $addrs:expr) => {
            $dns_cache.aaaa.push((Rc::clone(&$domain), dns::Entry::Ok(
                parse_aaaa_addrs(&$addrs),
            )));
        };

        (@mx, $dns_cache:ident, $domain:ident, NotFound) => {
            $dns_cache.mx.push((Rc::clone(&$domain), dns::Entry::NotFound));
        };
        (@mx, $dns_cache:ident, $domain:ident, Error) => {
            $dns_cache.mx.push((Rc::clone(&$domain), dns::Entry::Error));
        };
        (@mx, $dns_cache:ident, $domain:ident, $addrs:expr) => {
            $dns_cache.mx.push((Rc::clone(&$domain), dns::Entry::Ok(
                parse_names(&$addrs).into_iter()
                    .map(|name| (name, 0u16))
                    .collect(),
            )));
        };

        (@txt, $dns_cache:ident, $domain:ident, NotFound) => {
            $dns_cache.txt.push((Rc::clone(&$domain), dns::Entry::NotFound));
        };
        (@txt, $dns_cache:ident, $domain:ident, Error) => {
            $dns_cache.txt.push((Rc::clone(&$domain), dns::Entry::Error));
        };
        (@txt, $dns_cache:ident, $domain:ident, $txts:expr) => {
            $dns_cache.txt.push((Rc::clone(&$domain), dns::Entry::Ok(
                make_txts(&$txts),
            )));
        };
    }

    fn simple_context(sender_domain: &str, ip: &str) -> Context<'static> {
        Context {
            sender: None,
            sender_local: None,
            sender_domain: Cow::Owned(sender_domain.to_owned()),
            sender_domain_parsed: Rc::new(
                dns::Name::from_ascii(sender_domain).unwrap(),
            ),
            helo_domain: Cow::Owned(sender_domain.to_owned()),
            ip: ip.parse().unwrap(),
            receiver_host: Cow::Borrowed("unused"),
            now: DateTime::from_timestamp(0, 0).unwrap(),
        }
    }

    #[test]
    fn eval_no_spf() {
        assert_eq!(
            None,
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns::Cache::default(),
            ),
        );
        assert_eq!(
            Some((SpfResult::None, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: NotFound,
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::None, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: [],
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::None, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["not-an-spf-record"],
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: Error,
                    },
                },
            ),
        );

        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["v=spf1 all"],
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::Neutral, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["v=spf1 ?all"],
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::SoftFail, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["v=spf1 ~all"],
                    },
                },
            ),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["v=spf1 -all"],
                    },
                },
            ),
        );
    }

    #[test]
    fn eval_empty() {
        assert_eq!(
            Some((SpfResult::Neutral, Explanation::None)),
            eval(
                &simple_context("s.com", "1.2.3.4"),
                &mut dns_cache! {
                    "s.com" => {
                        txt: ["v=spf1"],
                    },
                },
            ),
        );
    }

    #[test]
    fn eval_ip_matchers() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ip4:1.2.3.4 ip4:2.0.0.0/16 \
                       ip6:dead::beef ip6:cafe:1::/32 -all"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.5"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "3.2.3.4"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "2.0.255.2"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "2.1.0.2"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "dead::f00d"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "cafe:1::beef"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "cafe:2::beef"), &mut dns_cache),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "beef:2::beef"), &mut dns_cache),
        );
    }

    #[test]
    fn eval_a_matchers() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 a a:t.com/24/16 ~a/24/16 -all"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 a a:t.com/24/16 ~a/24/16 -all"],
                a: NotFound,
                aaaa: Error,
            },
            "t.com" => {
                a: NotFound,
                aaaa: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 a a:t.com/24/16 ~a/24/16 -all"],
                a: ["1.2.3.4", "2.3.4.5"],
                aaaa: ["dead::beef"],
            },
            "t.com" => {
                a: ["4.5.6.7"],
                aaaa: ["cafe::f00d", "f00d::cafe"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "4.5.6.255"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::SoftFail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.255"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "99.88.77.66"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "cafe::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "f00d::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::SoftFail, Explanation::None)),
            eval(&simple_context("s.com", "dead::cafe"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "baad::cafe"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_mx_matchers() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com", "bar.s.com"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com"],
            },
            "foo.s.com" => {
                a: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com"],
            },
            "foo.s.com" => {
                a: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com", "bar.s.com"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com", "bar.s.com"],
            },
            "foo.s.com" => {
                a: ["1.2.3.4"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            None,
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com", "bar.s.com"],
            },
            "bar.s.com" => {
                a: ["1.2.3.4"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            None,
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: ["foo.s.com", "bar.s.com"],
            },
            "bar.s.com" => {
                a: ["1.2.3.4"],
            },
            "foo.s.com" => {
                a: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx mx:t.com/24/16 ~mx/24/16 -all"],
                mx: ["mail.s.com"],
            },
            "mail.s.com" => {
                a: ["1.2.3.4", "2.3.4.5"],
                aaaa: ["dead::beef"],
            },
            "t.com" => {
                mx: ["mx.t.com"],
            },
            "mx.t.com" => {
                a: ["4.5.6.7"],
                aaaa: ["cafe::f00d", "f00d::cafe"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "4.5.6.255"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::SoftFail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.255"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "99.88.77.66"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "cafe::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "f00d::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::SoftFail, Explanation::None)),
            eval(&simple_context("s.com", "dead::cafe"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "baad::cafe"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 mx -all"],
                mx: [
                    "mx1.s.com",
                    "mx2.s.com",
                    "mx3.s.com",
                    "mx4.s.com",
                    "mx5.s.com",
                    "mx6.s.com",
                    "mx7.s.com",
                    "mx8.s.com",
                    "mx9.s.com",
                    "mx10.s.com",
                    "mx11.s.com",
                ],
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_ptr() {
        // The tests for ptr resolution are separate, so this just verifies
        // that the mechanism itself does the right thing.
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ptr -all"],
                a: ["1.2.3.4"],
                aaaa: ["dead::beef"],
            },
        };
        dns_cache.ptr.insert(
            "1.2.3.4".parse::<IpAddr>().unwrap(),
            dns::Entry::Ok(vec![rdn("s.com")]),
        );
        dns_cache.ptr.insert(
            "dead::beef".parse::<IpAddr>().unwrap(),
            dns::Entry::Ok(vec![rdn("s.com")]),
        );

        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );

        assert_eq!(
            None,
            eval(&simple_context("s.com", "5.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            None,
            eval(&simple_context("s.com", "baad::beef"), &mut dns_cache,),
        );

        dns_cache.ptr.insert(
            "5.2.3.4".parse::<IpAddr>().unwrap(),
            dns::Entry::Ok(vec![rdn("other.com")]),
        );
        dns_cache.ptr.insert(
            "baad::beef".parse::<IpAddr>().unwrap(),
            dns::Entry::NotFound,
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "5.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "baad::beef"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_exists() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exists:%{i4r}.spf.s.com -all"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            None,
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exists:%{i4r}.spf.s.com -all"],
            },
            "4.3.2.1.spf.s.com" => {
                a: ["1.1.1.1"],
            },
            "5.4.3.2.spf.s.com" => {
                a: NotFound,
                aaaa: ["dead::beef"], // never used
            },
            "d.a.e.d.spf.s.com" => {
                a: ["1.1.1.1"],
            },
            "d.a.a.b.spf.s.com" => {
                a: Error,
                aaaa: ["dead::beef"], // never used
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "dead::beef"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "baad::f00d"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_include() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: ["v=spf1 invalid-syntax"],
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: ["v=spf1 a"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: ["v=spf1 a"],
                a: ["1.2.3.4"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com -all"],
            },
            "t.com" => {
                txt: ["v=spf1 a"],
                a: ["5.2.3.4"],
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:t.com ?a -all"],
                a: ["1.2.3.4"],
            },
            "t.com" => {
                txt: ["v=spf1 -all"],
            },
        };
        assert_eq!(
            Some((SpfResult::Neutral, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 include:s.com"],
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_redirect() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 redirect=next.s.com -all"],
            },
        };
        // -all is evaluated before the redirect
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ip4:4.4.4.4 redirect=next.s.com"],
            },
        };
        assert_eq!(
            None,
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ip4:4.4.4.4 redirect=next.s.com"],
            },
            "next.s.com" => {
                txt: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::TempError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ip4:4.4.4.4 redirect=next.s.com"],
            },
            "next.s.com" => {
                txt: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 ip4:4.4.4.4 redirect=next.s.com"],
            },
            "next.s.com" => {
                txt: ["v=spf1 a -all"],
                a: ["1.2.3.4"],
            },
        };
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "5.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 redirect=s.com"],
            },
        };
        assert_eq!(
            Some((SpfResult::PermError, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
    }

    #[test]
    fn eval_exp() {
        let mut dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exp=exp.s.com -all"],
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::NotReady)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exp=exp.s.com -all"],
            },
            "exp.s.com" => {
                txt: Error,
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exp=exp.s.com -all"],
            },
            "exp.s.com" => {
                txt: NotFound,
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exp=exp.s.com -all"],
            },
            "exp.s.com" => {
                txt: ["Nobody sends mail from %{d}!"],
            },
        };
        assert_eq!(
            Some((
                SpfResult::Fail,
                Explanation::Some("Nobody sends mail from s.com!".to_owned())
            )),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 exp=exp.s.com -all"],
            },
            "exp.s.com" => {
                txt: ["Nobody sends mail from %{d"],
            },
        };
        assert_eq!(
            Some((SpfResult::Fail, Explanation::None)),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );

        dns_cache = dns_cache! {
            "s.com" => {
                txt: ["v=spf1 -ip4:1.2.3.4 exp=exp.s.com redirect=t.com"],
            },
            "exp.s.com" => {
                txt: ["1.2.3.4 is banned"],
            },
            "t.com" => {
                txt: ["v=spf1 ip4:2.3.4.5 -all exp=exp.t.com"],
            },
            "exp.t.com" => {
                txt: ["only 2.3.4.5 is allowed"],
            },
        };
        assert_eq!(
            Some((
                SpfResult::Fail,
                Explanation::Some("1.2.3.4 is banned".to_owned(),)
            )),
            eval(&simple_context("s.com", "1.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((
                SpfResult::Fail,
                Explanation::Some("only 2.3.4.5 is allowed".to_owned(),)
            )),
            eval(&simple_context("s.com", "99.2.3.4"), &mut dns_cache,),
        );
        assert_eq!(
            Some((SpfResult::Pass, Explanation::None)),
            eval(&simple_context("s.com", "2.3.4.5"), &mut dns_cache,),
        );
    }
}