nmstate 2.2.60

Library for networking management in a declarative manner
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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashMap, rc::Rc, str::FromStr};

use super::nm_dbus::{NmActiveConnection, NmConnection, NmIfaceType};
use crate::{
    BaseInterface, InterfaceIdentifier, InterfaceType, MergedInterfaces,
    PciAddress,
};

#[derive(Debug, Default)]
pub(crate) struct NmConnectionMatcher {
    saved_by_uuid: HashMap<String, Rc<NmConnection>>,
    applied_by_uuid: HashMap<String, Rc<NmConnection>>,
    acs_by_uuid: HashMap<String, Rc<NmActiveConnection>>,
    // Veth will also stored into `NmIfaceType::Ethernet`
    acs_by_name_and_type:
        HashMap<(String, NmIfaceType), Rc<NmActiveConnection>>,

    // Veth will also stored into `NmIfaceType::Ethernet`
    applied_by_name_and_type: HashMap<(String, NmIfaceType), Rc<NmConnection>>,

    saved_by_name: HashMap<String, Vec<Rc<NmConnection>>>,

    // Veth will also stored into `NmIfaceType::Ethernet`
    saved_by_name_and_type:
        HashMap<(String, NmIfaceType), Vec<Rc<NmConnection>>>,

    // (mac_upper_case, nm_iface_type) to Vec<Rc<NmConnection>> for mac
    // identifier connection.
    // Veth will also stored into `NmIfaceType::Ethernet`
    saved_by_mac: HashMap<(String, NmIfaceType), Vec<Rc<NmConnection>>>,

    // Veth will also stored into `NmIfaceType::Ethernet`
    saved_by_pci: HashMap<(PciAddress, NmIfaceType), Vec<Rc<NmConnection>>>,
}

#[cfg_attr(not(feature = "query_apply"), allow(dead_code))]
impl NmConnectionMatcher {
    pub(crate) fn new(
        nm_saved_cons: Vec<NmConnection>,
        nm_applied_cons: Vec<NmConnection>,
        nm_acs: Vec<NmActiveConnection>,
        merged_ifaces: &MergedInterfaces,
    ) -> Self {
        let mut ret = Self::default();
        for nm_ac in nm_acs {
            ret.add_nm_ac(nm_ac);
        }

        for nm_conn in nm_applied_cons {
            ret.add_nm_applied_conn(nm_conn, merged_ifaces);
        }

        for nm_conn in nm_saved_cons {
            ret.add_nm_saved_conn(nm_conn, merged_ifaces);
        }

        ret
    }

    fn add_nm_ac(&mut self, nm_ac: NmActiveConnection) {
        let uuid = nm_ac.uuid.clone();
        let nm_ac = Rc::new(nm_ac);
        self.acs_by_uuid.insert(uuid, nm_ac.clone());
        if nm_ac.iface_type == NmIfaceType::Veth {
            self.acs_by_name_and_type.insert(
                (nm_ac.iface_name.clone(), NmIfaceType::Ethernet),
                nm_ac.clone(),
            );
        }
        self.acs_by_name_and_type
            .insert((nm_ac.iface_name.clone(), nm_ac.iface_type), nm_ac);
    }

    fn add_nm_applied_conn(
        &mut self,
        nm_conn: NmConnection,
        merged_ifaces: &MergedInterfaces,
    ) {
        let nm_conn = Rc::new(nm_conn);
        let uuid = match nm_conn.uuid().as_ref() {
            Some(u) => u.to_string(),
            None => return,
        };
        self.applied_by_uuid.insert(uuid, nm_conn.clone());

        if let (Some(name), Some(nm_iface_type)) = (
            get_nm_connection_iface_name(nm_conn.as_ref(), merged_ifaces),
            nm_conn.iface_type(),
        ) {
            if nm_iface_type == &NmIfaceType::Veth {
                self.applied_by_name_and_type.insert(
                    (name.to_string(), NmIfaceType::Ethernet),
                    nm_conn.clone(),
                );
            }
            self.applied_by_name_and_type
                .insert((name.to_string(), *nm_iface_type), nm_conn.clone());
        } else {
            // For all applied NmConnection, it should have existing
            // network interface defined, hence we ignore unexpected
            // NmConnection
            log::error!(
                "BUG: Ignoring the applied NmConnection due to unable to \
                 resolve network interface name: {nm_conn:?}"
            );
        }
    }

