Skip to main content

utopia_emails/
lists.rs

1//! The free and disposable domain lists an address's domain is classified
2//! with.
3//!
4//! PHP: `data/free-domains.php` and `data/disposable-domains.php`.
5//!
6//! The embedded lists are the `data/*.txt` text itself plus, built by
7//! `build.rs`, a hash table of their lines' byte offsets (`table.rs`): a lookup
8//! probes one or two slots, with nothing allocated or built at run time. Both
9//! live in the library's read-only pages, shared by every process.
10
11use std::borrow::Cow;
12use std::sync::OnceLock;
13
14use php_std::value;
15use serde_json::Value;
16
17mod table {
18    include!("table.rs");
19}
20
21include!(concat!(env!("OUT_DIR"), "/tables.rs"));
22
23/// A set of domains, matched as PHP's `in_array($domain, $list)`: a loose
24/// comparison, so numeric strings compare as numbers (`"1e3"` matches an
25/// entry `"1000"`).
26#[derive(Debug)]
27pub struct DomainList {
28    /// The domains, one per line.
29    source: Cow<'static, [u8]>,
30    /// The hash table of `source`'s distinct lines (`table.rs`).
31    table: Cow<'static, [u32]>,
32    /// The number of distinct domains.
33    entries: usize,
34    /// The entries that are numeric strings, which a numeric needle can equal
35    /// without being byte-identical; found on the first numeric needle.
36    numeric: OnceLock<Vec<String>>,
37}
38
39impl Default for DomainList {
40    fn default() -> Self {
41        Self::from_source(Vec::new())
42    }
43}
44
45impl DomainList {
46    /// An embedded list and its build-time table.
47    const fn embedded(source: &'static str, table: &'static [u32], entries: usize) -> Self {
48        Self {
49            source: Cow::Borrowed(source.as_bytes()),
50            table: Cow::Borrowed(table),
51            entries,
52            numeric: OnceLock::new(),
53        }
54    }
55
56    /// A list from text, one domain per line, with its table built now.
57    fn from_source(source: Vec<u8>) -> Self {
58        let (table, entries) = table::build(&source);
59        Self { source: Cow::Owned(source), table: Cow::Owned(table), entries, numeric: OnceLock::new() }
60    }
61
62    /// Whether `domain` is on the list.
63    ///
64    /// PHP: `in_array($domain, $list)`.
65    pub fn contains(&self, domain: &[u8]) -> bool {
66        if table::contains(&self.source, &self.table, domain) {
67            return true;
68        }
69        if value::numeric_bytes_ex(domain).is_none() {
70            return false;
71        }
72        let numeric = self.numeric.get_or_init(|| {
73            self.source
74                .split(|&b| b == b'\n')
75                .filter_map(|entry| std::str::from_utf8(entry).ok())
76                .filter(|entry| value::numeric_str(entry).is_some())
77                .map(str::to_owned)
78                .collect()
79        });
80        if numeric.is_empty() {
81            return false;
82        }
83        // A numeric string is ASCII.
84        let needle = Value::String(String::from_utf8_lossy(domain).into_owned());
85        numeric.iter().any(|entry| value::loose_eq(&needle, &Value::String(entry.clone())))
86    }
87
88    /// The number of entries.
89    pub fn len(&self) -> usize {
90        self.entries
91    }
92
93    /// Whether the list has no entries.
94    pub fn is_empty(&self) -> bool {
95        self.entries == 0
96    }
97}
98
99impl<'a> FromIterator<&'a str> for DomainList {
100    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
101        let mut source = Vec::new();
102        for domain in iter {
103            source.extend_from_slice(domain.as_bytes());
104            source.push(b'\n');
105        }
106        Self::from_source(source)
107    }
108}
109
110/// The free and disposable domain lists.
111#[derive(Debug, Default)]
112pub struct Lists {
113    /// Domains of free mail services (`gmail.com`).
114    pub free: DomainList,
115    /// Domains of disposable, throwaway mail services.
116    pub disposable: DomainList,
117}
118
119static GLOBAL: Lists = Lists::embedded();
120
121impl Lists {
122    /// The free domains the crate embeds: one per line, in the order of
123    /// `data/free-domains.php`, which `data/export.php` writes them from.
124    pub const FREE: &'static str = include_str!("../data/free-domains.txt");
125
126    /// The disposable domains the crate embeds, from
127    /// `data/disposable-domains.php`, in the format of [`Self::FREE`].
128    pub const DISPOSABLE: &'static str = include_str!("../data/disposable-domains.txt");
129
130    /// One list: a domain per line.
131    pub fn parse(source: &str) -> DomainList {
132        DomainList::from_source(source.as_bytes().to_vec())
133    }
134
135    /// The embedded lists, with tables built at compile time: no work and no
136    /// allocation.
137    pub const fn embedded() -> Self {
138        Self {
139            free: DomainList::embedded(Self::FREE, &FREE_TABLE, FREE_ENTRIES),
140            disposable: DomainList::embedded(Self::DISPOSABLE, &DISPOSABLE_TABLE, DISPOSABLE_ENTRIES),
141        }
142    }
143
144    /// The embedded lists, shared by every caller.
145    pub fn global() -> &'static Self {
146        &GLOBAL
147    }
148
149    /// Whether the domain, or else its registrable domain (empty when it has
150    /// none), is disposable.
151    ///
152    /// PHP: `isDisposable()`, given `getRegisterable()` of the domain.
153    pub fn is_disposable(&self, domain: &[u8], registerable: &[u8]) -> bool {
154        self.disposable.contains(domain) || (!registerable.is_empty() && self.disposable.contains(registerable))
155    }
156
157    /// Whether the domain is on the free list. Not PHP's `isFree()`, which is false
158    /// for a domain that is also disposable: that is this and not
159    /// [`Self::is_disposable`].
160    ///
161    /// PHP: `in_array($this->domain, self::$freeDomains)`.
162    pub fn is_on_free_list(&self, domain: &[u8]) -> bool {
163        self.free.contains(domain)
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn parse() {
173        let list = Lists::parse("gmail.com\nit's.com\n1000\n");
174        assert_eq!(list.len(), 3);
175        assert!(list.contains(b"gmail.com") && list.contains(b"it's.com"));
176        assert!(list.contains(b"1e3") && list.contains(b" 1000") && !list.contains(b"1e4"));
177        assert!(!list.contains(b"GMAIL.COM"));
178    }
179
180    #[test]
181    fn embedded_lists_parse_whole() {
182        let lists = Lists::embedded();
183        for (list, source) in [(&lists.free, Lists::FREE), (&lists.disposable, Lists::DISPOSABLE)] {
184            let lines = source.lines().count();
185            assert!(source.ends_with('\n') && !source.lines().any(str::is_empty));
186            assert_eq!(list.len(), lines, "every line is one distinct domain");
187            assert!(lines > 30_000, "the list has {lines} domains");
188        }
189        assert!(lists.is_on_free_list(b"gmail.com") && lists.is_disposable(b"x.mailinator.com", b"mailinator.com"));
190    }
191
192    /// The build-time table finds every line of each embedded list, and only those.
193    #[test]
194    fn embedded_table_finds_every_entry() {
195        let lists = Lists::global();
196        for (list, source) in [(&lists.free, Lists::FREE), (&lists.disposable, Lists::DISPOSABLE)] {
197            for domain in source.lines() {
198                assert!(list.contains(domain.as_bytes()), "{domain} is on its list");
199                assert!(
200                    !list.contains(format!("{domain}x").as_bytes())
201                        || source.lines().any(|l| l == format!("{domain}x"))
202                );
203                assert!(
204                    !list.contains(format!("x{domain}").as_bytes())
205                        || source.lines().any(|l| l == format!("x{domain}"))
206                );
207            }
208            assert!(!list.contains(b"") && !list.contains(b"\n") && !list.contains(b"not-a-listed-domain.invalid"));
209        }
210    }
211
212    /// The build-time table is the one a run-time parse builds.
213    #[test]
214    fn embedded_table_matches_a_parse() {
215        let lists = Lists::global();
216        for (list, source) in [(&lists.free, Lists::FREE), (&lists.disposable, Lists::DISPOSABLE)] {
217            let parsed = Lists::parse(source);
218            assert_eq!(list.table.as_ref(), parsed.table.as_ref());
219            assert_eq!(list.len(), parsed.len());
220        }
221    }
222}