cloudflare-speed-cli 1.0.0

CLI tool for Cloudflare speed testing with TUI interface
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
use crate::cli::Cli;
use crate::model::RunResult;
use serde_json::Value;
use std::process::Command;

/// Path to the legacy macOS airport CLI. Apple removed this binary in macOS 14.4 (Sonoma),
/// so it is only useful as a fallback on macOS 13 and earlier.
#[cfg(target_os = "macos")]
const MACOS_AIRPORT_PATH: &str =
    "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport";

/// Extracted metadata fields from Cloudflare response
#[derive(Debug, Clone, Default)]
pub struct ExtractedMetadata {
    pub ip: Option<String>,
    pub colo: Option<String>,
    pub asn: Option<String>,
    pub as_org: Option<String>,
}

/// Extract metadata fields (IP, colo, ASN, org) from Cloudflare JSON response.
/// Handles multiple possible field names for compatibility.
pub fn extract_metadata(meta: &Value) -> ExtractedMetadata {
    let ip = ["clientIp", "ip", "clientIP"]
        .iter()
        .find_map(|key| meta.get(*key))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let colo = meta
        .get("colo")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let asn = meta.get("asn").and_then(|v| {
        v.as_i64()
            .map(|n| n.to_string())
            .or_else(|| v.as_str().map(|s| s.to_string()))
    });

    let as_org = ["asOrganization", "asnOrg"]
        .iter()
        .find_map(|key| meta.get(*key))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    ExtractedMetadata {
        ip,
        colo,
        asn,
        as_org,
    }
}

/// Network information gathered from the system
pub struct NetworkInfo {
    pub interface_name: Option<String>,
    pub network_name: Option<String>,
    pub is_wireless: Option<bool>,
    pub interface_mac: Option<String>,
    pub local_ipv4: Option<String>,
    pub local_ipv6: Option<String>,
}

/// Gather network interface information based on CLI arguments
pub fn gather_network_info(args: &Cli) -> NetworkInfo {
    // Determine the interface: explicit --interface, reverse-lookup from --source, or auto-detect
    let resolved_iface = args.interface.clone().or_else(|| {
        args.source.as_ref().and_then(|ip| {
            crate::engine::network_bind::get_interface_for_ip(ip)
        })
    });

    let (interface_name, network_name, is_wireless, interface_mac) =
        if let Some(ref iface) = resolved_iface {
            let is_wireless = check_if_wireless(iface);
            let network_name = if is_wireless.unwrap_or(false) {
                get_wireless_ssid(iface)
            } else {
                None
            };
            let mac = get_interface_mac(iface);
            (Some(iface.clone()), network_name, is_wireless, mac)
        } else {
            // Auto-detect default interface
            gather_default_network_info()
        };

    let (local_ipv4, local_ipv6) = get_interface_ips(interface_name.as_deref());

    NetworkInfo {
        interface_name,
        network_name,
        is_wireless,
        interface_mac,
        local_ipv4,
        local_ipv6,
    }
}

/// Gather network interface information for the default interface
fn gather_default_network_info() -> (Option<String>, Option<String>, Option<bool>, Option<String>) {
    // Get default interface by trying to connect to a remote address
    let interface_name = get_default_interface();

    if let Some(ref iface) = interface_name {
        let is_wireless = check_if_wireless(iface);
        let network_name = if is_wireless.unwrap_or(false) {
            get_wireless_ssid(iface)
        } else {
            None
        };
        let mac = get_interface_mac(iface);
        (Some(iface.clone()), network_name, is_wireless, mac)
    } else {
        (None, None, None, None)
    }
}

/// Get the default network interface name
#[cfg(target_os = "linux")]
fn get_default_interface() -> Option<String> {
    // Try to get interface from default route
    if let Ok(output) = Command::new("ip")
        .args(&["route", "show", "default"])
        .output()
    {
        if let Ok(output_str) = String::from_utf8(output.stdout) {
            // Look for "dev <interface>" in the output
            for line in output_str.lines() {
                if let Some(dev_pos) = line.find("dev ") {
                    let rest = &line[dev_pos + 4..];
                    return if let Some(space_pos) = rest.find(' ') {
                        Some(rest[..space_pos].to_string())
                    } else {
                        Some(rest.to_string())
                    };
                }
            }
        }
    }

    // Fallback: try to find first non-loopback interface
    if let Ok(entries) = std::fs::read_dir("/sys/class/net") {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str != "lo" && !name_str.starts_with("docker") && !name_str.starts_with("br-") {
                return Some(name_str.to_string());
            }
        }
    }

    None
}

