nmrs 2.3.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Core VPN connection management logic.
//!
//! This module contains internal implementation for managing VPN connections
//! through NetworkManager, including connecting, disconnecting, listing, and
//! deleting VPN profiles.
//!
//! Currently supports:
//! - WireGuard connections (NetworkManager connection.type == "wireguard")
//!
//! These functions are not part of the public API and should be accessed
//! through the [`NetworkManager`][crate::NetworkManager] interface.

use log::{debug, info, warn};
use std::collections::HashMap;
use zbus::Connection;
use zvariant::OwnedObjectPath;

use crate::Result;
use crate::api::models::{
    ConnectionError, ConnectionOptions, DeviceState, TimeoutConfig, VpnConnection,
    VpnConnectionInfo, VpnCredentials, VpnType,
};
use crate::builders::build_wireguard_connection;
use crate::core::state_wait::wait_for_connection_activation;
use crate::dbus::{NMActiveConnectionProxy, NMProxy};
use crate::util::utils::{extract_connection_state_reason, nm_proxy, settings_proxy};
use crate::util::validation::{validate_connection_name, validate_vpn_credentials};

/// Connects to a WireGuard connection.
///
/// This function checks for an existing saved connection by name.
/// If found, it activates the saved connection. If not found, it creates
/// a new WireGuard connection using the provided credentials.
/// The function waits for the connection to reach the activated state
/// before returning.
///
/// WireGuard activations do not require binding to an underlying device.
/// Use "/" so NetworkManager auto-selects.
pub(crate) async fn connect_vpn(
    conn: &Connection,
    creds: VpnCredentials,
    timeout_config: Option<TimeoutConfig>,
) -> Result<()> {
    // Validate VPN credentials before attempting connection
    validate_vpn_credentials(&creds)?;

    debug!("Connecting to VPN: {}", creds.name);

    let nm = NMProxy::new(conn).await?;

    // Check saved connections
    let saved =
        crate::core::connection_settings::get_saved_connection_path(conn, &creds.name).await?;

    // For WireGuard activation, always use "/" as device path - NetworkManager will auto-select
    let vpn_device_path = OwnedObjectPath::default();
    let specific_object = OwnedObjectPath::default();

    let active_conn = if let Some(saved_path) = saved {
        debug!("Activating existent VPN connection");
        nm.activate_connection(saved_path, vpn_device_path.clone(), specific_object.clone())
            .await?
    } else {
        debug!("Creating new VPN connection");
        let opts = ConnectionOptions {
            autoconnect: false,
            autoconnect_priority: None,
            autoconnect_retries: None,
        };

        let settings = build_wireguard_connection(&creds, &opts)?;

        let settings_api = settings_proxy(conn).await?;

        debug!("Adding connection via Settings API");
        let add_reply = settings_api
            .call_method("AddConnection", &(settings,))
            .await?;
        let conn_path: OwnedObjectPath = add_reply.body().deserialize()?;
        debug!("Connection added, activating VPN connection");

        nm.activate_connection(conn_path, vpn_device_path, specific_object)
            .await?
    };

    let timeout = timeout_config.map(|c| c.connection_timeout);
    wait_for_connection_activation(conn, &active_conn, timeout).await?;
    debug!("Connection reached Activated state, waiting briefly...");

    match NMActiveConnectionProxy::builder(conn).path(active_conn.clone()) {
        Ok(builder) => match builder.build().await {
            Ok(active_conn_check) => {
                let final_state = active_conn_check.state().await?;
                let state = crate::api::models::ActiveConnectionState::from(final_state);
                debug!("Connection state after delay: {:?}", state);

                match state {
                    crate::api::models::ActiveConnectionState::Activated => {
                        info!("Successfully connected to VPN: {}", creds.name);
                        Ok(())
                    }
                    crate::api::models::ActiveConnectionState::Deactivated => {
                        warn!("Connection deactivated immediately after activation");
                        let reason = extract_connection_state_reason(conn, &active_conn).await;
                        Err(crate::api::models::ConnectionError::ActivationFailed(
                            reason,
                        ))
                    }
                    _ => {
                        warn!("Connection in unexpected state: {:?}", state);
                        Err(crate::api::models::ConnectionError::Stuck(format!(
                            "connection in state {:?}",
                            state
                        )))
                    }
                }
            }
            Err(e) => {
                warn!("Failed to build active connection proxy after delay: {}", e);
                let reason = extract_connection_state_reason(conn, &active_conn).await;
                Err(crate::api::models::ConnectionError::ActivationFailed(
                    reason,
                ))
            }
        },
        Err(e) => {
            warn!(
                "Failed to create active connection proxy builder after delay: {}",
                e
            );
            let reason = extract_connection_state_reason(conn, &active_conn).await;
            Err(crate::api::models::ConnectionError::ActivationFailed(
                reason,
            ))
        }
    }
}

