ftr 0.7.0

A fast, parallel ICMP traceroute with ASN lookup, reverse DNS, and ISP detection
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
//! ftr - Fast TraceRoute: A parallel ICMP traceroute implementation with ASN lookup.
//!
//! This is the command-line interface for the ftr library.

#![allow(clippy::single_match)]
#![allow(clippy::nonminimal_bool)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::needless_pass_by_value)]

use clap::Parser;
use ftr::{ProbeProtocol, SocketMode, TracerouteConfigBuilder, TracerouteError, TracerouteResult};
use std::net::IpAddr;
use std::time::{Duration, Instant};

/// Get the version string for ftr
fn get_version() -> &'static str {
    if cfg!(debug_assertions) {
        concat!(env!("CARGO_PKG_VERSION"), "-UNRELEASED")
    } else {
        env!("CARGO_PKG_VERSION")
    }
}

/// Command-line arguments for the traceroute tool.
#[derive(Parser, Debug)]
#[clap(author, version, about = "Fast parallel ICMP traceroute with ASN lookup", long_about = None)]
struct Args {
    /// Target hostname or IP address
    host: String,

    /// Starting TTL value
    #[clap(short, long, default_value_t = 1)]
    start_ttl: u8,

    /// Maximum number of hops
    #[clap(short = 'm', long, default_value_t = 30)]
    max_hops: u8,

    /// Timeout for individual probes in milliseconds
    #[clap(long, default_value_t = 1000)]
    probe_timeout_ms: u64,

    /// Interval between launching probes in milliseconds (applies to both inter-TTL and inter-query delays)
    #[clap(short = 'i', long, default_value_t = 0)]
    send_launch_interval_ms: u64,

    /// Overall timeout for the traceroute in milliseconds
    #[clap(short = 'W', long, default_value_t = 3000)]
    overall_timeout_ms: u64,

    /// Disable ASN lookup and segment classification
    #[clap(long)]
    no_enrich: bool,

    /// Disable reverse DNS lookups
    #[clap(long)]
    no_rdns: bool,

    /// Protocol to use (icmp, udp)
    #[clap(long, value_enum)]
    protocol: Option<ProtocolArg>,

    /// Socket mode to use (raw, dgram)
    #[clap(long, value_enum)]
    socket_mode: Option<SocketModeArg>,

    /// Number of probes per hop
    #[clap(short = 'q', long, default_value_t = 1)]
    queries: u8,

    /// Output results in JSON format
    #[clap(long)]
    json: bool,

    /// Enable verbose output (use -vv for debug timestamps)
    #[clap(short, long, action = clap::ArgAction::Count)]
    verbose: u8,

    /// Target port for UDP/TCP modes
    #[clap(short, long, default_value_t = 33434)]
    port: u16,

    /// Specify public IP address (skip STUN detection)
    #[clap(long)]
    public_ip: Option<String>,

