nmrs 3.4.0

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
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Network device enumeration and control.
//!
//! Provides functions for listing network devices, checking Wi-Fi state,
//! and enabling/disabling Wi-Fi. Uses D-Bus signals for efficient state
//! monitoring instead of polling.

use log::{debug, warn};
use zbus::Connection;

use crate::Result;
use crate::api::models::{
    BluetoothDevice, ConnectionError, Device, DeviceIdentity, DeviceState, WiredDevice,
};
use crate::core::bluetooth::populate_bluez_info;
use crate::core::connection::get_device_by_interface;
use crate::core::state_wait::wait_for_wifi_device_ready;
use crate::dbus::{
    NMAccessPointProxy, NMActiveConnectionProxy, NMBluetoothProxy, NMDeviceProxy, NMProxy,
    NMWiredProxy, NMWirelessProxy,
};
use crate::types::constants::device_type;
use crate::util::utils::get_ip_addresses_from_active_connection;

/// Lists all network devices managed by NetworkManager.
///
/// Returns information about each device including its interface name,
/// type (Ethernet, Wi-Fi, etc.), current state, and driver.
pub(crate) async fn list_devices(conn: &Connection) -> Result<Vec<Device>> {
    let proxy = NMProxy::new(conn).await?;
    let paths = proxy
        .get_devices()
        .await
        .map_err(|e| ConnectionError::DbusOperation {
            context: "failed to get device paths from NetworkManager".to_string(),
            source: e,
        })?;

    let mut devices = Vec::new();
    for p in paths {
        let d_proxy = NMDeviceProxy::builder(conn)
            .path(p.clone())?
            .build()
            .await?;

        let interface = d_proxy
            .interface()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("failed to get interface name for device {}", p.as_str()),
                source: e,
            })?;

        let raw_type = d_proxy
            .device_type()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("failed to get device type for {}", interface),
                source: e,
            })?;
        let current_mac = match d_proxy.hw_address().await {
            Ok(addr) => addr,
            Err(e) => {
                warn!(
                    "Failed to get hardware address for device {}: {}",
                    interface, e
                );
                String::from("00:00:00:00:00:00")
            }
        };

        let perm_mac = match d_proxy.perm_hw_address().await {
            Ok(addr) => addr,
            Err(e) => {
                debug!(
                    "Permanent hardware address not available for device {}: {}",
                    interface, e
                );
                current_mac.clone()
            }
        };

        let device_type = raw_type.into();
        let raw_state = d_proxy.state().await?;
        let state = raw_state.into();
        let managed = match d_proxy.managed().await {
            Ok(m) => Some(m),
            Err(e) => {
                debug!(
                    "Failed to get 'managed' property for device {}: {}",
                    interface, e
                );
                None
            }
        };
        let driver = match d_proxy.driver().await {
            Ok(d) => Some(d),
            Err(e) => {
                debug!("Failed to get driver for device {}: {}", interface, e);
                None
            }
        };
        let frequency = if raw_type == device_type::WIFI {
            match NMWirelessProxy::builder(conn)
                .path(p.clone())?
                .build()
                .await
            {
                Ok(wifi) => match wifi.active_access_point().await {
                    Ok(ap_path) if ap_path.as_str() != "/" => {
                        match NMAccessPointProxy::builder(conn)
                            .path(ap_path)?
                            .build()
                            .await
                        {
                            Ok(ap) => ap.frequency().await.ok(),
                            Err(e) => {
                                debug!("Failed to build active AP proxy for {}: {}", interface, e);
                                None
                            }
                        }
                    }
                    Ok(_) => None,
                    Err(e) => {
                        debug!("Failed to get active AP for {}: {}", interface, e);
                        None
                    }
                },
                Err(e) => {
                    debug!("Failed to build wireless proxy for {}: {}", interface, e);
                    None
                }
            }
        } else {
            None
        };

        // Get IP addresses from active connection
        let (ip4_address, ip6_address) =
            if let Ok(active_conn_path) = d_proxy.active_connection().await {
                if active_conn_path.as_str() != "/" {
                    get_ip_addresses_from_active_connection(conn, &active_conn_path).await
                } else {
                    (None, None)
                }
            } else {
                (None, None)
            };

        let speed_mbps = if raw_type == device_type::ETHERNET {
            async {
                let wired = NMWiredProxy::builder(conn).path(p.clone())?.build().await?;
                wired.speed().await
            }
            .await
            .ok()
        } else {
            None
        };

        devices.push(Device {
            path: p.to_string(),
            interface,
            identity: DeviceIdentity::new(perm_mac, current_mac),
            device_type,
            state,
            managed,
            driver,
            ip4_address,
            ip6_address,
            frequency,
            speed_mbps,
        });
    }
    Ok(devices)
}

