vortix 0.2.0

Terminal UI for WireGuard and OpenVPN with real-time telemetry and leak guarding
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
//! Background telemetry collection service.
//!
//! This module handles asynchronous collection of network telemetry data
//! including public IP address, ISP information, latency measurements,
//! DNS configuration, and IPv6 leak detection.
//!
//! The telemetry worker runs in a background thread and communicates
//! updates via an MPSC channel to the main application.

use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::Duration;

use crate::constants;
use crate::logger::LogLevel;
use serde::Deserialize;

/// Configuration subset needed by the telemetry worker thread.
#[derive(Debug, Clone)]
pub struct TelemetryConfig {
    /// Telemetry polling interval.
    pub poll_rate: Duration,
    /// HTTP API timeout in seconds.
    pub api_timeout: u64,
    /// Ping command timeout in seconds.
    pub ping_timeout: u64,
    /// Ping targets for latency measurement.
    pub ping_targets: Vec<String>,
    /// IPv6 leak detection endpoints.
    pub ipv6_check_apis: Vec<String>,
    /// Primary API endpoint for IP lookup.
    pub ip_api_primary: String,
    /// Fallback API endpoints for IP lookup.
    pub ip_api_fallbacks: Vec<String>,
}

impl From<&crate::config::AppConfig> for TelemetryConfig {
    fn from(config: &crate::config::AppConfig) -> Self {
        Self {
            poll_rate: Duration::from_secs(config.telemetry_poll_rate),
            api_timeout: config.api_timeout,
            ping_timeout: config.ping_timeout,
            ping_targets: config.ping_targets.clone(),
            ipv6_check_apis: config.ipv6_check_apis.clone(),
            ip_api_primary: config.ip_api_primary.clone(),
            ip_api_fallbacks: config.ip_api_fallbacks.clone(),
        }
    }
}

/// Telemetry update messages sent from background workers to the main application.
#[derive(Debug, Clone)]
pub enum TelemetryUpdate {
    /// Updated public IP address.
    PublicIp(String),
    /// Updated latency measurement in milliseconds.
    Latency(u64),
    /// Packet loss percentage (0.0-100.0).
    PacketLoss(f32),
    /// Jitter (latency standard deviation) in milliseconds.
    Jitter(u64),
    /// Updated ISP/organization name.
    Isp(String),
    /// Updated DNS server address.
    Dns(String),
    /// Updated physical location (City, Country).
    Location(String),
    /// IPv6 leak detection result (true = leak detected).
    Ipv6Leak(bool),
    /// Log message with level for production logging (uses centralized logger)
    Log(LogLevel, String),
}

/// Spawns a background telemetry worker that periodically fetches network information.
///
/// # Returns
///
/// A tuple of:
/// - `Receiver<TelemetryUpdate>` — yields telemetry data as it arrives
/// - `Sender<()>` — send on this to trigger an immediate refresh (e.g. after connect/disconnect)
///
/// # Panics
///
/// This function does not panic. All errors in background threads are silently handled.
#[must_use]
pub fn spawn_telemetry_worker(config: TelemetryConfig) -> (Receiver<TelemetryUpdate>, Sender<()>) {
    let (tx, rx) = mpsc::channel();
    let (nudge_tx, nudge_rx) = mpsc::channel::<()>();
    let config = std::sync::Arc::new(config);

    thread::spawn(move || loop {
        fetch_ip_and_isp(&tx, &config);
        fetch_latency(&tx, &config);
        fetch_security_info(&tx, &config);

        // Wait for the poll interval, but wake up immediately if nudged.
        // Drain any extra nudges that accumulated while we were fetching.
        let _ = nudge_rx.recv_timeout(config.poll_rate);
        while nudge_rx.try_recv().is_ok() {}
    });

    (rx, nudge_tx)
}

