nmrs 3.2.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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
use serde::{Deserialize, Serialize};

use super::access_point::SecurityFeatures;
use super::error::ConnectionError;

/// Represents a Wi-Fi network discovered during a scan.
///
/// This struct contains information about a WiFi network that was discovered
/// by NetworkManager during a scan operation.
///
/// # Examples
///
/// ```no_run
/// use nmrs::NetworkManager;
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// // Scan for networks (None = all Wi-Fi devices)
/// nm.scan_networks(None).await?;
/// let networks = nm.list_networks(None).await?;
///
/// for net in networks {
///     println!("SSID: {}", net.ssid);
///     println!("  Signal: {}%", net.strength.unwrap_or(0));
///     println!("  Secured: {}", net.secured);
///     
///     if let Some(freq) = net.frequency {
///         let band = if freq > 5000 { "5GHz" } else { "2.4GHz" };
///         println!("  Band: {}", band);
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Network {
    /// Device interface name (e.g., "wlan0")
    pub device: String,
    /// Network SSID (name)
    pub ssid: String,
    /// Access point MAC address (BSSID)
    pub bssid: Option<String>,
    /// Signal strength (0-100)
    pub strength: Option<u8>,
    /// Frequency in MHz (e.g., 2437 for channel 6)
    pub frequency: Option<u32>,
    /// Whether the network requires authentication
    pub secured: bool,
    /// Whether the network uses WPA-PSK authentication
    pub is_psk: bool,
    /// Whether the network uses WPA-EAP (Enterprise) authentication
    pub is_eap: bool,
    /// Whether the access point is operating in AP (hotspot) mode
    pub is_hotspot: bool,
    /// Assigned IPv4 address with CIDR notation (only present when connected)
    pub ip4_address: Option<String>,
    /// Assigned IPv6 address with CIDR notation (only present when connected)
    pub ip6_address: Option<String>,
    /// BSSID of the strongest AP for this SSID.
    #[serde(default)]
    pub best_bssid: String,
    /// All known BSSIDs for this SSID, strongest first.
    #[serde(default)]
    pub bssids: Vec<String>,
    /// `true` if this network is currently active (connected).
    #[serde(default)]
    pub is_active: bool,
    /// `true` if a saved connection profile exists for this SSID.
    #[serde(default)]
    pub known: bool,
    /// Decoded security capabilities from NM flag triplet.
    #[serde(default)]
    pub security_features: SecurityFeatures,
}

/// Detailed information about a Wi-Fi network.
///
/// Contains comprehensive information about a WiFi network, including
/// connection status, signal quality, and technical details.
///
/// # Examples
///
/// ```no_run
/// use nmrs::NetworkManager;
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
/// let networks = nm.list_networks(None).await?;
///
/// if let Some(network) = networks.first() {
///     let info = nm.show_details(network).await?;
///     
///     println!("Network: {}", info.ssid);
///     println!("Signal: {} {}", info.strength, info.bars);
///     println!("Security: {}", info.security);
///     println!("Status: {}", info.status);
///     
///     if let Some(rate) = info.rate_mbps {
///         println!("Speed: {} Mbps", rate);
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInfo {
    /// Network SSID (name)
    pub ssid: String,
    /// Access point MAC address (BSSID)
    pub bssid: String,
    /// Signal strength (0-100)
    pub strength: u8,
    /// Frequency in MHz
    pub freq: Option<u32>,
    /// WiFi channel number
    pub channel: Option<u16>,
    /// Operating mode (e.g., "infrastructure")
    pub mode: String,
    /// Connection speed in Mbps
    pub rate_mbps: Option<u32>,
    /// Visual signal strength representation (e.g., "▂▄▆█")
    pub bars: String,
    /// Security type description
    pub security: String,
    /// Connection status
    pub status: String,
    /// Assigned IPv4 address with CIDR notation (only present when connected)
    pub ip4_address: Option<String>,
    /// Assigned IPv6 address with CIDR notation (only present when connected)
    pub ip6_address: Option<String>,
}

