luciola-cli 0.15.0

Command-line interface and diagnostic radar for the Luciola P2P discovery engine
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
//! `luciola-cli doctor` — single-command environment & network health check.
//!
//! Aggregates local interface intelligence, discovery port conflict probing,
//! STUN / RFC 5780 NAT probing, and WAN signaling `/health` probes into either
//! a concise human-readable report or a single JSON object.

use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use luciola::stun::{probe_nat_behavior, query_public_address};
use luciola_ip::{is_overlay_address, is_proxy_fake_ip, is_public_gua_ipv6};
use luciola_net::NetworkDetector;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};

/// Configuration for `luciola-cli doctor`.
pub struct DoctorOptions {
    pub discovery_port: u16,
    pub stun_servers: Vec<String>,
    pub probe_nat: bool,
    pub skip_stun: bool,
    pub signaling_urls: Vec<String>,
    pub timeout: Duration,
    pub json: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct HealthTarget {
    scheme: String,
    host: String,
    port: u16,
    path: String,
    display_url: String,
}

/// Normalize any `ws://`, `wss://`, `http://`, or `https://` signaling URL
/// into its `/health` HTTP(S) probe target.
fn normalize_health_target(raw: &str) -> Result<HealthTarget, String> {
    let trimmed = raw.trim();
    let (scheme, rest) = if let Some(r) = trimmed.strip_prefix("wss://") {
        ("https", r)
    } else if let Some(r) = trimmed.strip_prefix("ws://") {
        ("http", r)
    } else if let Some(r) = trimmed.strip_prefix("https://") {
        ("https", r)
    } else if let Some(r) = trimmed.strip_prefix("http://") {
        ("http", r)
    } else {
        return Err(format!(
            "unsupported signaling URL scheme (expected wss://, ws://, https://, or http://): {trimmed}"
        ));
    };

    let authority = rest.split('/').next().unwrap_or("").trim();
    if authority.is_empty() {
        return Err(format!("missing host in signaling URL: {trimmed}"));
    }

    let default_port = if scheme == "https" { 443 } else { 80 };
    let (host, port) = if let Some(bracket_rest) = authority.strip_prefix('[') {
        let end = bracket_rest
            .find(']')
            .ok_or_else(|| format!("unclosed IPv6 literal in URL: {trimmed}"))?;
        let h = &bracket_rest[..end];
        let after = &bracket_rest[end + 1..];
        let p = if let Some(port_str) = after.strip_prefix(':') {
            port_str
                .parse::<u16>()
                .map_err(|_| format!("invalid port in URL: {trimmed}"))?
        } else {
            default_port
        };
        (h.to_string(), p)
    } else if let Some((h, port_str)) = authority.rsplit_once(':') {
        let p = port_str
            .parse::<u16>()
            .map_err(|_| format!("invalid port in URL: {trimmed}"))?;
        (h.to_string(), p)
    } else {
        (authority.to_string(), default_port)
    };

    let host_header = if host.contains(':') {
        format!("[{host}]")
    } else {
        host.clone()
    };
    let display_url = if port == default_port {
        format!("{scheme}://{host_header}/health")
    } else {
        format!("{scheme}://{host_header}:{port}/health")
    };

    Ok(HealthTarget {
        scheme: scheme.to_string(),
        host,
        port,
        path: "/health".to_string(),
        display_url,
    })
}

async fn probe_udp_port(port: u16) -> serde_json::Value {
    let bind_addr = SocketAddr::from(([0, 0, 0, 0], port));
    match UdpSocket::bind(bind_addr).await {
        Ok(sock) => {
            let assigned = sock.local_addr().map(|a| a.port()).unwrap_or(port);
            serde_json::json!({
                "port": assigned,
                "status": "available",
                "ok": true,
            })
        }
        Err(e) => serde_json::json!({
            "port": port,
            "status": "in_use_or_blocked",
            "ok": false,
            "error": e.to_string(),
        }),
    }
}

async fn probe_signaling_health(raw_url: &str, timeout: Duration) -> serde_json::Value {
    let target = match normalize_health_target(raw_url) {
        Ok(t) => t,
        Err(err) => {
            return serde_json::json!({
                "input": raw_url,
                "ok": false,
                "error": err,
            });
        }
    };

    let start = Instant::now();
    let res = tokio::time::timeout(timeout, fetch_health(&target)).await;
    let rtt_ms = start.elapsed().as_millis() as u64;

    match res {
        Ok(Ok((status_code, body, server_epoch))) => {
            let local_epoch = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs() / 600)
                .unwrap_or(0);
            let epoch_drift = server_epoch.map(|se| se as i64 - local_epoch as i64);
            let parsed_json: Option<serde_json::Value> = serde_json::from_str(&body).ok();
            serde_json::json!({
                "input": raw_url,
                "health_url": target.display_url,
                "ok": (200..300).contains(&status_code),
                "status_code": status_code,
                "rtt_ms": rtt_ms,
                "server_epoch": server_epoch,
                "local_epoch": local_epoch,
                "epoch_drift": epoch_drift,
                "body": parsed_json.unwrap_or(serde_json::Value::String(body)),
            })
        }
        Ok(Err(err)) => serde_json::json!({
            "input": raw_url,
            "health_url": target.display_url,
            "ok": false,
            "rtt_ms": rtt_ms,
            "error": err,
        }),
        Err(_) => serde_json::json!({
            "input": raw_url,
            "health_url": target.display_url,
            "ok": false,
            "rtt_ms": rtt_ms,
            "error": format!("timed out after {} ms", timeout.as_millis()),
        }),
    }
}

