Skip to main content

asterust_junos/
policy_options.rs

1//! `policy-options { ... }`: policy statements, communities, prefix lists and AS paths.
2
3use crate::{active_children, list_values, named_children, split_keyword, split_name, statements, top_level, unquote};
4use asterust::config::{Config, ConfigLine};
5
6/// A `route-filter <prefix> <match-type>` condition.
7#[derive(Clone, Debug, PartialEq, Eq)]
8#[non_exhaustive]
9pub struct RouteFilter {
10    pub prefix: String,
11    /// Everything after the prefix, e.g. `"exact"`, `"orlonger"`, `"upto /24"`.
12    pub match_type: Option<String>,
13}
14
15/// The match conditions of a term's `from` or `to` statement. Conditions not listed here are ignored.
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct PolicyConditions {
19    pub protocols: Vec<String>,
20    pub families: Vec<String>,
21    pub communities: Vec<String>,
22    pub as_paths: Vec<String>,
23    pub prefix_lists: Vec<String>,
24    /// The raw `prefix-list-filter` argument, e.g. `"CUSTOMERS orlonger"`.
25    pub prefix_list_filters: Vec<String>,
26    pub route_filters: Vec<RouteFilter>,
27    pub neighbors: Vec<String>,
28    /// Subroutine policies from `policy`.
29    pub policies: Vec<String>,
30}
31
32/// The flow-control action ending a term.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum PolicyAction {
36    Accept,
37    Reject,
38    NextTerm,
39    NextPolicy,
40}
41
42/// How a `then community` action changes the route's communities.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum CommunityOperation {
46    Add,
47    Set,
48    Delete,
49}
50
51/// A `then community (add | set | delete) <name>` action.
52#[derive(Clone, Debug, PartialEq, Eq)]
53#[non_exhaustive]
54pub struct CommunityAction {
55    pub operation: CommunityOperation,
56    pub community: String,
57}
58
59/// The actions of a term's `then` statement. Actions not listed here are ignored.
60#[derive(Clone, Debug, Default, PartialEq, Eq)]
61#[non_exhaustive]
62pub struct PolicyActions {
63    pub action: Option<PolicyAction>,
64    /// Everything after `metric`, e.g. `"63"` or `"add 10"`.
65    pub metric: Option<String>,
66    pub local_preference: Option<String>,
67    pub next_hop: Option<String>,
68    pub as_path_prepend: Option<String>,
69    pub communities: Vec<CommunityAction>,
70}
71
72/// One term of a policy statement.
73#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct PolicyTerm {
76    /// `None` for the unnamed term, which is the only one in a policy written without `term` statements.
77    pub name: Option<String>,
78    pub from: PolicyConditions,
79    pub to: PolicyConditions,
80    pub then: PolicyActions,
81}
82
83/// A `policy-statement <name>`. An unnamed term is placed last.
84#[derive(Clone, Debug, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct PolicyStatement {
87    pub name: String,
88    pub terms: Vec<PolicyTerm>,
89}
90
91/// A `community <name> members ...`, which may be a standard, extended or large community.
92#[derive(Clone, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct Community {
95    pub name: String,
96    pub members: Vec<String>,
97    pub invert_match: bool,
98}
99
100/// A `prefix-list <name>`.
101#[derive(Clone, Debug, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct PrefixList {
104    pub name: String,
105    pub prefixes: Vec<String>,
106    pub apply_path: Option<String>,
107}
108
109/// An `as-path <name> <regular-expression>`.
110#[derive(Clone, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct AsPath {
113    pub name: String,
114    pub regex: String,
115}
116
117/// An `as-path-group <name>` of AS path expressions.
118#[derive(Clone, Debug, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct AsPathGroup {
121    pub name: String,
122    pub as_paths: Vec<AsPath>,
123}
124
125/// The top-level `policy-options` configuration.
126#[derive(Clone, Debug, PartialEq, Eq)]
127#[non_exhaustive]
128pub struct PolicyOptions {
129    pub policy_statements: Vec<PolicyStatement>,
130    pub communities: Vec<Community>,
131    pub prefix_lists: Vec<PrefixList>,
132    pub as_paths: Vec<AsPath>,
133    pub as_path_groups: Vec<AsPathGroup>,
134}
135
136/// The top-level `policy-options` block, or `None` if there is none.
137pub fn policy_options(config: &Config) -> Option<PolicyOptions> {
138    let root = top_level(config, "policy-options")?;
139    Some(PolicyOptions {
140        policy_statements: named_children(root, "policy-statement")
141            .map(|(name, line)| parse_policy(name, line))
142            .collect(),
143        communities: active_children(root).filter_map(parse_community).collect(),
144        prefix_lists: named_children(root, "prefix-list")
145            .map(|(name, line)| parse_prefix_list(name, line))
146            .collect(),
147        as_paths: active_children(root).filter_map(parse_as_path).collect(),
148        as_path_groups: named_children(root, "as-path-group")
149            .map(|(name, line)| AsPathGroup {
150                name: name.to_string(),
151                as_paths: active_children(line).filter_map(parse_as_path).collect(),
152            })
153            .collect(),
154    })
155}
156
157fn parse_policy(name: &str, line: &ConfigLine) -> PolicyStatement {
158    let mut terms: Vec<PolicyTerm> = named_children(line, "term")
159        .map(|(term_name, term)| parse_term(Some(term_name), term))
160        .collect();
161    let has_unnamed_term = active_children(line).any(|c| {
162        ["from", "to", "then"]
163            .iter()
164            .any(|k| c.text == *k || c.arg(k).is_some())
165    });
166    if has_unnamed_term {
167        terms.push(parse_term(None, line));
168    }
169    PolicyStatement {
170        name: name.to_string(),
171        terms,
172    }
173}
174
175fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
176    PolicyTerm {
177        name: name.map(str::to_string),
178        from: parse_conditions(line, "from"),
179        to: parse_conditions(line, "to"),
180        then: parse_actions(line),
181    }
182}
183
184fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
185    let mut conditions = PolicyConditions::default();
186    for statement in statements(line, keyword) {
187        let (condition, arg) = split_keyword(statement);
188        match condition {
189            "protocol" => conditions.protocols.extend(list_values(arg)),
190            "family" => conditions.families.push(unquote(arg).to_string()),
191            "community" => conditions.communities.extend(list_values(arg)),
192            "as-path" => conditions.as_paths.extend(list_values(arg)),
193            "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
194            "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
195            "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
196            "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
197            "policy" => conditions.policies.push(unquote(arg).to_string()),
198            _ => {}
199        }
200    }
201    conditions
202}
203
204fn parse_route_filter(arg: &str) -> RouteFilter {
205    let (prefix, match_type) = split_keyword(arg);
206    RouteFilter {
207        prefix: prefix.to_string(),
208        match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
209    }
210}
211
212fn parse_actions(line: &ConfigLine) -> PolicyActions {
213    let mut actions = PolicyActions::default();
214    for statement in statements(line, "then") {
215        let (action, arg) = split_keyword(statement);
216        let value = || Some(unquote(arg).to_string());
217        match (action, arg) {
218            ("accept", "") => actions.action = Some(PolicyAction::Accept),
219            ("reject", "") => actions.action = Some(PolicyAction::Reject),
220            ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
221            ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
222            ("metric", _) => actions.metric = value(),
223            ("local-preference", _) => actions.local_preference = value(),
224            ("next-hop", _) => actions.next_hop = value(),
225            ("as-path-prepend", _) => actions.as_path_prepend = value(),
226            ("community", _) => actions.communities.extend(parse_community_action(arg)),
227            _ => {}
228        }
229    }
230    actions
231}
232
233fn parse_community_action(arg: &str) -> Option<CommunityAction> {
234    let (operation, community) = split_name(arg);
235    let operation = match operation {
236        "add" => CommunityOperation::Add,
237        "set" => CommunityOperation::Set,
238        "delete" => CommunityOperation::Delete,
239        _ => return None,
240    };
241    Some(CommunityAction {
242        operation,
243        community: unquote(community).to_string(),
244    })
245}
246
247/// A `community` statement written either on one line (`community X members 1:1;`) or as a block.
248fn parse_community(line: &ConfigLine) -> Option<Community> {
249    let (name, rest) = split_name(line.arg("community")?);
250    let (keyword, members) = split_keyword(rest);
251    let mut community = Community {
252        name: name.to_string(),
253        members: if keyword == "members" {
254            list_values(members)
255        } else {
256            Vec::new()
257        },
258        invert_match: false,
259    };
260    for child in active_children(line) {
261        if let Some(members) = child.arg("members") {
262            community.members.extend(list_values(members));
263        } else if child.text == "invert-match" {
264            community.invert_match = true;
265        }
266    }
267    Some(community)
268}
269
270fn parse_prefix_list(name: &str, line: &ConfigLine) -> PrefixList {
271    let mut list = PrefixList {
272        name: name.to_string(),
273        prefixes: Vec::new(),
274        apply_path: None,
275    };
276    for child in active_children(line) {
277        if let Some(path) = child.arg("apply-path") {
278            list.apply_path = Some(unquote(path).to_string());
279        } else if !child.text.contains(' ') {
280            // Prefixes are the only statements without arguments; `apply-groups` and the like have a space.
281            list.prefixes.push(child.text.clone());
282        }
283    }
284    list
285}
286
287fn parse_as_path(line: &ConfigLine) -> Option<AsPath> {
288    let (name, regex) = split_name(line.arg("as-path")?);
289    Some(AsPath {
290        name: name.to_string(),
291        regex: unquote(regex).to_string(),
292    })
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use asterust::config::juniper;
299
300    fn parse(text: &str) -> PolicyOptions {
301        policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
302    }
303
304    // Adapted from Juniper's BGP User Guide "Routing Policies for BGP Communities"; see the README "Sources".
305    const DOC_COMMUNITY_TAG: &str = r#"
306policy-options {
307    policy-statement Edu-to-isis {
308        term 1 {
309            from {
310                protocol bgp;
311                community Edu;
312            }
313            then {
314                metric 63;
315                accept;
316            }
317        }
318    }
319    policy-statement send-isis-and-direct {
320        term 1 {
321            from {
322                protocol [ isis direct ];
323                route-filter 10.0.0.0/16 orlonger;
324                route-filter 192.168.0.0/16 orlonger;
325            }
326            then accept;
327        }
328    }
329    community Edu members 2:5;
330}
331"#;
332
333    #[test]
334    fn doc_term_with_from_block_and_metric() {
335        let options = parse(DOC_COMMUNITY_TAG);
336        assert_eq!(options.policy_statements.len(), 2);
337
338        let policy = &options.policy_statements[0];
339        assert_eq!(policy.name, "Edu-to-isis");
340        let term = &policy.terms[0];
341        assert_eq!(term.name.as_deref(), Some("1"));
342        assert_eq!(term.from.protocols, ["bgp"]);
343        assert_eq!(term.from.communities, ["Edu"]);
344        assert_eq!(term.then.metric.as_deref(), Some("63"));
345        assert_eq!(term.then.action, Some(PolicyAction::Accept));
346    }
347
348    #[test]
349    fn doc_protocol_list_route_filters_and_leaf_then() {
350        let options = parse(DOC_COMMUNITY_TAG);
351        let term = &options.policy_statements[1].terms[0];
352        assert_eq!(term.from.protocols, ["isis", "direct"]);
353        assert_eq!(term.from.route_filters.len(), 2);
354        assert_eq!(term.from.route_filters[0].prefix, "10.0.0.0/16");
355        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("orlonger"));
356        assert_eq!(term.then.action, Some(PolicyAction::Accept));
357    }
358
359    #[test]
360    fn doc_one_line_community() {
361        let options = parse(DOC_COMMUNITY_TAG);
362        assert_eq!(options.communities.len(), 1);
363        assert_eq!(options.communities[0].name, "Edu");
364        assert_eq!(options.communities[0].members, ["2:5"]);
365        assert!(!options.communities[0].invert_match);
366    }
367
368    // Adapted from the same guide's "Configuring a Routing Policy That Removes BGP Communities" and "...Based on
369    // the Number of BGP Communities" examples (Devices R1 and R2).
370    const DOC_COMMUNITY_ACTIONS: &str = r#"
371policy-options {
372    policy-statement statics {
373        from protocol static;
374        then {
375            community add 1;
376            accept;
377        }
378    }
379    policy-statement remove-communities {
380        term 1 {
381            from protocol bgp;
382            then {
383                community delete wild;
384                accept;
385            }
386        }
387        term 2 {
388            then reject;
389        }
390    }
391    community wild members *:*;
392    community 1 members [ 2:1 2:2 2:3 ];
393}
394"#;
395
396    #[test]
397    fn doc_policy_without_terms_has_one_unnamed_term() {
398        let options = parse(DOC_COMMUNITY_ACTIONS);
399        let statics = &options.policy_statements[0];
400        assert_eq!(statics.terms.len(), 1);
401        let term = &statics.terms[0];
402        assert_eq!(term.name, None);
403        assert_eq!(term.from.protocols, ["static"]);
404        assert_eq!(
405            term.then.communities,
406            [CommunityAction {
407                operation: CommunityOperation::Add,
408                community: "1".to_string()
409            }]
410        );
411        assert_eq!(term.then.action, Some(PolicyAction::Accept));
412    }
413
414    #[test]
415    fn doc_community_delete_and_final_reject_term() {
416        let options = parse(DOC_COMMUNITY_ACTIONS);
417        let remove = &options.policy_statements[1];
418        assert_eq!(remove.terms.len(), 2);
419        assert_eq!(
420            remove.terms[0].then.communities[0].operation,
421            CommunityOperation::Delete
422        );
423        assert_eq!(remove.terms[0].then.communities[0].community, "wild");
424        assert_eq!(remove.terms[1].name.as_deref(), Some("2"));
425        assert_eq!(remove.terms[1].then.action, Some(PolicyAction::Reject));
426    }
427
428    #[test]
429    fn doc_community_members_list() {
430        let options = parse(DOC_COMMUNITY_ACTIONS);
431        assert_eq!(options.communities[0].members, ["*:*"]);
432        assert_eq!(options.communities[1].name, "1");
433        assert_eq!(options.communities[1].members, ["2:1", "2:2", "2:3"]);
434    }
435
436    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
437    const CONFIG: &str = r#"
438policy-options {
439    prefix-list CUSTOMERS {
440        192.0.2.0/24;
441        2001:db8::/32;
442    }
443    prefix-list DYNAMIC {
444        apply-path "protocols bgp group <*> neighbor <*>";
445    }
446    as-path FROM-AS65001 ".* 65001";
447    as-path-group TRANSIT {
448        as-path TIER1 "65100 .*";
449        as-path TIER2 "65200 .*";
450    }
451    community BLOCK {
452        invert-match;
453        members [ no-export 65000:666 ];
454    }
455    community WILD members "* : *";
456    policy-statement IMPORT {
457        term FROM-CUSTOMER {
458            from {
459                family inet;
460                neighbor 192.0.2.1;
461                prefix-list CUSTOMERS;
462                prefix-list-filter CUSTOMERS orlonger;
463                as-path FROM-AS65001;
464                route-filter 10.0.0.0/8 upto /24;
465                policy SUBROUTINE;
466            }
467            then {
468                local-preference 200;
469                next-hop self;
470                as-path-prepend "65000 65000";
471                next policy;
472            }
473        }
474        inactive: term DISABLED {
475            then reject;
476        }
477        term SKIP {
478            from protocol ospf;
479            then next term;
480        }
481        then reject;
482    }
483}
484"#;
485
486    #[test]
487    fn extracts_prefix_lists_and_as_paths() {
488        let options = parse(CONFIG);
489        assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
490        assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24", "2001:db8::/32"]);
491        assert_eq!(options.prefix_lists[0].apply_path, None);
492        assert!(options.prefix_lists[1].prefixes.is_empty());
493        assert_eq!(
494            options.prefix_lists[1].apply_path.as_deref(),
495            Some("protocols bgp group <*> neighbor <*>")
496        );
497
498        assert_eq!(options.as_paths.len(), 1);
499        assert_eq!(options.as_paths[0].name, "FROM-AS65001");
500        assert_eq!(options.as_paths[0].regex, ".* 65001");
501        let group = &options.as_path_groups[0];
502        assert_eq!(group.name, "TRANSIT");
503        let names: Vec<_> = group.as_paths.iter().map(|p| p.name.as_str()).collect();
504        assert_eq!(names, ["TIER1", "TIER2"]);
505        assert_eq!(group.as_paths[1].regex, "65200 .*");
506    }
507
508    #[test]
509    fn extracts_block_and_quoted_communities() {
510        let options = parse(CONFIG);
511        assert_eq!(options.communities.len(), 2);
512        assert_eq!(options.communities[0].name, "BLOCK");
513        assert_eq!(options.communities[0].members, ["no-export", "65000:666"]);
514        assert!(options.communities[0].invert_match);
515        assert_eq!(options.communities[1].members, ["* : *"]);
516    }
517
518    #[test]
519    fn extracts_conditions_and_manipulation_actions() {
520        let options = parse(CONFIG);
521        let term = &options.policy_statements[0].terms[0];
522        assert_eq!(term.name.as_deref(), Some("FROM-CUSTOMER"));
523        assert_eq!(term.from.families, ["inet"]);
524        assert_eq!(term.from.neighbors, ["192.0.2.1"]);
525        assert_eq!(term.from.prefix_lists, ["CUSTOMERS"]);
526        assert_eq!(term.from.prefix_list_filters, ["CUSTOMERS orlonger"]);
527        assert_eq!(term.from.as_paths, ["FROM-AS65001"]);
528        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("upto /24"));
529        assert_eq!(term.from.policies, ["SUBROUTINE"]);
530        assert_eq!(term.then.local_preference.as_deref(), Some("200"));
531        assert_eq!(term.then.next_hop.as_deref(), Some("self"));
532        assert_eq!(term.then.as_path_prepend.as_deref(), Some("65000 65000"));
533        assert_eq!(term.then.action, Some(PolicyAction::NextPolicy));
534    }
535
536    #[test]
537    fn skips_inactive_terms_and_keeps_unnamed_final_term_last() {
538        let options = parse(CONFIG);
539        let terms = &options.policy_statements[0].terms;
540        let names: Vec<_> = terms.iter().map(|t| t.name.as_deref()).collect();
541        assert_eq!(names, [Some("FROM-CUSTOMER"), Some("SKIP"), None]);
542        assert_eq!(terms[1].then.action, Some(PolicyAction::NextTerm));
543        assert_eq!(terms[2].then.action, Some(PolicyAction::Reject));
544    }
545
546    #[test]
547    fn no_policy_options_is_none() {
548        assert!(policy_options(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
549    }
550}