/// Fetches public IP address and ISP information with fallback APIs.
fn fetch_ip_and_isp(tx: &Sender<TelemetryUpdate>, cfg: &std::sync::Arc<TelemetryConfig>) {
    let tx_clone = tx.clone();
    let cfg = std::sync::Arc::clone(cfg);
    thread::spawn(move || {
        // Log start of fetch
        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Debug,
            "Starting IP/Location fetch...".to_string(),
        ));

        // Primary: ipinfo.io (provides IP + ISP + Location)
        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Debug,
            "Trying ipinfo.io (primary API with location data)...".to_string(),
        ));

        if let Some((ip, isp, loc)) = try_ipinfo_api(&tx_clone, &cfg) {
            let _ = tx_clone.send(TelemetryUpdate::Log(
                LogLevel::Info,
                format!(
                    "✓ ipinfo.io: IP={}, ISP={}, Location={}",
                    ip,
                    isp.as_ref().unwrap_or(&"Unknown".to_string()),
                    loc.as_ref().unwrap_or(&"Unknown".to_string())
                ),
            ));
            let _ = tx_clone.send(TelemetryUpdate::PublicIp(ip));
            if let Some(org) = isp {
                let _ = tx_clone.send(TelemetryUpdate::Isp(org));
            }
            if let Some(location) = loc {
                let _ = tx_clone.send(TelemetryUpdate::Location(location));
            }
            return;
        }

        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Warning,
            "ipinfo.io failed, trying fallback APIs (no location data)...".to_string(),
        ));

        // Fallback 1: ipify.org (IP only, very reliable)
        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Debug,
            "Trying ipify.org (fallback 1, IP only)...".to_string(),
        ));

        if let Some(ip) = try_ipify_api(&tx_clone, &cfg) {
            let _ = tx_clone.send(TelemetryUpdate::Log(
                LogLevel::Info,
                format!("✓ ipify.org: IP={ip} (no ISP/location)"),
            ));
            let _ = tx_clone.send(TelemetryUpdate::PublicIp(ip));
            let _ = tx_clone.send(TelemetryUpdate::Isp("Unknown".to_string()));
            let _ = tx_clone.send(TelemetryUpdate::Location("Unknown".to_string()));
            return;
        }

        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Warning,
            "ipify.org failed, trying icanhazip.com...".to_string(),
        ));

        // Fallback 2: icanhazip.com (IP only)
        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Debug,
            "Trying icanhazip.com (fallback 2)...".to_string(),
        ));

        if let Some(ip) = try_icanhazip_api(&tx_clone, &cfg) {
            let _ = tx_clone.send(TelemetryUpdate::Log(
                LogLevel::Info,
                format!("✓ icanhazip.com: IP={ip}"),
            ));
            let _ = tx_clone.send(TelemetryUpdate::PublicIp(ip));
            let _ = tx_clone.send(TelemetryUpdate::Isp("Unknown".to_string()));
            let _ = tx_clone.send(TelemetryUpdate::Location("Unknown".to_string()));
            return;
        }

        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Warning,
            "icanhazip.com failed, trying ifconfig.me (last resort)...".to_string(),
        ));

        // Fallback 3: ifconfig.me (IP only)
        if let Some(ip) = try_ifconfig_api(&tx_clone, &cfg) {
            let _ = tx_clone.send(TelemetryUpdate::Log(
                LogLevel::Info,
                format!("✓ ifconfig.me: IP={ip}"),
            ));
            let _ = tx_clone.send(TelemetryUpdate::PublicIp(ip));
            let _ = tx_clone.send(TelemetryUpdate::Isp("Unknown".to_string()));
            let _ = tx_clone.send(TelemetryUpdate::Location("Unknown".to_string()));
            return;
        }

        // All APIs failed - report error
        let _ = tx_clone.send(TelemetryUpdate::Log(
            LogLevel::Error,
            "✗ ALL IP APIs FAILED! Check: 1) Network 2) curl installed 3) VPN routing 4) Firewall"
                .to_string(),
        ));
        let _ = tx_clone.send(TelemetryUpdate::PublicIp("Unavailable".to_string()));
    });
}