/// EAP (Extensible Authentication Protocol) method for WPA-Enterprise Wi-Fi.
///
/// These are the outer authentication methods used in 802.1X authentication.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EapMethod {
    /// Protected EAP (PEAPv0) - tunnels inner authentication in TLS.
    /// Most commonly used with MSCHAPv2 inner authentication.
    Peap,
    /// Tunneled TLS (EAP-TTLS) - similar to PEAP but more flexible.
    /// Can use various inner authentication methods like PAP or MSCHAPv2.
    Ttls,
    /// TLS (EAP-TLS) - uses certificates for client authentication.
    Tls,
}

/// Phase 2 (inner) authentication methods for EAP connections.
///
/// These methods run inside the TLS tunnel established by the outer
/// EAP method (PEAP or TTLS).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Phase2 {
    /// Microsoft Challenge Handshake Authentication Protocol v2.
    /// More secure than PAP, commonly used with PEAP.
    Mschapv2,
    /// Password Authentication Protocol.
    /// Simple plaintext password (protected by TLS tunnel).
    /// Often used with TTLS.
    Pap,
}

/// EAP options for WPA-EAP (Enterprise) Wi-Fi connections.
///
/// Configuration for 802.1X authentication, commonly used in corporate
/// and educational networks.
///
/// # Examples
///
/// ## PEAP with MSCHAPv2 (Common Corporate Setup)
///
/// ```rust
/// use nmrs::{EapOptions, EapMethod, Phase2};
///
/// let opts = EapOptions::new("employee@company.com", "my_password")
///     .with_anonymous_identity("anonymous@company.com")
///     .with_domain_suffix_match("company.com")
///     .with_system_ca_certs(true)  // Use system certificate store
///     .with_method(EapMethod::Peap)
///     .with_phase2(Phase2::Mschapv2);
/// ```
///
/// ## TTLS with PAP (Alternative Setup)
///
/// ```rust
/// use nmrs::{EapOptions, EapMethod, Phase2};
///
/// let opts = EapOptions::new("student@university.edu", "password")
///     .with_ca_cert_path("file:///etc/ssl/certs/university-ca.pem")
///     .with_method(EapMethod::Ttls)
///     .with_phase2(Phase2::Pap);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EapOptions {
    /// User identity (usually email or username)
    pub identity: String,
    /// PEAP/TTLS: Password for authentication
    pub password: String,
    /// PEAP/TTLS: Anonymous outer identity (for privacy)
    pub anonymous_identity: Option<String>,
    /// Domain to match against server certificate
    pub domain_suffix_match: Option<String>,
    /// Path to CA certificate file (file:// URL), mutually exclusive with `ca_cert_blob`
    pub ca_cert_path: Option<String>,
    /// CA certificate encoded as DER, mutually exclusive with `ca_cert_path`
    pub ca_cert_blob: Option<Vec<u8>>,
    /// Use system CA certificate store
    pub system_ca_certs: bool,
    /// EAP method (PEAP or TTLS)
    pub method: EapMethod,
    /// PEAP/TTLS: Phase 2 inner authentication method
    pub phase2: Phase2,
    /// TLS: Path to the private key file of the client certificate (file:// URL), mutually exclusive with `private_key_blob`
    pub private_key_path: Option<String>,
    /// TLS: Private key of the client certificate encoded as PEM or PKCS#12, mutually exclusive with `private_key_path`
    pub private_key_blob: Option<Vec<u8>>,
    /// TLS: Password for the private key file
    pub private_key_password: Option<String>,
    /// TLS: Path to the client certificate file (file:// URL), mutually exclusive with `client_cert_blob`
    pub client_cert_path: Option<String>,
    /// TLS: Client certificate encoded as DER or PKCS#12, mutually exclusive with `client_cert_path`
    pub client_cert_blob: Option<Vec<u8>>,
}

impl Default for EapOptions {
    fn default() -> Self {
        Self {
            identity: String::new(),
            password: String::new(),
            anonymous_identity: None,
            domain_suffix_match: None,
            ca_cert_path: None,
            ca_cert_blob: None,
            system_ca_certs: false,
            method: EapMethod::Peap,
            phase2: Phase2::Mschapv2,
            private_key_path: None,
            private_key_blob: None,
            private_key_password: None,
            client_cert_path: None,
            client_cert_blob: None,
        }
    }
}

impl EapOptions {
    /// Creates a new `EapOptions` with the minimum required fields.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod, Phase2};
    ///
    /// let opts = EapOptions::new("user@example.com", "password")
    ///     .with_method(EapMethod::Peap)
    ///     .with_phase2(Phase2::Mschapv2);
    /// ```
    pub fn new(identity: impl Into<String>, password: impl Into<String>) -> Self {
        Self {
            identity: identity.into(),
            password: password.into(),
            ..Default::default()
        }
    }