/// Lists wired Ethernet devices with Ethernet-specific details.
pub(crate) async fn list_wired_device_details(conn: &Connection) -> Result<Vec<WiredDevice>> {
    let proxy = NMProxy::new(conn).await?;
    let paths = proxy
        .get_devices()
        .await
        .map_err(|e| ConnectionError::DbusOperation {
            context: "failed to get device paths from NetworkManager".to_string(),
            source: e,
        })?;

    let mut devices = Vec::new();
    for p in paths {
        let d_proxy = NMDeviceProxy::builder(conn)
            .path(p.clone())?
            .build()
            .await?;

        if d_proxy.device_type().await? != device_type::ETHERNET {
            continue;
        }

        let interface = d_proxy
            .interface()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("failed to get interface name for device {}", p.as_str()),
                source: e,
            })?;
        // Some virtual or unusual devices omit HwAddress; keep the row usable.
        let hw_address = d_proxy
            .hw_address()
            .await
            .unwrap_or_else(|_| String::from("00:00:00:00:00:00"));
        let permanent_hw_address = d_proxy
            .perm_hw_address()
            .await
            .ok()
            .filter(|addr| !addr.is_empty());
        let state = d_proxy.state().await?.into();

        let speed_mbps = async {
            let wired = NMWiredProxy::builder(conn).path(p.clone())?.build().await?;
            wired.speed().await
        }
        .await
        .ok();

        let active_conn_path = d_proxy.active_connection().await.ok();
        let active_connection_id = match active_conn_path.as_ref() {
            Some(path) if path.as_str() != "/" => {
                async {
                    let active = NMActiveConnectionProxy::builder(conn)
                        .path(path.clone())
                        .ok()?
                        .build()
                        .await
                        .ok()?;
                    active.id().await.ok()
                }
                .await
            }
            _ => None,
        };

        let (ip4_address, ip6_address) = match active_conn_path.as_ref() {
            Some(path) if path.as_str() != "/" => {
                get_ip_addresses_from_active_connection(conn, path).await
            }
            _ => (None, None),
        };

        devices.push(WiredDevice {
            path: p.to_string(),
            interface,
            hw_address,
            permanent_hw_address,
            speed_mbps,
            active_connection_id,
            state,
            ip4_address,
            ip6_address,
        });
    }

    Ok(devices)
}

/// Returns `true` if any network device is in a transitional state
/// (preparing, configuring, authenticating, obtaining IP, etc.).
///
/// Useful for guarding against concurrent connection attempts.
pub(crate) async fn is_connecting(conn: &Connection) -> Result<bool> {
    let nm = NMProxy::new(conn).await?;
    let devices = nm.get_devices().await?;

    for dp in devices {
        let dev = NMDeviceProxy::builder(conn)
            .path(dp.clone())?
            .build()
            .await?;

        let raw_state = dev
            .state()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("failed to get state for device {}", dp.as_str()),
                source: e,
            })?;

        let state: DeviceState = raw_state.into();
        if state.is_transitional() {
            return Ok(true);
        }
    }

    Ok(false)
}

/// Returns `true` if the device with the given interface name is in a
/// transitional state.
///
/// Returns `false` if no device matches the interface name.
pub(crate) async fn is_connecting_on_interface(conn: &Connection, interface: &str) -> Result<bool> {
    let path = match get_device_by_interface(conn, interface).await {
        Ok(p) => p,
        Err(ConnectionError::NotFound) => return Ok(false),
        Err(e) => return Err(e),
    };

    let dev = NMDeviceProxy::builder(conn)
        .path(path.clone())?
        .build()
        .await?;

    let raw_state = dev
        .state()
        .await
        .map_err(|e| ConnectionError::DbusOperation {
            context: format!("failed to get state for device {}", path.as_str()),
            source: e,
        })?;

    Ok(DeviceState::from(raw_state).is_transitional())
}