/// Try ipinfo.io API (returns IP and optionally ISP + Location) with retry
fn try_ipinfo_api(
    tx: &Sender<TelemetryUpdate>,
    cfg: &TelemetryConfig,
) -> Option<(String, Option<String>, Option<String>)> {
    let timeout = cfg.api_timeout.to_string();

    for attempt in 0..constants::RETRY_ATTEMPTS {
        let output = std::process::Command::new("curl")
            .args(["-s", "--max-time", &timeout, &cfg.ip_api_primary])
            .output();

        if let Err(e) = &output {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Error,
                format!("ipinfo.io attempt {}: curl failed: {}", attempt + 1, e),
            ));
            if attempt == 0 {
                thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
            }
            continue;
        }

        let output = output.ok()?;

        if !output.status.success() {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Debug,
                format!(
                    "ipinfo.io attempt {}: HTTP error {}",
                    attempt + 1,
                    output.status
                ),
            ));
            if attempt == 0 {
                thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
            }
            continue;
        }

        let text = String::from_utf8_lossy(&output.stdout);
        let _ = tx.send(TelemetryUpdate::Log(
            LogLevel::Debug,
            format!(
                "ipinfo.io attempt {}: received {} bytes",
                attempt + 1,
                text.len()
            ),
        ));

        // Use proper JSON deserialization instead of manual string parsing
        if let Some(result) = parse_ip_api_response(&text) {
            return Some(result);
        }
        let _ = tx.send(TelemetryUpdate::Log(
            LogLevel::Warning,
            format!("ipinfo.io attempt {}: failed to parse JSON", attempt + 1),
        ));

        if attempt == 0 {
            thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
        }
    }

    let _ = tx.send(TelemetryUpdate::Log(
        LogLevel::Warning,
        format!(
            "ipinfo.io: all {} attempts exhausted",
            constants::RETRY_ATTEMPTS
        ),
    ));
    None
}

/// Validates if a string is a valid IPv4 address
fn is_valid_ipv4(ip: &str) -> bool {
    let parts: Vec<&str> = ip.split('.').collect();
    if parts.len() != 4 {
        return false;
    }

    // Verify each octet is a valid u8 (0-255) and doesn't have leading zeros
    parts.iter().all(|part| {
        // Reject empty parts or parts with leading zeros (except "0" itself)
        if part.is_empty() || (part.len() > 1 && part.starts_with('0')) {
            return false;
        }
        part.parse::<u8>().is_ok()
    })
}

/// Try ipify.org API (IP only, very reliable) with retry
fn try_ipify_api(tx: &Sender<TelemetryUpdate>, cfg: &TelemetryConfig) -> Option<String> {
    let timeout = cfg.api_timeout.to_string();
    let url = cfg
        .ip_api_fallbacks
        .first()
        .map_or("https://api.ipify.org", String::as_str);

    for attempt in 0..constants::RETRY_ATTEMPTS {
        let output = std::process::Command::new("curl")
            .args(["-s", "--max-time", &timeout, url])
            .output();

        if let Err(e) = &output {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Error,
                format!("ipify.org attempt {}: curl failed: {}", attempt + 1, e),
            ));
            if attempt == 0 {
                thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
            }
            continue;
        }

        let output = output.ok()?;

        if output.status.success() {
            let ip = String::from_utf8_lossy(&output.stdout).trim().to_string();

            if !ip.is_empty() && is_valid_ipv4(&ip) {
                return Some(ip);
            }
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Warning,
                format!(
                    "ipify.org attempt {}: invalid IP format: '{}'",
                    attempt + 1,
                    ip
                ),
            ));
        } else {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Debug,
                format!("ipify.org attempt {}: HTTP error", attempt + 1),
            ));
        }

        if attempt == 0 {
            thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
        }
    }

    let _ = tx.send(TelemetryUpdate::Log(
        LogLevel::Warning,
        "ipify.org: all attempts failed".to_string(),
    ));
    None
}

/// Try icanhazip.com API (IP only) with retry
fn try_icanhazip_api(tx: &Sender<TelemetryUpdate>, cfg: &TelemetryConfig) -> Option<String> {
    let timeout = cfg.api_timeout.to_string();
    let url = cfg
        .ip_api_fallbacks
        .get(1)
        .map_or("https://icanhazip.com", String::as_str);

    for attempt in 0..constants::RETRY_ATTEMPTS {
        let output = std::process::Command::new("curl")
            .args(["-s", "--max-time", &timeout, url])
            .output();

        if let Err(e) = &output {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Error,
                format!("icanhazip.com: curl failed: {e}"),
            ));
            continue;
        }

        let output = output.ok()?;

        if output.status.success() {
            let ip = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !ip.is_empty() {
                return Some(ip);
            }
        }

        if attempt == 0 {
            thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
        }
    }
    None
}