    /// Creates a new `EapOptions` with the minimum required fields for EAP-TLS.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod};
    ///
    /// let opts = EapOptions::new_tls_path("user@example.com", "file:///etc/ssl/private/client.key", "file:///etc/ssl/certs/client.crt")
    ///     .with_private_key_password("password")
    ///     .with_ca_cert_path("file:///etc/ssl/certs/ca.pem");
    /// ```
    pub fn new_tls_path(
        identity: impl Into<String>,
        private_key_path: impl Into<String>,
        client_cert_path: impl Into<String>,
    ) -> Self {
        Self {
            identity: identity.into(),
            method: EapMethod::Tls,
            private_key_path: Some(private_key_path.into()),
            client_cert_path: Some(client_cert_path.into()),
            ..Default::default()
        }
    }

    /// Creates a new `EapOptions` with the minimum required fields for EAP-TLS.
    ///
    /// Private key must be in PEM or PKCS#12 format.
    /// Certificate must be in DER or PKCS#12 format.
    /// CA certificate must be in DER format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod};
    ///
    /// let opts = EapOptions::new_tls_blob("user@example.com", vec![], vec![])
    ///     .with_private_key_password("password")
    ///     .with_ca_cert_blob(vec![]);
    /// ```
    pub fn new_tls_blob(
        identity: impl Into<String>,
        private_key_blob: impl Into<Vec<u8>>,
        client_cert_blob: impl Into<Vec<u8>>,
    ) -> Self {
        Self {
            identity: identity.into(),
            method: EapMethod::Tls,
            private_key_blob: Some(private_key_blob.into()),
            client_cert_blob: Some(client_cert_blob.into()),
            ..Default::default()
        }
    }

    /// Creates a new `EapOptions` builder.
    ///
    /// This provides an alternative way to construct EAP options with a fluent API,
    /// making it clearer what each configuration option does.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod, Phase2};
    ///
    /// let opts = EapOptions::builder()
    ///     .identity("user@company.com")
    ///     .password("my_password")
    ///     .method(EapMethod::Peap)
    ///     .phase2(Phase2::Mschapv2)
    ///     .domain_suffix_match("company.com")
    ///     .system_ca_certs(true)
    ///     .build()
    ///     .expect("all required fields set");
    /// ```
    #[must_use]
    pub fn builder() -> EapOptionsBuilder {
        EapOptionsBuilder::default()
    }

    /// Sets the anonymous identity for privacy.
    #[must_use]
    pub fn with_anonymous_identity(mut self, anonymous_identity: impl Into<String>) -> Self {
        self.anonymous_identity = Some(anonymous_identity.into());
        self
    }

    /// Sets the domain suffix to match against the server certificate.
    #[must_use]
    pub fn with_domain_suffix_match(mut self, domain: impl Into<String>) -> Self {
        self.domain_suffix_match = Some(domain.into());
        self
    }

    /// Sets the path to the CA certificate file (must start with `file://`).
    ///
    /// Clears `ca_cert_blob` because they are mutually exclusive.
    #[must_use]
    pub fn with_ca_cert_path(mut self, path: impl Into<String>) -> Self {
        self.ca_cert_blob = None;
        self.ca_cert_path = Some(path.into());
        self
    }

    /// Sets the CA certificate encoded as DER.
    ///
    /// Clears `ca_cert_path` because they are mutually exclusive.
    #[must_use]
    pub fn with_ca_cert_blob(mut self, data: impl Into<Vec<u8>>) -> Self {
        self.ca_cert_path = None;
        self.ca_cert_blob = Some(data.into());
        self
    }

    /// Sets whether to use the system CA certificate store.
    #[must_use]
    pub fn with_system_ca_certs(mut self, use_system: bool) -> Self {
        self.system_ca_certs = use_system;
        self
    }

    /// Sets the EAP method (PEAP or TTLS).
    #[must_use]
    pub fn with_method(mut self, method: EapMethod) -> Self {
        self.method = method;
        self
    }

    /// Sets the Phase 2 authentication method.
    #[must_use]
    pub fn with_phase2(mut self, phase2: Phase2) -> Self {
        self.phase2 = phase2;
        self
    }