/// Disconnects from a connection by name.
///
/// Searches through active connections for a WireGuard connection matching the given name.
/// If found, deactivates the connection. If not found, assumes already
/// disconnected and returns success.
pub(crate) async fn disconnect_vpn(conn: &Connection, name: &str) -> Result<()> {
    // Validate connection name
    validate_connection_name(name)?;

    debug!("Disconnecting VPN: {name}");

    let nm = NMProxy::new(conn).await?;
    let active_conns = match nm.active_connections().await {
        Ok(conns) => conns,
        Err(e) => {
            debug!("Failed to get active connections: {}", e);
            info!("Disconnected VPN: {name} (could not verify active state)");
            return Ok(());
        }
    };

    for ac_path in active_conns {
        let ac_proxy = match nm_proxy(
            conn,
            ac_path.clone(),
            "org.freedesktop.NetworkManager.Connection.Active",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for active connection {}: {}",
                    ac_path, e
                );
                continue;
            }
        };

        let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await {
            Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() {
                Ok(path) => path,
                Err(e) => {
                    warn!(
                        "Failed to deserialize connection path for {}: {}",
                        ac_path, e
                    );
                    continue;
                }
            },
            Err(e) => {
                warn!("Failed to get Connection property from {}: {}", ac_path, e);
                continue;
            }
        };

        let cproxy = match nm_proxy(
            conn,
            conn_path.clone(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for connection settings {}: {}",
                    conn_path, e
                );
                continue;
            }
        };

        let msg = match cproxy.call_method("GetSettings", &()).await {
            Ok(msg) => msg,
            Err(e) => {
                warn!("Failed to get settings for connection {}: {}", conn_path, e);
                continue;
            }
        };

        let body = msg.body();
        let settings_map: HashMap<String, HashMap<String, zvariant::Value>> =
            match body.deserialize() {
                Ok(map) => map,
                Err(e) => {
                    warn!("Failed to deserialize settings for {}: {}", conn_path, e);
                    continue;
                }
            };

        if let Some(conn_sec) = settings_map.get("connection") {
            let id_match = conn_sec
                .get("id")
                .and_then(|v| match v {
                    zvariant::Value::Str(s) => Some(s.as_str() == name),
                    _ => None,
                })
                .unwrap_or(false);

            let is_wireguard = conn_sec
                .get("type")
                .and_then(|v| match v {
                    zvariant::Value::Str(s) => Some(s.as_str() == "wireguard"),
                    _ => None,
                })
                .unwrap_or(false);

            if id_match && is_wireguard {
                debug!("Found active WireGuard connection, deactivating: {name}");
                match nm.deactivate_connection(ac_path.clone()).await {
                    Ok(_) => info!("Successfully disconnected VPN: {name}"),
                    Err(e) => warn!("Failed to deactivate connection {}: {}", ac_path, e),
                }
                return Ok(());
            }
        }
    }

    info!("Disconnected VPN: {name} (not active)");
    Ok(())
}

