use crate::{list_values, split_keyword, split_name, statements, unquote};
use asterust::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>,
pub aggregate_contributor: bool,
pub areas: Vec<String>,
pub as_path_groups: Vec<String>,
pub as_path_neighbors: Vec<String>,
pub as_path_origins: Vec<String>,
pub as_path_transits: Vec<String>,
pub as_path_unique_count: Option<String>,
pub as_path_calc_length: Option<String>,
pub color: Option<String>,
pub community_count: Option<String>,
pub conditions: Vec<String>,
pub external: bool,
pub external_type: Option<String>,
pub internal: bool,
pub interfaces: Vec<String>,
pub level: Option<String>,
pub local_preference: Option<String>,
pub metric: Option<String>,
pub mac_filter_lists: Vec<String>,
pub multicast_scoping: Option<String>,
pub next_hops: Vec<String>,
pub next_hop_type: Option<String>,
pub nlri_route_types: Vec<String>,
pub origin: Option<String>,
pub preference: Option<String>,
pub programmed: bool,
pub ribs: Vec<String>,
pub route_filter_lists: Vec<String>,
pub route_type: Option<String>,
pub rtf_prefix_lists: Vec<String>,
pub source_address_filter_lists: Vec<String>,
pub source_address_filters: Vec<RouteFilter>,
pub state: Option<String>,
pub tag: Option<String>,
pub traffic_engineering: bool,
}
#[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, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicySrv6Action {
pub locator: String,
pub sid_type: Option<String>,
pub sid_value: Option<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>,
pub load_balance: Option<String>,
pub resolution_map: Option<String>,
pub multipath_resolve: bool,
pub srv6: Option<PolicySrv6Action>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyTerm {
pub name: Option<String>,
pub from: PolicyConditions,
pub to: PolicyConditions,
pub then: PolicyActions,
}
pub(super) 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()),
"aggregate-contributor" => conditions.aggregate_contributor = true,
"area" => conditions.areas.push(arg.to_string()),
"as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
"as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
"as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
"as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
"as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
"as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
"color" => conditions.color = rest(arg),
"community-count" => conditions.community_count = rest(arg),
"condition" => conditions.conditions.extend(list_values(arg)),
"external" => {
conditions.external = true;
conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
}
"internal" => conditions.internal = true,
"interface" => conditions.interfaces.extend(list_values(arg)),
"level" => conditions.level = rest(arg),
"local-preference" => conditions.local_preference = rest(arg),
"metric" => conditions.metric = rest(arg),
"mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
"multicast-scoping" => conditions.multicast_scoping = rest(arg),
"next-hop" => conditions.next_hops.extend(list_values(arg)),
"next-hop-type" => conditions.next_hop_type = rest(arg),
"nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
"origin" => conditions.origin = rest(arg),
"preference" => conditions.preference = rest(arg),
"programmed" => conditions.programmed = true,
"rib" => conditions.ribs.extend(list_values(arg)),
"route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
"route-type" => conditions.route_type = rest(arg),
"rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
"source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
"source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
"state" => conditions.state = rest(arg),
"tag" => conditions.tag = rest(arg),
"traffic-engineering" => conditions.traffic_engineering = true,
_ => {}
}
}
conditions
}
fn rest(arg: &str) -> Option<String> {
Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
}
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)),
("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
("resolution-map", _) => actions.resolution_map = value(),
("multipath-resolve", "") => actions.multipath_resolve = true,
("srv6", _) => actions.srv6 = parse_srv6_action(arg),
_ => {}
}
}
actions
}
fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
let (sid_type, sid_value) = split_keyword(sid);
Some(PolicySrv6Action {
locator: unquote(locator).to_string(),
sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
})
}
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(),
})
}
#[cfg(test)]
mod tests {
use crate::policy_options::{policy_options, PolicyConditions, PolicyOptions};
use asterust::config::juniper;
fn parse(text: &str) -> PolicyOptions {
policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
}
fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
&options.policy_statements[policy].terms[term].from
}
const DOC_CONDITIONS: &str = r#"
policy-options {
policy-statement import-communities {
term 1 {
from {
protocol bgp;
community-count 5 orlower;
}
then accept;
}
term 2 {
then reject;
}
}
policy-statement join-filter {
from {
neighbor 10.14.12.20;
source-address-filter 10.83.0.0/16 orlonger;
}
then reject;
}
policy-statement join-filter-interface {
from {
interface so-1/0/0.0;
source-address-filter 10.83.0.0/16 orlonger;
}
then reject;
}
policy-statement as-list-match {
term neighbor-match {
from as-path-neighbors as-list peer-match;
}
term group-match {
from as-path-origins as-list-group origin_group;
}
}
policy-statement rf-test-policy {
term term2 {
from route-filter-list rf-list-1;
}
}
policy-statement conditional-export-bgp {
term conditional-default {
from {
condition prefix_11;
route-filter 0.0.0.0/0 exact;
}
then accept;
}
}
policy-statement dampPolicy {
term term1 {
from nlri-route-type [ 3 4 5 ];
}
}
policy-statement vrf-leak {
term 1 {
from {
protocol bgp;
rib vrf-customer2.inet.0;
community customer;
}
}
}
}
"#;
#[test]
fn reads_the_guide_community_count() {
let options = parse(DOC_CONDITIONS);
let from = from_of(&options, 0, 0);
assert_eq!(from.protocols, ["bgp"]);
assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
assert_eq!(from_of(&options, 0, 1).community_count, None);
}
#[test]
fn reads_the_guide_source_address_filters() {
let options = parse(DOC_CONDITIONS);
let from = from_of(&options, 1, 0);
assert_eq!(from.neighbors, ["10.14.12.20"]);
assert_eq!(from.source_address_filters.len(), 1);
assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));
let from = from_of(&options, 2, 0);
assert_eq!(from.interfaces, ["so-1/0/0.0"]);
}
#[test]
fn reads_the_guide_as_lists() {
let options = parse(DOC_CONDITIONS);
assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
}
#[test]
fn reads_the_guide_lists_and_conditions() {
let options = parse(DOC_CONDITIONS);
assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);
let from = from_of(&options, 5, 0);
assert_eq!(from.conditions, ["prefix_11"]);
assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
}
#[test]
fn reads_the_guide_nlri_route_types_and_rib() {
let options = parse(DOC_CONDITIONS);
assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);
let from = from_of(&options, 7, 0);
assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
assert_eq!(from.communities, ["customer"]);
}
#[test]
fn reads_the_other_match_conditions() {
let options = parse(
r#"
policy-options {
policy-statement igp {
term ospf {
from {
protocol ospf;
area 0.0.0.0;
external type 2;
level 2;
tag 100 tag2 200;
state active;
aggregate-contributor;
programmed;
traffic-engineering;
}
}
term internal {
from {
internal;
route-type external;
color 10 color2 5;
metric 20 metric2 30;
preference 100 preference2 200;
local-preference 150;
origin igp;
next-hop [ 192.0.2.1 192.0.2.2 ];
next-hop-type merged;
as-path-group TRANSIT;
as-path-unique-count 2 orhigher;
as-path-calc-length 4 equal;
mac-filter-list MACS;
multicast-scoping link-local;
rtf-prefix-list RTF route-targets;
source-address-filter-list SOURCES;
}
}
term bare {
from external;
}
}
}
"#,
);
let ospf = from_of(&options, 0, 0);
assert_eq!(ospf.areas, ["0.0.0.0"]);
assert!(ospf.external);
assert_eq!(ospf.external_type.as_deref(), Some("2"));
assert_eq!(ospf.level.as_deref(), Some("2"));
assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
assert_eq!(ospf.state.as_deref(), Some("active"));
assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
assert!(!ospf.internal);
let other = from_of(&options, 0, 1);
assert!(other.internal && !other.external);
assert_eq!(other.route_type.as_deref(), Some("external"));
assert_eq!(other.color.as_deref(), Some("10 color2 5"));
assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
assert_eq!(other.local_preference.as_deref(), Some("150"));
assert_eq!(other.origin.as_deref(), Some("igp"));
assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
assert_eq!(other.as_path_groups, ["TRANSIT"]);
assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
assert_eq!(other.mac_filter_lists, ["MACS"]);
assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
assert_eq!(other.source_address_filter_lists, ["SOURCES"]);
let bare = from_of(&options, 0, 2);
assert!(bare.external);
assert_eq!(bare.external_type, None);
}
#[test]
fn reads_to_conditions_with_the_same_statements() {
let options = parse(
"policy-options {\n policy-statement export {\n to {\n level 1;\n interface ge-0/0/0.0;\n }\n }\n}\n",
);
let to = &options.policy_statements[0].terms[0].to;
assert_eq!(to.level.as_deref(), Some("1"));
assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
}
}