    fn add_nm_saved_conn(
        &mut self,
        nm_conn: NmConnection,
        merged_ifaces: &MergedInterfaces,
    ) {
        let nm_conn = Rc::new(nm_conn);
        let uuid = match nm_conn.uuid().as_ref() {
            Some(u) => u.to_string(),
            None => return,
        };
        self.saved_by_uuid.insert(uuid, nm_conn.clone());

        if let Some(name) =
            get_nm_connection_iface_name(nm_conn.as_ref(), merged_ifaces)
        {
            self.saved_by_name
                .entry(name.clone())
                .or_default()
                .push(nm_conn.clone());

            if let Some(nm_iface_type) = nm_conn.iface_type() {
                if nm_iface_type == &NmIfaceType::Veth {
                    self.saved_by_name_and_type
                        .entry((name.to_string(), NmIfaceType::Ethernet))
                        .or_default()
                        .push(nm_conn.clone())
                }
                self.saved_by_name_and_type
                    .entry((name, *nm_iface_type))
                    .or_default()
                    .push(nm_conn.clone())
            }
        }

        if let (Some(mac), Some(nm_iface_type)) = (
            nm_conn
                .wired
                .as_ref()
                .and_then(|w| w.mac_address.as_deref()),
            nm_conn.iface_type(),
        ) {
            // For VLAN, MACVLAN and MACSEC, 802-3-ethernet.mac-address is
            // the MAC of the parent, not of the interface itself.
            if !mac.is_empty()
                && nm_conn.iface_type().map(|nm_iface_type| {
                    NM_IFACE_TYPES_USE_PARENT_MAC.contains(nm_iface_type)
                }) == Some(false)
            {
                if nm_iface_type == &NmIfaceType::Veth {
                    self.saved_by_mac
                        .entry((mac.to_uppercase(), NmIfaceType::Ethernet))
                        .or_default()
                        .push(nm_conn.clone())
                }
                self.saved_by_mac
                    .entry((mac.to_uppercase(), *nm_iface_type))
                    .or_default()
                    .push(nm_conn.clone())
            }
        }

        if let (Some(nm_pci_addr), Some(nm_iface_type)) = (
            nm_conn
                .iface_match
                .as_ref()
                .and_then(|m| m.path.as_deref())
                .and_then(|s| s.first()),
            nm_conn.iface_type(),
        ) && let Some(pci) = nm_pci_addr
            .strip_prefix("pci-")
            .and_then(|s| PciAddress::from_str(s).ok())
        {
            if nm_iface_type == &NmIfaceType::Veth {
                self.saved_by_pci
                    .entry((pci, NmIfaceType::Ethernet))
                    .or_default()
                    .push(nm_conn.clone())
            }
            self.saved_by_pci
                .entry((pci, *nm_iface_type))
                .or_default()
                .push(nm_conn.clone())
        }
    }

    /// Activated NmConnection (including in-memory)
    pub(crate) fn get_applied(
        &self,
        base_iface: &BaseInterface,
    ) -> Option<&NmConnection> {
        self.applied_by_name_and_type
            .get(&(
                base_iface.name.to_string(),
                NmIfaceType::from(&base_iface.iface_type),
            ))
            .map(Rc::as_ref)
    }

