add write to network on received packets

This commit is contained in:
Jett Chen 2023-12-07 00:51:52 +08:00
parent 4fbcdad49e
commit 48aba8ccb6
2 changed files with 13 additions and 5 deletions

View file

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

View file

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