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/// `Some(true)` for `<name>`, `Some(false)` for `no-<name>`, `None` if neither is present. Either may carry options.
57pub(crate) fn toggle(line: &ConfigLine, name: &str) -> Option<bool> {
58    let written = |statement: &str| active_children(line).any(|c| c.text == statement || c.arg(statement).is_some());
59    if written(name) {
60        Some(true)
61    } else if written(&format!("no-{name}")) {
62        Some(false)
63    } else {
64        None
65    }
66}
67
68/// Active children written `<keyword> <name>` (as a block or a leaf), with the name.
69pub(crate) fn named_children<'a>(
70    line: &'a ConfigLine,
71    keyword: &'a str,
72) -> impl Iterator<Item = (&'a str, &'a ConfigLine)> {
73    // Names can be quoted, e.g. `neighbor "fe80::20%ge-0/0/1.1";`.
74    active_children(line).filter_map(move |c| Some((unquote(c.arg(keyword)?), c)))
75}
76
77/// The active child that is exactly `name`.
78pub(crate) fn child_block<'a>(line: &'a ConfigLine, name: &str) -> Option<&'a ConfigLine> {
79    active_children(line).find(|c| c.text == name)
80}
81
82/// The top-level block called `name`.
83pub(crate) fn top_level<'a>(config: &'a Config, name: &str) -> Option<&'a ConfigLine> {
84    config.blocks.iter().map(|b| b.get_root_line()).find(|l| l.text == name)
85}
86
87/// Values of a JunOS list: `[ a b ]` or a single bare value. A quoted value may contain spaces.
88pub(crate) fn list_values(arg: &str) -> Vec<String> {
89    let inner = arg.trim().trim_start_matches('[').trim_end_matches(']');
90    let mut values = Vec::new();
91    let mut current = String::new();
92    let mut quoted = false;
93    for ch in inner.chars() {
94        match ch {
95            '"' => quoted = !quoted,
96            c if c.is_whitespace() && !quoted => {
97                if !current.is_empty() {
98                    values.push(std::mem::take(&mut current));
99                }
100            }
101            c => current.push(c),
102        }
103    }
104    if !current.is_empty() {
105        values.push(current);
106    }
107    values
108}
109
110/// Split `<name> <rest>`, where the name may be quoted.
111pub(crate) fn split_name(arg: &str) -> (&str, &str) {
112    if let Some((name, rest)) = arg.strip_prefix('"').and_then(|quoted| quoted.split_once('"')) {
113        return (name, rest.trim());
114    }
115    arg.split_once(char::is_whitespace)
116        .map_or((arg, ""), |(name, rest)| (name, rest.trim()))
117}
118
119/// Split `<keyword> <argument>` into its two parts; the argument is empty for a bare keyword.
120pub(crate) fn split_keyword(statement: &str) -> (&str, &str) {
121    statement
122        .split_once(char::is_whitespace)
123        .map_or((statement, ""), |(keyword, arg)| (keyword, arg.trim()))
124}
125
126/// Statements under `line`'s `keyword` entries, whether written `then x;` or `then { x; y; }`.
127pub(crate) fn statements<'a>(line: &'a ConfigLine, keyword: &str) -> Vec<&'a str> {
128    let mut found = Vec::new();
129    for child in active_children(line) {
130        if child.text == keyword {
131            found.extend(active_children(child).map(|s| s.text.as_str()));
132        } else if let Some(arg) = child.arg(keyword) {
133            found.push(arg);
134        }
135    }
136    found
137}
138
139/// Words of the first active `<keyword> ...` statement: those on its own line, then those of each child statement.
140pub(crate) fn statement_words<'a>(parent: &'a ConfigLine, keyword: &str) -> Option<Vec<&'a str>> {
141    let statement = active_children(parent).find(|c| c.text == keyword || c.arg(keyword).is_some())?;
142    Some(
143        statement
144            .text
145            .split_whitespace()
146            .skip(1)
147            .chain(active_children(statement).flat_map(|c| c.text.split_whitespace()))
148            .collect(),
149    )
150}
151
152/// The word after the first occurrence of `name` in `words`.
153pub(crate) fn value_after(words: &[&str], name: &str) -> Option<String> {
154    let position = words.iter().position(|w| *w == name)?;
155    words.get(position + 1).map(|w| w.to_string())
156}
157
158/// First whitespace-separated word of `arg`.
159pub(crate) fn first_word(arg: &str) -> Option<&str> {
160    arg.split_whitespace().next()
161}