-
Notifications
You must be signed in to change notification settings - Fork 321
/
Copy pathlib.rs
189 lines (166 loc) · 5.4 KB
/
lib.rs
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
#[cfg(unix)]
use crate::linux::{detect_linux_ping};
/// Pinger
/// This crate exposes a simple function to ping remote hosts across different operating systems.
/// Example:
/// ```no_run
/// use pinger::{ping, PingResult};
///
/// let stream = ping("tomforb.es".to_string(), None).expect("Error pinging");
/// for message in stream {
/// match message {
/// PingResult::Pong(duration, line) => println!("{:?} (line: {})", duration, line),
/// PingResult::Timeout(_) => println!("Timeout!"),
/// PingResult::Unknown(line) => println!("Unknown line: {}", line),
/// PingResult::PingExited(_code, _stderr) => {}
/// }
/// }
/// ```
use anyhow::{Context, Result};
use regex::Regex;
use std::fmt::Formatter;
use std::process::{Child, Command, ExitStatus, Stdio, Output};
use std::sync::mpsc;
use std::time::Duration;
use std::{fmt, thread};
use thiserror::Error;
#[macro_use]
extern crate lazy_static;
pub mod linux;
#[cfg(windows)]
pub mod windows;
#[cfg(test)]
mod test;
pub fn run_ping(cmd: &str, args: Vec<String>) -> Result<Output> {
Command::new(cmd)
.args(&args)
// Required to ensure that the output is formatted in the way we expect, not
// using locale specific delimiters.
.env("LANG", "C")
.env("LC_ALL", "C")
.output()
.context(|| format!("Failed to run ping with args {:?}", &args))
}
pub trait Pinger: Default {
fn start<P: Parser>(&self, target: String) -> Result<mpsc::Receiver<PingResult>>;
fn set_interval(&mut self, interval: Duration);
fn get_interval(&mut self);
fn set_interface(&mut self, interface: Option<String>);
fn ping_args(&self, target: String) -> (&str, Vec<String>) {
("ping", vec![target])
}
}
pub trait Parser: Default {
fn parse(&self, line: String) -> Option<PingResult>;
fn extract_regex(&self, regex: &Regex, line: String) -> Option<PingResult> {
let cap = regex.captures(&line)?;
let ms = cap
.name("ms")
.expect("No capture group named 'ms'")
.as_str()
.parse::<u64>()
.ok()?;
let ns = match cap.name("ns") {
None => 0,
Some(cap) => {
let matched_str = cap.as_str();
let number_of_digits = matched_str.len() as u32;
let fractional_ms = matched_str.parse::<u64>().ok()?;
fractional_ms * (10u64.pow(6 - number_of_digits))
}
};
let duration = Duration::from_millis(ms) + Duration::from_nanos(ns);
Some(PingResult::Pong(duration, line))
}
}
#[derive(Debug)]
pub enum PingResult {
Pong(Duration, String),
Timeout(String),
Unknown(String),
PingExited(ExitStatus, String),
}
impl fmt::Display for PingResult {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self {
PingResult::Pong(duration, _) => write!(f, "{duration:?}"),
PingResult::Timeout(_) => write!(f, "Timeout"),
PingResult::Unknown(_) => write!(f, "Unknown"),
PingResult::PingExited(status, stderr) => write!(f, "Exited({status}, {stderr})"),
}
}
}
#[derive(Error, Debug)]
pub enum PingDetectionError {
#[error("Could not detect ping. Stderr: {stderr:?}\nStdout: {stdout:?}")]
UnknownPing {
stderr: Vec<String>,
stdout: Vec<String>,
},
#[error(transparent)]
CommandError(#[from] anyhow::Error),
#[error("Installed ping is not supported: {alternative}")]
NotSupported { alternative: String },
}
#[derive(Error, Debug)]
pub enum PingError {
#[error("Could not detect ping command type")]
UnsupportedPing(#[from] PingDetectionError),
#[error("Invalid or unresolvable hostname {0}")]
HostnameError(String),
}
/// Start pinging a an address. The address can be either a hostname or an IP address.
pub fn ping(addr: String, interface: Option<String>) -> Result<mpsc::Receiver<PingResult>> {
ping_with_interval(addr, Duration::from_millis(200), interface)
}
/// Start pinging a an address. The address can be either a hostname or an IP address.
pub fn ping_with_interval(
addr: String,
interval: Duration,
interface: Option<String>,
) -> Result<mpsc::Receiver<PingResult>> {
#[cfg(windows)]
{
let mut p = windows::WindowsPinger::default();
p.set_interval(interval);
p.set_interface(interface);
return p.start::<windows::WindowsParser>(addr);
}
#[cfg(unix)]
{
match detect_linux_ping() {
Ok(_) => {
let mut p = linux::LinuxPinger::default();
p.set_interval(interval);
p.set_interface(interface);
p.start::<linux::LinuxParser>(addr)
}
Err(e) => Err(PingError::UnsupportedPing(e))?,
}
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::TryRecvError;
use std::thread::sleep;
#[test]
#[cfg(target_os = "linux")]
fn test() {
use super::*;
let ping_channel = ping_with_interval(
"8.8.8.8".to_string(),
Duration::from_millis(200),
None,
).unwrap();
loop {
println!("hi");
match ping_channel.try_recv() {
Ok(hi) => {
println!("{:?}", hi);
}
Err(e) => {println!("{:?}", e);}
}
sleep(Duration::from_millis(200));
}
}
}