From 46d76b80c6b1b3b1c549b770b1a5ba791b49da8a Mon Sep 17 00:00:00 2001 From: Mathias Hall-Andersen Date: Sat, 31 Aug 2019 20:25:16 +0200 Subject: Reduce number of type parameters in router Merge multiple related type parameters into trait, allowing for easier refactoring and better maintainability. --- src/handshake/noise.rs | 2 -- src/main.rs | 40 ++++++++++++++++++++++++++++++++- src/router/device.rs | 60 +++++++++++++++++++++++++++----------------------- src/router/messages.rs | 4 ++-- src/router/mod.rs | 2 +- src/router/peer.rs | 48 ++++++++++++++++++++-------------------- src/router/types.rs | 23 +++++++++++++++++++ src/router/workers.rs | 30 +++++++++++++------------ 8 files changed, 137 insertions(+), 72 deletions(-) diff --git a/src/handshake/noise.rs b/src/handshake/noise.rs index 1e7c50d..9fc0eb4 100644 --- a/src/handshake/noise.rs +++ b/src/handshake/noise.rs @@ -1,5 +1,3 @@ -#![allow(dead_code)] - // DH use x25519_dalek::PublicKey; use x25519_dalek::StaticSecret; diff --git a/src/main.rs b/src/main.rs index 600e144..cfe93eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,44 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use types::{Bind, KeyPair}; +use types::{Bind, KeyPair, Tun}; + +#[derive(Debug)] +enum TunError {} + +impl Error for TunError { + fn description(&self) -> &str { + "Generic Tun Error" + } + + fn source(&self) -> Option<&(dyn Error + 'static)> { + None + } +} + +impl fmt::Display for TunError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Not Possible") + } +} + +struct TunTest {} + +impl Tun for TunTest { + type Error = TunError; + + fn mtu(&self) -> usize { + 1500 + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result { + Ok(0) + } + + fn write(&self, src: &[u8]) -> Result<(), Self::Error> { + Ok(()) + } +} struct Test {} @@ -73,6 +110,7 @@ fn main() { { let router = router::Device::new( 4, + TunTest {}, |t: &PeerTimer, data: bool, sent: bool| t.a.reset(Duration::from_millis(1000)), |t: &PeerTimer, data: bool, sent: bool| t.b.reset(Duration::from_millis(1000)), |t: &PeerTimer| println!("new key requested"), diff --git a/src/router/device.rs b/src/router/device.rs index a7f0590..84f25c6 100644 --- a/src/router/device.rs +++ b/src/router/device.rs @@ -5,7 +5,7 @@ use std::sync::{Arc, Weak}; use std::thread; use std::time::Instant; -use crossbeam_deque::{Injector, Steal, Stealer, Worker}; +use crossbeam_deque::{Injector, Worker}; use spin; use treebitmap::IpLookupTable; @@ -15,24 +15,25 @@ use super::anti_replay::AntiReplay; use super::peer; use super::peer::{Peer, PeerInner}; -use super::types::{Callback, KeyCallback, Opaque}; +use super::types::{Callback, Callbacks, CallbacksPhantom, KeyCallback, Opaque}; use super::workers::{worker_parallel, JobParallel}; -pub struct DeviceInner, R: Callback, K: KeyCallback> { +pub struct DeviceInner { + // IO & timer generics + pub tun: T, + pub call_recv: C::CallbackRecv, + pub call_send: C::CallbackSend, + pub call_need_key: C::CallbackKey, + // threading and workers pub running: AtomicBool, // workers running? pub parked: AtomicBool, // any workers parked? pub injector: Injector, // parallel enc/dec task injector - // unboxed callbacks (used for timers and handshake requests) - pub event_send: S, // called when authenticated message send - pub event_recv: R, // called when authenticated message received - pub event_need_key: K, // called when new key material is required - // routing - pub recv: spin::RwLock>>, // receiver id -> decryption state - pub ipv4: spin::RwLock>>>, // ipv4 cryptkey routing - pub ipv6: spin::RwLock>>>, // ipv6 cryptkey routing + pub recv: spin::RwLock>>, // receiver id -> decryption state + pub ipv4: spin::RwLock>>>, // ipv4 cryptkey routing + pub ipv6: spin::RwLock>>>, // ipv6 cryptkey routing } pub struct EncryptionState { @@ -43,21 +44,18 @@ pub struct EncryptionState { // (birth + reject-after-time - keepalive-timeout - rekey-timeout) } -pub struct DecryptionState, R: Callback, K: KeyCallback> { +pub struct DecryptionState { pub key: [u8; 32], pub keypair: Weak, pub confirmed: AtomicBool, pub protector: spin::Mutex, - pub peer: Weak>, + pub peer: Weak>, pub death: Instant, // time when the key can no longer be used for decryption } -pub struct Device, R: Callback, K: KeyCallback>( - Arc>, - Vec>, -); +pub struct Device(Arc>, Vec>); -impl, R: Callback, K: KeyCallback> Drop for Device { +impl Drop for Device { fn drop(&mut self) { // mark device as stopped let device = &self.0; @@ -75,18 +73,22 @@ impl, R: Callback, K: KeyCallback> Drop for Devi } } -impl, R: Callback, K: KeyCallback> Device { +impl, S: Callback, K: KeyCallback, T: Tun> + Device, T> +{ pub fn new( num_workers: usize, - event_recv: R, - event_send: S, - event_need_key: K, - ) -> Device { + tun: T, + call_recv: R, + call_send: S, + call_need_key: K, + ) -> Device, T> { // allocate shared device state let inner = Arc::new(DeviceInner { - event_recv, - event_send, - event_need_key, + tun, + call_recv, + call_send, + call_need_key, parked: AtomicBool::new(false), running: AtomicBool::new(true), injector: Injector::new(), @@ -95,7 +97,7 @@ impl, R: Callback, K: KeyCallback> Device, R: Callback, K: KeyCallback> Device Device { /// Adds a new peer to the device /// /// # Returns /// /// A atomic ref. counted peer (with liftime matching the device) - pub fn new_peer(&self, opaque: T) -> Peer { + pub fn new_peer(&self, opaque: C::Opaque) -> Peer { peer::new_peer(self.0.clone(), opaque) } diff --git a/src/router/messages.rs b/src/router/messages.rs index d09bbb3..bec24ac 100644 --- a/src/router/messages.rs +++ b/src/router/messages.rs @@ -7,5 +7,5 @@ use zerocopy::{AsBytes, ByteSlice, FromBytes, LayoutVerified}; pub struct TransportHeader { pub f_type: U32, pub f_receiver: U32, - pub f_counter: U64 -} \ No newline at end of file + pub f_counter: U64, +} diff --git a/src/router/mod.rs b/src/router/mod.rs index 70ac868..c1ecf1c 100644 --- a/src/router/mod.rs +++ b/src/router/mod.rs @@ -1,9 +1,9 @@ mod anti_replay; mod device; +mod messages; mod peer; mod types; mod workers; -mod messages; pub use device::Device; pub use peer::Peer; diff --git a/src/router/peer.rs b/src/router/peer.rs index 234c353..647d24f 100644 --- a/src/router/peer.rs +++ b/src/router/peer.rs @@ -12,7 +12,7 @@ use treebitmap::address::Address; use treebitmap::IpLookupTable; use super::super::constants::*; -use super::super::types::KeyPair; +use super::super::types::{KeyPair, Tun}; use super::anti_replay::AntiReplay; use super::device::DecryptionState; @@ -20,7 +20,7 @@ use super::device::DeviceInner; use super::device::EncryptionState; use super::workers::{worker_inbound, worker_outbound, JobInbound, JobOutbound}; -use super::types::{Callback, KeyCallback, Opaque}; +use super::types::Callbacks; const MAX_STAGED_PACKETS: usize = 128; @@ -31,14 +31,14 @@ pub struct KeyWheel { retired: Option, // retired id (previous id, after confirming key-pair) } -pub struct PeerInner, R: Callback, K: KeyCallback> { +pub struct PeerInner { pub stopped: AtomicBool, - pub opaque: T, - pub device: Arc>, + pub opaque: C::Opaque, + pub device: Arc>, pub thread_outbound: spin::Mutex>>, pub thread_inbound: spin::Mutex>>, pub queue_outbound: SyncSender, - pub queue_inbound: SyncSender>, + pub queue_inbound: SyncSender>, pub staged_packets: spin::Mutex; MAX_STAGED_PACKETS], Wrapping>>, // packets awaiting handshake pub rx_bytes: AtomicU64, // received bytes pub tx_bytes: AtomicU64, // transmitted bytes @@ -47,15 +47,15 @@ pub struct PeerInner, R: Callback, K: KeyCallback>>, } -pub struct Peer, R: Callback, K: KeyCallback>( - Arc>, +pub struct Peer( + Arc>, ); -fn treebit_list, R: Callback, K: KeyCallback>( - peer: &Arc>, - table: &spin::RwLock>>>, - callback: Box O>, -) -> Vec +fn treebit_list( + peer: &Arc>, + table: &spin::RwLock>>>, + callback: Box E>, +) -> Vec where A: Address, { @@ -71,9 +71,9 @@ where res } -fn treebit_remove, R: Callback, K: KeyCallback>( - peer: &Peer, - table: &spin::RwLock>>>, +fn treebit_remove( + peer: &Peer, + table: &spin::RwLock>>>, ) { let mut m = table.write(); @@ -95,7 +95,7 @@ fn treebit_remove, R: Callback, K: KeyC } } -impl, R: Callback, K: KeyCallback> Drop for Peer { +impl Drop for Peer { fn drop(&mut self) { // mark peer as stopped @@ -150,10 +150,10 @@ impl, R: Callback, K: KeyCallback> Drop for Peer } } -pub fn new_peer, R: Callback, K: KeyCallback>( - device: Arc>, - opaque: T, -) -> Peer { +pub fn new_peer( + device: Arc>, + opaque: C::Opaque, +) -> Peer { // allocate in-order queues let (send_inbound, recv_inbound) = sync_channel(MAX_STAGED_PACKETS); let (send_outbound, recv_outbound) = sync_channel(MAX_STAGED_PACKETS); @@ -204,7 +204,7 @@ pub fn new_peer, R: Callback, K: KeyCallback>( Peer(peer) } -impl, R: Callback, K: KeyCallback> PeerInner { +impl PeerInner { pub fn confirm_key(&self, kp: Weak) { // upgrade key-pair to strong reference @@ -214,8 +214,8 @@ impl, R: Callback, K: KeyCallback> PeerInner, R: Callback, K: KeyCallback> Peer { - fn new(inner: PeerInner) -> Peer { +impl Peer { + fn new(inner: PeerInner) -> Peer { Peer(Arc::new(inner)) } diff --git a/src/router/types.rs b/src/router/types.rs index 3d486bc..f6a0311 100644 --- a/src/router/types.rs +++ b/src/router/types.rs @@ -1,3 +1,5 @@ +use std::marker::PhantomData; + pub trait Opaque: Send + Sync + 'static {} impl Opaque for T where T: Send + Sync + 'static {} @@ -23,3 +25,24 @@ pub trait TunCallback: Fn(&T, bool, bool) -> () + Sync + Send + 'static {} pub trait BindCallback: Fn(&T, bool, bool) -> () + Sync + Send + 'static {} pub trait Endpoint: Send + Sync {} + +pub trait Callbacks: Send + Sync + 'static { + type Opaque: Opaque; + type CallbackRecv: Callback; + type CallbackSend: Callback; + type CallbackKey: KeyCallback; +} + +pub struct CallbacksPhantom, S: Callback, K: KeyCallback> { + _phantom_opaque: PhantomData, + _phantom_recv: PhantomData, + _phantom_send: PhantomData, + _phantom_key: PhantomData +} + +impl , S: Callback, K: KeyCallback> Callbacks for CallbacksPhantom { + type Opaque = O; + type CallbackRecv = R; + type CallbackSend = S; + type CallbackKey = K; +} \ No newline at end of file diff --git a/src/router/workers.rs b/src/router/workers.rs index 4861847..2b0b9ec 100644 --- a/src/router/workers.rs +++ b/src/router/workers.rs @@ -15,7 +15,9 @@ use super::device::DecryptionState; use super::device::DeviceInner; use super::messages::TransportHeader; use super::peer::PeerInner; -use super::types::{Callback, KeyCallback, Opaque}; +use super::types::Callbacks; + +use super::super::types::Tun; #[derive(PartialEq, Debug)] pub enum Operation { @@ -39,7 +41,7 @@ pub struct JobInner { pub type JobBuffer = Arc>; pub type JobParallel = (Arc>, JobBuffer); -pub type JobInbound = (Weak>, JobBuffer); +pub type JobInbound = (Weak>, JobBuffer); pub type JobOutbound = JobBuffer; /* Strategy for workers acquiring a new job: @@ -87,10 +89,10 @@ fn wait_recv(running: &AtomicBool, recv: &Receiver) -> Result, R: Callback, K: KeyCallback>( - device: Arc>, // related device - peer: Arc>, // related peer - recv: Receiver>, // in order queue +pub fn worker_inbound( + device: Arc>, // related device + peer: Arc>, // related peer + recv: Receiver>, // in order queue ) { loop { match wait_recv(&peer.stopped, &recv) { @@ -134,7 +136,7 @@ pub fn worker_inbound, R: Callback, K: KeyCallback< packet.len() >= CHACHA20_POLY1305.nonce_len(), "this should be checked earlier in the pipeline" ); - (device.event_recv)( + (device.call_recv)( &peer.opaque, packet.len() > CHACHA20_POLY1305.nonce_len(), true, @@ -155,10 +157,10 @@ pub fn worker_inbound, R: Callback, K: KeyCallback< } } -pub fn worker_outbound, R: Callback, K: KeyCallback>( - device: Arc>, // related device - peer: Arc>, // related peer - recv: Receiver, // in order queue +pub fn worker_outbound( + device: Arc>, // related device + peer: Arc>, // related peer + recv: Receiver, // in order queue ) { loop { match wait_recv(&peer.stopped, &recv) { @@ -180,7 +182,7 @@ pub fn worker_outbound, R: Callback, K: KeyCallback let xmit = false; // trigger callback - (device.event_send)( + (device.call_send)( &peer.opaque, buf.msg.len() > CHACHA20_POLY1305.nonce_len() @@ -203,8 +205,8 @@ pub fn worker_outbound, R: Callback, K: KeyCallback } } -pub fn worker_parallel, R: Callback, K: KeyCallback>( - device: Arc>, +pub fn worker_parallel( + device: Arc>, local: Worker, // local job queue (local to thread) stealers: Vec>, // stealers (from other threads) ) { -- cgit v1.2.3-59-g8ed1b