Skip to main content

asterust_junos/firewall/family/
filter.rs

1//! `filter`
2//! `firewall { family <family> { filter <name> { term <name> { from { ... } then { ... } } } } }`.
3//!
4//! # See also
5//!
6//! - [filter (Configuring)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/filter-edit-firewall.html)
7//! - [term (Firewall Filter)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/term-edit-firewall.html)
8
9use crate::{active_children, list_values, named_children, split_keyword, statements, unquote};
10use asterust::config::ConfigLine;
11
12/// One `from` match condition, e.g. `destination-port bgp` or `source-address { 10.0.0.0/8; }`.
13#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct MatchCondition {
16    pub name: String,
17    /// Values as written, including any trailing modifier such as `except`; empty for a flag like
18    /// `first-fragment`.
19    pub values: Vec<String>,
20}
21
22/// The terminating action of a filter term. A term without one accepts matching packets.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum FilterAction {
26    Accept,
27    Discard,
28    Reject,
29    NextTerm,
30}
31
32/// The actions of a term's `then` statement. Actions not listed here are ignored.
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct FilterActions {
36    pub action: Option<FilterAction>,
37    /// Counter name from `count`.
38    pub count: Option<String>,
39    pub policer: Option<String>,
40    pub forwarding_class: Option<String>,
41    pub loss_priority: Option<String>,
42    pub log: bool,
43    pub syslog: bool,
44}
45
46/// A `term` of a filter.
47#[derive(Clone, Debug, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct FilterTerm {
50    pub name: String,
51    pub from: Vec<MatchCondition>,
52    pub then: FilterActions,
53}
54
55impl FilterTerm {
56    /// The `from` condition called `name`, e.g. `"destination-port"`.
57    pub fn condition(&self, name: &str) -> Option<&MatchCondition> {
58        self.from.iter().find(|c| c.name == name)
59    }
60}
61
62/// A `filter <name>` under `family <family>`.
63#[derive(Clone, Debug, PartialEq, Eq)]
64#[non_exhaustive]
65pub struct FirewallFilter {
66    /// Address family, e.g. `"inet"`, `"inet6"`, `"bridge"`.
67    pub family: String,
68    pub name: String,
69    pub terms: Vec<FilterTerm>,
70}
71
72pub(super) fn parse_filter(family: &str, name: &str, line: &ConfigLine) -> FirewallFilter {
73    FirewallFilter {
74        family: family.to_string(),
75        name: name.to_string(),
76        terms: named_children(line, "term")
77            .map(|(term_name, term)| FilterTerm {
78                name: term_name.to_string(),
79                from: parse_conditions(term),
80                then: parse_actions(term),
81            })
82            .collect(),
83    }
84}
85
86/// Conditions written either as `from x;` or inside a `from { ... }` block.
87fn parse_conditions(term: &ConfigLine) -> Vec<MatchCondition> {
88    let mut found = Vec::new();
89    for child in active_children(term) {
90        if child.text == "from" {
91            found.extend(active_children(child).map(parse_condition));
92        } else if let Some(statement) = child.arg("from") {
93            found.push(condition_from(statement, &[]));
94        }
95    }
96    found
97}
98
99fn parse_condition(line: &ConfigLine) -> MatchCondition {
100    condition_from(&line.text, &line.children)
101}
102
103fn condition_from(statement: &str, children: &[ConfigLine]) -> MatchCondition {
104    let (name, arg) = split_keyword(statement);
105    // A bare value keeps its modifier (`10.0.0.0/8 except`); only a bracketed list is split.
106    let mut values = if arg.is_empty() {
107        Vec::new()
108    } else if arg.starts_with('[') {
109        list_values(arg)
110    } else {
111        vec![unquote(arg).to_string()]
112    };
113    values.extend(
114        children
115            .iter()
116            .filter(|c| !c.text.starts_with("inactive:"))
117            .map(|c| c.text.clone()),
118    );
119    MatchCondition {
120        name: name.to_string(),
121        values,
122    }
123}
124
125fn parse_actions(term: &ConfigLine) -> FilterActions {
126    let mut actions = FilterActions::default();
127    for statement in statements(term, "then") {
128        let (action, arg) = split_keyword(statement);
129        let value = || Some(unquote(arg).to_string());
130        match (action, arg) {
131            ("accept", _) => actions.action = Some(FilterAction::Accept),
132            ("discard", _) => actions.action = Some(FilterAction::Discard),
133            ("reject", _) => actions.action = Some(FilterAction::Reject),
134            ("next", "term") => actions.action = Some(FilterAction::NextTerm),
135            ("count", _) => actions.count = value(),
136            ("policer", _) => actions.policer = value(),
137            ("forwarding-class", _) => actions.forwarding_class = value(),
138            ("loss-priority", _) => actions.loss_priority = value(),
139            ("log", "") => actions.log = true,
140            ("syslog", "") => actions.syslog = true,
141            _ => {}
142        }
143    }
144    actions
145}