    /// Find the best saved NmConnection in the order of:
    /// * Currently activated
    /// * Biggest `connection.autoconnect-priority`
    /// * Biggest `connection.timestamp`
    /// * Biggest `connection.uuid`
    pub(crate) fn get_prefered_saved_by_name_type<'s>(
        &'s self,
        name: &str,
        nm_iface_type: &NmIfaceType,
    ) -> Option<&'s NmConnection> {
        // Prefer the current activated NmConnection by searching
        // NmActiveConnection for specified interface, then use the UUID of
        // NmActiveConnection to search out the NmConnection.
        if let Some(nm_conn) = self
            .acs_by_name_and_type
            .get(&(name.to_string(), *nm_iface_type))
            .and_then(|nm_ac| self.saved_by_uuid.get(nm_ac.uuid.as_str()))
            .map(Rc::as_ref)
        {
            return Some(nm_conn);
        }

        let nm_conns = self
            .saved_by_name_and_type
            .get(&(name.to_string(), *nm_iface_type))?;

        for nm_conn in nm_conns {
            if let Some(uuid) = nm_conn.uuid()
                && self.acs_by_uuid.contains_key(uuid)
            {
                return Some(Rc::as_ref(nm_conn));
            }
        }

        let mut nm_conns: Vec<&NmConnection> =
            nm_conns.iter().map(|n| n.as_ref()).collect();
        nm_conns.sort_unstable_by_key(|c| nm_conn_activation_sort_keys(c));

        nm_conns.pop()
    }

    /// Find the best saved NmConnection in the order of:
    /// * Currently activated
    /// * Biggest `connection.autoconnect-priority`
    /// * Biggest `connection.timestamp`
    /// * Biggest `connection.uuid`
    pub(crate) fn get_prefered_saved<'s>(
        &'s self,
        base_iface: &BaseInterface,
    ) -> Option<&'s NmConnection> {
        let nm_iface_type = NmIfaceType::from(&base_iface.iface_type);

        // Prefer the current activated NmConnection by searching
        // NmActiveConnection for specified interface, then use the UUID of
        // NmActiveConnection to search out the NmConnection.
        if let Some(nm_conn) = self
            .acs_by_name_and_type
            .get(&(base_iface.name.to_string(), nm_iface_type))
            .and_then(|nm_ac| self.saved_by_uuid.get(nm_ac.uuid.as_str()))
            .map(Rc::as_ref)
        {
            return Some(nm_conn);
        }

        match base_iface.identifier {
            None | Some(InterfaceIdentifier::Name) => self
                .get_prefered_saved_by_name_type(
                    base_iface.name.as_str(),
                    &nm_iface_type,
                ),
            Some(InterfaceIdentifier::MacAddress) => {
                if let Some(mac) = base_iface.mac_address.as_deref() {
                    let mut nm_conns: Vec<&NmConnection> = self
                        .saved_by_mac
                        .get(&(mac.to_string(), nm_iface_type))
                        .map(|nm_conns| {
                            nm_conns.iter().map(Rc::as_ref).collect()
                        })
                        .unwrap_or_default();
                    nm_conns.sort_unstable_by(|a, b| {
                        nm_conn_activation_sort_keys(a)
                            .cmp(&nm_conn_activation_sort_keys(b))
                    });
                    nm_conns.pop()
                } else {
                    None
                }
            }
            Some(InterfaceIdentifier::PciAddress) => {
                if let Some(pci) = base_iface.pci_address {
                    let mut nm_conns: Vec<&NmConnection> = self
                        .saved_by_pci
                        .get(&(pci, nm_iface_type))
                        .map(|nm_conns| {
                            nm_conns.iter().map(Rc::as_ref).collect()
                        })
                        .unwrap_or_default();
                    nm_conns.sort_unstable_by(|a, b| {
                        nm_conn_activation_sort_keys(a)
                            .cmp(&nm_conn_activation_sort_keys(b))
                    });
                    nm_conns.pop()
                } else {
                    None
                }
            }
        }
    }

    /// Get all connections can be used to activate specified interface.
    /// If interface type is unknown, all profiles with desired interface
    /// name will be included.
    pub(crate) fn get_saved(
        &self,
        base_iface: &BaseInterface,
    ) -> Vec<&NmConnection> {
        let mut ret: Vec<&NmConnection> = Vec::new();
        if base_iface.iface_type == InterfaceType::Unknown {
            if let Some(nm_conns) = self.saved_by_name.get(&base_iface.name) {
                ret.extend(nm_conns.iter().map(Rc::as_ref));
            }
            // also check `connection.id`
            ret.extend(
                self.saved_by_uuid
                    .values()
                    .filter(|nm_conn| {
                        nm_conn
                            .connection
                            .as_ref()
                            .and_then(|c| c.id.as_deref())
                            == Some(base_iface.name.as_str())
                    })
                    .map(Rc::as_ref),
            );
        } else if let Some(nm_conns) = self.saved_by_name_and_type.get(&(
            base_iface.name.to_string(),
            NmIfaceType::from(&base_iface.iface_type),
        )) {
            ret.extend(nm_conns.iter().map(Rc::as_ref));
        }
        match base_iface.identifier {
            None | Some(InterfaceIdentifier::Name) => (),
            Some(InterfaceIdentifier::MacAddress) => {
                if let Some(mac) = base_iface.mac_address.as_deref()
                    && let Some(nm_conns) = self.saved_by_mac.get(&(
                        mac.to_uppercase(),
                        NmIfaceType::from(&base_iface.iface_type),
                    ))
                {
                    ret.extend(nm_conns.iter().map(Rc::as_ref));
                }
            }
            Some(InterfaceIdentifier::PciAddress) => {
                if let Some(pci) = base_iface.pci_address
                    && let Some(nm_conns) = self
                        .saved_by_pci
                        .get(&(pci, NmIfaceType::from(&base_iface.iface_type)))
                {
                    ret.extend(nm_conns.iter().map(Rc::as_ref));
                }
            }
        }

        ret.sort_unstable_by(|a, b| a.uuid().cmp(&b.uuid()));
        ret.dedup();
        ret
    }

    pub(crate) fn get_nm_ac(
        &self,
        iface: &BaseInterface,
    ) -> Option<&NmActiveConnection> {
        self.acs_by_name_and_type
            .get(&(
                iface.name.to_string(),
                NmIfaceType::from(&iface.iface_type),
            ))
            .map(Rc::as_ref)
    }

    pub(crate) fn saved_iter(&self) -> impl Iterator<Item = &NmConnection> {
        self.saved_by_uuid.values().map(Rc::as_ref)
    }

    pub(crate) fn is_uuid_activated(&self, uuid: &str) -> bool {
        self.acs_by_uuid.contains_key(uuid)
    }

    pub(crate) fn get_applied_by_name_type(
        &self,
        name: &str,
        iface_type: &NmIfaceType,
    ) -> Option<&NmConnection> {
        self.applied_by_name_and_type
            .get(&(name.to_string(), *iface_type))
            .map(Rc::as_ref)
    }

    pub(crate) fn get_saved_by_name_type<'a>(
        &'a self,
        name: &str,
        iface_type: &NmIfaceType,
    ) -> Box<dyn Iterator<Item = &'a NmConnection> + 'a> {
        if let Some(nm_conns) = self
            .saved_by_name_and_type
            .get(&(name.to_string(), *iface_type))
        {
            Box::new(nm_conns.iter().map(Rc::as_ref))
        } else {
            Box::new(std::iter::empty::<&NmConnection>())
        }
    }

    pub(crate) fn is_activated(&self, uuid: &str) -> bool {
        self.acs_by_uuid.contains_key(uuid)
    }

    pub(crate) fn get_applied_by_uuid(
        &self,
        uuid: &str,
    ) -> Option<&NmConnection> {
        self.applied_by_uuid.get(uuid).map(Rc::as_ref)
    }

    pub(crate) fn get_nm_ac_by_uuid(
        &self,
        uuid: &str,
    ) -> Option<&NmActiveConnection> {
        self.acs_by_uuid.get(uuid).map(Rc::as_ref)
    }
}

