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
//! Traceroute engine
//!
//! This implementation maximizes parallelism by:
//! 1. Starting ISP detection (STUN) immediately on launch
//! 2. Sending all probes in parallel
//! 3. Starting ASN/rDNS enrichment immediately as each response arrives
//! 4. Using caches to avoid duplicate lookups
use crate::enrichment::EnrichmentService;
use crate::probe::{ProbeInfo, ProbeResponse};
use crate::services::Services;
use crate::socket::traits::ProbeSocket;
use crate::socket::{ProbeProtocol, SocketMode};
use crate::traceroute::TracerouteError;
use crate::traceroute::{AsnInfo, ClassifiedHopInfo, SegmentType, TracerouteResult};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::task::JoinSet;
#[cfg(test)]
#[path = "engine_test.rs"]
mod engine_test;
#[cfg(test)]
#[path = "sandwich_test.rs"]
mod sandwich_test;
use tokio::time::{sleep, timeout};
/// Enrichment result for an address
#[derive(Clone)]
struct EnrichmentResult {
hostname: Option<String>,
asn_info: Option<AsnInfo>,
}
/// Fully parallel async traceroute engine
pub struct TracerouteEngine {
socket: Arc<Box<dyn ProbeSocket>>,
config: crate::TracerouteConfig,
target: IpAddr,
enrichment_service: Arc<EnrichmentService>,
enrichment_cache: Arc<Mutex<HashMap<IpAddr, EnrichmentResult>>>,
services: Option<Arc<Services>>,
}
impl TracerouteEngine {
/// Create a new fully parallel async traceroute engine with injected services
pub async fn new_with_services(
socket: Box<dyn ProbeSocket>,
config: crate::TracerouteConfig,
target: IpAddr,
services: Arc<Services>,
) -> Result<Self, TracerouteError> {
// Create enrichment service upfront
let enrichment_service = Arc::new(
EnrichmentService::new()
.await
.map_err(|e| TracerouteError::Other(e.to_string()))?,
);
Ok(Self {
socket: Arc::new(socket),
config,
target,
enrichment_service,
enrichment_cache: Arc::new(Mutex::new(HashMap::new())),
services: Some(services),
})
}
/// Create a new fully parallel async traceroute engine (uses global caches)
pub async fn new(
socket: Box<dyn ProbeSocket>,
config: crate::TracerouteConfig,
target: IpAddr,
) -> Result<Self, TracerouteError> {
// Create enrichment service upfront
let enrichment_service = Arc::new(
EnrichmentService::new()
.await
.map_err(|e| TracerouteError::Other(e.to_string()))?,
);
Ok(Self {
socket: Arc::new(socket),
config,
target,
enrichment_service,
enrichment_cache: Arc::new(Mutex::new(HashMap::new())),
services: None,
})
}
/// Run the fully parallel async traceroute
pub async fn run(&self) -> Result<TracerouteResult, TracerouteError> {
let start_time = Instant::now();
trace_time!(
self.config.verbose,
"Starting fully parallel async traceroute to {}",
self.target
);
// 1. Start ISP detection immediately (if enabled)
let isp_future = if self.config.enable_asn_lookup {
if let Some(public_ip) = self.config.public_ip {
// Use provided public IP
trace_time!(
self.config.verbose,
"Using provided public IP: {}",
public_ip
);
let verbose = self.config.verbose;
if let Some(ref services) = self.services {
// Use injected services
let services = services.clone();
Some(tokio::spawn(async move {
let isp_start = Instant::now();
let result = crate::public_ip::detect_isp_from_ip_with_services(
public_ip, &services,
)
.await;
trace_time!(
verbose,
"ISP detection from provided IP completed in {:?}",
isp_start.elapsed()
);
result
}))
} else {
// Cannot detect ISP without services
None
}
} else {
// Use STUN detection
trace_time!(
self.config.verbose,
"Starting ISP detection (STUN) in parallel"
);
let verbose = self.config.verbose;
if let Some(ref services) = self.services {
// Use injected services
let services = services.clone();
Some(tokio::spawn(async move {
let isp_start = Instant::now();
let result =
crate::public_ip::detect_isp_stun_with_services(&services).await;
trace_time!(
verbose,
"ISP detection completed in {:?}",
isp_start.elapsed()
);
result
}))
} else {
// Cannot detect ISP without services
None
}
}
} else {
None
};
// Start destination ASN lookup early in parallel (if services and enrichment enabled)
let dest_asn_future = if self.config.enable_asn_lookup {
if let Some(ref services) = self.services {
let services = services.clone();
let target = self.target;
let verbose = self.config.verbose;
Some(tokio::spawn(async move {
trace_time!(verbose, "Starting destination ASN lookup for {}", target);
match services.asn.lookup(target).await {
Ok(info) if info.asn != 0 => Some(info),
_ => None,
}
}))
} else {
None
}
} else {
None
};
// 2. Create futures for all probes with immediate enrichment
let mut probe_futures = JoinSet::new();
let mut sequence = 1u16;
trace_time!(
self.config.verbose,
"Creating probe futures with immediate enrichment"
);
for ttl in self.config.start_ttl..=self.config.max_hops {
for _query in 0..self.config.queries_per_hop {
let probe = ProbeInfo {
sequence,
ttl,
sent_at: Instant::now(),
};
sequence += 1;
let socket = Arc::clone(&self.socket);
let target = self.target;
let verbose = self.config.verbose;
let enrichment_service = Arc::clone(&self.enrichment_service);
let enrichment_cache = Arc::clone(&self.enrichment_cache);
let enable_asn = self.config.enable_asn_lookup;
let enable_rdns = self.config.enable_rdns;
// Create future that sends probe AND enriches response immediately
let probe_future = async move {
trace_time!(
verbose,
"Sending probe seq={} ttl={}",
probe.sequence,
probe.ttl
);
match socket.send_probe_and_recv(target, probe).await {
Ok(response) => {
trace_time!(
verbose,
"Received response seq={} ttl={} from={} rtt={:?}",
response.sequence,
response.ttl,
response.from_addr,
response.rtt
);
// Start enrichment immediately if not cached
if enable_asn || enable_rdns {
let cache = enrichment_cache.lock().await;
if !cache.contains_key(&response.from_addr) {
drop(cache); // Release lock before enrichment
trace_time!(
verbose,
"Starting immediate enrichment for {}",
response.from_addr
);
let enrich_start = Instant::now();
// Enrich this single address
let enrichment_results = enrichment_service
.enrich_addresses(vec![response.from_addr])
.await;
if let Some(enrichment) =
enrichment_results.get(&response.from_addr)
{
trace_time!(
verbose,
"Enrichment for {} completed in {:?}",
response.from_addr,
enrich_start.elapsed()
);
// Cache the result
let mut cache = enrichment_cache.lock().await;
cache.insert(
response.from_addr,
EnrichmentResult {
hostname: enrichment.hostname.clone(),
asn_info: enrichment.asn_info.clone(),
},
);
}
}
}
Some(response)
}
Err(_) => None,
}
};
probe_futures.spawn(probe_future);
}
}
trace_time!(
self.config.verbose,
"Started {} probe futures",
sequence - 1
);
// 3. Collect responses as they arrive
let mut responses: Vec<ProbeResponse> = Vec::new();
let mut ttl_responses: HashMap<u8, usize> = HashMap::new();
let mut destination_ttl: Option<u8> = None;
let collection_start = Instant::now();
trace_time!(self.config.verbose, "Starting response collection");
let collection_future = async {
while let Some(Ok(response)) = probe_futures.join_next().await {
if let Some(resp) = response {
let ttl = resp.ttl;
let is_destination = resp.is_destination;
// Track responses per TTL
*ttl_responses.entry(ttl).or_insert(0) += 1;
// Update destination TTL if we found it
if is_destination && destination_ttl.is_none() {
destination_ttl = Some(ttl);
}
responses.push(resp);
// Check if we can exit early
if let Some(dest_ttl) = destination_ttl {
let mut can_exit = true;
for check_ttl in self.config.start_ttl..=dest_ttl {
if ttl_responses.get(&check_ttl).copied().unwrap_or(0) == 0 {
can_exit = false;
break;
}
}
if can_exit {
trace_time!(
self.config.verbose,
"Early exit - all TTLs up to destination responded"
);
// Wait briefly for late responses
sleep(Duration::from_millis(25)).await;
// Collect any remaining
while let Ok(Some(Ok(response))) =
timeout(Duration::from_millis(10), probe_futures.join_next()).await
{
if let Some(resp) = response {
responses.push(resp);
}
}
break;
}
}
}
}
};
// Execute with overall timeout
let _ = timeout(self.config.overall_timeout, collection_future).await;
trace_time!(
self.config.verbose,
"Response collection completed in {:?}",
collection_start.elapsed()
);
// 4. Build result with cached enrichment data
let elapsed = start_time.elapsed();
self.build_result(responses, elapsed, isp_future, dest_asn_future)
.await
}
/// Build the final traceroute result with enriched data
async fn build_result(
&self,
responses: Vec<ProbeResponse>,
elapsed: Duration,
isp_future: Option<
tokio::task::JoinHandle<
Result<crate::traceroute::IspInfo, crate::public_ip::PublicIpError>,
>,
>,
dest_asn_future: Option<tokio::task::JoinHandle<Option<AsnInfo>>>,
) -> Result<TracerouteResult, TracerouteError> {
let mut hops: HashMap<u8, Vec<ProbeResponse>> = HashMap::new();
// Group responses by TTL
for response in responses {
hops.entry(response.ttl).or_default().push(response);
}
// Check if destination was reached
let destination_reached = hops
.values()
.any(|ttl_responses| ttl_responses.iter().any(|r| r.is_destination));
let destination_ttl = hops
.values()
.flat_map(|ttl_responses| ttl_responses.iter())
.filter(|r| r.is_destination)
.map(|r| r.ttl)
.min()
.unwrap_or(self.config.max_hops);
// Wait for ISP detection to complete
let isp_info = if let Some(future) = isp_future {
trace_time!(self.config.verbose, "Waiting for ISP detection to complete");
match future.await {
Ok(Ok(isp)) => Some(isp),
Ok(Err(e)) => {
trace_time!(self.config.verbose, "ISP detection failed: {}", e);
None
}
Err(e) => {
trace_time!(self.config.verbose, "ISP detection task failed: {}", e);
None
}
}
} else {
None
};
// Get ISP ASN for segment classification
let isp_asn = isp_info.as_ref().map(|isp| isp.asn);
// Wait for destination ASN
let dest_asn = if let Some(fut) = dest_asn_future {
fut.await.unwrap_or_default()
} else {
None
};
// Build classified hops with enrichment data
let enrichment_cache = self.enrichment_cache.lock().await;
let mut hop_infos: Vec<ClassifiedHopInfo> = Vec::new();
let mut in_isp_segment = false;
let display_max_ttl = if destination_reached {
destination_ttl
} else {
self.config.max_hops
};
for ttl in self.config.start_ttl..=display_max_ttl {
if let Some(ttl_responses) = hops.get(&ttl) {
if !ttl_responses.is_empty() {
// Get unique addresses
let mut unique_addrs: Vec<IpAddr> = ttl_responses
.iter()
.filter(|r| !r.is_timeout)
.map(|r| r.from_addr)
.collect();
unique_addrs.sort();
unique_addrs.dedup();
for addr in unique_addrs {
let addr_responses: Vec<&ProbeResponse> = ttl_responses
.iter()
.filter(|r| r.from_addr == addr)
.collect();
// Calculate average RTT
let rtt = if !addr_responses.is_empty() {
let total_rtt: Duration = addr_responses.iter().map(|r| r.rtt).sum();
Some(total_rtt / addr_responses.len() as u32)
} else {
None
};
// Get cached enrichment data
let enrichment = enrichment_cache.get(&addr);
let hostname = enrichment.and_then(|e| e.hostname.clone());
let asn_info = enrichment.and_then(|e| e.asn_info.clone());
// Classify segment
let segment = if let IpAddr::V4(ipv4) = addr {
if crate::traceroute::is_internal_ip(&ipv4) {
SegmentType::Lan
} else if crate::traceroute::is_cgnat(&ipv4) {
in_isp_segment = true;
SegmentType::Isp
} else {
// Public IP classification requires ISP and/or destination ASN
if let Some(ref asn) = asn_info {
// ISP boundary check if known
if let Some(isp) = isp_asn {
if asn.asn == isp {
in_isp_segment = true;
SegmentType::Isp
} else if let Some(ref dest) = dest_asn {
if asn.asn == dest.asn {
SegmentType::Destination
} else {
SegmentType::Transit
}
} else {
// ISP known but not this AS; without dest ASN, mark as TRANSIT
SegmentType::Transit
}
} else if let Some(ref dest) = dest_asn {
if asn.asn == dest.asn {
SegmentType::Destination
} else if in_isp_segment {
SegmentType::Transit
} else {
SegmentType::Unknown
}
} else if in_isp_segment {
SegmentType::Transit
} else {
SegmentType::Unknown
}
} else if in_isp_segment {
// Public IP after ISP without ASN = likely IXP/peering point
SegmentType::Transit
} else {
// Public IP without ASN before ISP boundary = assume transit
SegmentType::Transit
}
}
} else {
SegmentType::Unknown
};
hop_infos.push(ClassifiedHopInfo {
ttl,
segment,
hostname,
addr: Some(addr),
asn_info,
rtt,
});
}
// Add timeout responses
let timeout_count = ttl_responses.iter().filter(|r| r.is_timeout).count();
for _ in 0..timeout_count {
hop_infos.push(ClassifiedHopInfo {
ttl,
segment: SegmentType::Unknown,
hostname: None,
addr: None,
asn_info: None,
rtt: None,
});
}
}
} else {
// Add blank hop
hop_infos.push(ClassifiedHopInfo {
ttl,
segment: SegmentType::Unknown,
hostname: None,
addr: None,
asn_info: None,
rtt: None,
});
}
}
// Sort by TTL
hop_infos.sort_by_key(|h| h.ttl);
// Apply sandwich logic: fill Unknown/Transit hops between same-type segments
Self::apply_sandwich_logic(&mut hop_infos);
// Determine protocol and socket mode
let (protocol_used, socket_mode_used) = match self.socket.mode() {
crate::socket::traits::ProbeMode::DgramIcmp => (ProbeProtocol::Icmp, SocketMode::Dgram),
crate::socket::traits::ProbeMode::WindowsIcmp => (ProbeProtocol::Icmp, SocketMode::Raw),
crate::socket::traits::ProbeMode::UdpWithRecverr => {
(ProbeProtocol::Udp, SocketMode::Dgram)
}
crate::socket::traits::ProbeMode::RawIcmp => (ProbeProtocol::Icmp, SocketMode::Raw),
};
trace_time!(
self.config.verbose,
"Total fully parallel async traceroute completed in {:?}",
elapsed
);
Ok(TracerouteResult {
target: self.config.target.clone(),
target_ip: self.target,
hops: hop_infos,
isp_info,
destination_asn: dest_asn,
protocol_used,
socket_mode_used,
destination_reached,
total_duration: elapsed,
})
}
/// Apply sandwich logic: if Unknown/Transit hops are between two hops of the same segment type,
/// convert them to that segment type. This handles cases where probes fail or lack ASN data
/// but are clearly part of the same network segment.
pub(crate) fn apply_sandwich_logic(hops: &mut [ClassifiedHopInfo]) {
if hops.len() < 3 {
return; // Need at least 3 hops for sandwiching
}
for i in 1..hops.len() - 1 {
// Only modify Unknown or Transit segments that have addresses
if hops[i].addr.is_some()
&& (hops[i].segment == SegmentType::Unknown
|| hops[i].segment == SegmentType::Transit)
{
// Look for surrounding hops of the same type
let mut check_segment = |segment_type: SegmentType| {
// Find previous hop with this segment type
let has_before = (0..i).rev().any(|j| hops[j].segment == segment_type);
// Find next hop with this segment type
let has_after = (i + 1..hops.len()).any(|j| hops[j].segment == segment_type);
if has_before && has_after {
hops[i].segment = segment_type;
true
} else {
false
}
};
// Check ISP first, then Destination
// ISP takes precedence as it's typically earlier in the path
if check_segment(SegmentType::Isp) {
continue;
}
check_segment(SegmentType::Destination);
}
}
}
}