    /// Custom STUN server address (e.g., stun.l.google.com:19302)
    #[clap(long)]
    stun_server: Option<String>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum ProtocolArg {
    Icmp,
    Udp,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum SocketModeArg {
    Raw,
    Dgram,
}

/// JSON output structure for a single hop
#[derive(Debug, serde::Serialize)]
struct JsonHop {
    ttl: u8,
    segment: Option<String>,
    address: Option<String>,
    hostname: Option<String>,
    asn_info: Option<ftr::AsnInfo>,
    rtt_ms: Option<f64>,
}

/// JSON output structure for the entire traceroute result
#[derive(Debug, serde::Serialize)]
struct JsonOutput {
    version: String,
    target: String,
    target_ip: String,
    public_ip: Option<String>,
    isp: Option<JsonIsp>,
    destination_asn: Option<JsonAsn>,
    hops: Vec<JsonHop>,
    protocol: String,
    socket_mode: String,
}

/// JSON output structure for ASN information
#[derive(Debug, serde::Serialize)]
struct JsonAsn {
    asn: u32,
    name: String,
    country_code: String,
}

/// JSON output structure for ISP information
#[derive(Debug, serde::Serialize)]
struct JsonIsp {
    asn: String,
    name: String,
    hostname: Option<String>,
}

fn main() {
    let process_start = Instant::now();

    // Quick check for help/version before starting async runtime
    let args: Vec<String> = std::env::args().collect();
    if args.len() == 2 && (args[1] == "--help" || args[1] == "-h") {
        // Clap will handle this
        let _ = Args::parse();
        return;
    }
    if args.len() == 2 && (args[1] == "--version" || args[1] == "-V") {
        println!("ftr {}", get_version());
        return;
    }

    // Create single-threaded tokio runtime for lower overhead
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("Failed to create Tokio runtime");

    let result = runtime.block_on(async_main(process_start));

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}

async fn async_main(_process_start: Instant) -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();

    // Create Ftr instance with fresh caches
    let ftr_instance = ftr::Ftr::new();

    // Handle public IP option - skip STUN if provided
    if args.public_ip.is_none() {
        // Set custom STUN server if provided
        if let Some(stun_server) = &args.stun_server {
            std::env::set_var("FTR_STUN_SERVER", stun_server);
        }

        // Pre-warm STUN cache immediately for faster public IP detection
        // (Cache warming is now handled internally by Ftr instance)
    }

    // Initialize debug mode if requested
    // ftr::debug::init_debug(args.verbose);

    // Validate arguments
    if args.start_ttl < 1 {
        eprintln!("Error: start-ttl must be at least 1");
        std::process::exit(1);
    }

    if args.probe_timeout_ms == 0 {
        eprintln!("Error: probe-timeout-ms must be greater than 0");
        std::process::exit(1);
    }

    // Check if running without root on a platform that requires it
    if !ftr::socket::utils::is_root() && !ftr::socket::utils::has_non_root_capability() {
        eprintln!(
            "Error: ftr requires root privileges on {}",
            std::env::consts::OS
        );
        eprintln!("This platform does not support unprivileged traceroute.");
        eprintln!(
            "Please run with sudo: sudo {}",
            std::env::args().collect::<Vec<_>>().join(" ")
        );
        #[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
        eprintln!(
            "Or make the binary setuid root: sudo chown root:wheel ftr && sudo chmod u+s ftr"
        );
        std::process::exit(1);
    }

    // Convert command-line args to library types
    let preferred_protocol = args.protocol.map(|p| match p {
        ProtocolArg::Icmp => ProbeProtocol::Icmp,
        ProtocolArg::Udp => ProbeProtocol::Udp,
    });

    let preferred_mode = args.socket_mode.map(|m| match m {
        SocketModeArg::Raw => SocketMode::Raw,
        SocketModeArg::Dgram => SocketMode::Dgram,
    });

    // Resolve target early to use in config
    let target_ip = resolve_target(&args.host).await?;

    // Pre-fetch destination IP's rDNS and ASN lookups in the background
    {
        let target_ip_clone = target_ip;
        let no_rdns = args.no_rdns;
        tokio::spawn(async move {
            // Pre-warm DNS reverse lookup only if rDNS is enabled
            if !no_rdns {
                let _ = ftr::dns::resolve_ptr(target_ip_clone).await;
            }

            // ASN pre-warming removed - caches are now managed by Ftr instance
        });
    }

    // Parse public IP if provided
    let public_ip = if let Some(ip_str) = &args.public_ip {
        match ip_str.parse::<IpAddr>() {
            Ok(ip) => Some(ip),
            Err(_) => {
                eprintln!("Error: Invalid public IP address: {}", ip_str);
                std::process::exit(1);
            }
        }
    } else {
        None
    };

    // Build configuration
    let mut builder = TracerouteConfigBuilder::new()
        .target(&args.host)
        .target_ip(target_ip)
        .start_ttl(args.start_ttl)
        .max_hops(args.max_hops)
        .probe_timeout(Duration::from_millis(args.probe_timeout_ms))
        .send_interval(Duration::from_millis(args.send_launch_interval_ms))
        .overall_timeout(Duration::from_millis(args.overall_timeout_ms))
        .queries_per_hop(args.queries)
        .enable_asn_lookup(!args.no_enrich)
        .enable_rdns(!args.no_rdns)
        .verbose(args.verbose)
        .port(args.port);

    // Add public IP if provided
    if let Some(ip) = public_ip {
        builder = builder.public_ip(ip);
    }

    let config = builder.build();

    let config = match config {
        Ok(mut cfg) => {
            // Add protocol and mode if specified
            cfg.protocol = preferred_protocol;
            cfg.socket_mode = preferred_mode;

            // Warn Windows users about potential issues with short timeouts + enrichment
            #[cfg(target_os = "windows")]
            if args.probe_timeout_ms < 100 && (!args.no_enrich || !args.no_rdns) {
                eprintln!(
                    "Warning: On Windows, probe timeouts < 100ms with enrichment enabled may cause"
                );
                eprintln!(
                    "         unreliable results. Consider using --probe-timeout-ms 100 or higher,"
                );
                eprintln!("         or disable enrichment with --no-enrich --no-rdns");
                eprintln!();
            }

            cfg
        }
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    };

    // Warn if port was explicitly specified but won't be used
    if args.port != 33434 && preferred_protocol == Some(ProbeProtocol::Icmp) {
        eprintln!(
            "Warning: Port {} specified but will be ignored for ICMP protocol",
            args.port
        );
    }

    // Print initial message
    if !args.json {
        println!(
            "ftr to {} ({}), {} max hops, {}ms probe timeout, {}ms overall timeout{}",
            args.host,
            target_ip,
            args.max_hops,
            args.probe_timeout_ms,
            args.overall_timeout_ms,
            if args.no_enrich {
                " (enrichment disabled)"
            } else {
                ""
            }
        );

        if !args.no_enrich {
            println!(
                "\nPerforming ASN lookups{} and classifying segments...",
                if args.no_rdns {
                    ""
                } else {
                    ", reverse DNS lookups"
                }
            );
        } else {
            println!("\nTraceroute path (raw):");
        }
    }

    // Run traceroute using the Ftr instance
    let result = match ftr_instance.trace_with_config(config).await {
        Ok(result) => result,
        Err(TracerouteError::InsufficientPermissions {
            required,
            suggestion,
        }) => {
            eprintln!("\nError: Insufficient permissions");
            eprintln!("Required: {}", required);
            eprintln!("Suggestion: {}", suggestion);
            eprintln!(
                "\nTo run with elevated privileges: sudo {}",
                std::env::args().collect::<Vec<_>>().join(" ")
            );
            std::process::exit(1);
        }
        Err(TracerouteError::NotImplemented { feature }) => {
            eprintln!("\nError: {} is not yet implemented", feature);
            eprintln!("This feature is planned for a future release.");
            std::process::exit(1);
        }
        Err(TracerouteError::Ipv6NotSupported) => {
            eprintln!("\nError: IPv6 targets are not yet supported");
            eprintln!("Please use an IPv4 address or hostname that resolves to IPv4.");
            std::process::exit(1);
        }
        Err(TracerouteError::ResolutionError(msg)) => {
            eprintln!("\nError: {}", msg);
            eprintln!("Please check the hostname and your network connection.");
            std::process::exit(1);
        }
        Err(TracerouteError::ConfigError(msg)) => {
            eprintln!("\nError: Invalid configuration - {}", msg);
            eprintln!("Run 'ftr --help' for usage information.");
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("\nError: {}", e);
            std::process::exit(1);
        }
    };

    // Display results
    if args.json {
        display_json_results(result)?;
    } else {
        display_text_results(result, args.no_enrich, args.no_rdns);
    }

    // Quick exit to avoid cleanup overhead on Windows
    std::process::exit(0);
}

/// Resolve target hostname to IP address
async fn resolve_target(host: &str) -> Result<IpAddr, Box<dyn std::error::Error>> {
    // Try parsing as IP first
    if let Ok(ip) = host.parse::<IpAddr>() {
        return Ok(ip);
    }

    // Handle localhost without DNS
    if host == "localhost" {
        return Ok(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
    }

    // Use our DNS resolver
    let addrs = ftr::dns::resolve_a(host)
        .await
        .map_err(|e| format!("Error resolving host: {e}"))?;

    Ok(IpAddr::V4(addrs[0]))
}

/// Display results in JSON format
fn display_json_results(result: TracerouteResult) -> Result<(), Box<dyn std::error::Error>> {
    let mut json_output = JsonOutput {
        version: get_version().to_string(),
        target: result.target.clone(),
        target_ip: result.target_ip.to_string(),
        public_ip: result.isp_info.as_ref().map(|i| i.public_ip.to_string()),
        isp: result.isp_info.as_ref().map(|i| JsonIsp {
            asn: i.asn.to_string(),
            name: i.name.clone(),
            hostname: i.hostname.clone(),
        }),
        destination_asn: result.destination_asn.as_ref().map(|asn| JsonAsn {
            asn: asn.asn,
            name: asn.name.clone(),
            country_code: asn.country_code.clone(),
        }),
        hops: Vec::new(),
        protocol: result.protocol_used.description().to_string(),
        socket_mode: result.socket_mode_used.description().to_string(),
    };

    // Convert hops to JSON format based on SegmentType (0.6.0 refined segments)
    for hop in result.hops.iter() {
        let segment = match hop.segment {
            ftr::SegmentType::Lan => Some("LAN".to_string()),
            ftr::SegmentType::Isp => Some("ISP".to_string()),
            ftr::SegmentType::Transit => Some("TRANSIT".to_string()),
            ftr::SegmentType::Destination => Some("DESTINATION".to_string()),
            ftr::SegmentType::Unknown => None,
        };
        json_output.hops.push(JsonHop {
            ttl: hop.ttl,
            segment,
            address: hop.addr.map(|a| a.to_string()),
            hostname: hop.hostname.clone(),
            asn_info: hop.asn_info.clone(),
            rtt_ms: hop.rtt_ms().map(|ms| (ms * 10.0).round() / 10.0), // Round to 1 decimal place
        });
    }

    println!("{}", serde_json::to_string_pretty(&json_output)?);
    Ok(())
}

/// Display results in text format
fn display_text_results(result: TracerouteResult, no_enrich: bool, no_rdns: bool) {
    // Use the explicit no_enrich flag passed from command line args
    let enrichment_disabled = no_enrich;

    // Display hops
    let mut last_responsive_ttl = 0u8;
    for hop in result.hops.iter() {
        if hop.addr.is_some() {
            last_responsive_ttl = hop.ttl;
        }
    }

    for hop in result.hops.iter() {
        if hop.addr.is_none() {
            // Silent hop - only show if it's before the last responsive hop
            if hop.ttl <= last_responsive_ttl {
                println!("{:2}", hop.ttl);
            }
        } else {
            let addr_str = hop.addr.map_or("*".to_string(), |a| a.to_string());
            let rtt_str = hop
                .rtt_ms()
                .map_or("*".to_string(), |r| format!("{:.3} ms", r));

            // Format hostname and address
            let host_display = if let (false, Some(hostname)) = (no_rdns, &hop.hostname) {
                if hop.addr.is_some() {
                    format!("{} ({})", hostname, addr_str)
                } else {
                    hostname.clone()
                }
            } else {
                addr_str.clone()
            };

            // Format ASN info
            let asn_str = if let Some(asn_info) = &hop.asn_info {
                if asn_info.asn != 0 {
                    format!(
                        " [AS{} - {}, {}]",
                        asn_info.asn, asn_info.name, asn_info.country_code
                    )
                } else {
                    format!(" [{}]", asn_info.name)
                }
            } else {
                String::new()
            };

            // Only show segment and ASN if enrichment was enabled
            if enrichment_disabled {
                // Raw mode - no enrichment data at all
                println!("{:2} {} {}", hop.ttl, host_display, rtt_str);
            } else {
                // Enriched mode - show segment and ASN info with refined segments
                println!(
                    "{:2} [{}] {} {}{}",
                    hop.ttl, hop.segment, host_display, rtt_str, asn_str
                );
            }
        }
    }

    // Show message if we didn't reach destination and have silent hops at the end
    if !result.destination_reached
        && last_responsive_ttl > 0
        && last_responsive_ttl < result.max_ttl().unwrap_or(30)
    {
        println!(
            "\n[No further hops responded; max TTL was {}]",
            result.max_ttl().unwrap_or(30)
        );
    }

    // Display ISP info if available
    if let Some(isp_info) = &result.isp_info {
        if let (false, Some(hostname)) = (no_rdns, &isp_info.hostname) {
            println!(
                "\nDetected public IP: {} ({})",
                isp_info.public_ip, hostname
            );
        } else {
            println!("\nDetected public IP: {}", isp_info.public_ip);
        }
        println!("Detected ISP: AS{} ({})", isp_info.asn, isp_info.name);
    }

    // Display destination ASN if available
    if let Some(ref dest_asn) = result.destination_asn {
        println!(
            "Destination ASN: AS{} ({}, {})",
            dest_asn.asn, dest_asn.name, dest_asn.country_code
        );
    }
}

#[cfg(test)]
#[path = "main_tests.rs"]
mod main_tests;

#[cfg(test)]
#[path = "main_v6_tests.rs"]
mod main_v6_tests;