    /// Sets the password for the private key file.
    #[must_use]
    pub fn with_private_key_password(mut self, password: impl Into<String>) -> Self {
        self.private_key_password = Some(password.into());
        self
    }
}

/// Builder for constructing `EapOptions` with a fluent API.
///
/// This builder provides an ergonomic way to create EAP (Enterprise WiFi)
/// authentication options, making the configuration more explicit and readable.
///
/// # Examples
///
/// ## PEAP with MSCHAPv2 (Common Corporate Setup)
///
/// ```rust
/// use nmrs::{EapOptions, EapMethod, Phase2};
///
/// let opts = EapOptions::builder()
///     .identity("employee@company.com")
///     .password("my_password")
///     .method(EapMethod::Peap)
///     .phase2(Phase2::Mschapv2)
///     .anonymous_identity("anonymous@company.com")
///     .domain_suffix_match("company.com")
///     .system_ca_certs(true)
///     .build()
///     .expect("all required fields set");
/// ```
///
/// ## TTLS with PAP
///
/// ```rust
/// use nmrs::{EapOptions, EapMethod, Phase2};
///
/// let opts = EapOptions::builder()
///     .identity("student@university.edu")
///     .password("password")
///     .method(EapMethod::Ttls)
///     .phase2(Phase2::Pap)
///     .ca_cert_path("file:///etc/ssl/certs/university-ca.pem")
///     .build()
///     .expect("all required fields set");
/// ```
///
/// ## TLS
///
/// ```rust
/// use nmrs::{EapOptions, EapMethod};
///
/// let opts = EapOptions::builder()
///     .identity("student@university.edu")
///     .method(EapMethod::Tls)
///     .private_key_path("file:///etc/ssl/private/student.key")
///     .private_key_password("password")
///     .client_cert_path("file:///etc/ssl/certs/student.crt")
///     .ca_cert_path("file:///etc/ssl/certs/university-ca.pem")
///     .build()
///     .expect("all required fields set");
/// ```
#[derive(Debug, Default)]
pub struct EapOptionsBuilder {
    identity: Option<String>,
    password: Option<String>,
    anonymous_identity: Option<String>,
    domain_suffix_match: Option<String>,
    ca_cert_path: Option<String>,
    ca_cert_blob: Option<Vec<u8>>,
    system_ca_certs: bool,
    method: Option<EapMethod>,
    phase2: Option<Phase2>,
    private_key_path: Option<String>,
    private_key_blob: Option<Vec<u8>>,
    private_key_password: Option<String>,
    client_cert_path: Option<String>,
    client_cert_blob: Option<Vec<u8>>,
}

impl EapOptionsBuilder {
    /// Sets the user identity (usually email or username).
    ///
    /// This is a required field.
    #[must_use]
    pub fn identity(mut self, identity: impl Into<String>) -> Self {
        self.identity = Some(identity.into());
        self
    }

    /// Sets the password for authentication.
    ///
    /// This is a required field.
    #[must_use]
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Sets the anonymous outer identity for privacy.
    ///
    /// This identity is sent in the clear during the initial handshake,
    /// while the real identity is protected inside the TLS tunnel.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .anonymous_identity("anonymous@company.com");
    /// ```
    #[must_use]
    pub fn anonymous_identity(mut self, anonymous_identity: impl Into<String>) -> Self {
        self.anonymous_identity = Some(anonymous_identity.into());
        self
    }

    /// Sets the domain suffix to match against the server certificate.
    ///
    /// This provides additional security by verifying the server's certificate
    /// matches the expected domain.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .domain_suffix_match("company.com");
    /// ```
    #[must_use]
    pub fn domain_suffix_match(mut self, domain: impl Into<String>) -> Self {
        self.domain_suffix_match = Some(domain.into());
        self
    }

    /// Sets the path to the CA certificate file.
    ///
    /// The path must start with `file://` (e.g., "file:///etc/ssl/certs/ca.pem").
    ///
    /// Clears `ca_cert_blob` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .ca_cert_path("file:///etc/ssl/certs/company-ca.pem");
    /// ```
    #[must_use]
    pub fn ca_cert_path(mut self, path: impl Into<String>) -> Self {
        self.ca_cert_blob = None;
        self.ca_cert_path = Some(path.into());
        self
    }

