ftr 0.10.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
//! Fast TraceRoute (ftr) - A parallel traceroute implementation
//!
//! This library provides high-performance traceroute functionality with support for
//! multiple protocols, parallel probing, and rich network information enrichment.
//!
//! # Features
//!
//! - **Multiple protocols**: ICMP, UDP, and TCP traceroute support
//! - **Parallel probing**: Send multiple probes simultaneously for faster results
//! - **Rich information**: Automatic ASN lookup, reverse DNS, and ISP detection
//! - **Flexible socket modes**: Raw sockets, DGRAM sockets, or unprivileged UDP
//! - **Cross-platform**: Works on Linux, macOS, Windows, and BSD systems
//! - **Caching**: Built-in caching for DNS and ASN lookups to improve performance
//!
//! # Quick Start
//!
//! ```no_run
//! use ftr::{Ftr, TracerouteConfig};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Create an Ftr instance
//!     let ftr = Ftr::new();
//!     
//!     // Simple trace with defaults
//!     let result = ftr.trace("google.com").await?;
//!     
//!     for hop in result.hops {
//!         println!("Hop {}: {:?}", hop.ttl, hop.addr);
//!     }
//!     
//!     Ok(())
//! }
//! ```
//!
//! # Advanced Usage
//!
//! ```no_run
//! use ftr::{Ftr, TracerouteConfigBuilder, ProbeProtocol};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let ftr = Ftr::new();
//!     
//!     let config = TracerouteConfigBuilder::new()
//!         .target("1.1.1.1")
//!         .protocol(ProbeProtocol::Tcp)
//!         .port(443)
//!         .max_hops(20)
//!         .queries(3)
//!         .parallel_probes(32)
//!         .enable_asn_lookup(true)
//!         .enable_rdns(true)
//!         .build()?;
//!     
//!     let result = ftr.trace_with_config(config).await?;
//!     println!("Trace complete: {} hops", result.hops.len());
//!     
//!     Ok(())
//! }
//! ```
//!
//! # Error Handling
//!
//! The library provides structured error types through the [`TracerouteError`] enum,
//! allowing for programmatic error handling without string parsing:
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use ftr::{Ftr, TracerouteError};
//!
//! let ftr = Ftr::new();
//! match ftr.trace("example.com").await {
//!     Ok(result) => println!("Success! Found {} hops", result.hop_count()),
//!     
//!     // Permission errors include structured information
//!     Err(TracerouteError::InsufficientPermissions { required, suggestion }) => {
//!         eprintln!("Permission denied: {}", required);
//!         eprintln!("Try: {}", suggestion);
//!     }
//!     
//!     // Feature not implemented errors
//!     Err(TracerouteError::NotImplemented { feature }) => {
//!         eprintln!("{} is not yet implemented", feature);
//!         // Could fall back to supported features
//!     }
//!     
//!     // Other structured errors
//!     Err(TracerouteError::Ipv6NotSupported) => {
//!         eprintln!("IPv6 targets are not yet supported");
//!     }
//!     Err(TracerouteError::ResolutionError(msg)) => {
//!         eprintln!("DNS resolution failed: {}", msg);
//!     }
//!     Err(e) => eprintln!("Error: {}", e),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! See [`TracerouteError`] for all error variants and the `examples/error_handling.rs`
//! example for comprehensive error handling patterns.
//!
//! # Modules
//!
//! - [`asn`]: ASN (Autonomous System Number) lookup functionality
//! - [`dns`]: Reverse DNS lookup with caching
//! - [`public_ip`]: Public IP detection and ISP information
//! - [`socket`]: Low-level socket implementations for different probe types
//! - [`traceroute`]: Core traceroute engine and high-level API

#![allow(clippy::uninlined_format_args)]

pub mod asn;
pub mod config;
pub mod services;
/// Simple debug print macro for conditional debug output
#[macro_export]
macro_rules! debug_print {
    ($level:expr_2021, $($arg:tt)*) => {
        #[cfg(debug_assertions)]
        {
            eprintln!("[DEBUG {}] {}", $level, format!($($arg)*));
        }
    };
}

/// Macro for timing traces in very verbose mode
#[macro_export]
macro_rules! trace_time {
    ($verbose:expr_2021, $($arg:tt)*) => {
        if $verbose >= 2 {
            eprintln!("[TIMING {:?}] {}", std::time::Instant::now(), format!($($arg)*));
        }
    };
}
pub mod dns;
pub(crate) mod enrichment;
#[cfg(feature = "async")]
pub mod probe;
pub mod public_ip;
pub mod socket;
pub mod traceroute;

