Fix some clippy warnings

Signed-off-by: Quang Luong <quangio@outlook.com>
This commit is contained in:
Quang Luong
2020-09-18 11:20:06 +07:00
committed by Mathias Hall-Andersen
parent a7dea4f2b4
commit 9b53a9d1a6
26 changed files with 701 additions and 666 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
/target /target
**/*.rs.bk **/*.rs.bk
proptest-regressions/ proptest-regressions/
Cargo.lock
.idea/

1066
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -358,11 +358,11 @@ impl<T: tun::Tun, B: udp::PlatformUDP> Configuration for WireGuardConfig<T, B> {
for (pk, p) in peers.iter() { for (pk, p) in peers.iter() {
// convert the system time to (secs, nano) since epoch // convert the system time to (secs, nano) since epoch
let last_handshake_time = (*p.walltime_last_handshake.lock()).and_then(|t| { let last_handshake_time = (*p.walltime_last_handshake.lock()).map(|t| {
let duration = t let duration = t
.duration_since(SystemTime::UNIX_EPOCH) .duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0)); .unwrap_or_else(|_| Duration::from_secs(0));
Some((duration.as_secs(), duration.subsec_nanos() as u64)) (duration.as_secs(), duration.subsec_nanos() as u64)
}); });
if let Some(psk) = cfg.wireguard.get_psk(&pk) { if let Some(psk) = cfg.wireguard.get_psk(&pk) {

View File

@@ -1,4 +1,3 @@
use log;
use std::io; use std::io;
use super::Configuration; use super::Configuration;
@@ -8,10 +7,10 @@ pub fn serialize<C: Configuration, W: io::Write>(writer: &mut W, config: &C) ->
debug_assert!(value.is_ascii()); debug_assert!(value.is_ascii());
debug_assert!(key.is_ascii()); debug_assert!(key.is_ascii());
log::trace!("UAPI: return : {}={}", key, value); log::trace!("UAPI: return : {}={}", key, value);
writer.write(key.as_ref())?; writer.write_all(key.as_ref())?;
writer.write(b"=")?; writer.write_all(b"=")?;
writer.write(value.as_ref())?; writer.write_all(value.as_ref())?;
writer.write(b"\n") writer.write_all(b"\n")
}; };
// serialize interface // serialize interface

View File

@@ -1,7 +1,6 @@
mod get; mod get;
mod set; mod set;
use log;
use std::io::{Read, Write}; use std::io::{Read, Write};
use super::{ConfigError, Configuration}; use super::{ConfigError, Configuration};
@@ -20,7 +19,7 @@ pub fn handle<S: Read + Write, C: Configuration>(stream: &mut S, config: &C) {
fn readline<R: Read>(reader: &mut R) -> Result<String, ConfigError> { fn readline<R: Read>(reader: &mut R) -> Result<String, ConfigError> {
let mut m: [u8; 1] = [0u8]; let mut m: [u8; 1] = [0u8];
let mut l: String = String::with_capacity(MAX_LINE_LENGTH); let mut l: String = String::with_capacity(MAX_LINE_LENGTH);
while let Ok(_) = reader.read_exact(&mut m) { while reader.read_exact(&mut m).is_ok() {
let c = m[0] as char; let c = m[0] as char;
if c == '\n' { if c == '\n' {
log::trace!("UAPI, line: {}", l); log::trace!("UAPI, line: {}", l);
@@ -31,12 +30,12 @@ pub fn handle<S: Read + Write, C: Configuration>(stream: &mut S, config: &C) {
return Err(ConfigError::LineTooLong); return Err(ConfigError::LineTooLong);
} }
} }
return Err(ConfigError::IOError); Err(ConfigError::IOError)
} }
// split into (key, value) pair // split into (key, value) pair
fn keypair<'a>(ln: &'a str) -> Result<(&'a str, &'a str), ConfigError> { fn keypair(ln: &str) -> Result<(&str, &str), ConfigError> {
let mut split = ln.splitn(2, "="); let mut split = ln.splitn(2, '=');
match (split.next(), split.next()) { match (split.next(), split.next()) {
(Some(key), Some(value)) => Ok((key, value)), (Some(key), Some(value)) => Ok((key, value)),
_ => Err(ConfigError::LineTooLong), _ => Err(ConfigError::LineTooLong),

View File

@@ -220,7 +220,7 @@ impl<'a, C: Configuration> LineParser<'a, C> {
// opt add allowed ips // opt add allowed ips
"allowed_ip" => { "allowed_ip" => {
let mut split = value.splitn(2, "/"); let mut split = value.splitn(2, '/');
let addr = split.next().and_then(|x| x.parse().ok()); let addr = split.next().and_then(|x| x.parse().ok());
let cidr = split.next().and_then(|x| x.parse().ok()); let cidr = split.next().and_then(|x| x.parse().ok());
match (addr, cidr) { match (addr, cidr) {

View File

@@ -14,8 +14,6 @@ mod wireguard;
mod util; mod util;
use log;
use std::env; use std::env;
use std::process::exit; use std::process::exit;
use std::thread; use std::thread;

View File

@@ -1,7 +1,5 @@
use super::super::tun::*; use super::super::tun::*;
use libc;
use std::error::Error; use std::error::Error;
use std::fmt; use std::fmt;
use std::mem; use std::mem;
@@ -9,7 +7,7 @@ use std::os::raw::c_short;
use std::os::unix::io::RawFd; use std::os::unix::io::RawFd;
const TUNSETIFF: u64 = 0x4004_54ca; const TUNSETIFF: u64 = 0x4004_54ca;
const CLONE_DEVICE_PATH: &'static [u8] = b"/dev/net/tun\0"; const CLONE_DEVICE_PATH: &[u8] = b"/dev/net/tun\0";
#[repr(C)] #[repr(C)]
struct Ifreq { struct Ifreq {
@@ -75,11 +73,11 @@ impl fmt::Display for LinuxTunError {
} }
impl Error for LinuxTunError { impl Error for LinuxTunError {
fn description(&self) -> &str { fn source(&self) -> Option<&(dyn Error + 'static)> {
unimplemented!() unimplemented!()
} }
fn source(&self) -> Option<&(dyn Error + 'static)> { fn description(&self) -> &str {
unimplemented!() unimplemented!()
} }
} }
@@ -156,7 +154,7 @@ fn get_mtu(name: &[u8; libc::IFNAMSIZ]) -> Result<usize, LinuxTunError> {
mtu: 0, mtu: 0,
}; };
let err = unsafe { let err = unsafe {
let ptr: &libc::c_void = mem::transmute(&buf); let ptr: &libc::c_void = &*(&buf as *const _ as *const libc::c_void);
libc::ioctl(fd, libc::SIOCGIFMTU, ptr) libc::ioctl(fd, libc::SIOCGIFMTU, ptr)
}; };
@@ -312,9 +310,9 @@ impl LinuxTunStatus {
} }
impl Tun for LinuxTun { impl Tun for LinuxTun {
type Error = LinuxTunError;
type Reader = LinuxTunReader;
type Writer = LinuxTunWriter; type Writer = LinuxTunWriter;
type Reader = LinuxTunReader;
type Error = LinuxTunError;
} }
impl PlatformTun for LinuxTun { impl PlatformTun for LinuxTun {

View File

@@ -1,8 +1,6 @@
use super::super::udp::*; use super::super::udp::*;
use super::super::Endpoint; use super::super::Endpoint;
use log;
use std::convert::TryInto; use std::convert::TryInto;
use std::io; use std::io;
use std::mem; use std::mem;
@@ -132,19 +130,6 @@ fn safe_cast<T, D>(v: &mut T) -> *mut D {
} }
impl Endpoint for LinuxEndpoint { impl Endpoint for LinuxEndpoint {
fn clear_src(&mut self) {
match self {
LinuxEndpoint::V4(EndpointV4 { ref mut info, .. }) => {
info.ipi_ifindex = 0;
info.ipi_spec_dst = libc::in_addr { s_addr: 0 };
}
LinuxEndpoint::V6(EndpointV6 { ref mut info, .. }) => {
info.ipi6_addr = libc::in6_addr { s6_addr: [0; 16] };
info.ipi6_ifindex = 0;
}
};
}
fn from_address(addr: SocketAddr) -> Self { fn from_address(addr: SocketAddr) -> Self {
match addr { match addr {
SocketAddr::V4(addr) => LinuxEndpoint::V4(EndpointV4 { SocketAddr::V4(addr) => LinuxEndpoint::V4(EndpointV4 {
@@ -196,6 +181,19 @@ impl Endpoint for LinuxEndpoint {
)), )),
} }
} }
fn clear_src(&mut self) {
match self {
LinuxEndpoint::V4(EndpointV4 { ref mut info, .. }) => {
info.ipi_ifindex = 0;
info.ipi_spec_dst = libc::in_addr { s_addr: 0 };
}
LinuxEndpoint::V6(EndpointV6 { ref mut info, .. }) => {
info.ipi6_addr = libc::in6_addr { s6_addr: [0; 16] };
info.ipi6_ifindex = 0;
}
};
}
} }
impl LinuxUDPReader { impl LinuxUDPReader {
@@ -206,7 +204,7 @@ impl LinuxUDPReader {
buf.len() buf.len()
); );
debug_assert!(buf.len() > 0, "reading into empty buffer (will fail)"); debug_assert!(!buf.is_empty(), "reading into empty buffer (will fail)");
let mut iovs: [libc::iovec; 1] = [libc::iovec { let mut iovs: [libc::iovec; 1] = [libc::iovec {
iov_base: buf.as_mut_ptr() as *mut core::ffi::c_void, iov_base: buf.as_mut_ptr() as *mut core::ffi::c_void,
@@ -260,7 +258,7 @@ impl LinuxUDPReader {
buf.len() buf.len()
); );
debug_assert!(buf.len() > 0, "reading into empty buffer (will fail)"); debug_assert!(!buf.is_empty(), "reading into empty buffer (will fail)");
let mut iovs: [libc::iovec; 1] = [libc::iovec { let mut iovs: [libc::iovec; 1] = [libc::iovec {
iov_base: buf.as_mut_ptr() as *mut core::ffi::c_void, iov_base: buf.as_mut_ptr() as *mut core::ffi::c_void,
@@ -366,14 +364,14 @@ impl LinuxUDPWriter {
hdr.msg_control = ptr::null_mut(); hdr.msg_control = ptr::null_mut();
hdr.msg_controllen = 0; hdr.msg_controllen = 0;
dst.info = unsafe { mem::zeroed() }; dst.info = unsafe { mem::zeroed() };
if unsafe { libc::sendmsg(fd, &hdr, 0) } < 0 { return if unsafe { libc::sendmsg(fd, &hdr, 0) } < 0 {
return Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::NotConnected, io::ErrorKind::NotConnected,
"failed to send IPv6 packet", "failed to send IPv6 packet",
)); ))
} else { } else {
return Ok(()); Ok(())
} };
} }
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::NotConnected, io::ErrorKind::NotConnected,
@@ -431,14 +429,14 @@ impl LinuxUDPWriter {
hdr.msg_control = ptr::null_mut(); hdr.msg_control = ptr::null_mut();
hdr.msg_controllen = 0; hdr.msg_controllen = 0;
dst.info = unsafe { mem::zeroed() }; dst.info = unsafe { mem::zeroed() };
if unsafe { libc::sendmsg(fd, &hdr, 0) } < 0 { return if unsafe { libc::sendmsg(fd, &hdr, 0) } < 0 {
return Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::NotConnected, io::ErrorKind::NotConnected,
"failed to send IPv4 packet", "failed to send IPv4 packet",
)); ))
} else { } else {
return Ok(()); Ok(())
} };
} }
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::NotConnected, io::ErrorKind::NotConnected,
@@ -485,22 +483,26 @@ impl Owner for LinuxOwner {
impl Drop for LinuxOwner { impl Drop for LinuxOwner {
fn drop(&mut self) { fn drop(&mut self) {
log::debug!("closing the bind (port = {})", self.port); log::debug!("closing the bind (port = {})", self.port);
self.sock4.as_ref().map(|fd| unsafe { if let Some(fd) = &self.sock4 {
log::debug!("shutdown IPv4 (fd = {})", fd.0); log::debug!("shutdown IPv4 (fd = {})", fd.0);
libc::shutdown(fd.0, libc::SHUT_RDWR); unsafe {
}); libc::shutdown(fd.0, libc::SHUT_RDWR);
self.sock6.as_ref().map(|fd| unsafe { }
};
if let Some(fd) = &self.sock6 {
log::debug!("shutdown IPv6 (fd = {})", fd.0); log::debug!("shutdown IPv6 (fd = {})", fd.0);
libc::shutdown(fd.0, libc::SHUT_RDWR); unsafe {
}); libc::shutdown(fd.0, libc::SHUT_RDWR);
}
};
} }
} }
impl UDP for LinuxUDP { impl UDP for LinuxUDP {
type Error = io::Error; type Error = io::Error;
type Endpoint = LinuxEndpoint; type Endpoint = LinuxEndpoint;
type Reader = LinuxUDPReader;
type Writer = LinuxUDPWriter; type Writer = LinuxUDPWriter;
type Reader = LinuxUDPReader;
} }
impl LinuxUDP { impl LinuxUDP {
@@ -580,7 +582,7 @@ impl LinuxUDP {
debug_assert_eq!(sockaddr.sin6_family, libc::AF_INET6 as libc::sa_family_t); debug_assert_eq!(sockaddr.sin6_family, libc::AF_INET6 as libc::sa_family_t);
debug_assert_eq!(new_port, if port != 0 { port } else { new_port }); debug_assert_eq!(new_port, if port != 0 { port } else { new_port });
log::trace!("bound IPv6 socket (port {}, fd {})", new_port, fd); log::trace!("bound IPv6 socket (port {}, fd {})", new_port, fd);
return Ok((new_port, fd)); Ok((new_port, fd))
} }
/* Bind on all IPv4 interfaces. /* Bind on all IPv4 interfaces.
@@ -657,7 +659,7 @@ impl LinuxUDP {
debug_assert_eq!(sockaddr.sin_family, libc::AF_INET as libc::sa_family_t); debug_assert_eq!(sockaddr.sin_family, libc::AF_INET as libc::sa_family_t);
debug_assert_eq!(new_port, if port != 0 { port } else { new_port }); debug_assert_eq!(new_port, if port != 0 { port } else { new_port });
log::trace!("bound IPv4 socket (port {}, fd {})", new_port, fd); log::trace!("bound IPv4 socket (port {}, fd {})", new_port, fd);
return Ok((new_port, fd)); Ok((new_port, fd))
} }
} }
@@ -697,18 +699,18 @@ impl PlatformUDP for LinuxUDP {
// create readers // create readers
let mut readers: Vec<Self::Reader> = Vec::with_capacity(2); let mut readers: Vec<Self::Reader> = Vec::with_capacity(2);
sock6 if let Some(sock) = sock6.clone() {
.clone() readers.push(LinuxUDPReader::V6(sock))
.map(|sock| readers.push(LinuxUDPReader::V6(sock))); }
sock4 if let Some(sock) = sock4.clone() {
.clone() readers.push(LinuxUDPReader::V4(sock))
.map(|sock| readers.push(LinuxUDPReader::V4(sock))); }
debug_assert!(readers.len() > 0); debug_assert!(!readers.is_empty());
// create writer // create writer
let writer = LinuxUDPWriter { let writer = LinuxUDPWriter {
sock4: sock4.unwrap_or(Arc::new(FD(-1))), sock4: sock4.unwrap_or_else(|| Arc::new(FD(-1))),
sock6: sock6.unwrap_or(Arc::new(FD(-1))), sock6: sock6.unwrap_or_else(|| Arc::new(FD(-1))),
}; };
Ok((readers, writer, owner)) Ok((readers, writer, owner))

View File

@@ -1,3 +1,4 @@
use std::cmp::Ordering;
use std::fmt; use std::fmt;
use std::process::exit; use std::process::exit;
@@ -29,12 +30,10 @@ impl fmt::Display for DaemonizeError {
fn fork_and_exit() -> Result<(), DaemonizeError> { fn fork_and_exit() -> Result<(), DaemonizeError> {
let pid = unsafe { fork() }; let pid = unsafe { fork() };
if pid < 0 { match pid.cmp(&0) {
Err(DaemonizeError::Fork) Ordering::Less => Err(DaemonizeError::Fork),
} else if pid == 0 { Ordering::Equal => Ok(()),
Ok(()) Ordering::Greater => exit(0),
} else {
exit(0);
} }
} }

View File

@@ -118,7 +118,9 @@ impl<O> Device<O> {
} else { } else {
peer.ss.clear(); peer.ss.clear();
} }
peer.reset_state().map(|id| ids.push(id)); if let Some(id) = peer.reset_state() {
ids.push(id)
}
} }
(ids, same) (ids, same)
@@ -212,7 +214,7 @@ impl<O> Device<O> {
// remove the peer // remove the peer
self.pk_map self.pk_map
.remove(pk.as_bytes()) .remove(pk.as_bytes())
.ok_or(ConfigError::new("Public key not in device"))?; .ok_or_else(|| ConfigError::new("Public key not in device"))?;
// remove every id entry for the peer in the public key map // remove every id entry for the peer in the public key map
// O(n) operations, however it is rare: only when removing peers. // O(n) operations, however it is rare: only when removing peers.
@@ -389,9 +391,6 @@ impl<O> Device<O> {
// address validation & DoS mitigation // address validation & DoS mitigation
if let Some(src) = src { if let Some(src) = src {
// obtain ref to socket addr
let src = src.into();
// check mac2 field // check mac2 field
if !keyst.macs.check_mac2(msg.noise.as_bytes(), &src, &msg.macs) { if !keyst.macs.check_mac2(msg.noise.as_bytes(), &src, &msg.macs) {
let mut reply = Default::default(); let mut reply = Default::default();
@@ -471,12 +470,9 @@ impl<O> Device<O> {
} }
// write lock the shard and insert // write lock the shard and insert
match self.id_map.entry(id) { if let Entry::Vacant(entry) = self.id_map.entry(id) {
Entry::Vacant(entry) => { entry.insert(*pk.as_bytes());
entry.insert(*pk.as_bytes()); return id;
return id;
}
_ => (),
}; };
} }
} }

View File

@@ -11,8 +11,6 @@ use hmac::Hmac;
use aead::{Aead, NewAead, Payload}; use aead::{Aead, NewAead, Payload};
use chacha20poly1305::ChaCha20Poly1305; use chacha20poly1305::ChaCha20Poly1305;
use log;
use rand::prelude::{CryptoRng, RngCore}; use rand::prelude::{CryptoRng, RngCore};
use generic_array::typenum::*; use generic_array::typenum::*;

View File

@@ -50,13 +50,10 @@ pub enum State {
impl Drop for State { impl Drop for State {
fn drop(&mut self) { fn drop(&mut self) {
match self { if let State::InitiationSent { hs, ck, .. } = self {
State::InitiationSent { hs, ck, .. } => { // eph_sk already cleared by dalek-x25519
// eph_sk already cleared by dalek-x25519 hs.clear();
hs.clear(); ck.clear();
ck.clear();
}
_ => (),
} }
} }
} }
@@ -97,29 +94,22 @@ impl<O> Peer<O> {
let mut last_initiation_consumption = self.last_initiation_consumption.lock(); let mut last_initiation_consumption = self.last_initiation_consumption.lock();
// check replay attack // check replay attack
match *timestamp { if let Some(timestamp_old) = *timestamp {
Some(timestamp_old) => { if !timestamp::compare(&timestamp_old, &timestamp_new) {
if !timestamp::compare(&timestamp_old, &timestamp_new) { return Err(HandshakeError::OldTimestamp);
return Err(HandshakeError::OldTimestamp);
}
} }
_ => (),
}; };
// check flood attack // check flood attack
match *last_initiation_consumption { if let Some(last) = *last_initiation_consumption {
Some(last) => { if last.elapsed() < TIME_BETWEEN_INITIATIONS {
if last.elapsed() < TIME_BETWEEN_INITIATIONS { return Err(HandshakeError::InitiationFlood);
return Err(HandshakeError::InitiationFlood);
}
} }
_ => (),
} }
// reset state // reset state
match *state { if let State::InitiationSent { local, .. } = *state {
State::InitiationSent { local, .. } => device.release(local), device.release(local)
_ => (),
} }
// update replay & flood protection // update replay & flood protection

View File

@@ -5,8 +5,6 @@ use std::sync::{Arc, Condvar, Mutex};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use spin;
const PACKETS_PER_SECOND: u64 = 20; const PACKETS_PER_SECOND: u64 = 20;
const PACKETS_BURSTABLE: u64 = 5; const PACKETS_BURSTABLE: u64 = 5;
const PACKET_COST: u64 = 1_000_000_000 / PACKETS_PER_SECOND; const PACKET_COST: u64 = 1_000_000_000 / PACKETS_PER_SECOND;

View File

@@ -28,5 +28,5 @@ pub fn compare(old: &TAI64N, new: &TAI64N) -> bool {
return true; return true;
} }
} }
return false; false
} }

View File

@@ -26,7 +26,7 @@ pub struct PeerInner<T: Tun, B: UDP> {
pub pk: PublicKey, pub pk: PublicKey,
// handshake state // handshake state
pub walltime_last_handshake: Mutex<Option<SystemTime>>, // walltime for last handshake (for UAPI status) pub walltime_last_handshake: Mutex<Option<SystemTime>>, /* walltime for last handshake (for UAPI status) */
pub last_handshake_sent: Mutex<Instant>, // instant for last handshake pub last_handshake_sent: Mutex<Instant>, // instant for last handshake
pub handshake_queued: AtomicBool, // is a handshake job currently queued? pub handshake_queued: AtomicBool, // is a handshake job currently queued?

View File

@@ -12,7 +12,6 @@ impl<T> ParallelQueue<T> {
/// ///
/// - `queues`: number of readers /// - `queues`: number of readers
/// - `capacity`: capacity of each internal queue /// - `capacity`: capacity of each internal queue
///
pub fn new(queues: usize, capacity: usize) -> (Self, Vec<Receiver<T>>) { pub fn new(queues: usize, capacity: usize) -> (Self, Vec<Receiver<T>>) {
let mut receivers = Vec::with_capacity(queues); let mut receivers = Vec::with_capacity(queues);
let (tx, rx) = bounded(capacity); let (tx, rx) = bounded(capacity);
@@ -28,9 +27,9 @@ impl<T> ParallelQueue<T> {
} }
pub fn send(&self, v: T) { pub fn send(&self, v: T) {
self.queue.lock().unwrap().as_ref().map(|s| { if let Some(s) = self.queue.lock().unwrap().as_ref() {
let _ = s.send(v); let _ = s.send(v);
}); }
} }
pub fn close(&self) { pub fn close(&self) {

View File

@@ -4,7 +4,6 @@ use std::sync::atomic::AtomicBool;
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
use log;
use spin::{Mutex, RwLock}; use spin::{Mutex, RwLock};
use zerocopy::LayoutVerified; use zerocopy::LayoutVerified;
@@ -31,7 +30,7 @@ pub struct DeviceInner<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer
pub(super) outbound: RwLock<(bool, Option<B>)>, pub(super) outbound: RwLock<(bool, Option<B>)>,
// routing // routing
pub(super) recv: RwLock<HashMap<u32, Arc<DecryptionState<E, C, T, B>>>>, // receiver id -> decryption state pub(super) recv: RwLock<HashMap<u32, Arc<DecryptionState<E, C, T, B>>>>, /* receiver id -> decryption state */
pub(super) table: RoutingTable<Peer<E, C, T, B>>, pub(super) table: RoutingTable<Peer<E, C, T, B>>,
// work queue // work queue
@@ -141,7 +140,7 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> DeviceHandle<
return bind.write(msg, dst); return bind.write(msg, dst);
} }
} }
return Ok(()); Ok(())
} }
/// Brings the router down. /// Brings the router down.
@@ -178,7 +177,6 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> DeviceHandle<
/// # Arguments /// # Arguments
/// ///
/// - msg: IP packet to crypt-key route /// - msg: IP packet to crypt-key route
///
pub fn send(&self, msg: Vec<u8>) -> Result<(), RouterError> { pub fn send(&self, msg: Vec<u8>) -> Result<(), RouterError> {
debug_assert!(msg.len() > SIZE_MESSAGE_PREFIX); debug_assert!(msg.len() > SIZE_MESSAGE_PREFIX);
log::trace!( log::trace!(
@@ -209,8 +207,6 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> DeviceHandle<
/// - msg: Encrypted transport message /// - msg: Encrypted transport message
/// ///
/// # Returns /// # Returns
///
///
pub fn recv(&self, src: E, msg: Vec<u8>) -> Result<(), RouterError> { pub fn recv(&self, src: E, msg: Vec<u8>) -> Result<(), RouterError> {
log::trace!("receive, src: {}", src.into_address()); log::trace!("receive, src: {}", src.into_address());
@@ -253,8 +249,6 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> DeviceHandle<
} }
/// Set outbound writer /// Set outbound writer
///
///
pub fn set_outbound_writer(&self, new: B) { pub fn set_outbound_writer(&self, new: B) {
self.state.outbound.write().1 = Some(new); self.state.outbound.write().1 = Some(new);
} }

View File

@@ -26,7 +26,6 @@ use std::fmt;
use std::net::{IpAddr, SocketAddr}; use std::net::{IpAddr, SocketAddr};
use arraydeque::{ArrayDeque, Wrapping}; use arraydeque::{ArrayDeque, Wrapping};
use log;
use spin::Mutex; use spin::Mutex;
pub struct KeyWheel { pub struct KeyWheel {
@@ -155,11 +154,17 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> Drop for Peer
let mut keys = peer.keys.lock(); let mut keys = peer.keys.lock();
let mut release = Vec::with_capacity(3); let mut release = Vec::with_capacity(3);
keys.next.as_ref().map(|k| release.push(k.recv.id)); if let Some(k) = keys.next.as_ref() {
keys.current.as_ref().map(|k| release.push(k.recv.id)); release.push(k.recv.id)
keys.previous.as_ref().map(|k| release.push(k.recv.id)); }
if let Some(k) = keys.current.as_ref() {
release.push(k.recv.id)
}
if let Some(k) = keys.previous.as_ref() {
release.push(k.recv.id)
}
if release.len() > 0 { if !release.is_empty() {
let mut recv = peer.device.recv.write(); let mut recv = peer.device.recv.write();
for id in &release { for id in &release {
recv.remove(id); recv.remove(id);
@@ -185,7 +190,6 @@ pub fn new_peer<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>>(
) -> PeerHandle<E, C, T, B> { ) -> PeerHandle<E, C, T, B> {
// allocate peer object // allocate peer object
let peer = { let peer = {
let device = device.clone();
Peer { Peer {
inner: Arc::new(PeerInner { inner: Arc::new(PeerInner {
opaque, opaque,
@@ -245,7 +249,6 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> Peer<E, C, T,
/// ///
/// - `msg` : A padded vector holding the message (allows in-place construction of the transport header) /// - `msg` : A padded vector holding the message (allows in-place construction of the transport header)
/// - `stage`: Should the message be staged if no key is available /// - `stage`: Should the message be staged if no key is available
///
pub(super) fn send(&self, msg: Vec<u8>, stage: bool) { pub(super) fn send(&self, msg: Vec<u8>, stage: bool) {
// check if key available // check if key available
let (job, need_key) = { let (job, need_key) = {
@@ -385,9 +388,15 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> PeerHandle<E,
// update key-wheel // update key-wheel
mem::replace(&mut keys.next, None).map(|k| release.push(k.local_id())); if let Some(k) = mem::replace(&mut keys.next, None) {
mem::replace(&mut keys.current, None).map(|k| release.push(k.local_id())); release.push(k.local_id())
mem::replace(&mut keys.previous, None).map(|k| release.push(k.local_id())); }
if let Some(k) = mem::replace(&mut keys.current, None) {
release.push(k.local_id())
}
if let Some(k) = mem::replace(&mut keys.previous, None) {
release.push(k.local_id())
}
keys.retired.extend(&release[..]); keys.retired.extend(&release[..]);
// update inbound "recv" map // update inbound "recv" map
@@ -439,11 +448,11 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> PeerHandle<E,
*self.peer.enc_key.lock() = Some(EncryptionState::new(&new)); *self.peer.enc_key.lock() = Some(EncryptionState::new(&new));
// move current into previous // move current into previous
keys.previous = keys.current.as_ref().map(|v| v.clone()); keys.previous = keys.current.as_ref().cloned();
keys.current = Some(new.clone()); keys.current = Some(new.clone());
} else { } else {
// store the key and await confirmation // store the key and await confirmation
keys.previous = keys.next.as_ref().map(|v| v.clone()); keys.previous = keys.next.as_ref().cloned();
keys.next = Some(new.clone()); keys.next = Some(new.clone());
}; };
@@ -453,10 +462,10 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> PeerHandle<E,
let mut recv = self.peer.device.recv.write(); let mut recv = self.peer.device.recv.write();
// purge recv map of previous id // purge recv map of previous id
keys.previous.as_ref().map(|k| { if let Some(k) = &keys.previous {
recv.remove(&k.local_id()); recv.remove(&k.local_id());
release.push(k.local_id()); release.push(k.local_id());
}); }
// map new id to decryption state // map new id to decryption state
debug_assert!(!recv.contains_key(&new.recv.id)); debug_assert!(!recv.contains_key(&new.recv.id));
@@ -531,7 +540,9 @@ impl<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> PeerHandle<E,
} }
pub fn clear_src(&self) { pub fn clear_src(&self) {
(*self.peer.endpoint.lock()).as_mut().map(|e| e.clear_src()); if let Some(e) = (*self.peer.endpoint.lock()).as_mut() {
e.clear_src()
}
} }
pub fn purge_staged_packets(&self) { pub fn purge_staged_packets(&self) {

View File

@@ -67,9 +67,7 @@ impl<J: SequentialJob> Queue<J> {
match queue.front() { match queue.front() {
None => break, None => break,
Some(job) => { Some(job) => {
if job.is_ready() { if !job.is_ready() {
()
} else {
break; break;
} }
} }

View File

@@ -88,7 +88,7 @@ impl<T: Eq + Clone> RoutingTable<T> {
self.ipv4 self.ipv4
.read() .read()
.longest_match(Ipv4Addr::from(header.f_destination)) .longest_match(Ipv4Addr::from(header.f_destination))
.and_then(|(_, _, p)| Some(p.clone())) .map(|(_, _, p)| p.clone())
} }
VERSION_IP6 => { VERSION_IP6 => {
// check length and cast to IPv6 header // check length and cast to IPv6 header
@@ -104,7 +104,7 @@ impl<T: Eq + Clone> RoutingTable<T> {
self.ipv6 self.ipv6
.read() .read()
.longest_match(Ipv6Addr::from(header.f_destination)) .longest_match(Ipv6Addr::from(header.f_destination))
.and_then(|(_, _, p)| Some(p.clone())) .map(|(_, _, p)| p.clone())
} }
v => { v => {
log::trace!("router, invalid IP version {}", v); log::trace!("router, invalid IP version {}", v);

View File

@@ -15,16 +15,16 @@ impl<T> Opaque for T where T: Send + Sync + 'static {}
/// * `0`, a reference to the opaque value assigned to the peer /// * `0`, a reference to the opaque value assigned to the peer
/// * `1`, a bool indicating whether the message contained data (not just keepalive) /// * `1`, a bool indicating whether the message contained data (not just keepalive)
/// * `2`, a bool indicating whether the message was transmitted (i.e. did the peer have an associated endpoint?) /// * `2`, a bool indicating whether the message was transmitted (i.e. did the peer have an associated endpoint?)
pub trait Callback<T>: Fn(&T, usize, bool) -> () + Sync + Send + 'static {} pub trait Callback<T>: Fn(&T, usize, bool) + Sync + Send + 'static {}
impl<T, F> Callback<T> for F where F: Fn(&T, usize, bool) -> () + Sync + Send + 'static {} impl<T, F> Callback<T> for F where F: Fn(&T, usize, bool) + Sync + Send + 'static {}
/// A key callback takes 1 argument /// A key callback takes 1 argument
/// ///
/// * `0`, a reference to the opaque value assigned to the peer /// * `0`, a reference to the opaque value assigned to the peer
pub trait KeyCallback<T>: Fn(&T) -> () + Sync + Send + 'static {} pub trait KeyCallback<T>: Fn(&T) + Sync + Send + 'static {}
impl<T, F> KeyCallback<T> for F where F: Fn(&T) -> () + Sync + Send + 'static {} impl<T, F> KeyCallback<T> for F where F: Fn(&T) + Sync + Send + 'static {}
pub trait Callbacks: Send + Sync + 'static { pub trait Callbacks: Send + Sync + 'static {
type Opaque: Opaque; type Opaque: Opaque;
@@ -58,11 +58,11 @@ impl fmt::Display for RouterError {
} }
impl Error for RouterError { impl Error for RouterError {
fn description(&self) -> &str {
"Generic Handshake Error"
}
fn source(&self) -> Option<&(dyn Error + 'static)> { fn source(&self) -> Option<&(dyn Error + 'static)> {
None None
} }
fn description(&self) -> &str {
"Generic Handshake Error"
}
} }

View File

@@ -6,7 +6,6 @@ use super::super::{tun, udp, Endpoint};
use super::types::Callbacks; use super::types::Callbacks;
use crossbeam_channel::Receiver; use crossbeam_channel::Receiver;
use log;
pub enum JobUnion<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> { pub enum JobUnion<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>> {
Outbound(SendJob<E, C, T, B>), Outbound(SendJob<E, C, T, B>),

View File

@@ -268,7 +268,6 @@ impl Timers {
handshake_attempts: AtomicUsize::new(0), handshake_attempts: AtomicUsize::new(0),
retransmit_handshake: { retransmit_handshake: {
let wg = wg.clone(); let wg = wg.clone();
let pk = pk.clone();
runner.timer(move || { runner.timer(move || {
// fetch peer by public key // fetch peer by public key
fetch_peer!(wg, pk, peer); fetch_peer!(wg, pk, peer);
@@ -300,7 +299,6 @@ impl Timers {
}, },
send_keepalive: { send_keepalive: {
let wg = wg.clone(); let wg = wg.clone();
let pk = pk.clone();
runner.timer(move || { runner.timer(move || {
// fetch peer by public key // fetch peer by public key
fetch_peer!(wg, pk, peer); fetch_peer!(wg, pk, peer);
@@ -315,7 +313,6 @@ impl Timers {
}, },
new_handshake: { new_handshake: {
let wg = wg.clone(); let wg = wg.clone();
let pk = pk.clone();
runner.timer(move || { runner.timer(move || {
// fetch peer by public key // fetch peer by public key
fetch_peer!(wg, pk, peer); fetch_peer!(wg, pk, peer);
@@ -333,7 +330,6 @@ impl Timers {
}, },
zero_key_material: { zero_key_material: {
let wg = wg.clone(); let wg = wg.clone();
let pk = pk.clone();
runner.timer(move || { runner.timer(move || {
// fetch peer by public key // fetch peer by public key
fetch_peer!(wg, pk, peer); fetch_peer!(wg, pk, peer);
@@ -345,7 +341,6 @@ impl Timers {
}, },
send_persistent_keepalive: { send_persistent_keepalive: {
let wg = wg.clone(); let wg = wg.clone();
let pk = pk.clone();
runner.timer(move || { runner.timer(move || {
// fetch peer by public key // fetch peer by public key
fetch_peer!(wg, pk, peer); fetch_peer!(wg, pk, peer);

View File

@@ -126,7 +126,7 @@ impl<T: Tun, B: UDP> WireGuard<T, B> {
let mut enabled = self.enabled.write(); let mut enabled = self.enabled.write();
// check if already down // check if already down
if *enabled == false { if !(*enabled) {
return; return;
} }
@@ -209,7 +209,7 @@ impl<T: Tun, B: UDP> WireGuard<T, B> {
let enabled = self.enabled.read(); let enabled = self.enabled.read();
// create timers (lookup by public key) // create timers (lookup by public key)
let timers = Timers::new::<T, B>(self.clone(), pk.clone(), *enabled); let timers = Timers::new::<T, B>(self.clone(), pk, *enabled);
// create new router peer // create new router peer
let peer: router::PeerHandle<B::Endpoint, PeerInner<T, B>, T::Writer, B::Writer> = let peer: router::PeerHandle<B::Endpoint, PeerInner<T, B>, T::Writer, B::Writer> =

View File

@@ -231,7 +231,7 @@ pub fn handshake_worker<T: Tun, B: UDP>(
} }
// add any new keypair to peer // add any new keypair to peer
keypair.map(|kp| { if let Some(kp) = keypair {
debug!("{} : handshake worker, new keypair for {}", wg, peer); debug!("{} : handshake worker, new keypair for {}", wg, peer);
// this means that a handshake response was processed or sent // this means that a handshake response was processed or sent
@@ -241,7 +241,7 @@ pub fn handshake_worker<T: Tun, B: UDP>(
for id in peer.add_keypair(kp) { for id in peer.add_keypair(kp) {
device.release(id); device.release(id);
} }
}); };
} }
} }
Err(e) => debug!("{} : handshake worker, error = {:?}", wg, e), Err(e) => debug!("{} : handshake worker, error = {:?}", wg, e),