Skip to main content

asterust_junos/
lib.rs

1//! Typed views of common JunOS config statements, extracted from a tree parsed by
2//! [`asterust::config::juniper`] (brace-delimited `show configuration` output).
3//!
4//! JunOS nests everything under a few top-level blocks (`interfaces`, `protocols`, `routing-options`,
5//! `routing-instances`, `policy-options`, `firewall`, `system`), so each module exposes a free function that reads the relevant block from a
6//! [`asterust::config::Config`] rather than a per-block constructor. [`JunosDevice`] bundles a parsed
7//! config with all of them as getters.
8//!
9//! The module tree mirrors the configuration hierarchy: `system { radius-server ... }` is
10//! `system::radius_server`, `protocols { bgp { ... } }` is `protocols::bgp`. A statement with many children of
11//! its own gets a folder, e.g. `system::services::ssh` for `system { services { ssh { ... } } }`.
12//!
13//! Statements deactivated with `inactive:` are skipped. `| display set` output is not supported.
14
15pub mod device;
16pub mod firewall;
17pub mod interfaces;
18pub mod policy_options;
19pub mod protocols;
20pub mod routing_instances;
21pub mod routing_options;
22pub mod system;
23
24pub use device::JunosDevice;
25
26use asterust::config::{Config, ConfigLine};
27
28/// Drop the quotes JunOS puts around values containing spaces.
29pub(crate) fn unquote(value: &str) -> &str {
30    value.trim().trim_matches('"')
31}
32
33/// Direct children of `line`, minus statements deactivated with `inactive:`.
34pub(crate) fn active_children(line: &ConfigLine) -> impl Iterator<Item = &ConfigLine> {
35    line.children.iter().filter(|c| !c.text.starts_with("inactive:"))
36}
37
38/// Argument of the first active child that is `<keyword> <argument>`.
39pub(crate) fn arg_of<'a>(line: &'a ConfigLine, keyword: &str) -> Option<&'a str> {
40    active_children(line).find_map(|c| c.arg(keyword)).map(unquote)
41}
42
43/// Arguments of every active child that is `<keyword> <argument>`.
44pub(crate) fn args_of<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
45    active_children(line)
46        .filter_map(|c| c.arg(keyword))
47        .map(unquote)
48        .collect()
49}
50
51/// Whether `line` has an active child that is exactly `name` (a flag such as `passive`).
52pub(crate) fn has_leaf(line: &ConfigLine, name: &str) -> bool {
53    active_children(line).any(|c| c.text == name)
54}
55
56/// Active children written `<keyword> <name>` (as a block or a leaf), with the name.
57pub(crate) fn named_children<'a>(
58    line: &'a ConfigLine,
59    keyword: &'a str,
60) -> impl Iterator<Item = (&'a str, &'a ConfigLine)> {
61    // Names can be quoted, e.g. `neighbor "fe80::20%ge-0/0/1.1";`.
62    active_children(line).filter_map(move |c| Some((unquote(c.arg(keyword)?), c)))
63}
64
65/// The active child that is exactly `name`.
66pub(crate) fn child_block<'a>(line: &'a ConfigLine, name: &str) -> Option<&'a ConfigLine> {
67    active_children(line).find(|c| c.text == name)
68}
69
70/// The top-level block called `name`.
71pub(crate) fn top_level<'a>(config: &'a Config, name: &str) -> Option<&'a ConfigLine> {
72    config.blocks.iter().map(|b| b.get_root_line()).find(|l| l.text == name)
73}
74
75/// Values of a JunOS list: `[ a b ]` or a single bare value. A quoted value may contain spaces.
76pub(crate) fn list_values(arg: &str) -> Vec<String> {
77    let inner = arg.trim().trim_start_matches('[').trim_end_matches(']');
78    let mut values = Vec::new();
79    let mut current = String::new();
80    let mut quoted = false;
81    for ch in inner.chars() {
82        match ch {
83            '"' => quoted = !quoted,
84            c if c.is_whitespace() && !quoted => {
85                if !current.is_empty() {
86                    values.push(std::mem::take(&mut current));
87                }
88            }
89            c => current.push(c),
90        }
91    }
92    if !current.is_empty() {
93        values.push(current);
94    }
95    values
96}
97
98/// Split `<name> <rest>`, where the name may be quoted.
99pub(crate) fn split_name(arg: &str) -> (&str, &str) {
100    if let Some((name, rest)) = arg.strip_prefix('"').and_then(|quoted| quoted.split_once('"')) {
101        return (name, rest.trim());
102    }
103    arg.split_once(char::is_whitespace)
104        .map_or((arg, ""), |(name, rest)| (name, rest.trim()))
105}
106
107/// Split `<keyword> <argument>` into its two parts; the argument is empty for a bare keyword.
108pub(crate) fn split_keyword(statement: &str) -> (&str, &str) {
109    statement
110        .split_once(char::is_whitespace)
111        .map_or((statement, ""), |(keyword, arg)| (keyword, arg.trim()))
112}
113
114/// Statements under `line`'s `keyword` entries, whether written `then x;` or `then { x; y; }`.
115pub(crate) fn statements<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
116    let mut found = Vec::new();
117    for child in active_children(line) {
118        if child.text == keyword {
119            found.extend(active_children(child).map(|s| s.text.as_str()));
120        } else if let Some(arg) = child.arg(keyword) {
121            found.push(arg);
122        }
123    }
124    found
125}
126
127/// Words of the first active `<keyword> ...` statement: those on its own line, then those of each child statement.
128pub(crate) fn statement_words<'a>(parent: &'a ConfigLine, keyword: &str) -> Option<Vec<&'a str>> {
129    let statement = active_children(parent).find(|c| c.text == keyword || c.arg(keyword).is_some())?;
130    Some(
131        statement
132            .text
133            .split_whitespace()
134            .skip(1)
135            .chain(active_children(statement).flat_map(|c| c.text.split_whitespace()))
136            .collect(),
137    )
138}
139
140/// The word after the first occurrence of `name` in `words`.
141pub(crate) fn value_after(words: &[&str], name: &str) -> Option<String> {
142    let position = words.iter().position(|w| *w == name)?;
143    words.get(position + 1).map(|w| w.to_string())
144}
145
146/// First whitespace-separated word of `arg`.
147pub(crate) fn first_word(arg: &str) -> Option<&str> {
148    arg.split_whitespace().next()
149}