Skip to main content

asterust_junos/system/
mod.rs

1//! `system`
2//! `system { ... }`.
3//!
4//! Each statement with children of its own lives in a submodule named after it.
5//!
6//! # See also
7//!
8//! - [`[edit system]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-system.html)
9//! - [host-name (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/host-name-edit-system.html)
10//! - [domain-name (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-name-edit-system.html)
11//! - [time-zone](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/time-zone-edit-system.html)
12//! - [domain-search](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-search-edit-system.html)
13//! - [authentication-order (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/authentication-order-edit-system.html)
14//! - [max-configurations-on-flash (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/max-configurations-on-flash-edit-system.html)
15//! - [no-redirects (IPv4 Traffic)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-redirects-edit-system.html)
16//! - [default-address-selection](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/default-address-selection-edit-system.html)
17//! - [diag-port-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/diag-port-authentication-edit-system.html)
18//! - [pic-console-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/pic-console-authentication-edit-system.html)
19//! - [boot-loader-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/boot-loader-authentication-edit-system.html)
20//! - [device-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/device-authentication-edit-system.html)
21//! - [allow-6pe-traceroute](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-6pe-traceroute-edit-system.html)
22//! - [allow-l3vpn-traceroute-src-select](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-l3vpn-traceroute-src-select-edit-system.html)
23//! - [arp-system-cache-limit](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/arp-system-cache-limit-edit-system.html)
24//! - [dual-phase-bootup](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dual-phase-bootup-edit-system.html)
25//! - [extended-echo](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/extended-echo-edit-system.html)
26//! - [management-instance](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/management-instance-edit-system.html)
27//! - [nd-override-preferred-src](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/nd-override-preferred-src-edit-system.html)
28//! - [nd-retransmit-timer](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/nd-retransmit-timer-edit-system.html)
29//! - [nd-system-cache-limit](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/nd-system-cache-limit-edit-system.html)
30//! - [no-hidden-commands](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-hidden-set-system.html)
31//! - [node (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/node-edit-system.html)
32//! - [regex-additive-logic](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/regex-additive-logic-edit-system.html)
33//! - [rng](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/rng-edit-system.html)
34//! - [saved-core-context (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/saved-core-context-edit-system.html)
35//! - [saved-core-files (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/saved-core-files-edit-system.html)
36//! - [unattended-boot](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/unattended-boot-edit-system.html)
37
38mod access_line;
39mod accounting;
40mod archival;
41mod arp;
42mod authentication_secret;
43mod auto_sw_sync;
44mod autoinstallation;
45mod backup_router;
46mod commit;
47mod configuration;
48mod configuration_database;
49mod ddos_protection;
50mod demux_options;
51mod dynamic_profile_options;
52mod export_format;
53mod extensions;
54mod fib_streaming;
55mod health_monitor;
56mod icmp;
57mod internet_options;
58mod kernel_replication;
59mod license;
60mod location;
61mod login;
62mod management_traffic;
63mod master_password;
64mod monitor;
65mod name_server;
66mod ntp;
67mod packet_forwarding_options;
68mod password_options;
69mod pixel_tracing;
70mod ports;
71mod processes;
72mod proxy;
73mod radius_options;
74mod radius_server;
75mod resiliency;
76mod root_authentication;
77mod schema;
78mod scripts;
79mod services;
80mod snapshot;
81mod static_host_mapping;
82mod syslog;
83mod tacplus_options;
84mod tacplus_server;
85mod tracing;
86
87pub use access_line::{AccessLine, AccessLineAdjustment};
88pub use accounting::{Accounting, AccountingDestination};
89pub use archival::{Archival, ArchivalConfiguration};
90pub use arp::{Arp, ArpInterface};
91pub use authentication_secret::AuthenticationSecret;
92pub use auto_sw_sync::AutoSwSync;
93pub use autoinstallation::{Autoinstallation, AutoinstallationInterface};
94pub use backup_router::BackupRouter;
95pub use commit::{Commit, CommitPeer, CommitServer};
96pub use configuration::ConfigurationInput;
97pub use configuration_database::{
98    ConfigurationDatabase, DatabaseResize, EphemeralDatabase, EphemeralInstance, VirtualMemoryProcess,
99};
100pub use ddos_protection::{DdosFlowLevels, DdosFpc, DdosGlobal, DdosPacketType, DdosProtection, DdosProtocolGroup};
101pub use demux_options::DemuxOptions;
102pub use dynamic_profile_options::DynamicProfileOptions;
103pub use export_format::ExportFormat;
104pub use extensions::{ExtensionApplication, ExtensionProvider, Extensions, ProviderLicense};
105pub use fib_streaming::{FibStreaming, FibStreamingTable};
106pub use health_monitor::HealthMonitor;
107pub use icmp::Icmp;
108pub use internet_options::{IcmpRateLimit, InternetOptions};
109pub use kernel_replication::KernelReplication;
110pub use license::{License, LicenseAutoupdate, LicenseRenew};
111pub use location::Location;
112pub use login::{Login, LoginClass, LoginPassword, LoginRetryOptions, LoginUser};
113pub use management_traffic::ManagementTrafficProtocol;
114pub use master_password::MasterPassword;
115pub use monitor::{
116    MemoryMonitor, Monitor, ProcessMemoryEvent, ProcessMemoryMonitor, ProcessMemoryThreshold, SystemMemoryEvent,
117    SystemMemoryMonitor,
118};
119pub use name_server::NameServer;
120pub use ntp::{Ntp, NtpAuthenticationKey, NtpBroadcast, NtpHost, NtpHostNts, NtpNts, NtpRestriction, NtpThreshold};
121pub use packet_forwarding_options::{
122    HwMonitorProfile, HwResourceList, HwResourceMonitor, PacketForwardingOptions, PfeFirewall, PfeSystemProfile,
123    RecycleBandwidthProfile,
124};
125pub use password_options::PasswordOptions;
126pub use pixel_tracing::PixelTracing;
127pub use ports::{Auxiliary, Console, Ports};
128pub use processes::{Process, SnoopingFile};
129pub use proxy::Proxy;
130pub use radius_options::RadiusOptions;
131pub use radius_server::RadiusServer;
132pub use resiliency::{Resiliency, ResiliencyFile, ResiliencyStore};
133pub use root_authentication::RootAuthentication;
134pub use schema::Schema;
135pub use scripts::{ScriptArgument, ScriptFile, ScriptKind, ScriptOid, Scripts};
136pub use services::{
137    AaclStatisticsProfile, ConnectionLimits, DhcpLocalServer, DhcpLocalServerGroup, Dns, DnsCacheEntry, DnsDomain,
138    DnsProxy, DnsView, Dnssec, ExtensionService, FlowTapDtcp, FlowTapDtcpSsh, FpcLimit, FtpService, GrpcService,
139    GrpcSsl, HttpServer, HttpServerTls, InbandZtp, Jeb, JebTls, JetNotification, JtreeResourceType,
140    LocalPolicyDecisionFunction, Netconf, NetconfClientIdentity, NetconfDefaultClientIdentity, NetconfHelloMessage,
141    NetconfMonitoring, NetconfSsh, NetconfTls, NetconfYangModules, OutboundHttpsAddress, OutboundHttpsClient,
142    OutboundSshClient, OutboundSshServer, PicLimit, PortLimit, RedundancyInterface, ResourceMonitor, Rest, RestHttp,
143    RestHttps, Reverse, ServiceDeployment, ServiceDeploymentServer, Services, SshModuli, SshService,
144    StaticSubscriberGroup, StaticSubscriberProfile, StaticSubscribers, SubscriberLimit, SubscriberManagement,
145    SubscriberRedundancy, TelnetService, WebManagement, WebManagementHttp, WebManagementHttps,
146    WebManagementVirtualDomain, XnmClearText, XnmSsl,
147};
148pub use snapshot::{Snapshot, SnapshotRecovery};
149pub use static_host_mapping::StaticHostMapping;
150pub use syslog::{Syslog, SyslogArchive, SyslogHost, SyslogRule, SyslogStructuredData, SyslogTarget};
151pub use tacplus_options::TacplusOptions;
152pub use tacplus_server::TacplusServer;
153pub use tracing::Tracing;
154
155use crate::{
156    active_children, arg_of, args_of, child_block, has_leaf, list_values, split_name, toggle, top_level, unquote,
157};
158use access_line::parse_access_line;
159use accounting::parse_accounting;
160use archival::parse_archival;
161use arp::parse_arp;
162use asterust::config::{Config, ConfigLine};
163use authentication_secret::password_secrets;
164use auto_sw_sync::auto_sw_sync;
165use autoinstallation::parse_autoinstallation;
166use backup_router::parse_backup_router;
167use commit::parse_commit;
168use configuration::parse_configuration;
169use configuration_database::parse_configuration_database;
170use ddos_protection::parse_ddos_protection;
171use demux_options::parse_demux_options;
172use dynamic_profile_options::parse_dynamic_profile_options;
173use export_format::parse_export_format;
174use extensions::parse_extensions;
175use fib_streaming::parse_fib_streaming;
176use health_monitor::parse_health_monitor;
177use icmp::parse_icmp;
178use internet_options::parse_internet_options;
179use kernel_replication::parse_kernel_replication;
180use license::parse_license;
181use location::parse_location;
182use login::parse_login;
183use management_traffic::management_traffic;
184use master_password::parse_master_password;
185use monitor::parse_monitor;
186use name_server::name_servers;
187use ntp::parse_ntp;
188use packet_forwarding_options::parse_packet_forwarding_options;
189use password_options::parse_password_options;
190use pixel_tracing::parse_pixel_tracing;
191use ports::parse_ports;
192use processes::parse_processes;
193use proxy::parse_proxy;
194use radius_options::parse_radius_options;
195use radius_server::radius_servers;
196use resiliency::parse_resiliency;
197use root_authentication::root_authentication;
198use schema::parse_schema;
199use scripts::parse_scripts;
200use services::parse_services;
201use snapshot::parse_snapshot;
202use static_host_mapping::static_host_mappings;
203use syslog::parse_syslog;
204use tacplus_options::parse_tacplus_options;
205use tacplus_server::tacplus_servers;
206use tracing::parse_tracing;
207
208/// The top-level `system` configuration.
209#[derive(Clone, Debug, PartialEq, Eq)]
210#[non_exhaustive]
211pub struct System {
212    pub host_name: Option<String>,
213    pub domain_name: Option<String>,
214    /// e.g. `"UTC"` or `"America/New_York"`.
215    pub time_zone: Option<String>,
216    pub domain_search: Vec<String>,
217    pub static_host_mappings: Vec<StaticHostMapping>,
218    pub backup_router: Option<BackupRouter>,
219    pub inet6_backup_router: Option<BackupRouter>,
220    /// Methods in the order tried: `password`, `radius`, `tacplus`.
221    pub authentication_order: Vec<String>,
222    pub radius_servers: Vec<RadiusServer>,
223    pub tacplus_servers: Vec<TacplusServer>,
224    pub location: Option<Location>,
225    pub ports: Option<Ports>,
226    pub max_configurations_on_flash: Option<String>,
227    pub max_configuration_rollbacks: Option<String>,
228    pub no_redirects: bool,
229    /// `default-address-selection`: use the loopback as the source of locally generated packets.
230    pub default_address_selection: bool,
231    pub internet_options: Option<InternetOptions>,
232    pub commit: Option<Commit>,
233    pub processes: Vec<Process>,
234    pub dynamic_profile_options: Option<DynamicProfileOptions>,
235    pub extensions: Option<Extensions>,
236    pub autoinstallation: Option<Autoinstallation>,
237    pub schema: Option<Schema>,
238    pub pixel_tracing: Option<PixelTracing>,
239    pub scripts: Option<Scripts>,
240    pub no_multicast_echo: bool,
241    pub no_ping_record_route: bool,
242    pub no_ping_time_stamp: bool,
243    pub auto_snapshot: bool,
244    pub compress_configuration_files: bool,
245    pub mirror_flash_on_disk: bool,
246    pub switchover_on_routing_crash: bool,
247    pub use_imported_time_zones: bool,
248    pub archival: Option<Archival>,
249    pub accounting: Option<Accounting>,
250    pub root_authentication: Option<RootAuthentication>,
251    pub master_password: Option<MasterPassword>,
252    /// Method name of `diag-port-authentication`, e.g. `encrypted-password`.
253    pub diag_port_authentication: Vec<String>,
254    /// The passwords of `diag-port-authentication`; empty unless the `secrets` feature is enabled.
255    pub diag_port_authentication_secrets: Vec<AuthenticationSecret>,
256    /// Method names of `pic-console-authentication`.
257    pub pic_console_authentication: Vec<String>,
258    /// The passwords of `pic-console-authentication`; empty unless the `secrets` feature is enabled.
259    pub pic_console_authentication_secrets: Vec<AuthenticationSecret>,
260    pub license: Option<License>,
261    pub name_servers: Vec<NameServer>,
262    pub ntp: Option<Ntp>,
263    pub syslog: Option<Syslog>,
264    pub login: Option<Login>,
265    pub services: Option<Services>,
266    pub arp: Option<Arp>,
267    pub icmp: Option<Icmp>,
268    pub tracing: Option<Tracing>,
269    pub proxy: Option<Proxy>,
270    pub demux_options: Option<DemuxOptions>,
271    pub kernel_replication: Option<KernelReplication>,
272    pub password_options: Option<PasswordOptions>,
273    pub radius_options: Option<RadiusOptions>,
274    pub tacplus_options: Option<TacplusOptions>,
275    pub configuration: Option<ConfigurationInput>,
276    pub configuration_database: Option<ConfigurationDatabase>,
277    pub export_format: Option<ExportFormat>,
278    pub health_monitor: Option<HealthMonitor>,
279    pub monitor: Option<Monitor>,
280    pub resiliency: Option<Resiliency>,
281    pub snapshot: Option<Snapshot>,
282    pub access_line: Option<AccessLine>,
283    pub ddos_protection: Option<DdosProtection>,
284    pub fib_streaming: Option<FibStreaming>,
285    pub packet_forwarding_options: Option<PacketForwardingOptions>,
286    /// The `protocol <name>` entries of `management-traffic`.
287    pub management_traffic: Vec<ManagementTrafficProtocol>,
288    /// Junos OS Evolved `auto-sw-sync node <name>` statements.
289    pub auto_sw_sync: Vec<AutoSwSync>,
290    /// Names from `node { offline <name>; }`.
291    pub offline_nodes: Vec<String>,
292    /// Method name of `boot-loader-authentication`, e.g. `encrypted-password`.
293    pub boot_loader_authentication: Vec<String>,
294    /// The passwords of `boot-loader-authentication`; empty unless the `secrets` feature is enabled.
295    pub boot_loader_authentication_secrets: Vec<AuthenticationSecret>,
296    /// Method name of `device-authentication`, e.g. `encrypted-password`.
297    pub device_authentication: Vec<String>,
298    /// The passwords of `device-authentication`; empty unless the `secrets` feature is enabled.
299    pub device_authentication_secrets: Vec<AuthenticationSecret>,
300    pub allow_6pe_traceroute: bool,
301    pub allow_l3vpn_traceroute_src_select: bool,
302    pub dual_phase_bootup: bool,
303    pub extended_echo: bool,
304    /// `management-instance`: confine the management interface in the `mgmt_junos` instance.
305    pub management_instance: bool,
306    pub nd_override_preferred_src: bool,
307    pub no_hidden_commands: bool,
308    pub regex_additive_logic: bool,
309    pub unattended_boot: bool,
310    pub arp_system_cache_limit: Option<String>,
311    pub nd_retransmit_timer: Option<String>,
312    pub nd_system_cache_limit: Option<String>,
313    /// `rng`: `dyce`, `fortuna` or `hmac-drbg`.
314    pub rng: Option<String>,
315    /// `Some(true)` for `saved-core-context`, `Some(false)` for `no-saved-core-context`.
316    pub saved_core_context: Option<bool>,
317    pub saved_core_files: Option<String>,
318}
319
320/// Returns the top-level `system` block, or `None` if there is none.
321///
322/// # Examples
323///
324/// ```
325/// use asterust::config::juniper;
326/// use asterust_junos::system::system;
327///
328/// let config = juniper::parse_braces("system {\n    host-name pe1;\n}\n");
329/// let system = system(&config).unwrap();
330/// assert_eq!(system.host_name.as_deref(), Some("pe1"));
331/// ```
332pub fn system(config: &Config) -> Option<System> {
333    let system = top_level(config, "system")?;
334    Some(System {
335        host_name: arg_of(system, "host-name").map(str::to_string),
336        domain_name: arg_of(system, "domain-name").map(str::to_string),
337        time_zone: arg_of(system, "time-zone").map(str::to_string),
338        domain_search: args_of(system, "domain-search")
339            .into_iter()
340            .flat_map(list_values)
341            .collect(),
342        static_host_mappings: static_host_mappings(system),
343        backup_router: arg_of(system, "backup-router").map(parse_backup_router),
344        inet6_backup_router: arg_of(system, "inet6-backup-router").map(parse_backup_router),
345        authentication_order: args_of(system, "authentication-order")
346            .into_iter()
347            .flat_map(list_values)
348            .collect(),
349        radius_servers: radius_servers(system, "radius-server"),
350        tacplus_servers: tacplus_servers(system, "tacplus-server"),
351        location: child_block(system, "location").map(parse_location),
352        ports: child_block(system, "ports").map(parse_ports),
353        max_configurations_on_flash: arg_of(system, "max-configurations-on-flash").map(str::to_string),
354        max_configuration_rollbacks: arg_of(system, "max-configuration-rollbacks").map(str::to_string),
355        no_redirects: has_leaf(system, "no-redirects"),
356        default_address_selection: has_leaf(system, "default-address-selection"),
357        internet_options: child_block(system, "internet-options").map(parse_internet_options),
358        commit: child_block(system, "commit").map(parse_commit),
359        processes: child_block(system, "processes")
360            .map(parse_processes)
361            .unwrap_or_default(),
362        dynamic_profile_options: child_block(system, "dynamic-profile-options").map(parse_dynamic_profile_options),
363        extensions: child_block(system, "extensions").map(parse_extensions),
364        autoinstallation: child_block(system, "autoinstallation").map(parse_autoinstallation),
365        schema: child_block(system, "schema").map(parse_schema),
366        pixel_tracing: child_block(system, "pixel-tracing").map(parse_pixel_tracing),
367        scripts: child_block(system, "scripts").map(parse_scripts),
368        no_multicast_echo: has_leaf(system, "no-multicast-echo"),
369        no_ping_record_route: has_leaf(system, "no-ping-record-route"),
370        no_ping_time_stamp: has_leaf(system, "no-ping-time-stamp"),
371        auto_snapshot: has_leaf(system, "auto-snapshot"),
372        compress_configuration_files: has_leaf(system, "compress-configuration-files"),
373        mirror_flash_on_disk: has_leaf(system, "mirror-flash-on-disk"),
374        switchover_on_routing_crash: has_leaf(system, "switchover-on-routing-crash"),
375        use_imported_time_zones: has_leaf(system, "use-imported-time-zones"),
376        archival: child_block(system, "archival").map(parse_archival),
377        accounting: child_block(system, "accounting").map(parse_accounting),
378        root_authentication: root_authentication(system),
379        master_password: child_block(system, "master-password").map(parse_master_password),
380        diag_port_authentication: password_methods(system, "diag-port-authentication"),
381        diag_port_authentication_secrets: password_secrets(system, "diag-port-authentication"),
382        pic_console_authentication: password_methods(system, "pic-console-authentication"),
383        pic_console_authentication_secrets: password_secrets(system, "pic-console-authentication"),
384        license: child_block(system, "license").map(parse_license),
385        name_servers: name_servers(system),
386        ntp: child_block(system, "ntp").map(parse_ntp),
387        syslog: child_block(system, "syslog").map(parse_syslog),
388        login: child_block(system, "login").map(parse_login),
389        services: child_block(system, "services").map(parse_services),
390        arp: child_block(system, "arp").map(parse_arp),
391        icmp: child_block(system, "icmp").map(parse_icmp),
392        tracing: child_block(system, "tracing").map(parse_tracing),
393        proxy: child_block(system, "proxy").map(parse_proxy),
394        demux_options: child_block(system, "demux-options").map(parse_demux_options),
395        kernel_replication: child_block(system, "kernel-replication").map(parse_kernel_replication),
396        password_options: child_block(system, "password-options").map(parse_password_options),
397        radius_options: child_block(system, "radius-options").map(parse_radius_options),
398        tacplus_options: child_block(system, "tacplus-options").map(parse_tacplus_options),
399        configuration: child_block(system, "configuration").map(parse_configuration),
400        configuration_database: child_block(system, "configuration-database").map(parse_configuration_database),
401        export_format: child_block(system, "export-format").map(parse_export_format),
402        health_monitor: child_block(system, "health-monitor").map(parse_health_monitor),
403        monitor: child_block(system, "monitor").map(parse_monitor),
404        resiliency: child_block(system, "resiliency").map(parse_resiliency),
405        snapshot: child_block(system, "snapshot").map(parse_snapshot),
406        access_line: child_block(system, "access-line").map(parse_access_line),
407        ddos_protection: child_block(system, "ddos-protection").map(parse_ddos_protection),
408        fib_streaming: child_block(system, "fib-streaming").map(parse_fib_streaming),
409        packet_forwarding_options: child_block(system, "packet-forwarding-options")
410            .map(parse_packet_forwarding_options),
411        management_traffic: management_traffic(system),
412        auto_sw_sync: auto_sw_sync(system),
413        offline_nodes: child_block(system, "node")
414            .map(|node| args_of(node, "offline").into_iter().map(str::to_string).collect())
415            .unwrap_or_default(),
416        boot_loader_authentication: password_methods(system, "boot-loader-authentication"),
417        boot_loader_authentication_secrets: password_secrets(system, "boot-loader-authentication"),
418        device_authentication: password_methods(system, "device-authentication"),
419        device_authentication_secrets: password_secrets(system, "device-authentication"),
420        allow_6pe_traceroute: has_leaf(system, "allow-6pe-traceroute"),
421        allow_l3vpn_traceroute_src_select: has_leaf(system, "allow-l3vpn-traceroute-src-select"),
422        dual_phase_bootup: has_leaf(system, "dual-phase-bootup"),
423        extended_echo: has_leaf(system, "extended-echo"),
424        management_instance: has_leaf(system, "management-instance"),
425        nd_override_preferred_src: has_leaf(system, "nd-override-preferred-src"),
426        no_hidden_commands: has_leaf(system, "no-hidden-commands"),
427        regex_additive_logic: has_leaf(system, "regex-additive-logic"),
428        unattended_boot: has_leaf(system, "unattended-boot"),
429        arp_system_cache_limit: arg_of(system, "arp-system-cache-limit").map(str::to_string),
430        nd_retransmit_timer: arg_of(system, "nd-retransmit-timer").map(str::to_string),
431        nd_system_cache_limit: arg_of(system, "nd-system-cache-limit").map(str::to_string),
432        rng: arg_of(system, "rng").map(str::to_string),
433        saved_core_context: toggle(system, "saved-core-context"),
434        saved_core_files: arg_of(system, "saved-core-files").map(str::to_string),
435    })
436}
437
438/// Servers written as `<keyword> <address> { ... }`, or as `<keyword> { <address> { ... } }`, with
439/// their option lines.
440fn servers<'a>(system: &'a ConfigLine, keyword: &str) -> Vec<(&'a str, &'a ConfigLine)> {
441    let mut found = Vec::new();
442    for child in active_children(system) {
443        if child.text == keyword {
444            found.extend(active_children(child).map(|server| (unquote(&server.text), server)));
445        } else if let Some(arg) = child.arg(keyword) {
446            found.push((split_name(arg).0, child));
447        }
448    }
449    found
450}
451
452/// The method names of a password setting such as `diag-port-authentication`, written either as
453/// `<keyword> encrypted-password "...";` or as a block. The passwords are dropped.
454fn password_methods(system: &ConfigLine, keyword: &str) -> Vec<String> {
455    let mut methods = Vec::new();
456    for child in active_children(system) {
457        if child.text == keyword {
458            methods.extend(authentication_methods(child));
459        } else if let Some(method) = child.arg(keyword).and_then(|arg| arg.split_whitespace().next()) {
460            methods.push(method.to_string());
461        }
462    }
463    methods
464}
465
466/// The name of each statement in an `authentication` block. Secrets can carry a trailing `##
467/// SECRET-DATA` marker, so only the first word is kept.
468fn authentication_methods(auth: &ConfigLine) -> Vec<String> {
469    active_children(auth)
470        .filter_map(|c| c.text.split_whitespace().next())
471        .map(str::to_string)
472        .collect()
473}
474
475#[cfg(test)]
476mod tests {
477    use crate::system::system;
478    use asterust::config::juniper;
479
480    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
481    #[test]
482    fn extracts_host_name() {
483        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
484        assert_eq!(system.host_name.as_deref(), Some("pe1"));
485    }
486
487    #[test]
488    fn host_name_is_optional() {
489        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
490        assert_eq!(system.host_name, None);
491    }
492
493    #[test]
494    fn skips_inactive_host_name() {
495        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
496        assert_eq!(system.host_name, None);
497    }
498
499    #[test]
500    fn extracts_domain_name() {
501        let system = system(&juniper::parse_braces(
502            "system {\n    host-name pe1;\n    domain-name example.net;\n}\n",
503        ))
504        .unwrap();
505        assert_eq!(system.domain_name.as_deref(), Some("example.net"));
506    }
507
508    #[test]
509    fn domain_name_is_optional() {
510        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
511        assert_eq!(system.domain_name, None);
512    }
513
514    #[test]
515    fn extracts_time_zone() {
516        let system = system(&juniper::parse_braces("system {\n    time-zone America/New_York;\n}\n")).unwrap();
517        assert_eq!(system.time_zone.as_deref(), Some("America/New_York"));
518    }
519
520    #[test]
521    fn time_zone_is_optional() {
522        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
523        assert_eq!(system.time_zone, None);
524    }
525
526    #[test]
527    fn extracts_configuration_limits_and_no_redirects() {
528        let system = system(&juniper::parse_braces(
529            "system {\n    max-configurations-on-flash 5;\n    max-configuration-rollbacks 20;\n    no-redirects;\n}\n",
530        ))
531        .unwrap();
532        assert_eq!(system.max_configurations_on_flash.as_deref(), Some("5"));
533        assert_eq!(system.max_configuration_rollbacks.as_deref(), Some("20"));
534        assert!(system.no_redirects);
535    }
536
537    #[test]
538    fn configuration_limits_are_optional() {
539        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
540        assert_eq!(system.max_configurations_on_flash, None);
541        assert_eq!(system.max_configuration_rollbacks, None);
542        assert!(!system.no_redirects);
543    }
544
545    #[test]
546    fn extracts_system_flags() {
547        let system = system(&juniper::parse_braces(
548            "system {\n    no-multicast-echo;\n    no-ping-record-route;\n    no-ping-time-stamp;\n    auto-snapshot;\n    compress-configuration-files;\n    mirror-flash-on-disk;\n    switchover-on-routing-crash;\n    use-imported-time-zones;\n}\n",
549        ))
550        .unwrap();
551        assert!(system.no_multicast_echo);
552        assert!(system.no_ping_record_route);
553        assert!(system.no_ping_time_stamp);
554        assert!(system.auto_snapshot);
555        assert!(system.compress_configuration_files);
556        assert!(system.mirror_flash_on_disk);
557        assert!(system.switchover_on_routing_crash);
558        assert!(system.use_imported_time_zones);
559    }
560
561    #[test]
562    fn system_flags_default_to_off() {
563        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
564        assert!(!system.no_multicast_echo);
565        assert!(!system.auto_snapshot);
566        assert!(!system.use_imported_time_zones);
567    }
568
569    #[test]
570    fn no_system_is_none() {
571        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
572    }
573
574    #[test]
575    fn diag_port_and_pic_console_report_only_the_method() {
576        let system = system(&juniper::parse_braces(
577            r#"
578system {
579    diag-port-authentication encrypted-password "$6$salt$hash"; ## SECRET-DATA
580    pic-console-authentication {
581        encrypted-password "$6$salt$other"; ## SECRET-DATA
582    }
583}
584"#,
585        ))
586        .unwrap();
587        assert_eq!(system.diag_port_authentication, ["encrypted-password"]);
588        assert_eq!(system.pic_console_authentication, ["encrypted-password"]);
589        let values = |secrets: &[crate::system::AuthenticationSecret]| -> Vec<String> {
590            secrets.iter().map(|s| s.value.expose().to_string()).collect()
591        };
592        let (diag, pic) = if cfg!(feature = "secrets") {
593            (vec!["$6$salt$hash".to_string()], vec!["$6$salt$other".to_string()])
594        } else {
595            (Vec::new(), Vec::new())
596        };
597        assert_eq!(values(&system.diag_port_authentication_secrets), diag);
598        assert_eq!(values(&system.pic_console_authentication_secrets), pic);
599    }
600
601    #[test]
602    fn secret_settings_are_optional() {
603        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
604        assert!(system.master_password.is_none());
605        assert!(system.diag_port_authentication.is_empty());
606        assert!(system.pic_console_authentication.is_empty());
607    }
608
609    #[test]
610    fn extracts_authentication_order() {
611        let system = system(&juniper::parse_braces(
612            "system {\n    authentication-order [ tacplus radius password ];\n}\n",
613        ))
614        .unwrap();
615        assert_eq!(system.authentication_order, ["tacplus", "radius", "password"]);
616    }
617
618    #[test]
619    fn authentication_settings_are_optional() {
620        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
621        assert!(system.authentication_order.is_empty());
622        assert!(system.radius_servers.is_empty());
623        assert!(system.tacplus_servers.is_empty());
624    }
625
626    #[test]
627    fn extracts_domain_search_list() {
628        let system = system(&juniper::parse_braces(
629            "system {\n    domain-search [ example.net lab.example.net ];\n}\n",
630        ))
631        .unwrap();
632        assert_eq!(system.domain_search, ["example.net", "lab.example.net"]);
633    }
634
635    #[test]
636    fn addressing_settings_are_optional() {
637        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
638        assert!(system.domain_search.is_empty());
639        assert!(system.static_host_mappings.is_empty());
640        assert!(system.backup_router.is_none());
641        assert!(system.inet6_backup_router.is_none());
642    }
643
644    #[test]
645    fn extracts_the_scalar_flags_and_limits() {
646        let system = system(&juniper::parse_braces(
647            r#"
648system {
649    allow-6pe-traceroute;
650    allow-l3vpn-traceroute-src-select;
651    dual-phase-bootup;
652    extended-echo;
653    management-instance;
654    nd-override-preferred-src;
655    no-hidden-commands;
656    regex-additive-logic;
657    unattended-boot;
658    arp-system-cache-limit 50000;
659    nd-retransmit-timer 2000;
660    nd-system-cache-limit 150000;
661    rng fortuna;
662    saved-core-files 3;
663    saved-core-context;
664}
665"#,
666        ))
667        .unwrap();
668        assert!(system.allow_6pe_traceroute);
669        assert!(system.allow_l3vpn_traceroute_src_select);
670        assert!(system.dual_phase_bootup);
671        assert!(system.extended_echo);
672        assert!(system.management_instance);
673        assert!(system.nd_override_preferred_src);
674        assert!(system.no_hidden_commands);
675        assert!(system.regex_additive_logic);
676        assert!(system.unattended_boot);
677        assert_eq!(system.arp_system_cache_limit.as_deref(), Some("50000"));
678        assert_eq!(system.nd_retransmit_timer.as_deref(), Some("2000"));
679        assert_eq!(system.nd_system_cache_limit.as_deref(), Some("150000"));
680        assert_eq!(system.rng.as_deref(), Some("fortuna"));
681        assert_eq!(system.saved_core_files.as_deref(), Some("3"));
682        assert_eq!(system.saved_core_context, Some(true));
683    }
684
685    #[test]
686    fn reads_no_saved_core_context() {
687        let system = system(&juniper::parse_braces("system {\n    no-saved-core-context;\n}\n")).unwrap();
688        assert_eq!(system.saved_core_context, Some(false));
689    }
690
691    #[test]
692    fn scalar_flags_and_limits_are_optional() {
693        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
694        assert!(!system.allow_6pe_traceroute);
695        assert!(!system.management_instance);
696        assert!(!system.unattended_boot);
697        assert_eq!(system.arp_system_cache_limit, None);
698        assert_eq!(system.rng, None);
699        assert_eq!(system.saved_core_context, None);
700        assert!(system.offline_nodes.is_empty());
701    }
702
703    #[test]
704    fn extracts_offline_nodes() {
705        let system = system(&juniper::parse_braces(
706            "system {\n    node {\n        offline re1;\n        offline fpc3;\n    }\n}\n",
707        ))
708        .unwrap();
709        assert_eq!(system.offline_nodes, ["re1", "fpc3"]);
710    }
711
712    #[test]
713    fn boot_loader_and_device_authentication_report_only_the_method() {
714        let system = system(&juniper::parse_braces(
715            r#"
716system {
717    boot-loader-authentication {
718        encrypted-password "$1$salt$hash"; ## SECRET-DATA
719    }
720    device-authentication {
721        encrypted-password "$6$salt$other"; ## SECRET-DATA
722    }
723}
724"#,
725        ))
726        .unwrap();
727        assert_eq!(system.boot_loader_authentication, ["encrypted-password"]);
728        assert_eq!(system.device_authentication, ["encrypted-password"]);
729        let values = |secrets: &[crate::system::AuthenticationSecret]| -> Vec<String> {
730            secrets.iter().map(|s| s.value.expose().to_string()).collect()
731        };
732        let (boot, device) = if cfg!(feature = "secrets") {
733            (vec!["$1$salt$hash".to_string()], vec!["$6$salt$other".to_string()])
734        } else {
735            (Vec::new(), Vec::new())
736        };
737        assert_eq!(values(&system.boot_loader_authentication_secrets), boot);
738        assert_eq!(values(&system.device_authentication_secrets), device);
739    }
740}