    /// Sets the CA certificate encoded as DER.
    ///
    /// Clears `ca_cert_path` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .ca_cert_blob(vec![]);
    /// ```
    #[must_use]
    pub fn ca_cert_blob(mut self, data: impl Into<Vec<u8>>) -> Self {
        self.ca_cert_path = None;
        self.ca_cert_blob = Some(data.into());
        self
    }

    /// Sets whether to use the system CA certificate store.
    ///
    /// When enabled, the system's trusted CA certificates will be used
    /// to validate the server certificate.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .system_ca_certs(true);
    /// ```
    #[must_use]
    pub fn system_ca_certs(mut self, use_system: bool) -> Self {
        self.system_ca_certs = use_system;
        self
    }

    /// Sets the EAP method (PEAP or TTLS).
    ///
    /// This is a required field. PEAP is more common in corporate environments,
    /// while TTLS offers more flexibility in inner authentication methods.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod};
    ///
    /// let builder = EapOptions::builder()
    ///     .method(EapMethod::Peap);
    /// ```
    #[must_use]
    pub fn method(mut self, method: EapMethod) -> Self {
        self.method = Some(method);
        self
    }

    /// Sets the Phase 2 (inner) authentication method.
    ///
    /// This is a required field. MSCHAPv2 is commonly used with PEAP,
    /// while PAP is often used with TTLS.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, Phase2};
    ///
    /// let builder = EapOptions::builder()
    ///     .phase2(Phase2::Mschapv2);
    /// ```
    #[must_use]
    pub fn phase2(mut self, phase2: Phase2) -> Self {
        self.phase2 = Some(phase2);
        self
    }

    /// Sets the path to the private key file of the client certificate.
    ///
    /// The path must start with `file://` (e.g., "file:///etc/ssl/private/client.key").
    ///
    /// Clears `private_key_blob` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .private_key_path("file:///etc/ssl/private/client.key");
    /// ```
    #[must_use]
    pub fn private_key_path(mut self, path: impl Into<String>) -> Self {
        self.private_key_blob = None;
        self.private_key_path = Some(path.into());
        self
    }

    /// Sets the private key of the client certificate encoded as PEM or PKCS#12.
    ///
    /// Clears `private_key_path` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .private_key_blob(vec![]);
    /// ```
    #[must_use]
    pub fn private_key_blob(mut self, data: impl Into<Vec<u8>>) -> Self {
        self.private_key_path = None;
        self.private_key_blob = Some(data.into());
        self
    }

    /// Sets the password for the private key file.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .private_key_password("password");
    /// ```
    #[must_use]
    pub fn private_key_password(mut self, password: impl Into<String>) -> Self {
        self.private_key_password = Some(password.into());
        self
    }

    /// Sets the path to the client certificate file.
    ///
    /// The path must start with `file://` (e.g., "file:///etc/ssl/certs/client.crt").
    ///
    /// Clears `client_cert_blob` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .client_cert_path("file:///etc/ssl/certs/client.crt");
    /// ```
    #[must_use]
    pub fn client_cert_path(mut self, path: impl Into<String>) -> Self {
        self.client_cert_blob = None;
        self.client_cert_path = Some(path.into());
        self
    }

    /// Sets the client certificate encoded as DER or PKCS#12.
    ///
    /// Clears `client_cert_path` because they are mutually exclusive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::EapOptions;
    ///
    /// let builder = EapOptions::builder()
    ///     .client_cert_blob(vec![]);
    /// ```
    #[must_use]
    pub fn client_cert_blob(mut self, data: impl Into<Vec<u8>>) -> Self {
        self.client_cert_path = None;
        self.client_cert_blob = Some(data.into());
        self
    }

