sieve-rs 1.0.1

Sieve filter interpreter for Rust
Documentation
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use crate::{
    bytecode::{
        Corrupt, Decoded, FORMAT_VERSION, HEADER_LEN, REC_LEN, Sections,
        header_id::{HEADER_OTHER, header_from_id},
        rec::{Range, Rec, Str},
        verify::verify,
    },
    runtime::tests::glob::GlobView,
};
use mail_parser::HeaderName;
use std::{
    borrow::Cow,
    cell::UnsafeCell,
    fmt::{Debug, Display, Formatter},
    sync::OnceLock,
};

pub struct Sieve<'a> {
    code: Cow<'a, [u8]>,
    records: Cow<'a, [u8]>,
    blob: Cow<'a, str>,
    header_names_raw: Cow<'a, [u8]>,
    globs: Cow<'a, [u8]>,
    header_names: Box<[HeaderName<'static>]>,
    regexes: Box<[OnceLock<Option<fancy_regex::Regex>>]>,
    num_vars: u16,
    num_match_vars: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoadError {
    Truncated,
    UnsupportedVersion(u16),
    Corrupted,
}

impl From<Corrupt> for LoadError {
    fn from(_: Corrupt) -> Self {
        LoadError::Corrupted
    }
}

impl Display for LoadError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            LoadError::Truncated => f.write_str("Truncated Sieve script"),
            LoadError::UnsupportedVersion(version) => write!(
                f,
                "Sieve script was compiled with format version {version}, expected {FORMAT_VERSION}"
            ),
            LoadError::Corrupted => f.write_str("Corrupted Sieve script"),
        }
    }
}

impl std::error::Error for LoadError {}

pub(crate) struct RecIter<'s> {
    bytes: &'s [u8],
    pub(crate) index: u32,
}

impl Iterator for RecIter<'_> {
    type Item = Rec;

    #[inline(always)]
    fn next(&mut self) -> Option<Rec> {
        let (chunk, rest) = self.bytes.split_first_chunk::<REC_LEN>()?;
        self.bytes = rest;
        self.index += 1;
        Some(Rec::decode(chunk))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.bytes.len() / REC_LEN;
        (len, Some(len))
    }
}

impl ExactSizeIterator for RecIter<'_> {}

