Making clippy happy

This commit is contained in:
Dennis Schwerdel 2016-06-11 16:08:57 +02:00
parent b8c2ce5bea
commit f933db2dd9
9 changed files with 120 additions and 103 deletions

View File

@ -65,23 +65,23 @@ impl PeerList {
del
}
#[inline(always)]
#[inline]
fn contains_addr(&self, addr: &SocketAddr) -> bool {
self.addresses.contains(addr)
}
#[inline]
fn is_connected<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> {
let mut addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
while let Some(a) = addrs.next() {
if self.contains_addr(&a) {
let addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
for addr in addrs {
if self.contains_addr(&addr) {
return Ok(true);
}
}
Ok(false)
}
#[inline(always)]
#[inline]
fn contains_node(&self, node_id: &NodeId) -> bool {
self.nodes.contains_key(node_id)
}
@ -112,14 +112,20 @@ impl PeerList {
#[inline]
fn as_vec(&self) -> Vec<SocketAddr> {
self.addresses.iter().map(|addr| *addr).collect()
self.addresses.iter().cloned().collect()
}
#[inline(always)]
#[inline]
fn len(&self) -> usize {
self.peers.len()
}
#[inline]
#[allow(dead_code)]
fn is_empty(&self) -> bool {
self.peers.is_empty()
}
#[inline]
fn subset(&self, size: usize) -> Vec<SocketAddr> {
sample(&mut thread_rng(), self.as_vec(), size)
@ -127,7 +133,7 @@ impl PeerList {
#[inline]
fn remove(&mut self, addr: &SocketAddr) {
if let Some((_timeout, node_id, alt_addrs)) = self.peers.remove(&addr) {
if let Some((_timeout, node_id, alt_addrs)) = self.peers.remove(addr) {
info!("Removed peer: {}", addr);
self.nodes.remove(&node_id);
self.addresses.remove(addr);
@ -214,11 +220,11 @@ impl<P: Protocol> GenericCloud<P> {
#[inline]
fn broadcast_msg(&mut self, msg: &mut Message) -> Result<(), Error> {
debug!("Broadcasting {:?}", msg);
let msg_data = encode(&mut self.options, msg, &mut self.buffer_out, &mut self.crypto);
for addr in &self.peers.as_vec() {
let msg_data = encode(&self.options, msg, &mut self.buffer_out, &mut self.crypto);
for addr in self.peers.as_vec() {
let socket = match addr {
&SocketAddr::V4(_) => &self.socket4,
&SocketAddr::V6(_) => &self.socket6
SocketAddr::V4(_) => &self.socket4,
SocketAddr::V6(_) => &self.socket6
};
try!(match socket.send_to(msg_data, addr) {
Ok(written) if written == msg_data.len() => Ok(()),
@ -235,10 +241,10 @@ impl<P: Protocol> GenericCloud<P> {
#[inline]
fn send_msg(&mut self, addr: SocketAddr, msg: &mut Message) -> Result<(), Error> {
debug!("Sending {:?} to {}", msg, addr);
let msg_data = encode(&mut self.options, msg, &mut self.buffer_out, &mut self.crypto);
let socket = match &addr {
&SocketAddr::V4(_) => &self.socket4,
&SocketAddr::V6(_) => &self.socket6
let msg_data = encode(&self.options, msg, &mut self.buffer_out, &mut self.crypto);
let socket = match addr {
SocketAddr::V4(_) => &self.socket4,
SocketAddr::V6(_) => &self.socket6
};
match socket.send_to(msg_data, addr) {
Ok(written) if written == msg_data.len() => Ok(()),
@ -270,9 +276,9 @@ impl<P: Protocol> GenericCloud<P> {
}
fn is_blacklisted<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> {
let mut addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
while let Some(a) = addrs.next() {
if self.blacklist_peers.contains(&a) {
let addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
for addr in addrs {
if self.blacklist_peers.contains(&addr) {
return Ok(true);
}
}
@ -285,7 +291,7 @@ impl<P: Protocol> GenericCloud<P> {
}
debug!("Connecting to {}", addr);
let subnets = self.addresses.clone();
let node_id = self.node_id.clone();
let node_id = self.node_id;
let mut msg = Message::Init(0, node_id, subnets);
if let Ok(addrs) = addr.to_socket_addrs() {
let mut addrs = addrs.collect::<Vec<_>>();
@ -414,13 +420,13 @@ impl<P: Protocol> GenericCloud<P> {
} else {
self.peers.add(node_id, peer);
for range in ranges {
self.table.learn(range.base, Some(range.prefix_len), peer.clone());
self.table.learn(range.base, Some(range.prefix_len), peer);
}
}
if stage == 0 {
let peers = self.peers.as_vec();
let own_addrs = self.addresses.clone();
let own_node_id = self.node_id.clone();
let own_node_id = self.node_id;
try!(self.send_msg(peer, &mut Message::Init(stage+1, own_node_id, own_addrs)));
try!(self.send_msg(peer, &mut Message::Peers(peers)));
}
@ -451,23 +457,23 @@ impl<P: Protocol> GenericCloud<P> {
loop {
let count = try_fail!(epoll::wait(epoll_handle, &mut events, 1000), "Epoll wait failed: {}") as usize;
// Process events
for i in 0..count {
match &events[i].data {
&0 => {
for evt in events.iter().take(count) {
match evt.data {
0 => {
let (size, src) = try_fail!(self.socket4.recv_from(&mut buffer), "Failed to read from ipv4 network socket: {}");
match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) {
Ok(_) => (),
Err(e) => error!("Error: {}, from: {}", e, src)
}
},
&1 => {
1 => {
let (size, src) = try_fail!(self.socket6.recv_from(&mut buffer), "Failed to read from ipv6 network socket: {}");
match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) {
Ok(_) => (),
Err(e) => error!("Error: {}, from: {}", e, src)
}
},
&2 => {
2 => {
let start = 64;
let size = try_fail!(self.device.read(&mut buffer[start..]), "Failed to read from tap device: {}");
match self.handle_interface_data(&mut buffer, start, start+size) {

View File

@ -170,31 +170,31 @@ impl Crypto {
}
pub fn method(&self) -> u8 {
match self {
&Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, nonce: _} => 1,
&Crypto::AES256GCM{state: _, nonce: _} => 2
match *self {
Crypto::None => 0,
Crypto::ChaCha20Poly1305{..} => 1,
Crypto::AES256GCM{..} => 2
}
}
pub fn nonce_bytes(&self) -> usize {
match self {
&Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, ref nonce} => nonce.len(),
&Crypto::AES256GCM{state: _, ref nonce} => nonce.len()
match *self {
Crypto::None => 0,
Crypto::ChaCha20Poly1305{ref nonce, ..} => nonce.len(),
Crypto::AES256GCM{ref nonce, ..} => nonce.len()
}
}
pub fn additional_bytes(&self) -> usize {
match self {
&Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, nonce: _} => crypto_aead_chacha20poly1305_ietf_ABYTES,
&Crypto::AES256GCM{state: _, nonce: _} => crypto_aead_aes256gcm_ABYTES
match *self {
Crypto::None => 0,
Crypto::ChaCha20Poly1305{..} => crypto_aead_chacha20poly1305_ietf_ABYTES,
Crypto::AES256GCM{..} => crypto_aead_aes256gcm_ABYTES
}
}
pub fn from_shared_key(method: CryptoMethod, password: &str) -> Self {
let salt = "vpncloudVPNCLOUDvpncl0udVpnCloud".as_bytes();
let salt = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
assert_eq!(salt.len(), crypto_pwhash_scryptsalsa208sha256_SALTBYTES);
let mut key = [0; crypto_pwhash_scryptsalsa208sha256_STRBYTES];
let res = unsafe { crypto_pwhash_scryptsalsa208sha256(
@ -235,9 +235,9 @@ impl Crypto {
}
pub fn decrypt(&self, mut buf: &mut [u8], nonce: &[u8], header: &[u8]) -> Result<usize, Error> {
match self {
&Crypto::None => Ok(buf.len()),
&Crypto::ChaCha20Poly1305{ref key, nonce: _} => {
match *self {
Crypto::None => Ok(buf.len()),
Crypto::ChaCha20Poly1305{ref key, ..} => {
let mut mlen: u64 = buf.len() as u64;
let res = unsafe { crypto_aead_chacha20poly1305_ietf_decrypt(
buf.as_mut_ptr(), // Base pointer to buffer
@ -255,7 +255,7 @@ impl Crypto {
_ => Err(Error::CryptoError("Failed to decrypt"))
}
},
&Crypto::AES256GCM{ref state, nonce: _} => {
Crypto::AES256GCM{ref state, ..} => {
let mut mlen: u64 = buf.len() as u64;
let res = unsafe { crypto_aead_aes256gcm_decrypt_afternm(
buf.as_mut_ptr(), // Base pointer to buffer
@ -277,9 +277,9 @@ impl Crypto {
}
pub fn encrypt(&mut self, mut buf: &mut [u8], mlen: usize, nonce_bytes: &mut [u8], header: &[u8]) -> usize {
match self {
&mut Crypto::None => mlen,
&mut Crypto::ChaCha20Poly1305{ref key, ref mut nonce} => {
match *self {
Crypto::None => mlen,
Crypto::ChaCha20Poly1305{ref key, ref mut nonce} => {
inc_nonce_12(nonce);
let mut clen: u64 = buf.len() as u64;
assert!(nonce_bytes.len() == nonce.len());
@ -301,7 +301,7 @@ impl Crypto {
}
clen as usize
},
&mut Crypto::AES256GCM{ref state, ref mut nonce} => {
Crypto::AES256GCM{ref state, ref mut nonce} => {
inc_nonce_12(nonce);
let mut clen: u64 = buf.len() as u64;
assert!(nonce_bytes.len() == nonce.len());

View File

@ -47,7 +47,7 @@ impl Device {
Ok(Device{fd: try!(fs::OpenOptions::new().create(true).read(true).write(true).open(path)), ifname: ifname.to_string()})
}
#[inline(always)]
#[inline]
pub fn ifname(&self) -> &str {
&self.ifname
}
@ -59,7 +59,7 @@ impl Device {
#[inline]
pub fn write(&mut self, data: &[u8]) -> Result<(), Error> {
match self.fd.write_all(&data) {
match self.fd.write_all(data) {
Ok(_) => self.fd.flush().map_err(|_| Error::TunTapDevError("Flush error")),
Err(_) => Err(Error::TunTapDevError("Write error"))
}
@ -67,7 +67,7 @@ impl Device {
}
impl AsRawFd for Device {
#[inline(always)]
#[inline]
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}

View File

@ -32,8 +32,8 @@ impl Protocol for Frame {
let mut dst = [0; 16];
src[0] = data[pos]; src[1] = data[pos+1];
dst[0] = data[pos]; dst[1] = data[pos+1];
src[2..8].clone_from_slice(&src_data);
dst[2..8].clone_from_slice(&dst_data);
src[2..8].clone_from_slice(src_data);
dst[2..8].clone_from_slice(dst_data);
Ok((Address{data: src, len: 8}, Address{data: dst, len: 8}))
} else {
let src = try!(Address::read_from_fixed(&src_data, 6));
@ -69,7 +69,7 @@ impl Table for SwitchTable {
let mut del: Vec<Address> = Vec::new();
for (key, val) in &self.table {
if val.timeout < now {
del.push(key.clone());
del.push(*key);
}
}
for key in del {
@ -102,9 +102,9 @@ impl Table for SwitchTable {
fn remove_all(&mut self, addr: &SocketAddr) {
let mut remove = Vec::new();
for (key, val) in self.table.iter() {
for (key, val) in &self.table {
if &val.address == addr {
remove.push(key.clone());
remove.push(*key);
}
}
for key in remove {

View File

@ -140,7 +140,7 @@ impl Table for RoutingTable {
}
fn remove_all(&mut self, addr: &SocketAddr) {
for (_key, entry) in self.0.iter_mut() {
for (_key, entry) in &mut self.0 {
entry.retain(|entr| &entr.address != addr);
}
}

View File

@ -47,12 +47,12 @@ use util::Duration;
struct SimpleLogger;
impl log::Log for SimpleLogger {
#[inline(always)]
#[inline]
fn enabled(&self, _metadata: &log::LogMetadata) -> bool {
true
}
#[inline(always)]
#[inline]
fn log(&self, record: &log::LogRecord) {
if self.enabled(record.metadata()) {
println!("{} - {}", record.level(), record.args());
@ -87,9 +87,10 @@ fn run_script(script: String, ifname: &str) {
cmd.arg("-c").arg(&script).env("IFNAME", ifname);
debug!("Running script: {:?}", cmd);
match cmd.status() {
Ok(status) => match status.success() {
true => (),
false => error!("Script returned with error: {:?}", status.code())
Ok(status) => if status.success() {
()
} else {
error!("Script returned with error: {:?}", status.code())
},
Err(e) => error!("Failed to execute script {:?}: {}", script, e)
}

View File

@ -5,6 +5,7 @@
use std::net::{SocketAddr, Ipv4Addr, Ipv6Addr};
use std::fmt;
use std::str::FromStr;
use std::hash::{Hash, Hasher};
use super::util::{bytes_to_hex, Encoder};
@ -14,7 +15,7 @@ pub type NetworkId = u64;
pub type NodeId = [u8; NODE_ID_BYTES];
#[derive(PartialOrd, Eq, Ord, Clone, Hash, Copy)]
#[derive(PartialOrd, Eq, Ord, Clone, Copy)]
pub struct Address {
pub data: [u8; 16],
pub len: u8
@ -70,6 +71,15 @@ impl PartialEq for Address {
}
}
impl Hash for Address {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write(&self.data[0..self.len as usize])
}
}
impl fmt::Display for Address {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let d = &self.data;
@ -121,7 +131,7 @@ impl FromStr for Address {
}
return Ok(Address{data: bytes, len: 6});
}
return Err(Error::ParseError("Failed to parse address"))
Err(Error::ParseError("Failed to parse address"))
}
}
@ -156,7 +166,7 @@ impl FromStr for Range {
type Err=Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let pos = match text.find("/") {
let pos = match text.find('/') {
Some(pos) => pos,
None => return Err(Error::ParseError("Invalid range format"))
};
@ -186,9 +196,9 @@ pub enum Type {
}
impl fmt::Display for Type {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&Type::Tun => write!(formatter, "tun"),
&Type::Tap => write!(formatter, "tap"),
match *self {
Type::Tun => write!(formatter, "tun"),
Type::Tap => write!(formatter, "tap"),
}
}
}
@ -200,11 +210,11 @@ pub enum Mode {
}
impl fmt::Display for Mode {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&Mode::Normal => write!(formatter, "normal"),
&Mode::Hub => write!(formatter, "hub"),
&Mode::Switch => write!(formatter, "switch"),
&Mode::Router => write!(formatter, "router"),
match *self {
Mode::Normal => write!(formatter, "normal"),
Mode::Hub => write!(formatter, "hub"),
Mode::Switch => write!(formatter, "switch"),
Mode::Router => write!(formatter, "router"),
}
}
}
@ -231,13 +241,13 @@ pub enum Error {
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&Error::ParseError(ref msg) => write!(formatter, "{}", msg),
&Error::SocketError(ref msg) => write!(formatter, "{}", msg),
&Error::TunTapDevError(ref msg) => write!(formatter, "{}", msg),
&Error::CryptoError(ref msg) => write!(formatter, "{}", msg),
&Error::WrongNetwork(Some(net)) => write!(formatter, "wrong network id: {}", net),
&Error::WrongNetwork(None) => write!(formatter, "wrong network id: none"),
match *self {
Error::ParseError(ref msg) => write!(formatter, "{}", msg),
Error::SocketError(ref msg) => write!(formatter, "{}", msg),
Error::TunTapDevError(ref msg) => write!(formatter, "{}", msg),
Error::CryptoError(ref msg) => write!(formatter, "{}", msg),
Error::WrongNetwork(Some(net)) => write!(formatter, "wrong network id: {}", net),
Error::WrongNetwork(None) => write!(formatter, "wrong network id: none"),
}
}
}

View File

@ -26,7 +26,7 @@ struct TopHeader {
}
impl TopHeader {
#[inline(always)]
#[inline]
pub fn size() -> usize {
8
}
@ -74,9 +74,9 @@ pub enum Message<'a> {
impl<'a> fmt::Debug for Message<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&Message::Data(_, start, end) => write!(formatter, "Data({} bytes)", end-start),
&Message::Peers(ref peers) => {
match *self {
Message::Data(_, start, end) => write!(formatter, "Data({} bytes)", end-start),
Message::Peers(ref peers) => {
try!(write!(formatter, "Peers ["));
let mut first = true;
for p in peers {
@ -88,8 +88,8 @@ impl<'a> fmt::Debug for Message<'a> {
}
write!(formatter, "]")
},
&Message::Init(stage, ref node_id, ref peers) => write!(formatter, "Init(stage={}, node_id={}, {:?})", stage, bytes_to_hex(node_id), peers),
&Message::Close => write!(formatter, "Close"),
Message::Init(stage, ref node_id, ref peers) => write!(formatter, "Init(stage={}, node_id={}, {:?})", stage, bytes_to_hex(node_id), peers),
Message::Close => write!(formatter, "Close"),
}
}
}
@ -196,19 +196,19 @@ pub fn decode<'a>(data: &'a mut [u8], crypto: &mut Crypto) -> Result<(Options, M
pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8], crypto: &mut Crypto) -> &'a mut [u8] {
let mut start = 64;
let mut end = 64;
match msg {
&mut Message::Data(ref mut data, data_start, data_end) => {
match *msg {
Message::Data(ref mut data, data_start, data_end) => {
buf = data;
start = data_start;
end = data_end;
},
&mut Message::Peers(ref peers) => {
Message::Peers(ref peers) => {
let mut v4addrs = Vec::new();
let mut v6addrs = Vec::new();
for p in peers {
match p {
&SocketAddr::V4(addr) => v4addrs.push(addr),
&SocketAddr::V6(addr) => v6addrs.push(addr)
match *p {
SocketAddr::V4(addr) => v4addrs.push(addr),
SocketAddr::V6(addr) => v6addrs.push(addr)
}
};
assert!(v4addrs.len() <= 255);
@ -237,7 +237,7 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
};
end = pos;
},
&mut Message::Init(stage, ref node_id, ref ranges) => {
Message::Init(stage, ref node_id, ref ranges) => {
let mut pos = start;
assert!(buf.len() >= pos + 2 + NODE_ID_BYTES);
buf[pos] = stage;
@ -252,7 +252,7 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
}
end = pos;
},
&mut Message::Close => {
Message::Close => {
}
}
assert!(start >= 64);
@ -265,11 +265,11 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
let crypto_start = start;
start -= crypto.nonce_bytes();
let mut header = TopHeader::default();
header.msgtype = match msg {
&mut Message::Data(_, _, _) => 0,
&mut Message::Peers(_) => 1,
&mut Message::Init(_, _, _) => 2,
&mut Message::Close => 3
header.msgtype = match *msg {
Message::Data(_, _, _) => 0,
Message::Peers(_) => 1,
Message::Init(_, _, _) => 2,
Message::Close => 3
};
header.crypto_method = crypto.method();
if options.network_id.is_some() {

View File

@ -42,18 +42,18 @@ pub fn bytes_to_hex(bytes: &[u8]) -> String {
pub struct Encoder;
impl Encoder {
#[inline(always)]
#[inline]
pub fn read_u16(data: &[u8]) -> u16 {
((data[0] as u16) << 8) | data[1] as u16
}
#[inline(always)]
#[inline]
pub fn write_u16(val: u16, data: &mut [u8]) {
data[0] = ((val >> 8) & 0xff) as u8;
data[1] = (val & 0xff) as u8;
}
#[inline(always)]
#[inline]
pub fn read_u64(data: &[u8]) -> u64 {
((data[0] as u64) << 56) | ((data[1] as u64) << 48) |
((data[2] as u64) << 40) | ((data[3] as u64) << 32) |
@ -61,7 +61,7 @@ impl Encoder {
((data[6] as u64) << 8) | data[7] as u64
}
#[inline(always)]
#[inline]
pub fn write_u64(val: u64, data: &mut [u8]) {
data[0] = ((val >> 56) & 0xff) as u8;
data[1] = ((val >> 48) & 0xff) as u8;