async fn fetch_health(target: &HealthTarget) -> Result<(u16, String, Option<u64>), String> {
    let connect_host = if target.host.contains(':') {
        format!("[{}]:{}", target.host, target.port)
    } else {
        format!("{}:{}", target.host, target.port)
    };
    let host_header = if target.host.contains(':') {
        format!("[{}]:{}", target.host, target.port)
    } else if (target.scheme == "https" && target.port == 443)
        || (target.scheme == "http" && target.port == 80)
    {
        target.host.clone()
    } else {
        format!("{}:{}", target.host, target.port)
    };

    let req = format!(
        "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: luciola-doctor\r\nAccept: application/json\r\nConnection: close\r\n\r\n",
        target.path, host_header
    );

    let tcp = TcpStream::connect(&connect_host)
        .await
        .map_err(|e| format!("tcp connect failed: {e}"))?;

    let raw_response = if target.scheme == "https" {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let mut root_store = rustls::RootCertStore::empty();
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        let tls_cfg = rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();
        let connector = tokio_rustls::TlsConnector::from(Arc::new(tls_cfg));
        let server_name = rustls::pki_types::ServerName::try_from(target.host.clone())
            .map_err(|e| format!("invalid TLS server name '{}': {e}", target.host))?;
        let mut stream = connector
            .connect(server_name, tcp)
            .await
            .map_err(|e| format!("TLS handshake failed: {e}"))?;
        stream
            .write_all(req.as_bytes())
            .await
            .map_err(|e| format!("write failed: {e}"))?;
        let mut buf = Vec::with_capacity(4096);
        stream
            .take(64 * 1024)
            .read_to_end(&mut buf)
            .await
            .map_err(|e| format!("read failed: {e}"))?;
        buf
    } else {
        let mut stream = tcp;
        stream
            .write_all(req.as_bytes())
            .await
            .map_err(|e| format!("write failed: {e}"))?;
        let mut buf = Vec::with_capacity(4096);
        stream
            .take(64 * 1024)
            .read_to_end(&mut buf)
            .await
            .map_err(|e| format!("read failed: {e}"))?;
        buf
    };

    parse_http_health_response(&raw_response)
}

