kftray-portforward 0.30.2

KFtray library with port forwarding logic
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
use std::net::IpAddr;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::process::Command;
use std::str::FromStr;

use anyhow::{
    Result,
    anyhow,
};
use tracing::{
    debug,
    error,
    info,
    warn,
};

#[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn execute_command(cmd: &str, args: &[&str]) -> anyhow::Result<()> {
    let status = Command::new(cmd)
        .args(args)
        .status()
        .map_err(|e| anyhow!("failed to spawn `{}`: {}", cmd, e))?;
    if status.success() {
        Ok(())
    } else {
        Err(anyhow!("`{}` exited with {}", cmd, status))
    }
}

pub fn is_loopback_address(addr: &str) -> bool {
    if let Ok(ip) = IpAddr::from_str(addr) {
        return ip.is_loopback();
    }
    false
}

pub fn is_default_loopback_address(addr: &str) -> bool {
    addr == "127.0.0.1"
}

pub fn is_custom_loopback_address(addr: &str) -> bool {
    is_loopback_address(addr) && !is_default_loopback_address(addr)
}

pub async fn ensure_loopback_address(addr: &str) -> Result<()> {
    if !is_loopback_address(addr) {
        return Ok(());
    }

    if addr == "127.0.0.1" {
        return Ok(());
    }

    debug!("Ensuring loopback address {} is configured", addr);

    if is_address_accessible(addr).await {
        debug!("Loopback address {} is already accessible", addr);
        return Ok(());
    }

    info!("Configuring loopback address: {}", addr);

    let helper_result = configure_loopback_with_helper(addr).await;

    if helper_result.is_ok() {
        debug!(
            "Successfully configured loopback address via helper: {}",
            addr
        );

        if is_address_accessible(addr).await {
            debug!("Verified loopback address {} is now accessible", addr);
            return Ok(());
        } else {
            warn!(
                "Helper claimed success but address {} is still not accessible",
                addr
            );
        }
    } else if let Err(e) = helper_result {
        warn!("Failed to configure loopback address with helper: {}", e);
    }

    debug!("Falling back to traditional methods for configuring loopback address");

    #[cfg(target_os = "macos")]
    {
        info!("Using macOS-specific method for loopback configuration");
        configure_loopback_macos(addr)?;
    }

    #[cfg(target_os = "linux")]
    {
        info!("Using Linux-specific method for loopback configuration");
        configure_loopback_linux(addr)?;
    }

    #[cfg(target_os = "windows")]
    {
        info!("Using Windows-specific method for loopback configuration");
        configure_loopback_windows(addr)?;
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows",)))]
    {
        return Err(anyhow!(
            "Loopback address configuration not supported on this platform"
        ));
    }

    if is_address_accessible(addr).await {
        debug!("Successfully configured loopback address: {}", addr);
        Ok(())
    } else {
        Err(anyhow!(
            "Failed to configure loopback address {} after all attempts",
            addr
        ))
    }
}

async fn configure_loopback_with_helper(addr: &str) -> Result<()> {
    debug!("Checking if helper is available");

    let app_id = "com.kftray.app".to_string();

    let socket_path = kftray_helper::communication::get_default_socket_path()?;

    if !kftray_helper::client::socket_comm::is_socket_available(&socket_path) {
        return Err(anyhow!("Helper service is not available"));
    }

    debug!("Helper service is available, proceeding with configuration");

    let command = kftray_helper::messages::RequestCommand::Network(
        kftray_helper::messages::NetworkCommand::Add {
            address: addr.to_string(),
        },
    );

    match kftray_helper::client::socket_comm::send_request(&socket_path, &app_id, command) {
        Ok(response) => match response.result {
            kftray_helper::messages::RequestResult::Success => {
                debug!(
                    "Successfully configured loopback address with helper: {}",
                    addr
                );
                Ok(())
            }
            kftray_helper::messages::RequestResult::Error(e) => {
                error!("Helper failed to add loopback address: {}", e);
                Err(anyhow!(
                    "Helper failed to configure loopback address: {}",
                    e
                ))
            }
            other => Err(anyhow!(
                "Unexpected helper response to loopback add: {:?}",
                other
            )),
        },
        Err(e) => {
            error!("Helper failed to add loopback address: {}", e);
            Err(anyhow!(
                "Helper failed to configure loopback address: {}",
                e
            ))
        }
    }
}

async fn remove_loopback_with_helper(addr: &str) -> Result<()> {
    debug!("Checking if helper is available for address removal");

    let app_id = "com.kftray.app".to_string();

    let socket_path = kftray_helper::communication::get_default_socket_path()?;

    if !kftray_helper::client::socket_comm::is_socket_available(&socket_path) {
        return Err(anyhow!("Helper service is not available"));
    }

    debug!("Helper service is available, proceeding with address removal");

    let command = kftray_helper::messages::RequestCommand::Network(
        kftray_helper::messages::NetworkCommand::Remove {
            address: addr.to_string(),
        },
    );

    match kftray_helper::client::socket_comm::send_request(&socket_path, &app_id, command) {
        Ok(response) => match response.result {
            kftray_helper::messages::RequestResult::Success => {
                debug!(
                    "Successfully removed loopback address with helper: {}",
                    addr
                );
                Ok(())
            }
            kftray_helper::messages::RequestResult::Error(e) => {
                error!("Helper failed to remove loopback address: {}", e);
                Err(anyhow!("Helper failed to remove loopback address: {}", e))
            }
            other => Err(anyhow!(
                "Unexpected helper response to loopback removal: {:?}",
                other
            )),
        },
        Err(e) => {
            error!("Helper failed to remove loopback address: {}", e);
            Err(anyhow!("Helper failed to remove loopback address: {}", e))
        }
    }
}

/// Whether an error from `remove_loopback_with_helper` means the helper
/// itself is unreachable (not installed, not running, or its socket gone)
/// rather than the removal request itself failing.
///
/// Only unreachability is unsatisfiable without a privilege change: any
/// other failure (a serialization error, a broken pipe mid-request, a
/// malformed response) is a transient IPC problem that a retry can still
/// resolve once the alias is confirmed present.
#[cfg(any(target_os = "macos", all(test, unix)))]
fn helper_is_unavailable(error: &str) -> bool {
    error.contains("Helper service is not available")
        || error.contains("Connection refused")
        || error.contains("No such file or directory")
}

/// Outcome of attempting to release a loopback alias.
///
/// A caller cannot treat every non-removal the same way: one where the
/// helper is missing or `sudo` needs a password will not resolve itself by
/// retrying, so it must be surfaced once and recorded as unsatisfiable here,
/// rather than kept as a cleanup that is retried forever.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoopbackRelease {
    /// The alias was configured and has been removed.
    Released,
    /// Nothing was configured for this address; there was nothing to remove.
    AlreadyAbsent,
    /// The alias is still configured, but this process cannot escalate the
    /// privileges removal needs right now (helper unavailable, `sudo -n`
    /// needs a password). Retrying without a privilege change will not help.
    PrivilegeUnavailable(String),
    /// The alias is still configured and removal failed for a reason a later
    /// attempt might resolve.
    Failed(String),
}

