use crate::{active_children, list_values, named_children, split_keyword, split_name, statements, top_level, unquote};
use asterust::config::{Config, ConfigLine};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RouteFilter {
pub prefix: String,
pub match_type: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyConditions {
pub protocols: Vec<String>,
pub families: Vec<String>,
pub communities: Vec<String>,
pub as_paths: Vec<String>,
pub prefix_lists: Vec<String>,
pub prefix_list_filters: Vec<String>,
pub route_filters: Vec<RouteFilter>,
pub neighbors: Vec<String>,
pub policies: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PolicyAction {
Accept,
Reject,
NextTerm,
NextPolicy,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommunityOperation {
Add,
Set,
Delete,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommunityAction {
pub operation: CommunityOperation,
pub community: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyActions {
pub action: Option<PolicyAction>,
pub metric: Option<String>,
pub local_preference: Option<String>,
pub next_hop: Option<String>,
pub as_path_prepend: Option<String>,
pub communities: Vec<CommunityAction>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyTerm {
pub name: Option<String>,
pub from: PolicyConditions,
pub to: PolicyConditions,
pub then: PolicyActions,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyStatement {
pub name: String,
pub terms: Vec<PolicyTerm>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Community {
pub name: String,
pub members: Vec<String>,
pub invert_match: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrefixList {
pub name: String,
pub prefixes: Vec<String>,
pub apply_path: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsPath {
pub name: String,
pub regex: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsPathGroup {
pub name: String,
pub as_paths: Vec<AsPath>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyOptions {
pub policy_statements: Vec<PolicyStatement>,
pub communities: Vec<Community>,
pub prefix_lists: Vec<PrefixList>,
pub as_paths: Vec<AsPath>,
pub as_path_groups: Vec<AsPathGroup>,
}
pub fn policy_options(config: &Config) -> Option<PolicyOptions> {
let root = top_level(config, "policy-options")?;
Some(PolicyOptions {
policy_statements: named_children(root, "policy-statement")
.map(|(name, line)| parse_policy(name, line))
.collect(),
communities: active_children(root).filter_map(parse_community).collect(),
prefix_lists: named_children(root, "prefix-list")
.map(|(name, line)| parse_prefix_list(name, line))
.collect(),
as_paths: active_children(root).filter_map(parse_as_path).collect(),
as_path_groups: named_children(root, "as-path-group")
.map(|(name, line)| AsPathGroup {
name: name.to_string(),
as_paths: active_children(line).filter_map(parse_as_path).collect(),
})
.collect(),
})
}
fn parse_policy(name: &str, line: &ConfigLine) -> PolicyStatement {
let mut terms: Vec<PolicyTerm> = named_children(line, "term")
.map(|(term_name, term)| parse_term(Some(term_name), term))
.collect();
let has_unnamed_term = active_children(line).any(|c| {
["from", "to", "then"]
.iter()
.any(|k| c.text == *k || c.arg(k).is_some())
});
if has_unnamed_term {
terms.push(parse_term(None, line));
}
PolicyStatement {
name: name.to_string(),
terms,
}
}
fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
PolicyTerm {
name: name.map(str::to_string),
from: parse_conditions(line, "from"),
to: parse_conditions(line, "to"),
then: parse_actions(line),
}
}
fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
let mut conditions = PolicyConditions::default();
for statement in statements(line, keyword) {
let (condition, arg) = split_keyword(statement);
match condition {
"protocol" => conditions.protocols.extend(list_values(arg)),
"family" => conditions.families.push(unquote(arg).to_string()),
"community" => conditions.communities.extend(list_values(arg)),
"as-path" => conditions.as_paths.extend(list_values(arg)),
"prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
"prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
"route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
"neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
"policy" => conditions.policies.push(unquote(arg).to_string()),
_ => {}
}
}
conditions
}
fn parse_route_filter(arg: &str) -> RouteFilter {
let (prefix, match_type) = split_keyword(arg);
RouteFilter {
prefix: prefix.to_string(),
match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
}
}
fn parse_actions(line: &ConfigLine) -> PolicyActions {
let mut actions = PolicyActions::default();
for statement in statements(line, "then") {
let (action, arg) = split_keyword(statement);
let value = || Some(unquote(arg).to_string());
match (action, arg) {
("accept", "") => actions.action = Some(PolicyAction::Accept),
("reject", "") => actions.action = Some(PolicyAction::Reject),
("next", "term") => actions.action = Some(PolicyAction::NextTerm),
("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
("metric", _) => actions.metric = value(),
("local-preference", _) => actions.local_preference = value(),
("next-hop", _) => actions.next_hop = value(),
("as-path-prepend", _) => actions.as_path_prepend = value(),
("community", _) => actions.communities.extend(parse_community_action(arg)),
_ => {}
}
}
actions
}
fn parse_community_action(arg: &str) -> Option<CommunityAction> {
let (operation, community) = split_name(arg);
let operation = match operation {
"add" => CommunityOperation::Add,
"set" => CommunityOperation::Set,
"delete" => CommunityOperation::Delete,
_ => return None,
};
Some(CommunityAction {
operation,
community: unquote(community).to_string(),
})
}
fn parse_community(line: &ConfigLine) -> Option<Community> {
let (name, rest) = split_name(line.arg("community")?);
let (keyword, members) = split_keyword(rest);
let mut community = Community {
name: name.to_string(),
members: if keyword == "members" {
list_values(members)
} else {
Vec::new()
},
invert_match: false,
};
for child in active_children(line) {
if let Some(members) = child.arg("members") {
community.members.extend(list_values(members));
} else if child.text == "invert-match" {
community.invert_match = true;
}
}
Some(community)
}
fn parse_prefix_list(name: &str, line: &ConfigLine) -> PrefixList {
let mut list = PrefixList {
name: name.to_string(),
prefixes: Vec::new(),
apply_path: None,
};
for child in active_children(line) {
if let Some(path) = child.arg("apply-path") {
list.apply_path = Some(unquote(path).to_string());
} else if !child.text.contains(' ') {
list.prefixes.push(child.text.clone());
}
}
list
}
fn parse_as_path(line: &ConfigLine) -> Option<AsPath> {
let (name, regex) = split_name(line.arg("as-path")?);
Some(AsPath {
name: name.to_string(),
regex: unquote(regex).to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use asterust::config::juniper;
fn parse(text: &str) -> PolicyOptions {
policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
}
const DOC_COMMUNITY_TAG: &str = r#"
policy-options {
policy-statement Edu-to-isis {
term 1 {
from {
protocol bgp;
community Edu;
}
then {
metric 63;
accept;
}
}
}
policy-statement send-isis-and-direct {
term 1 {
from {
protocol [ isis direct ];
route-filter 10.0.0.0/16 orlonger;
route-filter 192.168.0.0/16 orlonger;
}
then accept;
}
}
community Edu members 2:5;
}
"#;
#[test]
fn doc_term_with_from_block_and_metric() {
let options = parse(DOC_COMMUNITY_TAG);
assert_eq!(options.policy_statements.len(), 2);
let policy = &options.policy_statements[0];
assert_eq!(policy.name, "Edu-to-isis");
let term = &policy.terms[0];
assert_eq!(term.name.as_deref(), Some("1"));
assert_eq!(term.from.protocols, ["bgp"]);
assert_eq!(term.from.communities, ["Edu"]);
assert_eq!(term.then.metric.as_deref(), Some("63"));
assert_eq!(term.then.action, Some(PolicyAction::Accept));
}
#[test]
fn doc_protocol_list_route_filters_and_leaf_then() {
let options = parse(DOC_COMMUNITY_TAG);
let term = &options.policy_statements[1].terms[0];
assert_eq!(term.from.protocols, ["isis", "direct"]);
assert_eq!(term.from.route_filters.len(), 2);
assert_eq!(term.from.route_filters[0].prefix, "10.0.0.0/16");
assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("orlonger"));
assert_eq!(term.then.action, Some(PolicyAction::Accept));
}
#[test]
fn doc_one_line_community() {
let options = parse(DOC_COMMUNITY_TAG);
assert_eq!(options.communities.len(), 1);
assert_eq!(options.communities[0].name, "Edu");
assert_eq!(options.communities[0].members, ["2:5"]);
assert!(!options.communities[0].invert_match);
}
const DOC_COMMUNITY_ACTIONS: &str = r#"
policy-options {
policy-statement statics {
from protocol static;
then {
community add 1;
accept;
}
}
policy-statement remove-communities {
term 1 {
from protocol bgp;
then {
community delete wild;
accept;
}
}
term 2 {
then reject;
}
}
community wild members *:*;
community 1 members [ 2:1 2:2 2:3 ];
}
"#;
#[test]
fn doc_policy_without_terms_has_one_unnamed_term() {
let options = parse(DOC_COMMUNITY_ACTIONS);
let statics = &options.policy_statements[0];
assert_eq!(statics.terms.len(), 1);
let term = &statics.terms[0];
assert_eq!(term.name, None);
assert_eq!(term.from.protocols, ["static"]);
assert_eq!(
term.then.communities,
[CommunityAction {
operation: CommunityOperation::Add,
community: "1".to_string()
}]
);
assert_eq!(term.then.action, Some(PolicyAction::Accept));
}
#[test]
fn doc_community_delete_and_final_reject_term() {
let options = parse(DOC_COMMUNITY_ACTIONS);
let remove = &options.policy_statements[1];
assert_eq!(remove.terms.len(), 2);
assert_eq!(
remove.terms[0].then.communities[0].operation,
CommunityOperation::Delete
);
assert_eq!(remove.terms[0].then.communities[0].community, "wild");
assert_eq!(remove.terms[1].name.as_deref(), Some("2"));
assert_eq!(remove.terms[1].then.action, Some(PolicyAction::Reject));
}
#[test]
fn doc_community_members_list() {
let options = parse(DOC_COMMUNITY_ACTIONS);
assert_eq!(options.communities[0].members, ["*:*"]);
assert_eq!(options.communities[1].name, "1");
assert_eq!(options.communities[1].members, ["2:1", "2:2", "2:3"]);
}
const CONFIG: &str = r#"
policy-options {
prefix-list CUSTOMERS {
192.0.2.0/24;
2001:db8::/32;
}
prefix-list DYNAMIC {
apply-path "protocols bgp group <*> neighbor <*>";
}
as-path FROM-AS65001 ".* 65001";
as-path-group TRANSIT {
as-path TIER1 "65100 .*";
as-path TIER2 "65200 .*";
}
community BLOCK {
invert-match;
members [ no-export 65000:666 ];
}
community WILD members "* : *";
policy-statement IMPORT {
term FROM-CUSTOMER {
from {
family inet;
neighbor 192.0.2.1;
prefix-list CUSTOMERS;
prefix-list-filter CUSTOMERS orlonger;
as-path FROM-AS65001;
route-filter 10.0.0.0/8 upto /24;
policy SUBROUTINE;
}
then {
local-preference 200;
next-hop self;
as-path-prepend "65000 65000";
next policy;
}
}
inactive: term DISABLED {
then reject;
}
term SKIP {
from protocol ospf;
then next term;
}
then reject;
}
}
"#;
#[test]
fn extracts_prefix_lists_and_as_paths() {
let options = parse(CONFIG);
assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24", "2001:db8::/32"]);
assert_eq!(options.prefix_lists[0].apply_path, None);
assert!(options.prefix_lists[1].prefixes.is_empty());
assert_eq!(
options.prefix_lists[1].apply_path.as_deref(),
Some("protocols bgp group <*> neighbor <*>")
);
assert_eq!(options.as_paths.len(), 1);
assert_eq!(options.as_paths[0].name, "FROM-AS65001");
assert_eq!(options.as_paths[0].regex, ".* 65001");
let group = &options.as_path_groups[0];
assert_eq!(group.name, "TRANSIT");
let names: Vec<_> = group.as_paths.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["TIER1", "TIER2"]);
assert_eq!(group.as_paths[1].regex, "65200 .*");
}
#[test]
fn extracts_block_and_quoted_communities() {
let options = parse(CONFIG);
assert_eq!(options.communities.len(), 2);
assert_eq!(options.communities[0].name, "BLOCK");
assert_eq!(options.communities[0].members, ["no-export", "65000:666"]);
assert!(options.communities[0].invert_match);
assert_eq!(options.communities[1].members, ["* : *"]);
}
#[test]
fn extracts_conditions_and_manipulation_actions() {
let options = parse(CONFIG);
let term = &options.policy_statements[0].terms[0];
assert_eq!(term.name.as_deref(), Some("FROM-CUSTOMER"));
assert_eq!(term.from.families, ["inet"]);
assert_eq!(term.from.neighbors, ["192.0.2.1"]);
assert_eq!(term.from.prefix_lists, ["CUSTOMERS"]);
assert_eq!(term.from.prefix_list_filters, ["CUSTOMERS orlonger"]);
assert_eq!(term.from.as_paths, ["FROM-AS65001"]);
assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("upto /24"));
assert_eq!(term.from.policies, ["SUBROUTINE"]);
assert_eq!(term.then.local_preference.as_deref(), Some("200"));
assert_eq!(term.then.next_hop.as_deref(), Some("self"));
assert_eq!(term.then.as_path_prepend.as_deref(), Some("65000 65000"));
assert_eq!(term.then.action, Some(PolicyAction::NextPolicy));
}
#[test]
fn skips_inactive_terms_and_keeps_unnamed_final_term_last() {
let options = parse(CONFIG);
let terms = &options.policy_statements[0].terms;
let names: Vec<_> = terms.iter().map(|t| t.name.as_deref()).collect();
assert_eq!(names, [Some("FROM-CUSTOMER"), Some("SKIP"), None]);
assert_eq!(terms[1].then.action, Some(PolicyAction::NextTerm));
assert_eq!(terms[2].then.action, Some(PolicyAction::Reject));
}
#[test]
fn no_policy_options_is_none() {
assert!(policy_options(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
}
}