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
use async_std::task::block_on;
use pnet::datalink::{self, channel};
use pnet::datalink::{MacAddr, NetworkInterface};
use pnet::packet::ethernet::{EtherTypes, EthernetPacket};
use pnet::packet::icmp::{IcmpPacket, IcmpTypes};
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::Packet;
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
use std::time::Duration;
use crate::dns;
pub mod interface;
use interface::{get_default_gateway, get_local_ipaddr};
pub(crate) mod packet_builder;
#[derive(Debug)]
pub struct Traceroute {
src_target: String,
target: IpAddr,
config: Config,
done: bool,
}
impl Iterator for Traceroute {
type Item = TracerouteHop;
fn next(&mut self) -> Option<Self::Item> {
if self.done
|| self
.config
.channel
.max_hops_reached(self.config.max_hops as u8)
{
return None;
}
let hop = self.calculate_next_hop();
self.done = hop
.query_result
.iter()
.filter(|ip| ip.addr.contains(&self.target.to_string()))
.next()
.is_some();
Some(hop)
}
}
impl Traceroute {
pub fn new(target: String, iface_ip: Option<IpAddr>) -> Result<Self, String> {
let destination_ip = target.parse::<IpAddr>().unwrap_or_else(|_x| {
dns::lookup_host(&target).unwrap_or(vec![target
.parse::<IpAddr>()
.unwrap_or(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)))])[0]
});
let src_ip = if let Some(ip) = iface_ip {
ip
} else {
get_local_ipaddr()?
};
if let Some(iface) = datalink::interfaces()
.into_iter()
.find(|x| x.ips.iter().find(|xx| xx.ip() == src_ip).is_some())
{
Ok(Traceroute {
src_target: target,
target: destination_ip,
config: Config::default()
.with_port(33480)
.with_max_hops(30)
.with_first_ttl(1)
.with_interface(iface)
.with_number_of_queries(3)
.with_protocol(Protocol::ICMP)
.with_timeout(3000),
done: false,
})
} else {
Err(String::from("无法找到相匹配ip的网卡"))
}
}
pub fn get_info(&self) -> String {
format!(
"src_target[ {} ] parse_target[ {} ] gateway[ {} ]",
self.src_target,
self.target,
get_default_gateway()
.and_then(|x| Ok(x.ip_addr.to_string()))
.unwrap_or("".to_owned())
)
}
pub fn perform_traceroute(&mut self) -> Vec<TracerouteHop> {
let mut hops = Vec::<TracerouteHop>::new();
for _ in 1..self.config.max_hops {
if self.done {
return hops;
}
match self.next() {
Some(hop) => hops.push(hop),
None => {}
}
}
return hops;
}
fn calculate_next_hop(&mut self) -> TracerouteHop {
let mut query_results = Vec::<TracerouteQueryResult>::new();
for _ in 0..self.config.number_of_queries {
let result = self.get_next_query_result();
if result.addr.len() == 0
|| query_results
.iter()
.filter(|query_result| query_result.addr == result.addr)
.next()
.is_none()
{
query_results.push(result)
}
}
TracerouteHop {
ttl: self.config.channel.increment_ttl(),
query_result: query_results,
}
}
fn get_next_query_result(&mut self) -> TracerouteQueryResult {
let now = std::time::SystemTime::now();
self.config.channel.send_to(self.target);
let hop_ip = self.config.channel.recv_timeout(Duration::from_secs(1));
TracerouteQueryResult {
rtt: now.elapsed().unwrap_or(Duration::from_millis(0)),
addr: if hop_ip == "*" {
vec![]
} else {
let dn = dns::lookup_addr(
&hop_ip
.parse::<IpAddr>()
.unwrap_or(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))),
)
.unwrap_or("".to_owned());
if dn == hop_ip {
vec![dn]
} else {
vec![dn, hop_ip]
}
},
}
}
}
#[derive(PartialEq, Debug)]
pub enum Protocol {
UDP,
TCP,
ICMP,
}
#[derive(Debug)]
pub(crate) struct Channel {
interface: NetworkInterface,
packet_builder: packet_builder::PacketBuilder,
payload_offset: usize,
port: u16,
ttl: u8,
seq: u16,
}
impl Default for Channel {
fn default() -> Self {
let available_interfaces = get_available_interfaces();
let default_interface = available_interfaces
.iter()
.next()
.expect("no interfaces available")
.clone();
Channel::new(default_interface, 33434, 1)
}
}
impl Channel {
pub(crate) fn new(network_interface: NetworkInterface, port: u16, ttl: u8) -> Self {
let source_ip = network_interface
.ips
.iter()
.filter(|i| i.is_ipv4())
.next()
.expect("couldn't get interface IP")
.ip()
.to_string();
let source_ip = Ipv4Addr::from_str(source_ip.as_str()).expect("malformed source ip");
let payload_offset = if cfg!(any(target_os = "macos", target_os = "ios"))
&& network_interface.is_up()
&& !network_interface.is_broadcast()
&& ((!network_interface.is_loopback() && network_interface.is_point_to_point())
|| network_interface.is_loopback())
{
if network_interface.is_loopback() {
14
} else {
0
}
} else {
0
};
Channel {
interface: network_interface.clone(),
packet_builder: packet_builder::PacketBuilder::new(
Protocol::UDP,
network_interface.mac.unwrap(),
source_ip,
),
payload_offset,
port,
ttl,
seq: 0,
}
}
pub(crate) fn change_protocol(&mut self, new_protocol: Protocol) {
self.packet_builder.protocol = new_protocol;
}
pub(crate) fn increment_ttl(&mut self) -> u8 {
self.ttl += 1;
self.ttl - 1
}
pub(crate) fn max_hops_reached(&self, max_hops: u8) -> bool {
self.ttl > max_hops
}
pub(crate) fn send_to(&mut self, destination_ip: IpAddr) {
match destination_ip {
IpAddr::V4(dst_ip) => {
let (mut tx, _) = match channel(&self.interface, Default::default()) {
Ok(pnet::datalink::Channel::Ethernet(tx, rx)) => (tx, rx),
Ok(_) => panic!("libtraceroute: unhandled util type"),
Err(e) => panic!("libtraceroute: unable to create util: {}", e),
};
let buf = self
.packet_builder
.build_packet(dst_ip, self.ttl, self.port + self.seq);
tx.send_to(&buf, None);
if self.packet_builder.protocol != Protocol::TCP {
self.seq += 1;
}
}
IpAddr::V6(_) => {}
}
}
pub(crate) fn recv_timeout(&mut self, timeout: Duration) -> String {
let processor =
async_std::task::spawn(Self::recv(self.interface.clone(), self.payload_offset));
let ip = block_on(async {
match async_std::future::timeout(timeout, processor).await {
Ok(ip) => ip,
Err(_) => String::from("*"),
}
});
ip
}
async fn recv(interface: NetworkInterface, payload_offset: usize) -> String {
loop {
match process_incoming_packet(interface.clone(), payload_offset) {
Ok(ip) => return ip,
Err(_) => {}
}
}
}
}
pub fn get_available_interfaces() -> Vec<NetworkInterface> {
let all_interfaces = pnet::datalink::interfaces();
let available_interfaces: Vec<NetworkInterface>;
available_interfaces = if cfg!(target_family = "windows") {
all_interfaces
.into_iter()
.filter(|e| {
e.mac.is_some()
&& e.mac.unwrap() != MacAddr::zero()
&& e.ips
.iter()
.filter(|ip| ip.ip().to_string() != "0.0.0.0")
.next()
.is_some()
})
.collect()
} else {
all_interfaces
.into_iter()
.filter(|e| {
e.is_up()
&& !e.is_loopback()
&& e.ips.iter().filter(|ip| ip.is_ipv4()).next().is_some()
&& e.mac.is_some()
&& e.mac.unwrap() != MacAddr::zero()
})
.collect()
};
available_interfaces
}
fn handle_icmp_packet(source: IpAddr, packet: &[u8]) -> Result<String, &'static str> {
let icmp_packet = IcmpPacket::new(packet).expect("malformed ICMP packet");
match icmp_packet.get_icmp_type() {
IcmpTypes::TimeExceeded => Ok(source.to_string()),
IcmpTypes::EchoReply => Ok(source.to_string()),
IcmpTypes::DestinationUnreachable => Ok(source.to_string()),
_ => Err("wrong packet"),
}
}
fn handle_ipv4_packet(packet: &[u8]) -> Result<String, &'static str> {
let header = Ipv4Packet::new(packet).expect("malformed IPv4 packet");
let source = IpAddr::V4(header.get_source());
let payload = header.payload();
match header.get_next_level_protocol() {
IpNextHeaderProtocols::Icmp => handle_icmp_packet(source, payload),
_ => Err("wrong packet"),
}
}
fn handle_ethernet_frame(packet: &[u8]) -> Result<String, &'static str> {
let ethernet = EthernetPacket::new(packet).expect("malformed Ethernet frame");
match ethernet.get_ethertype() {
EtherTypes::Ipv4 => return handle_ipv4_packet(ethernet.payload()),
_ => Err("wrong packet"),
}
}
fn process_incoming_packet(
interface: NetworkInterface,
payload_offset: usize,
) -> Result<String, &'static str> {
let (_, mut rx) = match channel(&interface, Default::default()) {
Ok(pnet::datalink::Channel::Ethernet(tx, rx)) => (tx, rx),
Ok(_) => panic!("libtraceroute: unhandled util type"),
Err(e) => panic!("libtraceroute: unable to create util: {}", e),
};
match rx.next() {
Ok(packet) => {
if payload_offset > 0 && packet.len() > payload_offset {
return handle_ipv4_packet(&packet[payload_offset..]);
}
return handle_ethernet_frame(packet);
}
Err(e) => panic!("libtraceroute: unable to receive packet: {}", e),
}
}
#[derive(Debug)]
pub struct Config {
port: u16,
max_hops: u32,
number_of_queries: u32,
ttl: u8,
timeout: Duration,
channel: Channel,
}
#[derive(Debug)]
pub struct TracerouteHop {
pub ttl: u8,
pub query_result: Vec<TracerouteQueryResult>,
}
#[derive(Debug)]
pub struct TracerouteQueryResult {
pub rtt: Duration,
pub addr: Vec<String>,
}
impl Default for Config {
fn default() -> Self {
Config {
port: 33434,
max_hops: 30,
number_of_queries: 3,
ttl: 1,
timeout: Duration::from_secs(1),
channel: Default::default(),
}
}
}
impl Config {
pub fn with_port(mut self, port: u16) -> Self {
self.port = port;
self
}
pub fn with_max_hops(mut self, max_hops: u32) -> Self {
self.max_hops = max_hops;
self
}
pub fn with_number_of_queries(mut self, number_of_queries: u32) -> Self {
self.number_of_queries = number_of_queries;
self
}
pub fn with_protocol(mut self, protocol: Protocol) -> Self {
self.channel.change_protocol(protocol);
self
}
pub fn with_interface(mut self, network_interface: NetworkInterface) -> Self {
self.channel = Channel::new(network_interface, self.port, self.ttl);
self
}
pub fn with_first_ttl(mut self, first_ttl: u8) -> Self {
self.ttl = first_ttl;
self
}
pub fn with_timeout(mut self, timeout: u64) -> Self {
self.timeout = Duration::from_millis(timeout);
self
}
}