wifui 0.3.0

A lightweight, keyboard-driven Terminal User Interface (TUI) for managing Wi-Fi connections on Windows.
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
use color_eyre::eyre::{Result, eyre};
use std::collections::HashMap;
use tokio::sync::mpsc::UnboundedSender;
use windows::{
    Win32::{
        Foundation::{ERROR_NOT_FOUND, ERROR_SUCCESS, HANDLE},
        NetworkManagement::WiFi::*,
    },
    core::{GUID, PCWSTR, PWSTR},
};

#[derive(Debug, Default, Clone)]
pub struct WifiInfo {
    pub ssid: String,
    pub network_type: String,
    pub authentication: String,
    pub encryption: String,
    pub signal: u8,
    pub is_saved: bool,
    pub is_connected: bool,
    pub auto_connect: bool,
    pub phy_type: String,
    pub channel: u32,
    pub frequency: u32,
    pub link_speed: Option<u32>,
}

#[derive(Debug, Clone)]
pub enum ConnectionEvent {
    Connected(String),
    #[allow(dead_code)]
    Disconnected(String),
    Failed {
        ssid: String,
        #[allow(dead_code)]
        reason_code: u32,
        reason_str: String,
    },
}

#[derive(Debug)]
pub struct WifiListener {
    handle: HANDLE,
    context: *mut std::ffi::c_void,
}

unsafe impl Send for WifiListener {}
unsafe impl Sync for WifiListener {}

impl Drop for WifiListener {
    fn drop(&mut self) {
        unsafe {
            let _ = WlanRegisterNotification(
                self.handle,
                WLAN_NOTIFICATION_SOURCE_NONE,
                true,
                None,
                None,
                None,
                None,
            );
            let _ = WlanCloseHandle(self.handle, None);
            let _ = Box::from_raw(self.context as *mut UnboundedSender<ConnectionEvent>);
        }
    }
}