/// Try ifconfig.me API (IP only) with retry
fn try_ifconfig_api(tx: &Sender<TelemetryUpdate>, cfg: &TelemetryConfig) -> Option<String> {
    let timeout = cfg.api_timeout.to_string();
    let url = cfg
        .ip_api_fallbacks
        .get(2)
        .map_or("https://ifconfig.me/ip", String::as_str);

    for attempt in 0..constants::RETRY_ATTEMPTS {
        let output = std::process::Command::new("curl")
            .args(["-s", "--max-time", &timeout, url])
            .output();

        if let Err(e) = &output {
            let _ = tx.send(TelemetryUpdate::Log(
                LogLevel::Error,
                format!("ifconfig.me: curl failed: {e}"),
            ));
            continue;
        }

        let output = output.ok()?;

        if output.status.success() {
            let ip = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !ip.is_empty() {
                return Some(ip);
            }
        }

        if attempt == 0 {
            thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
        }
    }
    None
}

/// IP API response structure (supports both ipinfo.io and ip-api.com formats)
#[derive(Debug, Deserialize)]
struct IpApiResponse {
    #[serde(alias = "query")] // ip-api.com uses "query"
    ip: Option<String>,
    isp: Option<String>,
    org: Option<String>,
    city: Option<String>,
    country: Option<String>,
    status: Option<String>,
}

/// Parse IP API JSON response using proper JSON deserialization
/// This replaces the unsafe string-matching approach with proper parsing
/// that handles escaped quotes, unicode, and nested JSON correctly.
///
/// # Safety Benefits
/// - Handles escaped quotes: `"org": "Company \"Premium\" Networks"`
/// - Handles unicode: `"city": "São Paulo"` or `"city": "S\u00e3o Paulo"`
/// - Validates JSON structure
/// - Fails gracefully on malformed JSON
fn parse_ip_api_response(json: &str) -> Option<(String, Option<String>, Option<String>)> {
    let response: IpApiResponse = serde_json::from_str(json).ok()?;

    // Check if API returned success (ip-api.com includes status field)
    if let Some(status) = &response.status {
        if status != "success" {
            return None;
        }
    }

    let ip = response.ip?;

    // Validate that the returned IP is a valid IPv4 address
    if !is_valid_ipv4(&ip) {
        return None;
    }

    // Prefer "org" over "isp" as it's usually more specific (ipinfo.io uses "org")
    let isp = response.org.or(response.isp);

    // Build location string from city and country
    let location = match (response.city, response.country) {
        (Some(city), Some(country)) => Some(format!("{city}, {country}")),
        (Some(city), None) => Some(city),
        (None, Some(country)) => Some(country),
        (None, None) => None,
    };

    Some((ip, isp, location))
}

/// Legacy function kept for backward compatibility with tests
/// DEPRECATED: Use `parse_ip_api_response` instead
#[cfg(test)]
fn extract_json_string(json: &str, key: &str) -> Option<String> {
    // Use proper JSON parsing now
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    value.get(key)?.as_str().map(String::from)
}

/// Parsed ping output statistics.
#[derive(Debug, Default, PartialEq)]
pub struct PingStats {
    pub latency_ms: u64,
    pub packet_loss: f32,
    pub jitter_ms: u64,
}

