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
use crate::sources::interfaces::{IpFuture, IpResult, Source};
use igd;
use std::pin::Pin;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::task::{Poll, Waker};
use std::thread;
use log::trace;
use std::net::IpAddr;
#[derive(Debug, Clone)]
pub struct IGD {}
impl IGD {
pub fn source() -> Box<dyn Source> {
Box::new(IGD {})
}
}
impl Source for IGD {
fn get_ip<'a>(&'a self) -> IpFuture<'a> {
let (tx, rx) = mpsc::channel();
let future = IGDFuture {
rx: rx,
waker: Arc::new(Mutex::from(None)),
};
future.run(tx);
Box::pin(future)
}
fn box_clone(&self) -> Box<dyn Source> {
Box::new(self.clone())
}
}
struct IGDFuture {
rx: mpsc::Receiver<IpResult>,
waker: Arc<Mutex<Option<Waker>>>,
}
impl std::fmt::Display for IGD {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "IGD")
}
}
impl IGDFuture {
pub fn run(&self, tx: mpsc::Sender<IpResult>) {
let waker = self.waker.clone();
thread::spawn(move || {
trace!("IGD Future thread started");
fn inner() -> IpResult {
let gateway = igd::search_gateway(Default::default())?;
let ip = gateway.get_external_ip()?;
return Ok(IpAddr::from(ip));
}
let result = inner();
log::debug!("IGD task completed: {:?}", result);
let r = tx.send(IpResult::from(result));
log::debug!("Send result: {:?}", r);
if let Some(waker) = waker.lock().unwrap().take() {
waker.wake();
}
});
}
}
impl std::future::Future for IGDFuture {
type Output = IpResult;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
let r = self.rx.try_recv();
match r {
Err(_) => {
let mut waker = self.waker.lock().unwrap();
*waker = Some(cx.waker().clone());
Poll::Pending
}
Ok(x) => Poll::Ready(x),
}
}
}