impl<'a> Sieve<'a> {
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Sieve<'a>, LoadError> {
        let sections = Self::sections(bytes)?;
        let blob = std::str::from_utf8(&bytes[sections.blob.0..sections.blob.1])
            .map_err(|_| LoadError::Corrupted)?;
        let sieve = Self::build(bytes, sections, Cow::Borrowed(blob))?;
        verify(&sieve)?;
        Ok(sieve)
    }

    #[allow(clippy::missing_safety_doc)]
    pub unsafe fn from_bytes_unchecked(bytes: &'a [u8]) -> Result<Sieve<'a>, LoadError> {
        let sections = Self::sections(bytes)?;
        let blob =
            unsafe { std::str::from_utf8_unchecked(&bytes[sections.blob.0..sections.blob.1]) };
        Self::build(bytes, sections, Cow::Borrowed(blob))
    }

    fn sections(bytes: &[u8]) -> Result<Sections, LoadError> {
        Sections::parse(bytes)
    }

    fn build(
        bytes: &'a [u8],
        sections: Sections,
        blob: Cow<'a, str>,
    ) -> Result<Sieve<'a>, LoadError> {
        let header_names_raw = &bytes[sections.header_names.0..sections.header_names.1];
        let header_names = parse_header_names(header_names_raw, &blob)?;
        Ok(Sieve {
            code: Cow::Borrowed(&bytes[sections.code.0..sections.code.1]),
            records: Cow::Borrowed(&bytes[sections.records.0..sections.records.1]),
            blob,
            header_names_raw: Cow::Borrowed(header_names_raw),
            globs: Cow::Borrowed(&bytes[sections.globs.0..sections.globs.1]),
            header_names,
            regexes: new_regex_cache(sections.num_regexes),
            num_vars: sections.num_vars,
            num_match_vars: sections.num_match_vars,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn from_parts(
        code: Vec<u8>,
        records: Vec<u8>,
        blob: String,
        header_names_raw: Vec<u8>,
        globs: Vec<u8>,
        num_regexes: u32,
        num_vars: u16,
        num_match_vars: u16,
    ) -> Result<Sieve<'static>, LoadError> {
        let header_names = parse_header_names(&header_names_raw, &blob)?;
        Ok(Sieve {
            code: Cow::Owned(code),
            records: Cow::Owned(records),
            blob: Cow::Owned(blob),
            header_names_raw: Cow::Owned(header_names_raw),
            globs: Cow::Owned(globs),
            header_names,
            regexes: new_regex_cache(num_regexes),
            num_vars,
            num_match_vars,
        })
    }

    pub fn into_owned(self) -> Sieve<'static> {
        Sieve {
            code: Cow::Owned(self.code.into_owned()),
            records: Cow::Owned(self.records.into_owned()),
            blob: Cow::Owned(self.blob.into_owned()),
            header_names_raw: Cow::Owned(self.header_names_raw.into_owned()),
            globs: Cow::Owned(self.globs.into_owned()),
            header_names: self.header_names,
            regexes: self.regexes,
            num_vars: self.num_vars,
            num_match_vars: self.num_match_vars,
        }
    }

    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.serialized_len());
        let mut start = HEADER_LEN;
        let mut section = |len: usize| {
            let range = (start, start + len);
            start += len;
            range
        };
        Sections {
            num_vars: self.num_vars,
            num_match_vars: self.num_match_vars,
            code: section(self.code.len()),
            records: section(self.records.len()),
            blob: section(self.blob.len()),
            header_names: section(self.header_names_raw.len()),
            globs: section(self.globs.len()),
            num_regexes: self.regexes.len() as u32,
        }
        .write_header(&mut out);
        out.extend_from_slice(&self.code);
        out.extend_from_slice(&self.records);
        out.extend_from_slice(self.blob.as_bytes());
        out.extend_from_slice(&self.header_names_raw);
        out.extend_from_slice(&self.globs);
        out
    }

    pub fn serialized_len(&self) -> usize {
        HEADER_LEN
            + self.code.len()
            + self.records.len()
            + self.blob.len()
            + self.header_names_raw.len()
            + self.globs.len()
    }

    pub fn code_len(&self) -> usize {
        self.code.len()
    }

    pub fn constant_count(&self) -> usize {
        self.blob.len()
    }

    #[inline(always)]
    pub(crate) fn code(&self) -> &[u8] {
        &self.code
    }

    #[inline(always)]
    pub(crate) fn num_vars(&self) -> usize {
        self.num_vars as usize
    }

    #[inline(always)]
    pub(crate) fn num_match_vars(&self) -> usize {
        self.num_match_vars as usize
    }

    #[inline(always)]
    pub(crate) fn num_records(&self) -> u32 {
        (self.records.len() / REC_LEN) as u32
    }

    #[inline(always)]
    pub(crate) fn num_globs(&self) -> u32 {
        self.globs
            .first_chunk::<4>()
            .map_or(0, |b| u32::from_le_bytes(*b))
    }

    #[inline(always)]
    pub(crate) fn num_regexes(&self) -> u32 {
        self.regexes.len() as u32
    }

    #[inline(always)]
    pub(crate) fn rec(&self, index: u32) -> Decoded<Rec> {
        let start = index as usize * REC_LEN;
        self.records
            .get(start..)
            .and_then(|s| s.first_chunk::<REC_LEN>())
            .map(Rec::decode)
            .ok_or(Corrupt)
    }

    #[inline(always)]
    pub(crate) fn recs(&self, range: Range) -> Decoded<RecIter<'_>> {
        let start = range.start as usize * REC_LEN;
        let len = range.len as usize * REC_LEN;
        self.records
            .get(start..start.checked_add(len).ok_or(Corrupt)?)
            .map(|bytes| RecIter {
                bytes,
                index: range.start,
            })
            .ok_or(Corrupt)
    }

    #[inline(always)]
    pub(crate) fn str(&self, s: Str) -> Decoded<&str> {
        let start = s.off as usize;
        self.blob
            .get(start..start.checked_add(s.len as usize).ok_or(Corrupt)?)
            .ok_or(Corrupt)
    }

    #[inline(always)]
    pub(crate) fn header_name(&self, index: u16) -> Decoded<&HeaderName<'static>> {
        self.header_names.get(index as usize).ok_or(Corrupt)
    }

    pub(crate) fn glob(&self, index: u16) -> Decoded<GlobView<'_>> {
        let count = self.num_globs();
        if index as u32 >= count {
            return Err(Corrupt);
        }
        let at = 4 + index as usize * 4;
        let offset = self
            .globs
            .get(at..at + 4)
            .and_then(|b| b.try_into().ok())
            .map(u32::from_le_bytes)
            .ok_or(Corrupt)? as usize;
        GlobView::parse(self.globs.get(offset..).ok_or(Corrupt)?, self)
    }

    pub(crate) fn regex(&self, slot: u16, pattern: &str) -> Option<&fancy_regex::Regex> {
        self.regexes
            .get(slot as usize)?
            .get_or_init(|| crate::regex::compile(pattern))
            .as_ref()
    }
}

