Update daemon

This commit is contained in:
Jett Chen 2023-12-07 11:45:42 +08:00
parent 48aba8ccb6
commit 60e5d1f8fd
4 changed files with 23 additions and 10 deletions

View file

@ -1,13 +1,14 @@
use std::ops::Deref;
use tracing::{debug, info, warn}; use tracing::{debug, info, warn};
use DaemonResponse; use DaemonResponse;
use tun::TunInterface; use tun::tokio::TunInterface;
use crate::daemon::response::{DaemonResponseData, ServerConfig, ServerInfo}; use crate::daemon::response::{DaemonResponseData, ServerConfig, ServerInfo};
use super::*; use super::*;
pub struct DaemonInstance { pub struct DaemonInstance {
rx: async_channel::Receiver<DaemonCommand>, rx: async_channel::Receiver<DaemonCommand>,
sx: async_channel::Sender<DaemonResponse>, sx: async_channel::Sender<DaemonResponse>,
tun_interface: Option<TunInterface>, tun_interface: Option<Arc<RwLock<TunInterface>>>,
} }
impl DaemonInstance { impl DaemonInstance {
@ -19,13 +20,17 @@ impl DaemonInstance {
} }
} }
pub fn set_tun_interface(&mut self, tun_interface: Arc<RwLock<TunInterface>>) {
self.tun_interface = Some(tun_interface);
}
async fn proc_command(&mut self, command: DaemonCommand) -> Result<DaemonResponseData> { async fn proc_command(&mut self, command: DaemonCommand) -> Result<DaemonResponseData> {
info!("Daemon got command: {:?}", command); info!("Daemon got command: {:?}", command);
match command { match command {
DaemonCommand::Start(st) => { DaemonCommand::Start(st) => {
if self.tun_interface.is_none() { if self.tun_interface.is_none() {
debug!("Daemon attempting start tun interface."); debug!("Daemon attempting start tun interface.");
self.tun_interface = Some(st.tun.open()?); self.tun_interface = Some(Arc::new(RwLock::new(TunInterface::new(st.tun.open()?)?)));
info!("Daemon started tun interface"); info!("Daemon started tun interface");
} else { } else {
warn!("Got start, but tun interface already up."); warn!("Got start, but tun interface already up.");
@ -39,7 +44,7 @@ impl DaemonInstance {
info!("{:?}", ti); info!("{:?}", ti);
Ok( Ok(
DaemonResponseData::ServerInfo( DaemonResponseData::ServerInfo(
ServerInfo::try_from(ti)? ServerInfo::try_from(ti.read().await.inner.get_ref())?
) )
) )
} }

View file

@ -1,4 +1,5 @@
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::sync::Arc;
mod command; mod command;
@ -11,6 +12,7 @@ use base64::{engine::general_purpose, Engine as _};
pub use command::{DaemonCommand, DaemonStartOptions}; pub use command::{DaemonCommand, DaemonStartOptions};
use fehler::throws; use fehler::throws;
use ip_network::{IpNetwork, Ipv4Network}; use ip_network::{IpNetwork, Ipv4Network};
use tokio::sync::RwLock;
use instance::DaemonInstance; use instance::DaemonInstance;
use crate::wireguard::{StaticSecret, Peer, Interface, PublicKey}; use crate::wireguard::{StaticSecret, Peer, Interface, PublicKey};
pub use net::DaemonClient; pub use net::DaemonClient;
@ -19,6 +21,7 @@ pub use net::DaemonClient;
pub use net::start_srv; pub use net::start_srv;
pub use response::{DaemonResponseData, DaemonResponse, ServerInfo}; pub use response::{DaemonResponseData, DaemonResponse, ServerInfo};
use crate::daemon::net::listen;
#[throws] #[throws]
fn parse_key(string: &str) -> [u8; 32] { fn parse_key(string: &str) -> [u8; 32] {
@ -49,12 +52,16 @@ pub async fn daemon_main() -> Result<()> {
_tun.set_ipv4_addr(Ipv4Addr::from([10,13,13,2]))?; _tun.set_ipv4_addr(Ipv4Addr::from([10,13,13,2]))?;
_tun.set_nonblocking(true)?; _tun.set_nonblocking(true)?;
let tun = tun::tokio::TunInterface::new(_tun)?; let tun = tun::tokio::TunInterface::new(_tun)?;
let tun_ref = Arc::new(RwLock::new(tun));
let private_key = parse_secret_key("GNqIAOCRxjl/cicZyvkvpTklgQuUmGUIEkH7IXF/sEE=")?; let private_key = parse_secret_key("GNqIAOCRxjl/cicZyvkvpTklgQuUmGUIEkH7IXF/sEE=")?;
let public_key = parse_public_key("uy75leriJay0+oHLhRMpV+A5xAQ0hCJ+q7Ww81AOvT4=")?; let public_key = parse_public_key("uy75leriJay0+oHLhRMpV+A5xAQ0hCJ+q7Ww81AOvT4=")?;
let preshared_key = Some(parse_key("s7lx/mg+reVEMnGnqeyYOQkzD86n2+gYnx1M9ygi08k=")?); let preshared_key = Some(parse_key("s7lx/mg+reVEMnGnqeyYOQkzD86n2+gYnx1M9ygi08k=")?);
let endpoint = "wg.burrow.rs:51820".to_socket_addrs()?.next().unwrap(); let endpoint = "wg.burrow.rs:51820".to_socket_addrs()?.next().unwrap();
let iface = Interface::new(tun, vec![Peer {
inst.set_tun_interface(tun_ref.clone());
let iface = Interface::new(tun_ref, vec![Peer {
endpoint, endpoint,
private_key, private_key,
public_key, public_key,
@ -62,6 +69,7 @@ pub async fn daemon_main() -> Result<()> {
allowed_ips: vec![IpNetwork::V4(Ipv4Network::DEFAULT_ROUTE)], allowed_ips: vec![IpNetwork::V4(Ipv4Network::DEFAULT_ROUTE)],
}])?; }])?;
iface.run().await; tokio::try_join!(iface.run(), inst.run(), listen(commands_tx, response_rx))
.map(|_| {()});
Ok(()) Ok(())
} }

View file

@ -83,8 +83,7 @@ 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: Arc<RwLock<TunInterface>>, peers: I) -> Self {
let tun = Arc::new(RwLock::new(tun));
let pcbs: IndexedPcbs = peers let pcbs: IndexedPcbs = peers
.into_iter() .into_iter()
.map(|peer| PeerPcb::new(peer, tun.clone())) .map(|peer| PeerPcb::new(peer, tun.clone()))
@ -94,7 +93,7 @@ impl Interface {
Self { tun, pcbs } Self { tun, pcbs }
} }
pub async fn run(self) { pub async fn run(self) -> anyhow::Result<()> {
let pcbs = self.pcbs.clone(); let pcbs = self.pcbs.clone();
let tun = self.tun.clone(); let tun = self.tun.clone();
log::info!("starting interface"); log::info!("starting interface");
@ -187,5 +186,6 @@ impl Interface {
} }
log::debug!("preparing to join.."); log::debug!("preparing to join..");
join_all(tsks).await; join_all(tsks).await;
Ok(())
} }
} }

View file

@ -5,7 +5,7 @@ use tracing::instrument;
#[derive(Debug)] #[derive(Debug)]
pub struct TunInterface { pub struct TunInterface {
inner: AsyncFd<crate::TunInterface>, pub inner: AsyncFd<crate::TunInterface>,
} }
impl TunInterface { impl TunInterface {