/// Parse ping command output to extract latency, packet loss, and jitter.
///
/// Handles both macOS and Linux output formats:
/// - macOS: "round-trip min/avg/max/stddev = 1.234/5.678/9.012/3.456 ms"
/// - Linux: "rtt min/avg/max/mdev = 1.234/5.678/9.012/3.456 ms"
/// - macOS loss: "10 packets transmitted, 8 packets received, 20.0% packet loss"
/// - Linux loss: "10 packets transmitted, 8 received, 20% packet loss, time 9001ms"
#[must_use]
pub fn parse_ping_output(output: &str) -> PingStats {
    let mut stats = PingStats::default();

    for line in output.lines() {
        if line.contains("packet loss") {
            if let Some(loss_idx) = line.find("% packet loss") {
                let before_loss = &line[..loss_idx];
                if let Some(percent_str) = before_loss
                    .split([',', ' '])
                    .filter(|s| !s.is_empty())
                    .rfind(|s| s.chars().all(|c| c.is_ascii_digit() || c == '.'))
                {
                    if let Ok(val) = percent_str.parse::<f32>() {
                        stats.packet_loss = val;
                    }
                }
            }
        }

        // Handle both "min/avg/max/stddev" (Linux mdev) and "round-trip min/avg/max/stddev" (macOS)
        if line.contains("min/avg/max") {
            if let Some(eq_pos) = line.find('=') {
                let values_str = &line[eq_pos + 1..].trim();
                let values: Vec<&str> = values_str.split('/').collect();
                if values.len() >= 4 {
                    if let Ok(avg) = values[1].trim().parse::<f64>() {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                        {
                            stats.latency_ms = avg.max(0.0) as u64;
                        }
                    }
                    let stddev_str = values[3].trim_end_matches(" ms").trim();
                    if let Ok(stddev) = stddev_str.parse::<f64>() {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                        {
                            stats.jitter_ms = stddev.max(0.0) as u64;
                        }
                    }
                }
            }
        }
    }

    stats
}

/// Parse `/proc/net/dev` output (Linux) to get total bytes in/out.
#[allow(dead_code)]
///
/// Format: `iface: rx_bytes rx_packets rx_errs ... tx_bytes tx_packets tx_errs ...`
/// Returns (`total_bytes_in`, `total_bytes_out`) excluding loopback.
#[must_use]
pub fn parse_proc_net_dev(content: &str) -> (u64, u64) {
    let mut total_in: u64 = 0;
    let mut total_out: u64 = 0;

    for line in content.lines().skip(2) {
        // Skip 2 header lines
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        // Split on ':' to get interface name and stats
        let parts: Vec<&str> = line.splitn(2, ':').collect();
        if parts.len() != 2 {
            continue;
        }

        let iface = parts[0].trim();
        // Skip loopback
        if iface == "lo" {
            continue;
        }

        let stats: Vec<&str> = parts[1].split_whitespace().collect();
        // rx_bytes is index 0, tx_bytes is index 8
        if stats.len() >= 10 {
            if let Ok(rx) = stats[0].parse::<u64>() {
                total_in += rx;
            }
            if let Ok(tx) = stats[8].parse::<u64>() {
                total_out += tx;
            }
        }
    }

    (total_in, total_out)
}

/// Parse `ip addr show {iface}` output (Linux) to extract IP and MTU.
#[allow(dead_code)]
///
/// Returns (`ip_address`, `mtu`).
#[must_use]
pub fn parse_ip_addr_output(output: &str) -> (String, String) {
    let mut ip = String::new();
    let mut mtu = String::new();

    for line in output.lines() {
        let trimmed = line.trim();
        // MTU is on the first line: "4: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 ..."
        if trimmed.contains("mtu ") && mtu.is_empty() {
            if let Some(mtu_idx) = trimmed.find("mtu ") {
                let rest = &trimmed[mtu_idx + 4..];
                if let Some(val) = rest.split_whitespace().next() {
                    mtu = val.to_string();
                }
            }
        }
        // IP is on an "inet " line: "    inet 10.0.0.2/32 scope global wg0"
        if trimmed.starts_with("inet ") && ip.is_empty() {
            let parts: Vec<&str> = trimmed.split_whitespace().collect();
            if parts.len() >= 2 {
                // Strip CIDR notation if present
                ip = parts[1].split('/').next().unwrap_or("").to_string();
            }
        }
    }

    (ip, mtu)
}