unsafe extern "system" fn notification_callback(
    data: *mut L2_NOTIFICATION_DATA,
    context: *mut std::ffi::c_void,
) {
    if data.is_null() || context.is_null() {
        return;
    }

    // SAFETY: We checked for null above.
    // The context is a pointer to UnboundedSender<ConnectionEvent> created in start_wifi_listener
    let (data, sender) = unsafe {
        (
            &*data,
            &*(context as *const UnboundedSender<ConnectionEvent>),
        )
    };

    if data.NotificationSource != WLAN_NOTIFICATION_SOURCE_ACM {
        return;
    }

    if data.NotificationCode == wlan_notification_acm_connection_complete.0 as u32
        || data.NotificationCode == wlan_notification_acm_connection_attempt_fail.0 as u32
        || data.NotificationCode == wlan_notification_acm_disconnected.0 as u32
    {
        if data.dwDataSize < std::mem::size_of::<WLAN_CONNECTION_NOTIFICATION_DATA>() as u32 {
            return;
        }

        // SAFETY: The documentation guarantees pData points to WLAN_CONNECTION_NOTIFICATION_DATA
        // for these notification codes, and we checked the size above.
        let conn_data = unsafe { &*(data.pData as *const WLAN_CONNECTION_NOTIFICATION_DATA) };

        // Extract SSID
        let ssid_len = conn_data.dot11Ssid.uSSIDLength as usize;
        let ssid_bytes = &conn_data.dot11Ssid.ucSSID[..ssid_len];
        let ssid = String::from_utf8_lossy(ssid_bytes).to_string();

        if data.NotificationCode == wlan_notification_acm_connection_complete.0 as u32 {
            let _ = sender.send(ConnectionEvent::Connected(ssid));
        } else if data.NotificationCode == wlan_notification_acm_disconnected.0 as u32 {
            let _ = sender.send(ConnectionEvent::Disconnected(ssid));
        } else if data.NotificationCode == wlan_notification_acm_connection_attempt_fail.0 as u32 {
            let reason_code = conn_data.wlanReasonCode;
            let reason_str = match reason_code {
                // Success / Unknown
                v if v == WLAN_REASON_CODE_SUCCESS => "Success".to_string(),
                v if v == WLAN_REASON_CODE_UNKNOWN => "Unknown Failure".to_string(),

                // Network / Profile Compatibility
                v if v == WLAN_REASON_CODE_NETWORK_NOT_COMPATIBLE => {
                    "Network Not Compatible".to_string()
                }
                v if v == WLAN_REASON_CODE_PROFILE_NOT_COMPATIBLE => {
                    "Profile Not Compatible".to_string()
                }

                // Association
                v if v == WLAN_REASON_CODE_ASSOCIATION_FAILURE => "Association Failed".to_string(),
                v if v == WLAN_REASON_CODE_ASSOCIATION_TIMEOUT => "Association Timeout".to_string(),
                v if v == WLAN_REASON_CODE_PRE_SECURITY_FAILURE => {
                    "Pre-Security Failure".to_string()
                }
                v if v == WLAN_REASON_CODE_START_SECURITY_FAILURE => {
                    "Start Security Failure".to_string()
                }
                v if v == WLAN_REASON_CODE_SECURITY_FAILURE => "Security Failure".to_string(),
                v if v == WLAN_REASON_CODE_SECURITY_TIMEOUT => "Security Timeout".to_string(),
                v if v == WLAN_REASON_CODE_ROAMING_FAILURE => "Roaming Failure".to_string(),
                v if v == WLAN_REASON_CODE_ROAMING_SECURITY_FAILURE => {
                    "Roaming Security Failure".to_string()
                }
                v if v == WLAN_REASON_CODE_ADHOC_SECURITY_FAILURE => {
                    "Ad-hoc Security Failure".to_string()
                }

                // Driver / IHV
                v if v == WLAN_REASON_CODE_DRIVER_DISCONNECTED => {
                    "Driver Disconnected (Possible Wrong Password)".to_string()
                }
                v if v == WLAN_REASON_CODE_DRIVER_OPERATION_FAILURE => {
                    "Driver Operation Failure".to_string()
                }
                v if v == WLAN_REASON_CODE_IHV_NOT_AVAILABLE => "IHV Not Available".to_string(),
                v if v == WLAN_REASON_CODE_IHV_NOT_RESPONDING => "IHV Not Responding".to_string(),

                // Manual mappings for missing constants (MSM Security)
                327684 => "Incorrect Password".to_string(), // WLAN_REASON_CODE_MSM_SECURITY_BAD_PASSPHRASE (0x00050004)
                294917 => "Incorrect Password (Key Exchange Timeout)".to_string(), // WLAN_REASON_CODE_MSMSEC_AUTH_SUCCESS_TIMEOUT (0x00048005) - Often Wrong Password
                294932 => "Authentication Timeout (Possible Wrong Password)".to_string(), // 0x48014 - Timeout waiting for response
                524294 => "MSM Security Missing".to_string(), // WLAN_REASON_CODE_MSM_SECURITY_MISSING
                229396 => "Connection Failed (Profile Issue)".to_string(), // 0x38014 - WLAN_REASON_CODE_MSMSEC_UI_REQUEST_FAILURE

                _ => format!("Reason Code: {}", reason_code),
            };

            let _ = sender.send(ConnectionEvent::Failed {
                ssid,
                reason_code,
                reason_str,
            });
        }
    }
}

pub fn start_wifi_listener(sender: UnboundedSender<ConnectionEvent>) -> Result<WifiListener> {
    let (handle, _) = get_wlan_handle()?;

    // Box the sender to pass as context
    let context = Box::into_raw(Box::new(sender));

    unsafe {
        let result = WlanRegisterNotification(
            handle,
            WLAN_NOTIFICATION_SOURCE_ACM,
            false,
            Some(notification_callback),
            Some(context as *mut std::ffi::c_void),
            None,
            None,
        );

        if result != ERROR_SUCCESS.0 {
            let _ = Box::from_raw(context as *mut UnboundedSender<ConnectionEvent>); // Cleanup
            WlanCloseHandle(handle, None);
            return Err(eyre!("Failed to register notification: {}", result));
        }
    }

    Ok(WifiListener {
        handle,
        context: context as *mut std::ffi::c_void,
    })
}