/// Lists all saved WireGuard connections with their current state.
///
/// Returns connections where `connection.type == "wireguard"`.
/// For active connections, populates `state` and `interface` from the active connection.
pub(crate) async fn list_vpn_connections(conn: &Connection) -> Result<Vec<VpnConnection>> {
    let nm = NMProxy::new(conn).await?;

    let settings = nm_proxy(
        conn,
        "/org/freedesktop/NetworkManager/Settings",
        "org.freedesktop.NetworkManager.Settings",
    )
    .await?;

    let list_reply = settings
        .call_method("ListConnections", &())
        .await
        .map_err(|e| ConnectionError::DbusOperation {
            context: "failed to list saved connections".to_string(),
            source: e,
        })?;

    let saved_conns: Vec<OwnedObjectPath> = list_reply.body().deserialize()?;

    // Map active WireGuard connection id -> (state, interface)
    let active_conns = nm.active_connections().await?;
    let mut active_wg_map: HashMap<String, (DeviceState, Option<String>)> = HashMap::new();

    for ac_path in active_conns {
        let ac_proxy = match nm_proxy(
            conn,
            ac_path.clone(),
            "org.freedesktop.NetworkManager.Connection.Active",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for active connection {}: {}",
                    ac_path, e
                );
                continue;
            }
        };

        let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await {
            Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() {
                Ok(p) => p,
                Err(e) => {
                    warn!(
                        "Failed to deserialize connection path for {}: {}",
                        ac_path, e
                    );
                    continue;
                }
            },
            Err(e) => {
                warn!("Failed to get Connection property from {}: {}", ac_path, e);
                continue;
            }
        };

        let cproxy = match nm_proxy(
            conn,
            conn_path.clone(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for connection settings {}: {}",
                    conn_path, e
                );
                continue;
            }
        };

        let msg = match cproxy.call_method("GetSettings", &()).await {
            Ok(m) => m,
            Err(e) => {
                warn!("Failed to get settings for connection {}: {}", conn_path, e);
                continue;
            }
        };

        let body = msg.body();
        let settings_map: HashMap<String, HashMap<String, zvariant::Value>> =
            match body.deserialize() {
                Ok(m) => m,
                Err(e) => {
                    warn!("Failed to deserialize settings for {}: {}", conn_path, e);
                    continue;
                }
            };

        let conn_sec = match settings_map.get("connection") {
            Some(s) => s,
            None => continue,
        };

        let id = match conn_sec.get("id") {
            Some(zvariant::Value::Str(s)) => s.as_str().to_string(),
            _ => continue,
        };

        let conn_type = match conn_sec.get("type") {
            Some(zvariant::Value::Str(s)) => s.as_str(),
            _ => continue,
        };

        if conn_type != "wireguard" {
            continue;
        }

        let state = if let Ok(state_val) = ac_proxy.get_property::<u32>("State").await {
            DeviceState::from(state_val)
        } else {
            DeviceState::Other(0)
        };

        let interface = if let Ok(dev_paths) = ac_proxy
            .get_property::<Vec<OwnedObjectPath>>("Devices")
            .await
        {
            if let Some(dev_path) = dev_paths.first() {
                match nm_proxy(
                    conn,
                    dev_path.clone(),
                    "org.freedesktop.NetworkManager.Device",
                )
                .await
                {
                    Ok(dev_proxy) => match dev_proxy.get_property::<String>("Interface").await {
                        Ok(iface) => Some(iface),
                        Err(e) => {
                            debug!(
                                "Failed to get interface name for VPN device {}: {}",
                                dev_path, e
                            );
                            None
                        }
                    },
                    Err(e) => {
                        debug!("Failed to create device proxy for {}: {}", dev_path, e);
                        None
                    }
                }
            } else {
                None
            }
        } else {
            None
        };

        active_wg_map.insert(id, (state, interface));
    }

    let mut wg_conns = Vec::new();

    for cpath in saved_conns {
        let cproxy = match nm_proxy(
            conn,
            cpath.clone(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for saved connection {}: {}",
                    cpath, e
                );
                continue;
            }
        };

        let msg = match cproxy.call_method("GetSettings", &()).await {
            Ok(m) => m,
            Err(e) => {
                warn!(
                    "Failed to get settings for saved connection {}: {}",
                    cpath, e
                );
                continue;
            }
        };

        let body = msg.body();
        let settings_map: HashMap<String, HashMap<String, zvariant::Value>> =
            match body.deserialize() {
                Ok(m) => m,
                Err(e) => {
                    warn!(
                        "Failed to deserialize settings for saved connection {}: {}",
                        cpath, e
                    );
                    continue;
                }
            };

        let conn_sec = match settings_map.get("connection") {
            Some(s) => s,
            None => continue,
        };

        let id = match conn_sec.get("id") {
            Some(zvariant::Value::Str(s)) => s.as_str().to_string(),
            _ => continue,
        };

        let conn_type = match conn_sec.get("type") {
            Some(zvariant::Value::Str(s)) => s.as_str(),
            _ => continue,
        };

        if conn_type != "wireguard" {
            continue;
        }

        let (state, interface) = active_wg_map
            .get(&id)
            .cloned()
            .unwrap_or((DeviceState::Other(0), None));

        wg_conns.push(VpnConnection {
            name: id,
            vpn_type: VpnType::WireGuard,
            interface,
            state,
        });
    }

    Ok(wg_conns)
}

