pure_magic/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(unused_imports)]
3//! # `pure-magic`: A Safe Rust Reimplementation of `libmagic`
4//!
5//! This crate provides a high-performance, memory-safe alternative to the traditional
6//! `libmagic` (used by the `file` command). It supports **file type detection**,
7//! **MIME type inference**, and **custom magic rule parsing**.
8//!
9//! ## Installation
10//! Add `pure-magic` to your `Cargo.toml`:
11//!
12//! ```toml
13//! [dependencies]
14//! pure-magic = "0.1"  # Replace with the latest version
15//! ```
16//!
17//! Or add the latest version with cargo:
18//!
19//! ```sh
20//! cargo add pure-magic
21//! ```
22//!
23//! ## Quick Start
24//!
25//! ### Detect File Types Programmatically
26//! ```rust
27//! use pure_magic::{MagicDb, MagicSource};
28//! use std::fs::File;
29//!
30//! fn main() -> Result<(), Box<dyn std::error::Error>> {
31//!     let mut db = MagicDb::new();
32//!     // Create a MagicSource from a file
33//!     let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
34//!     db.load(rust_magic)?;
35//!
36//!     // Open a file and detect its type
37//!     let mut file = File::open("src/lib.rs")?;
38//!     let magic = db.first_magic(&mut file, None)?;
39//!
40//!     println!(
41//!         "File type: {} (MIME: {}, strength: {})",
42//!         magic.message(),
43//!         magic.mime_type(),
44//!         magic.strength()
45//!     );
46//!     Ok(())
47//! }
48//! ```
49//!
50//! ### Get All Matching Rules
51//! ```rust
52//! use pure_magic::{MagicDb, MagicSource};
53//! use std::fs::File;
54//!
55//! fn main() -> Result<(), Box<dyn std::error::Error>> {
56//!     let mut db = MagicDb::new();
57//!     // Create a MagicSource from a file
58//!     let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
59//!     db.load(rust_magic)?;
60//!
61//!     // Open a file and detect its type
62//!     let mut file = File::open("src/lib.rs")?;
63//!
64//!     // Get all matching rules, sorted by strength
65//!     let magics = db.all_magics(&mut file)?;
66//!
67//!     // Must contain rust file magic and default text magic
68//!     assert!(magics.len() > 1);
69//!
70//!     for magic in magics {
71//!         println!(
72//!             "Match: {} (strength: {}, source: {})",
73//!             magic.message(),
74//!             magic.strength(),
75//!             magic.source().unwrap_or("unknown")
76//!         );
77//!     }
78//!     Ok(())
79//! }
80//! ```
81//!
82//! ### Serialize a Database to Disk
83//! ```rust
84//! use pure_magic::{MagicDb, MagicSource};
85//! use std::fs::File;
86//!
87//! fn main() -> Result<(), Box<dyn std::error::Error>> {
88//!     let mut db = MagicDb::new();
89//!     // Create a MagicSource from a file
90//!     let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
91//!     db.load(rust_magic)?;
92//!
93//!     // Serialize the database to a file
94//!     let mut output = File::create("/tmp/compiled.db")?;
95//!     db.serialize(&mut output)?;
96//!
97//!     println!("Database saved to file");
98//!     Ok(())
99//! }
100//! ```
101//!
102//! ### Deserialize a Database
103//! ```rust
104//! use pure_magic::{MagicDb, MagicSource};
105//! use std::fs::File;
106//!
107//! fn main() -> Result<(), Box<dyn std::error::Error>> {
108//!     let mut db = MagicDb::new();
109//!     // Create a MagicSource from a file
110//!     let rust_magic = MagicSource::open("../magic-db/src/magdir/rust")?;
111//!     db.load(rust_magic)?;
112//!
113//!     // Serialize the database in a vector
114//!     let mut ser = vec![];
115//!     db.serialize(&mut ser)?;
116//!     println!("Database saved to vector");
117//!
118//!     // We deserialize from slice
119//!     let db = MagicDb::deserialize(&mut ser.as_slice())?;
120//!
121//!     assert!(!db.rules().is_empty());
122//!
123//!     Ok(())
124//! }
125//! ```
126//!
127//! ## License
128//! This project is licensed under the **GPL-3.0 License**.
129//!
130//! ## Contributing
131//! Contributions are welcome! Open an issue or submit a pull request.
132//!
133//! ## Acknowledgments
134//! - Inspired by the original `libmagic` (part of the `file` command).
135
136use dyf::{DynDisplay, FormatString, dformat};
137use flagset::{FlagSet, flags};
138use flate2::{Compression, read::GzDecoder, write::GzEncoder};
139use lazy_cache::LazyCache;
140use memchr::memchr;
141use pest::{Span, error::ErrorVariant};
142use regex::bytes::{self};
143use serde::{Deserialize, Serialize};
144use std::{
145    borrow::Cow,
146    cmp::max,
147    collections::{HashMap, HashSet},
148    fmt::{self, Debug, Display},
149    io::{self, Read, Seek, SeekFrom, Write},
150    ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Rem, Sub},
151    path::Path,
152};
153use tar::Archive;
154use thiserror::Error;
155use tracing::{Level, debug, enabled, trace};
156
157use crate::{
158    numeric::{Float, FloatDataType, Scalar, ScalarDataType},
159    parser::{FileMagicParser, Rule},
160    utils::{decode_id3, find_json_boundaries},
161};
162
163mod numeric;
164mod parser;
165mod utils;
166
167const HARDCODED_MAGIC_STRENGTH: u64 = 2048;
168const HARDCODED_SOURCE: &str = "hardcoded";
169// corresponds to FILE_INDIR_MAX constant defined in libmagic
170const MAX_RECURSION: usize = 50;
171// constant found in libmagic. It is used to limit for search tests
172pub const FILE_BYTES_MAX: usize = 7 * 1024 * 1024;
173// constant found in libmagic. It is used to limit for regex tests
174const FILE_REGEX_MAX: usize = 8192;
175
176pub const DEFAULT_BIN_MIMETYPE: &str = "application/octet-stream";
177pub const DEFAULT_TEXT_MIMETYPE: &str = "text/plain";
178
179pub(crate) const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
180
181macro_rules! debug_panic {
182    ($($arg:tt)*) => {
183        if cfg!(debug_assertions) {
184            panic!($($arg)*);
185        }
186    };
187}
188
189macro_rules! read {
190    ($r: expr, $ty: ty) => {{
191        let mut a = [0u8; std::mem::size_of::<$ty>()];
192        $r.read_exact(&mut a)?;
193        a
194    }};
195}
196
197macro_rules! read_le {
198    ($r:expr, $ty: ty ) => {{ <$ty>::from_le_bytes(read!($r, $ty)) }};
199}
200
201macro_rules! read_be {
202    ($r:expr, $ty: ty ) => {{ <$ty>::from_be_bytes(read!($r, $ty)) }};
203}
204
205macro_rules! read_me {
206    ($r: expr) => {{ ((read_le!($r, u16) as i32) << 16) | (read_le!($r, u16) as i32) }};
207}
208
209#[inline(always)]
210fn read_octal_u64<R: Read + Seek>(haystack: &mut LazyCache<R>) -> Option<u64> {
211    let s = haystack
212        .read_while_or_limit(|b| matches!(b, b'0'..=b'7'), 22)
213        .map(|buf| str::from_utf8(buf))
214        .ok()?
215        .ok()?;
216
217    if !s.starts_with("0") {
218        return None;
219    }
220
221    u64::from_str_radix(s, 8).ok()
222}
223
224/// Represents all possible errors that can occur during file type detection and processing.
225#[derive(Debug, Error)]
226pub enum Error {
227    /// A generic error with a custom message.
228    #[error("{0}")]
229    Msg(String),
230
231    /// An error with a source location and a nested error.
232    #[error("source={0} line={1} error={2}")]
233    Localized(String, usize, Box<Error>),
234
235    /// Indicates a required rule was not found.
236    #[error("missing rule: {0}")]
237    MissingRule(String),
238
239    /// Indicates the maximum recursion depth was reached.
240    #[error("maximum recursion reached: {0}")]
241    MaximumRecursion(usize),
242
243    /// Wraps an I/O error.
244    #[error("io: {0}")]
245    Io(#[from] io::Error),
246
247    /// Wraps a parsing error from the `pest` parser.
248    #[error("parser error: {0}")]
249    Parse(#[from] Box<pest::error::Error<Rule>>),
250
251    /// Wraps a formatting error from the `dyf` crate.
252    #[error("formatting: {0}")]
253    Format(#[from] dyf::Error),
254
255    /// Wraps a regex-related error.
256    #[error("regex: {0}")]
257    Regex(#[from] regex::Error),
258
259    /// Wraps a serialization error from `bincode`.
260    #[error("{0}")]
261    Serialize(#[from] bincode::error::EncodeError),
262
263    /// Wraps a deserialization error from `bincode`.
264    #[error("{0}")]
265    Deserialize(#[from] bincode::error::DecodeError),
266}
267
268impl Error {
269    #[inline]
270    fn parser<S: ToString>(msg: S, span: Span<'_>) -> Self {
271        Self::Parse(Box::new(pest::error::Error::new_from_span(
272            ErrorVariant::CustomError {
273                message: msg.to_string(),
274            },
275            span,
276        )))
277    }
278
279    fn msg<M: AsRef<str>>(msg: M) -> Self {
280        Self::Msg(msg.as_ref().into())
281    }
282
283    fn localized<S: AsRef<str>>(source: S, line: usize, err: Error) -> Self {
284        Self::Localized(source.as_ref().into(), line, err.into())
285    }
286
287    /// Unwraps the localized error
288    pub fn unwrap_localized(&self) -> &Self {
289        match self {
290            Self::Localized(_, _, e) => e,
291            _ => self,
292        }
293    }
294}
295
296#[derive(Debug, Clone, Serialize, Deserialize)]
297enum Message {
298    String(String),
299    Format {
300        printf_spec: String,
301        fs: FormatString,
302    },
303}
304
305impl Display for Message {
306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307        match self {
308            Self::String(s) => write!(f, "{s}"),
309            Self::Format { printf_spec: _, fs } => write!(f, "{}", fs.to_string_lossy()),
310        }
311    }
312}
313
314impl Message {
315    fn to_string_lossy(&self) -> Cow<'_, str> {
316        match self {
317            Message::String(s) => Cow::Borrowed(s),
318            Message::Format { printf_spec: _, fs } => fs.to_string_lossy(),
319        }
320    }
321
322    #[inline(always)]
323    fn format_with(&self, mr: Option<&MatchRes>) -> Result<Cow<'_, str>, Error> {
324        match self {
325            Self::String(s) => Ok(Cow::Borrowed(s.as_str())),
326            Self::Format {
327                printf_spec: c_spec,
328                fs,
329            } => {
330                if let Some(mr) = mr {
331                    match mr {
332                        MatchRes::Float(_, _) | MatchRes::Bytes(_, _, _, _) => {
333                            Ok(Cow::Owned(dformat!(fs, mr)?))
334                        }
335                        MatchRes::Scalar(_, scalar) => {
336                            // we want to print a byte as char
337                            if c_spec.as_str() == "c" {
338                                match scalar {
339                                    Scalar::byte(b) => {
340                                        let b = (*b as u8) as char;
341                                        Ok(Cow::Owned(dformat!(fs, b)?))
342                                    }
343                                    Scalar::ubyte(b) => {
344                                        let b = *b as char;
345                                        Ok(Cow::Owned(dformat!(fs, b)?))
346                                    }
347                                    _ => Ok(Cow::Owned(dformat!(fs, mr)?)),
348                                }
349                            } else {
350                                Ok(Cow::Owned(dformat!(fs, mr)?))
351                            }
352                        }
353                    }
354                } else {
355                    Ok(fs.to_string_lossy())
356                }
357            }
358        }
359    }
360}
361
362impl ScalarDataType {
363    #[inline(always)]
364    fn read<R: Read + Seek>(&self, from: &mut R, switch_endianness: bool) -> Result<Scalar, Error> {
365        macro_rules! _read_le {
366            ($ty: ty) => {{
367                if switch_endianness {
368                    <$ty>::from_be_bytes(read!(from, $ty))
369                } else {
370                    <$ty>::from_le_bytes(read!(from, $ty))
371                }
372            }};
373        }
374
375        macro_rules! _read_be {
376            ($ty: ty) => {{
377                if switch_endianness {
378                    <$ty>::from_le_bytes(read!(from, $ty))
379                } else {
380                    <$ty>::from_be_bytes(read!(from, $ty))
381                }
382            }};
383        }
384
385        macro_rules! _read_ne {
386            ($ty: ty) => {{
387                if cfg!(target_endian = "big") {
388                    _read_be!($ty)
389                } else {
390                    _read_le!($ty)
391                }
392            }};
393        }
394
395        macro_rules! _read_me {
396            () => {
397                ((_read_le!(u16) as i32) << 16) | (_read_le!(u16) as i32)
398            };
399        }
400
401        Ok(match self {
402            // signed
403            Self::byte => Scalar::byte(read!(from, u8)[0] as i8),
404            Self::short => Scalar::short(_read_ne!(i16)),
405            Self::long => Scalar::long(_read_ne!(i32)),
406            Self::date => Scalar::date(_read_ne!(i32)),
407            Self::ldate => Scalar::ldate(_read_ne!(i32)),
408            Self::qwdate => Scalar::qwdate(_read_ne!(i64)),
409            Self::leshort => Scalar::leshort(_read_le!(i16)),
410            Self::lelong => Scalar::lelong(_read_le!(i32)),
411            Self::lequad => Scalar::lequad(_read_le!(i64)),
412            Self::bequad => Scalar::bequad(_read_be!(i64)),
413            Self::belong => Scalar::belong(_read_be!(i32)),
414            Self::bedate => Scalar::bedate(_read_be!(i32)),
415            Self::beldate => Scalar::beldate(_read_be!(i32)),
416            Self::beqdate => Scalar::beqdate(_read_be!(i64)),
417            // unsigned
418            Self::ubyte => Scalar::ubyte(read!(from, u8)[0]),
419            Self::ushort => Scalar::ushort(_read_ne!(u16)),
420            Self::uleshort => Scalar::uleshort(_read_le!(u16)),
421            Self::ulelong => Scalar::ulelong(_read_le!(u32)),
422            Self::uledate => Scalar::uledate(_read_le!(u32)),
423            Self::ulequad => Scalar::ulequad(_read_le!(u64)),
424            Self::offset => Scalar::offset(from.stream_position()?),
425            Self::ubequad => Scalar::ubequad(_read_be!(u64)),
426            Self::medate => Scalar::medate(_read_me!()),
427            Self::meldate => Scalar::meldate(_read_me!()),
428            Self::melong => Scalar::melong(_read_me!()),
429            Self::beshort => Scalar::beshort(_read_be!(i16)),
430            Self::quad => Scalar::quad(_read_ne!(i64)),
431            Self::uquad => Scalar::uquad(_read_ne!(u64)),
432            Self::ledate => Scalar::ledate(_read_le!(i32)),
433            Self::leldate => Scalar::leldate(_read_le!(i32)),
434            Self::leqdate => Scalar::leqdate(_read_le!(i64)),
435            Self::leqldate => Scalar::leqldate(_read_le!(i64)),
436            Self::leqwdate => Scalar::leqwdate(_read_le!(i64)),
437            Self::ubelong => Scalar::ubelong(_read_be!(u32)),
438            Self::ulong => Scalar::ulong(_read_ne!(u32)),
439            Self::ubeshort => Scalar::ubeshort(_read_be!(u16)),
440            Self::ubeqdate => Scalar::ubeqdate(_read_be!(u64)),
441            Self::lemsdosdate => Scalar::lemsdosdate(_read_le!(u16)),
442            Self::lemsdostime => Scalar::lemsdostime(_read_le!(u16)),
443            Self::guid => Scalar::guid(u128::from_be_bytes(read!(from, u128))),
444        })
445    }
446}
447
448impl FloatDataType {
449    #[inline(always)]
450    fn read<R: Read + Seek>(&self, from: &mut R, switch_endianness: bool) -> Result<Float, Error> {
451        macro_rules! _read_le {
452            ($ty: ty) => {{
453                if switch_endianness {
454                    <$ty>::from_be_bytes(read!(from, $ty))
455                } else {
456                    <$ty>::from_le_bytes(read!(from, $ty))
457                }
458            }};
459        }
460
461        macro_rules! _read_be {
462            ($ty: ty) => {{
463                if switch_endianness {
464                    <$ty>::from_le_bytes(read!(from, $ty))
465                } else {
466                    <$ty>::from_be_bytes(read!(from, $ty))
467                }
468            }};
469        }
470
471        macro_rules! _read_ne {
472            ($ty: ty) => {{
473                if cfg!(target_endian = "big") {
474                    _read_be!($ty)
475                } else {
476                    _read_le!($ty)
477                }
478            }};
479        }
480
481        macro_rules! _read_me {
482            () => {
483                ((_read_le!(u16) as i32) << 16) | (_read_le!(u16) as i32)
484            };
485        }
486
487        Ok(match self {
488            Self::lefloat => Float::lefloat(_read_le!(f32)),
489            Self::befloat => Float::befloat(_read_le!(f32)),
490            Self::ledouble => Float::ledouble(_read_le!(f64)),
491            Self::bedouble => Float::bedouble(_read_be!(f64)),
492        })
493    }
494}
495
496#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
497enum Op {
498    Mul,
499    Add,
500    Sub,
501    Div,
502    Mod,
503    And,
504    Xor,
505    Or,
506}
507
508impl Display for Op {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        match self {
511            Op::Mul => write!(f, "*"),
512            Op::Add => write!(f, "+"),
513            Op::Sub => write!(f, "-"),
514            Op::Div => write!(f, "/"),
515            Op::Mod => write!(f, "%"),
516            Op::And => write!(f, "&"),
517            Op::Or => write!(f, "|"),
518            Op::Xor => write!(f, "^"),
519        }
520    }
521}
522
523#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
524enum CmpOp {
525    Eq,
526    Lt,
527    Gt,
528    BitAnd,
529    Neq, // ! operator
530    Xor,
531    Not, // ~ operator
532}
533
534impl CmpOp {
535    #[inline(always)]
536    fn is_neq(&self) -> bool {
537        matches!(self, Self::Neq)
538    }
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
542struct ScalarTransform {
543    op: Op,
544    num: Scalar,
545}
546
547impl ScalarTransform {
548    fn apply(&self, s: Scalar) -> Option<Scalar> {
549        match self.op {
550            Op::Add => s.checked_add(self.num),
551            Op::Sub => s.checked_sub(self.num),
552            Op::Mul => s.checked_mul(self.num),
553            Op::Div => s.checked_div(self.num),
554            Op::Mod => s.checked_rem(self.num),
555            Op::And => Some(s.bitand(self.num)),
556            Op::Xor => Some(s.bitxor(self.num)),
557            Op::Or => Some(s.bitor(self.num)),
558        }
559    }
560}
561
562#[derive(Debug, Clone, Serialize, Deserialize)]
563struct FloatTransform {
564    op: Op,
565    num: Float,
566}
567
568impl FloatTransform {
569    fn apply(&self, s: Float) -> Float {
570        match self.op {
571            Op::Add => s.add(self.num),
572            Op::Sub => s.sub(self.num),
573            Op::Mul => s.mul(self.num),
574            // returns inf when div by 0
575            Op::Div => s.div(self.num),
576            // returns NaN when rem by 0
577            Op::Mod => s.rem(self.num),
578            // parser makes sure those operators cannot be used
579            Op::And | Op::Xor | Op::Or => {
580                debug_panic!("unsupported operation");
581                s
582            }
583        }
584    }
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize)]
588enum TestValue<T> {
589    Value(T),
590    Any,
591}
592
593impl<T> TestValue<T> {
594    #[inline(always)]
595    fn as_ref(&self) -> TestValue<&T> {
596        match self {
597            Self::Value(v) => TestValue::Value(v),
598            Self::Any => TestValue::Any,
599        }
600    }
601}
602
603flags! {
604    enum ReMod: u8{
605        CaseInsensitive,
606        StartOffsetUpdate,
607        LineLimit,
608        ForceBin,
609        ForceText,
610        TrimMatch,
611    }
612}
613
614fn serialize_regex<S>(re: &bytes::Regex, serializer: S) -> Result<S::Ok, S::Error>
615where
616    S: serde::Serializer,
617{
618    re.as_str().serialize(serializer)
619}
620
621fn deserialize_regex<'de, D>(deserializer: D) -> Result<bytes::Regex, D::Error>
622where
623    D: serde::Deserializer<'de>,
624{
625    let wrapper = String::deserialize(deserializer)?;
626    bytes::Regex::new(&wrapper).map_err(serde::de::Error::custom)
627}
628
629#[derive(Debug, Clone, Serialize, Deserialize)]
630struct RegexTest {
631    #[serde(
632        serialize_with = "serialize_regex",
633        deserialize_with = "deserialize_regex"
634    )]
635    re: bytes::Regex,
636    length: Option<usize>,
637    mods: FlagSet<ReMod>,
638    str_mods: FlagSet<StringMod>,
639    non_magic_len: usize,
640    binary: bool,
641    cmp_op: CmpOp,
642}
643
644impl RegexTest {
645    #[inline(always)]
646    fn is_binary(&self) -> bool {
647        self.binary
648            || self.mods.contains(ReMod::ForceBin)
649            || self.str_mods.contains(StringMod::ForceBin)
650    }
651
652    fn match_buf<'buf>(
653        &self,
654        off_buf: u64, // absolute buffer offset in content
655        stream_kind: StreamKind,
656        buf: &'buf [u8],
657    ) -> Option<MatchRes<'buf>> {
658        let mr = match stream_kind {
659            StreamKind::Text(_) => {
660                let mut off_txt = off_buf;
661
662                let mut line_limit = self.length.unwrap_or(usize::MAX);
663
664                for line in buf.split(|c| c == &b'\n') {
665                    // we don't need to break on offset
666                    // limit as buf contains the good amount
667                    // of bytes to match against
668                    if line_limit == 0 {
669                        break;
670                    }
671
672                    if let Some(re_match) = self.re.find(line) {
673                        // the offset of the string is computed from the start of the buffer
674                        let start_offset = off_txt + re_match.start() as u64;
675
676                        // if we matched until EOL we need to add one to include the delimiter removed from the split
677                        let stop_offset = if re_match.end() == line.len() {
678                            Some(start_offset + re_match.as_bytes().len() as u64 + 1)
679                        } else {
680                            None
681                        };
682
683                        return Some(MatchRes::Bytes(
684                            start_offset,
685                            stop_offset,
686                            re_match.as_bytes(),
687                            Encoding::Utf8,
688                        ));
689                    }
690
691                    off_txt += line.len() as u64;
692                    // we have to add one because lines do not contain splitting character
693                    off_txt += 1;
694                    line_limit = line_limit.saturating_sub(1)
695                }
696                None
697            }
698
699            StreamKind::Binary => {
700                self.re.find(buf).map(|re_match| {
701                    MatchRes::Bytes(
702                        // the offset of the string is computed from the start of the buffer
703                        off_buf + re_match.start() as u64,
704                        None,
705                        re_match.as_bytes(),
706                        Encoding::Utf8,
707                    )
708                })
709            }
710        };
711
712        // handle the case where we want the regex not to match
713        if self.cmp_op.is_neq() && mr.is_none() {
714            return Some(MatchRes::Bytes(off_buf, None, buf, Encoding::Utf8));
715        }
716
717        mr
718    }
719}
720
721impl From<RegexTest> for Test {
722    fn from(value: RegexTest) -> Self {
723        Self::Regex(value)
724    }
725}
726
727flags! {
728    enum StringMod: u8{
729        ForceBin,
730        UpperInsensitive,
731        LowerInsensitive,
732        FullWordMatch,
733        Trim,
734        ForceText,
735        CompactWhitespace,
736        OptBlank,
737    }
738}
739
740#[derive(Debug, Clone, Serialize, Deserialize)]
741struct StringTest {
742    test_val: TestValue<Vec<u8>>,
743    cmp_op: CmpOp,
744    length: Option<usize>,
745    mods: FlagSet<StringMod>,
746    binary: bool,
747}
748
749impl From<StringTest> for Test {
750    fn from(value: StringTest) -> Self {
751        Self::String(value)
752    }
753}
754
755#[inline(always)]
756fn string_match(str: &[u8], mods: FlagSet<StringMod>, buf: &[u8]) -> (bool, usize) {
757    let mut consumed = 0;
758    // we can do a simple string comparison
759    if mods.is_disjoint(
760        StringMod::UpperInsensitive
761            | StringMod::LowerInsensitive
762            | StringMod::FullWordMatch
763            | StringMod::CompactWhitespace
764            | StringMod::OptBlank,
765    ) {
766        // we check if target contains
767        if buf.starts_with(str) {
768            (true, str.len())
769        } else {
770            (false, consumed)
771        }
772    } else {
773        let mut i_src = 0;
774        let mut iter = buf.iter().peekable();
775
776        macro_rules! consume_target {
777            () => {{
778                iter.next();
779                consumed += 1;
780            }};
781        }
782
783        macro_rules! continue_next_iteration {
784            () => {{
785                consume_target!();
786                i_src += 1;
787                continue;
788            }};
789        }
790
791        while let Some(&&b) = iter.peek() {
792            let Some(&ref_byte) = str.get(i_src) else {
793                break;
794            };
795
796            if mods.contains(StringMod::OptBlank) && (b == b' ' || ref_byte == b' ') {
797                if b == b' ' {
798                    // we ignore whitespace in target
799                    consume_target!();
800                }
801
802                if ref_byte == b' ' {
803                    // we ignore whitespace in test
804                    i_src += 1;
805                }
806
807                continue;
808            }
809
810            if mods.contains(StringMod::UpperInsensitive) {
811                //upper case characters in the magic match both lower and upper case characters in the target
812                if ref_byte.is_ascii_uppercase() && ref_byte == b.to_ascii_uppercase()
813                    || ref_byte == b
814                {
815                    continue_next_iteration!()
816                }
817            }
818
819            if mods.contains(StringMod::LowerInsensitive)
820                && (ref_byte.is_ascii_lowercase() && ref_byte == b.to_ascii_lowercase()
821                    || ref_byte == b)
822            {
823                continue_next_iteration!()
824            }
825
826            if mods.contains(StringMod::CompactWhitespace) && ref_byte == b' ' {
827                let mut src_blk = 0;
828                while let Some(b' ') = str.get(i_src) {
829                    src_blk += 1;
830                    i_src += 1;
831                }
832
833                let mut tgt_blk = 0;
834                while let Some(b' ') = iter.peek() {
835                    tgt_blk += 1;
836                    consume_target!();
837                }
838
839                if src_blk > tgt_blk {
840                    return (false, consumed);
841                }
842
843                continue;
844            }
845
846            if ref_byte == b {
847                continue_next_iteration!()
848            } else {
849                return (false, consumed);
850            }
851        }
852
853        if mods.contains(StringMod::FullWordMatch)
854            && let Some(b) = iter.peek()
855            && !b.is_ascii_whitespace()
856        {
857            return (false, consumed);
858        }
859
860        (consumed > 0 && consumed <= buf.len(), consumed)
861    }
862}
863
864impl StringTest {
865    fn has_length_mod(&self) -> bool {
866        !self.mods.is_disjoint(
867            StringMod::UpperInsensitive
868                | StringMod::LowerInsensitive
869                | StringMod::FullWordMatch
870                | StringMod::CompactWhitespace
871                | StringMod::OptBlank,
872        )
873    }
874
875    #[inline(always)]
876    fn test_value_len(&self) -> usize {
877        match self.test_val.as_ref() {
878            TestValue::Value(s) => s.len(),
879            TestValue::Any => 0,
880        }
881    }
882
883    #[inline(always)]
884    fn is_binary(&self) -> bool {
885        self.binary || self.mods.contains(StringMod::ForceBin)
886    }
887
888    #[inline(always)]
889    fn is_text(&self) -> bool {
890        self.mods.contains(StringMod::ForceText)
891    }
892}
893
894#[derive(Debug, Clone, Serialize, Deserialize)]
895struct SearchTest {
896    str: Vec<u8>,
897    n_pos: Option<usize>,
898    str_mods: FlagSet<StringMod>,
899    re_mods: FlagSet<ReMod>,
900    binary: bool,
901    cmp_op: CmpOp,
902}
903
904impl From<SearchTest> for Test {
905    fn from(value: SearchTest) -> Self {
906        Self::Search(value)
907    }
908}
909
910impl SearchTest {
911    #[inline(always)]
912    fn is_binary(&self) -> bool {
913        (self.binary
914            || self.str_mods.contains(StringMod::ForceBin)
915            || self.re_mods.contains(ReMod::ForceBin))
916            && !(self.str_mods.contains(StringMod::ForceText)
917                || self.re_mods.contains(ReMod::ForceText))
918    }
919
920    // off_buf: absolute buffer offset in content
921    #[inline]
922    fn match_buf<'buf>(&self, off_buf: u64, buf: &'buf [u8]) -> Option<MatchRes<'buf>> {
923        let mut i = 0;
924
925        let needle = self.str.first()?;
926
927        while i < buf.len() {
928            // we cannot match if the first character isn't the same
929            // so we accelerate the search by finding potential matches
930            i += memchr(*needle, &buf[i..])?;
931
932            // if we want a full word match
933            if self.str_mods.contains(StringMod::FullWordMatch) {
934                let prev_is_whitespace = buf
935                    .get(i.saturating_sub(1))
936                    .map(|c| c.is_ascii_whitespace())
937                    .unwrap_or_default();
938
939                // if it is not the first character
940                // and its previous character isn't
941                // a whitespace. It cannot be a
942                // fullword match
943                if i > 0 && !prev_is_whitespace {
944                    i += 1;
945                    continue;
946                }
947            }
948
949            if let Some(npos) = self.n_pos
950                && i > npos
951            {
952                break;
953            }
954
955            let pos = i;
956            let (ok, consumed) = string_match(&self.str, self.str_mods, &buf[i..]);
957
958            if ok {
959                return Some(MatchRes::Bytes(
960                    off_buf.saturating_add(pos as u64),
961                    None,
962                    &buf[i..i + consumed],
963                    Encoding::Utf8,
964                ));
965            } else {
966                i += max(consumed, 1)
967            }
968        }
969
970        // handles the case where we want the string not to be found
971        if self.cmp_op.is_neq() {
972            return Some(MatchRes::Bytes(off_buf, None, buf, Encoding::Utf8));
973        }
974
975        None
976    }
977}
978
979#[derive(Debug, Clone, Serialize, Deserialize)]
980struct ScalarTest {
981    ty: ScalarDataType,
982    transform: Option<ScalarTransform>,
983    cmp_op: CmpOp,
984    test_val: TestValue<Scalar>,
985}
986
987#[derive(Debug, Clone, Serialize, Deserialize)]
988struct FloatTest {
989    ty: FloatDataType,
990    transform: Option<FloatTransform>,
991    cmp_op: CmpOp,
992    test_val: TestValue<Float>,
993}
994
995// the value read from the haystack we want to match against
996// 'buf is the lifetime of the buffer we are scanning
997#[derive(Debug, PartialEq)]
998enum ReadValue<'buf> {
999    Float(u64, Float),
1000    Scalar(u64, Scalar),
1001    Bytes(u64, &'buf [u8]),
1002}
1003
1004impl DynDisplay for ReadValue<'_> {
1005    fn dyn_fmt(&self, f: &dyf::FormatSpec) -> Result<String, dyf::Error> {
1006        match self {
1007            Self::Float(_, s) => DynDisplay::dyn_fmt(s, f),
1008            Self::Scalar(_, s) => DynDisplay::dyn_fmt(s, f),
1009            Self::Bytes(_, b) => Ok(format!("{b:?}")),
1010        }
1011    }
1012}
1013
1014impl DynDisplay for &ReadValue<'_> {
1015    fn dyn_fmt(&self, f: &dyf::FormatSpec) -> Result<String, dyf::Error> {
1016        // Dereference self to get the TestValue and call its fmt method
1017        DynDisplay::dyn_fmt(*self, f)
1018    }
1019}
1020
1021impl Display for ReadValue<'_> {
1022    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1023        match self {
1024            Self::Float(_, v) => write!(f, "{v}"),
1025            Self::Scalar(_, s) => write!(f, "{s}"),
1026            Self::Bytes(_, b) => write!(f, "{b:?}"),
1027        }
1028    }
1029}
1030
1031enum Encoding {
1032    Utf16(String16Encoding),
1033    Utf8,
1034}
1035
1036// Carry the offset of the start of the data in the stream
1037// and the data itself
1038enum MatchRes<'buf> {
1039    // Bytes.0: offset of the match
1040    // Bytes.1: optional end of match (to address the need of EOL adjustment in string regex)
1041    // Bytes.2: the bytes matching
1042    // Bytes.3: encoding of the buffer
1043    Bytes(u64, Option<u64>, &'buf [u8], Encoding),
1044    Scalar(u64, Scalar),
1045    Float(u64, Float),
1046}
1047
1048impl DynDisplay for &MatchRes<'_> {
1049    fn dyn_fmt(&self, f: &dyf::FormatSpec) -> Result<String, dyf::Error> {
1050        (*self).dyn_fmt(f)
1051    }
1052}
1053
1054impl DynDisplay for MatchRes<'_> {
1055    fn dyn_fmt(&self, f: &dyf::FormatSpec) -> Result<String, dyf::Error> {
1056        match self {
1057            Self::Scalar(_, v) => v.dyn_fmt(f),
1058            Self::Float(_, v) => v.dyn_fmt(f),
1059            Self::Bytes(_, _, v, enc) => match enc {
1060                Encoding::Utf8 => String::from_utf8_lossy(v).to_string().dyn_fmt(f),
1061                Encoding::Utf16(enc) => {
1062                    let utf16: Vec<u16> = slice_to_utf16_iter(v, *enc).collect();
1063                    String::from_utf16_lossy(&utf16).dyn_fmt(f)
1064                }
1065            },
1066        }
1067    }
1068}
1069
1070impl MatchRes<'_> {
1071    // start offset of the match
1072    #[inline]
1073    fn start_offset(&self) -> u64 {
1074        match self {
1075            MatchRes::Bytes(o, _, _, _) => *o,
1076            MatchRes::Scalar(o, _) => *o,
1077            MatchRes::Float(o, _) => *o,
1078        }
1079    }
1080
1081    // start offset of the match
1082    #[inline]
1083    fn end_offset(&self) -> u64 {
1084        match self {
1085            MatchRes::Bytes(start, end, buf, _) => match end {
1086                Some(end) => *end,
1087                None => start.saturating_add(buf.len() as u64),
1088            },
1089            MatchRes::Scalar(o, sc) => o.add(sc.size_of() as u64),
1090            MatchRes::Float(o, f) => o.add(f.size_of() as u64),
1091        }
1092    }
1093}
1094
1095fn slice_to_utf16_iter(read: &[u8], encoding: String16Encoding) -> impl Iterator<Item = u16> {
1096    let even = read
1097        .iter()
1098        .enumerate()
1099        .filter(|(i, _)| i % 2 == 0)
1100        .map(|t| t.1);
1101
1102    let odd = read
1103        .iter()
1104        .enumerate()
1105        .filter(|(i, _)| i % 2 != 0)
1106        .map(|t| t.1);
1107
1108    even.zip(odd).map(move |(e, o)| match encoding {
1109        String16Encoding::Le => u16::from_le_bytes([*e, *o]),
1110        String16Encoding::Be => u16::from_be_bytes([*e, *o]),
1111    })
1112}
1113
1114#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1115enum String16Encoding {
1116    Le,
1117    Be,
1118}
1119
1120#[derive(Debug, Clone, Serialize, Deserialize)]
1121struct String16Test {
1122    orig: String,
1123    test_val: TestValue<Vec<u16>>,
1124    encoding: String16Encoding,
1125}
1126
1127impl String16Test {
1128    /// if the test value is a specific value this method returns
1129    /// the number of utf16 characters. To obtain the length in
1130    /// bytes the return value needs to be multiplied by two.
1131    #[inline(always)]
1132    fn test_value_len(&self) -> usize {
1133        match self.test_val.as_ref() {
1134            TestValue::Value(str16) => str16.len(),
1135            TestValue::Any => 0,
1136        }
1137    }
1138}
1139
1140flags! {
1141    enum IndirectMod: u8{
1142        Relative,
1143    }
1144}
1145
1146type IndirectMods = FlagSet<IndirectMod>;
1147
1148#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1149enum PStringLen {
1150    Byte,    // B
1151    ShortBe, // H
1152    ShortLe, // h
1153    LongBe,  // L
1154    LongLe,  // l
1155}
1156
1157impl PStringLen {
1158    #[inline(always)]
1159    const fn size_of_len(&self) -> usize {
1160        match self {
1161            PStringLen::Byte => 1,
1162            PStringLen::ShortBe => 2,
1163            PStringLen::ShortLe => 2,
1164            PStringLen::LongBe => 4,
1165            PStringLen::LongLe => 4,
1166        }
1167    }
1168}
1169
1170#[derive(Debug, Clone, Serialize, Deserialize)]
1171struct PStringTest {
1172    len: PStringLen,
1173    test_val: TestValue<Vec<u8>>,
1174    include_len: bool,
1175}
1176
1177impl PStringTest {
1178    #[inline]
1179    fn read<'cache, R: Read + Seek>(
1180        &self,
1181        haystack: &'cache mut LazyCache<R>,
1182    ) -> Result<Option<&'cache [u8]>, Error> {
1183        let mut len = match self.len {
1184            PStringLen::Byte => read_le!(haystack, u8) as u32,
1185            PStringLen::ShortBe => read_be!(haystack, u16) as u32,
1186            PStringLen::ShortLe => read_le!(haystack, u16) as u32,
1187            PStringLen::LongBe => read_be!(haystack, u32),
1188            PStringLen::LongLe => read_le!(haystack, u32),
1189        } as usize;
1190
1191        if self.include_len {
1192            len = len.saturating_sub(self.len.size_of_len())
1193        }
1194
1195        if let TestValue::Value(s) = self.test_val.as_ref()
1196            && len != s.len()
1197        {
1198            return Ok(None);
1199        }
1200
1201        let read = haystack.read_exact_count(len as u64)?;
1202
1203        Ok(Some(read))
1204    }
1205
1206    #[inline(always)]
1207    fn test_value_len(&self) -> usize {
1208        match self.test_val.as_ref() {
1209            TestValue::Value(s) => s.len(),
1210            TestValue::Any => 0,
1211        }
1212    }
1213}
1214
1215#[derive(Debug, Clone, Serialize, Deserialize)]
1216enum Test {
1217    Name(String),
1218    Use(bool, String),
1219    Scalar(ScalarTest),
1220    Float(FloatTest),
1221    String(StringTest),
1222    Search(SearchTest),
1223    PString(PStringTest),
1224    Regex(RegexTest),
1225    Indirect(FlagSet<IndirectMod>),
1226    String16(String16Test),
1227    // FIXME: placeholder for strength computation
1228    #[allow(dead_code)]
1229    Der,
1230    Clear,
1231    Default,
1232}
1233
1234impl Test {
1235    // read the value to test from the haystack
1236    #[inline]
1237    fn read_test_value<'haystack, R: Read + Seek>(
1238        &self,
1239        haystack: &'haystack mut LazyCache<R>,
1240        switch_endianness: bool,
1241    ) -> Result<Option<ReadValue<'haystack>>, Error> {
1242        let test_value_offset = haystack.lazy_stream_position();
1243
1244        match self {
1245            Self::Scalar(t) => {
1246                t.ty.read(haystack, switch_endianness)
1247                    .map(|s| Some(ReadValue::Scalar(test_value_offset, s)))
1248            }
1249
1250            Self::Float(t) => {
1251                t.ty.read(haystack, switch_endianness)
1252                    .map(|f| Some(ReadValue::Float(test_value_offset, f)))
1253            }
1254            Self::String(t) => {
1255                match t.test_val.as_ref() {
1256                    TestValue::Value(str) => {
1257                        let buf = if let Some(length) = t.length {
1258                            // if there is a length specified
1259                            haystack.read_exact_count(length as u64)?
1260                        } else {
1261                            // no length specified we read until end of string
1262
1263                            match t.cmp_op {
1264                                CmpOp::Eq | CmpOp::Neq => {
1265                                    if !t.has_length_mod() {
1266                                        haystack.read_exact_count(str.len() as u64)?
1267                                    } else {
1268                                        haystack.read_count(FILE_BYTES_MAX as u64)?
1269                                    }
1270                                }
1271                                CmpOp::Lt | CmpOp::Gt => {
1272                                    let read =
1273                                        haystack.read_until_any_delim_or_limit(b"\n\0", 8092)?;
1274
1275                                    if read.ends_with(b"\0") || read.ends_with(b"\n") {
1276                                        &read[..read.len() - 1]
1277                                    } else {
1278                                        read
1279                                    }
1280                                }
1281                                _ => {
1282                                    return Err(Error::Msg(format!(
1283                                        "string test does not support {:?} operator",
1284                                        t.cmp_op
1285                                    )));
1286                                }
1287                            }
1288                        };
1289
1290                        Ok(Some(ReadValue::Bytes(test_value_offset, buf)))
1291                    }
1292                    TestValue::Any => {
1293                        let read = haystack.read_until_any_delim_or_limit(b"\0\n", 8192)?;
1294                        // we don't take last byte if it matches end of string
1295                        let bytes = if read.ends_with(b"\0") || read.ends_with(b"\n") {
1296                            &read[..read.len() - 1]
1297                        } else {
1298                            read
1299                        };
1300
1301                        Ok(Some(ReadValue::Bytes(test_value_offset, bytes)))
1302                    }
1303                }
1304            }
1305
1306            Self::String16(t) => {
1307                match t.test_val.as_ref() {
1308                    TestValue::Value(str16) => {
1309                        let read = haystack.read_exact_count((str16.len() * 2) as u64)?;
1310
1311                        Ok(Some(ReadValue::Bytes(test_value_offset, read)))
1312                    }
1313                    TestValue::Any => {
1314                        let read = haystack.read_until_utf16_or_limit(b"\x00\x00", 8192)?;
1315
1316                        // we make sure we have an even number of elements
1317                        let end = if read.len() % 2 == 0 {
1318                            read.len()
1319                        } else {
1320                            // we decide to read anyway even though
1321                            // length isn't even
1322                            read.len().saturating_sub(1)
1323                        };
1324
1325                        Ok(Some(ReadValue::Bytes(test_value_offset, &read[..end])))
1326                    }
1327                }
1328            }
1329
1330            Self::PString(t) => {
1331                let Some(read) = t.read(haystack)? else {
1332                    return Ok(None);
1333                };
1334                Ok(Some(ReadValue::Bytes(test_value_offset, read)))
1335            }
1336
1337            Self::Search(_) => {
1338                let buf = haystack.read_count(FILE_BYTES_MAX as u64)?;
1339                Ok(Some(ReadValue::Bytes(test_value_offset, buf)))
1340            }
1341
1342            Self::Regex(r) => {
1343                let length = {
1344                    match r.length {
1345                        Some(len) => {
1346                            if r.mods.contains(ReMod::LineLimit) {
1347                                len * 80
1348                            } else {
1349                                len
1350                            }
1351                        }
1352
1353                        None => FILE_REGEX_MAX,
1354                    }
1355                };
1356
1357                let read = haystack.read_count(length as u64)?;
1358                Ok(Some(ReadValue::Bytes(test_value_offset, read)))
1359            }
1360
1361            Self::Name(_)
1362            | Self::Use(_, _)
1363            | Self::Indirect(_)
1364            | Self::Clear
1365            | Self::Default
1366            | Self::Der => Err(Error::msg("no value to read for this test")),
1367        }
1368    }
1369
1370    #[inline(always)]
1371    fn match_value<'s>(
1372        &'s self,
1373        tv: &ReadValue<'s>,
1374        stream_kind: StreamKind,
1375    ) -> Option<MatchRes<'s>> {
1376        match (self, tv) {
1377            (Self::Scalar(t), ReadValue::Scalar(o, ts)) => {
1378                let read_value: Scalar = match t.transform.as_ref() {
1379                    Some(t) => t.apply(*ts)?,
1380                    None => *ts,
1381                };
1382
1383                match t.test_val {
1384                    TestValue::Value(test_value) => {
1385                        let ok = match t.cmp_op {
1386                            // NOTE: this should not happen in practice because
1387                            // we convert it into Eq equivalent at parsing time
1388                            CmpOp::Not => read_value == !test_value,
1389                            CmpOp::Eq => read_value == test_value,
1390                            CmpOp::Lt => read_value < test_value,
1391                            CmpOp::Gt => read_value > test_value,
1392                            CmpOp::Neq => read_value != test_value,
1393                            CmpOp::BitAnd => read_value & test_value == test_value,
1394                            CmpOp::Xor => (read_value & test_value).is_zero(),
1395                        };
1396
1397                        if ok {
1398                            Some(MatchRes::Scalar(*o, read_value))
1399                        } else {
1400                            None
1401                        }
1402                    }
1403
1404                    TestValue::Any => Some(MatchRes::Scalar(*o, read_value)),
1405                }
1406            }
1407
1408            (Self::Float(t), ReadValue::Float(o, f)) => {
1409                let read_value: Float = t.transform.as_ref().map(|t| t.apply(*f)).unwrap_or(*f);
1410
1411                match t.test_val {
1412                    TestValue::Value(tf) => {
1413                        let ok = match t.cmp_op {
1414                            CmpOp::Eq => read_value == tf,
1415                            CmpOp::Lt => read_value < tf,
1416                            CmpOp::Gt => read_value > tf,
1417                            CmpOp::Neq => read_value != tf,
1418                            _ => {
1419                                // this should never be reached as we validate
1420                                // operator in parser
1421                                debug_panic!("unsupported float comparison");
1422                                debug!("unsupported float comparison");
1423                                false
1424                            }
1425                        };
1426
1427                        if ok {
1428                            Some(MatchRes::Float(*o, read_value))
1429                        } else {
1430                            None
1431                        }
1432                    }
1433                    TestValue::Any => Some(MatchRes::Float(*o, read_value)),
1434                }
1435            }
1436
1437            (Self::String(st), ReadValue::Bytes(o, buf)) => {
1438                macro_rules! trim_buf {
1439                    ($buf: expr) => {{
1440                        if st.mods.contains(StringMod::Trim) {
1441                            $buf.trim_ascii()
1442                        } else {
1443                            $buf
1444                        }
1445                    }};
1446                }
1447
1448                match st.test_val.as_ref() {
1449                    TestValue::Value(str) => {
1450                        match st.cmp_op {
1451                            CmpOp::Eq => {
1452                                if let (true, _) = string_match(str, st.mods, buf) {
1453                                    Some(MatchRes::Bytes(*o, None, trim_buf!(str), Encoding::Utf8))
1454                                } else {
1455                                    None
1456                                }
1457                            }
1458                            CmpOp::Neq => {
1459                                if let (false, _) = string_match(str, st.mods, buf) {
1460                                    Some(MatchRes::Bytes(*o, None, trim_buf!(str), Encoding::Utf8))
1461                                } else {
1462                                    None
1463                                }
1464                            }
1465                            CmpOp::Gt => {
1466                                if buf.len() > str.len() {
1467                                    Some(MatchRes::Bytes(*o, None, trim_buf!(buf), Encoding::Utf8))
1468                                } else {
1469                                    None
1470                                }
1471                            }
1472                            CmpOp::Lt => {
1473                                if buf.len() < str.len() {
1474                                    Some(MatchRes::Bytes(*o, None, trim_buf!(buf), Encoding::Utf8))
1475                                } else {
1476                                    None
1477                                }
1478                            }
1479
1480                            // unsupported for strings
1481                            _ => {
1482                                // this should never be reached as we validate
1483                                // operator in parser
1484                                debug_panic!("unsupported string comparison");
1485                                debug!("unsupported string comparison");
1486                                None
1487                            }
1488                        }
1489                    }
1490                    TestValue::Any => {
1491                        Some(MatchRes::Bytes(*o, None, trim_buf!(buf), Encoding::Utf8))
1492                    }
1493                }
1494            }
1495
1496            (Self::PString(m), ReadValue::Bytes(o, buf)) => match m.test_val.as_ref() {
1497                TestValue::Value(psv) => {
1498                    if buf == psv {
1499                        Some(MatchRes::Bytes(*o, None, buf, Encoding::Utf8))
1500                    } else {
1501                        None
1502                    }
1503                }
1504                TestValue::Any => Some(MatchRes::Bytes(*o, None, buf, Encoding::Utf8)),
1505            },
1506
1507            (Self::String16(t), ReadValue::Bytes(o, buf)) => {
1508                match t.test_val.as_ref() {
1509                    TestValue::Value(str16) => {
1510                        // strings cannot be equal
1511                        if str16.len() * 2 != buf.len() {
1512                            return None;
1513                        }
1514
1515                        // we check string equality
1516                        for (i, utf16_char) in slice_to_utf16_iter(buf, t.encoding).enumerate() {
1517                            if str16[i] != utf16_char {
1518                                return None;
1519                            }
1520                        }
1521
1522                        Some(MatchRes::Bytes(
1523                            *o,
1524                            None,
1525                            t.orig.as_bytes(),
1526                            Encoding::Utf16(t.encoding),
1527                        ))
1528                    }
1529
1530                    TestValue::Any => {
1531                        Some(MatchRes::Bytes(*o, None, buf, Encoding::Utf16(t.encoding)))
1532                    }
1533                }
1534            }
1535
1536            (Self::Regex(r), ReadValue::Bytes(o, buf)) => r.match_buf(*o, stream_kind, buf),
1537
1538            (Self::Search(t), ReadValue::Bytes(o, buf)) => t.match_buf(*o, buf),
1539
1540            _ => None,
1541        }
1542    }
1543
1544    #[inline(always)]
1545    fn strength(&self) -> u64 {
1546        const MULT: usize = 10;
1547
1548        let mut out = 2 * MULT;
1549
1550        // FIXME: octal is missing but it is not used in practice ...
1551        match self {
1552            Test::Scalar(s) => {
1553                out += s.ty.type_size() * MULT;
1554            }
1555
1556            Test::Float(t) => {
1557                out += t.ty.type_size() * MULT;
1558            }
1559
1560            Test::String(t) => out += t.test_value_len().saturating_mul(MULT),
1561
1562            Test::PString(t) => out += t.test_value_len().saturating_mul(MULT),
1563
1564            Test::Search(s) => {
1565                // NOTE: this implementation deviates from what is in
1566                // C libmagic. The purpose of this implementation is to
1567                // minimize the difference between similar tests,
1568                // implemented differently (ex: string test VS very localized search test).
1569                let n_pos = s.n_pos.unwrap_or(FILE_BYTES_MAX);
1570
1571                match n_pos {
1572                    // a search on one line should be equivalent to a string match
1573                    0..=80 => out += s.str.len().saturating_mul(MULT),
1574                    // search on the first 3 lines gets a little penalty
1575                    81..=240 => out += s.str.len() * s.str.len().clamp(0, MULT - 2),
1576                    // a search on more than 3 lines isn't considered very accurate
1577                    _ => out += s.str.len(),
1578                }
1579            }
1580
1581            Test::Regex(r) => {
1582                // NOTE: this implementation deviates from what is in
1583                // C libmagic. The purpose of this implementation is to
1584                // minimize the difference between similar tests,
1585                // implemented differently (ex: string test VS very localized regex test).
1586
1587                // we divide length by the number of capture group
1588                // which gives us a value close to he average string
1589                // length match in the regex.
1590                let v = r.non_magic_len / r.re.captures_len();
1591
1592                let len = r
1593                    .length
1594                    .map(|l| {
1595                        if r.mods.contains(ReMod::LineLimit) {
1596                            l * 80
1597                        } else {
1598                            l
1599                        }
1600                    })
1601                    .unwrap_or(FILE_BYTES_MAX);
1602
1603                match len {
1604                    // a search on one line should be equivalent to a string match
1605                    0..=80 => out += v.saturating_mul(MULT),
1606                    // search on the first 3 lines gets a little penalty
1607                    81..=240 => out += v * v.clamp(0, MULT - 2),
1608                    // a search on more than 3 lines isn't considered very accurate
1609                    _ => out += v,
1610                }
1611            }
1612
1613            Test::String16(t) => {
1614                // NOTE: in libmagic the result is div by 2
1615                // but I GUESS it is because the len is expressed
1616                // in number bytes. In our case length is expressed
1617                // in number of u16 so we shouldn't divide.
1618                out += t.test_value_len().saturating_mul(MULT);
1619            }
1620
1621            Test::Der => out += MULT,
1622
1623            Test::Default | Test::Name(_) | Test::Use(_, _) | Test::Indirect(_) | Test::Clear => {
1624                return 0;
1625            }
1626        }
1627
1628        // matching any output gets penalty
1629        if self.is_match_any() {
1630            return 0;
1631        }
1632
1633        if let Some(op) = self.cmp_op() {
1634            match op {
1635                // matching almost any gets penalty
1636                CmpOp::Neq => out = 0,
1637                CmpOp::Eq | CmpOp::Not => out += MULT,
1638                CmpOp::Lt | CmpOp::Gt => out -= 2 * MULT,
1639                CmpOp::Xor | CmpOp::BitAnd => out -= MULT,
1640            }
1641        }
1642
1643        out as u64
1644    }
1645
1646    #[inline(always)]
1647    fn cmp_op(&self) -> Option<CmpOp> {
1648        match self {
1649            Self::String(t) => Some(t.cmp_op),
1650            Self::Scalar(s) => Some(s.cmp_op),
1651            Self::Float(t) => Some(t.cmp_op),
1652            Self::Name(_)
1653            | Self::Use(_, _)
1654            | Self::Search(_)
1655            | Self::PString(_)
1656            | Self::Regex(_)
1657            | Self::Clear
1658            | Self::Default
1659            | Self::Indirect(_)
1660            | Self::String16(_)
1661            | Self::Der => None,
1662        }
1663    }
1664
1665    #[inline(always)]
1666    fn is_match_any(&self) -> bool {
1667        match self {
1668            Test::Name(_) => false,
1669            Test::Use(_, _) => false,
1670            Test::Scalar(scalar_test) => matches!(scalar_test.test_val, TestValue::Any),
1671            Test::Float(float_test) => matches!(float_test.test_val, TestValue::Any),
1672            Test::String(string_test) => matches!(string_test.test_val, TestValue::Any),
1673            Test::Search(_) => false,
1674            Test::PString(pstring_test) => matches!(pstring_test.test_val, TestValue::Any),
1675            Test::Regex(_) => false,
1676            Test::Indirect(_) => false,
1677            Test::String16(string16_test) => matches!(string16_test.test_val, TestValue::Any),
1678            Test::Der => false,
1679            Test::Clear => false,
1680            Test::Default => false,
1681        }
1682    }
1683
1684    #[inline(always)]
1685    fn is_binary(&self) -> bool {
1686        match self {
1687            Self::Name(_) => true,
1688            Self::Use(_, _) => true,
1689            Self::Scalar(_) => true,
1690            Self::Float(_) => true,
1691            Self::String(t) => !t.is_binary() & !t.is_text() || t.is_binary(),
1692            Self::Search(t) => t.is_binary(),
1693            Self::PString(_) => true,
1694            Self::Regex(t) => t.is_binary(),
1695            Self::Clear => true,
1696            Self::Default => true,
1697            Self::Indirect(_) => true,
1698            Self::String16(_) => true,
1699            Self::Der => true,
1700        }
1701    }
1702
1703    #[inline(always)]
1704    fn is_text(&self) -> bool {
1705        match self {
1706            Self::Name(_) => true,
1707            Self::Use(_, _) => true,
1708            Self::Indirect(_) => true,
1709            Self::Clear => true,
1710            Self::Default => true,
1711            Self::String(t) => !t.is_binary() & !t.is_text() || t.is_text(),
1712            _ => !self.is_binary(),
1713        }
1714    }
1715
1716    #[inline(always)]
1717    fn is_only_text(&self) -> bool {
1718        self.is_text() && !self.is_binary()
1719    }
1720
1721    #[inline(always)]
1722    fn is_only_binary(&self) -> bool {
1723        self.is_binary() && !self.is_text()
1724    }
1725}
1726
1727#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1728enum OffsetType {
1729    Byte,
1730    DoubleLe,
1731    DoubleBe,
1732    ShortLe,
1733    ShortBe,
1734    Id3Le,
1735    Id3Be,
1736    LongLe,
1737    LongBe,
1738    Middle,
1739    Octal,
1740    QuadBe,
1741    QuadLe,
1742}
1743
1744#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1745enum Shift {
1746    Direct(u64),
1747    Indirect(i64),
1748}
1749
1750#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1751struct IndOffset {
1752    // where to find the offset
1753    off_addr: DirOffset,
1754    // signed or unsigned
1755    signed: bool,
1756    // type of the offset
1757    ty: OffsetType,
1758    op: Option<Op>,
1759    shift: Option<Shift>,
1760}
1761
1762impl IndOffset {
1763    // if we overflow we must not return an offset
1764    fn read_offset<R: Read + Seek>(
1765        &self,
1766        haystack: &mut LazyCache<R>,
1767        rule_base_offset: Option<u64>,
1768        last_upper_match_offset: Option<u64>,
1769    ) -> Result<Option<u64>, io::Error> {
1770        let offset_address = match self.off_addr {
1771            DirOffset::Start(s) => {
1772                let Some(o) = s.checked_add(rule_base_offset.unwrap_or_default()) else {
1773                    return Ok(None);
1774                };
1775
1776                haystack.seek(SeekFrom::Start(o))?
1777            }
1778            DirOffset::LastUpper(c) => haystack.seek(SeekFrom::Start(
1779                (last_upper_match_offset.unwrap_or_default() as i64 + c) as u64,
1780            ))?,
1781            DirOffset::End(e) => haystack.seek(SeekFrom::End(e))?,
1782        };
1783
1784        macro_rules! read_value {
1785            () => {
1786                match self.ty {
1787                    OffsetType::Byte => {
1788                        if self.signed {
1789                            read_le!(haystack, u8) as u64
1790                        } else {
1791                            read_le!(haystack, i8) as u64
1792                        }
1793                    }
1794                    OffsetType::DoubleLe => read_le!(haystack, f64) as u64,
1795                    OffsetType::DoubleBe => read_be!(haystack, f64) as u64,
1796                    OffsetType::ShortLe => {
1797                        if self.signed {
1798                            read_le!(haystack, i16) as u64
1799                        } else {
1800                            read_le!(haystack, u16) as u64
1801                        }
1802                    }
1803                    OffsetType::ShortBe => {
1804                        if self.signed {
1805                            read_be!(haystack, i16) as u64
1806                        } else {
1807                            read_be!(haystack, u16) as u64
1808                        }
1809                    }
1810                    OffsetType::Id3Le => decode_id3(read_le!(haystack, u32)) as u64,
1811                    OffsetType::Id3Be => decode_id3(read_be!(haystack, u32)) as u64,
1812                    OffsetType::LongLe => {
1813                        if self.signed {
1814                            read_le!(haystack, i32) as u64
1815                        } else {
1816                            read_le!(haystack, u32) as u64
1817                        }
1818                    }
1819                    OffsetType::LongBe => {
1820                        if self.signed {
1821                            read_be!(haystack, i32) as u64
1822                        } else {
1823                            read_be!(haystack, u32) as u64
1824                        }
1825                    }
1826                    OffsetType::Middle => read_me!(haystack) as u64,
1827                    OffsetType::Octal => {
1828                        if let Some(o) = read_octal_u64(haystack) {
1829                            o
1830                        } else {
1831                            debug!("failed to read octal offset @ {offset_address}");
1832                            return Ok(None);
1833                        }
1834                    }
1835                    OffsetType::QuadLe => {
1836                        if self.signed {
1837                            read_le!(haystack, i64) as u64
1838                        } else {
1839                            read_le!(haystack, u64)
1840                        }
1841                    }
1842                    OffsetType::QuadBe => {
1843                        if self.signed {
1844                            read_be!(haystack, i64) as u64
1845                        } else {
1846                            read_be!(haystack, u64)
1847                        }
1848                    }
1849                }
1850            };
1851        }
1852
1853        // in theory every offset read should end up in something seekable from start, so we can use u64 to store the result
1854        let o = read_value!();
1855
1856        trace!(
1857            "offset read @ {offset_address} value={o} op={:?} shift={:?}",
1858            self.op, self.shift
1859        );
1860
1861        // apply transformation
1862        if let (Some(op), Some(shift)) = (self.op, self.shift) {
1863            let shift = match shift {
1864                Shift::Direct(i) => i,
1865                Shift::Indirect(i) => {
1866                    let tmp = offset_address as i128 + i as i128;
1867                    if tmp.is_negative() {
1868                        return Ok(None);
1869                    } else {
1870                        haystack.seek(SeekFrom::Start(tmp as u64))?;
1871                    };
1872                    // NOTE: here we assume that the shift has the same
1873                    // type as the main offset !
1874                    read_value!()
1875                }
1876            };
1877
1878            match op {
1879                Op::Add => return Ok(o.checked_add(shift)),
1880                Op::Mul => return Ok(o.checked_mul(shift)),
1881                Op::Sub => return Ok(o.checked_sub(shift)),
1882                Op::Div => return Ok(o.checked_div(shift)),
1883                Op::Mod => return Ok(o.checked_rem(shift)),
1884                Op::And => return Ok(Some(o & shift)),
1885                Op::Or => return Ok(Some(o | shift)),
1886                Op::Xor => return Ok(Some(o ^ shift)),
1887            }
1888        }
1889
1890        Ok(Some(o))
1891    }
1892}
1893
1894#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1895enum DirOffset {
1896    Start(u64),
1897    // relative to the last up-level field
1898    LastUpper(i64),
1899    End(i64),
1900}
1901
1902#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1903enum Offset {
1904    Direct(DirOffset),
1905    Indirect(IndOffset),
1906}
1907
1908impl From<DirOffset> for Offset {
1909    fn from(value: DirOffset) -> Self {
1910        Self::Direct(value)
1911    }
1912}
1913
1914impl From<IndOffset> for Offset {
1915    fn from(value: IndOffset) -> Self {
1916        Self::Indirect(value)
1917    }
1918}
1919
1920impl Display for DirOffset {
1921    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1922        match self {
1923            DirOffset::Start(i) => write!(f, "{i}"),
1924            DirOffset::LastUpper(c) => write!(f, "&{c}"),
1925            DirOffset::End(e) => write!(f, "-{e}"),
1926        }
1927    }
1928}
1929
1930impl Default for DirOffset {
1931    fn default() -> Self {
1932        Self::LastUpper(0)
1933    }
1934}
1935
1936#[derive(Debug, Clone, Serialize, Deserialize)]
1937struct Match {
1938    line: usize,
1939    depth: u8,
1940    offset: Offset,
1941    test: Test,
1942    test_strength: u64,
1943    message: Option<Message>,
1944}
1945
1946impl From<Use> for Match {
1947    fn from(value: Use) -> Self {
1948        let test = Test::Use(value.switch_endianness, value.rule_name);
1949        let test_strength = test.strength();
1950        Self {
1951            line: value.line,
1952            depth: value.depth,
1953            offset: value.start_offset,
1954            test,
1955            test_strength,
1956            message: value.message,
1957        }
1958    }
1959}
1960
1961impl From<Name> for Match {
1962    fn from(value: Name) -> Self {
1963        let test = Test::Name(value.name);
1964        let test_strength = test.strength();
1965        Self {
1966            line: value.line,
1967            depth: 0,
1968            offset: Offset::Direct(DirOffset::Start(0)),
1969            test,
1970            test_strength,
1971            message: value.message,
1972        }
1973    }
1974}
1975
1976impl Match {
1977    /// Turns the `Match`'s offset into an absolute offset from the start of the stream
1978    #[inline(always)]
1979    fn offset_from_start<R: Read + Seek>(
1980        &self,
1981        haystack: &mut LazyCache<R>,
1982        rule_base_offset: Option<u64>,
1983        last_level_offset: Option<u64>,
1984    ) -> Result<Option<u64>, io::Error> {
1985        match self.offset {
1986            Offset::Direct(dir_offset) => match dir_offset {
1987                DirOffset::Start(s) => Ok(Some(s)),
1988                DirOffset::LastUpper(shift) => {
1989                    let o = last_level_offset.unwrap_or_default() as i64 + shift;
1990
1991                    if o >= 0 { Ok(Some(o as u64)) } else { Ok(None) }
1992                }
1993                DirOffset::End(e) => Ok(Some(haystack.offset_from_start(SeekFrom::End(e)))),
1994            },
1995            Offset::Indirect(ind_offset) => {
1996                let Some(o) =
1997                    ind_offset.read_offset(haystack, rule_base_offset, last_level_offset)?
1998                else {
1999                    return Ok(None);
2000                };
2001
2002                Ok(Some(o))
2003            }
2004        }
2005    }
2006
2007    /// this method emulates the buffer based matching
2008    /// logic implemented in libmagic. It needs some aweful
2009    /// and weird offset convertions to turn buffer
2010    /// relative offsets (libmagic is based on) into
2011    /// absolute offset in the file.
2012    ///
2013    /// this method shoud bubble up only critical errors
2014    /// all the other errors should make the match result
2015    /// false and be logged via debug!
2016    ///
2017    /// the function returns an error if the maximum recursion
2018    /// has been reached or if a dependency rule is missing.
2019    #[inline]
2020    #[allow(clippy::too_many_arguments)]
2021    fn matches<'a: 'h, 'h, R: Read + Seek>(
2022        &'a self,
2023        source: Option<&str>,
2024        magic: &mut Magic<'a>,
2025        stream_kind: StreamKind,
2026        state: &mut MatchState,
2027        buf_base_offset: Option<u64>,
2028        rule_base_offset: Option<u64>,
2029        last_level_offset: Option<u64>,
2030        haystack: &'h mut LazyCache<R>,
2031        switch_endianness: bool,
2032        db: &'a MagicDb,
2033        depth: usize,
2034    ) -> Result<(bool, Option<MatchRes<'h>>), Error> {
2035        let source = source.unwrap_or("unknown");
2036        let line = self.line;
2037
2038        if depth >= MAX_RECURSION {
2039            return Err(Error::localized(
2040                source,
2041                line,
2042                Error::MaximumRecursion(MAX_RECURSION),
2043            ));
2044        }
2045
2046        if self.test.is_only_binary() && stream_kind.is_text() {
2047            trace!("skip binary test source={source} line={line} stream_kind={stream_kind:?}",);
2048            return Ok((false, None));
2049        }
2050
2051        if self.test.is_only_text() && !stream_kind.is_text() {
2052            trace!("skip text test source={source} line={line} stream_kind={stream_kind:?}",);
2053            return Ok((false, None));
2054        }
2055
2056        let Ok(Some(mut offset)) = self
2057            .offset_from_start(haystack, rule_base_offset, last_level_offset)
2058            .inspect_err(|e| debug!("source={source} line={line} failed at computing offset: {e}"))
2059        else {
2060            return Ok((false, None));
2061        };
2062
2063        offset = match self.offset {
2064            Offset::Indirect(_) => {
2065                // the result we get for an indirect offset
2066                // is relative to the start of the libmagic
2067                // buffer so we need to add base to make it
2068                // absolute.
2069                buf_base_offset.unwrap_or_default().saturating_add(offset)
2070            }
2071            // offset from start are computed from rule base
2072            Offset::Direct(DirOffset::Start(_)) => {
2073                rule_base_offset.unwrap_or_default().saturating_add(offset)
2074            }
2075            _ => offset,
2076        };
2077
2078        match &self.test {
2079            Test::Clear => {
2080                trace!("source={source} line={line} clear");
2081                state.clear_continuation_level(&self.continuation_level());
2082                Ok((true, None))
2083            }
2084
2085            Test::Name(name) => {
2086                trace!(
2087                    "source={source} line={line} running rule {name} switch_endianness={switch_endianness}",
2088                );
2089                Ok((true, None))
2090            }
2091
2092            Test::Use(flip_endianness, rule_name) => {
2093                trace!(
2094                    "source={source} line={line} use {rule_name} switch_endianness={flip_endianness}",
2095                );
2096
2097                // switch_endianness must propagate down the rule call stack
2098                let switch_endianness = switch_endianness ^ flip_endianness;
2099
2100                let dr: &DependencyRule = db.dependencies.get(rule_name).ok_or(
2101                    Error::localized(source, line, Error::MissingRule(rule_name.clone())),
2102                )?;
2103
2104                // we push the message here otherwise we push message in depth first
2105                if let Some(msg) = self.message.as_ref() {
2106                    magic.push_message(msg.to_string_lossy());
2107                }
2108
2109                dr.rule.magic(
2110                    magic,
2111                    stream_kind,
2112                    buf_base_offset,
2113                    Some(offset),
2114                    haystack,
2115                    db,
2116                    switch_endianness,
2117                    depth.saturating_add(1),
2118                )?;
2119
2120                // we return false not to push message again
2121                Ok((false, None))
2122            }
2123
2124            Test::Indirect(m) => {
2125                trace!(
2126                    "source={source} line={line} indirect mods={:?} offset={offset:#x}",
2127                    m
2128                );
2129
2130                let new_buf_base_off = if m.contains(IndirectMod::Relative) {
2131                    Some(offset)
2132                } else {
2133                    None
2134                };
2135
2136                // we push the message here otherwise we push message in depth first
2137                if let Some(msg) = self.message.as_ref() {
2138                    magic.push_message(msg.to_string_lossy());
2139                }
2140
2141                for r in db.rules.iter() {
2142                    let messages_cnt = magic.message.len();
2143
2144                    r.magic(
2145                        magic,
2146                        stream_kind,
2147                        new_buf_base_off,
2148                        Some(offset),
2149                        haystack,
2150                        db,
2151                        false,
2152                        depth.saturating_add(1),
2153                    )?;
2154
2155                    // this means we matched a rule
2156                    if magic.message.len() != messages_cnt {
2157                        break;
2158                    }
2159                }
2160
2161                // we return false not to push message again
2162                Ok((false, None))
2163            }
2164
2165            Test::Default => {
2166                // default matches if nothing else at the continuation level matched
2167                let ok = !state.get_continuation_level(&self.continuation_level());
2168
2169                trace!("source={source} line={line} default match={ok}");
2170                if ok {
2171                    state.set_continuation_level(self.continuation_level());
2172                }
2173
2174                Ok((ok, None))
2175            }
2176
2177            _ => {
2178                if let Err(e) = haystack.seek(SeekFrom::Start(offset)) {
2179                    debug!("source={source} line={line} failed to seek in haystack: {e}");
2180                    return Ok((false, None));
2181                }
2182
2183                let mut trace_msg = None;
2184
2185                if enabled!(Level::DEBUG) {
2186                    trace_msg = Some(vec![format!(
2187                        "source={source} line={line} depth={} stream_offset={:#x}",
2188                        self.depth,
2189                        haystack.lazy_stream_position()
2190                    )])
2191                }
2192
2193                // NOTE: we may have a way to optimize here. In case we do a Any
2194                // test and we don't use the value to format the message, we don't
2195                // need to read the value.
2196                if let Ok(opt_test_value) = self
2197                    .test
2198                    .read_test_value(haystack, switch_endianness)
2199                    .inspect_err(|e| {
2200                        debug!("source={source} line={line} error while reading test value @{offset}: {e}",)
2201                    })
2202                {
2203                    if let Some(v) = trace_msg
2204                        .as_mut() { v.push(format!("test={:?}", self.test)) }
2205
2206                    let match_res =
2207                        opt_test_value.and_then(|tv| self.test.match_value(&tv, stream_kind));
2208
2209                    if let Some(v) = trace_msg.as_mut() { v.push(format!(
2210                            "message=\"{}\" match={}",
2211                            self.message
2212                                .as_ref()
2213                                .map(|fs| fs.to_string_lossy())
2214                                .unwrap_or_default(),
2215                            match_res.is_some()
2216                        )) }
2217
2218                    // trace message
2219                    if enabled!(Level::DEBUG) && !enabled!(Level::TRACE) && match_res.is_some() {
2220                        if let Some(m) = trace_msg{
2221                            debug!("{}", m.join(" "));
2222                        }
2223                    } else if enabled!(Level::TRACE)
2224                        && let Some(m) = trace_msg{
2225                            trace!("{}", m.join(" "));
2226                        }
2227
2228                    if let Some(mr) = match_res {
2229                        state.set_continuation_level(self.continuation_level());
2230                        return Ok((true, Some(mr)));
2231                    }
2232                }
2233
2234                Ok((false, None))
2235            }
2236        }
2237    }
2238
2239    #[inline(always)]
2240    fn continuation_level(&self) -> ContinuationLevel {
2241        ContinuationLevel(self.depth)
2242    }
2243}
2244
2245#[derive(Debug, Clone)]
2246struct Use {
2247    line: usize,
2248    depth: u8,
2249    start_offset: Offset,
2250    rule_name: String,
2251    switch_endianness: bool,
2252    message: Option<Message>,
2253}
2254
2255#[derive(Debug, Clone, Serialize, Deserialize)]
2256struct StrengthMod {
2257    op: Op,
2258    by: u8,
2259}
2260
2261impl StrengthMod {
2262    #[inline(always)]
2263    fn apply(&self, strength: u64) -> u64 {
2264        let by = self.by as u64;
2265        debug!("applying strength modifier: {strength} {} {}", self.op, by);
2266        match self.op {
2267            Op::Mul => strength.saturating_mul(by),
2268            Op::Add => strength.saturating_add(by),
2269            Op::Sub => strength.saturating_sub(by),
2270            Op::Div => {
2271                if by > 0 {
2272                    strength.saturating_div(by)
2273                } else {
2274                    strength
2275                }
2276            }
2277            Op::Mod => strength % by,
2278            Op::And => strength & by,
2279            // this should never happen as strength operators
2280            // are enforced by our parser
2281            Op::Xor | Op::Or => {
2282                debug_panic!("unsupported strength operator");
2283                strength
2284            }
2285        }
2286    }
2287}
2288
2289#[derive(Debug, Clone)]
2290enum Flag {
2291    Mime(String),
2292    Ext(HashSet<String>),
2293    Strength(StrengthMod),
2294    Apple(String),
2295}
2296
2297#[derive(Debug, Clone)]
2298struct Name {
2299    line: usize,
2300    name: String,
2301    message: Option<Message>,
2302}
2303
2304#[derive(Debug, Clone)]
2305enum Entry<'span> {
2306    Match(Span<'span>, Match),
2307    Flag(Span<'span>, Flag),
2308}
2309
2310#[derive(Debug, Clone, Serialize, Deserialize)]
2311struct EntryNode {
2312    root: bool,
2313    entry: Match,
2314    children: Vec<EntryNode>,
2315    mimetype: Option<String>,
2316    apple: Option<String>,
2317    strength_mod: Option<StrengthMod>,
2318    exts: HashSet<String>,
2319}
2320
2321impl EntryNode {
2322    fn update_exts_rec(
2323        &self,
2324        exts: &mut HashSet<String>,
2325        deps: &HashMap<String, DependencyRule>,
2326        marked: &mut HashSet<String>,
2327    ) -> Result<(), ()> {
2328        for ext in self.exts.iter() {
2329            if !exts.contains(ext) {
2330                exts.insert(ext.clone());
2331            }
2332        }
2333
2334        for c in self.children.iter() {
2335            if let Test::Use(_, ref name) = c.entry.test {
2336                if marked.contains(name) {
2337                    continue;
2338                }
2339                if let Some(r) = deps.get(name) {
2340                    marked.insert(name.clone());
2341                    exts.extend(r.rule.fetch_all_extensions(deps, marked)?);
2342                } else {
2343                    return Err(());
2344                }
2345            } else {
2346                c.update_exts_rec(exts, deps, marked)?;
2347            }
2348        }
2349
2350        Ok(())
2351    }
2352
2353    fn update_score_rec(
2354        &self,
2355        depth: usize,
2356        score: &mut u64,
2357        deps: &HashMap<String, DependencyRule>,
2358        marked: &mut HashSet<String>,
2359    ) {
2360        if depth == 3 {
2361            return;
2362        }
2363
2364        *score += self
2365            .children
2366            .iter()
2367            .map(|e| e.entry.test_strength)
2368            .min()
2369            .unwrap_or_default();
2370
2371        for c in self.children.iter() {
2372            if let Test::Use(_, ref name) = c.entry.test {
2373                if marked.contains(name) {
2374                    continue;
2375                }
2376
2377                if let Some(r) = deps.get(name) {
2378                    marked.insert(name.clone());
2379                    *score += r.rule.compute_score(depth, deps, marked);
2380                }
2381            }
2382            c.update_score_rec(depth + 1, score, deps, marked);
2383        }
2384    }
2385
2386    #[inline]
2387    #[allow(clippy::too_many_arguments)]
2388    fn matches<'r, R: Read + Seek>(
2389        &'r self,
2390        opt_source: Option<&str>,
2391        magic: &mut Magic<'r>,
2392        state: &mut MatchState,
2393        stream_kind: StreamKind,
2394        buf_base_offset: Option<u64>,
2395        rule_base_offset: Option<u64>,
2396        last_level_offset: Option<u64>,
2397        haystack: &mut LazyCache<R>,
2398        db: &'r MagicDb,
2399        switch_endianness: bool,
2400        depth: usize,
2401    ) -> Result<(), Error> {
2402        let (ok, opt_match_res) = self.entry.matches(
2403            opt_source,
2404            magic,
2405            stream_kind,
2406            state,
2407            buf_base_offset,
2408            rule_base_offset,
2409            last_level_offset,
2410            haystack,
2411            switch_endianness,
2412            db,
2413            depth,
2414        )?;
2415
2416        let source = opt_source.unwrap_or("unknown");
2417        let line = self.entry.line;
2418
2419        if ok {
2420            // update magic with message if match is successful
2421            if let Some(msg) = self.entry.message.as_ref()
2422                && let Ok(msg) = msg.format_with(opt_match_res.as_ref()).inspect_err(|e| {
2423                    debug!("source={source} line={line} failed to format message: {e}")
2424                })
2425            {
2426                magic.push_message(msg);
2427            }
2428
2429            // we need to adjust stream offset in case of regex/search tests
2430            if let Some(mr) = opt_match_res {
2431                match &self.entry.test {
2432                    Test::String(t) => {
2433                        if t.has_length_mod() {
2434                            let o = mr.end_offset();
2435                            haystack.seek(SeekFrom::Start(o))?;
2436                        }
2437                    }
2438                    Test::Search(t) => {
2439                        if t.re_mods.contains(ReMod::StartOffsetUpdate) {
2440                            let o = mr.start_offset();
2441                            haystack.seek(SeekFrom::Start(o))?;
2442                        } else {
2443                            let o = mr.end_offset();
2444                            haystack.seek(SeekFrom::Start(o))?;
2445                        }
2446                    }
2447
2448                    Test::Regex(t) => {
2449                        if t.mods.contains(ReMod::StartOffsetUpdate) {
2450                            let o = mr.start_offset();
2451                            haystack.seek(SeekFrom::Start(o))?;
2452                        } else {
2453                            let o = mr.end_offset();
2454                            haystack.seek(SeekFrom::Start(o))?;
2455                        }
2456                    }
2457                    // other types do not need offset adjustement
2458                    _ => {}
2459                }
2460            }
2461
2462            if let Some(mimetype) = self.mimetype.as_ref() {
2463                magic.set_mime_type(Cow::Borrowed(mimetype));
2464            }
2465
2466            if let Some(apple_ty) = self.apple.as_ref() {
2467                magic.set_creator_code(Cow::Borrowed(apple_ty));
2468            }
2469
2470            if !self.exts.is_empty() {
2471                magic.insert_extensions(self.exts.iter().map(|s| s.as_str()));
2472            }
2473
2474            // NOTE: here we try to implement a similar logic as in file_magic_strength.
2475            // Sticking to the exact same strength computation logic is complicated due
2476            // to implementation differences. Let's wait and see if that is a real issue.
2477            let mut strength = self.entry.test_strength;
2478
2479            let continuation_level = self.entry.continuation_level().0 as u64;
2480            if self.entry.message.is_none() && continuation_level < 3 {
2481                strength = strength.saturating_add(continuation_level);
2482            }
2483
2484            if let Some(sm) = self.strength_mod.as_ref() {
2485                strength = sm.apply(strength);
2486            }
2487
2488            // entries with no message get a bonus
2489            if self.entry.message.is_none() {
2490                strength += 1
2491            }
2492
2493            magic.update_strength(strength);
2494
2495            let end_upper_level = haystack.lazy_stream_position();
2496
2497            // we have to fix rule_base_offset if
2498            // the rule_base_starts from end otherwise it
2499            // breaks some offset computation in match
2500            // see test_offset_bug_1 and test_offset_bug_2
2501            // they implement the same test logic yet indirect
2502            // offsets have to be different so that it works
2503            // in libmagic/file
2504            let rule_base_offset = if self.root {
2505                match self.entry.offset {
2506                    Offset::Direct(DirOffset::End(o)) => {
2507                        Some(haystack.offset_from_start(SeekFrom::End(o)))
2508                    }
2509                    _ => rule_base_offset,
2510                }
2511            } else {
2512                rule_base_offset
2513            };
2514
2515            for e in self.children.iter() {
2516                e.matches(
2517                    opt_source,
2518                    magic,
2519                    state,
2520                    stream_kind,
2521                    buf_base_offset,
2522                    rule_base_offset,
2523                    Some(end_upper_level),
2524                    haystack,
2525                    db,
2526                    switch_endianness,
2527                    depth,
2528                )?
2529            }
2530        }
2531
2532        Ok(())
2533    }
2534}
2535
2536/// Represents a parsed magic rule
2537#[derive(Debug, Clone, Serialize, Deserialize)]
2538pub struct MagicRule {
2539    id: usize,
2540    source: Option<String>,
2541    entries: EntryNode,
2542    extensions: HashSet<String>,
2543    /// score used for rule ranking
2544    score: u64,
2545    finalized: bool,
2546}
2547
2548impl MagicRule {
2549    #[inline(always)]
2550    fn set_id(&mut self, id: usize) {
2551        self.id = id
2552    }
2553
2554    /// Fetches all the extensions defined in the magic rule. This
2555    /// function goes recursive and find extensions also defined in
2556    /// dependencies
2557    fn fetch_all_extensions(
2558        &self,
2559        deps: &HashMap<String, DependencyRule>,
2560        marked: &mut HashSet<String>,
2561    ) -> Result<HashSet<String>, ()> {
2562        let mut exts = HashSet::new();
2563        self.entries.update_exts_rec(&mut exts, deps, marked)?;
2564        Ok(exts)
2565    }
2566
2567    /// Computes the ranking score of a magic rule by walking
2568    /// tests recursively, dependencies included.
2569    fn compute_score(
2570        &self,
2571        depth: usize,
2572        deps: &HashMap<String, DependencyRule>,
2573        marked: &mut HashSet<String>,
2574    ) -> u64 {
2575        let mut score = 0;
2576        score += self.entries.entry.test_strength;
2577        self.entries
2578            .update_score_rec(depth, &mut score, deps, marked);
2579        score
2580    }
2581
2582    /// Finalize a rule by searching for all extensions and computing its score
2583    /// for ranking. In the `MagicRule` is already finalized it returns immediately.
2584    fn try_finalize(&mut self, deps: &HashMap<String, DependencyRule>) {
2585        if self.finalized {
2586            return;
2587        }
2588
2589        let Ok(exts) = self.fetch_all_extensions(deps, &mut HashSet::new()) else {
2590            return;
2591        };
2592
2593        self.extensions.extend(exts);
2594
2595        // fetch_all_extensions walks through all the dependencies
2596        // so there is no reason for compute_score to fail as it is walking
2597        // only some of them
2598        self.score = self.compute_score(0, deps, &mut HashSet::new());
2599        self.finalized = true
2600    }
2601
2602    #[inline]
2603    fn magic_entrypoint<'r, R: Read + Seek>(
2604        &'r self,
2605        magic: &mut Magic<'r>,
2606        stream_kind: StreamKind,
2607        haystack: &mut LazyCache<R>,
2608        db: &'r MagicDb,
2609        switch_endianness: bool,
2610        depth: usize,
2611    ) -> Result<(), Error> {
2612        self.entries.matches(
2613            self.source.as_deref(),
2614            magic,
2615            &mut MatchState::empty(),
2616            stream_kind,
2617            None,
2618            None,
2619            None,
2620            haystack,
2621            db,
2622            switch_endianness,
2623            depth,
2624        )
2625    }
2626
2627    #[inline]
2628    #[allow(clippy::too_many_arguments)]
2629    fn magic<'r, R: Read + Seek>(
2630        &'r self,
2631        magic: &mut Magic<'r>,
2632        stream_kind: StreamKind,
2633        buf_base_offset: Option<u64>,
2634        rule_base_offset: Option<u64>,
2635        haystack: &mut LazyCache<R>,
2636        db: &'r MagicDb,
2637        switch_endianness: bool,
2638        depth: usize,
2639    ) -> Result<(), Error> {
2640        self.entries.matches(
2641            self.source.as_deref(),
2642            magic,
2643            &mut MatchState::empty(),
2644            stream_kind,
2645            buf_base_offset,
2646            rule_base_offset,
2647            None,
2648            haystack,
2649            db,
2650            switch_endianness,
2651            depth,
2652        )
2653    }
2654
2655    /// Checks if the rule is for matching against text content
2656    ///
2657    /// # Returns
2658    ///
2659    /// * `bool` - True if the rule is for text files
2660    pub fn is_text(&self) -> bool {
2661        self.entries.entry.test.is_text()
2662            && self.entries.children.iter().all(|e| e.entry.test.is_text())
2663    }
2664
2665    /// Gets the rule's score used for ranking rules between them
2666    ///
2667    /// # Returns
2668    ///
2669    /// * `u64` - The rule's score
2670    #[inline(always)]
2671    pub fn score(&self) -> u64 {
2672        self.score
2673    }
2674
2675    /// Gets the rule's filename if any
2676    ///
2677    /// # Returns
2678    ///
2679    /// * `Option<&str>` - The rule's source if available
2680    #[inline(always)]
2681    pub fn source(&self) -> Option<&str> {
2682        self.source.as_deref()
2683    }
2684
2685    /// Gets the line number at which the rule is defined
2686    ///
2687    /// # Returns
2688    ///
2689    /// * `usize` - The rule's line number
2690    #[inline(always)]
2691    pub fn line(&self) -> usize {
2692        self.entries.entry.line
2693    }
2694
2695    /// Gets all the file extensions associated to the rule
2696    ///
2697    /// # Returns
2698    ///
2699    /// * `&HashSet<String>` - The set of all associated extensions
2700    #[inline(always)]
2701    pub fn extensions(&self) -> &HashSet<String> {
2702        &self.extensions
2703    }
2704}
2705
2706#[derive(Debug, Clone, Serialize, Deserialize)]
2707struct DependencyRule {
2708    name: String,
2709    rule: MagicRule,
2710}
2711
2712/// A parsed source of magic rules
2713///
2714/// # Methods
2715///
2716/// * `open` - Opens a magic file from a path
2717#[derive(Debug, Clone, Serialize, Deserialize)]
2718pub struct MagicSource {
2719    rules: Vec<MagicRule>,
2720    dependencies: HashMap<String, DependencyRule>,
2721}
2722
2723impl MagicSource {
2724    /// Opens and parses a magic file from a path
2725    ///
2726    /// # Arguments
2727    ///
2728    /// * `p` - The path to the magic file
2729    ///
2730    /// # Returns
2731    ///
2732    /// * `Result<Self, Error>` - The parsed magic file or an error
2733    pub fn open<P: AsRef<Path>>(p: P) -> Result<Self, Error> {
2734        FileMagicParser::parse_file(p)
2735    }
2736}
2737
2738#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
2739struct ContinuationLevel(u8);
2740
2741// FIXME: magic handles many more text encodings
2742#[derive(Debug, PartialEq, Eq, Clone, Copy)]
2743enum TextEncoding {
2744    Ascii,
2745    Utf8,
2746    Unknown,
2747}
2748
2749impl TextEncoding {
2750    const fn as_magic_str(&self) -> &'static str {
2751        match self {
2752            TextEncoding::Ascii => "ASCII",
2753            TextEncoding::Utf8 => "UTF-8",
2754            TextEncoding::Unknown => "Unknown",
2755        }
2756    }
2757}
2758
2759#[derive(Debug, PartialEq, Eq, Clone, Copy)]
2760enum StreamKind {
2761    Binary,
2762    Text(TextEncoding),
2763}
2764
2765impl StreamKind {
2766    const fn is_text(&self) -> bool {
2767        matches!(self, StreamKind::Text(_))
2768    }
2769}
2770
2771#[derive(Debug)]
2772struct MatchState {
2773    continuation_levels: [bool; 256],
2774}
2775
2776impl MatchState {
2777    #[inline(always)]
2778    fn empty() -> Self {
2779        MatchState {
2780            continuation_levels: [false; 256],
2781        }
2782    }
2783
2784    #[inline(always)]
2785    fn get_continuation_level(&mut self, level: &ContinuationLevel) -> bool {
2786        self.continuation_levels
2787            .get(level.0 as usize)
2788            .cloned()
2789            .unwrap_or_default()
2790    }
2791
2792    #[inline(always)]
2793    fn set_continuation_level(&mut self, level: ContinuationLevel) {
2794        if let Some(b) = self.continuation_levels.get_mut(level.0 as usize) {
2795            *b = true
2796        }
2797    }
2798
2799    #[inline(always)]
2800    fn clear_continuation_level(&mut self, level: &ContinuationLevel) {
2801        if let Some(b) = self.continuation_levels.get_mut(level.0 as usize) {
2802            *b = false;
2803        }
2804    }
2805}
2806
2807/// Represents a file magic detection result
2808#[derive(Debug, Default)]
2809pub struct Magic<'m> {
2810    stream_kind: Option<StreamKind>,
2811    source: Option<Cow<'m, str>>,
2812    message: Vec<Cow<'m, str>>,
2813    mime_type: Option<Cow<'m, str>>,
2814    creator_code: Option<Cow<'m, str>>,
2815    strength: u64,
2816    exts: HashSet<Cow<'m, str>>,
2817    is_default: bool,
2818}
2819
2820impl<'m> Magic<'m> {
2821    #[inline(always)]
2822    fn set_source(&mut self, source: Option<&'m str>) {
2823        self.source = source.map(Cow::Borrowed);
2824    }
2825
2826    #[inline(always)]
2827    fn set_stream_kind(&mut self, stream_kind: StreamKind) {
2828        self.stream_kind = Some(stream_kind)
2829    }
2830
2831    #[inline(always)]
2832    fn reset(&mut self) {
2833        self.stream_kind = None;
2834        self.source = None;
2835        self.message.clear();
2836        self.mime_type = None;
2837        self.creator_code = None;
2838        self.strength = 0;
2839        self.exts.clear();
2840        self.is_default = false;
2841    }
2842
2843    /// Converts borrowed data into owned data. This method involves
2844    /// data cloning, so you must use this method only if you need to
2845    /// extend the lifetime of a [`Magic`] struct.
2846    ///
2847    /// # Returns
2848    ///
2849    /// * `Magic<'owned>` - A new [`Magic`] with owned data
2850    #[inline]
2851    pub fn into_owned<'owned>(self) -> Magic<'owned> {
2852        Magic {
2853            stream_kind: self.stream_kind,
2854            source: self.source.map(|s| Cow::Owned(s.into_owned())),
2855            message: self
2856                .message
2857                .into_iter()
2858                .map(Cow::into_owned)
2859                .map(Cow::Owned)
2860                .collect(),
2861            mime_type: self.mime_type.map(|m| Cow::Owned(m.into_owned())),
2862            creator_code: self.creator_code.map(|m| Cow::Owned(m.into_owned())),
2863            strength: self.strength,
2864            exts: self
2865                .exts
2866                .into_iter()
2867                .map(|e| Cow::Owned(e.into_owned()))
2868                .collect(),
2869            is_default: self.is_default,
2870        }
2871    }
2872
2873    /// Gets the formatted message describing the file type
2874    ///
2875    /// # Returns
2876    ///
2877    /// * `String` - The formatted message
2878    #[inline(always)]
2879    pub fn message(&self) -> String {
2880        let mut out = String::new();
2881        for (i, m) in self.message.iter().enumerate() {
2882            if let Some(s) = m.strip_prefix(r#"\b"#) {
2883                out.push_str(s);
2884            } else {
2885                // don't put space on first string
2886                if i > 0 {
2887                    out.push(' ');
2888                }
2889                out.push_str(m);
2890            }
2891        }
2892        out
2893    }
2894
2895    /// Returns an iterator over the individual parts of the magic message
2896    ///
2897    /// A magic message is typically composed of multiple parts, each appended
2898    /// during successful magic tests. This method provides an efficient way to
2899    /// iterate over these parts without concatenating them into a new string,
2900    /// as done when calling [`Magic::message`].
2901    ///
2902    /// # Returns
2903    ///
2904    /// * `impl Iterator<Item = &str>` - An iterator yielding string slices of each message part
2905    #[inline]
2906    pub fn message_parts(&self) -> impl Iterator<Item = &str> {
2907        self.message.iter().map(|p| p.as_ref())
2908    }
2909
2910    #[inline(always)]
2911    fn update_strength(&mut self, value: u64) {
2912        self.strength = self.strength.saturating_add(value);
2913        debug!("updated strength = {:?}", self.strength)
2914    }
2915
2916    /// Gets the detected MIME type
2917    ///
2918    /// # Returns
2919    ///
2920    /// * `&str` - The MIME type or default based on stream kind
2921    #[inline(always)]
2922    pub fn mime_type(&self) -> &str {
2923        self.mime_type.as_deref().unwrap_or(match self.stream_kind {
2924            Some(StreamKind::Text(_)) => DEFAULT_TEXT_MIMETYPE,
2925            Some(StreamKind::Binary) | None => DEFAULT_BIN_MIMETYPE,
2926        })
2927    }
2928
2929    #[inline(always)]
2930    fn push_message<'a: 'm>(&mut self, msg: Cow<'a, str>) {
2931        if !msg.is_empty() {
2932            debug!("pushing message: msg={msg} len={}", msg.len());
2933            self.message.push(msg);
2934        }
2935    }
2936
2937    #[inline(always)]
2938    fn set_mime_type<'a: 'm>(&mut self, mime: Cow<'a, str>) {
2939        if self.mime_type.is_none() {
2940            debug!("insert mime: {:?}", mime);
2941            self.mime_type = Some(mime)
2942        }
2943    }
2944
2945    #[inline(always)]
2946    fn set_creator_code<'a: 'm>(&mut self, apple_ty: Cow<'a, str>) {
2947        if self.creator_code.is_none() {
2948            debug!("insert apple type: {apple_ty:?}");
2949            self.creator_code = Some(apple_ty)
2950        }
2951    }
2952
2953    #[inline(always)]
2954    fn insert_extensions<'a: 'm, I: Iterator<Item = &'a str>>(&mut self, exts: I) {
2955        if self.exts.is_empty() {
2956            self.exts.extend(exts.filter_map(|e| {
2957                if e.is_empty() {
2958                    None
2959                } else {
2960                    Some(Cow::Borrowed(e))
2961                }
2962            }));
2963        }
2964    }
2965
2966    /// Gets the confidence score of the detection. This
2967    /// value is used to sort [`Magic`] in [`MagicDb::best_magic`]
2968    /// and [`MagicDb::all_magics`].
2969    ///
2970    /// # Returns
2971    ///
2972    /// * `u64` - The confidence score attributed to that [`Magic`]
2973    #[inline(always)]
2974    pub fn strength(&self) -> u64 {
2975        self.strength
2976    }
2977
2978    /// Gets the filename where the magic rule was defined
2979    ///
2980    /// # Returns
2981    ///
2982    /// * `Option<&str>` - The source if available
2983    #[inline(always)]
2984    pub fn source(&self) -> Option<&str> {
2985        self.source.as_deref()
2986    }
2987
2988    /// Gets the Apple creator code if available
2989    ///
2990    /// # Returns
2991    ///
2992    /// * `Option<&str>` - The creator code if available
2993    #[inline(always)]
2994    pub fn creator_code(&self) -> Option<&str> {
2995        self.creator_code.as_deref()
2996    }
2997
2998    /// Gets the possible file extensions for the detected [`Magic`]
2999    ///
3000    /// # Returns
3001    ///
3002    /// * `&HashSet<Cow<'m, str>>` - The set of possible extensions
3003    #[inline(always)]
3004    pub fn extensions(&self) -> &HashSet<Cow<'m, str>> {
3005        &self.exts
3006    }
3007
3008    /// Checks if this is a default fallback detection
3009    ///
3010    /// # Returns
3011    ///
3012    /// * `bool` - True if this is a default detection
3013    #[inline(always)]
3014    pub fn is_default(&self) -> bool {
3015        self.is_default
3016    }
3017}
3018
3019/// Represents a database of [`MagicRule`]
3020#[derive(Debug, Default, Clone, Serialize, Deserialize)]
3021pub struct MagicDb {
3022    rule_id: usize,
3023    rules: Vec<MagicRule>,
3024    dependencies: HashMap<String, DependencyRule>,
3025}
3026
3027#[inline(always)]
3028/// Returns `true` if the byte stream is likely text.
3029fn is_likely_text(bytes: &[u8]) -> bool {
3030    if bytes.is_empty() {
3031        return false;
3032    }
3033
3034    let mut printable = 0f64;
3035    let mut high_bytes = 0f64; // Bytes > 0x7F (non-ASCII)
3036
3037    for byte in bytes.iter() {
3038        match byte {
3039            0x00 => return false,
3040            0x09 | 0x0A | 0x0D => printable += 1.0, // Whitespace
3041            0x20..=0x7E => printable += 1.0,        // Printable ASCII
3042            _ => high_bytes += 1.0,
3043        }
3044    }
3045
3046    let total = bytes.len() as f64;
3047    let printable_ratio = printable / total;
3048    let high_bytes_ratio = high_bytes / total;
3049
3050    // Heuristic thresholds (adjust as needed):
3051    printable_ratio > 0.85 && high_bytes_ratio < 0.20
3052}
3053
3054#[inline(always)]
3055fn guess_stream_kind<S: AsRef<[u8]>>(stream: S) -> StreamKind {
3056    let Ok(s) = str::from_utf8(stream.as_ref()) else {
3057        if is_likely_text(stream.as_ref()) {
3058            return StreamKind::Text(TextEncoding::Unknown);
3059        } else {
3060            return StreamKind::Binary;
3061        }
3062    };
3063
3064    let count = s.chars().count();
3065    let mut is_ascii = true;
3066
3067    for c in s.chars().take(count.saturating_sub(1)) {
3068        is_ascii &= c.is_ascii()
3069    }
3070
3071    if is_ascii {
3072        StreamKind::Text(TextEncoding::Ascii)
3073    } else {
3074        StreamKind::Text(TextEncoding::Utf8)
3075    }
3076}
3077
3078impl MagicDb {
3079    fn open_reader<R: Read + Seek>(f: R) -> Result<LazyCache<R>, Error> {
3080        Ok(LazyCache::<R>::from_read_seek(f)
3081            .and_then(|lc| lc.with_hot_cache(2 * FILE_BYTES_MAX))?)
3082        .map(|lc| lc.with_warm_cache(100 << 20))
3083    }
3084
3085    /// Creates a new empty database
3086    ///
3087    /// # Returns
3088    ///
3089    /// * [`MagicDb`] - A new empty database
3090    pub fn new() -> Self {
3091        Self::default()
3092    }
3093
3094    #[inline(always)]
3095    fn next_rule_id(&mut self) -> usize {
3096        let t = self.rule_id;
3097        self.rule_id += 1;
3098        t
3099    }
3100
3101    #[inline(always)]
3102    fn try_json<R: Read + Seek>(
3103        haystack: &mut LazyCache<R>,
3104        stream_kind: StreamKind,
3105        magic: &mut Magic,
3106    ) -> Result<bool, Error> {
3107        // cannot be json if content is binary
3108        if matches!(stream_kind, StreamKind::Binary) {
3109            return Ok(false);
3110        }
3111
3112        let buf = haystack.read_range(0..FILE_BYTES_MAX as u64)?.trim_ascii();
3113
3114        let Some((start, end)) = find_json_boundaries(buf) else {
3115            return Ok(false);
3116        };
3117
3118        // if anything else than whitespace before start
3119        // this is not json
3120        for c in buf[0..start].iter() {
3121            if !c.is_ascii_whitespace() {
3122                return Ok(false);
3123            }
3124        }
3125
3126        let mut is_ndjson = false;
3127
3128        trace!("maybe a json document");
3129        let ok = serde_json::from_slice::<serde_json::Value>(&buf[start..=end]).is_ok();
3130        if !ok {
3131            return Ok(false);
3132        }
3133
3134        // we are sure it is json now we must look if we are ndjson
3135        if end + 1 < buf.len() {
3136            // after first json
3137            let buf = &buf[end + 1..];
3138            if let Some((second_start, second_end)) = find_json_boundaries(buf) {
3139                // there is a new line between the two json docs
3140                if memchr(b'\n', &buf[..second_start]).is_some() {
3141                    trace!("might be ndjson");
3142                    is_ndjson = serde_json::from_slice::<serde_json::Value>(
3143                        &buf[second_start..=second_end],
3144                    )
3145                    .is_ok();
3146                }
3147            }
3148        }
3149
3150        if is_ndjson {
3151            magic.push_message(Cow::Borrowed("New Line Delimited"));
3152            magic.set_mime_type(Cow::Borrowed("application/x-ndjson"));
3153            magic.insert_extensions(["ndjson", "jsonl"].into_iter());
3154        } else {
3155            magic.set_mime_type(Cow::Borrowed("application/json"));
3156            magic.insert_extensions(["json"].into_iter());
3157        }
3158
3159        magic.push_message(Cow::Borrowed("JSON text data"));
3160        magic.set_source(Some(HARDCODED_SOURCE));
3161        magic.update_strength(HARDCODED_MAGIC_STRENGTH);
3162        Ok(true)
3163    }
3164
3165    #[inline(always)]
3166    fn try_csv<R: Read + Seek>(
3167        haystack: &mut LazyCache<R>,
3168        stream_kind: StreamKind,
3169        magic: &mut Magic,
3170    ) -> Result<bool, Error> {
3171        // cannot be csv if content is binary
3172        let StreamKind::Text(enc) = stream_kind else {
3173            return Ok(false);
3174        };
3175
3176        let buf = haystack.read_range(0..FILE_BYTES_MAX as u64)?;
3177        let mut reader = csv::Reader::from_reader(io::Cursor::new(buf));
3178        let mut records = reader.records();
3179
3180        let Some(Ok(first)) = records.next() else {
3181            return Ok(false);
3182        };
3183
3184        // very not likely a CSV otherwise all programming
3185        // languages having ; line terminator would be
3186        // considered as CSV
3187        if first.len() <= 1 {
3188            return Ok(false);
3189        }
3190
3191        // we already parsed first line
3192        let mut n = 1;
3193        for i in records.take(9) {
3194            if let Ok(rec) = i {
3195                if first.len() != rec.len() {
3196                    return Ok(false);
3197                }
3198            } else {
3199                return Ok(false);
3200            }
3201            n += 1;
3202        }
3203
3204        // we need at least 10 lines
3205        if n != 10 {
3206            return Ok(false);
3207        }
3208
3209        magic.set_mime_type(Cow::Borrowed("text/csv"));
3210        magic.push_message(Cow::Borrowed("CSV"));
3211        magic.push_message(Cow::Borrowed(enc.as_magic_str()));
3212        magic.push_message(Cow::Borrowed("text"));
3213        magic.insert_extensions(["csv"].into_iter());
3214        magic.set_source(Some(HARDCODED_SOURCE));
3215        magic.update_strength(HARDCODED_MAGIC_STRENGTH);
3216        Ok(true)
3217    }
3218
3219    #[inline(always)]
3220    fn try_tar<R: Read + Seek>(
3221        haystack: &mut LazyCache<R>,
3222        stream_kind: StreamKind,
3223        magic: &mut Magic,
3224    ) -> Result<bool, Error> {
3225        // cannot be json if content is not binary
3226        if !matches!(stream_kind, StreamKind::Binary) {
3227            return Ok(false);
3228        }
3229
3230        let buf = haystack.read_range(0..FILE_BYTES_MAX as u64)?;
3231        let mut ar = Archive::new(io::Cursor::new(buf));
3232
3233        let Ok(mut entries) = ar.entries() else {
3234            return Ok(false);
3235        };
3236
3237        let Some(Ok(first)) = entries.next() else {
3238            return Ok(false);
3239        };
3240
3241        let header = first.header();
3242
3243        if header.as_ustar().is_some() {
3244            magic.push_message(Cow::Borrowed("POSIX tar archive"));
3245        } else if header.as_gnu().is_some() {
3246            magic.push_message(Cow::Borrowed("POSIX tar archive (GNU)"));
3247        } else {
3248            magic.push_message(Cow::Borrowed("tar archive"));
3249        }
3250
3251        magic.set_mime_type(Cow::Borrowed("application/x-tar"));
3252        magic.set_source(Some(HARDCODED_SOURCE));
3253        magic.update_strength(HARDCODED_MAGIC_STRENGTH);
3254        magic.insert_extensions(["tar"].into_iter());
3255        Ok(true)
3256    }
3257
3258    #[inline(always)]
3259    fn try_hard_magic<R: Read + Seek>(
3260        haystack: &mut LazyCache<R>,
3261        stream_kind: StreamKind,
3262        magic: &mut Magic,
3263    ) -> Result<bool, Error> {
3264        Ok(Self::try_json(haystack, stream_kind, magic)?
3265            || Self::try_csv(haystack, stream_kind, magic)?
3266            || Self::try_tar(haystack, stream_kind, magic)?)
3267    }
3268
3269    #[inline(always)]
3270    fn magic_default<'m, R: Read + Seek>(
3271        haystack: &mut LazyCache<R>,
3272        stream_kind: StreamKind,
3273        magic: &mut Magic<'m>,
3274    ) -> Result<(), Error> {
3275        let buf = haystack.read_range(0..FILE_BYTES_MAX as u64)?;
3276
3277        magic.set_source(Some(HARDCODED_SOURCE));
3278        magic.set_stream_kind(stream_kind);
3279        magic.is_default = true;
3280
3281        if buf.is_empty() {
3282            magic.push_message(Cow::Borrowed("empty"));
3283            magic.set_mime_type(Cow::Borrowed(DEFAULT_BIN_MIMETYPE));
3284            return Ok(());
3285        }
3286
3287        match stream_kind {
3288            StreamKind::Binary => {
3289                magic.push_message(Cow::Borrowed("data"));
3290            }
3291            StreamKind::Text(e) => {
3292                magic.push_message(Cow::Borrowed(e.as_magic_str()));
3293                magic.push_message(Cow::Borrowed("text"));
3294            }
3295        }
3296
3297        Ok(())
3298    }
3299
3300    /// Loads rules from a [`MagicSource`]
3301    ///
3302    /// # Arguments
3303    ///
3304    /// * `mf` - The [`MagicSource`] to load rules from
3305    ///
3306    /// # Returns
3307    ///
3308    /// * `Result<&mut Self, Error>` - Self for chaining or an error
3309    pub fn load(&mut self, mf: MagicSource) -> Result<&mut Self, Error> {
3310        for rule in mf.rules.into_iter() {
3311            let mut rule = rule;
3312            rule.set_id(self.next_rule_id());
3313
3314            self.rules.push(rule);
3315        }
3316
3317        self.dependencies.extend(mf.dependencies);
3318        self.prepare();
3319        Ok(self)
3320    }
3321
3322    /// Gets all rules in the database
3323    ///
3324    /// # Returns
3325    ///
3326    /// * `&[MagicRule]` - A slice of all rules
3327    pub fn rules(&self) -> &[MagicRule] {
3328        &self.rules
3329    }
3330
3331    #[inline]
3332    fn first_magic_with_stream_kind<R: Read + Seek>(
3333        &self,
3334        haystack: &mut LazyCache<R>,
3335        stream_kind: StreamKind,
3336        extension: Option<&str>,
3337    ) -> Result<Magic<'_>, Error> {
3338        // re-using magic makes this function faster
3339        let mut magic = Magic::default();
3340
3341        if Self::try_hard_magic(haystack, stream_kind, &mut magic)? {
3342            return Ok(magic);
3343        }
3344
3345        let mut marked = vec![false; self.rules.len()];
3346
3347        macro_rules! do_magic {
3348            ($rule: expr) => {{
3349                $rule.magic_entrypoint(&mut magic, stream_kind, haystack, &self, false, 0)?;
3350
3351                if !magic.message.is_empty() {
3352                    magic.set_stream_kind(stream_kind);
3353                    magic.set_source($rule.source.as_deref());
3354                    return Ok(magic);
3355                }
3356
3357                magic.reset();
3358            }};
3359        }
3360
3361        if let Some(ext) = extension.map(|e| e.to_lowercase())
3362            && !ext.is_empty()
3363        {
3364            for rule in self.rules.iter().filter(|r| r.extensions.contains(&ext)) {
3365                do_magic!(rule);
3366                if let Some(f) = marked.get_mut(rule.id) {
3367                    *f = true
3368                }
3369            }
3370        }
3371
3372        for rule in self
3373            .rules
3374            .iter()
3375            // we don't run again rules run by extension
3376            .filter(|r| !*marked.get(r.id).unwrap_or(&false))
3377        {
3378            do_magic!(rule)
3379        }
3380
3381        Self::magic_default(haystack, stream_kind, &mut magic)?;
3382
3383        Ok(magic)
3384    }
3385
3386    /// Detects file [`Magic`] stopping at the first matching magic. Magic
3387    /// rules are evaluated from the best to the least relevant, so this method
3388    /// returns most of the time the best magic. For the rare cases where
3389    /// it doesn't or if the best result is always required, use [`MagicDb::best_magic`]
3390    ///
3391    /// # Arguments
3392    ///
3393    /// * `r` - A readable and seekable input
3394    /// * `extension` - Optional file extension to use for acceleration
3395    ///
3396    /// # Returns
3397    ///
3398    /// * `Result<Magic<'_>, Error>` - The detection result or an error
3399    pub fn first_magic<R: Read + Seek>(
3400        &self,
3401        r: &mut R,
3402        extension: Option<&str>,
3403    ) -> Result<Magic<'_>, Error> {
3404        let mut haystack = Self::open_reader(r)?;
3405        let stream_kind = guess_stream_kind(haystack.read_range(0..FILE_BYTES_MAX as u64)?);
3406        self.first_magic_with_stream_kind(&mut haystack, stream_kind, extension)
3407    }
3408
3409    #[inline(always)]
3410    fn all_magics_sort_with_stream_kind<R: Read + Seek>(
3411        &self,
3412        haystack: &mut LazyCache<R>,
3413        stream_kind: StreamKind,
3414    ) -> Result<Vec<Magic<'_>>, Error> {
3415        let mut out = Vec::new();
3416
3417        let mut magic = Magic::default();
3418
3419        if Self::try_hard_magic(haystack, stream_kind, &mut magic)? {
3420            out.push(magic);
3421            magic = Magic::default();
3422        }
3423
3424        for rule in self.rules.iter() {
3425            rule.magic_entrypoint(&mut magic, stream_kind, haystack, self, false, 0)?;
3426
3427            // it is possible we have a strength with no message
3428            if !magic.message.is_empty() {
3429                magic.set_stream_kind(stream_kind);
3430                magic.set_source(rule.source.as_deref());
3431                out.push(magic);
3432                magic = Magic::default();
3433            }
3434
3435            magic.reset();
3436        }
3437
3438        Self::magic_default(haystack, stream_kind, &mut magic)?;
3439        out.push(magic);
3440
3441        out.sort_by_key(|b| std::cmp::Reverse(b.strength()));
3442
3443        Ok(out)
3444    }
3445
3446    /// Detects all [`Magic`] matching a given content.
3447    ///
3448    /// # Arguments
3449    ///
3450    /// * `r` - A readable and seekable input
3451    ///
3452    /// # Returns
3453    ///
3454    /// * `Result<Vec<Magic<'_>>, Error>` - All detection results sorted by strength or an error
3455    pub fn all_magics<R: Read + Seek>(&self, r: &mut R) -> Result<Vec<Magic<'_>>, Error> {
3456        let mut haystack = Self::open_reader(r)?;
3457        let stream_kind = guess_stream_kind(haystack.read_range(0..FILE_BYTES_MAX as u64)?);
3458        self.all_magics_sort_with_stream_kind(&mut haystack, stream_kind)
3459    }
3460
3461    #[inline(always)]
3462    fn best_magic_with_stream_kind<R: Read + Seek>(
3463        &self,
3464        haystack: &mut LazyCache<R>,
3465        stream_kind: StreamKind,
3466    ) -> Result<Magic<'_>, Error> {
3467        let magics = self.all_magics_sort_with_stream_kind(haystack, stream_kind)?;
3468
3469        // magics is guaranteed to contain at least the default magic
3470        return Ok(magics
3471            .into_iter()
3472            .next()
3473            .expect("magics must at least contain default"));
3474    }
3475
3476    /// Detects the best [`Magic`] matching a given content.
3477    ///
3478    /// # Arguments
3479    ///
3480    /// * `r` - A readable and seekable input
3481    ///
3482    /// # Returns
3483    ///
3484    /// * `Result<Magic<'_>, Error>` - The best detection result or an error
3485    pub fn best_magic<R: Read + Seek>(&self, r: &mut R) -> Result<Magic<'_>, Error> {
3486        let mut haystack = Self::open_reader(r)?;
3487        let stream_kind = guess_stream_kind(haystack.read_range(0..FILE_BYTES_MAX as u64)?);
3488        self.best_magic_with_stream_kind(&mut haystack, stream_kind)
3489    }
3490
3491    /// Serializes the database to a generic writer implementing [`io::Write`]
3492    ///
3493    /// # Returns
3494    ///
3495    /// * `Result<(), Error>` - The serialized database or an error
3496    pub fn serialize<W: Write>(self, w: &mut W) -> Result<(), Error> {
3497        let mut encoder = GzEncoder::new(w, Compression::best());
3498
3499        bincode::serde::encode_into_std_write(&self, &mut encoder, bincode::config::standard())?;
3500        encoder.finish()?;
3501        Ok(())
3502    }
3503
3504    /// Deserializes the database from a generic reader implementing [`io::Read`]
3505    ///
3506    /// # Arguments
3507    ///
3508    /// * `r` - The reader to deserialize from
3509    ///
3510    /// # Returns
3511    ///
3512    /// * `Result<Self, Error>` - The deserialized database or an error
3513    pub fn deserialize<R: Read>(r: &mut R) -> Result<Self, Error> {
3514        let mut buf = vec![];
3515        let mut gz = GzDecoder::new(r);
3516        gz.read_to_end(&mut buf).map_err(|e| {
3517            bincode::error::DecodeError::OtherString(format!("failed to read: {e}"))
3518        })?;
3519        let (sdb, _): (MagicDb, usize) =
3520            bincode::serde::decode_from_slice(&buf, bincode::config::standard())?;
3521        Ok(sdb)
3522    }
3523
3524    #[inline(always)]
3525    fn prepare(&mut self) {
3526        self.rules
3527            .iter_mut()
3528            .for_each(|r| r.try_finalize(&self.dependencies));
3529
3530        // put text rules at the end
3531        self.rules.sort_by_key(|r| (r.is_text(), -(r.score as i64)));
3532    }
3533}
3534
3535#[cfg(test)]
3536mod tests {
3537    use std::io::Cursor;
3538
3539    use regex::bytes::Regex;
3540
3541    use crate::utils::unix_local_time_to_string;
3542
3543    use super::*;
3544
3545    macro_rules! lazy_cache {
3546        ($l: literal) => {
3547            LazyCache::from_read_seek(Cursor::new($l)).unwrap()
3548        };
3549    }
3550
3551    fn first_magic(
3552        rule: &str,
3553        content: &[u8],
3554        stream_kind: StreamKind,
3555    ) -> Result<Magic<'static>, Error> {
3556        let mut md = MagicDb::new();
3557        md.load(
3558            FileMagicParser::parse_str(rule, None)
3559                .inspect_err(|e| eprintln!("{e}"))
3560                .unwrap(),
3561        )
3562        .unwrap();
3563        let mut reader = LazyCache::from_read_seek(Cursor::new(content)).unwrap();
3564        let v = md.best_magic_with_stream_kind(&mut reader, stream_kind)?;
3565        Ok(v.into_owned())
3566    }
3567
3568    /// helper macro to debug tests
3569    #[allow(unused_macros)]
3570    macro_rules! enable_trace {
3571        () => {
3572            tracing_subscriber::fmt()
3573                .with_max_level(tracing_subscriber::filter::LevelFilter::TRACE)
3574                .try_init();
3575        };
3576    }
3577
3578    macro_rules! parse_assert {
3579        ($rule:literal) => {
3580            FileMagicParser::parse_str($rule, None)
3581                .inspect_err(|e| eprintln!("{e}"))
3582                .unwrap();
3583        };
3584    }
3585
3586    macro_rules! assert_magic_match_bin {
3587        ($rule: literal, $content:literal) => {{ first_magic($rule, $content, StreamKind::Binary).unwrap() }};
3588        ($rule: literal, $content:literal, $message:expr) => {{
3589            assert_eq!(
3590                first_magic($rule, $content, StreamKind::Binary)
3591                    .unwrap()
3592                    .message(),
3593                $message
3594            );
3595        }};
3596    }
3597
3598    macro_rules! assert_magic_match_text {
3599        ($rule: literal, $content:literal) => {{ first_magic($rule, $content, StreamKind::Text(TextEncoding::Utf8)).unwrap() }};
3600        ($rule: literal, $content:literal, $message:expr) => {{
3601            assert_eq!(
3602                first_magic($rule, $content, StreamKind::Text(TextEncoding::Utf8))
3603                    .unwrap()
3604                    .message(),
3605                $message
3606            );
3607        }};
3608    }
3609
3610    macro_rules! assert_magic_not_match_text {
3611        ($rule: literal, $content:literal) => {{
3612            assert!(
3613                first_magic($rule, $content, StreamKind::Text(TextEncoding::Utf8))
3614                    .unwrap()
3615                    .is_default()
3616            );
3617        }};
3618    }
3619
3620    macro_rules! assert_magic_not_match_bin {
3621        ($rule: literal, $content:literal) => {{
3622            assert!(
3623                first_magic($rule, $content, StreamKind::Binary)
3624                    .unwrap()
3625                    .is_default()
3626            );
3627        }};
3628    }
3629
3630    #[test]
3631    fn test_regex() {
3632        assert_magic_match_text!(
3633            r#"
36340	regex/1024 \^#![[:space:]]*/usr/bin/env[[:space:]]+
3635!:mime	text/x-shellscript
3636>&0  regex/64 .*($|\\b) %s shell script text executable
3637    "#,
3638            br#"#!/usr/bin/env bash
3639        echo hello world"#,
3640            // the magic generated
3641            "bash shell script text executable"
3642        );
3643
3644        let re = Regex::new(r"(?-u)\x42\x82").unwrap();
3645        assert!(re.is_match(b"\x42\x82"));
3646
3647        assert_magic_match_bin!(
3648            r#"0 regex \x42\x82 binary regex match"#,
3649            b"\x00\x00\x00\x00\x00\x00\x42\x82"
3650        );
3651
3652        // test regex continuation after match
3653        assert_magic_match_bin!(
3654            r#"
3655            0 regex \x42\x82
3656            >&0 string \xde\xad\xbe\xef it works
3657            "#,
3658            b"\x00\x00\x00\x00\x00\x00\x42\x82\xde\xad\xbe\xef"
3659        );
3660
3661        assert_magic_match_bin!(
3662            r#"
3663            0 regex/s \x42\x82
3664            >&0 string \x42\x82\xde\xad\xbe\xef it works
3665            "#,
3666            b"\x00\x00\x00\x00\x00\x00\x42\x82\xde\xad\xbe\xef"
3667        );
3668
3669        // ^ must match stat of line when matching text
3670        assert_magic_match_text!(
3671            r#"
36720	regex/1024 \^HelloWorld$ HelloWorld String"#,
3673            br#"
3674// this is a comment after an empty line
3675HelloWorld
3676            "#
3677        );
3678    }
3679
3680    #[test]
3681    fn test_string_with_mods() {
3682        assert_magic_match_text!(
3683            r#"0	string/w	#!\ \ \ /usr/bin/env\ bash	BASH
3684        "#,
3685            b"#! /usr/bin/env bash i
3686        echo hello world"
3687        );
3688
3689        // test uppercase insensitive
3690        assert_magic_match_text!(
3691            r#"0	string/C	HelloWorld	it works
3692        "#,
3693            b"helloworld"
3694        );
3695
3696        assert_magic_not_match_text!(
3697            r#"0	string/C	HelloWorld	it works
3698        "#,
3699            b"hELLOwORLD"
3700        );
3701
3702        // test lowercase insensitive
3703        assert_magic_match_text!(
3704            r#"0	string/c	HelloWorld	it works
3705        "#,
3706            b"HELLOWORLD"
3707        );
3708
3709        assert_magic_not_match_text!(
3710            r#"0	string/c	HelloWorld	it works
3711        "#,
3712            b"helloworld"
3713        );
3714
3715        // test full word match
3716        assert_magic_match_text!(
3717            r#"0	string/f	#!/usr/bin/env\ bash	BASH
3718        "#,
3719            b"#!/usr/bin/env bash"
3720        );
3721
3722        assert_magic_not_match_text!(
3723            r#"0	string/f	#!/usr/bin/python PYTHON"#,
3724            b"#!/usr/bin/pythonic"
3725        );
3726
3727        // testing whitespace compacting
3728        assert_magic_match_text!(
3729            r#"0	string/W	#!/usr/bin/env\ python  PYTHON"#,
3730            b"#!/usr/bin/env    python"
3731        );
3732
3733        assert_magic_not_match_text!(
3734            r#"0	string/W	#!/usr/bin/env\ \ python  PYTHON"#,
3735            b"#!/usr/bin/env python"
3736        );
3737    }
3738
3739    #[test]
3740    fn test_search_with_mods() {
3741        assert_magic_match_text!(
3742            r#"0	search/1/fwt	#!\ /usr/bin/luatex	LuaTex script text executable"#,
3743            b"#!          /usr/bin/luatex "
3744        );
3745
3746        // test matching from the beginning
3747        assert_magic_match_text!(
3748            r#"
3749            0	search/s	/usr/bin/env
3750            >&0 string /usr/bin/env it works
3751            "#,
3752            b"#!/usr/bin/env    python"
3753        );
3754
3755        assert_magic_not_match_text!(
3756            r#"
3757            0	search	/usr/bin/env
3758            >&0 string /usr/bin/env it works
3759            "#,
3760            b"#!/usr/bin/env    python"
3761        );
3762    }
3763
3764    #[test]
3765    fn test_pstring() {
3766        assert_magic_match_bin!(r#"0 pstring Toast it works"#, b"\x05Toast");
3767
3768        assert_magic_match_bin!(r#"0 pstring Toast %s"#, b"\x05Toast", "Toast");
3769
3770        assert_magic_not_match_bin!(r#"0 pstring Toast Doesn't work"#, b"\x07Toaster");
3771
3772        // testing with modifiers
3773        assert_magic_match_bin!(r#"0 pstring/H Toast it works"#, b"\x00\x05Toast");
3774
3775        assert_magic_match_bin!(r#"0 pstring/HJ Toast it works"#, b"\x00\x07Toast");
3776
3777        assert_magic_match_bin!(r#"0 pstring/HJ Toast %s"#, b"\x00\x07Toast", "Toast");
3778
3779        assert_magic_match_bin!(r#"0 pstring/h Toast it works"#, b"\x05\x00Toast");
3780
3781        assert_magic_match_bin!(r#"0 pstring/hJ Toast it works"#, b"\x07\x00Toast");
3782
3783        assert_magic_match_bin!(r#"0 pstring/L Toast it works"#, b"\x00\x00\x00\x05Toast");
3784
3785        assert_magic_match_bin!(r#"0 pstring/LJ Toast it works"#, b"\x00\x00\x00\x09Toast");
3786
3787        assert_magic_match_bin!(r#"0 pstring/l Toast it works"#, b"\x05\x00\x00\x00Toast");
3788
3789        assert_magic_match_bin!(r#"0 pstring/lJ Toast it works"#, b"\x09\x00\x00\x00Toast");
3790    }
3791
3792    #[test]
3793    fn test_max_recursion() {
3794        let res = first_magic(
3795            r#"0	indirect x"#,
3796            b"#!          /usr/bin/luatex ",
3797            StreamKind::Binary,
3798        );
3799        assert!(res.is_err());
3800        let _ = res.inspect_err(|e| {
3801            assert!(matches!(
3802                e.unwrap_localized(),
3803                Error::MaximumRecursion(MAX_RECURSION)
3804            ))
3805        });
3806    }
3807
3808    #[test]
3809    fn test_string_ops() {
3810        assert_magic_match_text!("0	string/b MZ MZ File", b"MZ\0");
3811        assert_magic_match_text!("0	string !MZ Not MZ File", b"AZ\0");
3812        assert_magic_match_text!("0	string >\0 Any String", b"A\0");
3813        assert_magic_match_text!("0	string >Test Any String", b"Test 1\0");
3814        assert_magic_match_text!("0	string <Test Any String", b"\0");
3815        assert_magic_not_match_text!("0	string >Test Any String", b"\0");
3816    }
3817
3818    #[test]
3819    fn test_lestring16() {
3820        assert_magic_match_bin!(
3821            "0 lestring16 abcd Little-endian UTF-16 string",
3822            b"\x61\x00\x62\x00\x63\x00\x64\x00"
3823        );
3824        assert_magic_match_bin!(
3825            "0 lestring16 x %s",
3826            b"\x61\x00\x62\x00\x63\x00\x64\x00\x00",
3827            "abcd"
3828        );
3829        assert_magic_not_match_bin!(
3830            "0 lestring16 abcd Little-endian UTF-16 string",
3831            b"\x00\x61\x00\x62\x00\x63\x00\x64"
3832        );
3833        assert_magic_match_bin!(
3834            "4 lestring16 abcd Little-endian UTF-16 string",
3835            b"\x00\x00\x00\x00\x61\x00\x62\x00\x63\x00\x64\x00"
3836        );
3837    }
3838
3839    #[test]
3840    fn test_bestring16() {
3841        assert_magic_match_bin!(
3842            "0 bestring16 abcd Big-endian UTF-16 string",
3843            b"\x00\x61\x00\x62\x00\x63\x00\x64"
3844        );
3845        assert_magic_match_bin!(
3846            "0 bestring16 x %s",
3847            b"\x00\x61\x00\x62\x00\x63\x00\x64",
3848            "abcd"
3849        );
3850        assert_magic_not_match_bin!(
3851            "0 bestring16 abcd Big-endian UTF-16 string",
3852            b"\x61\x00\x62\x00\x63\x00\x64\x00"
3853        );
3854        assert_magic_match_bin!(
3855            "4 bestring16 abcd Big-endian UTF-16 string",
3856            b"\x00\x00\x00\x00\x00\x61\x00\x62\x00\x63\x00\x64"
3857        );
3858    }
3859
3860    #[test]
3861    fn test_offset_from_end() {
3862        assert_magic_match_bin!("-1 ubyte 0x42 last byte ok", b"\x00\x00\x42");
3863        assert_magic_match_bin!("-2 ubyte 0x41 last byte ok", b"\x00\x41\x00");
3864    }
3865
3866    #[test]
3867    fn test_relative_offset() {
3868        assert_magic_match_bin!(
3869            "
3870            0 ubyte 0x42
3871            >&0 ubyte 0x00
3872            >>&0 ubyte 0x41 third byte ok
3873            ",
3874            b"\x42\x00\x41\x00"
3875        );
3876    }
3877
3878    #[test]
3879    fn test_indirect_offset() {
3880        assert_magic_match_bin!("(0.l) ubyte 0x42 it works", b"\x04\x00\x00\x00\x42");
3881        // adding fixed value to offset
3882        assert_magic_match_bin!("(0.l+3) ubyte 0x42 it works", b"\x01\x00\x00\x00\x42");
3883        // testing offset pair
3884        assert_magic_match_bin!(
3885            "(0.l+(4)) ubyte 0x42 it works",
3886            b"\x04\x00\x00\x00\x04\x00\x00\x00\x42"
3887        );
3888    }
3889
3890    #[test]
3891    fn test_use_with_message() {
3892        assert_magic_match_bin!(
3893            r#"
38940 string MZ
3895>0 use mz first match
3896
38970 name mz then second match
3898>0 string MZ
3899"#,
3900            b"MZ\0",
3901            "first match then second match"
3902        );
3903    }
3904
3905    #[test]
3906    fn test_scalar_transform() {
3907        assert_magic_match_bin!("0 ubyte+1 0x1 add works", b"\x00");
3908        assert_magic_match_bin!("0 ubyte-1 0xfe sub works", b"\xff");
3909        assert_magic_match_bin!("0 ubyte%2 0 mod works", b"\x0a");
3910        assert_magic_match_bin!("0 ubyte&0x0f 0x0f bitand works", b"\xff");
3911        assert_magic_match_bin!("0 ubyte|0x0f 0xff bitor works", b"\xf0");
3912        assert_magic_match_bin!("0 ubyte^0x0f 0xf0 bitxor works", b"\xff");
3913
3914        FileMagicParser::parse_str("0 ubyte%0 mod by zero", None)
3915            .expect_err("expect div by zero error");
3916        FileMagicParser::parse_str("0 ubyte/0 div by zero", None)
3917            .expect_err("expect div by zero error");
3918    }
3919
3920    #[test]
3921    fn test_belong() {
3922        // Test that a file with a four-byte value at offset 0 that matches the given value in big-endian byte order
3923        assert_magic_match_bin!("0 belong 0x12345678 Big-endian long", b"\x12\x34\x56\x78");
3924        // Test that a file with a four-byte value at offset 0 that does not match the given value in big-endian byte order
3925        assert_magic_not_match_bin!("0 belong 0x12345678 Big-endian long", b"\x78\x56\x34\x12");
3926        // Test that a file with a four-byte value at a non-zero offset that matches the given value in big-endian byte order
3927        assert_magic_match_bin!(
3928            "4 belong 0x12345678 Big-endian long",
3929            b"\x00\x00\x00\x00\x12\x34\x56\x78"
3930        );
3931        // Test < operator
3932        assert_magic_match_bin!("0 belong <0x12345678 Big-endian long", b"\x12\x34\x56\x77");
3933        assert_magic_not_match_bin!("0 belong <0x12345678 Big-endian long", b"\x12\x34\x56\x78");
3934
3935        // Test > operator
3936        assert_magic_match_bin!("0 belong >0x12345678 Big-endian long", b"\x12\x34\x56\x79");
3937        assert_magic_not_match_bin!("0 belong >0x12345678 Big-endian long", b"\x12\x34\x56\x78");
3938
3939        // Test & operator
3940        assert_magic_match_bin!("0 belong &0x5678 Big-endian long", b"\x00\x00\x56\x78");
3941        assert_magic_not_match_bin!("0 belong &0x0000FFFF Big-endian long", b"\x12\x34\x56\x78");
3942
3943        // Test ^ operator (bitwise AND with complement)
3944        assert_magic_match_bin!("0 belong ^0xFFFF0000 Big-endian long", b"\x00\x00\x56\x78");
3945        assert_magic_not_match_bin!("0 belong ^0xFFFF0000 Big-endian long", b"\x00\x01\x56\x78");
3946
3947        // Test ~ operator
3948        assert_magic_match_bin!("0 belong ~0x12345678 Big-endian long", b"\xed\xcb\xa9\x87");
3949        assert_magic_not_match_bin!("0 belong ~0x12345678 Big-endian long", b"\x12\x34\x56\x78");
3950
3951        // Test x operator
3952        assert_magic_match_bin!("0 belong x Big-endian long", b"\x12\x34\x56\x78");
3953        assert_magic_match_bin!("0 belong x Big-endian long", b"\x78\x56\x34\x12");
3954    }
3955
3956    #[test]
3957    fn test_parse_search() {
3958        parse_assert!("0 search test");
3959        parse_assert!("0 search/24/s test");
3960        parse_assert!("0 search/s/24 test");
3961    }
3962
3963    #[test]
3964    fn test_bedate() {
3965        assert_magic_match_bin!(
3966            "0 bedate 946684800 Unix date (Jan 1, 2000)",
3967            b"\x38\x6D\x43\x80"
3968        );
3969        assert_magic_not_match_bin!(
3970            "0 bedate 946684800 Unix date (Jan 1, 2000)",
3971            b"\x00\x00\x00\x00"
3972        );
3973        assert_magic_match_bin!(
3974            "4 bedate 946684800 %s",
3975            b"\x00\x00\x00\x00\x38\x6D\x43\x80",
3976            "2000-01-01 00:00:00"
3977        );
3978    }
3979    #[test]
3980    fn test_beldate() {
3981        assert_magic_match_bin!(
3982            "0 beldate 946684800 Local date (Jan 1, 2000)",
3983            b"\x38\x6D\x43\x80"
3984        );
3985        assert_magic_not_match_bin!(
3986            "0 beldate 946684800 Local date (Jan 1, 2000)",
3987            b"\x00\x00\x00\x00"
3988        );
3989
3990        assert_magic_match_bin!(
3991            "4 beldate 946684800 {}",
3992            b"\x00\x00\x00\x00\x38\x6D\x43\x80",
3993            unix_local_time_to_string(946684800)
3994        );
3995    }
3996
3997    #[test]
3998    fn test_beqdate() {
3999        assert_magic_match_bin!(
4000            "0 beqdate 946684800 Unix date (Jan 1, 2000)",
4001            b"\x00\x00\x00\x00\x38\x6D\x43\x80"
4002        );
4003
4004        assert_magic_not_match_bin!(
4005            "0 beqdate 946684800 Unix date (Jan 1, 2000)",
4006            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4007        );
4008
4009        assert_magic_match_bin!(
4010            "0 beqdate 946684800 %s",
4011            b"\x00\x00\x00\x00\x38\x6D\x43\x80",
4012            "2000-01-01 00:00:00"
4013        );
4014    }
4015
4016    #[test]
4017    fn test_medate() {
4018        assert_magic_match_bin!(
4019            "0 medate 946684800 Unix date (Jan 1, 2000)",
4020            b"\x6D\x38\x80\x43"
4021        );
4022
4023        assert_magic_not_match_bin!(
4024            "0 medate 946684800 Unix date (Jan 1, 2000)",
4025            b"\x00\x00\x00\x00"
4026        );
4027
4028        assert_magic_match_bin!(
4029            "4 medate 946684800 %s",
4030            b"\x00\x00\x00\x00\x6D\x38\x80\x43",
4031            "2000-01-01 00:00:00"
4032        );
4033    }
4034
4035    #[test]
4036    fn test_meldate() {
4037        assert_magic_match_bin!(
4038            "0 meldate 946684800 Local date (Jan 1, 2000)",
4039            b"\x6D\x38\x80\x43"
4040        );
4041        assert_magic_not_match_bin!(
4042            "0 meldate 946684800 Local date (Jan 1, 2000)",
4043            b"\x00\x00\x00\x00"
4044        );
4045
4046        assert_magic_match_bin!(
4047            "4 meldate 946684800 %s",
4048            b"\x00\x00\x00\x00\x6D\x38\x80\x43",
4049            unix_local_time_to_string(946684800)
4050        );
4051    }
4052
4053    #[test]
4054    fn test_date() {
4055        assert_magic_match_bin!(
4056            "0 date 946684800 Local date (Jan 1, 2000)",
4057            b"\x80\x43\x6D\x38"
4058        );
4059        assert_magic_not_match_bin!(
4060            "0 date 946684800 Local date (Jan 1, 2000)",
4061            b"\x00\x00\x00\x00"
4062        );
4063        assert_magic_match_bin!(
4064            "4 date 946684800 {}",
4065            b"\x00\x00\x00\x00\x80\x43\x6D\x38",
4066            "2000-01-01 00:00:00"
4067        );
4068    }
4069
4070    #[test]
4071    fn test_leldate() {
4072        assert_magic_match_bin!(
4073            "0 leldate 946684800 Local date (Jan 1, 2000)",
4074            b"\x80\x43\x6D\x38"
4075        );
4076        assert_magic_not_match_bin!(
4077            "0 leldate 946684800 Local date (Jan 1, 2000)",
4078            b"\x00\x00\x00\x00"
4079        );
4080        assert_magic_match_bin!(
4081            "4 leldate 946684800 {}",
4082            b"\x00\x00\x00\x00\x80\x43\x6D\x38",
4083            unix_local_time_to_string(946684800)
4084        );
4085    }
4086
4087    #[test]
4088    fn test_leqdate() {
4089        assert_magic_match_bin!(
4090            "0 leqdate 1577836800 Unix date (Jan 1, 2020)",
4091            b"\x00\xe1\x0b\x5E\x00\x00\x00\x00"
4092        );
4093
4094        assert_magic_not_match_bin!(
4095            "0 leqdate 1577836800 Unix date (Jan 1, 2020)",
4096            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4097        );
4098        assert_magic_match_bin!(
4099            "8 leqdate 1577836800 %s",
4100            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\xE1\x0B\x5E\x00\x00\x00\x00",
4101            "2020-01-01 00:00:00"
4102        );
4103    }
4104
4105    #[test]
4106    fn test_leqldate() {
4107        assert_magic_match_bin!(
4108            "0 leqldate 1577836800 Unix date (Jan 1, 2020)",
4109            b"\x00\xe1\x0b\x5E\x00\x00\x00\x00"
4110        );
4111
4112        assert_magic_not_match_bin!(
4113            "0 leqldate 1577836800 Unix date (Jan 1, 2020)",
4114            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4115        );
4116        assert_magic_match_bin!(
4117            "8 leqldate 1577836800 %s",
4118            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\xE1\x0B\x5E\x00\x00\x00\x00",
4119            unix_local_time_to_string(1577836800)
4120        );
4121    }
4122
4123    #[test]
4124    fn test_melong() {
4125        // Test = operator
4126        assert_magic_match_bin!(
4127            "0 melong =0x12345678 Middle-endian long",
4128            b"\x34\x12\x78\x56"
4129        );
4130        assert_magic_not_match_bin!(
4131            "0 melong =0x12345678 Middle-endian long",
4132            b"\x00\x00\x00\x00"
4133        );
4134
4135        // Test < operator
4136        assert_magic_match_bin!(
4137            "0 melong <0x12345678 Middle-endian long",
4138            b"\x34\x12\x78\x55"
4139        ); // 0x12345677 in middle-endian
4140        assert_magic_not_match_bin!(
4141            "0 melong <0x12345678 Middle-endian long",
4142            b"\x34\x12\x78\x56"
4143        ); // 0x12345678 in middle-endian
4144
4145        // Test > operator
4146        assert_magic_match_bin!(
4147            "0 melong >0x12345678 Middle-endian long",
4148            b"\x34\x12\x78\x57"
4149        ); // 0x12345679 in middle-endian
4150        assert_magic_not_match_bin!(
4151            "0 melong >0x12345678 Middle-endian long",
4152            b"\x34\x12\x78\x56"
4153        ); // 0x12345678 in middle-endian
4154
4155        // Test & operator
4156        assert_magic_match_bin!("0 melong &0x5678 Middle-endian long", b"\xab\xcd\x78\x56"); // 0x00007856 in middle-endian
4157        assert_magic_not_match_bin!(
4158            "0 melong &0x0000FFFF Middle-endian long",
4159            b"\x34\x12\x78\x56"
4160        ); // 0x12347856 in middle-endian
4161
4162        // Test ^ operator (bitwise AND with complement)
4163        assert_magic_match_bin!(
4164            "0 melong ^0xFFFF0000 Middle-endian long",
4165            b"\x00\x00\x78\x56"
4166        ); // 0x00007856 in middle-endian
4167        assert_magic_not_match_bin!(
4168            "0 melong ^0xFFFF0000 Middle-endian long",
4169            b"\x00\x01\x78\x56"
4170        ); // 0x00017856 in middle-endian
4171
4172        // Test ~ operator
4173        assert_magic_match_bin!(
4174            "0 melong ~0x12345678 Middle-endian long",
4175            b"\xCB\xED\x87\xA9"
4176        );
4177        assert_magic_not_match_bin!(
4178            "0 melong ~0x12345678 Middle-endian long",
4179            b"\x34\x12\x78\x56"
4180        ); // The original value
4181
4182        // Test x operator
4183        assert_magic_match_bin!("0 melong x Middle-endian long", b"\x34\x12\x78\x56");
4184        assert_magic_match_bin!("0 melong x Middle-endian long", b"\x00\x00\x00\x00");
4185    }
4186
4187    #[test]
4188    fn test_uquad() {
4189        // Test = operator
4190        assert_magic_match_bin!(
4191            "0 uquad =0x123456789ABCDEF0 Unsigned quad",
4192            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4193        );
4194        assert_magic_not_match_bin!(
4195            "0 uquad =0x123456789ABCDEF0 Unsigned quad",
4196            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4197        );
4198
4199        // Test < operator
4200        assert_magic_match_bin!(
4201            "0 uquad <0x123456789ABCDEF0 Unsigned quad",
4202            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x11"
4203        );
4204        assert_magic_not_match_bin!(
4205            "0 uquad <0x123456789ABCDEF0 Unsigned quad",
4206            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4207        );
4208
4209        // Test > operator
4210        assert_magic_match_bin!(
4211            "0 uquad >0x123456789ABCDEF0 Unsigned quad",
4212            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x13"
4213        );
4214        assert_magic_not_match_bin!(
4215            "0 uquad >0x123456789ABCDEF0 Unsigned quad",
4216            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4217        );
4218
4219        // Test & operator
4220        assert_magic_match_bin!(
4221            "0 uquad &0xF0 Unsigned quad",
4222            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4223        );
4224        assert_magic_not_match_bin!(
4225            "0 uquad &0xFF Unsigned quad",
4226            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4227        );
4228
4229        // Test ^ operator (bitwise AND with complement)
4230        assert_magic_match_bin!(
4231            "0 uquad ^0xFFFFFFFFFFFFFFFF Unsigned quad",
4232            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4233        ); // All bits clear
4234        assert_magic_not_match_bin!(
4235            "0 uquad ^0xFFFFFFFFFFFFFFFF Unsigned quad",
4236            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4237        ); // Some bits set
4238
4239        // Test ~ operator
4240        assert_magic_match_bin!(
4241            "0 uquad ~0x123456789ABCDEF0 Unsigned quad",
4242            b"\x0F\x21\x43\x65\x87\xA9\xCB\xED"
4243        );
4244        assert_magic_not_match_bin!(
4245            "0 uquad ~0x123456789ABCDEF0 Unsigned quad",
4246            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12"
4247        ); // The original value
4248
4249        // Test x operator
4250        assert_magic_match_bin!(
4251            "0 uquad x {:#x}",
4252            b"\xF0\xDE\xBC\x9A\x78\x56\x34\x12",
4253            "0x123456789abcdef0"
4254        );
4255        assert_magic_match_bin!(
4256            "0 uquad x Unsigned quad",
4257            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4258        );
4259    }
4260
4261    #[test]
4262    fn test_guid() {
4263        assert_magic_match_bin!(
4264            "0 guid EC959539-6786-2D4E-8FDB-98814CE76C1E It works",
4265            b"\xEC\x95\x95\x39\x67\x86\x2D\x4E\x8F\xDB\x98\x81\x4C\xE7\x6C\x1E"
4266        );
4267
4268        assert_magic_not_match_bin!(
4269            "0 guid 399595EC-8667-4E2D-8FDB-98814CE76C1E It works",
4270            b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
4271        );
4272
4273        assert_magic_match_bin!(
4274            "0 guid x %s",
4275            b"\xEC\x95\x95\x39\x67\x86\x2D\x4E\x8F\xDB\x98\x81\x4C\xE7\x6C\x1E",
4276            "EC959539-6786-2D4E-8FDB-98814CE76C1E"
4277        );
4278    }
4279
4280    #[test]
4281    fn test_ubeqdate() {
4282        assert_magic_match_bin!(
4283            "0 ubeqdate 1633046400 It works",
4284            b"\x00\x00\x00\x00\x61\x56\x4f\x80"
4285        );
4286
4287        assert_magic_match_bin!(
4288            "0 ubeqdate x %s",
4289            b"\x00\x00\x00\x00\x61\x56\x4f\x80",
4290            "2021-10-01 00:00:00"
4291        );
4292
4293        assert_magic_not_match_bin!(
4294            "0 ubeqdate 1633046400 It should not work",
4295            b"\x00\x00\x00\x00\x00\x00\x00\x00"
4296        );
4297    }
4298
4299    #[test]
4300    fn test_ldate() {
4301        assert_magic_match_bin!("0 ldate 1640551520 It works", b"\x60\xd4\xC8\x61");
4302
4303        assert_magic_not_match_bin!("0 ldate 1633046400 It should not work", b"\x00\x00\x00\x00");
4304
4305        assert_magic_match_bin!(
4306            "0 ldate x %s",
4307            b"\x60\xd4\xC8\x61",
4308            unix_local_time_to_string(1640551520)
4309        );
4310    }
4311
4312    #[test]
4313    fn test_scalar_with_transform() {
4314        assert_magic_match_bin!("0 ubyte/10 2 {}", b"\x14", "2");
4315        assert_magic_match_bin!("0 ubyte/10 x {}", b"\x14", "2");
4316        assert_magic_match_bin!("0 ubyte%10 x {}", b"\x14", "0");
4317    }
4318
4319    #[test]
4320    fn test_float_with_transform() {
4321        assert_magic_match_bin!("0 lefloat/10 2 {}", b"\x00\x00\xa0\x41", "2");
4322        assert_magic_match_bin!("0 lefloat/10 x {}", b"\x00\x00\xa0\x41", "2");
4323        assert_magic_match_bin!("0 lefloat%10 x {}", b"\x00\x00\xa0\x41", "0");
4324    }
4325
4326    #[test]
4327    fn test_read_octal() {
4328        // Basic cases
4329        assert_eq!(read_octal_u64(&mut lazy_cache!("0")), Some(0));
4330        assert_eq!(read_octal_u64(&mut lazy_cache!("00")), Some(0));
4331        assert_eq!(read_octal_u64(&mut lazy_cache!("01")), Some(1));
4332        assert_eq!(read_octal_u64(&mut lazy_cache!("07")), Some(7));
4333        assert_eq!(read_octal_u64(&mut lazy_cache!("010")), Some(8));
4334        assert_eq!(read_octal_u64(&mut lazy_cache!("0123")), Some(83));
4335        assert_eq!(read_octal_u64(&mut lazy_cache!("0755")), Some(493));
4336
4337        // With trailing non-octal characters
4338        assert_eq!(read_octal_u64(&mut lazy_cache!("0ABC")), Some(0));
4339        assert_eq!(read_octal_u64(&mut lazy_cache!("01ABC")), Some(1));
4340        assert_eq!(read_octal_u64(&mut lazy_cache!("0755ABC")), Some(493));
4341        assert_eq!(read_octal_u64(&mut lazy_cache!("0123ABC")), Some(83));
4342
4343        // Invalid octal digits
4344        assert_eq!(read_octal_u64(&mut lazy_cache!("08")), Some(0)); // stops at '8'
4345        assert_eq!(read_octal_u64(&mut lazy_cache!("01238")), Some(83)); // stops at '8'
4346
4347        // No leading '0'
4348        assert_eq!(read_octal_u64(&mut lazy_cache!("123")), None);
4349        assert_eq!(read_octal_u64(&mut lazy_cache!("755")), None);
4350
4351        // Empty string
4352        assert_eq!(read_octal_u64(&mut lazy_cache!("")), None);
4353
4354        // Only non-octal characters
4355        assert_eq!(read_octal_u64(&mut lazy_cache!("ABC")), None);
4356        assert_eq!(read_octal_u64(&mut lazy_cache!("8ABC")), None); // first char is not '0'
4357
4358        // Longer valid octal (but within u64 range)
4359        assert_eq!(
4360            read_octal_u64(&mut lazy_cache!("01777777777")),
4361            Some(268435455)
4362        );
4363    }
4364
4365    #[test]
4366    fn test_offset_bug_1() {
4367        // this tests the exact behaviour
4368        // expected by libmagic/file
4369        assert_magic_match_bin!(
4370            r"
43711	string		TEST Bread is
4372# offset computation is relative to
4373# rule start
4374>(5.b)	use toasted
4375
43760 name toasted
4377>0	string twice Toasted
4378>>0  use toasted_twice 
4379
43800 name toasted_twice
4381>(6.b) string x %s
4382        ",
4383            b"\x00TEST\x06twice\x00\x06",
4384            "Bread is Toasted twice"
4385        );
4386    }
4387
4388    // this test implement the exact same logic as
4389    // test_offset_bug_1 except that the rule starts
4390    // matching from end. Surprisingly we need to
4391    // adjust indirect offsets so that it works in
4392    // libmagic/file
4393    #[test]
4394    fn test_offset_bug_2() {
4395        // this tests the exact behaviour
4396        // expected by libmagic/file
4397        assert_magic_match_bin!(
4398            r"
4399-12	string		TEST Bread is
4400>(4.b)	use toasted
4401
44020 name toasted
4403>0	string twice Toasted
4404>>0  use toasted_twice
4405
44060 name toasted_twice
4407>(6.b) string x %
4408        ",
4409            b"\x00TEST\x06twice\x00\x06",
4410            "Bread is Toasted twice"
4411        )
4412    }
4413
4414    #[test]
4415    fn test_offset_bug_3() {
4416        // this tests the exact behaviour
4417        // expected by libmagic/file
4418        assert_magic_match_bin!(
4419            r"
44201	string		TEST Bread is
4421>(5.b) indirect/r x
4422
44230	string twice Toasted
4424>0  use toasted_twice
4425
44260 name toasted_twice
4427>0 string x %s
4428        ",
4429            b"\x00TEST\x06twice\x00\x08",
4430            "Bread is Toasted twice"
4431        )
4432    }
4433
4434    #[test]
4435    fn test_offset_bug_4() {
4436        // this tests the exact behaviour
4437        // expected by libmagic/file
4438        assert_magic_match_bin!(
4439            r"
44401	string		Bread %s
4441>(6.b) indirect/r x
4442
4443# this one uses a based offset
4444# computed at indirection
44451	string is\ Toasted %s
4446>(11.b)  use toasted_twice
4447
4448# this one is using a new base
4449# offset being previous base 
4450# offset + offset of use
44510 name toasted_twice
4452>0 string x %s
4453            ",
4454            b"\x00Bread\x06is Toasted\x0ctwice\x00",
4455            "Bread is Toasted twice"
4456        )
4457    }
4458
4459    #[test]
4460    fn test_offset_bug_5() {
4461        assert_magic_match_bin!(
4462            r"
44631	string		TEST Bread is
4464>(5.b) indirect/r x
4465
44660	string twice Toasted
4467>0  use toasted_twice
4468
44690 name toasted_twice
4470>0 string twice
4471>>&1 byte 0x08 twice
4472            ",
4473            b"\x00TEST\x06twice\x00\x08",
4474            "Bread is Toasted twice"
4475        )
4476    }
4477
4478    #[test]
4479    fn test_message_parts() {
4480        let m = first_magic(
4481            r#"0	string/W	#!/usr/bin/env\ python  PYTHON"#,
4482            b"#!/usr/bin/env    python",
4483            StreamKind::Text(TextEncoding::Ascii),
4484        )
4485        .unwrap();
4486
4487        assert!(m.message_parts().any(|p| p.eq_ignore_ascii_case("python")))
4488    }
4489}