/// Measures network latency, packet loss, and jitter by pinging reliable hosts.
fn fetch_latency(tx: &Sender<TelemetryUpdate>, cfg: &std::sync::Arc<TelemetryConfig>) {
    let tx_clone = tx.clone();
    let cfg = std::sync::Arc::clone(cfg);
    thread::spawn(move || {
        // macOS ping -W takes milliseconds; Linux ping -W takes seconds
        #[cfg(target_os = "macos")]
        let timeout = (cfg.ping_timeout * 1000).to_string();
        #[cfg(not(target_os = "macos"))]
        let timeout = cfg.ping_timeout.to_string();

        for target in &cfg.ping_targets {
            for attempt in 0..constants::RETRY_ATTEMPTS {
                if let Ok(output) = std::process::Command::new("ping")
                    .args(["-c", "3", "-i", "0.2", "-W", &timeout, target])
                    .output()
                {
                    if output.status.success() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        let stats = parse_ping_output(&stdout);

                        if stats.latency_ms > 0 {
                            let _ = tx_clone.send(TelemetryUpdate::Latency(stats.latency_ms));
                            let _ = tx_clone.send(TelemetryUpdate::PacketLoss(stats.packet_loss));
                            let _ = tx_clone.send(TelemetryUpdate::Jitter(stats.jitter_ms));
                            return;
                        }
                    }
                }

                if attempt == 0 {
                    thread::sleep(std::time::Duration::from_millis(constants::RETRY_DELAY_MS));
                }
            }
        }

        let _ = tx_clone.send(TelemetryUpdate::Latency(0));
        let _ = tx_clone.send(TelemetryUpdate::PacketLoss(100.0));
        let _ = tx_clone.send(TelemetryUpdate::Jitter(0));
    });
}

/// Fetches DNS configuration and checks for IPv6 leaks.
fn fetch_security_info(tx: &Sender<TelemetryUpdate>, cfg: &std::sync::Arc<TelemetryConfig>) {
    let tx_clone = tx.clone();
    let cfg = std::sync::Arc::clone(cfg);
    thread::spawn(move || {
        // Use platform-specific DNS resolution
        let dns = {
            #[cfg(target_os = "macos")]
            {
                use crate::platform::DnsResolver;
                crate::platform::macos::dns::MacDns::get_dns_server()
            }
            #[cfg(target_os = "linux")]
            {
                use crate::platform::DnsResolver;
                crate::platform::linux::dns::LinuxDns::get_dns_server()
            }
        };

        if let Some(dns_server) = dns {
            let _ = tx_clone.send(TelemetryUpdate::Dns(dns_server));
        }

        // Check for IPv6 connectivity with multiple endpoints (indicates potential leak when VPN active)
        let mut is_leaking = false;
        let ipv6_timeout = cfg.api_timeout.to_string();
        for endpoint in &cfg.ipv6_check_apis {
            let output6 = std::process::Command::new("curl")
                .args(["-6", "-s", "--max-time", &ipv6_timeout, endpoint])
                .output();
            if output6.map(|o| o.status.success()).unwrap_or(false) {
                is_leaking = true;
                break;
            }
        }
        let _ = tx_clone.send(TelemetryUpdate::Ipv6Leak(is_leaking));
    });
}