/// Forgets (deletes) a saved WireGuard connection by name.
///
/// If currently connected, the connection will be disconnected first before deletion.
pub(crate) async fn forget_vpn(conn: &Connection, name: &str) -> Result<()> {
    // Validate connection name
    validate_connection_name(name)?;

    debug!("Starting forget operation for VPN: {name}");

    match disconnect_vpn(conn, name).await {
        Ok(_) => debug!("VPN disconnected before deletion"),
        Err(e) => warn!(
            "Failed to disconnect VPN before deletion (may already be disconnected): {}",
            e
        ),
    }

    let settings = nm_proxy(
        conn,
        "/org/freedesktop/NetworkManager/Settings",
        "org.freedesktop.NetworkManager.Settings",
    )
    .await?;

    let list_reply = settings.call_method("ListConnections", &()).await?;
    let conns: Vec<OwnedObjectPath> = list_reply.body().deserialize()?;

    for cpath in conns {
        let cproxy = match nm_proxy(
            conn,
            cpath.clone(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!("Failed to create proxy for connection {}: {}", cpath, e);
                continue;
            }
        };

        let msg = match cproxy.call_method("GetSettings", &()).await {
            Ok(msg) => msg,
            Err(e) => {
                warn!("Failed to get settings for connection {}: {}", cpath, e);
                continue;
            }
        };

        let body = msg.body();
        let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = body.deserialize()?;

        if let Some(conn_sec) = settings_map.get("connection") {
            let id_ok = conn_sec
                .get("id")
                .and_then(|v| match v {
                    zvariant::Value::Str(s) => Some(s.as_str() == name),
                    _ => None,
                })
                .unwrap_or(false);

            let type_ok = conn_sec
                .get("type")
                .and_then(|v| match v {
                    zvariant::Value::Str(s) => Some(s.as_str() == "wireguard"),
                    _ => None,
                })
                .unwrap_or(false);

            if id_ok && type_ok {
                debug!("Found WireGuard connection, deleting: {name}");
                cproxy.call_method("Delete", &()).await.map_err(|e| {
                    ConnectionError::DbusOperation {
                        context: format!("failed to delete VPN connection '{}'", name),
                        source: e,
                    }
                })?;
                info!("Successfully deleted VPN connection: {name}");
                return Ok(());
            }
        }
    }

    debug!("No saved VPN connection found for '{name}'");
    Ok(())
}

