Skip to main content

suricatax_rule_parser/
lib.rs

1// SPDX-FileCopyrightText: (C) 2021 Jason Ish <jason@codemonkey.net>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! A minimal Suricata rule parser/lexer.
5//!
6//! This library provides a simple scanner for tokenizing Suricata rules into their
7//! component parts (headers and options) without attempting to parse option values
8//! in detail.
9
10use nom::Offset;
11
12use scanner::ScanError;
13
14pub mod scanner;
15
16/// Rule scanner errors.
17///
18/// This error type helps hide the details of the internal scanner errors.
19#[derive(Debug, PartialEq, Eq, Clone)]
20#[non_exhaustive]
21pub struct Error {
22    pub offset: usize,
23    pub reason: String,
24}
25
26impl std::fmt::Display for Error {
27    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
28        write!(f, "error at offset {}: {}", self.offset, self.reason)
29    }
30}
31
32impl std::error::Error for Error {}
33
34impl Error {
35    /// Create an external error from a nom error.
36    pub(crate) fn from_nom_error(
37        err: nom::Err<ScanError<&str>>,
38        start: &str,
39        context: &str,
40    ) -> Self {
41        match err {
42            nom::Err::Incomplete(_) => Error {
43                offset: start.len(),
44                reason: format!("{context}: incomplete"),
45            },
46            nom::Err::Failure(err) | nom::Err::Error(err) => {
47                let offset = start.offset(err.input);
48                Error {
49                    offset,
50                    reason: format!("{}: {}", context, err.reason),
51                }
52            }
53        }
54    }
55}