fn new_regex_cache(count: u32) -> Box<[OnceLock<Option<fancy_regex::Regex>>]> {
    (0..count).map(|_| OnceLock::new()).collect()
}

fn parse_header_names(raw: &[u8], blob: &str) -> Result<Box<[HeaderName<'static>]>, LoadError> {
    let Some((count, mut rest)) = raw.split_first_chunk::<4>() else {
        return if raw.is_empty() {
            Ok(Box::default())
        } else {
            Err(LoadError::Corrupted)
        };
    };
    let count = u32::from_le_bytes(*count) as usize;
    if count > rest.len() {
        return Err(LoadError::Corrupted);
    }
    let mut names = Vec::with_capacity(count);
    for _ in 0..count {
        let (&id, tail) = rest.split_first().ok_or(LoadError::Corrupted)?;
        rest = tail;
        if id != HEADER_OTHER {
            names.push(header_from_id(id).ok_or(LoadError::Corrupted)?);
            continue;
        }
        let (entry, tail) = rest.split_first_chunk::<8>().ok_or(LoadError::Corrupted)?;
        rest = tail;
        let off = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]) as usize;
        let len = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]) as usize;
        let name = blob
            .get(off..off.checked_add(len).ok_or(LoadError::Corrupted)?)
            .ok_or(LoadError::Corrupted)?;
        let name = HeaderName::parse(name)
            .map(HeaderName::into_owned)
            .unwrap_or_else(|| HeaderName::Other(Cow::Owned(name.to_string())));
        names.push(name);
    }
    if rest.is_empty() {
        Ok(names.into_boxed_slice())
    } else {
        Err(LoadError::Corrupted)
    }
}

#[derive(Default)]
pub struct ScriptArena {
    #[allow(clippy::vec_box)]
    scripts: UnsafeCell<Vec<Box<Sieve<'static>>>>,
}

impl ScriptArena {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn push(&self, script: Sieve<'static>) -> &Sieve<'static> {
        let boxed = Box::new(script);
        let stable: *const Sieve<'static> = &*boxed;
        unsafe { (*self.scripts.get()).push(boxed) };
        unsafe { &*stable }
    }

    pub fn len(&self) -> usize {
        unsafe { (*self.scripts.get()).len() }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Clone for Sieve<'_> {
    fn clone(&self) -> Self {
        Sieve {
            code: self.code.clone(),
            records: self.records.clone(),
            blob: self.blob.clone(),
            header_names_raw: self.header_names_raw.clone(),
            globs: self.globs.clone(),
            header_names: self.header_names.clone(),
            regexes: self
                .regexes
                .iter()
                .map(|slot| {
                    let cell = OnceLock::new();
                    if let Some(value) = slot.get() {
                        let _ = cell.set(value.clone());
                    }
                    cell
                })
                .collect(),
            num_vars: self.num_vars,
            num_match_vars: self.num_match_vars,
        }
    }
}

impl PartialEq for Sieve<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.code == other.code
            && self.records == other.records
            && self.blob == other.blob
            && self.header_names_raw == other.header_names_raw
            && self.globs == other.globs
            && self.regexes.len() == other.regexes.len()
            && self.num_vars == other.num_vars
            && self.num_match_vars == other.num_match_vars
    }
}

impl Eq for Sieve<'_> {}

impl Debug for Sieve<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sieve")
            .field("code_len", &self.code.len())
            .field("records", &self.num_records())
            .field("blob_len", &self.blob.len())
            .field("header_names", &self.header_names)
            .field("globs", &self.num_globs())
            .field("regexes", &self.regexes.len())
            .field("num_vars", &self.num_vars)
            .field("num_match_vars", &self.num_match_vars)
            .finish()
    }
}