retina_filtergen/
packet_filter.rs

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
use quote::quote;

use crate::utils::*;
use retina_core::filter::ast::*;
use retina_core::filter::ptree::{FilterLayer, PNode, PTree};

pub(crate) fn gen_packet_filter(
    ptree: &PTree,
    statics: &mut Vec<proc_macro2::TokenStream>,
    filter_layer: FilterLayer,
) -> proc_macro2::TokenStream {
    let mut body: Vec<proc_macro2::TokenStream> = vec![];

    // Ensure root is covered
    if !ptree.root.actions.drop() || !ptree.root.deliver.is_empty() {
        update_body(&mut body, &ptree.root, filter_layer, false);
    }

    gen_packet_filter_util(&mut body, statics, &ptree.root, filter_layer);

    let body = PacketDataFilter::add_root_pred(&ptree.root, &body);

    let packet_filter = quote! {
        let mut result = retina_core::filter::Actions::new();
        #body
        result
    };
    packet_filter
}

fn gen_packet_filter_util(
    code: &mut Vec<proc_macro2::TokenStream>,
    statics: &mut Vec<proc_macro2::TokenStream>,
    node: &PNode,
    filter_layer: FilterLayer,
) {
    let mut first_unary = true;
    for child in node.children.iter().filter(|n| n.pred.on_packet()) {
        match &child.pred {
            Predicate::Unary { protocol } => {
                PacketDataFilter::add_unary_pred(
                    code,
                    statics,
                    child,
                    node.pred.get_protocol(),
                    protocol,
                    first_unary,
                    filter_layer,
                    &gen_packet_filter_util,
                );
                first_unary = false;
            }
            Predicate::Binary {
                protocol,
                field,
                op,
                value,
            } => {
                PacketDataFilter::add_binary_pred(
                    code,
                    statics,
                    child,
                    protocol,
                    field,
                    op,
                    value,
                    filter_layer,
                    &gen_packet_filter_util,
                );
            }
        }
    }
}