Skip to content

Commit

Permalink
Fixed a number of warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
conradev committed Dec 18, 2023
1 parent 7627880 commit 104f821
Show file tree
Hide file tree
Showing 28 changed files with 144 additions and 199 deletions.
12 changes: 0 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion burrow/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ base64 = "0.21.4"
fehler = "1.0.0"
ip_network_table = "0.2.0"
ip_network = "0.4.0"
async-trait = "0.1.74"
async-channel = "2.1.1"
schemars = "0.8"
futures = "0.3.28"
Expand Down
4 changes: 0 additions & 4 deletions burrow/src/daemon/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,6 @@ 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> {
info!("Daemon got command: {:?}", command);
match command {
Expand Down
39 changes: 6 additions & 33 deletions burrow/src/daemon/mod.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,24 @@
use std::net::ToSocketAddrs;
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::Arc,
};
use std::sync::Arc;

mod command;
mod instance;
mod net;
mod response;

use anyhow::{anyhow, Error, Result};
use base64::{engine::general_purpose, Engine as _};
use anyhow::Result;
pub use command::{DaemonCommand, DaemonStartOptions};
use fehler::throws;
use instance::DaemonInstance;
use ip_network::{IpNetwork, Ipv4Network};
#[cfg(target_vendor = "apple")]
pub use net::start_srv;
pub use net::DaemonClient;
pub use response::{DaemonResponse, DaemonResponseData, ServerInfo};
use tokio::sync::RwLock;
use crate::wireguard::Config;

use crate::{
daemon::net::listen,
wireguard::{Interface, Peer, PublicKey, StaticSecret},
wireguard::{Config, Interface},
};

#[throws]
fn parse_key(string: &str) -> [u8; 32] {
let value = general_purpose::STANDARD.decode(string)?;
let mut key = [0u8; 32];
key.copy_from_slice(&value[..]);
key
}

#[throws]
fn parse_secret_key(string: &str) -> StaticSecret {
let key = parse_key(string)?;
StaticSecret::from(key)
}

#[throws]
fn parse_public_key(string: &str) -> PublicKey {
let key = parse_key(string)?;
PublicKey::from(key)
}

pub async fn daemon_main() -> Result<()> {
let (commands_tx, commands_rx) = async_channel::unbounded();
let (response_tx, response_rx) = async_channel::unbounded();
Expand All @@ -73,6 +45,7 @@ pub async fn daemon_main() -> Result<()> {
}
});

tokio::try_join!(inst_job, listen_job).map(|_| ());
Ok(())
tokio::try_join!(inst_job, listen_job)
.map(|_| ())
.map_err(|e| e.into())
}
4 changes: 2 additions & 2 deletions burrow/src/daemon/net/apple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ pub extern "C" fn start_srv() {
Ok(..) => {
info!("Server successfully started");
break
},
Err(e) => error!("Could not connect to server: {}", e)
}
Err(e) => error!("Could not connect to server: {}", e),
}
}
});
Expand Down
6 changes: 4 additions & 2 deletions burrow/src/daemon/net/systemd.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::os::fd::IntoRawFd;

use anyhow::Result;

use super::*;
use crate::daemon::DaemonResponse;
use anyhow::Result;
use std::os::fd::IntoRawFd;

pub async fn listen(
cmd_tx: async_channel::Sender<DaemonCommand>,
Expand Down
8 changes: 4 additions & 4 deletions burrow/src/daemon/net/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ use std::{
},
path::{Path, PathBuf},
};
use tracing::info;

use crate::daemon::{DaemonCommand, DaemonResponse, DaemonResponseData};
use anyhow::{anyhow, Result};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::{UnixListener, UnixStream},
};
use tracing::debug;
use tracing::{debug, info};

use super::*;
use crate::daemon::{DaemonCommand, DaemonResponse, DaemonResponseData};