// Helper to open WLAN handle
fn get_wlan_handle() -> Result<(HANDLE, u32)> {
    let mut negotiated_version = 0;
    let mut handle = HANDLE::default();
    unsafe {
        let result = WlanOpenHandle(2, None, &mut negotiated_version, &mut handle);
        if result != ERROR_SUCCESS.0 {
            return Err(eyre!("Failed to open WLAN handle: {}", result));
        }
    }
    Ok((handle, negotiated_version))
}

// Helper to get the first interface GUID
fn get_interface_guid(handle: HANDLE) -> Result<GUID> {
    unsafe {
        let mut interface_list: *mut WLAN_INTERFACE_INFO_LIST = std::ptr::null_mut();
        let result = WlanEnumInterfaces(handle, None, &mut interface_list);
        if result != ERROR_SUCCESS.0 {
            return Err(eyre!("Failed to enum interfaces: {}", result));
        }

        if (*interface_list).dwNumberOfItems == 0 {
            WlanFreeMemory(interface_list as *mut _);
            return Err(eyre!("No WiFi interface found"));
        }

        let interface_info = &(*interface_list).InterfaceInfo[0];
        let guid = interface_info.InterfaceGuid;
        WlanFreeMemory(interface_list as *mut _);
        Ok(guid)
    }
}

pub fn get_connected_ssid() -> Result<Option<String>> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    let mut connected_ssid = None;

    unsafe {
        let mut data_size = 0;
        let mut data_ptr: *mut std::ffi::c_void = std::ptr::null_mut();
        let mut opcode_value_type = wlan_opcode_value_type_invalid;

        let result = WlanQueryInterface(
            handle,
            &guid,
            wlan_intf_opcode_current_connection,
            None,
            &mut data_size,
            &mut data_ptr,
            Some(&mut opcode_value_type),
        );

        if result == ERROR_SUCCESS.0 {
            let connection_attributes = &*(data_ptr as *const WLAN_CONNECTION_ATTRIBUTES);
            if connection_attributes.isState == wlan_interface_state_connected {
                let ssid_len = connection_attributes
                    .wlanAssociationAttributes
                    .dot11Ssid
                    .uSSIDLength as usize;
                let ssid_bytes = &connection_attributes
                    .wlanAssociationAttributes
                    .dot11Ssid
                    .ucSSID[..ssid_len];
                connected_ssid = Some(String::from_utf8_lossy(ssid_bytes).to_string());
            }
            WlanFreeMemory(data_ptr);
        }

        WlanCloseHandle(handle, None);
    }

    Ok(connected_ssid)
}

pub fn scan_networks() -> Result<()> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let result = WlanScan(handle, &guid, None, None, None);
        WlanCloseHandle(handle, None);
        if result != ERROR_SUCCESS.0 {
            return Err(eyre!("Failed to scan networks: {}", result));
        }
    }
    Ok(())
}

fn is_profile_auto_connect(handle: HANDLE, guid: &GUID, profile_name: &str) -> bool {
    unsafe {
        let profile_name_wide: Vec<u16> = profile_name
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        let p_profile_name = PCWSTR(profile_name_wide.as_ptr());
        let mut p_profile_xml = PWSTR::null();
        let mut flags = 0;

        let result = WlanGetProfile(
            handle,
            guid,
            p_profile_name,
            None,
            &mut p_profile_xml,
            Some(&mut flags),
            None,
        );

        if result == ERROR_SUCCESS.0 && !p_profile_xml.is_null() {
            let xml = p_profile_xml.to_string().unwrap_or_default();
            WlanFreeMemory(p_profile_xml.as_ptr() as *mut _);
            return xml.contains("<connectionMode>auto</connectionMode>");
        }
    }
    false
}