    /// Builds the `EapOptions` from the configured values.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectionError::IncompleteBuilder`](crate::ConnectionError::IncompleteBuilder)
    /// if any required field is missing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{EapOptions, EapMethod, Phase2};
    ///
    /// let opts = EapOptions::builder()
    ///     .identity("user@example.com")
    ///     .password("password")
    ///     .method(EapMethod::Peap)
    ///     .phase2(Phase2::Mschapv2)
    ///     .build()
    ///     .expect("all required fields set");
    /// ```
    #[must_use = "use the EAP options with WifiSecurity::WpaEap or handle the error"]
    pub fn build(self) -> Result<EapOptions, ConnectionError> {
        let is_peap_or_ttls =
            self.method == Some(EapMethod::Peap) || self.method == Some(EapMethod::Ttls);

        if self.ca_cert_path.is_some() && self.ca_cert_blob.is_some() {
            return Err(ConnectionError::IncompleteBuilder(
                "EAP CA certificate cannot be specified both as a path and blob".into(),
            ));
        }
        if self.private_key_path.is_some() && self.private_key_blob.is_some() {
            return Err(ConnectionError::IncompleteBuilder(
                "EAP private key cannot be specified both as a path and blob".into(),
            ));
        }
        if self.client_cert_path.is_some() && self.client_cert_blob.is_some() {
            return Err(ConnectionError::IncompleteBuilder(
                "EAP client certificate cannot be specified both as a path and blob".into(),
            ));
        }
        if self.method == Some(EapMethod::Tls) {
            if self.private_key_path.is_none() && self.private_key_blob.is_none() {
                return Err(ConnectionError::IncompleteBuilder(
                    "EAP private key is required for TLS (use .private_key_path() or .private_key_blob())".into(),
                ));
            }
            if self.client_cert_path.is_none() && self.client_cert_blob.is_none() {
                return Err(ConnectionError::IncompleteBuilder(
                    "EAP client certificate is required for TLS (use .client_cert_path() or .client_cert_blob())".into(),
                ));
            }
        }

        Ok(EapOptions {
            identity: self.identity.ok_or_else(|| {
                ConnectionError::IncompleteBuilder(
                    "EAP identity is required (use .identity())".into(),
                )
            })?,
            password: if is_peap_or_ttls {
                self.password.ok_or_else(|| {
                    ConnectionError::IncompleteBuilder(
                        "EAP password is required (use .password())".into(),
                    )
                })?
            } else {
                String::new()
            },
            anonymous_identity: self.anonymous_identity,
            domain_suffix_match: self.domain_suffix_match,
            ca_cert_path: self.ca_cert_path,
            ca_cert_blob: self.ca_cert_blob,
            system_ca_certs: self.system_ca_certs,
            method: self.method.ok_or_else(|| {
                ConnectionError::IncompleteBuilder("EAP method is required (use .method())".into())
            })?,
            phase2: if is_peap_or_ttls {
                self.phase2.ok_or_else(|| {
                    ConnectionError::IncompleteBuilder(
                        "EAP phase 2 method is required (use .phase2())".into(),
                    )
                })?
            } else {
                Phase2::Mschapv2
            },
            private_key_path: self.private_key_path,
            private_key_blob: self.private_key_blob,
            private_key_password: self.private_key_password,
            client_cert_path: self.client_cert_path,
            client_cert_blob: self.client_cert_blob,
        })
    }
}

/// Wi-Fi connection security types.
///
/// Represents the authentication method for connecting to a WiFi network.
///
/// # Variants
///
/// - [`Open`](WifiSecurity::Open) - No authentication required (open network)
/// - [`WpaPsk`](WifiSecurity::WpaPsk) - WPA/WPA2/WPA3 Personal (password-based)
/// - [`WpaEap`](WifiSecurity::WpaEap) - WPA/WPA2 Enterprise (802.1X authentication)
///
/// # Examples
///
/// ## Open Network
///
/// ```rust
/// use nmrs::WifiSecurity;
///
/// let security = WifiSecurity::Open;
/// ```
///
/// ## Password-Protected Network
///
/// ```no_run
/// use nmrs::{NetworkManager, WifiSecurity};
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// nm.connect("HomeWiFi", None, WifiSecurity::WpaPsk {
///     psk: "my_secure_password".into()
/// }).await?;
/// # Ok(())
/// # }
/// ```
///
/// ## Enterprise Network (WPA-EAP)
///
/// ```no_run
/// use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2};
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// 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?;
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WifiSecurity {
    /// Open network (no authentication)
    Open,
    /// WPA-PSK (password-based authentication)
    WpaPsk {
        /// Pre-shared key (password)
        psk: String,
    },
    /// WPA-EAP (Enterprise authentication via 802.1X)
    WpaEap {
        /// EAP configuration options
        opts: EapOptions,
    },
    /// WPA3-EAP 192-bit mode (Enterprise authentication via 802.1X)
    /// Only EAP-TLS is allowed as authentication method.
    Wpa3Eap192bit {
        /// EAP configuration options
        opts: EapOptions,
    },
}

