Edition 2018

This commit is contained in:
Dennis Schwerdel 2019-03-01 23:12:19 +01:00
parent 73fd3134a5
commit 706d205ff1
13 changed files with 103 additions and 102 deletions

View File

@ -9,6 +9,7 @@ homepage = "https://vpncloud.ddswd.de"
repository = "https://github.com/dswd/vpncloud"
keywords = ["vpn", "p2p", "tun", "tap", "network"]
readme = "README.md"
edition = "2018"
[dependencies]
time = "0.1"

View File

@ -209,9 +209,9 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
pub fn write_to_file<P: AsRef<Path>>(&self, peers: &[SocketAddr], path: P) -> Result<(), io::Error> {
let beacon = self.encode(peers);
debug!("Beacon: {}", beacon);
let mut f = try!(File::create(&path));
try!(writeln!(&mut f, "{}", beacon));
try!(fs::set_permissions(&path, Permissions::from_mode(0o644)));
let mut f = File::create(&path)?;
writeln!(&mut f, "{}", beacon)?;
fs::set_permissions(&path, Permissions::from_mode(0o644))?;
Ok(())
}
@ -221,9 +221,9 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
let end = self.end();
let beacon = format!("{}{}{}", begin, data, end);
debug!("Calling beacon command: {}", cmd);
let process = try!(Command::new("sh").args(&["-c", cmd])
let process = Command::new("sh").args(&["-c", cmd])
.env("begin", begin).env("data", data).env("end", end).env("beacon", beacon)
.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn());
.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
thread::spawn(move || {
let output = process.wait_with_output().expect("Failed to wait on child");
if !output.status.success() {
@ -256,9 +256,9 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
}
pub fn read_from_file<P: AsRef<Path>>(&self, path: P, ttl_hours: Option<u16>) -> Result<Vec<SocketAddr>, io::Error> {
let mut f = try!(File::open(&path));
let mut f = File::open(&path)?;
let mut contents = String::new();
try!(f.read_to_string(&mut contents));
f.read_to_string(&mut contents)?;
Ok(self.decode(&contents, ttl_hours))
}
@ -266,9 +266,9 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
let begin = self.begin();
let end = self.end();
debug!("Calling beacon command: {}", cmd);
let process = try!(Command::new("sh").args(&["-c", cmd])
let process = Command::new("sh").args(&["-c", cmd])
.env("begin", begin).env("end", end)
.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn());
.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
let this = self.clone();
thread::spawn(move || {
let output = process.wait_with_output().expect("Failed to wait on child");
@ -301,7 +301,7 @@ impl<TS: TimeSource> BeaconSerializer<TS> {
#[cfg(test)] use std::str::FromStr;
#[cfg(test)] use std::time::Duration;
#[cfg(test)] use tempfile;
#[cfg(test)] use ::util::MockTimeSource;
#[cfg(test)] use crate::util::MockTimeSource;
#[test]
fn encode() {

View File

@ -87,7 +87,7 @@ impl<TS: TimeSource> PeerList<TS> {
#[inline]
pub fn is_connected<Addr: ToSocketAddrs+fmt::Debug>(&self, addr: Addr) -> Result<bool, Error> {
for addr in try!(resolve(&addr)) {
for addr in resolve(&addr)? {
if self.contains_addr(&addr) {
return Ok(true);
}
@ -181,10 +181,10 @@ impl<TS: TimeSource> PeerList<TS> {
#[inline]
fn write_out<W: Write>(&self, out: &mut W) -> Result<(), io::Error> {
try!(writeln!(out, "Peers:"));
writeln!(out, "Peers:")?;
let now = TS::now();
for (addr, data) in &self.peers {
try!(writeln!(out, " - {} (ttl: {} s)", addr, data.timeout-now));
writeln!(out, " - {} (ttl: {} s)", addr, data.timeout-now)?;
}
Ok(())
}
@ -296,11 +296,11 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
SocketAddr::V4(_) => &mut self.socket4,
SocketAddr::V6(_) => &mut self.socket6
};
try!(match socket.send(msg_data, *addr) {
match socket.send(msg_data, *addr) {
Ok(written) if written == msg_data.len() => Ok(()),
Ok(_) => Err(Error::Socket("Sent out truncated packet", io::Error::new(io::ErrorKind::Other, "truncated"))),
Err(e) => Err(Error::Socket("IOError when sending", e))
})
}?
}
Ok(())
}
@ -336,7 +336,7 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
/// Returns an IOError if the underlying system call fails
#[allow(dead_code)]
pub fn address(&self) -> io::Result<(SocketAddr, SocketAddr)> {
Ok((try!(self.socket4.address()), try!(self.socket6.address())))
Ok((self.socket4.address()?, self.socket6.address()?))
}
/// Returns the number of peers
@ -367,7 +367,7 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
/// Returns an `Error::SocketError` if the given address is a name that failed to resolve to
/// actual addresses.
fn is_own_address<Addr: ToSocketAddrs+fmt::Debug>(&self, addr: Addr) -> Result<bool, Error> {
for addr in try!(resolve(&addr)) {
for addr in resolve(&addr)? {
if self.own_addresses.contains(&addr) {
return Ok(true);
}
@ -384,14 +384,14 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
/// # Errors
/// This method returns `Error::NameError` if the address is a name that fails to resolve.
pub fn connect<Addr: ToSocketAddrs+fmt::Debug+Clone>(&mut self, addr: Addr) -> Result<(), Error> {
if try!(self.peers.is_connected(addr.clone())) || try!(self.is_own_address(addr.clone())) {
if self.peers.is_connected(addr.clone())? || self.is_own_address(addr.clone())? {
return Ok(())
}
debug!("Connecting to {:?}", addr);
let subnets = self.addresses.clone();
let node_id = self.node_id;
// Send a message to each resolved address
for a in try!(resolve(&addr)) {
for a in resolve(&addr)? {
// Ignore error this time
let mut msg = Message::Init(0, node_id, subnets.clone());
self.send_msg(a, &mut msg).ok();
@ -449,7 +449,7 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
let peers = self.peers.subset(peer_num);
// ...and send them to all peers
let mut msg = Message::Peers(peers);
try!(self.broadcast_msg(&mut msg));
self.broadcast_msg(&mut msg)?;
// Reschedule for next update
self.next_peerlist = now + Time::from(self.update_freq);
}
@ -458,11 +458,11 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
if entry.next > now {
continue
}
try!(self.connect(&entry.resolved as &[SocketAddr]));
self.connect(&entry.resolved as &[SocketAddr])?;
}
for entry in &mut self.reconnect_peers {
// Schedule for next second if node is connected
if try!(self.peers.is_connected(&entry.resolved as &[SocketAddr])) {
if self.peers.is_connected(&entry.resolved as &[SocketAddr])? {
entry.tries = 0;
entry.timeout = 1;
entry.next = now + 1;
@ -494,19 +494,19 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
}
if self.next_stats_out < now {
// Write out the statistics
try!(self.write_out_stats().map_err(|err| Error::File("Failed to write stats file", err)));
self.write_out_stats().map_err(|err| Error::File("Failed to write stats file", err))?;
self.next_stats_out = now + STATS_INTERVAL;
self.traffic.period(Some(60));
}
if let Some(peers) = self.beacon_serializer.get_cmd_results() {
debug!("Loaded beacon with peers: {:?}", peers);
for peer in peers {
try!(self.connect_sock(peer));
self.connect_sock(peer)?;
}
}
if self.next_beacon < now {
try!(self.store_beacon());
try!(self.load_beacon());
self.store_beacon()?;
self.load_beacon()?;
self.next_beacon = now + Time::from(self.config.beacon_interval);
}
Ok(())
@ -517,9 +517,9 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
if let Some(ref path) = self.config.beacon_store {
let peers: Vec<_> = self.own_addresses.choose_multiple(&mut thread_rng(),3).cloned().collect();
if path.starts_with('|') {
try!(self.beacon_serializer.write_to_cmd(&peers, &path[1..]).map_err(|e| Error::Beacon("Failed to call beacon command", e)));
self.beacon_serializer.write_to_cmd(&peers, &path[1..]).map_err(|e| Error::Beacon("Failed to call beacon command", e))?;
} else {
try!(self.beacon_serializer.write_to_file(&peers, &path).map_err(|e| Error::Beacon("Failed to write beacon to file", e)));
self.beacon_serializer.write_to_file(&peers, &path).map_err(|e| Error::Beacon("Failed to write beacon to file", e))?;
}
}
Ok(())
@ -530,17 +530,17 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
let peers;
if let Some(ref path) = self.config.beacon_load {
if path.starts_with('|') {
try!(self.beacon_serializer.read_from_cmd(&path[1..], Some(50)).map_err(|e| Error::Beacon("Failed to call beacon command", e)));
self.beacon_serializer.read_from_cmd(&path[1..], Some(50)).map_err(|e| Error::Beacon("Failed to call beacon command", e))?;
return Ok(())
} else {
peers = try!(self.beacon_serializer.read_from_file(&path, Some(50)).map_err(|e| Error::Beacon("Failed to read beacon from file", e)));
peers = self.beacon_serializer.read_from_file(&path, Some(50)).map_err(|e| Error::Beacon("Failed to read beacon from file", e))?;
}
} else {
return Ok(())
}
debug!("Loaded beacon with peers: {:?}", peers);
for peer in peers {
try!(self.connect_sock(peer));
self.connect_sock(peer)?;
}
Ok(())
}
@ -549,14 +549,14 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
fn write_out_stats(&mut self) -> Result<(), io::Error> {
if self.config.stats_file.is_none() { return Ok(()) }
debug!("Writing out stats");
let mut f = try!(File::create(self.config.stats_file.as_ref().unwrap()));
try!(self.peers.write_out(&mut f));
try!(writeln!(&mut f));
try!(self.table.write_out(&mut f));
try!(writeln!(&mut f));
try!(self.traffic.write_out(&mut f));
try!(writeln!(&mut f));
try!(fs::set_permissions(self.config.stats_file.as_ref().unwrap(), Permissions::from_mode(0o644)));
let mut f = File::create(self.config.stats_file.as_ref().unwrap())?;
self.peers.write_out(&mut f)?;
writeln!(&mut f)?;
self.table.write_out(&mut f)?;
writeln!(&mut f)?;
self.traffic.write_out(&mut f)?;
writeln!(&mut f)?;
fs::set_permissions(self.config.stats_file.as_ref().unwrap(), Permissions::from_mode(0o644))?;
Ok(())
}
@ -577,26 +577,26 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
/// - with `Error::ParseError` if the payload data failed to parse
/// - with `Error::SocketError` if sending a message fails
pub fn handle_interface_data(&mut self, payload: &mut [u8], start: usize, end: usize) -> Result<(), Error> {
let (src, dst) = try!(P::parse(&payload[start..end]));
let (src, dst) = P::parse(&payload[start..end])?;
debug!("Read data from interface: src: {}, dst: {}, {} bytes", src, dst, end-start);
self.traffic.count_out_payload(dst, src, end-start);
match self.table.lookup(&dst) {
Some(addr) => { // Peer found for destination
debug!("Found destination for {} => {}", dst, addr);
try!(self.send_msg(addr, &mut Message::Data(payload, start, end)));
self.send_msg(addr, &mut Message::Data(payload, start, end))?;
if !self.peers.contains_addr(&addr) {
// If the peer is not actually connected, remove the entry in the table and try
// to reconnect.
warn!("Destination for {} not found in peers: {}", dst, addr);
self.table.remove(&dst);
try!(self.connect_sock(addr));
self.connect_sock(addr)?;
}
},
None => {
if self.broadcast {
debug!("No destination for {} found, broadcasting", dst);
let mut msg = Message::Data(payload, start, end);
try!(self.broadcast_msg(&mut msg));
self.broadcast_msg(&mut msg)?;
} else {
debug!("No destination for {} found, dropping", dst);
}
@ -642,7 +642,7 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
debug!("Received {:?} from {}", msg, peer);
match msg {
Message::Data(payload, start, end) => {
let (src, dst) = try!(P::parse(&payload[start..end]));
let (src, dst) = P::parse(&payload[start..end])?;
debug!("Writing data to device: {} bytes", end-start);
self.traffic.count_in_payload(src, dst, end-start);
if let Err(e) = self.device.write(&mut payload[..end], start) {
@ -658,14 +658,14 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
Message::Peers(peers) => {
// Connect to sender if not connected
if !self.peers.contains_addr(&peer) {
try!(self.connect_sock(peer));
self.connect_sock(peer)?;
}
if let Some(node_id) = self.peers.get_node_id(&peer) {
self.peers.make_primary(node_id, peer);
}
// Connect to all peers in the message
for p in &peers {
try!(self.connect_sock(*p));
self.connect_sock(*p)?;
}
// Refresh peer
self.peers.refresh(&peer);
@ -689,11 +689,11 @@ impl<D: Device, P: Protocol, T: Table, S: Socket, TS: TimeSource> GenericCloud<D
if stage == 0 {
let own_addrs = self.addresses.clone();
let own_node_id = self.node_id;
try!(self.send_msg(peer, &mut Message::Init(stage+1, own_node_id, own_addrs)));
self.send_msg(peer, &mut Message::Init(stage+1, own_node_id, own_addrs))?;
}
// Send peers in any case
let peers = self.peers.as_vec();
try!(self.send_msg(peer, &mut Message::Peers(peers)));
self.send_msg(peer, &mut Message::Peers(peers))?;
},
Message::Close => {
self.peers.remove(&peer);

View File

@ -107,7 +107,7 @@ impl TunTapDevice {
if type_ == Type::Dummy {
return Self::dummy(ifname, path, type_);
}
let fd = try!(fs::OpenOptions::new().read(true).write(true).open(path));
let fd = fs::OpenOptions::new().read(true).write(true).open(path)?;
// Add trailing \0 to interface name
let mut ifname_string = String::with_capacity(32);
ifname_string.push_str(ifname);
@ -156,7 +156,7 @@ impl TunTapDevice {
#[allow(dead_code)]
pub fn dummy(ifname: &str, path: &str, type_: Type) -> io::Result<Self> {
Ok(TunTapDevice{
fd: try!(fs::OpenOptions::new().create(true).read(true).write(true).open(path)),
fd: fs::OpenOptions::new().create(true).read(true).write(true).open(path)?,
ifname: ifname.to_string(),
type_
})
@ -218,7 +218,7 @@ impl Device for TunTapDevice {
}
fn read(&mut self, mut buffer: &mut [u8]) -> Result<(usize, usize), Error> {
let read = try!(self.fd.read(&mut buffer).map_err(|e| Error::TunTapDev("Read error", e)));
let read = self.fd.read(&mut buffer).map_err(|e| Error::TunTapDev("Read error", e))?;
let (start, read) = self.correct_data_after_read(&mut buffer, 0, read);
Ok((start, read))
}

View File

@ -49,8 +49,8 @@ impl Protocol for Frame {
dst[2..8].copy_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));
let dst = try!(Address::read_from_fixed(dst_data, 6));
let src = Address::read_from_fixed(src_data, 6)?;
let dst = Address::read_from_fixed(dst_data, 6)?;
Ok((src, dst))
}
}
@ -105,9 +105,9 @@ impl<TS: TimeSource> Table for SwitchTable<TS> {
/// Write out the table
fn write_out<W: Write>(&self, out: &mut W) -> Result<(), io::Error> {
let now = TS::now();
try!(writeln!(out, "Switch table:"));
writeln!(out, "Switch table:")?;
for (addr, val) in &self.table {
try!(writeln!(out, " - {} => {} (ttl: {} s)", addr, val.address, val.timeout - now));
writeln!(out, " - {} => {} (ttl: {} s)", addr, val.address, val.timeout - now)?;
}
Ok(())
}

View File

@ -34,16 +34,16 @@ impl Protocol for Packet {
if data.len() < 20 {
return Err(Error::Parse("Truncated IPv4 header"));
}
let src = try!(Address::read_from_fixed(&data[12..], 4));
let dst = try!(Address::read_from_fixed(&data[16..], 4));
let src = Address::read_from_fixed(&data[12..], 4)?;
let dst = Address::read_from_fixed(&data[16..], 4)?;
Ok((src, dst))
},
6 => {
if data.len() < 40 {
return Err(Error::Parse("Truncated IPv6 header"));
}
let src = try!(Address::read_from_fixed(&data[8..], 16));
let dst = try!(Address::read_from_fixed(&data[24..], 16));
let src = Address::read_from_fixed(&data[8..], 16)?;
let dst = Address::read_from_fixed(&data[24..], 16)?;
Ok((src, dst))
},
_ => Err(Error::Parse("Invalid version"))
@ -149,10 +149,10 @@ impl Table for RoutingTable {
/// Write out the table
fn write_out<W: Write>(&self, out: &mut W) -> Result<(), io::Error> {
try!(writeln!(out, "Routing table:"));
writeln!(out, "Routing table:")?;
for entries in self.0.values() {
for entry in entries {
try!(writeln!(out, " - {}/{} => {}", entry.bytes, entry.prefix_len, entry.address));
writeln!(out, " - {}/{} => {}", entry.bytes, entry.prefix_len, entry.address)?;
}
}
Ok(())

View File

@ -51,15 +51,15 @@ use std::path::Path;
use std::io::{self, Write};
use std::net::UdpSocket;
use device::{TunTapDevice, Device, Type};
use ethernet::SwitchTable;
use ip::RoutingTable;
use types::{Mode, Range, Protocol, HeaderMagic, Error};
use cloud::GenericCloud;
use crypto::{Crypto, CryptoMethod};
use port_forwarding::PortForwarding;
use util::{Duration, SystemTimeSource};
use config::Config;
use crate::device::{TunTapDevice, Device, Type};
use crate::ethernet::SwitchTable;
use crate::ip::RoutingTable;
use crate::types::{Mode, Range, Protocol, HeaderMagic, Error};
use crate::cloud::GenericCloud;
use crate::crypto::{Crypto, CryptoMethod};
use crate::port_forwarding::PortForwarding;
use crate::util::{Duration, SystemTimeSource};
use crate::config::Config;
const VERSION: u8 = 1;
@ -109,7 +109,7 @@ struct DualLogger {
impl DualLogger {
pub fn new<P: AsRef<Path>>(path: Option<P>) -> Result<Self, io::Error> {
if let Some(path) = path {
let file = try!(File::create(path));
let file = File::create(path)?;
Ok(DualLogger{file: Mutex::new(Some(file))})
} else {
Ok(DualLogger{file: Mutex::new(None)})

View File

@ -6,11 +6,11 @@ use libc;
use std::os::unix::io::RawFd;
use std::io;
use device::Device;
use crate::device::Device;
use super::WaitResult;
use ::device::Type;
use net::Socket;
use crate::device::Type;
use crate::net::Socket;
pub struct EpollWait {
poll_fd: RawFd,

View File

@ -73,7 +73,7 @@ fn msg6_put<P: Protocol, T: Table>(node: &mut TestNode<P, T>, from: SocketAddr,
}
fn simulate<P: Protocol, T: Table>(nodes: &mut [(&mut TestNode<P, T>, SocketAddr)]) {
for (ref mut node, ref from_addr) in nodes.iter_mut() {
for (ref mut node, ref _from_addr) in nodes.iter_mut() {
while node.device().has_inbound() {
node.trigger_device_event();
}

View File

@ -105,18 +105,18 @@ impl TrafficStats {
#[inline]
pub fn write_out<W: Write>(&self, out: &mut W) -> Result<(), io::Error> {
try!(writeln!(out, "Peer traffic:"));
writeln!(out, "Peer traffic:")?;
let mut peers: Vec<_> = self.get_peer_traffic().collect();
peers.sort_unstable_by_key(|(_, data)| (data.out_bytes + data.in_bytes));
for (addr, data) in peers.iter().rev() {
try!(writeln!(out, " - {}: in={}/s, out={}/s", addr, Bytes(data.in_bytes/60), Bytes(data.out_bytes/60)));
writeln!(out, " - {}: in={}/s, out={}/s", addr, Bytes(data.in_bytes/60), Bytes(data.out_bytes/60))?;
}
try!(writeln!(out));
try!(writeln!(out, "Payload traffic:"));
writeln!(out)?;
writeln!(out, "Payload traffic:")?;
let mut payload: Vec<_> = self.get_payload_traffic().collect();
payload.sort_unstable_by_key(|(_, data)| (data.out_bytes + data.in_bytes));
for ((remote, local), data) in payload.iter().rev() {
try!(writeln!(out, " - {} <-> {}: in={}/s, out={}/s", remote, local, Bytes(data.in_bytes/60), Bytes(data.out_bytes/60)));
writeln!(out, " - {} <-> {}: in={}/s, out={}/s", remote, local, Bytes(data.in_bytes/60), Bytes(data.out_bytes/60))?;
}
Ok(())
}

View File

@ -29,7 +29,7 @@ impl Address {
return Err(Error::Parse("Address too short"));
}
let len = data[0] as usize;
let addr = try!(Address::read_from_fixed(&data[1..], len));
let addr = Address::read_from_fixed(&data[1..], len)?;
Ok((addr, len + 1))
}
@ -121,7 +121,7 @@ impl FromStr for Address {
if parts.len() == 6 {
let mut bytes = [0; 16];
for i in 0..6 {
bytes[i] = try!(u8::from_str_radix(parts[i], 16).map_err(|_| Error::Parse("Failed to parse mac")));
bytes[i] = u8::from_str_radix(parts[i], 16).map_err(|_| Error::Parse("Failed to parse mac"))?;
}
return Ok(Address{data: bytes, len: 6});
}
@ -139,7 +139,7 @@ pub struct Range {
impl Range {
#[inline]
pub fn read_from(data: &[u8]) -> Result<(Range, usize), Error> {
let (address, read) = try!(Address::read_from(data));
let (address, read) = Address::read_from(data)?;
if data.len() < read + 1 {
return Err(Error::Parse("Range too short"));
}
@ -164,9 +164,9 @@ impl FromStr for Range {
Some(pos) => pos,
None => return Err(Error::Parse("Invalid range format"))
};
let prefix_len = try!(u8::from_str(&text[pos+1..])
.map_err(|_| Error::Parse("Failed to parse prefix length")));
let base = try!(Address::from_str(&text[..pos]));
let prefix_len = u8::from_str(&text[pos+1..])
.map_err(|_| Error::Parse("Failed to parse prefix length"))?;
let base = Address::from_str(&text[..pos])?;
Ok(Range{base, prefix_len})
}
}
@ -207,16 +207,16 @@ impl fmt::Display for Mode {
}
pub trait Table {
fn learn(&mut self, Address, Option<u8>, SocketAddr);
fn lookup(&mut self, &Address) -> Option<SocketAddr>;
fn learn(&mut self, _: Address, _: Option<u8>, _: SocketAddr);
fn lookup(&mut self, _: &Address) -> Option<SocketAddr>;
fn housekeep(&mut self);
fn write_out<W: Write>(&self, out: &mut W) -> Result<(), io::Error>;
fn remove(&mut self, &Address) -> bool;
fn remove_all(&mut self, &SocketAddr);
fn remove(&mut self, _: &Address) -> bool;
fn remove_all(&mut self, _: &SocketAddr);
}
pub trait Protocol: Sized {
fn parse(&[u8]) -> Result<(Address, Address), Error>;
fn parse(_: &[u8]) -> Result<(Address, Address), Error>;
}
#[derive(Debug)]
@ -278,10 +278,10 @@ fn address_decode_encode() {
#[test]
fn address_eq() {
assert!(Address::read_from_fixed(&[1,2,3,4], 4).unwrap() == Address::read_from_fixed(&[1,2,3,4], 4).unwrap());
assert!(Address::read_from_fixed(&[1,2,3,4], 4).unwrap() != Address::read_from_fixed(&[1,2,3,5], 4).unwrap());
assert!(Address::read_from_fixed(&[1,2,3,4], 3).unwrap() == Address::read_from_fixed(&[1,2,3,5], 3).unwrap());
assert!(Address::read_from_fixed(&[1,2,3,4], 3).unwrap() != Address::read_from_fixed(&[1,2,3,4], 4).unwrap());
assert_eq!(Address::read_from_fixed(&[1,2,3,4], 4).unwrap(), Address::read_from_fixed(&[1,2,3,4], 4).unwrap());
assert_ne!(Address::read_from_fixed(&[1,2,3,4], 4).unwrap(), Address::read_from_fixed(&[1,2,3,5], 4).unwrap());
assert_eq!(Address::read_from_fixed(&[1,2,3,4], 3).unwrap(), Address::read_from_fixed(&[1,2,3,5], 3).unwrap());
assert_ne!(Address::read_from_fixed(&[1,2,3,4], 3).unwrap(), Address::read_from_fixed(&[1,2,3,4], 4).unwrap());
}
#[test]

View File

@ -71,14 +71,14 @@ impl<'a> fmt::Debug for Message<'a> {
match *self {
Message::Data(_, start, end) => write!(formatter, "Data({} bytes)", end-start),
Message::Peers(ref peers) => {
try!(write!(formatter, "Peers ["));
write!(formatter, "Peers [")?;
let mut first = true;
for p in peers {
if !first {
try!(write!(formatter, ", "));
write!(formatter, ", ")?;
}
first = false;
try!(write!(formatter, "{}", p));
write!(formatter, "{}", p)?;
}
write!(formatter, "]")
},
@ -91,7 +91,7 @@ impl<'a> fmt::Debug for Message<'a> {
#[allow(unknown_lints,clippy::needless_range_loop)]
pub fn decode<'a>(data: &'a mut [u8], magic: HeaderMagic, crypto: &Crypto) -> Result<Message<'a>, Error> {
let mut end = data.len();
let (header, mut pos) = try!(TopHeader::read_from(&data[..end]));
let (header, mut pos) = TopHeader::read_from(&data[..end])?;
if header.magic != magic {
return Err(Error::WrongHeaderMagic(header.magic));
}
@ -107,7 +107,7 @@ pub fn decode<'a>(data: &'a mut [u8], magic: HeaderMagic, crypto: &Crypto) -> Re
let (before, after) = data.split_at_mut(pos);
let (nonce, crypto_data) = after.split_at_mut(len);
pos += len;
end = try!(crypto.decrypt(crypto_data, nonce, &before[..TopHeader::size()])) + pos;
end = crypto.decrypt(crypto_data, nonce, &before[..TopHeader::size()])? + pos;
}
assert_eq!(end, data.len()-crypto.additional_bytes());
}
@ -169,7 +169,7 @@ pub fn decode<'a>(data: &'a mut [u8], magic: HeaderMagic, crypto: &Crypto) -> Re
pos += 1;
let mut addrs = Vec::with_capacity(count);
for _ in 0..count {
let (range, read) = try!(Range::read_from(&data[pos..end]));
let (range, read) = Range::read_from(&data[pos..end])?;
pos += read;
addrs.push(range);
}

View File

@ -117,7 +117,7 @@ macro_rules! try_fail {
#[allow(unknown_lints,clippy::needless_pass_by_value)]
pub fn resolve<Addr: ToSocketAddrs+fmt::Debug>(addr: Addr) -> Result<Vec<SocketAddr>, Error> {
let addrs = try!(addr.to_socket_addrs().map_err(|_| Error::Name(format!("{:?}", addr))));
let addrs = addr.to_socket_addrs().map_err(|_| Error::Name(format!("{:?}", addr)))?;
// Remove duplicates in addrs (why are there duplicates???)
let mut addrs = addrs.collect::<Vec<_>>();
// Try IPv4 first as it usually is faster