#[allow(non_upper_case_globals)]
pub fn get_wifi_networks() -> Result<Vec<WifiInfo>> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    let mut wifi_list: Vec<WifiInfo>;

    unsafe {
        let mut available_network_list: *mut WLAN_AVAILABLE_NETWORK_LIST = std::ptr::null_mut();
        let result = WlanGetAvailableNetworkList(
            handle,
            &guid,
            WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES
                | WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
            None,
            &mut available_network_list,
        );

        if result != ERROR_SUCCESS.0 {
            WlanCloseHandle(handle, None);
            return Err(eyre!("Failed to get available networks: {}", result));
        }

        // Get current connection info for link speed
        let mut current_connection: Option<(String, u32)> = None;
        let mut data_size = 0;
        let mut data_ptr: *mut std::ffi::c_void = std::ptr::null_mut();
        let mut opcode_value_type = wlan_opcode_value_type_invalid;

        let result_query = WlanQueryInterface(
            handle,
            &guid,
            wlan_intf_opcode_current_connection,
            None,
            &mut data_size,
            &mut data_ptr,
            Some(&mut opcode_value_type),
        );

        if result_query == ERROR_SUCCESS.0 {
            let conn = &*(data_ptr as *const WLAN_CONNECTION_ATTRIBUTES);
            if conn.isState == wlan_interface_state_connected {
                let ssid_len = conn.wlanAssociationAttributes.dot11Ssid.uSSIDLength as usize;
                let ssid_bytes = &conn.wlanAssociationAttributes.dot11Ssid.ucSSID[..ssid_len];
                let ssid = String::from_utf8_lossy(ssid_bytes).to_string();
                let tx_rate = conn.wlanAssociationAttributes.ulTxRate;
                current_connection = Some((ssid, tx_rate));
            }
            WlanFreeMemory(data_ptr);
        }

        // Get BSS List to find channel, frequency and rate
        let mut bss_list: *mut WLAN_BSS_LIST = std::ptr::null_mut();
        let result_bss = WlanGetNetworkBssList(
            handle,
            &guid,
            None,
            dot11_BSS_type_any,
            false,
            None,
            &mut bss_list,
        );

        let mut bss_entries: &[WLAN_BSS_ENTRY] = &[];
        if result_bss == ERROR_SUCCESS.0 && !bss_list.is_null() {
            let num_bss = (*bss_list).dwNumberOfItems;
            bss_entries =
                std::slice::from_raw_parts((*bss_list).wlanBssEntries.as_ptr(), num_bss as usize);
        }

        let num_items = (*available_network_list).dwNumberOfItems;
        let items = std::slice::from_raw_parts(
            (*available_network_list).Network.as_ptr(),
            num_items as usize,
        );

        let mut wifi_map: HashMap<(String, String), WifiInfo> = HashMap::new();

        for item in items {
            let ssid_len = item.dot11Ssid.uSSIDLength as usize;
            if ssid_len == 0 {
                continue;
            }

            let ssid_bytes = &item.dot11Ssid.ucSSID[..ssid_len];
            let ssid = String::from_utf8_lossy(ssid_bytes).to_string();

            // Find best BSS entry for this SSID
            let best_bss = bss_entries
                .iter()
                .filter(|bss| {
                    let bss_ssid_len = bss.dot11Ssid.uSSIDLength as usize;
                    if bss_ssid_len != ssid_len {
                        return false;
                    }
                    &bss.dot11Ssid.ucSSID[..bss_ssid_len] == ssid_bytes
                })
                .max_by_key(|bss| bss.lRssi);

            let (frequency, channel) = if let Some(bss) = best_bss {
                let freq = bss.ulChCenterFrequency;
                let ch = if (2412000..=2484000).contains(&freq) {
                    if freq == 2484000 {
                        14
                    } else {
                        (freq - 2407000) / 5000
                    }
                } else if (5000000..=5900000).contains(&freq) {
                    (freq - 5000000) / 5000
                } else if (5925000..=7125000).contains(&freq) {
                    (freq - 5950000) / 5000
                } else {
                    0
                };

                (freq, ch)
            } else {
                (0, 0)
            };

            let mut link_speed = None;
            let mut is_connected = false;
            if let Some((ref conn_ssid, conn_rate)) = current_connection
                && *conn_ssid == ssid
            {
                link_speed = Some(conn_rate / 1000); // Kbps to Mbps
                is_connected = true;
            }

            let authentication = match item.dot11DefaultAuthAlgorithm {
                DOT11_AUTH_ALGO_80211_OPEN => "Open",
                DOT11_AUTH_ALGO_80211_SHARED_KEY => "Shared",
                DOT11_AUTH_ALGO_WPA => "WPA",
                DOT11_AUTH_ALGO_WPA_PSK => "WPA-PSK",
                DOT11_AUTH_ALGO_WPA_NONE => "WPA-None",
                DOT11_AUTH_ALGO_RSNA => "WPA2",
                DOT11_AUTH_ALGO_RSNA_PSK => "WPA2-PSK",
                DOT11_AUTH_ALGO_WPA3 => "WPA3",
                DOT11_AUTH_ALGO_WPA3_SAE => "WPA3-SAE",
                _ => "Unknown",
            }
            .to_string();

            let encryption = match item.dot11DefaultCipherAlgorithm {
                DOT11_CIPHER_ALGO_NONE => "None",
                DOT11_CIPHER_ALGO_WEP40 => "WEP",
                DOT11_CIPHER_ALGO_TKIP => "TKIP",
                DOT11_CIPHER_ALGO_CCMP => "AES",
                DOT11_CIPHER_ALGO_WEP104 => "WEP",
                DOT11_CIPHER_ALGO_WPA_USE_GROUP => "WPA-Group",
                DOT11_CIPHER_ALGO_GCMP => "GCMP",
                _ => "Unknown",
            }
            .to_string();

            let is_saved = (item.dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE) != 0;
            let mut auto_connect = false;
            if is_saved {
                auto_connect = is_profile_auto_connect(handle, &guid, &ssid);
            }

            let bss_type = match item.dot11BssType {
                dot11_BSS_type_infrastructure => "Infrastructure",
                dot11_BSS_type_independent => "Ad-hoc",
                dot11_BSS_type_any => "Any",
                _ => "Unknown",
            }
            .to_string();

            let phy_types = std::slice::from_raw_parts(
                item.dot11PhyTypes.as_ptr(),
                item.uNumberOfPhyTypes as usize,
            );

            let phy_type = if let Some(phy) = phy_types.first() {
                match *phy {
                    dot11_phy_type_ofdm => "802.11a",
                    dot11_phy_type_hrdsss => "802.11b",
                    dot11_phy_type_erp => "802.11g",
                    dot11_phy_type_ht => "802.11n (Wi-Fi 4)",
                    dot11_phy_type_vht => "802.11ac (Wi-Fi 5)",
                    dot11_phy_type_he => "802.11ax (Wi-Fi 6)",
                    dot11_phy_type_eht => "802.11be (Wi-Fi 7)",
                    _ => "Legacy/Unknown",
                }
                .to_string()
            } else {
                "Unknown".to_string()
            };

            let signal = item.wlanSignalQuality as u8;

            let new_info = WifiInfo {
                ssid: ssid.clone(),
                network_type: bss_type,
                authentication: authentication.clone(),
                encryption,
                signal,
                is_saved,
                is_connected,
                auto_connect,
                phy_type,
                channel,
                frequency,
                link_speed,
            };

            wifi_map
                .entry((ssid, authentication))
                .and_modify(|info| {
                    if new_info.is_saved {
                        info.is_saved = true;
                    }
                    if new_info.is_connected {
                        info.is_connected = true;
                    }
                    if new_info.signal > info.signal {
                        info.signal = new_info.signal;
                    }
                })
                .or_insert(new_info);
        }

        wifi_list = wifi_map.into_values().collect();

        if !bss_list.is_null() {
            WlanFreeMemory(bss_list as *mut _);
        }
        WlanFreeMemory(available_network_list as *mut _);
        WlanCloseHandle(handle, None);
    }

    // Sort by connected first, then saved, then signal strength descending
    wifi_list.sort_by(|a, b| {
        if a.is_connected != b.is_connected {
            return b.is_connected.cmp(&a.is_connected);
        }
        if a.is_saved != b.is_saved {
            return b.is_saved.cmp(&a.is_saved);
        }
        b.signal.cmp(&a.signal)
    });

    Ok(wifi_list)
}