fn parse_http_health_response(raw: &[u8]) -> Result<(u16, String, Option<u64>), String> {
    let text = String::from_utf8_lossy(raw);
    let (head, body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| "malformed HTTP response (missing header terminator)".to_string())?;
    let mut lines = head.lines();
    let status_line = lines
        .next()
        .ok_or_else(|| "empty HTTP status line".to_string())?;
    let status_code = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|s| s.parse::<u16>().ok())
        .ok_or_else(|| format!("unparseable HTTP status line: {status_line}"))?;

    let mut epoch_from_header: Option<u64> = None;
    let mut is_chunked = false;
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            let key = k.trim();
            if key.eq_ignore_ascii_case("x-luciola-epoch") {
                epoch_from_header = v.trim().parse::<u64>().ok();
            } else if key.eq_ignore_ascii_case("transfer-encoding")
                && v.to_ascii_lowercase().contains("chunked")
            {
                is_chunked = true;
            }
        }
    }

    let decoded_body = if is_chunked {
        decode_chunked_body(body).unwrap_or_else(|| body.trim().to_string())
    } else {
        body.trim().to_string()
    };
    let epoch_from_body = serde_json::from_str::<serde_json::Value>(&decoded_body)
        .ok()
        .and_then(|v| v.get("epoch").and_then(|e| e.as_u64()));

    Ok((
        status_code,
        decoded_body,
        epoch_from_header.or(epoch_from_body),
    ))
}

fn decode_chunked_body(raw: &str) -> Option<String> {
    let mut rest = raw;
    let mut out = String::new();
    loop {
        let (size_line, after_size) = rest.split_once("\r\n")?;
        let hex_size = size_line.split(';').next()?.trim();
        let len = usize::from_str_radix(hex_size, 16).ok()?;
        if len == 0 {
            break;
        }
        if after_size.len() < len {
            return None;
        }
        out.push_str(&after_size[..len]);
        rest = after_size[len..].strip_prefix("\r\n")?;
    }
    Some(out.trim().to_string())
}

