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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
mod controls;
mod monitoring;
mod types;
/// WiFi device functionality and management.
pub mod wifi;
/// Wired (ethernet) device functionality and management.
pub mod wired;
use std::{collections::HashMap, sync::Arc};
use controls::DeviceControls;
use derive_more::Debug;
use futures::{Stream, StreamExt};
use tokio_util::sync::CancellationToken;
pub use types::DeviceStateChangedEvent;
use types::{AppliedConnection, DeviceProperties};
pub(crate) use types::{DeviceParams, LiveDeviceParams};
use wayle_core::{Property, unwrap_dbus, unwrap_dbus_or};
use wayle_traits::{ModelMonitoring, Reactive};
use zbus::{
Connection,
zvariant::{OwnedObjectPath, OwnedValue},
};
use crate::{
error::Error,
proxy::devices::DeviceProxy,
types::{
connectivity::{NMConnectivityState, NMMetered},
device::{LldpNeighbor, NMDeviceManaged, NMDeviceManagedFlags, NMDeviceType},
flags::{NMDeviceCapabilities, NMDeviceInterfaceFlags},
states::{NMDeviceState, NMDeviceStateReason},
},
};
/// Network device managed by NetworkManager.
///
/// Common functionality for all network interfaces (WiFi, ethernet, etc).
/// Contains hardware information, state, configuration, and statistics.
#[derive(Debug, Clone)]
pub struct Device {
#[debug(skip)]
pub(crate) connection: Connection,
#[debug(skip)]
pub(crate) cancellation_token: Option<CancellationToken>,
/// D-Bus object path for this device.
pub object_path: OwnedObjectPath,
/// Operating-system specific transient device hardware identifier. Opaque
/// string representing the underlying hardware for the device, and shouldn't be used to
/// keep track of individual devices. For some device types (Bluetooth, Modems) it is an
/// identifier used by the hardware service (eg bluez or ModemManager) to refer to that
/// device, and client programs use it get additional information from those services
/// which NM does not provide. The Udi is not guaranteed to be consistent across reboots
/// or hotplugs of the hardware.
pub udi: Property<String>,
/// The path of the device as exposed by the udev property ID_PATH.
pub udev_path: Property<String>,
/// The name of the device's control (and often data) interface. Note that non UTF-8
/// characters are backslash escaped, so the resulting name may be longer then 15
/// characters. Use g_strcompress() to revert the escaping.
pub interface: Property<String>,
/// The name of the device's data interface when available. May not refer
/// to the actual data interface until the device has successfully established a data
/// connection, indicated by the device's State becoming ACTIVATED. Note that non UTF-8
/// characters are backslash escaped, so the resulting name may be longer then 15
/// characters. Use g_strcompress() to revert the escaping.
pub ip_interface: Property<String>,
/// The driver handling the device. Non-UTF-8 sequences are backslash escaped.
pub driver: Property<String>,
/// The version of the driver handling the device. Non-UTF-8 sequences are backslash
/// escaped.
pub driver_version: Property<String>,
/// The firmware version for the device. Non-UTF-8 sequences are backslash escaped.
pub firmware_version: Property<String>,
/// Flags describing the capabilities of the device. See NMDeviceCapabilities.
pub capabilities: Property<NMDeviceCapabilities>,
/// The current state of the device.
pub state: Property<NMDeviceState>,
/// The current state and reason for that state.
pub state_reason: Property<(NMDeviceState, NMDeviceStateReason)>,
/// Object path of an ActiveConnection object that "owns" this device during activation.
/// The ActiveConnection object tracks the life-cycle of a connection to a specific
/// network and implements the org.freedesktop.NetworkManager.Connection.Active D-Bus
/// interface.
pub active_connection: Property<OwnedObjectPath>,
/// Object path of the Ip4Config object describing the configuration of the device. Only
/// valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
pub ip4_config: Property<OwnedObjectPath>,
/// Object path of the Dhcp4Config object describing the DHCP options returned by the
/// DHCP server. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
pub dhcp4_config: Property<OwnedObjectPath>,
/// Object path of the Ip6Config object describing the configuration of the device. Only
/// valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
pub ip6_config: Property<OwnedObjectPath>,
/// Object path of the Dhcp6Config object describing the DHCP options returned by the
/// DHCP server. Only valid when the device is in the NM_DEVICE_STATE_ACTIVATED state.
pub dhcp6_config: Property<OwnedObjectPath>,
/// Whether or not this device is managed by NetworkManager. Setting this property has a
/// similar effect to configuring the device as unmanaged via the
/// keyfile.unmanaged-devices setting in NetworkManager.conf.
pub managed: Property<bool>,
/// If TRUE, indicates the device is allowed to autoconnect. If FALSE, manual
/// intervention is required before the device will automatically connect to a known
/// network, such as activating a connection using the device, or setting this property
/// to TRUE.
pub autoconnect: Property<bool>,
/// If TRUE, indicates the device is likely missing firmware necessary for its
/// operation.
pub firmware_missing: Property<bool>,
/// If TRUE, indicates the NetworkManager plugin for the device is likely missing or
/// misconfigured.
pub nm_plugin_missing: Property<bool>,
/// The general type of the network device.
pub device_type: Property<NMDeviceType>,
/// An array of object paths of every configured connection that is currently 'available'
/// through this device.
pub available_connections: Property<Vec<OwnedObjectPath>>,
/// If non-empty, an (opaque) indicator of the physical network port associated with the
/// device. Can be used to recognize when two seemingly-separate hardware devices
/// are actually just different virtual interfaces to the same physical port.
pub physical_port_id: Property<String>,
/// The MTU of the device.
pub mtu: Property<u32>,
/// Whether the amount of traffic flowing through the device is subject to limitations,
/// for example set by service providers.
pub metered: Property<NMMetered>,
/// Array of LLDP neighbors; each element is a dictionary mapping LLDP TLV names to
/// variant boxed values.
pub lldp_neighbors: Property<Vec<LldpNeighbor>>,
/// True if the device exists, or False for placeholder devices that do not yet exist but
/// could be automatically created by NetworkManager if one of their
/// AvailableConnections was activated.
pub real: Property<bool>,
/// The result of the last IPv4 connectivity check.
pub ip4_connectivity: Property<NMConnectivityState>,
/// The result of the last IPv6 connectivity check.
pub ip6_connectivity: Property<NMConnectivityState>,
/// The flags of the network interface. See NMDeviceInterfaceFlags for the currently
/// defined flags.
pub interface_flags: Property<NMDeviceInterfaceFlags>,
/// The hardware address of the device.
pub hw_address: Property<String>,
/// The port devices of the controller device. Array of object paths of port devices for
/// controller devices. For devices that are not controllers this is an empty array.
pub ports: Property<Vec<OwnedObjectPath>>,
}
impl Reactive for Device {
type Context<'a> = DeviceParams<'a>;
type LiveContext<'a> = LiveDeviceParams<'a>;
type Error = Error;
async fn get(params: Self::Context<'_>) -> Result<Self, Self::Error> {
Self::from_path(params.connection, params.object_path, None).await
}
async fn get_live(params: Self::LiveContext<'_>) -> Result<Arc<Self>, Self::Error> {
let device = Self::from_path(
params.connection,
params.object_path.clone(),
Some(params.cancellation_token.child_token()),
)
.await
.map_err(|e| Error::ObjectCreationFailed {
object_type: String::from("Device"),
object_path: params.object_path.clone(),
source: e.into(),
})?;
let device = Arc::new(device);
device.clone().start_monitoring().await?;
Ok(device)
}
}
impl Device {
pub(crate) async fn from_path(
connection: &Connection,
object_path: OwnedObjectPath,
cancellation_token: Option<CancellationToken>,
) -> Result<Self, Error> {
let proxy = DeviceProxy::new(connection, &object_path).await?;
let props = Self::fetch_properties(&proxy).await?;
Ok(Self::from_properties(
props,
connection,
object_path,
cancellation_token,
))
}
#[allow(clippy::too_many_lines)]
async fn fetch_properties(proxy: &DeviceProxy<'_>) -> Result<DeviceProperties, Error> {
let (udi, path, interface, ip_interface, driver, driver_version, firmware_version) = tokio::join!(
proxy.udi(),
proxy.path(),
proxy.interface(),
proxy.ip_interface(),
proxy.driver(),
proxy.driver_version(),
proxy.firmware_version(),
);
let (
capabilities,
state,
state_reason,
active_connection,
ip4_config,
dhcp4_config,
ip6_config,
dhcp6_config,
) = tokio::join!(
proxy.capabilities(),
proxy.state(),
proxy.state_reason(),
proxy.active_connection(),
proxy.ip4_config(),
proxy.dhcp4_config(),
proxy.ip6_config(),
proxy.dhcp6_config(),
);
let (
managed,
autoconnect,
firmware_missing,
nm_plugin_missing,
device_type,
available_connections,
physical_port_id,
mtu,
) = tokio::join!(
proxy.managed(),
proxy.autoconnect(),
proxy.firmware_missing(),
proxy.nm_plugin_missing(),
proxy.device_type(),
proxy.available_connections(),
proxy.physical_port_id(),
proxy.mtu(),
);
let (
metered,
real,
ip4_connectivity,
ip6_connectivity,
interface_flags,
hw_address,
ports,
_lldp_neighbors,
) = tokio::join!(
proxy.metered(),
proxy.real(),
proxy.ip4_connectivity(),
proxy.ip6_connectivity(),
proxy.interface_flags(),
proxy.hw_address(),
proxy.ports(),
proxy.lldp_neighbors(),
);
let device_path = path.clone().unwrap_or_default();
let available_connections: Vec<OwnedObjectPath> =
unwrap_dbus!(available_connections, device_path)
.into_iter()
.map(|p| OwnedObjectPath::try_from(p.to_string()).unwrap_or_default())
.collect();
let ports: Vec<OwnedObjectPath> = unwrap_dbus!(ports, device_path)
.into_iter()
.map(|p| OwnedObjectPath::try_from(p.to_string()).unwrap_or_default())
.collect();
Ok(DeviceProperties {
udi: unwrap_dbus!(udi, device_path),
interface: unwrap_dbus!(interface, device_path),
ip_interface: unwrap_dbus!(ip_interface, device_path),
driver: unwrap_dbus!(driver, device_path),
driver_version: unwrap_dbus!(driver_version, device_path),
firmware_version: unwrap_dbus!(firmware_version, device_path),
capabilities: unwrap_dbus!(capabilities, device_path),
state: unwrap_dbus!(state, device_path),
state_reason: state_reason.unwrap_or((0, 0)),
active_connection: unwrap_dbus!(active_connection, device_path),
ip4_config: unwrap_dbus!(ip4_config, device_path),
dhcp4_config: unwrap_dbus!(dhcp4_config, device_path),
ip6_config: unwrap_dbus!(ip6_config, device_path),
dhcp6_config: unwrap_dbus!(dhcp6_config, device_path),
managed: unwrap_dbus_or!(managed, device_path, true),
autoconnect: unwrap_dbus!(autoconnect, device_path),
firmware_missing: unwrap_dbus!(firmware_missing, device_path),
nm_plugin_missing: unwrap_dbus!(nm_plugin_missing, device_path),
device_type: unwrap_dbus!(device_type, device_path),
available_connections,
physical_port_id: unwrap_dbus!(physical_port_id, device_path),
mtu: unwrap_dbus_or!(mtu, device_path, 1500),
metered: unwrap_dbus!(metered, device_path),
real: unwrap_dbus_or!(real, device_path, true),
ip4_connectivity: unwrap_dbus!(ip4_connectivity, device_path),
ip6_connectivity: unwrap_dbus!(ip6_connectivity, device_path),
interface_flags: unwrap_dbus!(interface_flags, device_path),
hw_address: unwrap_dbus!(hw_address, device_path),
ports,
udev_path: device_path,
})
}
fn from_properties(
props: DeviceProperties,
connection: &Connection,
object_path: OwnedObjectPath,
cancellation_token: Option<CancellationToken>,
) -> Self {
Self {
cancellation_token,
connection: connection.clone(),
object_path,
udi: Property::new(props.udi),
udev_path: Property::new(props.udev_path),
interface: Property::new(props.interface),
ip_interface: Property::new(props.ip_interface),
driver: Property::new(props.driver),
driver_version: Property::new(props.driver_version),
firmware_version: Property::new(props.firmware_version),
capabilities: Property::new(NMDeviceCapabilities::from_bits_truncate(
props.capabilities,
)),
state: Property::new(NMDeviceState::from_u32(props.state)),
state_reason: Property::new((
NMDeviceState::from_u32(props.state_reason.0),
NMDeviceStateReason::from_u32(props.state_reason.1),
)),
active_connection: Property::new(props.active_connection),
ip4_config: Property::new(props.ip4_config),
dhcp4_config: Property::new(props.dhcp4_config),
ip6_config: Property::new(props.ip6_config),
dhcp6_config: Property::new(props.dhcp6_config),
managed: Property::new(props.managed),
autoconnect: Property::new(props.autoconnect),
firmware_missing: Property::new(props.firmware_missing),
nm_plugin_missing: Property::new(props.nm_plugin_missing),
device_type: Property::new(NMDeviceType::from_u32(props.device_type)),
available_connections: Property::new(props.available_connections),
physical_port_id: Property::new(props.physical_port_id),
mtu: Property::new(props.mtu),
metered: Property::new(NMMetered::from_u32(props.metered)),
real: Property::new(props.real),
ip4_connectivity: Property::new(NMConnectivityState::from_u32(props.ip4_connectivity)),
ip6_connectivity: Property::new(NMConnectivityState::from_u32(props.ip6_connectivity)),
interface_flags: Property::new(NMDeviceInterfaceFlags::from_bits_truncate(
props.interface_flags,
)),
hw_address: Property::new(props.hw_address),
ports: Property::new(props.ports),
// No idea what the properties for LLDP are - feel free to open a PR if you need this
// In the meantime, lldp_neighbors will always return an empty vec
lldp_neighbors: Property::new(vec![]),
}
}
/// Whether or not this device is managed by NetworkManager.
///
/// # Errors
/// Returns error if the D-Bus operation fails.
pub async fn set_managed(&self, managed: bool) -> Result<(), Error> {
DeviceControls::set_managed(&self.connection, &self.object_path, managed).await
}
/// If TRUE, indicates the device is allowed to autoconnect.
///
/// # Errors
/// Returns error if the D-Bus operation fails.
pub async fn set_autoconnect(&self, autoconnect: bool) -> Result<(), Error> {
DeviceControls::set_autoconnect(&self.connection, &self.object_path, autoconnect).await
}
/// Attempts to update device with new connection settings and properties.
///
/// # Arguments
/// * `connection` - Optional connection settings
/// * `version_id` - Settings version id (0 for current)
/// * `flags` - Flags (none defined)
///
/// # Errors
/// Returns error if the reapply operation fails.
pub async fn reapply(
&self,
connection_settings: HashMap<String, HashMap<String, OwnedValue>>,
version_id: u64,
flags: u32,
) -> Result<(), Error> {
DeviceControls::reapply(
&self.connection,
&self.object_path,
connection_settings,
version_id,
flags,
)
.await
}
/// Get the currently applied connection on the device.
///
/// # Arguments
/// * `flags` - Flags (none defined)
///
/// # Returns
/// * Connection settings
/// * Version id
///
/// # Errors
/// Returns error if getting the applied connection fails.
pub async fn get_applied_connection(&self, flags: u32) -> Result<AppliedConnection, Error> {
DeviceControls::get_applied_connection(&self.connection, &self.object_path, flags).await
}
/// Disconnects a device and prevents the device from automatically activating further connections without user intervention.
///
/// # Errors
/// Returns error if the disconnect operation fails.
pub async fn disconnect(&self) -> Result<(), Error> {
DeviceControls::disconnect(&self.connection, &self.object_path).await
}
/// Deletes a software device from NetworkManager and removes the interface from the system.
///
/// # Errors
/// Returns error if the delete operation fails.
pub async fn delete(&self) -> Result<(), Error> {
DeviceControls::delete(&self.connection, &self.object_path).await
}
/// Sets the managed state with optional persistence. Since: NM 1.58.
///
/// # Errors
/// Returns error if the operation fails.
pub async fn set_managed_ext(
&self,
managed: NMDeviceManaged,
flags: NMDeviceManagedFlags,
) -> Result<(), Error> {
DeviceControls::set_managed_ext(&self.connection, &self.object_path, managed, flags).await
}
/// Emitted when the device's state changes.
///
/// # Errors
/// Returns error if D-Bus proxy creation fails.
pub async fn device_state_changed_signal(
&self,
) -> Result<impl Stream<Item = DeviceStateChangedEvent>, Error> {
let proxy = DeviceProxy::new(&self.connection, &self.object_path).await?;
let stream = proxy.receive_device_state_changed().await?;
Ok(stream.filter_map(|signal| async move {
signal.args().ok().map(|args| DeviceStateChangedEvent {
new_state: NMDeviceState::from_u32(args.new_state),
old_state: NMDeviceState::from_u32(args.old_state),
reason: NMDeviceStateReason::from_u32(args.reason),
})
}))
}
}