impl WifiSecurity {
    /// Returns `true` if this security type requires authentication.
    #[must_use]
    pub fn secured(&self) -> bool {
        !matches!(self, WifiSecurity::Open)
    }

    /// Returns `true` if this is a WPA-PSK (password-based) security type.
    #[must_use]
    pub fn is_psk(&self) -> bool {
        matches!(self, WifiSecurity::WpaPsk { .. })
    }

    /// Returns `true` if this is a WPA-EAP (Enterprise/802.1X) security type.
    #[must_use]
    pub fn is_eap(&self) -> bool {
        matches!(
            self,
            WifiSecurity::WpaEap { .. } | WifiSecurity::Wpa3Eap192bit { .. }
        )
    }
}

impl Network {
    /// Merges another access point's information into this network.
    ///
    /// When multiple access points share the same SSID (e.g., mesh networks),
    /// this method keeps the strongest signal and combines security flags.
    /// Used internally during network scanning to deduplicate results.
    pub fn merge_ap(&mut self, other: &Network) {
        if let Some(ref b) = other.bssid
            && !self.bssids.contains(b)
        {
            self.bssids.push(b.clone());
        }

        if other.strength.unwrap_or(0) > self.strength.unwrap_or(0) {
            self.strength = other.strength;
            self.frequency = other.frequency;
            self.bssid = other.bssid.clone();
            self.best_bssid = other.best_bssid.clone();
            self.security_features = other.security_features;
        }

        self.secured |= other.secured;
        self.is_psk |= other.is_psk;
        self.is_eap |= other.is_eap;
        self.is_hotspot |= other.is_hotspot;
        self.is_active |= other.is_active;
        self.known |= other.known;

        if self.ip4_address.is_none() {
            self.ip4_address.clone_from(&other.ip4_address);
        }
        if self.ip6_address.is_none() {
            self.ip6_address.clone_from(&other.ip6_address);
        }
        if self.device.is_empty() {
            self.device.clone_from(&other.device);
        }
    }
}

#[cfg(test)]
mod network_merge_tests {
    use super::Network;

    #[test]
    fn merge_ap_keeps_ip_and_device_when_stronger_ap_has_none() {
        let mut weaker_connected = Network {
            device: "wlan0".into(),
            ssid: "net".into(),
            bssid: Some("aa:aa:aa:aa:aa:aa".into()),
            strength: Some(20),
            frequency: Some(5200),
            secured: true,
            is_psk: true,
            is_eap: false,
            is_hotspot: false,
            ip4_address: Some("192.168.1.5/24".into()),
            ip6_address: Some("fe80::1/64".into()),
            best_bssid: "aa:aa:aa:aa:aa:aa".into(),
            bssids: vec!["aa:aa:aa:aa:aa:aa".into()],
            is_active: true,
            known: false,
            security_features: Default::default(),
        };
        let stronger = Network {
            device: String::new(),
            ssid: "net".into(),
            bssid: Some("bb:bb:bb:bb:bb:bb".into()),
            strength: Some(90),
            frequency: Some(5200),
            secured: true,
            is_psk: true,
            is_eap: false,
            is_hotspot: false,
            ip4_address: None,
            ip6_address: None,
            best_bssid: "bb:bb:bb:bb:bb:bb".into(),
            bssids: vec!["bb:bb:bb:bb:bb:bb".into()],
            is_active: false,
            known: false,
            security_features: Default::default(),
        };
        weaker_connected.merge_ap(&stronger);
        assert_eq!(weaker_connected.strength, Some(90));
        assert_eq!(weaker_connected.bssid, Some("bb:bb:bb:bb:bb:bb".into()));
        assert_eq!(weaker_connected.best_bssid, "bb:bb:bb:bb:bb:bb");
        assert_eq!(weaker_connected.ip4_address, Some("192.168.1.5/24".into()));
        assert_eq!(weaker_connected.ip6_address, Some("fe80::1/64".into()));
        assert_eq!(weaker_connected.device, "wlan0");
        assert!(weaker_connected.is_active);
        assert_eq!(weaker_connected.bssids.len(), 2);
    }
}