/// Run the full `luciola-cli doctor` check and print the report.
pub async fn run_doctor(opts: DoctorOptions) {
    let candidates = NetworkDetector::local_candidate_addresses();
    let broadcasts = NetworkDetector::subnet_broadcast_addresses();

    let mut lan_v4 = Vec::new();
    let mut global_v6 = Vec::new();
    let mut overlay_ips = Vec::new();
    let mut proxy_fake_ips = Vec::new();

    for ip_str in &candidates {
        if is_proxy_fake_ip(ip_str) {
            proxy_fake_ips.push(ip_str.clone());
        } else if is_overlay_address(ip_str) {
            overlay_ips.push(ip_str.clone());
        } else if let Ok(ip) = ip_str.parse::<IpAddr>() {
            match ip {
                IpAddr::V4(v4) => {
                    if !v4.is_loopback() {
                        lan_v4.push(ip_str.clone());
                    }
                }
                IpAddr::V6(_) => {
                    if is_public_gua_ipv6(ip_str) {
                        global_v6.push(ip_str.clone());
                    }
                }
            }
        }
    }

    let port_check = probe_udp_port(opts.discovery_port).await;

    let stun_report = if opts.skip_stun {
        serde_json::json!({ "skipped": true })
    } else {
        let stun_start = Instant::now();
        match UdpSocket::bind("0.0.0.0:0").await {
            Err(e) => serde_json::json!({
                "ok": false,
                "error": format!("failed to bind ephemeral UDP socket: {e}"),
            }),
            Ok(sock) => {
                let server_refs: Vec<&str> = opts.stun_servers.iter().map(String::as_str).collect();
                if opts.probe_nat {
                    match tokio::time::timeout(
                        opts.timeout,
                        probe_nat_behavior(&sock, &server_refs),
                    )
                    .await
                    {
                        Ok(Ok(nat)) => serde_json::json!({
                            "ok": true,
                            "mode": "rfc5780",
                            "local_addr": nat.local_addr.to_string(),
                            "mapped_addr": nat.reflexive_addr.map(|a| a.to_string()),
                            "rtt_ms": stun_start.elapsed().as_millis() as u64,
                            "mapping": format!("{:?}", nat.mapping),
                            "filtering": format!("{:?}", nat.filtering),
                            "classification": nat.classification(),
                        }),
                        Ok(Err(e)) => serde_json::json!({
                            "ok": false,
                            "mode": "rfc5780",
                            "error": e.to_string(),
                        }),
                        Err(_) => serde_json::json!({
                            "ok": false,
                            "mode": "rfc5780",
                            "error": format!("timed out after {} ms", opts.timeout.as_millis()),
                        }),
                    }
                } else {
                    match tokio::time::timeout(
                        opts.timeout,
                        query_public_address(&sock, &server_refs),
                    )
                    .await
                    {
                        Ok(Ok(mapped_addr)) => serde_json::json!({
                            "ok": true,
                            "mode": "binding",
                            "mapped_addr": mapped_addr.to_string(),
                            "rtt_ms": stun_start.elapsed().as_millis() as u64,
                        }),
                        Ok(Err(e)) => serde_json::json!({
                            "ok": false,
                            "mode": "binding",
                            "error": e.to_string(),
                        }),
                        Err(_) => serde_json::json!({
                            "ok": false,
                            "mode": "binding",
                            "error": format!("timed out after {} ms", opts.timeout.as_millis()),
                        }),
                    }
                }
            }
        }
    };

    let mut signaling_reports = Vec::with_capacity(opts.signaling_urls.len());
    for url in &opts.signaling_urls {
        signaling_reports.push(probe_signaling_health(url, opts.timeout).await);
    }

    let report = serde_json::json!({
        "network": {
            "candidate_count": candidates.len(),
            "lan_ipv4": lan_v4,
            "global_ipv6": global_v6,
            "overlay_ips": overlay_ips,
            "proxy_fake_ips": proxy_fake_ips,
            "subnet_broadcasts": broadcasts.iter().map(|b| b.to_string()).collect::<Vec<_>>(),
            "ipv6_ready": !global_v6.is_empty(),
        },
        "discovery_port": port_check,
        "stun": stun_report,
        "signaling": signaling_reports,
    });

    if opts.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&report).unwrap_or_else(|_| report.to_string())
        );
        return;
    }

    println!("========================================================");
    println!("              Luciola Environment Doctor                ");
    println!("========================================================");

    println!("\n[1] Network Interfaces & IP Intelligence");
    println!(
        "  LAN IPv4:       {}",
        if lan_v4.is_empty() {
            "(none)".to_string()
        } else {
            lan_v4.join(", ")
        }
    );
    println!(
        "  Global IPv6:    {}",
        if global_v6.is_empty() {
            "(none — IPv6 direct WAN unavailable)".to_string()
        } else {
            global_v6.join(", ")
        }
    );
    if !overlay_ips.is_empty() {
        println!("  Overlay IPs:    {}", overlay_ips.join(", "));
    }
    if !proxy_fake_ips.is_empty() {
        println!("  Proxy Fake-IPs: {}", proxy_fake_ips.join(", "));
    }

    println!("\n[2] Discovery UDP Port ({})", opts.discovery_port);
    if port_check["ok"].as_bool() == Some(true) {
        println!("  OK — UDP {} is available to bind", opts.discovery_port);
    } else {
        println!(
            "  WARN — UDP {} cannot be bound ({})",
            opts.discovery_port,
            port_check["error"].as_str().unwrap_or("already in use")
        );
    }

    println!("\n[3] STUN / NAT Traversal Probe");
    if opts.skip_stun {
        println!("  SKIPPED (--skip-stun)");
    } else if stun_report["ok"].as_bool() == Some(true) {
        println!(
            "  OK — mapped {} ({} ms)",
            stun_report["mapped_addr"].as_str().unwrap_or("?"),
            stun_report["rtt_ms"].as_u64().unwrap_or(0),
        );
        if let Some(cls) = stun_report["classification"].as_str() {
            println!(
                "       RFC 5780: {} (mapping={}, filtering={})",
                cls,
                stun_report["mapping"].as_str().unwrap_or("?"),
                stun_report["filtering"].as_str().unwrap_or("?"),
            );
        }
    } else {
        println!(
            "  FAIL — {}",
            stun_report["error"].as_str().unwrap_or("STUN probe failed")
        );
    }

    println!("\n[4] WAN Signaling /health Probes");
    if signaling_reports.is_empty() {
        println!("  (none configured — pass --signaling wss://<host>/ws to check)");
    } else {
        for item in &signaling_reports {
            let url = item["health_url"]
                .as_str()
                .or_else(|| item["input"].as_str())
                .unwrap_or("?");
            if item["ok"].as_bool() == Some(true) {
                let code = item["status_code"].as_u64().unwrap_or(0);
                let rtt = item["rtt_ms"].as_u64().unwrap_or(0);
                let drift = item["epoch_drift"]
                    .as_i64()
                    .map(|d| format!(", epoch_drift={d}"))
                    .unwrap_or_default();
                println!("  OK   {url} -> HTTP {code} ({rtt} ms{drift})");
            } else {
                println!(
                    "  FAIL {url} -> {}",
                    item["error"].as_str().unwrap_or("unreachable")
                );
            }
        }
    }
}

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

    #[test]
    fn normalize_health_target_maps_ws_and_wss_to_health() {
        let wss = normalize_health_target("wss://signal.example.com/ws").unwrap();
        assert_eq!(wss.scheme, "https");
        assert_eq!(wss.host, "signal.example.com");
        assert_eq!(wss.port, 443);
        assert_eq!(wss.display_url, "https://signal.example.com/health");

        let ws_custom = normalize_health_target("ws://127.0.0.1:8787/ws?foo=1").unwrap();
        assert_eq!(ws_custom.scheme, "http");
        assert_eq!(ws_custom.host, "127.0.0.1");
        assert_eq!(ws_custom.port, 8787);
        assert_eq!(ws_custom.display_url, "http://127.0.0.1:8787/health");

        assert!(normalize_health_target("ftp://invalid").is_err());
    }

    #[test]
    fn parse_http_health_response_decodes_chunked_transfer_encoding() {
        let json = r#"{"ok":true,"epoch":98765}"#;
        let raw = format!(
            "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: application/json\r\n\r\n{:x}\r\n{}\r\n0\r\n\r\n",
            json.len(),
            json
        );
        let (status, body, epoch) = parse_http_health_response(raw.as_bytes()).unwrap();
        assert_eq!(status, 200);
        assert_eq!(body, json);
        assert_eq!(epoch, Some(98765));
    }

    #[tokio::test]
    async fn probe_udp_port_zero_succeeds() {
        let res = probe_udp_port(0).await;
        assert_eq!(res["ok"].as_bool(), Some(true));
        assert!(res["port"].as_u64().unwrap_or(0) > 0);
    }

    #[tokio::test]
    async fn probe_signaling_health_reads_http_status_and_epoch() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            let _ = sock.read(&mut buf).await;
            let body = r#"{"ok":true,"epoch":123456,"version":"0.15.0"}"#;
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nx-luciola-epoch: 123456\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            let _ = sock.write_all(resp.as_bytes()).await;
        });

        let url = format!("ws://127.0.0.1:{}/ws", addr.port());
        let report = probe_signaling_health(&url, Duration::from_secs(3)).await;
        server.await.unwrap();

        assert_eq!(report["ok"].as_bool(), Some(true));
        assert_eq!(report["status_code"].as_u64(), Some(200));
        assert_eq!(report["server_epoch"].as_u64(), Some(123456));
    }
}