add write to network on received packets

This commit is contained in:
Jett Chen 2023-12-07 00:51:52 +08:00
parent 5e4491105a
commit 5226326caa
2 changed files with 13 additions and 5 deletions

View file

@ -84,12 +84,12 @@ pub struct Interface {
impl Interface {
#[throws]
pub fn new<I: IntoIterator<Item = Peer>>(tun: TunInterface, peers: I) -> Self {
let mut pcbs: IndexedPcbs = peers
let tun = Arc::new(RwLock::new(tun));
let pcbs: IndexedPcbs = peers
.into_iter()
.map(|peer| PeerPcb::new(peer))
.map(|peer| PeerPcb::new(peer, tun.clone()))
.collect::<Result<_, _>>()?;
let tun = Arc::new(RwLock::new(tun));
let pcbs = Arc::new(pcbs);
Self { tun, pcbs }
}

View file

@ -13,6 +13,7 @@ use tokio::{net::UdpSocket, task::JoinHandle};
use tokio::sync::{Mutex, RwLock};
use tokio::time::timeout;
use uuid::uuid;
use tun::tokio::TunInterface;
use super::{
iface::PacketInterface,
@ -27,11 +28,12 @@ pub struct PeerPcb {
pub handle: Option<JoinHandle<()>>,
socket: Option<UdpSocket>,
tunnel: RwLock<Tunnel>,
tun_interface: Arc<RwLock<TunInterface>>
}
impl PeerPcb {
#[throws]
pub fn new(peer: Peer) -> Self {
pub fn new(peer: Peer, tun_interface: Arc<RwLock<TunInterface>>) -> Self {
let tunnel = RwLock::new(Tunnel::new(peer.private_key, peer.public_key, peer.preshared_key, None, 1, None)
.map_err(|s| anyhow::anyhow!("{}", s))?);
@ -41,6 +43,7 @@ impl PeerPcb {
handle: None,
socket: None,
tunnel,
tun_interface
}
}
@ -102,9 +105,14 @@ impl PeerPcb {
}
TunnResult::WriteToTunnelV4(packet, addr) => {
tracing::debug!("WriteToTunnelV4: {:?}, {:?}", packet, addr);
self.tun_interface.read().await.send(packet).await?;
continue;
}
TunnResult::WriteToTunnelV6(packet, addr) => {
tracing::debug!("WriteToTunnelV6: {:?}, {:?}", packet, addr);
self.tun_interface.read().await.send(packet).await?;
continue;
}
e => panic!("Unexpected result from decapsulate: {:?}", e),
}
}
return Ok(len)