nmrs 3.1.1

A Rust library for NetworkManager over D-Bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! A Rust library for managing network connections via NetworkManager.
//!
//! This crate provides a high-level async API for NetworkManager over D-Bus,
//! enabling easy management of WiFi, Ethernet, and VPN connections on Linux.
//!
//! # Quick Start
//!
//! ## WiFi Connection
//!
//! ```rust
//! use nmrs::{NetworkManager, WifiSecurity};
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! // List visible networks (None = all Wi-Fi devices)
//! let networks = nm.list_networks(None).await?;
//! for net in &networks {
//!     println!("{} - Signal: {}%", net.ssid, net.strength.unwrap_or(0));
//! }
//!
//! // Connect to a network on the first Wi-Fi device
//! nm.connect("MyNetwork", None, WifiSecurity::WpaPsk {
//!     psk: "password123".into()
//! }).await?;
//!
//! // Check current connection
//! if let Some(ssid) = nm.current_ssid().await {
//!     println!("Connected to: {}", ssid);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## VPN Connection (WireGuard)
//!
//! ```rust
//! use nmrs::{NetworkManager, WireGuardConfig, WireGuardPeer};
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! let peer = WireGuardPeer::new(
//!     "peer_public_key",
//!     "vpn.example.com:51820",
//!     vec!["0.0.0.0/0".into()],
//! ).with_persistent_keepalive(25);
//!
//! let config = WireGuardConfig::new(
//!     "MyVPN",
//!     "vpn.example.com:51820",
//!     "your_private_key",
//!     "10.0.0.2/24",
//!     vec![peer],
//! ).with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]);
//!
//! nm.connect_vpn(config).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## VPN Connection (OpenVPN)
//!
//! ```rust
//! use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType};
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! let config = OpenVpnConfig::new("CorpVPN", "vpn.example.com", 1194, false)
//!     .with_auth_type(OpenVpnAuthType::PasswordTls)
//!     .with_username("user")
//!     .with_password("secret")
//!     .with_ca_cert("/etc/openvpn/ca.crt")
//!     .with_client_cert("/etc/openvpn/client.crt")
//!     .with_client_key("/etc/openvpn/client.key");
//!
//! nm.connect_vpn(config).await?;
//!
//! // Or import an .ovpn file directly:
//! nm.import_ovpn("corp.ovpn", Some("user"), Some("secret")).await?;
//!
//! // List VPN connections
//! let vpns = nm.list_vpn_connections().await?;
//! for vpn in vpns {
//!     println!("{}: {:?} - {:?}", vpn.name, vpn.vpn_type, vpn.state);
//! }
//!
//! nm.disconnect_vpn("CorpVPN").await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Core Concepts
//!
//! ## NetworkManager
//!
//! The main entry point is [`NetworkManager`], which provides methods for:
//! - Listing and managing network devices
//! - Scanning for available Wi-Fi networks
//! - Connecting to networks (Wi-Fi, Ethernet, Bluetooth PAN, VPN)
//! - Managing saved connection profiles
//! - Real-time monitoring of network and device changes
//! - Querying connectivity state and captive-portal URLs
//! - Toggling Wi-Fi/WWAN/Bluetooth radios and airplane mode
//!
//! ## Models
//!
//! The [`models`] module contains all types, enums, and errors. The most
//! commonly used items are also re-exported at the crate root:
//!
//! - [`Device`] / [`DeviceType`] / [`DeviceState`] — network devices and their state
//! - [`Network`] / [`AccessPoint`] / [`NetworkInfo`] — discovered Wi-Fi data
//! - [`WifiDevice`] — per-Wi-Fi-device summary
//! - [`WifiSecurity`] / [`EapOptions`] / [`EapMethod`] / [`Phase2`] — Wi-Fi security
//! - [`ConnectionOptions`] / [`TimeoutConfig`] — connection knobs
//! - [`WireGuardConfig`] / [`WireGuardPeer`] — WireGuard configuration
//! - [`OpenVpnConfig`] / [`OpenVpnAuthType`] / [`OpenVpnProxy`] — OpenVPN configuration
//! - [`VpnConfig`] / [`VpnConfiguration`] — generic VPN dispatch trait/enum
//! - [`VpnConnection`] / [`VpnConnectionInfo`] / [`VpnDetails`] / [`VpnType`] / [`VpnKind`] — saved or active VPN data
//! - [`SavedConnection`] / [`SavedConnectionBrief`] / [`SettingsSummary`] / [`SettingsPatch`] — saved profile management
//! - [`AirplaneModeState`] / [`RadioState`] — radio/rfkill state
//! - [`BluetoothDevice`] / [`BluetoothIdentity`] / [`BluetoothNetworkRole`] — Bluetooth networking
//! - [`ConnectivityState`] / [`ConnectivityReport`] — internet connectivity
//! - [`ConnectionError`] / [`StateReason`] / [`ConnectionStateReason`] — errors
//!
//! [`VpnCredentials`] is still re-exported but is **deprecated**; new code
//! should use [`WireGuardConfig`] together with [`NetworkManager::connect_vpn`].
//!
//! ## Connection Builders
//!
//! The [`builders`] module provides both fluent builder types
//! ([`builders::ConnectionBuilder`], [`builders::WifiConnectionBuilder`],
//! [`builders::WireGuardBuilder`], [`builders::OpenVpnBuilder`]) and
//! free functions (`build_wifi_connection`, `build_ethernet_connection`,
//! `build_wireguard_connection`, `build_openvpn_connection`,
//! `build_bluetooth_connection`, `build_vlan_connection`) for constructing
//! NetworkManager settings dictionaries. Most callers should reach for the
//! higher-level [`NetworkManager`] API; these builders are exposed for
//! advanced use cases that need to assemble the raw settings dictionary
//! before calling a D-Bus method directly.
//!
//! ## Secret Agent
//!
//! The [`agent`] module lets a consumer register a NetworkManager **secret
//! agent** to handle interactive credential prompts (Wi-Fi passwords, VPN
//! tokens, 802.1X passwords) over D-Bus. See the module docs for the
//! three-stream model and a full example.
//!
//! # Examples
//!
//! ## Connecting to Different Network Types
//!
//! ```rust
//! use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2};
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! // Open network
//! nm.connect("OpenWiFi", None, WifiSecurity::Open).await?;
//!
//! // WPA-PSK (password-protected)
//! nm.connect("HomeWiFi", None, WifiSecurity::WpaPsk {
//!     psk: "my_password".into()
//! }).await?;
//!
//! // WPA-EAP (Enterprise)
//! let eap_opts = EapOptions::new("user@company.com", "password")
//!     .with_domain_suffix_match("company.com")
//!     .with_system_ca_certs(true)
//!     .with_method(EapMethod::Peap)
//!     .with_phase2(Phase2::Mschapv2);
//!
//! nm.connect("CorpWiFi", None, WifiSecurity::WpaEap {
//!     opts: eap_opts
//! }).await?;
//!
//! // Ethernet (auto-connects when cable is plugged in)
//! nm.connect_wired().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Error Handling
//!
//! All operations return [`Result<T>`], which is an alias for `Result<T, ConnectionError>`.
//! The [`ConnectionError`] type provides specific variants for different failure modes:
//!
//! ```rust
//! use nmrs::{NetworkManager, WifiSecurity, ConnectionError};
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! match nm.connect("MyNetwork", None, WifiSecurity::WpaPsk {
//!     psk: "wrong_password".into()
//! }).await {
//!     Ok(_) => println!("Connected successfully"),
//!     Err(ConnectionError::AuthFailed) => {
//!         eprintln!("Wrong password!");
//!     }
//!     Err(ConnectionError::NotFound) => {
//!         eprintln!("Network not found or out of range");
//!     }
//!     Err(ConnectionError::Timeout) => {
//!         eprintln!("Connection timed out");
//!     }
//!     Err(ConnectionError::DhcpFailed) => {
//!         eprintln!("Failed to obtain IP address");
//!     }
//!     Err(e) => eprintln!("Error: {}", e),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Device Management
//!
//! ```rust
//! use nmrs::NetworkManager;
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! // List all devices
//! let devices = nm.list_devices().await?;
//! for device in devices {
//!     println!("{}: {} ({})",
//!         device.interface,
//!         device.device_type,
//!         device.state
//!     );
//! }
//!
//! // Enable/disable WiFi
//! nm.set_wireless_enabled(false).await?;
//! nm.set_wireless_enabled(true).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Real-Time Monitoring
//!
//! Monitor network and device changes in real-time using D-Bus signals:
//!
//! ```rust
//! use nmrs::NetworkManager;
//!
//! # async fn example() -> nmrs::Result<()> {
//! let nm = NetworkManager::new().await?;
//!
//! // Monitor network changes (new networks, signal changes, etc.)
//! nm.monitor_network_changes(|| {
//!     println!("Networks changed! Refresh your UI.");
//! }).await?;
//!
//! // Monitor device state changes (cable plugged in, device activated, etc.)
//! nm.monitor_device_changes(|| {
//!     println!("Device state changed!");
//! }).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Architecture
//!
//! This crate uses D-Bus signals for efficient state monitoring instead of polling.
//! When connecting to a network, it subscribes to NetworkManager's `StateChanged`
//! signals to detect connection success or failure immediately. This provides:
//!
//! - **Faster response times** - Immediate notification vs polling delay
//! - **Lower CPU usage** - No spinning loops
//! - **Better error messages** - Specific failure reasons from NetworkManager
//!
//! # Logging
//!
//! This crate uses the [`log`](https://docs.rs/log) facade. To see log output,
//! add a logging implementation like `env_logger`:
//!
//! ```no_run,ignore
//! env_logger::init();
//! ```
//!
//! # Feature Flags
//!
//! This crate currently has no optional features. All functionality is enabled by default.
//!
//! # Platform Support
//!
//! This crate is Linux-only and requires:
//! - NetworkManager running and accessible via D-Bus
//! - Appropriate permissions to manage network connections

// Internal modules (not exposed in public API)
mod api;
mod core;
mod dbus;
mod monitoring;
mod types;
mod util;

/// NetworkManager secret agent for credential prompting over D-Bus.
///
/// See the [module documentation](agent) for the three-stream model,
/// lifecycle, and a full example.
pub mod agent;

// ============================================================================
// Public API
// ============================================================================

/// Connection builders for Wi-Fi, Ethernet, Bluetooth, VLAN, and VPN connections.
///
/// This module provides two complementary APIs for constructing NetworkManager
/// settings dictionaries:
///
/// - **Fluent builder types** — [`ConnectionBuilder`](builders::ConnectionBuilder),
///   [`WifiConnectionBuilder`](builders::WifiConnectionBuilder),
///   [`WireGuardBuilder`](builders::WireGuardBuilder), and
///   [`OpenVpnBuilder`](builders::OpenVpnBuilder), which support method
///   chaining and validation at `.build()`.
/// - **Free functions** — `build_wifi_connection`, `build_ethernet_connection`,
///   `build_wireguard_connection`, `build_openvpn_connection`,
///   `build_bluetooth_connection`, and `build_vlan_connection`, which are
///   handy for one-shot construction.
///
/// Most callers should prefer [`NetworkManager`](crate::NetworkManager)'s
/// high-level methods such as [`connect`](crate::NetworkManager::connect)
/// and [`connect_vpn`](crate::NetworkManager::connect_vpn). Use these
/// builders only when you need to feed a raw settings dictionary to
/// NetworkManager's `AddConnection` or `AddAndActivateConnection` D-Bus
/// methods directly.
///
/// # Example
///
/// ```rust
/// use nmrs::builders::build_wifi_connection;
/// use nmrs::{ConnectionOptions, WifiSecurity};
///
/// let opts = ConnectionOptions::new(true);
/// let settings = build_wifi_connection("MyNetwork", &WifiSecurity::Open, &opts);
/// // `settings` can be passed straight to NetworkManager via D-Bus.
/// ```
pub mod builders {
    pub use crate::api::builders::*;
}

/// Types, enums, and errors for NetworkManager operations.
///
/// This module re-exports every public data type used by the crate.
/// The same types are also re-exported at the crate root for convenience
/// (so `nmrs::Device` and `nmrs::models::Device` refer to the same type),
/// with the exceptions of [`NetworkManager`](crate::NetworkManager) and
/// [`WifiScope`](crate::WifiScope), which live only at the crate root.
///
/// # Core Data Types
/// - [`Device`] — Network device representation
/// - [`Network`] — Wi-Fi network representation (SSID-grouped)
/// - [`AccessPoint`] — Per-BSSID access point details
/// - [`NetworkInfo`] — Detailed network information returned by `show_details`
/// - [`WifiDevice`] — Wi-Fi-specific device summary
/// - [`BluetoothDevice`] — Discovered Bluetooth peer
/// - [`SavedConnection`] / [`SavedConnectionBrief`] — Saved profile snapshots
/// - [`SettingsSummary`] / [`SettingsPatch`] — Decoded NM settings & update patches
/// - [`VpnConnection`] / [`VpnConnectionInfo`] / [`VpnDetails`] — Active or saved VPN data
///
/// # Configuration
/// - [`WifiSecurity`] — Wi-Fi security types (Open, WPA-PSK, WPA-EAP)
/// - [`EapOptions`] — Enterprise authentication options
/// - [`ConnectionOptions`] — Connection settings (autoconnect, priority, retries)
/// - [`TimeoutConfig`] — Timeout configuration for connection operations
/// - [`WireGuardConfig`] / [`WireGuardPeer`] — WireGuard tunnel configuration
/// - [`OpenVpnConfig`] — OpenVPN plugin configuration
/// - [`VlanConfig`] — VLAN tagging configuration
/// - [`BluetoothIdentity`] — Bluetooth target (bdaddr + role)
/// - [`VpnConfig`] / [`VpnConfiguration`] — Trait & enum used by `connect_vpn`
///
/// # Enums
/// - [`DeviceType`] — Device types (Ethernet, Wi-Fi, Bluetooth, etc.)
/// - [`DeviceState`] — Device states (Disconnected, Activated, etc.)
/// - [`ActiveConnectionState`] — State of an active connection
/// - [`ConnectivityState`] — NM-reported internet connectivity
/// - [`RadioState`] / [`AirplaneModeState`] — Radio/rfkill state
/// - [`ApMode`] — Access point operating mode
/// - [`BluetoothNetworkRole`] — PAN-U / NAP / DUN roles
/// - [`EapMethod`] — EAP authentication methods
/// - [`Phase2`] — Phase 2 authentication for EAP
/// - [`OpenVpnAuthType`] / [`OpenVpnConnectionType`] / [`OpenVpnCompression`] — OpenVPN auth/transport options
/// - [`OpenVpnProxy`] — OpenVPN HTTP/SOCKS proxy configuration
/// - [`VpnKind`] / [`VpnType`] — Plugin vs. kernel WireGuard, plus protocol-specific metadata
/// - [`VpnSecretFlags`] — NM secret flags for VPN credentials
/// - [`WifiKeyMgmt`] / [`WifiSecuritySummary`] / [`SecurityFeatures`] — Decoded Wi-Fi security info
/// - [`ConnectType`] — How a `connect_vpn` call resolved (saved vs. new)
///
/// # Errors
/// - [`ConnectionError`] — Comprehensive error type for all operations
/// - [`StateReason`] — Device state change reasons
/// - [`ConnectionStateReason`] — Connection state change reasons
///
/// # Helper Functions
/// - [`reason_to_error`] — Convert a device state reason to a [`ConnectionError`]
/// - [`connection_state_reason_to_error`] — Convert an active-connection state reason to a [`ConnectionError`]
pub mod models {
    pub use crate::api::models::*;
}

// Re-export commonly used types at crate root for convenience
#[allow(deprecated)]
pub use api::models::{
    AccessPoint, ActiveConnectionState, AirplaneModeState, ApMode, BluetoothDevice,
    BluetoothIdentity, BluetoothNetworkRole, ConnectType, ConnectionError, ConnectionOptions,
    ConnectionStateReason, ConnectivityReport, ConnectivityState, Device, DeviceState, DeviceType,
    EapMethod, EapOptions, Network, NetworkInfo, OpenVpnAuthType, OpenVpnCompression,
    OpenVpnConfig, OpenVpnConnectionType, OpenVpnProxy, Phase2, RadioState, SavedConnection,
    SavedConnectionBrief, SecurityFeatures, SettingsPatch, SettingsSummary, StateReason,
    TimeoutConfig, VlanConfig, VpnConfig, VpnConfiguration, VpnConnection, VpnConnectionInfo,
    VpnCredentials, VpnDetails, VpnKind, VpnRoute, VpnSecretFlags, VpnType, WifiDevice,
    WifiKeyMgmt, WifiSecurity, WifiSecuritySummary, WireGuardConfig, WireGuardPeer,
    connection_state_reason_to_error, reason_to_error,
};
pub use api::network_manager::NetworkManager;
pub use api::wifi_scope::WifiScope;

/// A specialized `Result` type for network operations.
///
/// This is an alias for `Result<T, ConnectionError>` and is used throughout
/// the crate for all fallible operations.
///
/// # Examples
///
/// ```rust
/// use nmrs::Result;
///
/// async fn connect_to_wifi() -> Result<()> {
///     // Your code here
///     Ok(())
/// }
/// ```
pub type Result<T> = std::result::Result<T, ConnectionError>;