// Re-export core types for library users
pub use socket::{IpVersion, ProbeMode, ProbeProtocol, SocketMode};
pub use traceroute::{
    AsnInfo, ClassifiedHopInfo, ConfigError, IspInfo, PreferredFamily, RawHopInfo, SegmentType,
    TimingConfig, Traceroute, TracerouteConfig, TracerouteConfigBuilder, TracerouteError,
    TracerouteProgress, TracerouteResult, resolve_target_with_family, trace, trace_with_config,
};

// Re-export API
pub use traceroute::api;

use services::Services;

/// Main handle for the Ftr library
///
/// The `Ftr` struct owns all services needed for traceroute operations.
/// This design allows for multiple independent instances with isolated state,
/// improving testability and enabling concurrent operations.
///
/// # Examples
///
/// ```no_run
/// use ftr::Ftr;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let ftr = Ftr::new();
///     let result = ftr.trace("google.com").await?;
///     
///     for hop in result.hops {
///         println!("Hop {}: {:?}", hop.ttl, hop.addr);
///     }
///     
///     Ok(())
/// }
/// ```
pub struct Ftr {
    /// The services container owning all external service clients
    services: Services,
}

impl Ftr {
    /// Access the services container for direct use of individual services
    ///
    /// This provides direct access to the ASN lookup, reverse DNS, and STUN
    /// services (and their caches) owned by this `Ftr` instance. Prefer the
    /// convenience methods ([`lookup_asn`](Self::lookup_asn),
    /// [`lookup_rdns`](Self::lookup_rdns),
    /// [`get_public_ip`](Self::get_public_ip)) for one-off lookups.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let ftr = Ftr::new();
    ///     let asn_info = ftr.services().asn.lookup("8.8.8.8".parse()?).await?;
    ///     println!("AS{}", asn_info.asn);
    ///     Ok(())
    /// }
    /// ```
    pub fn services(&self) -> &Services {
        &self.services
    }

    /// Create a new Ftr instance with fresh services
    pub fn new() -> Self {
        Self {
            services: Services::new(),
        }
    }

    /// Create a new Ftr instance using the provided services
    ///
    /// This allows customizing individual services, e.g. a
    /// [`StunClient`](crate::public_ip::StunClient) configured with custom
    /// STUN servers.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::services::Services;
    /// use ftr::public_ip::StunClient;
    /// use ftr::Ftr;
    ///
    /// let stun = StunClient::with_servers(vec!["stun.example.com:3478".to_string()]);
    /// let services = Services::with_services(None, None, Some(stun));
    /// let ftr = Ftr::with_services(services);
    /// ```
    pub fn with_services(services: Services) -> Self {
        Self { services }
    }

    /// Create a new Ftr instance with optional pre-initialized caches
    ///
    /// Any cache not provided will be created fresh.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    ///
    /// // With all fresh caches
    /// let ftr = Ftr::with_caches(None, None, None);
    ///
    /// // With a pre-populated ASN cache
    /// let asn_cache = ftr::asn::cache::AsnCache::new();
    /// // ... populate cache ...
    /// let ftr = Ftr::with_caches(Some(asn_cache), None, None);
    /// ```
    pub fn with_caches(
        asn_cache: Option<crate::asn::cache::AsnCache>,
        rdns_cache: Option<crate::dns::cache::RdnsCache>,
        stun_cache: Option<crate::public_ip::stun_cache::StunCache>,
    ) -> Self {
        // Create services with the provided caches
        let services = Services::with_caches(asn_cache, rdns_cache, stun_cache);

        Self { services }
    }

    /// Run a traceroute to the specified target with default configuration
    ///
    /// This is a convenience method equivalent to creating a default
    /// [`TracerouteConfig`] with the target and calling [`trace_with_config`].
    ///
    /// # Arguments
    ///
    /// * `target` - The target hostname or IP address
    ///
    /// # Returns
    ///
    /// A [`TracerouteResult`] containing the trace results, or a [`TracerouteError`]
    /// if the trace fails.
    pub async fn trace(&self, target: &str) -> Result<TracerouteResult, TracerouteError> {
        // ConfigError converts into TracerouteError::ConfigError via #[from]
        let config = TracerouteConfig::builder().target(target).build()?;
        self.trace_with_config(config).await
    }

