aboutsummaryrefslogtreecommitdiff
path: root/rustables/src/expr/log.rs
blob: aa7a8b73249ec028f5c29e20aa8327bb5d2fff9b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use super::{Expression, Rule};
use rustables_sys as sys;
use std::os::raw::c_char;
use std::ffi::CString;
use thiserror::Error;

/// A Log expression will log all packets that match the rule.
pub struct Log {
    pub group: Option<LogGroup>,
    pub prefix: Option<LogPrefix>
}

impl Expression for Log {
    fn to_expr(&self, _rule: &Rule) -> *mut sys::nftnl_expr {
        unsafe {
            let expr = try_alloc!(sys::nftnl_expr_alloc(
                b"log\0" as *const _ as *const c_char
            ));
            if let Some(log_group) = self.group {
                sys::nftnl_expr_set_u32(
                    expr,
                    sys::NFTNL_EXPR_LOG_GROUP as u16,
                    log_group.0 as u32,
                );
            };
            if let Some(LogPrefix(prefix)) = &self.prefix {
                sys::nftnl_expr_set_str(
                    expr,
                    sys::NFTNL_EXPR_LOG_PREFIX as u16,
                    prefix.as_ptr()
                );
            };

            expr
        }
    }
}

#[derive(Error, Debug)]
pub enum LogPrefixError {
    #[error("The log prefix string is more than 128 characters long")]
    TooLongPrefix,
    #[error("The log prefix string contains an invalid Nul character.")]
    PrefixContainsANul(#[from] std::ffi::NulError)

}

/// The NFLOG group that will be assigned to each log line.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct LogGroup(pub u16);

/// A prefix that will get prepended to each log line.
#[derive(Debug, Clone, PartialEq)]
pub struct LogPrefix(CString);

impl LogPrefix {
    /// Create a new LogPrefix from a String. Converts it to CString as needed by nftnl. Note
    /// that LogPrefix should not be more than 127 characters long.
    pub fn new(prefix: &str) -> Result<Self, LogPrefixError> {
        if prefix.chars().count() > 127 {
            return Err(LogPrefixError::TooLongPrefix)
        }
        Ok(LogPrefix(CString::new(prefix)?))
    }
}


#[macro_export]
macro_rules! nft_expr_log {
    (group $group:ident prefix $prefix:expr) => {
        $crate::expr::Log { group: $group, prefix: $prefix }
    };
    (prefix $prefix:expr) => {
        $crate::expr::Log { group: None, prefix: $prefix }
    };
    (group $group:ident) => {
        $crate::expr::Log { group: $group, prefix: None }
    };
    () => {
        $crate::expr::Log { group: None, prefix: None }
    };
}