// Network stats delta calculation is now handled directly in App::poll_network_stats()
// using last_bytes_in / last_bytes_out fields on the App struct.

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

    #[test]
    fn test_extract_json_string_ip() {
        let json = r#"{"ip": "1.2.3.4", "org": "Test ISP"}"#;
        assert_eq!(extract_json_string(json, "ip"), Some("1.2.3.4".to_string()));
    }

    #[test]
    fn test_extract_json_string_org() {
        let json = r#"{"ip": "1.2.3.4", "org": "AS12345 Test Company"}"#;
        assert_eq!(
            extract_json_string(json, "org"),
            Some("AS12345 Test Company".to_string())
        );
    }

    #[test]
    fn test_extract_json_string_missing_key() {
        let json = r#"{"ip": "1.2.3.4"}"#;
        assert_eq!(extract_json_string(json, "org"), None);
    }

    #[test]
    fn test_extract_json_string_with_whitespace() {
        let json = r#"{"ip":   "1.2.3.4"}"#;
        assert_eq!(extract_json_string(json, "ip"), Some("1.2.3.4".to_string()));
    }

    #[test]
    fn test_extract_json_string_empty() {
        let json = r"{}";
        assert_eq!(extract_json_string(json, "ip"), None);
    }

    #[test]
    fn test_is_valid_ipv4_valid() {
        assert!(is_valid_ipv4("1.2.3.4"));
        assert!(is_valid_ipv4("192.168.1.1"));
        assert!(is_valid_ipv4("0.0.0.0"));
        assert!(is_valid_ipv4("255.255.255.255"));
    }

    #[test]
    fn test_is_valid_ipv4_invalid() {
        assert!(!is_valid_ipv4("999.999.999.999"));
        assert!(!is_valid_ipv4("256.1.1.1"));
        assert!(!is_valid_ipv4("1.2.3"));
        assert!(!is_valid_ipv4("1.2.3.4.5"));
        assert!(!is_valid_ipv4("not.an.ip.address"));
        assert!(!is_valid_ipv4(""));
    }

    // === Ping output parsing tests ===

    #[test]
    fn test_parse_ping_output_macos() {
        let output = "\
PING 1.1.1.1 (1.1.1.1): 56 data bytes
64 bytes from 1.1.1.1: icmp_seq=0 ttl=57 time=1.234 ms
64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=5.678 ms

--- 1.1.1.1 ping statistics ---
10 packets transmitted, 10 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 1.234/5.678/9.012/3.456 ms";

        let stats = parse_ping_output(output);
        assert_eq!(stats.latency_ms, 5); // avg 5.678 truncated to u64
        assert!((stats.packet_loss - 0.0).abs() < f32::EPSILON);
        assert_eq!(stats.jitter_ms, 3); // stddev 3.456 truncated to u64
    }

    #[test]
    fn test_parse_ping_output_linux() {
        let output = "\
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=1.23 ms
64 bytes from 1.1.1.1: icmp_seq=2 ttl=57 time=5.67 ms

--- 1.1.1.1 ping statistics ---
10 packets transmitted, 8 received, 20% packet loss, time 9001ms
rtt min/avg/max/mdev = 1.234/5.678/9.012/3.456 ms";

        let stats = parse_ping_output(output);
        assert_eq!(stats.latency_ms, 5);
        assert!((stats.packet_loss - 20.0).abs() < f32::EPSILON);
        assert_eq!(stats.jitter_ms, 3);
    }

    #[test]
    fn test_parse_ping_output_100_percent_loss() {
        let output = "\
--- 1.1.1.1 ping statistics ---
10 packets transmitted, 0 packets received, 100.0% packet loss";

        let stats = parse_ping_output(output);
        assert_eq!(stats.latency_ms, 0);
        assert!((stats.packet_loss - 100.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_parse_ping_output_empty() {
        let stats = parse_ping_output("");
        assert_eq!(stats, PingStats::default());
    }

    // === /proc/net/dev parsing tests ===

    #[test]
    fn test_parse_proc_net_dev() {
        let content = "\
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 1000       10    0    0    0     0          0         0     1000       10    0    0    0     0       0          0
  eth0: 5000       50    0    0    0     0          0         0     3000       30    0    0    0     0       0          0
  wg0:  2000       20    0    0    0     0          0         0     1500       15    0    0    0     0       0          0";

        let (bytes_in, bytes_out) = parse_proc_net_dev(content);
        // Should skip lo (1000/1000) and sum eth0 (5000/3000) + wg0 (2000/1500)
        assert_eq!(bytes_in, 7000);
        assert_eq!(bytes_out, 4500);
    }

    #[test]
    fn test_parse_proc_net_dev_only_loopback() {
        let content = "\
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 1000       10    0    0    0     0          0         0     1000       10    0    0    0     0       0          0";

        let (bytes_in, bytes_out) = parse_proc_net_dev(content);
        assert_eq!(bytes_in, 0);
        assert_eq!(bytes_out, 0);
    }

    #[test]
    fn test_parse_proc_net_dev_empty() {
        let (bytes_in, bytes_out) = parse_proc_net_dev("");
        assert_eq!(bytes_in, 0);
        assert_eq!(bytes_out, 0);
    }

    // === ip addr output parsing tests ===

    #[test]
    fn test_parse_ip_addr_output_wireguard() {
        let output = "\
4: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000
    link/none
    inet 10.0.0.2/32 scope global wg0
       valid_lft forever preferred_lft forever";

        let (ip, mtu) = parse_ip_addr_output(output);
        assert_eq!(ip, "10.0.0.2");
        assert_eq!(mtu, "1420");
    }

    #[test]
    fn test_parse_ip_addr_output_tun() {
        let output = "\
5: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
    link/none
    inet 10.8.0.6/24 brd 10.8.0.255 scope global tun0
       valid_lft forever preferred_lft forever";

        let (ip, mtu) = parse_ip_addr_output(output);
        assert_eq!(ip, "10.8.0.6");
        assert_eq!(mtu, "1500");
    }

    #[test]
    fn test_parse_ip_addr_output_empty() {
        let (ip, mtu) = parse_ip_addr_output("");
        assert!(ip.is_empty());
        assert!(mtu.is_empty());
    }

    // === DNS parsing tests ===

    #[test]
    fn test_parse_ip_api_response_full() {
        let json =
            r#"{"ip": "1.2.3.4", "org": "AS12345 Test ISP", "city": "Berlin", "country": "DE"}"#;
        let result = parse_ip_api_response(json);
        assert!(result.is_some());
        let (ip, isp, location) = result.unwrap();
        assert_eq!(ip, "1.2.3.4");
        assert_eq!(isp, Some("AS12345 Test ISP".to_string()));
        assert_eq!(location, Some("Berlin, DE".to_string()));
    }

    #[test]
    fn test_parse_ip_api_response_ip_only() {
        let json = r#"{"ip": "8.8.8.8"}"#;
        let result = parse_ip_api_response(json);
        assert!(result.is_some());
        let (ip, isp, location) = result.unwrap();
        assert_eq!(ip, "8.8.8.8");
        assert!(isp.is_none());
        assert!(location.is_none());
    }

    #[test]
    fn test_parse_ip_api_response_invalid() {
        assert!(parse_ip_api_response("not json").is_none());
        assert!(parse_ip_api_response("{}").is_none());
        assert!(parse_ip_api_response(r#"{"ip": "not_an_ip"}"#).is_none());
    }

    // === TelemetryConfig conversion ===

    #[test]
    fn test_telemetry_config_from_app_config() {
        let app_cfg = crate::config::AppConfig {
            tick_rate: 500, // not used by TelemetryConfig
            telemetry_poll_rate: 45,
            api_timeout: 8,
            ping_timeout: 3,
            connect_timeout: 30, // not used by TelemetryConfig
            ping_targets: vec!["4.4.4.4".to_string()],
            ipv6_check_apis: vec!["https://v6.example.com".to_string()],
            ip_api_primary: "https://custom.api/json".to_string(),
            ip_api_fallbacks: vec![
                "https://fb1.example.com".to_string(),
                "https://fb2.example.com".to_string(),
            ],
            max_log_entries: 1000,
            log_level: "info".to_string(),
            log_rotation_size: 5 * 1024 * 1024,
            log_retention_days: 7,
            disconnect_timeout: 30,
            openvpn_verbosity: "3".to_string(),
            connect_max_retries: 3,
            connect_retry_base_delay_secs: 2,
            connect_retry_max_delay_secs: 300,
            auto_reconnect: true,
            auto_reconnect_delay_secs: 3,
        };

        let tel_cfg = TelemetryConfig::from(&app_cfg);

        assert_eq!(tel_cfg.poll_rate, Duration::from_secs(45));
        assert_eq!(tel_cfg.api_timeout, 8);
        assert_eq!(tel_cfg.ping_timeout, 3);
        assert_eq!(tel_cfg.ping_targets, vec!["4.4.4.4"]);
        assert_eq!(tel_cfg.ipv6_check_apis, vec!["https://v6.example.com"]);
        assert_eq!(tel_cfg.ip_api_primary, "https://custom.api/json");
        assert_eq!(tel_cfg.ip_api_fallbacks.len(), 2);
        assert_eq!(tel_cfg.ip_api_fallbacks[0], "https://fb1.example.com");
        assert_eq!(tel_cfg.ip_api_fallbacks[1], "https://fb2.example.com");
    }

    #[test]
    fn test_telemetry_config_from_defaults() {
        let defaults = crate::config::AppConfig::default();
        let tel_cfg = TelemetryConfig::from(&defaults);

        assert_eq!(tel_cfg.poll_rate, Duration::from_secs(30));
        assert_eq!(tel_cfg.api_timeout, 5);
        assert_eq!(tel_cfg.ping_timeout, 2);
        assert_eq!(tel_cfg.ping_targets.len(), 4);
        assert_eq!(tel_cfg.ipv6_check_apis.len(), 3);
        assert_eq!(tel_cfg.ip_api_fallbacks.len(), 3);
    }
}