    /// Run a traceroute with custom configuration
    ///
    /// # Arguments
    ///
    /// * `config` - The traceroute configuration
    ///
    /// # Returns
    ///
    /// A [`TracerouteResult`] containing the trace results, or a [`TracerouteError`]
    /// if the trace fails.
    pub async fn trace_with_config(
        &self,
        config: TracerouteConfig,
    ) -> Result<TracerouteResult, TracerouteError> {
        // Use the services-aware implementation
        traceroute::api::trace_with_services(config, &self.services).await
    }

    /// Look up ASN information for an IP address
    ///
    /// This is a convenience method that provides direct access to the ASN
    /// lookup service without needing to interact with `Arc<RwLock>`.
    ///
    /// Both IPv4 and IPv6 addresses are supported (IPv6 lookups use Team
    /// Cymru's `origin6.asn.cymru.com` zone).
    ///
    /// # Arguments
    ///
    /// * `ip` - The IP address to look up
    ///
    /// # Returns
    ///
    /// ASN information including AS number, prefix, country, and organization name
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    /// use std::net::IpAddr;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let ftr = Ftr::new();
    ///     let ip: IpAddr = "8.8.8.8".parse()?;
    ///     let asn_info = ftr.lookup_asn(ip).await?;
    ///     println!("AS{}: {}", asn_info.asn, asn_info.name);
    ///     Ok(())
    /// }
    /// ```
    pub async fn lookup_asn(
        &self,
        ip: std::net::IpAddr,
    ) -> Result<crate::traceroute::AsnInfo, crate::asn::AsnLookupError> {
        self.services.asn.lookup(ip).await
    }

    /// Look up the hostname for an IP address
    ///
    /// This is a convenience method that provides direct access to the reverse
    /// DNS lookup service without needing to interact with `Arc<RwLock>`.
    ///
    /// # Arguments
    ///
    /// * `ip` - The IP address to look up
    ///
    /// # Returns
    ///
    /// The hostname associated with the IP address
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    /// use std::net::IpAddr;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let ftr = Ftr::new();
    ///     let ip: IpAddr = "8.8.8.8".parse()?;
    ///     let hostname = ftr.lookup_rdns(ip).await?;
    ///     println!("{} -> {}", ip, hostname);
    ///     Ok(())
    /// }
    /// ```
    pub async fn lookup_rdns(
        &self,
        ip: std::net::IpAddr,
    ) -> Result<String, crate::dns::ReverseDnsError> {
        self.services.rdns.lookup(ip).await
    }

    /// Get the public IP address of this machine
    ///
    /// This is a convenience method that uses STUN protocol to detect
    /// the public IP address as seen from the internet.
    ///
    /// # Returns
    ///
    /// The public IP address
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let ftr = Ftr::new();
    ///     let public_ip = ftr.get_public_ip().await?;
    ///     println!("Public IP: {}", public_ip);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_public_ip(
        &self,
    ) -> Result<std::net::IpAddr, crate::public_ip::providers::PublicIpError> {
        self.services.stun.get_public_ip().await
    }

    /// Get the public IPv6 address of this machine
    ///
    /// This is a convenience method that uses STUN over UDPv6 to detect
    /// the public IPv6 address as seen from the internet. Fails with an
    /// error if the machine has no IPv6 connectivity.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let ftr = Ftr::new();
    ///     let public_ipv6 = ftr.get_public_ip_v6().await?;
    ///     println!("Public IPv6: {}", public_ipv6);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_public_ip_v6(
        &self,
    ) -> Result<std::net::Ipv6Addr, crate::public_ip::providers::PublicIpError> {
        self.services.stun.get_public_ip_v6().await
    }

    /// Get the public IP addresses for both families in parallel
    ///
    /// Discovers the public IPv4 and IPv6 addresses concurrently via STUN
    /// and never fails: a family without connectivity is `None` in the
    /// returned [`PublicIps`](crate::public_ip::PublicIps).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ftr::Ftr;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let ftr = Ftr::new();
    ///     let ips = ftr.get_public_ips().await;
    ///     println!("IPv4: {:?}, IPv6: {:?}", ips.v4, ips.v6);
    /// }
    /// ```
    pub async fn get_public_ips(&self) -> crate::public_ip::PublicIps {
        self.services.stun.get_public_ips().await
    }

    /// Clear all caches across all services
    ///
    /// This removes all cached data, forcing fresh lookups for all
    /// subsequent queries. Useful for testing or when cached data
    /// may be stale.
    pub async fn clear_all_caches(&self) {
        self.services.clear_all_caches().await;
    }
}

impl Default for Ftr {
    fn default() -> Self {
        Self::new()
    }
}