#[cfg(not(target_vendor = "apple"))]
const UNIX_SOCKET_PATH: &str = "/run/burrow.sock";
Expand All @@ -36,7 +36,7 @@ fn fetch_socket_path() -> Option<PathBuf> {
for path in tries {
let path = PathBuf::from(path);
if path.exists() {
return Some(path);
return Some(path)
}
}
None
Expand Down
3 changes: 2 additions & 1 deletion burrow/src/daemon/net/windows.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::*;
use anyhow::Result;

use super::*;
use crate::daemon::DaemonResponse;

pub async fn listen(
Expand Down
7 changes: 3 additions & 4 deletions burrow/src/daemon/response.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tun::TunInterface;
use anyhow::anyhow;

#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
pub struct DaemonResponse {
Expand All @@ -19,9 +18,9 @@ impl DaemonResponse {
}
}

impl Into<DaemonResponse> for DaemonResponseData {
fn into(self) -> DaemonResponse {
DaemonResponse::new(Ok::<DaemonResponseData, String>(self))
impl From<DaemonResponseData> for DaemonResponse {
fn from(val: DaemonResponseData) -> Self {
DaemonResponse::new(Ok::<DaemonResponseData, String>(val))
}
}

Expand Down
7 changes: 6 additions & 1 deletion burrow/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ pub mod wireguard;
mod daemon;
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
pub use daemon::{
DaemonClient, DaemonCommand, DaemonResponse, DaemonResponseData, DaemonStartOptions, ServerInfo,
DaemonClient,
DaemonCommand,
DaemonResponse,
DaemonResponseData,
DaemonStartOptions,
ServerInfo,
};

#[cfg(target_vendor = "apple")]
Expand Down
4 changes: 2 additions & 2 deletions burrow/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,6 @@ fn system_log() -> Result<Option<OsLogger>> {
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
pub fn main(){
pub fn main() {
eprintln!("This platform is not supported currently.")
}
}
32 changes: 15 additions & 17 deletions burrow/src/wireguard/config.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::wireguard::{Interface as WgInterface, Peer as WgPeer};
use std::{net::ToSocketAddrs, str::FromStr};

use anyhow::{anyhow, Error, Result};
use base64::engine::general_purpose;
use base64::Engine;
use base64::{engine::general_purpose, Engine};
use fehler::throws;
use ip_network::IpNetwork;
use std::net::ToSocketAddrs;
use std::str::FromStr;
use x25519_dalek::{PublicKey, StaticSecret};

use crate::wireguard::{Interface as WgInterface, Peer as WgPeer};

#[throws]
fn parse_key(string: &str) -> [u8; 32] {
let value = general_purpose::STANDARD.decode(string)?;
Expand Down Expand Up @@ -68,12 +68,11 @@ impl TryFrom<Config> for WgInterface {
endpoint: p
.endpoint
.to_socket_addrs()?
.filter(|sock| sock.is_ipv4())
.next()
.find(|sock| sock.is_ipv4())
.ok_or(anyhow!("DNS Lookup Fails!"))?,
preshared_key: match &p.preshared_key {
None => Ok(None),
Some(k) => parse_key(k).map(|res| Some(res)),
Some(k) => parse_key(k).map(Some),
}?,
allowed_ips: p
.allowed_ips
Expand All @@ -86,29 +85,28 @@ impl TryFrom<Config> for WgInterface {
})
})
.collect::<Result<Vec<WgPeer>>>()?;
Ok(WgInterface::new(wg_peers)?)
WgInterface::new(wg_peers)
}
}


impl Default for Config {
fn default() -> Self {
Self{
interface: Interface{
Self {
interface: Interface {
private_key: "GNqIAOCRxjl/cicZyvkvpTklgQuUmGUIEkH7IXF/sEE=".into(),
address: "10.13.13.2/24".into(),
listen_port: 51820,
dns: Default::default(),
mtu: Default::default()
mtu: Default::default(),
},
peers: vec![Peer{
peers: vec![Peer {
endpoint: "wg.burrow.rs:51820".into(),
allowed_ips: vec!["8.8.8.8/32".into()],
public_key: "uy75leriJay0+oHLhRMpV+A5xAQ0hCJ+q7Ww81AOvT4=".into(),
preshared_key: Some("s7lx/mg+reVEMnGnqeyYOQkzD86n2+gYnx1M9ygi08k=".into()),
persistent_keepalive: Default::default(),
name: Default::default()
}]
name: Default::default(),
}],
}
}
}
}
41 changes: 9 additions & 32 deletions burrow/src/wireguard/iface.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,15 @@
use std::{net::IpAddr, sync::Arc, time::Duration};
use std::{net::IpAddr, sync::Arc};

use anyhow::Error;
use async_trait::async_trait;
use fehler::throws;
use futures::{future::join_all, FutureExt};
use futures::future::join_all;
use ip_network_table::IpNetworkTable;
use tokio::{sync::RwLock, task::JoinHandle, time::timeout};
use tokio::sync::RwLock;
use tracing::{debug, error};
use tun::tokio::TunInterface;

use super::{noise::Tunnel, Peer, PeerPcb};

#[async_trait]
pub trait PacketInterface {
async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, tokio::io::Error>;
async fn send(&mut self, buf: &[u8]) -> Result<usize, tokio::io::Error>;
}

#[async_trait]
impl PacketInterface for tun::tokio::TunInterface {
async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, tokio::io::Error> {
self.recv(buf).await
}

async fn send(&mut self, buf: &[u8]) -> Result<usize, tokio::io::Error> {
self.send(buf).await
}
}

struct IndexedPcbs {
pcbs: Vec<Arc<PeerPcb>>,
allowed_ips: IpNetworkTable<usize>,
Expand All @@ -44,7 +26,7 @@ impl IndexedPcbs {
pub fn insert(&mut self, pcb: PeerPcb) {
let idx: usize = self.pcbs.len();
for allowed_ip in pcb.allowed_ips.iter() {
self.allowed_ips.insert(allowed_ip.clone(), idx);
self.allowed_ips.insert(*allowed_ip, idx);
}
self.pcbs.insert(idx, Arc::new(pcb));
}
Expand All @@ -53,10 +35,6 @@ impl IndexedPcbs {
let (_, &idx) = self.allowed_ips.longest_match(addr)?;
Some(idx)
}

pub async fn connect(&self, idx: usize, handle: JoinHandle<()>) {
self.pcbs[idx].handle.write().await.replace(handle);
}
}

impl FromIterator<PeerPcb> for IndexedPcbs {
Expand All @@ -78,7 +56,7 @@ impl Interface {
pub fn new<I: IntoIterator<Item = Peer>>(peers: I) -> Self {
let pcbs: IndexedPcbs = peers
.into_iter()
.map(|peer| PeerPcb::new(peer))
.map(PeerPcb::new)
.collect::<Result<_, _>>()?;

let pcbs = Arc::new(pcbs);
Expand Down Expand Up @@ -106,7 +84,7 @@ impl Interface {
Ok(len) => &buf[..len],
Err(e) => {
error!("Failed to read from interface: {}", e);
continue;
continue
}
};
debug!("Read {} bytes from interface", src.len());
Expand All @@ -117,7 +95,7 @@ impl Interface {
Some(addr) => addr,
None => {
debug!("No destination found");
continue;
continue
}
};

Expand All @@ -136,7 +114,7 @@ impl Interface {
}
Err(e) => {
log::error!("Failed to send packet {}", e);
continue;
continue
}
};
}
Expand All @@ -160,12 +138,11 @@ impl Interface {
let tsk = async move {
if let Err(e) = pcb.open_if_closed().await {
log::error!("failed to open pcb: {}", e);
return;
return
}
let r2 = pcb.run(tun).await;
if let Err(e) = r2 {
log::error!("failed to run pcb: {}", e);
return;
} else {
debug!("pcb ran successfully");
}
Expand Down
Loading

0 comments on commit 104f821

Please sign in to comment.