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