Skip to content

Commit

Permalink
Merge 41953fe into 6657c84
Browse files Browse the repository at this point in the history
  • Loading branch information
kurnevsky committed Sep 26, 2021
2 parents 6657c84 + 41953fe commit d918ab2
Show file tree
Hide file tree
Showing 38 changed files with 903 additions and 1,176 deletions.
3 changes: 2 additions & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ log = "0.4"
futures = { version = "0.3", default-features = false, features = ["std", "async-await"] }
env_logger = "0.9"
hex = "0.4"
failure = "0.1"
thiserror = "1.0"
rand = "0.8"
anyhow = "1.0"

[dev-dependencies.tokio]
version = "1.12"
Expand Down
2 changes: 1 addition & 1 deletion examples/dht_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ extern crate log;

use futures::future::FutureExt;
use futures::channel::mpsc;
use failure::Error;
use anyhow::Error;
use rand::thread_rng;

use std::net::SocketAddr;
Expand Down
4 changes: 2 additions & 2 deletions examples/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ extern crate log;
use futures::{*, future::TryFutureExt};
use futures::channel::mpsc;
use hex::FromHex;
use failure::{err_msg, Error};
use anyhow::Error;
use rand::thread_rng;

use std::net::SocketAddr;
Expand Down Expand Up @@ -174,7 +174,7 @@ async fn main() -> Result<(), Error> {
Ok((_, share_relays)) =>
friend_connections_c.handle_share_relays(pk, share_relays)
.map_err(Error::from).await?,
_ => return Err(err_msg("Failed to parse ShareRelays"))
_ => return Err(Error::msg("Failed to parse ShareRelays"))
}
},
0x18 => { // PACKET_ID_ONLINE
Expand Down
11 changes: 7 additions & 4 deletions examples/onion_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extern crate log;

use std::net::{SocketAddr, IpAddr};

use failure::Error;
use anyhow::Error;
use futures::future::FutureExt;
use futures::stream::StreamExt;
use futures::sink::SinkExt;
Expand Down Expand Up @@ -91,11 +91,14 @@ async fn main() -> Result<(), Error> {
while let Some(event) = stream.next().await {
let (packet, addr) = match event {
Ok(ev) => ev,
Err(ref e) => {
Err(e) => {
error!("packet receive error = {:?}", e);

if *e.kind() == DecodeErrorKind::Io { continue }
else { unimplemented!() }
if let DecodeError::Io(e) = e {
return Err(Error::new(e));
} else {
continue;
}
}
};

Expand Down
4 changes: 2 additions & 2 deletions examples/tcp_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use tox_core::relay::handshake::make_client_handshake;
use tox_core::relay::codec;
use tox_core::stats::Stats;

use failure::{Error, err_msg};
use anyhow::Error;

use hex::FromHex;

Expand Down Expand Up @@ -81,7 +81,7 @@ async fn create_client(mut rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>)
tx.clone().send(Packet::PongResponse(
PongResponse { ping_id: ping.ping_id }
))
.map_err(|_| err_msg("Could not send pong") )
.map_err(|_| Error::msg("Could not send pong") )
.await?;
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/tcp_server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[macro_use]
extern crate log;

use failure::Error;
use anyhow::Error;
use tox_crypto::*;
use tox_core::relay::server::{Server, tcp_run};
use tox_core::stats::Stats;
Expand Down
2 changes: 1 addition & 1 deletion tox_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ log = "0.4"
nom = "5.1"
cookie-factory = "0.3"
get_if_addrs = "0.5"
failure = "0.1"
thiserror = "1.0"
lru = "0.6"
bitflags = "1.3"
itertools = "0.10"
Expand Down
100 changes: 42 additions & 58 deletions tox_core/src/dht/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,88 +9,74 @@ use crate::stats::*;

use bytes::BytesMut;
use cookie_factory::GenError;
use failure::Fail;
use thiserror::Error;
use nom::{error::ErrorKind, Err};
use tokio_util::codec::{Decoder, Encoder};

/// A serialized `Packet` should be not longer than 2048 bytes.
pub const MAX_DHT_PACKET_SIZE: usize = 2048;

error_kind! {
#[doc = "Error that can happen when decoding `Packet` from bytes."]
#[derive(Debug)]
DecodeError,
#[doc = "Error that can happen when decoding `Packet` from bytes."]
#[derive(Clone, Debug, Eq, PartialEq, Fail)]
DecodeErrorKind {
#[doc = "Error indicates that we received too big packet."]
#[fail(display = "Packet should not be longer than 2048 bytes: {} bytes", len)]
TooBigPacket {
#[doc = "Length of received packet."]
len: usize
},
#[doc = "Error indicates that received packet can't be parsed."]
#[fail(display = "Deserialize Packet error: {:?}, packet: {:?}", error, packet)]
Deserialize {
#[doc = "Parsing error."]
error: nom::Err<(Vec<u8>, ErrorKind)>,
#[doc = "Received packet."]
packet: Vec<u8>,
},
#[doc = "General IO error that can happen with UDP socket."]
#[fail(display = "IO Error")]
Io,
}
/// Error that can happen when decoding `Packet` from bytes.
#[derive(Debug, Error)]
pub enum DecodeError {
/// Error indicates that we received too big packet.
#[error("Packet should not be longer than 2048 bytes: {} bytes", len)]
TooBigPacket {
/// Length of received packet.
len: usize
},
/// Error indicates that received packet can't be parsed.
#[error("Deserialize Packet error: {:?}, packet: {:?}", error, packet)]
Deserialize {
/// Parsing error.
error: nom::Err<(Vec<u8>, ErrorKind)>,
/// Received packet.
packet: Vec<u8>,
},
/// General IO error that can happen with UDP socket.
#[error("IO Error")]
Io(IoError),
}

impl DecodeError {
pub(crate) fn too_big_packet(len: usize) -> DecodeError {
DecodeError::from(DecodeErrorKind::TooBigPacket { len })
DecodeError::TooBigPacket { len }
}

pub(crate) fn deserialize(e: Err<(&[u8], ErrorKind)>, packet: Vec<u8>) -> DecodeError {
DecodeError::from(DecodeErrorKind::Deserialize { error: e.to_owned(), packet })
DecodeError::Deserialize { error: e.to_owned(), packet }
}
}

error_kind! {
#[doc = "Error that can happen when encoding `Packet` to bytes."]
#[derive(Debug)]
EncodeError,
#[doc = "Error that can happen when encoding `Packet` to bytes."]
#[derive(Debug, Fail)]
EncodeErrorKind {
#[doc = "Error indicates that `Packet` is invalid and can't be serialized."]
#[fail(display = "Serialize Packet error: {:?}", error)]
Serialize {
#[doc = "Serialization error."]
error: GenError
},
#[doc = "General IO error that can happen with UDP socket."]
#[fail(display = "IO Error")]
Io,
}
/// Error that can happen when encoding `Packet` to bytes.
#[derive(Debug, Error)]
pub enum EncodeError {
/// Error indicates that `Packet` is invalid and can't be serialized.
#[error("Serialize Packet error: {:?}", error)]
Serialize {
/// Serialization error.
error: GenError
},
/// General IO error that can happen with UDP socket.
#[error("IO Error")]
Io(IoError),
}

impl EncodeError {
pub(crate) fn serialize(error: GenError) -> EncodeError {
EncodeError::from(EncodeErrorKind::Serialize { error })
EncodeError::Serialize { error }
}
}

impl From<IoError> for DecodeError {
fn from(error: IoError) -> DecodeError {
DecodeError {
ctx: error.context(DecodeErrorKind::Io)
}
DecodeError::Io(error)
}
}

impl From<IoError> for EncodeError {
fn from(error: IoError) -> EncodeError {
EncodeError {
ctx: error.context(EncodeErrorKind::Io)
}
EncodeError::Io(error)
}
}

Expand Down Expand Up @@ -340,9 +326,8 @@ mod tests {
buf.extend_from_slice(b"\xFF");

let res = codec.decode(&mut buf);
// not enought bytes to decode EncryptedPacket
let error = res.err().unwrap();
assert_eq!(*error.kind(), DecodeErrorKind::Deserialize { error: Err::Error((vec![255], ErrorKind::Alt)) , packet: vec![0xff] });
// not enough bytes to decode EncryptedPacket
assert!(matches!(res, Err(DecodeError::Deserialize { error: Err::Error((_, ErrorKind::Alt)), packet: _ })));
}

#[test]
Expand Down Expand Up @@ -372,9 +357,8 @@ mod tests {
let res = codec.encode(packet, &mut buf);
assert!(res.is_err());
let error = res.err().unwrap();
let error_kind = error.kind();
let error_serialize = unpack!(error_kind, EncodeErrorKind::Serialize, error);
let error_serialize = unpack!(error, EncodeError::Serialize, error);
let too_small = unpack!(error_serialize, GenError::BufferTooSmall);
assert_eq!(*too_small, 2106 - MAX_DHT_PACKET_SIZE);
assert_eq!(too_small, 2106 - MAX_DHT_PACKET_SIZE);
}
}
35 changes: 15 additions & 20 deletions tox_core/src/dht/daemon_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,25 @@ use tox_binary_io::*;
use crate::dht::kbucket::*;
use crate::dht::ktree::*;

use failure::Fail;
use thiserror::Error;
use nom::{Err, error::ErrorKind as NomErrorKind};

error_kind! {
#[doc = "An error that can occur while serializing/deserializing object."]
#[derive(Debug)]
DeserializeError,
#[doc = "The specific kind of error that can occur."]
#[derive(Clone, Debug, Eq, PartialEq, Fail)]
DeserializeErrorKind {
#[doc = "Error indicates that object can't be parsed."]
#[fail(display = "Deserialize object error: {:?}, data: {:?}", error, data)]
Deserialize {
#[doc = "Parsing error."]
error: nom::Err<(Vec<u8>, NomErrorKind)>,
#[doc = "Object serialized data."]
data: Vec<u8>,
},
}
/// An error that can occur while serializing/deserializing object.
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum DeserializeError {
/// Error indicates that object can't be parsed.
#[error("Deserialize object error: {:?}, data: {:?}", error, data)]
Deserialize {
/// Parsing error.
error: nom::Err<(Vec<u8>, NomErrorKind)>,
/// Object serialized data.
data: Vec<u8>,
},
}

impl DeserializeError {
pub(crate) fn deserialize(e: Err<(&[u8], NomErrorKind)>, data: Vec<u8>) -> DeserializeError {
DeserializeError::from(DeserializeErrorKind::Deserialize { error: e.to_owned(), data })
DeserializeError::Deserialize { error: e.to_owned(), data }
}
}

Expand Down Expand Up @@ -143,14 +138,14 @@ mod tests {
let error = res.err().unwrap();
let mut input = vec![2, 1, 2, 3, 4, 4, 210];
input.extend_from_slice(&pk_org.as_bytes()[..crypto_box::KEY_SIZE - 1]);
assert_eq!(*error.kind(), DeserializeErrorKind::Deserialize { error: Err::Error((
assert_eq!(error, DeserializeError::Deserialize { error: Err::Error((
input, NomErrorKind::Eof)), data: serialized_vec[..serialized_len - 1].to_vec() });

// test with serialized data corrupted
let serialized_vec = [42; 10];
let res = DaemonState::deserialize_old(&alice, &serialized_vec).await;
let error = res.err().unwrap();
assert_eq!(*error.kind(), DeserializeErrorKind::Deserialize { error: Err::Error((
assert_eq!(error, DeserializeError::Deserialize { error: Err::Error((
vec![42; 10], NomErrorKind::Tag)), data: serialized_vec.to_vec() });

// test with empty close list
Expand Down
31 changes: 14 additions & 17 deletions tox_core/src/dht/lan_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,27 @@

use std::iter;
use std::net::{IpAddr, SocketAddr};
use std::time::{Duration};
use std::time::Duration;

use failure::Fail;
use thiserror::Error;
use futures::{stream, SinkExt};
use futures::channel::mpsc;
use get_if_addrs::IfAddr;

use tokio::time::error::Elapsed;
use tox_crypto::*;
use tox_packet::dht::*;

error_kind! {
#[doc = "Error that can happen during lan discovery."]
#[derive(Debug)]
LanDiscoveryError,
#[doc = "The specific kind of error that can occur."]
#[derive(Debug, Eq, PartialEq, Fail)]
LanDiscoveryErrorKind {
#[doc = "Ping wakeup timer error"]
#[fail(display = "Lan discovery wakeup timer error.")]
Wakeup,
#[doc = "Send packet(s) error."]
#[fail(display = "Send packet(s) error")]
SendTo,
}

/// Error that can happen during lan discovery.
#[derive(Debug, PartialEq, Error)]
pub enum LanDiscoveryError {
/// Ping wakeup timer error
#[error("Lan discovery wakeup timer error.")]
Wakeup,
/// Send packet(s) time out.
#[error("Send packet(s) error")]
Timeout(Elapsed),
}

/// How many ports should be used on every iteration.
Expand Down Expand Up @@ -150,7 +147,7 @@ impl LanDiscoverySender {
if let Err(e) = tokio::time::timeout(interval, self.send()).await {
warn!("Failed to send LAN discovery packets: {}", e);

return Err(e.context(LanDiscoveryErrorKind::SendTo).into())
return Err(LanDiscoveryError::Timeout(e))
}
}
}
Expand Down

0 comments on commit d918ab2

Please sign in to comment.