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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
use crate::error::NtraceError;
use crate::protocol::{Protocol, Target};
use log::{debug, info, warn};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
/// Configuration for traceroute
#[derive(Debug, Clone)]
pub struct TraceConfig {
/// Target to trace
pub target: Target,
/// Protocol to use (TCP, UDP, ICMP)
pub protocol: Protocol,
/// Port to use for TCP/UDP
pub port: u16,
/// Maximum number of hops to try
pub max_hops: u8,
/// Number of queries per hop
pub queries: u8,
/// Timeout for each probe in milliseconds
pub timeout_ms: u64,
/// Whether to perform reverse DNS lookups
pub resolve_hostnames: bool,
/// Number of parallel requests
pub parallel_requests: u8,
/// Time between sending packets in milliseconds
pub send_time_ms: u64,
/// Time between sending packets for different TTLs in milliseconds
pub ttl_time_ms: u64,
/// Payload size for probe packets
pub payload_size: usize,
}
impl Default for TraceConfig {
fn default() -> Self {
Self {
target: Target::Ip(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1))),
protocol: Protocol::Icmp,
port: 80,
max_hops: 30,
queries: 3,
timeout_ms: 1000,
resolve_hostnames: true,
parallel_requests: 18,
send_time_ms: 50,
ttl_time_ms: 50,
payload_size: 52,
}
}
}
/// Result for a single hop in the traceroute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HopResult {
/// Hop number (TTL)
pub hop: u8,
/// IP address of the hop
pub ip: Option<String>,
/// Hostname of the hop (if resolved)
pub hostname: Option<String>,
/// Latency for each query
pub latencies: Vec<Option<Duration>>,
/// Average latency
pub avg_latency: Option<Duration>,
/// Whether this hop is the final destination
pub is_destination: bool,
/// ASN information (if available)
pub asn: Option<String>,
/// Location information (if available)
pub location: Option<String>,
}
/// Result of a complete traceroute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceResult {
/// Target that was traced
pub target: String,
/// Protocol used
pub protocol: String,
/// Port used (for TCP/UDP)
pub port: Option<u16>,
/// Hops discovered
pub hops: Vec<HopResult>,
/// Total time taken
pub duration: Duration,
/// Whether the trace reached the destination
pub reached_destination: bool,
}
/// Tracer for performing traceroute operations
pub struct Tracer {
config: TraceConfig,
/// Statistics and results
results: Arc<Mutex<HashMap<u8, HopResult>>>,
}
impl Tracer {
/// Creates a new tracer with the given configuration
pub fn new(config: TraceConfig) -> Self {
Self {
config,
results: Arc::new(Mutex::new(HashMap::new())),
}
}
/// This would use proper reverse DNS lookup
async fn resolve_hostname(&self, ip: IpAddr) -> Option<String> {
// For now, we'll return None as proper DNS resolution requires
// additional setup that may not be available in all environments
debug!("Hostname resolution requested for {}", ip);
None
}
/// Perform a traceroute to the target
pub async fn trace(&mut self) -> Result<TraceResult, NtraceError> {
// Start timing
let start_time = Instant::now();
// Resolve target to IP if it's a domain
let target_ip = match &self.config.target {
Target::Ip(ip) => *ip,
Target::Domain(domain) => {
// Resolve domain to IP address using tokio's lookup_host
use tokio::net::lookup_host;
let addr_iter = lookup_host(format!("{}:{}", domain, 80))
.await
.map_err(|e| {
NtraceError::DnsError(format!("Failed to resolve {}: {}", domain, e))
})?;
// Get the first IP address
let addr = addr_iter.into_iter().next().ok_or_else(|| {
NtraceError::DnsError(format!("No IP addresses found for {}", domain))
})?;
addr.ip()
}
};
// Display target information
info!(
"Tracing route to {} ({})",
match &self.config.target {
Target::Ip(ip) => ip.to_string(),
Target::Domain(domain) => domain.clone(),
},
target_ip
);
// Determine which trace method to use based on protocol
match self.config.protocol {
Protocol::Tcp => self.trace_tcp(target_ip).await?,
Protocol::Udp => self.trace_udp(target_ip).await?,
Protocol::Icmp => {
// Try the raw socket implementation first
match self.trace_icmp_raw(target_ip).await {
Ok(_) => {}
Err(e) => {
warn!(
"Raw socket ICMP traceroute failed: {}. Trying alternative implementation.",
e
);
// Try the alternative implementation next
match self.trace_icmp_alternative(target_ip).await {
Ok(_) => {}
Err(e2) => {
warn!(
"Alternative ICMP traceroute failed: {}. Falling back to original implementation.",
e2
);
self.trace_icmp(target_ip).await?
}
}
}
}
}
}
// Calculate total duration
let duration = start_time.elapsed();
// Collect and sort results
let results = self.results.lock().await;
let mut hops: Vec<HopResult> = results.values().cloned().collect();
hops.sort_by_key(|h| h.hop);
// Determine if we reached the destination
let reached_destination = hops
.iter()
.any(|hop| hop.is_destination || (hop.ip.as_ref() == Some(&target_ip.to_string())));
// Create the final result
let trace_result = TraceResult {
target: match &self.config.target {
Target::Ip(ip) => ip.to_string(),
Target::Domain(domain) => domain.clone(),
},
protocol: format!("{:?}", self.config.protocol),
port: match self.config.protocol {
Protocol::Tcp | Protocol::Udp => Some(self.config.port),
_ => None,
},
hops,
duration,
reached_destination,
};
Ok(trace_result)
}
/// Perform a TCP traceroute
async fn trace_tcp(&self, target_ip: IpAddr) -> Result<(), NtraceError> {
// Both IPv4 and IPv6 are supported
// Create a progress indicator
let progress = if cfg!(not(test)) {
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(self.config.max_hops as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} hops")
.unwrap()
.progress_chars("█▓▒░ "),
);
Some(pb)
} else {
None
};
// Trace each TTL
for ttl in 1..=self.config.max_hops {
// Create a hop result entry
let mut hop_result = HopResult {
hop: ttl,
ip: None,
hostname: None,
latencies: vec![None; self.config.queries as usize],
avg_latency: None,
is_destination: false,
asn: None,
location: None,
};
// Send multiple queries for this hop
let mut responses = 0;
let mut total_latency = Duration::new(0, 0);
for q in 0..self.config.queries {
// Send TCP SYN packet with TTL set
let start_time = Instant::now();
// Create socket with TTL set
let socket = match std::net::TcpStream::connect_timeout(
&SocketAddr::new(target_ip, self.config.port),
Duration::from_millis(self.config.timeout_ms),
) {
Ok(s) => {
// Set TTL
if let Err(e) = s.set_ttl(ttl.into()) {
warn!("Failed to set TTL: {}", e);
continue;
}
s
}
Err(_) => {
// Connection failed, try next query
continue;
}
};
// Try to get socket error to determine if we got a response
match socket.take_error() {
Ok(Some(e)) => {
// Check if this is a TTL exceeded error
if let Some(addr) = Self::extract_router_ip_from_error(&e) {
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.to_string());
responses += 1;
total_latency += latency;
}
}
Ok(None) => {
// Connection succeeded - we reached the destination
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(target_ip.to_string());
hop_result.is_destination = true;
responses += 1;
total_latency += latency;
}
Err(e) => {
warn!("Error getting socket error: {}", e);
}
}
// Wait between queries
if q < self.config.queries - 1 {
tokio::time::sleep(Duration::from_millis(self.config.send_time_ms)).await;
}
}
// Calculate average latency if we got responses
if responses > 0 {
hop_result.avg_latency = Some(total_latency / responses);
}
// Resolve hostname if we have an IP and hostname resolution is enabled
if let Some(ip_str) = &hop_result.ip {
if self.config.resolve_hostnames {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
hop_result.hostname = self.resolve_hostname(ip).await;
}
}
}
// Store the result
{
let mut results = self.results.lock().await;
results.insert(ttl, hop_result.clone());
}
// Update progress
if let Some(pb) = &progress {
pb.inc(1);
}
// If we reached the destination, we're done
if let Some(ip) = &hop_result.ip {
if ip == &target_ip.to_string() {
break;
}
}
// Wait between TTLs
if ttl < self.config.max_hops {
tokio::time::sleep(Duration::from_millis(self.config.ttl_time_ms)).await;
}
}
// Finish progress
if let Some(pb) = &progress {
pb.finish_and_clear();
}
Ok(())
}
/// Perform a UDP traceroute
async fn trace_udp(&self, target_ip: IpAddr) -> Result<(), NtraceError> {
// Both IPv4 and IPv6 are supported
// Create a progress indicator
let progress = if cfg!(not(test)) {
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(self.config.max_hops as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} hops")
.unwrap()
.progress_chars("█▓▒░ "),
);
Some(pb)
} else {
None
};
// For UDP traceroute, we'll use a simpler approach with standard sockets
// since pnet's UDP implementation is more complex to work with
for ttl in 1..=self.config.max_hops {
// Create a hop result entry
let mut hop_result = HopResult {
hop: ttl,
ip: None,
hostname: None,
latencies: vec![None; self.config.queries as usize],
avg_latency: None,
is_destination: false,
asn: None,
location: None,
};
// Send multiple queries for this hop
let mut responses = 0;
let mut total_latency = Duration::new(0, 0);
for q in 0..self.config.queries {
// Create UDP socket with appropriate binding for IPv4 or IPv6
let bind_addr = match target_ip {
IpAddr::V4(_) => "0.0.0.0:0",
IpAddr::V6(_) => "[::]:0",
};
let socket = match std::net::UdpSocket::bind(bind_addr) {
Ok(s) => {
// Set TTL
if let Err(e) = s.set_ttl(ttl.into()) {
warn!("Failed to set TTL: {}", e);
continue;
}
// Set timeouts
if let Err(e) =
s.set_read_timeout(Some(Duration::from_millis(self.config.timeout_ms)))
{
warn!("Failed to set read timeout: {}", e);
continue;
}
s
}
Err(e) => {
warn!("Failed to create UDP socket: {}", e);
continue;
}
};
// Create a simple payload
let mut payload = vec![0u8; self.config.payload_size];
rand::rng().fill(&mut payload[..]);
// Start timing
let start_time = Instant::now();
// Send the packet
if let Err(e) =
socket.send_to(&payload, SocketAddr::new(target_ip, self.config.port))
{
warn!("Failed to send UDP packet: {}", e);
continue;
}
// Wait for response
let mut buf = [0u8; 1024];
match socket.recv_from(&mut buf) {
Ok((_, addr)) => {
// Got a response
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.ip().to_string());
// Check if this is the destination
if addr.ip() == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
}
Err(e) => {
debug!("No response from UDP packet: {}", e);
}
}
// Wait between queries
if q < self.config.queries - 1 {
tokio::time::sleep(Duration::from_millis(self.config.send_time_ms)).await;
}
}
// Calculate average latency if we got responses
if responses > 0 {
hop_result.avg_latency = Some(total_latency / responses);
}
// Resolve hostname if we have an IP and hostname resolution is enabled
if let Some(ip_str) = &hop_result.ip {
if self.config.resolve_hostnames {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
hop_result.hostname = self.resolve_hostname(ip).await;
}
}
}
// Store the result
{
let mut results = self.results.lock().await;
results.insert(ttl, hop_result.clone());
}
// Update progress
if let Some(pb) = &progress {
pb.inc(1);
}
// If we reached the destination, we're done
if hop_result.is_destination {
break;
}
// Wait between TTLs
if ttl < self.config.max_hops {
tokio::time::sleep(Duration::from_millis(self.config.ttl_time_ms)).await;
}
}
// Finish progress
if let Some(pb) = &progress {
pb.finish_and_clear();
}
Ok(())
}
/// Perform an ICMP traceroute
async fn trace_icmp(&self, target_ip: IpAddr) -> Result<(), NtraceError> {
// Both IPv4 and IPv6 are supported
// Create a progress indicator
let progress = if cfg!(not(test)) {
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(self.config.max_hops as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} hops")
.unwrap()
.progress_chars("█▓▒░ "),
);
Some(pb)
} else {
None
};
// For ICMP traceroute, we'll use a UDP socket with TTL to trigger ICMP responses
for ttl in 1..=self.config.max_hops {
// Create a hop result entry
let mut hop_result = HopResult {
hop: ttl,
ip: None,
hostname: None,
latencies: vec![None; self.config.queries as usize],
avg_latency: None,
is_destination: false,
asn: None,
location: None,
};
// Send multiple queries for this hop
let mut responses = 0;
let mut total_latency = Duration::new(0, 0);
for q in 0..self.config.queries {
// Create a UDP socket to send packets with appropriate binding for IPv4 or IPv6
let bind_addr = match target_ip {
IpAddr::V4(_) => "0.0.0.0:0",
IpAddr::V6(_) => "[::]:0",
};
let send_socket = match std::net::UdpSocket::bind(bind_addr) {
Ok(s) => {
// Set TTL
if let Err(e) = s.set_ttl(ttl.into()) {
warn!("Failed to set TTL: {}", e);
continue;
}
s
}
Err(e) => {
warn!("Failed to create send socket: {}", e);
continue;
}
};
// Create a separate socket to listen for ICMP responses
let recv_socket = match std::net::UdpSocket::bind(bind_addr) {
Ok(s) => {
// Set read timeout
if let Err(e) =
s.set_read_timeout(Some(Duration::from_millis(self.config.timeout_ms)))
{
warn!("Failed to set read timeout: {}", e);
continue;
}
s
}
Err(e) => {
warn!("Failed to create receive socket: {}", e);
continue;
}
};
// Create a simple payload
let mut payload = vec![0u8; self.config.payload_size];
rand::rng().fill(&mut payload[..]);
// Start timing
let start_time = Instant::now();
// Send the packet to an unreachable port to trigger ICMP responses
let dest_port = 33434 + (ttl as u16);
if let Err(e) = send_socket.send_to(&payload, SocketAddr::new(target_ip, dest_port))
{
warn!("Failed to send packet: {}", e);
continue;
}
// Try to receive a response on both sockets
let mut buf = [0u8; 1024];
let mut got_response = false;
// First try the send socket which might get ICMP errors
match send_socket.recv_from(&mut buf) {
Ok((_, addr)) => {
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.ip().to_string());
// Check if this is the destination
if addr.ip() == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
got_response = true;
}
Err(e) => {
debug!("No response on send socket: {}", e);
}
}
// If no response on send socket, try the receive socket
if !got_response {
match recv_socket.recv_from(&mut buf) {
Ok((_, addr)) => {
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.ip().to_string());
// Check if this is the destination
if addr.ip() == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
}
Err(e) => {
debug!("No response from packet: {}", e);
// Try to extract router IP from error (platform specific)
if let Some(router_ip) = Self::extract_router_ip_from_error(&e) {
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(router_ip.to_string());
responses += 1;
total_latency += latency;
}
}
}
}
// Wait between queries
if q < self.config.queries - 1 {
tokio::time::sleep(Duration::from_millis(self.config.send_time_ms)).await;
}
}
// Calculate average latency if we got responses
if responses > 0 {
hop_result.avg_latency = Some(total_latency / responses);
}
// Resolve hostname if we have an IP and hostname resolution is enabled
if let Some(ip_str) = &hop_result.ip {
if self.config.resolve_hostnames {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
hop_result.hostname = self.resolve_hostname(ip).await;
}
}
}
// Store the result
{
let mut results = self.results.lock().await;
results.insert(ttl, hop_result.clone());
}
// Update progress
if let Some(pb) = &progress {
pb.inc(1);
}
// If we reached the destination, we're done
if hop_result.is_destination {
break;
}
// Wait between TTLs
if ttl < self.config.max_hops {
tokio::time::sleep(Duration::from_millis(self.config.ttl_time_ms)).await;
}
}
// Finish progress
if let Some(pb) = &progress {
pb.finish_and_clear();
}
Ok(())
}
/// Alternative ICMP traceroute implementation using a different approach
async fn trace_icmp_alternative(&self, target_ip: IpAddr) -> Result<(), NtraceError> {
// Both IPv4 and IPv6 are supported
// Create a progress indicator
let progress = if cfg!(not(test)) {
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(self.config.max_hops as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} hops")
.unwrap()
.progress_chars("█▓▒░ "),
);
Some(pb)
} else {
None
};
// For each TTL value
for ttl in 1..=self.config.max_hops {
// Create a hop result entry
let mut hop_result = HopResult {
hop: ttl,
ip: None,
hostname: None,
latencies: vec![None; self.config.queries as usize],
avg_latency: None,
is_destination: false,
asn: None,
location: None,
};
// Send multiple queries for this hop
let mut responses = 0;
let mut total_latency = Duration::new(0, 0);
for q in 0..self.config.queries {
// Create a listener socket first
let listener = match std::net::UdpSocket::bind("0.0.0.0:0") {
Ok(s) => {
if let Err(e) =
s.set_read_timeout(Some(Duration::from_millis(self.config.timeout_ms)))
{
warn!("Failed to set read timeout: {}", e);
continue;
}
s
}
Err(e) => {
warn!("Failed to create listener socket: {}", e);
continue;
}
};
// Get the port we're bound to
let local_addr = match listener.local_addr() {
Ok(addr) => addr,
Err(e) => {
warn!("Failed to get local address: {}", e);
continue;
}
};
let local_port = local_addr.port();
// Create a sender socket
let sender = match std::net::UdpSocket::bind("0.0.0.0:0") {
Ok(s) => {
// Set TTL
if let Err(e) = s.set_ttl(ttl.into()) {
warn!("Failed to set TTL: {}", e);
continue;
}
s
}
Err(e) => {
warn!("Failed to create sender socket: {}", e);
continue;
}
};
// Create a simple payload
let mut payload = vec![0u8; self.config.payload_size];
rand::rng().fill(&mut payload[..]);
// Start timing
let start_time = Instant::now();
// Send to an unreachable port at the target
// The key is to use the same port as our listener, which helps with ICMP error correlation
if let Err(e) = sender.send_to(&payload, SocketAddr::new(target_ip, local_port)) {
warn!("Failed to send packet: {}", e);
continue;
}
// Try to receive a response
let mut buf = [0u8; 1024];
match listener.recv_from(&mut buf) {
Ok((_, addr)) => {
// Got a response
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.ip().to_string());
// Check if this is the destination
if addr.ip() == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
}
Err(e) => {
debug!("No response from packet: {}", e);
// Try a different approach - send a second packet to see if we get a response
// This can sometimes work when the first approach fails
let second_socket = match std::net::UdpSocket::bind("0.0.0.0:0") {
Ok(s) => s,
Err(_) => continue,
};
if let Err(_) =
second_socket.connect(SocketAddr::new(target_ip, 33434 + ttl as u16))
{
// Check the error kind - it might contain the router's IP
if let Some(router_ip) = extract_ip_from_last_error() {
if let Ok(_ip_addr) = router_ip.parse::<IpAddr>() {
let latency = start_time.elapsed();
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(router_ip);
responses += 1;
total_latency += latency;
}
}
}
}
}
// Wait between queries
if q < self.config.queries - 1 {
tokio::time::sleep(Duration::from_millis(self.config.send_time_ms)).await;
}
}
// Calculate average latency if we got responses
if responses > 0 {
hop_result.avg_latency = Some(total_latency / responses);
}
// Resolve hostname if we have an IP and hostname resolution is enabled
if let Some(ip_str) = &hop_result.ip {
if self.config.resolve_hostnames {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
hop_result.hostname = self.resolve_hostname(ip).await;
}
}
}
// Store the result
{
let mut results = self.results.lock().await;
results.insert(ttl, hop_result.clone());
}
// Update progress
if let Some(pb) = &progress {
pb.inc(1);
}
// If we reached the destination, we're done
if hop_result.is_destination {
break;
}
// Wait between TTLs
if ttl < self.config.max_hops {
tokio::time::sleep(Duration::from_millis(self.config.ttl_time_ms)).await;
}
}
// Finish progress
if let Some(pb) = &progress {
pb.finish_and_clear();
}
Ok(())
}
/// Perform a raw socket based ICMP traceroute similar to inetutils-traceroute
async fn trace_icmp_raw(&self, target_ip: IpAddr) -> Result<(), NtraceError> {
use pnet::packet::Packet;
use pnet::packet::icmp::{IcmpTypes, echo_request};
use pnet::packet::icmpv6::{Icmpv6Types, echo_request as icmpv6_echo_request};
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::transport::TransportChannelType::Layer4;
use pnet::transport::TransportProtocol::{Ipv4, Ipv6};
use pnet::transport::{icmp_packet_iter, icmpv6_packet_iter, transport_channel};
// Both IPv4 and IPv6 are supported
let is_ipv6 = matches!(target_ip, IpAddr::V6(_));
// Create a progress indicator
let progress = if cfg!(not(test)) {
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(self.config.max_hops as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} hops")
.unwrap()
.progress_chars("█▓▒░ "),
);
Some(pb)
} else {
None
};
// Create a transport channel for ICMP (IPv4 or IPv6)
let (mut tx, mut rx) = if is_ipv6 {
let protocol = Layer4(Ipv6(IpNextHeaderProtocols::Icmpv6));
match transport_channel(4096, protocol) {
Ok((tx, rx)) => (tx, rx),
Err(e) => {
// Check if this is a permission error
if e.kind() == std::io::ErrorKind::PermissionDenied {
return Err(NtraceError::PermissionDenied2(
"Permission denied creating ICMPv6 socket. Try running with sudo or as administrator.".to_string()
));
} else {
return Err(NtraceError::IcmpError(format!(
"Failed to create IPv6 transport channel: {}",
e
)));
}
}
}
} else {
let protocol = Layer4(Ipv4(IpNextHeaderProtocols::Icmp));
match transport_channel(4096, protocol) {
Ok((tx, rx)) => (tx, rx),
Err(e) => {
// Check if this is a permission error
if e.kind() == std::io::ErrorKind::PermissionDenied {
return Err(NtraceError::PermissionDenied2(
"Permission denied creating ICMP socket. Try running with sudo or as administrator.".to_string()
));
} else {
return Err(NtraceError::IcmpError(format!(
"Failed to create IPv4 transport channel: {}",
e
)));
}
}
}
};
// We'll handle the packet reception directly instead of using iterators
// This avoids the double mutable borrow of rx
// For each TTL value
for ttl in 1..=self.config.max_hops {
// Create a hop result entry
let mut hop_result = HopResult {
hop: ttl,
ip: None,
hostname: None,
latencies: vec![None; self.config.queries as usize],
avg_latency: None,
is_destination: false,
asn: None,
location: None,
};
// Send multiple queries for this hop
let mut responses = 0;
let mut total_latency = Duration::new(0, 0);
for q in 0..self.config.queries {
if is_ipv6 {
// Create an ICMPv6 echo request packet
// Buffer for the ICMPv6 packet
let mut echo_packet = [0u8; 64];
// Fill the payload with some data first
let payload_offset =
icmpv6_echo_request::MutableEchoRequestPacket::minimum_packet_size();
let payload_size = self
.config
.payload_size
.min(echo_packet.len() - payload_offset);
rand::rng()
.fill(&mut echo_packet[payload_offset..payload_offset + payload_size]);
// Now create the packet
let mut icmpv6_packet =
icmpv6_echo_request::MutableEchoRequestPacket::new(&mut echo_packet)
.ok_or_else(|| {
NtraceError::Protocol("Failed to create ICMPv6 packet".to_string())
})?;
// Set ICMPv6 packet fields
icmpv6_packet.set_icmpv6_type(Icmpv6Types::EchoRequest);
icmpv6_packet.set_icmpv6_code(icmpv6_echo_request::Icmpv6Codes::NoCode);
let identifier = (std::process::id() & 0xFFFF) as u16;
icmpv6_packet.set_identifier(identifier);
icmpv6_packet.set_sequence_number(q as u16);
// Calculate checksum
let checksum = pnet::util::checksum(icmpv6_packet.packet(), 1);
icmpv6_packet.set_checksum(checksum);
// Set the TTL (hop limit) on the socket
if let Err(e) = tx.set_ttl(ttl) {
warn!("Failed to set TTL for IPv6: {}", e);
if e.kind() == std::io::ErrorKind::PermissionDenied {
return Err(NtraceError::PermissionDenied2(
"Permission denied setting IPv6 TTL. Try running with sudo or as administrator.".to_string()
));
} else {
debug!("Non-critical TTL setting error: {}", e);
continue;
}
}
// Start timing
let start_time = Instant::now();
// Send the packet
match tx.send_to(icmpv6_packet, target_ip) {
Ok(_) => {}
Err(e) => {
warn!("Failed to send ICMPv6 packet: {}", e);
match e.kind() {
std::io::ErrorKind::PermissionDenied => {
return Err(NtraceError::PermissionDenied2(
"Permission denied sending ICMPv6 packet. Try running with sudo or as administrator.".to_string()
));
}
std::io::ErrorKind::ConnectionRefused => {
debug!("Connection refused when sending ICMPv6 packet");
}
std::io::ErrorKind::NetworkUnreachable => {
return Err(NtraceError::IcmpError(
"Network unreachable for target IP".to_string(),
));
}
_ => {
debug!("Error sending ICMPv6 packet: {}", e);
}
}
continue;
}
}
// Set a timeout for receiving
let timeout = Duration::from_millis(self.config.timeout_ms);
let start_wait = Instant::now();
// Wait for a response
let mut got_response = false;
while start_wait.elapsed() < timeout && !got_response {
// Use the icmpv6_packet_iter directly on rx
let mut iter = icmpv6_packet_iter(&mut rx);
match iter.next_with_timeout(timeout) {
Ok(Some((packet, addr))) => {
let latency = start_time.elapsed();
// Check if this is a TTL exceeded message or echo reply
if packet.get_icmpv6_type() == Icmpv6Types::TimeExceeded
|| (packet.get_icmpv6_type() == Icmpv6Types::EchoReply
&& packet.get_icmpv6_code().0
== icmpv6_echo_request::Icmpv6Codes::NoCode.0)
{
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.to_string());
// Check if this is the destination
if addr == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
got_response = true;
}
}
Ok(None) => {
// Timeout reached
break;
}
Err(e) => {
debug!("Error receiving IPv6 packet: {}", e);
break;
}
}
}
} else {
// Create an ICMP echo request packet
// Buffer for the ICMP packet
let mut echo_packet = [0u8; 64];
// Fill the payload with some data first
let payload_offset =
echo_request::MutableEchoRequestPacket::minimum_packet_size();
let payload_size = self
.config
.payload_size
.min(echo_packet.len() - payload_offset);
rand::rng()
.fill(&mut echo_packet[payload_offset..payload_offset + payload_size]);
// Now create the packet
let mut icmp_packet =
echo_request::MutableEchoRequestPacket::new(&mut echo_packet).ok_or_else(
|| NtraceError::Protocol("Failed to create ICMP packet".to_string()),
)?;
// Set ICMP packet fields
icmp_packet.set_icmp_type(IcmpTypes::EchoRequest);
icmp_packet.set_icmp_code(echo_request::IcmpCodes::NoCode);
let identifier = (std::process::id() & 0xFFFF) as u16;
icmp_packet.set_identifier(identifier);
icmp_packet.set_sequence_number(q as u16);
// Calculate checksum
let checksum = pnet::util::checksum(icmp_packet.packet(), 1);
icmp_packet.set_checksum(checksum);
// Set the TTL on the socket
if let Err(e) = tx.set_ttl(ttl) {
warn!("Failed to set TTL for IPv4: {}", e);
if e.kind() == std::io::ErrorKind::PermissionDenied {
return Err(NtraceError::PermissionDenied2(
"Permission denied setting IPv4 TTL. Try running with sudo or as administrator.".to_string()
));
} else {
debug!("Non-critical TTL setting error: {}", e);
continue;
}
}
// Start timing
let start_time = Instant::now();
// Send the packet
match tx.send_to(icmp_packet, target_ip) {
Ok(_) => {}
Err(e) => {
warn!("Failed to send ICMP packet: {}", e);
match e.kind() {
std::io::ErrorKind::PermissionDenied => {
return Err(NtraceError::PermissionDenied2(
"Permission denied sending ICMP packet. Try running with sudo or as administrator.".to_string()
));
}
std::io::ErrorKind::ConnectionRefused => {
debug!("Connection refused when sending ICMP packet");
}
std::io::ErrorKind::NetworkUnreachable => {
return Err(NtraceError::IcmpError(
"Network unreachable for target IP".to_string(),
));
}
_ => {
debug!("Error sending ICMP packet: {}", e);
}
}
continue;
}
}
// Set a timeout for receiving
let timeout = Duration::from_millis(self.config.timeout_ms);
let start_wait = Instant::now();
// Wait for a response
let mut got_response = false;
while start_wait.elapsed() < timeout && !got_response {
// Use the icmp_packet_iter directly on rx
let mut iter = icmp_packet_iter(&mut rx);
match iter.next_with_timeout(timeout) {
Ok(Some((packet, addr))) => {
let latency = start_time.elapsed();
// Check if this is a TTL exceeded message or echo reply
if packet.get_icmp_type() == IcmpTypes::TimeExceeded
|| (packet.get_icmp_type() == IcmpTypes::EchoReply
&& packet.get_icmp_code().0
== echo_request::IcmpCodes::NoCode.0)
{
hop_result.latencies[q as usize] = Some(latency);
hop_result.ip = Some(addr.to_string());
// Check if this is the destination
if addr == target_ip {
hop_result.is_destination = true;
}
responses += 1;
total_latency += latency;
got_response = true;
}
}
Ok(None) => {
// Timeout reached
break;
}
Err(e) => {
debug!("Error receiving packet: {}", e);
break;
}
}
}
}
// Wait between queries
if q < self.config.queries - 1 {
tokio::time::sleep(Duration::from_millis(self.config.send_time_ms)).await;
}
}
// Calculate average latency if we got responses
if responses > 0 {
hop_result.avg_latency = Some(total_latency / responses);
}
// Resolve hostname if we have an IP and hostname resolution is enabled
if let Some(ip_str) = &hop_result.ip {
if self.config.resolve_hostnames {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
hop_result.hostname = self.resolve_hostname(ip).await;
}
}
}
// Store the result
{
let mut results = self.results.lock().await;
results.insert(ttl, hop_result.clone());
}
// Update progress
if let Some(pb) = &progress {
pb.inc(1);
}
// If we reached the destination, we're done
if hop_result.is_destination {
break;
}
// Wait between TTLs
if ttl < self.config.max_hops {
tokio::time::sleep(Duration::from_millis(self.config.ttl_time_ms)).await;
}
}
// Finish progress
if let Some(pb) = &progress {
pb.finish_and_clear();
}
Ok(())
}
/// Extract router IP from socket error
fn extract_router_ip_from_error(error: &std::io::Error) -> Option<IpAddr> {
// On most systems, we can't easily extract the router IP from the error
// This is a platform specific operation that would require raw socket handling
// Try to get the error number for more specific handling
let errno = error.raw_os_error();
// Platform specific handling
#[cfg(target_os = "linux")]
{
// On Linux, for ICMP Time Exceeded messages, we can try to extract the IP
// from the error message or use socket options to get the original sender
// EAGAIN
if let Some(11) = errno {
// For Linux, try to extract from error message first
let error_string = error.to_string();
if let Some(ip_str) = extract_ip_from_string(&error_string) {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
return Some(ip);
}
}
// If that fails, try to get the IP from the last socket error
if let Some(ip_str) = extract_ip_from_last_error() {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
return Some(ip);
}
}
}
}
#[cfg(target_os = "windows")]
{
// Windows specific handling
let error_string = error.to_string();
if let Some(ip_str) = extract_ip_from_string(&error_string) {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
return Some(ip);
}
}
}
#[cfg(target_os = "macos")]
{
// macOS specific handling
let error_string = error.to_string();
if let Some(ip_str) = extract_ip_from_string(&error_string) {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
return Some(ip);
}
}
}
// Generic fallback for all platforms
let error_string = error.to_string();
if let Some(ip_str) = extract_ip_from_string(&error_string) {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
return Some(ip);
}
}
None
}
}
/// Helper function to try to extract an IP address from a string
fn extract_ip_from_string(s: &str) -> Option<String> {
// Try to extract IPv4 address first (look for patterns like xxx.xxx.xxx.xxx)
let ipv4_re = regex::Regex::new(r"\b(?:\d{1,3}\.){3}\d{1,3}\b").ok()?;
if let Some(m) = ipv4_re.find(s) {
return Some(m.as_str().to_string());
}
// If no IPv4 address found, try to extract IPv6 address
// This is a simplified pattern and might not catch all valid IPv6 formats
let ipv6_re = regex::Regex::new(r"\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)").ok()?;
ipv6_re.find(s).map(|m| m.as_str().to_string())
}
/// Helper function to try to extract an IP from the last socket error
fn extract_ip_from_last_error() -> Option<String> {
// Get the last error message
let error = std::io::Error::last_os_error().to_string();
extract_ip_from_string(&error)
}