pub(crate) async fn list_bluetooth_devices(conn: &Connection) -> Result<Vec<BluetoothDevice>> {
    let proxy = NMProxy::new(conn).await?;
    let paths = proxy.get_devices().await?;

    let mut devices = Vec::new();
    for p in paths {
        // So we can get the device type and state
        let d_proxy = NMDeviceProxy::builder(conn)
            .path(p.clone())?
            .build()
            .await?;

        // Only process Bluetooth devices
        let dev_type = d_proxy
            .device_type()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!(
                    "failed to get device type for {} during Bluetooth scan",
                    p.as_str()
                ),
                source: e,
            })?;

        if dev_type != device_type::BLUETOOTH {
            continue;
        }

        // Bluetooth-specific proxy
        // to get BD_ADDR and capabilities
        let bd_proxy = NMBluetoothProxy::builder(conn)
            .path(p.clone())?
            .build()
            .await?;

        let bdaddr = bd_proxy
            .hw_address()
            .await
            .unwrap_or_else(|_| String::from("00:00:00:00:00:00"));
        let bt_caps = bd_proxy.bt_capabilities().await?;
        let raw_state = d_proxy.state().await?;
        let state = raw_state.into();

        let bluez_info = populate_bluez_info(conn, &bdaddr, None).await?;

        devices.push(BluetoothDevice::new(
            bdaddr,
            bluez_info.0,
            bluez_info.1,
            bt_caps,
            state,
        ));
    }
    Ok(devices)
}

/// Waits for a Wi-Fi device to become ready for operations.
///
/// Uses D-Bus signals to efficiently wait until a Wi-Fi device reaches
/// either Disconnected or Activated state, indicating it's ready for
/// scanning or connection operations. This is useful after enabling Wi-Fi,
/// as the device may take time to initialize.
///
/// Returns `WifiNotReady` if no Wi-Fi device becomes ready within the timeout.
pub(crate) async fn wait_for_wifi_ready(conn: &Connection) -> Result<()> {
    let nm = NMProxy::new(conn).await?;
    let devices = nm.get_devices().await?;

    // Find the Wi-Fi device
    for dev_path in devices {
        let dev = NMDeviceProxy::builder(conn)
            .path(dev_path.clone())?
            .build()
            .await?;

        if dev.device_type().await? != device_type::WIFI {
            continue;
        }

        debug!("Found Wi-Fi device, waiting for it to become ready");

        // Check current state first
        let current_state = dev.state().await?;
        let state = DeviceState::from(current_state);

        if state == DeviceState::Disconnected || state == DeviceState::Activated {
            debug!("Wi-Fi device already ready");
            return Ok(());
        }

        // Wait for device to become ready using signal-based monitoring
        return wait_for_wifi_device_ready(&dev).await;
    }

    Err(ConnectionError::NoWifiDevice)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::BluetoothNetworkRole;

    #[test]
    fn test_default_bluetooth_address() {
        // Test that the default address used for devices without hardware address is valid
        let default_addr = "00:00:00:00:00:00";
        assert_eq!(default_addr.len(), 17);
        assert_eq!(default_addr.matches(':').count(), 5);
    }

    #[test]
    fn test_bluetooth_device_construction() {
        let panu = BluetoothNetworkRole::PanU as u32;
        let device = BluetoothDevice::new(
            "00:1A:7D:DA:71:13".into(),
            Some("TestDevice".into()),
            Some("Test".into()),
            panu,
            DeviceState::Activated,
        );

        assert_eq!(device.bdaddr, "00:1A:7D:DA:71:13");
        assert_eq!(device.name, Some("TestDevice".into()));
        assert_eq!(device.alias, Some("Test".into()));
        assert!(matches!(device.bt_caps, _panu));
        assert_eq!(device.state, DeviceState::Activated);
    }

    // Note: Most device listing functions require a real D-Bus connection
    // and NetworkManager running, so they are better suited for integration tests.
}