1use crate::{list_values, split_keyword, split_name, statements, unquote};
14use asterust::config::ConfigLine;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct RouteFilter {
20 pub prefix: String,
21 pub match_type: Option<String>,
23}
24
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct PolicyConditions {
30 pub protocols: Vec<String>,
31 pub families: Vec<String>,
32 pub communities: Vec<String>,
33 pub as_paths: Vec<String>,
34 pub prefix_lists: Vec<String>,
35 pub prefix_list_filters: Vec<String>,
37 pub route_filters: Vec<RouteFilter>,
38 pub neighbors: Vec<String>,
39 pub policies: Vec<String>,
41 pub aggregate_contributor: bool,
43 pub areas: Vec<String>,
45 pub as_path_groups: Vec<String>,
47 pub as_path_neighbors: Vec<String>,
50 pub as_path_origins: Vec<String>,
51 pub as_path_transits: Vec<String>,
52 pub as_path_unique_count: Option<String>,
54 pub as_path_calc_length: Option<String>,
56 pub color: Option<String>,
58 pub community_count: Option<String>,
60 pub conditions: Vec<String>,
62 pub external: bool,
64 pub external_type: Option<String>,
66 pub internal: bool,
68 pub interfaces: Vec<String>,
69 pub level: Option<String>,
71 pub local_preference: Option<String>,
72 pub metric: Option<String>,
74 pub mac_filter_lists: Vec<String>,
75 pub multicast_scoping: Option<String>,
77 pub next_hops: Vec<String>,
78 pub next_hop_type: Option<String>,
80 pub nlri_route_types: Vec<String>,
82 pub origin: Option<String>,
83 pub preference: Option<String>,
85 pub programmed: bool,
87 pub ribs: Vec<String>,
89 pub route_filter_lists: Vec<String>,
90 pub route_type: Option<String>,
92 pub rtf_prefix_lists: Vec<String>,
94 pub source_address_filter_lists: Vec<String>,
95 pub source_address_filters: Vec<RouteFilter>,
97 pub state: Option<String>,
99 pub tag: Option<String>,
101 pub traffic_engineering: bool,
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum PolicyAction {
109 Accept,
110 Reject,
111 NextTerm,
112 NextPolicy,
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum CommunityOperation {
119 Add,
120 Set,
121 Delete,
122}
123
124#[derive(Clone, Debug, PartialEq, Eq)]
126#[non_exhaustive]
127pub struct CommunityAction {
128 pub operation: CommunityOperation,
129 pub community: String,
130}
131
132#[derive(Clone, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub struct PolicySrv6Action {
136 pub locator: String,
137 pub sid_type: Option<String>,
139 pub sid_value: Option<String>,
141}
142
143#[derive(Clone, Debug, Default, PartialEq, Eq)]
145#[non_exhaustive]
146pub struct PolicyActions {
147 pub action: Option<PolicyAction>,
148 pub metric: Option<String>,
150 pub local_preference: Option<String>,
151 pub next_hop: Option<String>,
152 pub as_path_prepend: Option<String>,
153 pub communities: Vec<CommunityAction>,
154 pub load_balance: Option<String>,
156 pub resolution_map: Option<String>,
158 pub multipath_resolve: bool,
159 pub srv6: Option<PolicySrv6Action>,
160}
161
162#[derive(Clone, Debug, PartialEq, Eq)]
164#[non_exhaustive]
165pub struct PolicyTerm {
166 pub name: Option<String>,
169 pub from: PolicyConditions,
170 pub to: PolicyConditions,
171 pub then: PolicyActions,
172}
173
174pub(super) fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
175 PolicyTerm {
176 name: name.map(str::to_string),
177 from: parse_conditions(line, "from"),
178 to: parse_conditions(line, "to"),
179 then: parse_actions(line),
180 }
181}
182
183fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
184 let mut conditions = PolicyConditions::default();
185 for statement in statements(line, keyword) {
186 let (condition, arg) = split_keyword(statement);
187 match condition {
188 "protocol" => conditions.protocols.extend(list_values(arg)),
189 "family" => conditions.families.push(unquote(arg).to_string()),
190 "community" => conditions.communities.extend(list_values(arg)),
191 "as-path" => conditions.as_paths.extend(list_values(arg)),
192 "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
193 "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
194 "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
195 "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
196 "policy" => conditions.policies.push(unquote(arg).to_string()),
197 "aggregate-contributor" => conditions.aggregate_contributor = true,
198 "area" => conditions.areas.push(arg.to_string()),
199 "as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
200 "as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
201 "as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
202 "as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
203 "as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
204 "as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
205 "color" => conditions.color = rest(arg),
206 "community-count" => conditions.community_count = rest(arg),
207 "condition" => conditions.conditions.extend(list_values(arg)),
208 "external" => {
209 conditions.external = true;
210 conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
211 }
212 "internal" => conditions.internal = true,
213 "interface" => conditions.interfaces.extend(list_values(arg)),
214 "level" => conditions.level = rest(arg),
215 "local-preference" => conditions.local_preference = rest(arg),
216 "metric" => conditions.metric = rest(arg),
217 "mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
218 "multicast-scoping" => conditions.multicast_scoping = rest(arg),
219 "next-hop" => conditions.next_hops.extend(list_values(arg)),
220 "next-hop-type" => conditions.next_hop_type = rest(arg),
221 "nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
222 "origin" => conditions.origin = rest(arg),
223 "preference" => conditions.preference = rest(arg),
224 "programmed" => conditions.programmed = true,
225 "rib" => conditions.ribs.extend(list_values(arg)),
226 "route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
227 "route-type" => conditions.route_type = rest(arg),
228 "rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
229 "source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
230 "source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
231 "state" => conditions.state = rest(arg),
232 "tag" => conditions.tag = rest(arg),
233 "traffic-engineering" => conditions.traffic_engineering = true,
234 _ => {}
235 }
236 }
237 conditions
238}
239
240fn rest(arg: &str) -> Option<String> {
241 Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
242}
243
244fn parse_route_filter(arg: &str) -> RouteFilter {
245 let (prefix, match_type) = split_keyword(arg);
246 RouteFilter {
247 prefix: prefix.to_string(),
248 match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
249 }
250}
251
252fn parse_actions(line: &ConfigLine) -> PolicyActions {
253 let mut actions = PolicyActions::default();
254 for statement in statements(line, "then") {
255 let (action, arg) = split_keyword(statement);
256 let value = || Some(unquote(arg).to_string());
257 match (action, arg) {
258 ("accept", "") => actions.action = Some(PolicyAction::Accept),
259 ("reject", "") => actions.action = Some(PolicyAction::Reject),
260 ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
261 ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
262 ("metric", _) => actions.metric = value(),
263 ("local-preference", _) => actions.local_preference = value(),
264 ("next-hop", _) => actions.next_hop = value(),
265 ("as-path-prepend", _) => actions.as_path_prepend = value(),
266 ("community", _) => actions.communities.extend(parse_community_action(arg)),
267 ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
268 ("resolution-map", _) => actions.resolution_map = value(),
269 ("multipath-resolve", "") => actions.multipath_resolve = true,
270 ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
271 _ => {}
272 }
273 }
274 actions
275}
276
277fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
278 let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
279 let (sid_type, sid_value) = split_keyword(sid);
280 Some(PolicySrv6Action {
281 locator: unquote(locator).to_string(),
282 sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
283 sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
284 })
285}
286
287fn parse_community_action(arg: &str) -> Option<CommunityAction> {
288 let (operation, community) = split_name(arg);
289 let operation = match operation {
290 "add" => CommunityOperation::Add,
291 "set" => CommunityOperation::Set,
292 "delete" => CommunityOperation::Delete,
293 _ => return None,
294 };
295 Some(CommunityAction {
296 operation,
297 community: unquote(community).to_string(),
298 })
299}
300
301#[cfg(test)]
302mod tests {
303 use crate::policy_options::{policy_options, PolicyConditions, PolicyOptions};
304 use asterust::config::juniper;
305
306 fn parse(text: &str) -> PolicyOptions {
307 policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
308 }
309
310 fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
311 &options.policy_statements[policy].terms[term].from
312 }
313
314 const DOC_CONDITIONS: &str = r#"
320policy-options {
321 policy-statement import-communities {
322 term 1 {
323 from {
324 protocol bgp;
325 community-count 5 orlower;
326 }
327 then accept;
328 }
329 term 2 {
330 then reject;
331 }
332 }
333 policy-statement join-filter {
334 from {
335 neighbor 10.14.12.20;
336 source-address-filter 10.83.0.0/16 orlonger;
337 }
338 then reject;
339 }
340 policy-statement join-filter-interface {
341 from {
342 interface so-1/0/0.0;
343 source-address-filter 10.83.0.0/16 orlonger;
344 }
345 then reject;
346 }
347 policy-statement as-list-match {
348 term neighbor-match {
349 from as-path-neighbors as-list peer-match;
350 }
351 term group-match {
352 from as-path-origins as-list-group origin_group;
353 }
354 }
355 policy-statement rf-test-policy {
356 term term2 {
357 from route-filter-list rf-list-1;
358 }
359 }
360 policy-statement conditional-export-bgp {
361 term conditional-default {
362 from {
363 condition prefix_11;
364 route-filter 0.0.0.0/0 exact;
365 }
366 then accept;
367 }
368 }
369 policy-statement dampPolicy {
370 term term1 {
371 from nlri-route-type [ 3 4 5 ];
372 }
373 }
374 policy-statement vrf-leak {
375 term 1 {
376 from {
377 protocol bgp;
378 rib vrf-customer2.inet.0;
379 community customer;
380 }
381 }
382 }
383}
384"#;
385
386 #[test]
387 fn reads_the_guide_community_count() {
388 let options = parse(DOC_CONDITIONS);
389 let from = from_of(&options, 0, 0);
390 assert_eq!(from.protocols, ["bgp"]);
391 assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
392 assert_eq!(from_of(&options, 0, 1).community_count, None);
393 }
394
395 #[test]
396 fn reads_the_guide_source_address_filters() {
397 let options = parse(DOC_CONDITIONS);
398 let from = from_of(&options, 1, 0);
399 assert_eq!(from.neighbors, ["10.14.12.20"]);
400 assert_eq!(from.source_address_filters.len(), 1);
401 assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
402 assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));
403
404 let from = from_of(&options, 2, 0);
405 assert_eq!(from.interfaces, ["so-1/0/0.0"]);
406 }
407
408 #[test]
409 fn reads_the_guide_as_lists() {
410 let options = parse(DOC_CONDITIONS);
411 assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
412 assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
413 }
414
415 #[test]
416 fn reads_the_guide_lists_and_conditions() {
417 let options = parse(DOC_CONDITIONS);
418 assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);
419
420 let from = from_of(&options, 5, 0);
421 assert_eq!(from.conditions, ["prefix_11"]);
422 assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
423 }
424
425 #[test]
426 fn reads_the_guide_nlri_route_types_and_rib() {
427 let options = parse(DOC_CONDITIONS);
428 assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);
429
430 let from = from_of(&options, 7, 0);
431 assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
432 assert_eq!(from.communities, ["customer"]);
433 }
434
435 #[test]
438 fn reads_the_other_match_conditions() {
439 let options = parse(
440 r#"
441policy-options {
442 policy-statement igp {
443 term ospf {
444 from {
445 protocol ospf;
446 area 0.0.0.0;
447 external type 2;
448 level 2;
449 tag 100 tag2 200;
450 state active;
451 aggregate-contributor;
452 programmed;
453 traffic-engineering;
454 }
455 }
456 term internal {
457 from {
458 internal;
459 route-type external;
460 color 10 color2 5;
461 metric 20 metric2 30;
462 preference 100 preference2 200;
463 local-preference 150;
464 origin igp;
465 next-hop [ 192.0.2.1 192.0.2.2 ];
466 next-hop-type merged;
467 as-path-group TRANSIT;
468 as-path-unique-count 2 orhigher;
469 as-path-calc-length 4 equal;
470 mac-filter-list MACS;
471 multicast-scoping link-local;
472 rtf-prefix-list RTF route-targets;
473 source-address-filter-list SOURCES;
474 }
475 }
476 term bare {
477 from external;
478 }
479 }
480}
481"#,
482 );
483 let ospf = from_of(&options, 0, 0);
484 assert_eq!(ospf.areas, ["0.0.0.0"]);
485 assert!(ospf.external);
486 assert_eq!(ospf.external_type.as_deref(), Some("2"));
487 assert_eq!(ospf.level.as_deref(), Some("2"));
488 assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
489 assert_eq!(ospf.state.as_deref(), Some("active"));
490 assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
491 assert!(!ospf.internal);
492
493 let other = from_of(&options, 0, 1);
494 assert!(other.internal && !other.external);
495 assert_eq!(other.route_type.as_deref(), Some("external"));
496 assert_eq!(other.color.as_deref(), Some("10 color2 5"));
497 assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
498 assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
499 assert_eq!(other.local_preference.as_deref(), Some("150"));
500 assert_eq!(other.origin.as_deref(), Some("igp"));
501 assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
502 assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
503 assert_eq!(other.as_path_groups, ["TRANSIT"]);
504 assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
505 assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
506 assert_eq!(other.mac_filter_lists, ["MACS"]);
507 assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
508 assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
509 assert_eq!(other.source_address_filter_lists, ["SOURCES"]);
510
511 let bare = from_of(&options, 0, 2);
512 assert!(bare.external);
513 assert_eq!(bare.external_type, None);
514 }
515
516 #[test]
517 fn reads_to_conditions_with_the_same_statements() {
518 let options = parse(
519 "policy-options {\n policy-statement export {\n to {\n level 1;\n interface ge-0/0/0.0;\n }\n }\n}\n",
520 );
521 let to = &options.policy_statements[0].terms[0].to;
522 assert_eq!(to.level.as_deref(), Some("1"));
523 assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
524 }
525}