#[cfg(target_os = "macos")]
fn get_default_interface() -> Option<String> {
    // Use `route -n get default` to find the default interface
    if let Ok(output) = Command::new("route").args(&["-n", "get", "default"]).output() {
        if output.status.success() {
            if let Ok(output_str) = String::from_utf8(output.stdout) {
                for line in output_str.lines() {
                    let line = line.trim();
                    if line.starts_with("interface:") {
                        if let Some(iface) = line.splitn(2, ':').nth(1) {
                            let iface = iface.trim().to_string();
                            if !iface.is_empty() {
                                return Some(iface);
                            }
                        }
                    }
                }
            }
        }
    }

    // Fallback: first non-loopback, non-tunnel interface from the system
    if let Ok(interfaces) = if_addrs::get_if_addrs() {
        for iface in interfaces {
            if iface.is_loopback() {
                continue;
            }
            // Skip common virtual/tunnel interfaces
            if iface.name.starts_with("utun")
                || iface.name.starts_with("awdl")
                || iface.name.starts_with("llw")
                || iface.name.starts_with("bridge")
            {
                continue;
            }
            return Some(iface.name);
        }
    }

    None
}

#[cfg(target_os = "windows")]
fn get_default_interface() -> Option<String> {
    let output = Command::new("powershell")
        .args(&[
            "-NoProfile",
            "-Command",
            "Get-NetRoute -DestinationPrefix 0.0.0.0/0 | Sort-Object RouteMetric | Select-Object -First 1 -ExpandProperty InterfaceAlias",
        ])
        .output()
        .ok()?;

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

    // Fallback: Get any active adapter
    let output = Command::new("powershell")
        .args(&[
            "-NoProfile",
            "-Command",
            "Get-NetAdapter | Where-Object Status -eq 'Up' | Select-Object -First 1 -ExpandProperty InterfaceAlias",
        ])
        .output()
        .ok()?;

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

    None
}

/// Check if interface is wireless
#[cfg(target_os = "linux")]
fn check_if_wireless(iface: &str) -> Option<bool> {
    // Check if /sys/class/net/<iface>/wireless exists
    let wireless_path = format!("/sys/class/net/{}/wireless", iface);
    Some(std::path::Path::new(&wireless_path).exists())
}

#[cfg(target_os = "macos")]
fn check_if_wireless(iface: &str) -> Option<bool> {
    // Parse `networksetup -listallhardwareports` to check if the interface is Wi-Fi
    let output = Command::new("networksetup")
        .arg("-listallhardwareports")
        .output()
        .ok()?;
    let output_str = String::from_utf8(output.stdout).ok()?;

    let mut is_wifi_section = false;
    for line in output_str.lines() {
        let line = line.trim();
        if line.starts_with("Hardware Port:") {
            let port_name = line.splitn(2, ':').nth(1).unwrap_or("").trim().to_lowercase();
            is_wifi_section = port_name.contains("wi-fi") || port_name.contains("airport");
        } else if line.starts_with("Device:") {
            if let Some(device) = line.splitn(2, ':').nth(1) {
                if device.trim() == iface {
                    return Some(is_wifi_section);
                }
            }
        }
    }

    // Interface wasn't listed (e.g. utun/VPN); we don't know, so return None
    None
}

#[cfg(target_os = "windows")]
fn check_if_wireless(iface: &str) -> Option<bool> {
    let output = Command::new("netsh")
        .args(&["wlan", "show", "interfaces"])
        .output()
        .ok()?;

    if output.status.success() {
        let output_str = String::from_utf8_lossy(&output.stdout);
        return Some(output_str.contains(iface));
    }
    Some(false)
}

/// Get wireless SSID for an interface
#[cfg(target_os = "linux")]
fn get_wireless_ssid(iface: &str) -> Option<String> {
    // Try iwgetid first (most reliable)
    if let Ok(output) = Command::new("iwgetid").arg("-r").arg(iface).output() {
        if let Ok(ssid) = String::from_utf8(output.stdout) {
            let ssid = ssid.trim().to_string();
            if !ssid.is_empty() {
                return Some(ssid);
            }
        }
    }

    // Fallback: try iw command
    if let Ok(output) = Command::new("iw").args(&["dev", iface, "info"]).output() {
        if let Ok(output_str) = String::from_utf8(output.stdout) {
            for line in output_str.lines() {
                if line.trim().starts_with("ssid ") {
                    let ssid = line.trim().strip_prefix("ssid ").unwrap_or("").trim();
                    if !ssid.is_empty() {
                        return Some(ssid.to_string());
                    }
                }
            }
        }
    }

    None
}

#[cfg(target_os = "macos")]
fn get_wireless_ssid(iface: &str) -> Option<String> {
    // Try `networksetup -getairportnetwork <iface>` (public API)
    if let Ok(output) = Command::new("networksetup")
        .args(&["-getairportnetwork", iface])
        .output()
    {
        if let Ok(output_str) = String::from_utf8(output.stdout) {
            let output_str = output_str.trim();
            if let Some(ssid) = output_str.strip_prefix("Current Wi-Fi Network:") {
                let ssid = ssid.trim().to_string();
                if !ssid.is_empty() {
                    return Some(ssid);
                }
            }
        }
    }

    // Fallback: try the legacy airport command (removed in macOS 14.4, but works on older versions)
    if let Ok(output) = Command::new(MACOS_AIRPORT_PATH).arg("-I").output() {
        if let Ok(output_str) = String::from_utf8(output.stdout) {
            for line in output_str.lines() {
                let line = line.trim();
                if line.starts_with("SSID:") {
                    if let Some(ssid) = line.splitn(2, ':').nth(1) {
                        let ssid = ssid.trim().to_string();
                        if !ssid.is_empty() {
                            return Some(ssid);
                        }
                    }
                }
            }
        }
    }

    None
}

