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