pub fn get_saved_profiles() -> Result<Vec<String>> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    let mut profiles = Vec::new();

    unsafe {
        let mut profile_list: *mut WLAN_PROFILE_INFO_LIST = std::ptr::null_mut();
        let result = WlanGetProfileList(handle, &guid, None, &mut profile_list);

        if result == ERROR_SUCCESS.0 {
            let num_items = (*profile_list).dwNumberOfItems;
            let items = std::slice::from_raw_parts(
                (*profile_list).ProfileInfo.as_ptr(),
                num_items as usize,
            );

            for item in items {
                let name = String::from_utf16_lossy(&item.strProfileName);
                // Trim null characters if any
                let name = name.trim_matches(char::from(0)).to_string();
                if !name.is_empty() {
                    profiles.push(name);
                }
            }
            WlanFreeMemory(profile_list as *mut _);
        }
        WlanCloseHandle(handle, None);
    }

    Ok(profiles)
}

fn escape_xml(s: &str) -> String {
    s.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace("\"", "&quot;")
        .replace("'", "&apos;")
}

pub fn connect_profile(ssid: &str) -> Result<()> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let ssid_wide: Vec<u16> = ssid.encode_utf16().chain(std::iter::once(0)).collect();
        let p_profile_name = PCWSTR(ssid_wide.as_ptr());

        let connection_params = WLAN_CONNECTION_PARAMETERS {
            wlanConnectionMode: wlan_connection_mode_profile,
            strProfile: p_profile_name,
            pDot11Ssid: std::ptr::null_mut(),
            pDesiredBssidList: std::ptr::null_mut(),
            dot11BssType: dot11_BSS_type_infrastructure,
            dwFlags: 0,
        };

        let result = WlanConnect(handle, &guid, &connection_params, None);
        WlanCloseHandle(handle, None);

        if result != ERROR_SUCCESS.0 {
            return Err(eyre!("Failed to connect: {}", result));
        }
    }
    Ok(())
}