/// Remove loopback address. Only uses helper service - skips osascript fallback
/// to avoid blocking on user interaction during stop operations.
pub async fn remove_loopback_address(addr: &str) -> Result<LoopbackRelease> {
    if !is_loopback_address(addr) {
        return Ok(LoopbackRelease::AlreadyAbsent);
    }

    if is_default_loopback_address(addr) || addr == "::1" {
        return Ok(LoopbackRelease::AlreadyAbsent);
    }
    #[cfg(target_os = "windows")]
    {
        // kftray never actually configures a Windows interface alias for a
        // loopback address (`configure_loopback_windows` is a no-op), and
        // the whole 127.0.0.0/8 range is bindable without one, so there is
        // nothing for the helper to remove and no reason to call it.
        if let Ok(IpAddr::V4(v4)) = addr.parse::<IpAddr>()
            && v4.octets()[0] == 127
        {
            debug!(
                "No interface alias is ever configured for {addr} on Windows; nothing to remove"
            );

            return Ok(LoopbackRelease::AlreadyAbsent);
        }
    }

    debug!("Removing loopback address: {}", addr);

    // Try helper service first (non-blocking)
    let helper_result = remove_loopback_with_helper(addr).await;

    if helper_result.is_ok() {
        debug!("Successfully removed loopback address via helper: {}", addr);
        return Ok(LoopbackRelease::Released);
    } else if let Err(e) = &helper_result {
        warn!("Failed to remove loopback address with helper: {}", e);
    }

    // Skip osascript fallback on macOS - it blocks waiting for user interaction
    // which can hang stop operations indefinitely.
    #[cfg(target_os = "macos")]
    {
        // An alias that is not there needs no removal. Without this check a
        // machine with no helper reports every stop as leaving an alias
        // behind, and the cleanup record that failure keeps would block
        // deleting the configuration for the rest of the session.
        //
        // Only a successful query proves absence: a failed one must stay an
        // error, or a broken `ifconfig` would read as confirmed cleanup.
        if !macos_alias_exists(addr)? {
            debug!("No loopback alias for {addr}; nothing to remove");

            return Ok(LoopbackRelease::AlreadyAbsent);
        }

        // The helper is the only non-blocking removal path on macOS, so its
        // unreachability is a privilege problem: nothing this process
        // retries on its own will make it reachable. Any other helper
        // failure (a timed-out request, a malformed response) is not a
        // privilege problem and is worth retrying once the alias is
        // confirmed present.
        let message = helper_result.unwrap_err().to_string();
        if helper_is_unavailable(&message) {
            warn!(
                "Could not remove loopback address {} via helper, and the osascript fallback would block.",
                addr
            );

            return Ok(LoopbackRelease::PrivilegeUnavailable(format!(
                "Loopback address {addr} is still configured: removing it needs the helper"
            )));
        }

        warn!("Helper failed to remove loopback address {addr}: {message}");

        Ok(LoopbackRelease::Failed(format!(
            "Loopback address {addr} is still configured: {message}"
        )))
    }

    #[cfg(target_os = "linux")]
    {
        info!("Using Linux-specific method for loopback removal");
        // Linux routes the whole 127.0.0.0/8 range to the loopback interface,
        // so an address can be bound without ever adding an explicit alias.
        // Deleting one that was never added is not a cleanup failure.
        // Only a successful query proves the alias is absent. A failed one
        // (for example `ip` missing from the process PATH) must not be read as
        // confirmed cleanup.
        if !linux_alias_exists(addr)? {
            debug!("No explicit loopback alias for {addr}; nothing to remove");

            return Ok(LoopbackRelease::AlreadyAbsent);
        }
        if unsafe { libc::geteuid() } == 0 {
            match execute_command("ip", &["addr", "del", addr, "dev", "lo"]) {
                Ok(()) => Ok(LoopbackRelease::Released),
                Err(e) => Ok(resolve_failed_removal(e.to_string(), || {
                    linux_alias_exists(addr)
                })),
            }
        } else {
            // `-n` keeps this non-interactive: a password prompt during a stop
            // would block until someone typed into a terminal that may not even
            // be attached. `sudo -n` failing outright, rather than prompting,
            // means this process cannot escalate without one, so it is a
            // privilege problem rather than a failure a retry can fix.
            Ok(classify_sudo_ip_addr_del(
                addr,
                run_sudo_ip_addr_del(addr),
                || linux_alias_exists(addr),
            ))
        }
    }

    #[cfg(target_os = "windows")]
    {
        info!("Using Windows-specific method for loopback removal");
        // Only a non-127.0.0.0/8 address (the IPv6 loopback) reaches here:
        // 127.0.0.0/8 addresses already returned above without calling the
        // helper. Unlike that range, this address is not guaranteed
        // reachable without an alias, but a helper failure is still not
        // proof that new privileges are needed, so it is worth retrying.
        Ok(LoopbackRelease::Failed(format!(
            "Loopback address {addr} is still configured: removing it needs the helper"
        )))
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows",)))]
    {
        Ok(LoopbackRelease::Failed(
            "Loopback address removal not supported on this platform".to_string(),
        ))
    }
}

pub async fn is_address_accessible(addr: &str) -> bool {
    let socket_addr = format!("{addr}:0");
    tokio::net::TcpListener::bind(socket_addr).await.is_ok()
}

#[cfg(target_os = "macos")]
fn configure_loopback_macos(addr: &str) -> Result<()> {
    let check_output = Command::new("ifconfig")
        .args(["lo0"])
        .output()
        .map_err(|e| anyhow!("Failed to check loopback interface: {}", e))?;

    let output_str = String::from_utf8_lossy(&check_output.stdout);
    if output_str.contains(addr) {
        debug!("Loopback address {} is already configured on lo0", addr);
        return Ok(());
    }

    debug!("Trying to add loopback address alias with osascript");
    let script =
        format!(r#"do shell script "ifconfig lo0 alias {addr}" with administrator privileges"#);

    let result = Command::new("osascript").args(["-e", &script]).output();

    match result {
        Ok(output) if output.status.success() => {
            debug!("Successfully added loopback address using osascript with admin privileges");
            Ok(())
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            debug!(
                "osascript command failed with exit code {}: {}",
                output.status.code().unwrap_or(-1),
                stderr
            );

            if stderr.contains("User cancelled")
                || stderr.contains("user cancelled")
                || stderr.contains("cancelled")
                || stderr.contains("User canceled")
                || stderr.contains("canceled")
                || stderr.contains("(-128)")
                || output.status.code() == Some(1)
            {
                Err(anyhow!("User cancelled loopback address configuration"))
            } else {
                Err(anyhow!("Failed to configure loopback address: {}", stderr))
            }
        }
        Err(e) => Err(anyhow!("Failed to execute osascript: {}", e)),
    }
}

/// Whether `addr` is configured on the loopback interface.
///
/// Matched field by field rather than by substring: `127.0.0.1` is a substring
/// of `127.0.0.10`, and treating one as the other would either skip a removal
/// that is owed or report one that is not.
#[cfg(target_os = "macos")]
fn macos_alias_exists(addr: &str) -> Result<bool> {
    let output = Command::new("/sbin/ifconfig")
        .arg("lo0")
        .output()
        .map_err(|error| anyhow!("Failed to query loopback aliases: {error}"))?;
    if !output.status.success() {
        return Err(anyhow!(
            "Failed to query loopback aliases: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }

    Ok(ifconfig_lists_address(
        &String::from_utf8_lossy(&output.stdout),
        addr,
    ))
}

/// Whether `ifconfig` output lists `addr` as a configured address.
#[cfg(target_os = "macos")]
fn ifconfig_lists_address(output: &str, addr: &str) -> bool {
    output
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            matches!(fields.next(), Some("inet" | "inet6")).then(|| fields.next())?
        })
        .any(|configured| configured == addr)
}

#[cfg(target_os = "linux")]
fn linux_alias_exists(addr: &str) -> Result<bool> {
    let output = Command::new("ip")
        .args(["-o", "addr", "show", "dev", "lo"])
        .output()
        .map_err(|error| anyhow!("Failed to query loopback aliases: {error}"))?;
    if !output.status.success() {
        return Err(anyhow!(
            "Failed to query loopback aliases: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }

    Ok(String::from_utf8_lossy(&output.stdout)
        .split_whitespace()
        .any(|field| field == addr || field.starts_with(&format!("{addr}/"))))
}

/// Whether a failed `sudo -n <cmd>` exited because sudo itself refused the
/// credentials (no cached ticket and no way to prompt for a password)
/// rather than the wrapped command failing on its own after sudo let it
/// run.
///
/// Kept independent of any process spawning so the classification itself is
/// exercised directly: `sudo -n` reports a refusal as exit code 1 with a
/// message on stderr, either the exact "a password is required" text or one
/// beginning with sudo's own "sudo:" prefix (missing tty, unknown user,
/// etc). Any other failure is `ip` (or another wrapped command) failing on
/// its own, which a retry might resolve without new privileges.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn is_sudo_privilege_refusal(exit_code: Option<i32>, stderr: &str) -> bool {
    exit_code == Some(1) && (stderr.contains("a password is required") || stderr.contains("sudo:"))
}

#[cfg(target_os = "linux")]
fn run_sudo_ip_addr_del(addr: &str) -> std::io::Result<std::process::Output> {
    Command::new("sudo")
        .args(["-n", "ip", "addr", "del", addr, "dev", "lo"])
        .output()
}

/// Classifies the outcome of a non-root `sudo -n ip addr del`.
///
/// Every non-root failure used to map to [`LoopbackRelease::PrivilegeUnavailable`],
/// which also swallowed `ip addr del` itself failing (missing binary, device
/// busy, and the like) or a `sudo`/`ip` exec failure other than a real
/// credentials refusal. Only a genuine sudo refusal is unsatisfiable without
/// new privileges; anything else is worth retrying, so it is reported as
/// [`LoopbackRelease::Failed`] once `alias_present` confirms the alias is
/// still there.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn classify_sudo_ip_addr_del(
    addr: &str, spawned: std::io::Result<std::process::Output>,
    alias_present: impl FnOnce() -> Result<bool>,
) -> LoopbackRelease {
    let output = match spawned {
        Ok(output) => output,
        Err(error) => {
            return LoopbackRelease::PrivilegeUnavailable(format!(
                "Removing loopback address {addr} needs a privileged `ip addr del`, and `sudo` \
                 could not be executed: {error}"
            ));
        }
    };
    if output.status.success() {
        return LoopbackRelease::Released;
    }
    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    if is_sudo_privilege_refusal(output.status.code(), &stderr) {
        return LoopbackRelease::PrivilegeUnavailable(format!(
            "Removing loopback address {addr} needs a privileged `ip addr del`, and `sudo -n` \
             refused it (a password may be required): {stderr}"
        ));
    }
    resolve_failed_removal(
        format!("`sudo -n ip addr del` failed: {stderr}"),
        alias_present,
    )
}

/// Re-queries `alias_present` after a failed removal attempt rather than
/// assuming the alias is still there: the alias can already be gone despite
/// the reported failure, and recording `Failed` for that would keep a
/// cleanup that already succeeded stuck retrying forever.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn resolve_failed_removal(
    error_message: String, alias_present: impl FnOnce() -> Result<bool>,
) -> LoopbackRelease {
    match alias_present() {
        Ok(false) => LoopbackRelease::Released,
        _ => LoopbackRelease::Failed(error_message),
    }
}

#[cfg(target_os = "linux")]
fn configure_loopback_linux(addr: &str) -> Result<()> {
    if unsafe { libc::geteuid() } == 0 {
        execute_command("ip", &["addr", "add", addr, "dev", "lo"])?;

        execute_command(
            "ip",
            &["route", "add", &format!("{}/32", addr), "dev", "lo"],
        )
        .or_else(|e| {
            debug!("Route might already exist: {}", e);
            Ok(())
        })
    } else {
        execute_command("/usr/bin/pkexec", &["ip", "addr", "add", addr, "dev", "lo"])
            .or_else(|_| execute_command("sudo", &["ip", "addr", "add", addr, "dev", "lo"]))?;

        execute_command(
            "/usr/bin/pkexec",
            &["ip", "route", "add", &format!("{}/32", addr), "dev", "lo"],
        )
        .or_else(|_| {
            execute_command(
                "sudo",
                &["ip", "route", "add", &format!("{}/32", addr), "dev", "lo"],
            )
        })
        .or_else(|e| {
            debug!("Route might already exist: {}", e);
            Ok(())
        })
    }
}

#[cfg(target_os = "windows")]
fn configure_loopback_windows(_addr: &str) -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_loopback_address() {
        assert!(is_loopback_address("127.0.0.1"));
        assert!(is_loopback_address("127.0.0.2"));
        assert!(is_loopback_address("127.255.255.255"));
        assert!(!is_loopback_address("192.168.1.1"));
        assert!(!is_loopback_address("10.0.0.1"));
        assert!(!is_loopback_address("invalid-ip"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_configured_alias_is_matched_whole() {
        let output = "lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384\n\
                      \toptions=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP>\n\
                      \tinet 127.0.0.1 netmask 0xff000000\n\
                      \tinet6 ::1 prefixlen 128\n\
                      \tinet 127.0.0.10 netmask 0xff000000\n";

        assert!(ifconfig_lists_address(output, "127.0.0.1"));
        assert!(ifconfig_lists_address(output, "127.0.0.10"));
        assert!(ifconfig_lists_address(output, "::1"));
        // A prefix of a configured address is not configured itself, and
        // treating it as present would keep reporting a removal that is owed.
        assert!(!ifconfig_lists_address(output, "127.0.0.2"));
        assert!(!ifconfig_lists_address(output, "127.0.0."));
        // Only the address field counts, never the flags or netmask columns.
        assert!(!ifconfig_lists_address(output, "0xff000000"));
    }

    #[test]
    fn test_is_default_loopback_address() {
        assert!(is_default_loopback_address("127.0.0.1"));
        assert!(!is_default_loopback_address("127.0.0.2"));
        assert!(!is_default_loopback_address("127.255.255.255"));
        assert!(!is_default_loopback_address("192.168.1.1"));
        assert!(!is_default_loopback_address("10.0.0.1"));
        assert!(!is_default_loopback_address("invalid-ip"));
    }

    #[test]
    fn test_is_custom_loopback_address() {
        assert!(!is_custom_loopback_address("127.0.0.1"));
        assert!(is_custom_loopback_address("127.0.0.2"));
        assert!(is_custom_loopback_address("127.0.0.5"));
        assert!(is_custom_loopback_address("127.255.255.255"));
        assert!(!is_custom_loopback_address("192.168.1.1"));
        assert!(!is_custom_loopback_address("10.0.0.1"));
        assert!(!is_custom_loopback_address("invalid-ip"));
    }

    #[tokio::test]
    async fn test_ensure_loopback_address_non_loopback() {
        assert!(ensure_loopback_address("192.168.1.1").await.is_ok());
    }

    #[tokio::test]
    async fn test_ensure_loopback_address_default() {
        assert!(ensure_loopback_address("127.0.0.1").await.is_ok());
    }

    #[tokio::test]
    async fn test_remove_loopback_address_non_loopback_is_already_absent() {
        assert_eq!(
            remove_loopback_address("192.168.1.1").await.unwrap(),
            LoopbackRelease::AlreadyAbsent
        );
    }

    #[tokio::test]
    async fn test_remove_loopback_address_default_is_already_absent() {
        assert_eq!(
            remove_loopback_address("127.0.0.1").await.unwrap(),
            LoopbackRelease::AlreadyAbsent
        );
    }

    #[tokio::test]
    async fn test_remove_loopback_address_ipv6_default_is_already_absent() {
        assert_eq!(
            remove_loopback_address("::1").await.unwrap(),
            LoopbackRelease::AlreadyAbsent
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_non_interactive_sudo_password_refusal_is_a_privilege_refusal() {
        assert!(is_sudo_privilege_refusal(
            Some(1),
            "sudo: a password is required"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn any_sudo_prefixed_stderr_at_exit_one_is_a_privilege_refusal() {
        // Covers sudo's own diagnostics beyond the password message: no tty,
        // unknown user, policy denial, and the like all start with "sudo:".
        assert!(is_sudo_privilege_refusal(
            Some(1),
            "sudo: no tty present and no askpass program specified"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn ip_failing_on_its_own_is_not_a_privilege_refusal() {
        // `ip` ran (sudo let it through) and failed for a reason a retry
        // might resolve, not because sudo withheld credentials.
        assert!(!is_sudo_privilege_refusal(
            Some(1),
            "Cannot find device \"lo\""
        ));
        assert!(!is_sudo_privilege_refusal(Some(2), ""));
    }

    #[cfg(unix)]
    fn exited(code: i32, stderr: &[u8]) -> std::process::Output {
        use std::os::unix::process::ExitStatusExt;

        std::process::Output {
            status: std::process::ExitStatus::from_raw(code << 8),
            stdout: Vec::new(),
            stderr: stderr.to_vec(),
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_successful_sudo_ip_addr_del_is_released() {
        assert_eq!(
            classify_sudo_ip_addr_del("127.0.0.5", Ok(exited(0, b"")), || Ok(true)),
            LoopbackRelease::Released
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_sudo_credentials_refusal_is_privilege_unavailable() {
        let output = exited(1, b"sudo: a password is required\n");
        match classify_sudo_ip_addr_del("127.0.0.5", Ok(output), || Ok(true)) {
            LoopbackRelease::PrivilegeUnavailable(message) => {
                assert!(message.contains("a password may be required"));
            }
            other => panic!("expected PrivilegeUnavailable, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn sudo_failing_to_execute_is_privilege_unavailable() {
        let error = std::io::Error::new(std::io::ErrorKind::NotFound, "sudo not found");
        match classify_sudo_ip_addr_del("127.0.0.5", Err(error), || Ok(true)) {
            LoopbackRelease::PrivilegeUnavailable(message) => {
                assert!(message.contains("could not be executed"));
            }
            other => panic!("expected PrivilegeUnavailable, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn ip_addr_del_failing_with_the_alias_still_present_is_reported_as_failed() {
        let output = exited(2, b"RTNETLINK answers: Operation not permitted");
        match classify_sudo_ip_addr_del("127.0.0.253", Ok(output), || Ok(true)) {
            LoopbackRelease::Failed(message) => {
                assert!(message.contains("sudo -n ip addr del"));
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn ip_addr_del_failing_after_the_alias_is_gone_is_released() {
        let output = exited(2, b"RTNETLINK answers: Cannot assign requested address");
        assert_eq!(
            classify_sudo_ip_addr_del("127.0.0.253", Ok(output), || Ok(false)),
            LoopbackRelease::Released
        );
    }

    #[cfg(unix)]
    #[test]
    fn an_unanswered_alias_query_keeps_the_release_retryable() {
        let output = exited(2, b"RTNETLINK answers: Operation not permitted");
        assert!(matches!(
            classify_sudo_ip_addr_del("127.0.0.253", Ok(output), || { Err(anyhow!("ip missing")) }),
            LoopbackRelease::Failed(_)
        ));
    }

    #[cfg(unix)]
    #[test]
    fn resolve_failed_removal_reports_released_when_alias_already_gone() {
        assert_eq!(
            resolve_failed_removal(
                "`ip addr del` exited with exit status: 1".to_string(),
                || { Ok(false) }
            ),
            LoopbackRelease::Released
        );
    }

    #[cfg(unix)]
    #[test]
    fn resolve_failed_removal_keeps_failure_when_alias_still_present() {
        assert!(matches!(
            resolve_failed_removal(
                "`ip addr del` exited with exit status: 1".to_string(),
                || { Ok(true) }
            ),
            LoopbackRelease::Failed(_)
        ));
    }

    #[cfg(unix)]
    #[test]
    fn helper_unavailable_from_the_availability_check_is_privilege_unavailable() {
        assert!(helper_is_unavailable("Helper service is not available"));
    }

    #[cfg(unix)]
    #[test]
    fn a_refused_connection_is_privilege_unavailable() {
        assert!(helper_is_unavailable(
            "Helper failed to remove loopback address: Communication error: Failed to connect to Unix socket: Connection refused (os error 61)"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn a_missing_socket_file_is_privilege_unavailable() {
        assert!(helper_is_unavailable(
            "Helper failed to remove loopback address: Communication error: Failed to connect to Unix socket: No such file or directory (os error 2)"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn a_transient_write_failure_is_not_privilege_unavailable() {
        assert!(!helper_is_unavailable(
            "Helper failed to remove loopback address: Communication error: Failed to write request: Broken pipe (os error 32)"
        ));
    }

    #[cfg(target_os = "linux")]
    fn serve_one_helper_reply(
        reply: fn(String) -> kftray_helper::messages::HelperResponse,
    ) -> (
        tempfile::TempDir,
        kftray_commons::test_utils::EnvVarGuard,
        std::thread::JoinHandle<()>,
    ) {
        use std::io::Write;
        use std::os::unix::net::UnixListener;

        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("kftray-helper.sock");
        let listener = UnixListener::bind(&socket).unwrap();
        let env =
            kftray_commons::test_utils::EnvVarGuard::set("SOCKET_PATH", socket.to_str().unwrap());

        let server = std::thread::spawn(move || {
            drop(listener.accept().unwrap());
            let (mut stream, _) = listener.accept().unwrap();
            let request: kftray_helper::messages::HelperRequest =
                serde_json::Deserializer::from_reader(&mut stream)
                    .into_iter()
                    .next()
                    .unwrap()
                    .unwrap();
            let response = reply(request.request_id);
            stream
                .write_all(&serde_json::to_vec(&response).unwrap())
                .unwrap();
        });

        (dir, env, server)
    }

    #[cfg(target_os = "linux")]
    fn helper_error(request_id: String) -> kftray_helper::messages::HelperResponse {
        kftray_helper::messages::HelperResponse::error(
            request_id,
            "Error: RTNETLINK answers: Operation not permitted",
        )
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_helper_error_reply_to_remove_is_not_a_removal() {
        let (_dir, _env, server) = serve_one_helper_reply(helper_error);

        let outcome = remove_loopback_with_helper("127.0.0.200").await;
        server.join().unwrap();

        let error = outcome.unwrap_err().to_string();
        assert!(error.contains("Operation not permitted"), "{error}");
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_helper_error_reply_to_add_is_not_a_configuration() {
        let (_dir, _env, server) = serve_one_helper_reply(helper_error);

        let outcome = configure_loopback_with_helper("127.0.0.200").await;
        server.join().unwrap();

        let error = outcome.unwrap_err().to_string();
        assert!(error.contains("Operation not permitted"), "{error}");
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_helper_success_reply_to_remove_is_a_removal() {
        let (_dir, _env, server) =
            serve_one_helper_reply(kftray_helper::messages::HelperResponse::success);

        let outcome = remove_loopback_with_helper("127.0.0.200").await;
        server.join().unwrap();

        assert!(outcome.is_ok(), "{outcome:?}");
    }

    #[cfg(target_os = "windows")]
    #[tokio::test]
    async fn a_127_range_address_is_already_absent_without_calling_the_helper() {
        // kftray never configures a Windows interface alias for a loopback
        // address (`configure_loopback_windows` is a no-op), and the whole
        // 127.0.0.0/8 range binds without one, so there is nothing to
        // remove and no reason to call the helper.
        assert_eq!(
            remove_loopback_address("127.0.0.9").await.unwrap(),
            LoopbackRelease::AlreadyAbsent
        );
    }

    #[cfg(target_os = "windows")]
    #[tokio::test]
    async fn ipv6_default_loopback_is_already_absent_without_calling_the_helper() {
        // `::1` is the IPv6 loopback that is always accessible without an
        // interface alias, so it must be treated the same as 127.0.0.1
        // rather than falling through to the helper-required Windows branch.
        assert_eq!(
            remove_loopback_address("::1").await.unwrap(),
            LoopbackRelease::AlreadyAbsent
        );
    }

    #[cfg(test)]
    #[cfg(target_os = "windows")]
    #[tokio::test]
    async fn test_configure_loopback_windows() {
        assert!(configure_loopback_windows("127.0.0.2").is_ok());
    }
}