#[cfg(target_os = "windows")]
fn get_wireless_ssid(iface: &str) -> Option<String> {
    let output = Command::new("netsh")
        .args(&["wlan", "show", "interfaces"])
        .output()
        .ok()?;

    if output.status.success() {
        let output_str = String::from_utf8_lossy(&output.stdout);
        let mut current_iface = String::new();
        for line in output_str.lines() {
            let line = line.trim();
            if line.starts_with("Name") {
                if let Some(name) = line.split(':').nth(1) {
                    current_iface = name.trim().to_string();
                }
            }
            if current_iface == iface && line.starts_with("SSID") {
                if let Some(ssid) = line.split(':').nth(1) {
                    let ssid = ssid.trim().to_string();
                    if !ssid.is_empty() {
                        return Some(ssid);
                    }
                }
            }
        }
    }
    None
}

/// Get MAC address of interface
#[cfg(target_os = "linux")]
fn get_interface_mac(iface: &str) -> Option<String> {
    let mac_path = format!("/sys/class/net/{}/address", iface);
    std::fs::read_to_string(mac_path)
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

#[cfg(target_os = "macos")]
fn get_interface_mac(iface: &str) -> Option<String> {
    // Use `ifconfig <iface>` and parse the `ether` line
    if let Ok(output) = Command::new("ifconfig").arg(iface).output() {
        if output.status.success() {
            if let Ok(output_str) = String::from_utf8(output.stdout) {
                for line in output_str.lines() {
                    let line = line.trim();
                    if line.starts_with("ether ") {
                        if let Some(mac) = line.split_whitespace().nth(1) {
                            return Some(mac.to_string());
                        }
                    }
                }
            }
        }
    }
    None
}

#[cfg(target_os = "windows")]
fn get_interface_mac(iface: &str) -> Option<String> {
    let output = Command::new("powershell")
        .args(&[
            "-NoProfile",
            "-Command",
            &format!("(Get-NetAdapter -Name '{}').LinkLayerAddress", iface),
        ])
        .output()
        .ok()?;

    if output.status.success() {
        let mac = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !mac.is_empty() {
            return Some(mac.replace('-', ":"));
        }
    }
    None
}

/// Get IPv4 and IPv6 addresses for an interface
fn get_interface_ips(interface_name: Option<&str>) -> (Option<String>, Option<String>) {
    let Ok(interfaces) = if_addrs::get_if_addrs() else {
        return (None, None);
    };

    let mut ipv4: Option<String> = None;
    let mut ipv6: Option<String> = None;

    for iface in interfaces {
        // If interface name is specified, only look at that interface
        if let Some(target) = interface_name {
            if iface.name != target {
                continue;
            }
        }

        // Skip loopback
        if iface.is_loopback() {
            continue;
        }

        match iface.addr {
            if_addrs::IfAddr::V4(ref addr) => {
                if ipv4.is_none() {
                    ipv4 = Some(addr.ip.to_string());
                }
            }
            if_addrs::IfAddr::V6(ref addr) => {
                // Skip link-local addresses (fe80::)
                let ip = addr.ip;
                if !ip.is_loopback() && !is_link_local_v6(&ip) {
                    if ipv6.is_none() {
                        ipv6 = Some(ip.to_string());
                    }
                }
            }
        }
    }

    (ipv4, ipv6)
}

/// Check if an IPv6 address is link-local (fe80::/10)
fn is_link_local_v6(ip: &std::net::Ipv6Addr) -> bool {
    let segments = ip.segments();
    (segments[0] & 0xffc0) == 0xfe80
}

/// Enrich RunResult with network information and metadata
pub fn enrich_result(result: &RunResult, network_info: &NetworkInfo) -> RunResult {
    let mut enriched = result.clone();

    // Add network interface information
    enriched.interface_name = network_info.interface_name.clone();
    enriched.network_name = network_info.network_name.clone();
    enriched.is_wireless = network_info.is_wireless;
    enriched.interface_mac = network_info.interface_mac.clone();
    enriched.local_ipv4 = network_info.local_ipv4.clone();
    enriched.local_ipv6 = network_info.local_ipv6.clone();

    // Extract metadata from result.meta if available
    if let Some(meta) = result.meta.as_ref() {
        let extracted = extract_metadata(meta);
        enriched.ip = extracted.ip;
        enriched.colo = extracted.colo;
        enriched.asn = extracted.asn;
        enriched.as_org = extracted.as_org;
    }

    // Server should already be set from RunResult.server, but preserve it
    // (no need to override)

    enriched
}