/// Gets detailed information about a WireGuard connection.
///
/// The connection must be in the active connections list to retrieve full details.
pub(crate) async fn get_vpn_info(conn: &Connection, name: &str) -> Result<VpnConnectionInfo> {
    // Validate connection name
    validate_connection_name(name)?;

    let nm = NMProxy::new(conn).await?;
    let active_conns = nm.active_connections().await?;

    for ac_path in active_conns {
        let ac_proxy = match nm_proxy(
            conn,
            ac_path.clone(),
            "org.freedesktop.NetworkManager.Connection.Active",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for active connection {}: {}",
                    ac_path, e
                );
                continue;
            }
        };

        let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await {
            Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() {
                Ok(p) => p,
                Err(e) => {
                    warn!(
                        "Failed to deserialize connection path for {}: {}",
                        ac_path, e
                    );
                    continue;
                }
            },
            Err(e) => {
                warn!("Failed to get Connection property from {}: {}", ac_path, e);
                continue;
            }
        };

        let cproxy = match nm_proxy(
            conn,
            conn_path.clone(),
            "org.freedesktop.NetworkManager.Settings.Connection",
        )
        .await
        {
            Ok(p) => p,
            Err(e) => {
                warn!(
                    "Failed to create proxy for connection settings {}: {}",
                    conn_path, e
                );
                continue;
            }
        };

        let msg = match cproxy.call_method("GetSettings", &()).await {
            Ok(m) => m,
            Err(e) => {
                warn!("Failed to get settings for connection {}: {}", conn_path, e);
                continue;
            }
        };

        let body = msg.body();
        let settings_map: HashMap<String, HashMap<String, zvariant::Value>> =
            match body.deserialize() {
                Ok(m) => m,
                Err(e) => {
                    warn!("Failed to deserialize settings for {}: {}", conn_path, e);
                    continue;
                }
            };

        let conn_sec = match settings_map.get("connection") {
            Some(s) => s,
            None => continue,
        };

        let id = match conn_sec.get("id") {
            Some(zvariant::Value::Str(s)) => s.as_str(),
            _ => continue,
        };

        let conn_type = match conn_sec.get("type") {
            Some(zvariant::Value::Str(s)) => s.as_str(),
            _ => continue,
        };

        if conn_type != "wireguard" || id != name {
            continue;
        }

        // WireGuard type is known by connection.type
        let vpn_type = VpnType::WireGuard;

        // ActiveConnection state
        let state_val: u32 = ac_proxy.get_property("State").await?;
        let state = DeviceState::from(state_val);

        // Device/interface
        let dev_paths: Vec<OwnedObjectPath> = ac_proxy.get_property("Devices").await?;
        let interface = if let Some(dev_path) = dev_paths.first() {
            let dev_proxy = nm_proxy(
                conn,
                dev_path.clone(),
                "org.freedesktop.NetworkManager.Device",
            )
            .await?;
            Some(dev_proxy.get_property::<String>("Interface").await?)
        } else {
            None
        };

        // Best-effort endpoint extraction from wireguard.peers (nmcli-style string)
        // This is not guaranteed to exist or be populated.
        let gateway = settings_map
            .get("wireguard")
            .and_then(|wg_sec| wg_sec.get("peers"))
            .and_then(|v| match v {
                zvariant::Value::Str(s) => Some(s.as_str().to_string()),
                _ => None,
            })
            .and_then(|peers| {
                // peers: "pubkey endpoint=host:port allowed-ips=... , pubkey2 ..."
                let first = peers.split(',').next()?.trim().to_string();
                for tok in first.split_whitespace() {
                    if let Some(rest) = tok.strip_prefix("endpoint=") {
                        return Some(rest.to_string());
                    }
                }
                None
            });

        // IPv4 config
        let ip4_path: OwnedObjectPath = ac_proxy.get_property("Ip4Config").await?;
        let (ip4_address, dns_servers) = if ip4_path.as_str() != "/" {
            let ip4_proxy =
                nm_proxy(conn, ip4_path, "org.freedesktop.NetworkManager.IP4Config").await?;

            let ip4_address = if let Ok(addr_array) = ip4_proxy
                .get_property::<Vec<HashMap<String, zvariant::Value>>>("AddressData")
                .await
            {
                addr_array.first().and_then(|addr_map| {
                    let address = addr_map.get("address").and_then(|v| match v {
                        zvariant::Value::Str(s) => Some(s.as_str().to_string()),
                        _ => None,
                    })?;
                    let prefix = addr_map.get("prefix").and_then(|v| match v {
                        zvariant::Value::U32(p) => Some(p),
                        _ => None,
                    })?;
                    Some(format!("{}/{}", address, prefix))
                })
            } else {
                None
            };

            let dns_servers =
                if let Ok(dns_array) = ip4_proxy.get_property::<Vec<u32>>("Nameservers").await {
                    dns_array
                        .iter()
                        .map(|ip| {
                            format!(
                                "{}.{}.{}.{}",
                                ip & 0xFF,
                                (ip >> 8) & 0xFF,
                                (ip >> 16) & 0xFF,
                                (ip >> 24) & 0xFF
                            )
                        })
                        .collect()
                } else {
                    vec![]
                };

            (ip4_address, dns_servers)
        } else {
            (None, vec![])
        };

        // IPv6 config
        let ip6_path: OwnedObjectPath = ac_proxy.get_property("Ip6Config").await?;
        let ip6_address = if ip6_path.as_str() != "/" {
            let ip6_proxy =
                nm_proxy(conn, ip6_path, "org.freedesktop.NetworkManager.IP6Config").await?;

            if let Ok(addr_array) = ip6_proxy
                .get_property::<Vec<HashMap<String, zvariant::Value>>>("AddressData")
                .await
            {
                addr_array.first().and_then(|addr_map| {
                    let address = addr_map.get("address").and_then(|v| match v {
                        zvariant::Value::Str(s) => Some(s.as_str().to_string()),
                        _ => None,
                    })?;
                    let prefix = addr_map.get("prefix").and_then(|v| match v {
                        zvariant::Value::U32(p) => Some(p),
                        _ => None,
                    })?;
                    Some(format!("{}/{}", address, prefix))
                })
            } else {
                None
            }
        } else {
            None
        };

        return Ok(VpnConnectionInfo {
            name: id.to_string(),
            vpn_type,
            state,
            interface,
            gateway,
            ip4_address,
            ip6_address,
            dns_servers,
        });
    }

    Err(crate::api::models::ConnectionError::NoVpnConnection)
}