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
use std::{
collections::HashMap,
mem::MaybeUninit,
net::{IpAddr, SocketAddr},
sync::Arc,
time::{Duration, Instant},
};
use parking_lot::Mutex;
use rand::random;
use tokio::task;
use tokio::time::{sleep, timeout};
use crate::error::{Result, Error};
use crate::icmp::{EchoReply, EchoRequest};
use crate::unix::AsyncSocket;
type Token = (u16, u16);
#[derive(Debug, Clone)]
struct Cache {
inner: Arc<Mutex<HashMap<Token, Instant>>>,
}
impl Cache {
fn new() -> Cache {
Cache {
inner: Arc::new(Mutex::new(HashMap::new())),
}
}
fn insert(&self, ident: u16, seq_cnt: u16, time: Instant) {
self.inner.lock().insert((ident, seq_cnt), time);
}
fn remove(&self, ident: u16, seq_cnt: u16) -> Option<Instant> {
self.inner.lock().remove(&(ident, seq_cnt))
}
}
#[derive(Debug, Clone)]
pub struct Pinger {
host: IpAddr,
ident: u16,
size: usize,
timeout: Duration,
socket: AsyncSocket,
cache: Cache,
}
impl Pinger {
pub fn new(host: IpAddr) -> Result<Pinger> {
Ok(Pinger {
host,
ident: random(),
size: 56,
timeout: Duration::from_secs(2),
socket: AsyncSocket::new(host)?,
cache: Cache::new(),
})
}
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub fn bind_device(&mut self, interface: Option<&[u8]>) -> Result<&mut Pinger> {
self.socket.bind_device(interface)?;
Ok(self)
}
pub fn ident(&mut self, val: u16) -> &mut Pinger {
self.ident = val;
self
}
pub fn size(&mut self, size: usize) -> &mut Pinger {
self.size = size;
self
}
pub fn timeout(&mut self, timeout: Duration) -> &mut Pinger {
self.timeout = timeout;
self
}
async fn recv_reply(&self, seq_cnt: u16) -> Result<(EchoReply, Duration)> {
let mut buffer = [MaybeUninit::new(0); 2048];
loop {
let size = self.socket.recv(&mut buffer).await?;
let buf = unsafe { assume_init(&buffer[..size]) };
match EchoReply::decode(self.host, buf) {
Ok(reply) => {
if reply.identifier == self.ident && reply.sequence == seq_cnt {
if let Some(ins) = self.cache.remove(self.ident, seq_cnt) {
return Ok((reply, Instant::now() - ins));
}
}
continue;
}
Err(Error::NotEchoReply(_)) => continue,
Err(Error::NotV6EchoReply(_)) => continue,
Err(Error::OtherICMP) => continue,
Err(e) => {
return Err(e);
}
}
}
}
pub async fn ping(&self, seq_cnt: u16) -> Result<(EchoReply, Duration)> {
let sender = self.socket.clone();
let mut packet = EchoRequest::new(self.host, self.ident, seq_cnt, self.size).encode()?;
let sock_addr = SocketAddr::new(self.host, 0);
let ident = self.ident;
let cache = self.cache.clone();
task::spawn(async move {
let _size = sender
.send_to(&mut packet, &sock_addr.into())
.await
.expect("socket send packet error");
cache.insert(ident, seq_cnt, Instant::now());
});
timeout(self.timeout, self.recv_reply(seq_cnt)).await.map_err(|err| {
self.cache.remove(ident, seq_cnt);
err
}).unwrap()
}
}
unsafe fn assume_init(buf: &[MaybeUninit<u8>]) -> &[u8] {
&*(buf as *const [MaybeUninit<u8>] as *const [u8])
}