fn create_profile_xml(
    ssid: &str,
    auth: &str,
    cipher: &str,
    password: Option<&str>,
    hidden: bool,
) -> String {
    let ssid_escaped = escape_xml(ssid);
    let non_broadcast = if hidden {
        "<nonBroadcast>true</nonBroadcast>"
    } else {
        ""
    };

    let (xml_auth, xml_cipher) = match auth {
        "WPA3-SAE" => ("WPA3SAE", "AES"),
        "WPA3" => ("WPA3", "AES"),
        "WPA2-PSK" => ("WPA2PSK", "AES"),
        "WPA2" => ("WPA2", "AES"),
        "WPA-PSK" => ("WPAPSK", if cipher == "AES" { "AES" } else { "TKIP" }),
        "WPA" => ("WPA", if cipher == "AES" { "AES" } else { "TKIP" }),
        "Shared" => ("shared", "WEP"),
        "Open" | "open" => ("open", "none"),
        _ => ("WPA2PSK", "AES"),
    };

    let final_cipher = if cipher == "GCMP" { "GCMP" } else { xml_cipher };

    let key_material_block = if let Some(pwd) = password {
        format!(
            r#"<sharedKey>
                <keyType>passPhrase</keyType>
                <protected>false</protected>
                <keyMaterial>{}</keyMaterial>
            </sharedKey>"#,
            escape_xml(pwd)
        )
    } else {
        String::new()
    };

    let connection_mode = "manual";

    format!(
        r#"<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>{}</name>
    <SSIDConfig>
        <SSID>
            <name>{}</name>
        </SSID>
        {}
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>{}</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>{}</authentication>
                <encryption>{}</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            {}
        </security>
    </MSM>
</WLANProfile>"#,
        ssid_escaped,
        ssid_escaped,
        non_broadcast,
        connection_mode,
        xml_auth,
        final_cipher,
        key_material_block
    )
}

pub fn connect_with_password(
    ssid: &str,
    password: &str,
    auth: &str,
    cipher: &str,
    hidden: bool,
) -> Result<()> {
    let profile_xml = create_profile_xml(ssid, auth, cipher, Some(password), hidden);

    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let xml_wide: Vec<u16> = profile_xml
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        let p_profile_xml = PCWSTR(xml_wide.as_ptr());

        let mut reason_code = 0;
        let result = WlanSetProfile(
            handle,
            &guid,
            0,
            p_profile_xml,
            None,
            true,
            None,
            &mut reason_code,
        );

        if result != ERROR_SUCCESS.0 {
            WlanCloseHandle(handle, None);
            return Err(eyre!(
                "Failed to add profile: {} (Reason: {})",
                result,
                reason_code
            ));
        }
        WlanCloseHandle(handle, None);
    }

    // Give the system a moment to register the profile
    std::thread::sleep(std::time::Duration::from_millis(1500));

    connect_profile(ssid)
}

