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