diplonat/src/igd_actor.rs

78 lines
2.1 KiB
Rust
Raw Normal View History

2020-05-21 20:25:33 +00:00
use igd::aio::*;
2020-05-22 20:01:27 +00:00
use igd::PortMappingProtocol;
use std::net::SocketAddrV4;
2020-05-21 20:25:33 +00:00
use log::*;
use anyhow::{Result, Context};
2020-05-22 20:01:27 +00:00
use tokio::{
select,
sync::watch,
time::{
self,
Duration
}};
2020-05-22 17:21:11 +00:00
use crate::messages;
2020-05-21 15:51:30 +00:00
2020-05-22 17:21:11 +00:00
pub struct IgdActor {
2020-05-22 20:01:27 +00:00
last_ports: messages::PublicExposedPorts,
2020-05-22 17:21:11 +00:00
rx_ports: watch::Receiver<messages::PublicExposedPorts>,
2020-05-21 20:25:33 +00:00
gateway: Gateway,
2020-05-22 20:01:27 +00:00
refresh: Duration,
expire: Duration,
private_ip: String
2020-05-21 20:25:33 +00:00
}
2020-05-22 17:21:11 +00:00
impl IgdActor {
2020-05-22 20:01:27 +00:00
pub async fn new(priv_ip: &str, refresh: Duration, expire: Duration, rxp: &watch::Receiver<messages::PublicExposedPorts>) -> Result<Self> {
2020-05-21 20:25:33 +00:00
let gw = search_gateway(Default::default())
.await
.context("Failed to find gateway")?;
info!("Gateway: {}", gw);
let ctx = Self {
2020-05-22 17:21:11 +00:00
gateway: gw,
2020-05-22 20:01:27 +00:00
rx_ports: rxp.clone(),
private_ip: priv_ip.to_string(),
refresh: refresh,
expire: expire
2020-05-21 20:25:33 +00:00
};
2020-05-22 17:21:11 +00:00
2020-05-21 20:25:33 +00:00
return Ok(ctx);
2020-05-21 15:51:30 +00:00
}
2020-05-21 20:25:33 +00:00
2020-05-22 17:21:11 +00:00
pub async fn listen(&mut self) -> Result<()> {
2020-05-22 20:01:27 +00:00
let mut interval = time::interval(self.refresh);
loop {
let res = select! {
msg = self.rx_ports.recv() => match msg {
Some(ports) => { self.last_ports = ports ; return self.do_igd().await; } ,
None => return Ok(()) // Sender dropped, terminate loop.
}
_ = interval.tick() => self.do_igd().await
};
match res {
Ok(()) => debug!("Successfully updated IGD"),
Err(e) => error!("An error occured while updating IGD. {}. {:#?}", e, self.last_ports),
}
}
}
pub async fn do_igd(&self) -> Result<()> {
let actions = [
(PortMappingProtocol::TCP, self.last_ports.tcp_ports),
(PortMappingProtocol::UDP, self.last_ports.udp_ports)
];
for (proto, list) in &actions {
for port in list {
let service_str = format!("{}:{}", self.private_ip, port);
let service: SocketAddrV4 = service_str.parse()?.context("Invalid socket address");
self.gateway.add_port(*proto, *port, service, self.expire.as_secs() as u32, "diplonat").await?;
debug!("IGD request successful for {:#?} {}", proto, service);
}
2020-05-22 17:21:11 +00:00
}
2020-05-22 20:01:27 +00:00
2020-05-21 15:51:30 +00:00
return Ok(());
}
}