pub fn connect_open(ssid: &str, hidden: bool) -> Result<()> {
    let profile_xml = create_profile_xml(ssid, "Open", "None", None, hidden);

    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let xml_wide: Vec<u16> = profile_xml
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        let p_profile_xml = PCWSTR(xml_wide.as_ptr());

        let mut reason_code = 0;
        let result = WlanSetProfile(
            handle,
            &guid,
            0,
            p_profile_xml,
            None,
            true,
            None,
            &mut reason_code,
        );

        if result != ERROR_SUCCESS.0 {
            WlanCloseHandle(handle, None);
            return Err(eyre!(
                "Failed to add open profile: {} (Reason: {})",
                result,
                reason_code
            ));
        }
        WlanCloseHandle(handle, None);
    }

    // Give the system a moment to register the profile
    std::thread::sleep(std::time::Duration::from_millis(1000));

    connect_profile(ssid)
}

pub fn forget_network(ssid: &str) -> Result<()> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let ssid_wide: Vec<u16> = ssid.encode_utf16().chain(std::iter::once(0)).collect();
        let p_profile_name = PCWSTR(ssid_wide.as_ptr());

        let result = WlanDeleteProfile(handle, &guid, p_profile_name, None);
        WlanCloseHandle(handle, None);

        if result != ERROR_SUCCESS.0 && result != ERROR_NOT_FOUND.0 {
            return Err(eyre!("Failed to forget network: {}", result));
        }
    }
    Ok(())
}

pub fn disconnect() -> Result<()> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let result = WlanDisconnect(handle, &guid, None);
        WlanCloseHandle(handle, None);

        if result != ERROR_SUCCESS.0 {
            return Err(eyre!("Failed to disconnect: {}", result));
        }
    }
    Ok(())
}

pub fn set_auto_connect(ssid: &str, enable: bool) -> Result<()> {
    let (handle, _) = get_wlan_handle()?;
    let guid = get_interface_guid(handle)?;

    unsafe {
        let profile_name_wide: Vec<u16> = ssid.encode_utf16().chain(std::iter::once(0)).collect();
        let p_profile_name = PCWSTR(profile_name_wide.as_ptr());
        let mut p_profile_xml = PWSTR::null();
        let mut flags = 0;

        let result = WlanGetProfile(
            handle,
            &guid,
            p_profile_name,
            None,
            &mut p_profile_xml,
            Some(&mut flags),
            None,
        );

        if result != ERROR_SUCCESS.0 || p_profile_xml.is_null() {
            WlanCloseHandle(handle, None);
            return Err(eyre!("Failed to get profile: {}", result));
        }

        let xml = p_profile_xml.to_string().unwrap_or_default();
        WlanFreeMemory(p_profile_xml.as_ptr() as *mut _);

        let new_mode = if enable { "auto" } else { "manual" };
        let new_xml = if xml.contains("<connectionMode>auto</connectionMode>") {
            xml.replace(
                "<connectionMode>auto</connectionMode>",
                &format!("<connectionMode>{}</connectionMode>", new_mode),
            )
        } else if xml.contains("<connectionMode>manual</connectionMode>") {
            xml.replace(
                "<connectionMode>manual</connectionMode>",
                &format!("<connectionMode>{}</connectionMode>", new_mode),
            )
        } else {
            WlanCloseHandle(handle, None);
            return Err(eyre!("Could not find connectionMode in profile XML"));
        };

        let xml_wide: Vec<u16> = new_xml.encode_utf16().chain(std::iter::once(0)).collect();
        let p_new_profile_xml = PCWSTR(xml_wide.as_ptr());

        let mut reason_code = 0;
        let result = WlanSetProfile(
            handle,
            &guid,
            0,
            p_new_profile_xml,
            None,
            true,
            None,
            &mut reason_code,
        );

        WlanCloseHandle(handle, None);

        if result != ERROR_SUCCESS.0 {
            return Err(eyre!(
                "Failed to set profile: {} (Reason: {})",
                result,
                reason_code
            ));
        }
    }
    Ok(())
}