Skip to main content

ccze_rs/
lib.rs

1//! Streaming log parsing, colorization, analytics, and protocol verification.
2
3pub mod analytics;
4#[cfg(feature = "system-integration")]
5pub mod cgroup;
6#[cfg(feature = "system-integration")]
7pub mod config;
8#[cfg(feature = "system-integration")]
9pub mod dkms;
10#[cfg(feature = "system-integration")]
11pub mod gossip;
12#[cfg(feature = "system-integration")]
13pub mod lsm;
14pub mod parser;
15pub mod protocol;
16#[cfg(feature = "system-integration")]
17pub mod rollback;
18#[cfg(feature = "system-integration")]
19pub mod scheduler;
20#[cfg(feature = "system-integration")]
21pub mod seccomp;
22pub mod severity;
23#[cfg(feature = "system-integration")]
24pub mod timing;
25pub mod vector;
26#[cfg(feature = "system-integration")]
27pub mod xdp;
28#[cfg(feature = "system-integration")]
29pub mod zram;
30
31use parser::{LogParser, Token, TokenKind};
32
33/// Available parser names accepted by the command-line interface.
34pub const PLUGINS: &[&str] = &["auto", "syslog", "httpd", "json"];
35
36/// Reusable line processor that avoids copying input while parsing.
37pub struct Processor {
38    parser: Box<dyn LogParser + Send + Sync>,
39    tokens: Vec<Token>,
40}
41
42impl Processor {
43    /// Creates a processor for a named parser.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error when `name` is not one of [`PLUGINS`].
48    pub fn new(name: &str) -> Result<Self, String> {
49        let parser = parser::by_name(name).ok_or_else(|| {
50            format!(
51                "unknown plugin '{name}'; expected one of {}",
52                PLUGINS.join(", ")
53            )
54        })?;
55        Ok(Self {
56            parser,
57            tokens: Vec::with_capacity(16),
58        })
59    }
60
61    /// Returns the parser's stable name.
62    #[must_use]
63    pub fn plugin_name(&self) -> &'static str {
64        self.parser.name()
65    }
66
67    /// Classifies and renders one line into `output`.
68    pub fn process(
69        &mut self,
70        line: &[u8],
71        color: bool,
72        output: &mut Vec<u8>,
73    ) -> severity::Severity {
74        self.tokens.clear();
75        let severity = self.parser.parse(line, &mut self.tokens);
76        self.tokens.sort_unstable_by_key(|token| token.start);
77        render(line, &self.tokens, color, output);
78        severity
79    }
80}
81
82fn render(input: &[u8], tokens: &[Token], color: bool, output: &mut Vec<u8>) {
83    output.clear();
84    if !color {
85        output.extend_from_slice(input);
86        return;
87    }
88
89    let mut cursor = 0;
90    for token in tokens {
91        if token.start < cursor || token.end > input.len() || token.start == token.end {
92            continue;
93        }
94        output.extend_from_slice(&input[cursor..token.start]);
95        output.extend_from_slice(token.kind.ansi().as_bytes());
96        output.extend_from_slice(&input[token.start..token.end]);
97        output.extend_from_slice(b"\x1b[0m");
98        cursor = token.end;
99    }
100    output.extend_from_slice(&input[cursor..]);
101}
102
103impl TokenKind {
104    const fn ansi(self) -> &'static str {
105        match self {
106            Self::Timestamp => "\x1b[33m",
107            Self::Host => "\x1b[36m",
108            Self::Process => "\x1b[35m",
109            Self::Key => "\x1b[34m",
110            Self::Value => "\x1b[32m",
111            Self::Warning => "\x1b[1;33m",
112            Self::Error => "\x1b[1;31m",
113            Self::Fatal => "\x1b[1;37;41m",
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn renders_syslog_without_changing_payload() {
124        let line = b"Jul 30 12:34:56 host sshd[42]: login failed";
125        let mut processor = Processor::new("syslog").unwrap();
126        let mut plain = Vec::new();
127        let severity = processor.process(line, false, &mut plain);
128        assert_eq!(plain, line);
129        assert_eq!(severity, severity::Severity::Error);
130
131        let mut colored = Vec::new();
132        processor.process(line, true, &mut colored);
133        assert!(colored.starts_with(b"\x1b[33mJul 30 12:34:56"));
134        assert!(colored.ends_with(b"\x1b[1;31mfailed\x1b[0m"));
135    }
136
137    #[test]
138    fn rejects_unknown_plugins() {
139        assert!(Processor::new("made-up").is_err());
140    }
141}