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