const NM_IFACE_TYPES_USE_PARENT_MAC: [NmIfaceType; 3] =
    [NmIfaceType::Vlan, NmIfaceType::Macvlan, NmIfaceType::Macsec];

/// Find interface name for NmConnection:
///  * `connection.interface-name`
///  * For VLAN, use `vlan.id` and `vlan.parent` if `connection.interface-name`
///    is empty
///  * Resolves `802-3-ethernet.mac-address` if defined
///  * Use `connection.id` for VPN connection
fn get_nm_connection_iface_name(
    nm_conn: &NmConnection,
    merged_ifaces: &MergedInterfaces,
) -> Option<String> {
    if let Some(iface_name) = nm_conn.iface_name()
        && !iface_name.is_empty()
    {
        return Some(iface_name.to_string());
    }

    if let (Some(vlan_parent), Some(vlan_id)) = (
        nm_conn.vlan.as_ref().and_then(|v| v.parent.as_deref()),
        nm_conn.vlan.as_ref().and_then(|v| v.id),
    ) {
        return Some(format!("{vlan_parent}.{vlan_id}"));
    }

    // Veth and ethernet will be unified to InterfaceType::Ethernet
    let iface_type = InterfaceType::from(nm_conn.iface_type()?);

    // For VLAN, MACVLAN and MACSEC, 802-3-ethernet.mac-address is the MAC of
    // the parent, not of the interface itself.
    if nm_conn.iface_type().map(|nm_iface_type| {
        NM_IFACE_TYPES_USE_PARENT_MAC.contains(nm_iface_type)
    }) == Some(false)
        && let Some(mac) = nm_conn
            .wired
            .as_ref()
            .and_then(|s| s.mac_address.as_deref())
        && let Some(name) = merged_ifaces
            .kernel_ifaces
            .values()
            .filter_map(|i| i.current.as_ref())
            .find_map(|iface| {
                let base_iface = iface.base_iface();
                if base_iface.mac_address.as_deref() == Some(mac)
                    && (base_iface.iface_type == iface_type
                        || ([InterfaceType::Veth, InterfaceType::Ethernet]
                            .contains(&base_iface.iface_type)
                            && iface_type == InterfaceType::Ethernet))
                {
                    Some(base_iface.name.to_string())
                } else {
                    None
                }
            })
    {
        return Some(name);
    }
    if nm_conn.vpn.is_some() {
        return nm_conn.id().map(|i| i.to_string());
    }
    None
}

const NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_DEFAULT: i32 = 0;
const NM_SETTING_CONNECTION_TIMESTAMP_DEFAULT: u64 = 0;
const NM_SETTING_CONNECTION_UUID_DEFAULT: u128 = 0;

// Sort key for choosing NmConnection for activation:
//  (connection.autoconnect-priority, connection.timestamp, connection.uuid)
fn nm_conn_activation_sort_keys(nm_conn: &NmConnection) -> (i32, u64, u128) {
    (
        nm_conn
            .connection
            .as_ref()
            .and_then(|c| c.autoconnect_priority)
            .unwrap_or(NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_DEFAULT),
        nm_conn
            .connection
            .as_ref()
            .and_then(|c| c.timestamp)
            .unwrap_or(NM_SETTING_CONNECTION_TIMESTAMP_DEFAULT),
        nm_conn
            .uuid()
            .and_then(|uuid_str| uuid::Uuid::parse_str(uuid_str).ok())
            .map(|u| u.as_u128())
            .unwrap_or(NM_SETTING_CONNECTION_UUID_DEFAULT),
    )
}