Skip to content

Commit

Permalink
Merge pull request #7 from algesten/anyhow
Browse files Browse the repository at this point in the history
Refactor out use of anyhow
  • Loading branch information
Rusty Rain authored Oct 8, 2021
2 parents f14a2aa + 7593adf commit 0edd955
Show file tree
Hide file tree
Showing 22 changed files with 160 additions and 123 deletions.
5 changes: 2 additions & 3 deletions crates/stun/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ repository = "https://github.com/webrtc-rs/stun"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
util = { package = "webrtc-util", version = "0.4.3", default-features = false, features = ["conn"] }
util = { package = "webrtc-util", version = "0.5.0", default-features = false, features = ["conn"] }
tokio = { version = "1.12.0", features = ["full"] }
lazy_static = "1.4.0"
url = "2.2.0"
Expand All @@ -22,8 +22,7 @@ subtle = "2.1.1"
crc = "2.0.0"
ring = "0.16.19"
md-5 = "0.9.1"
thiserror = "1.0.25"
anyhow = "1.0.41"
thiserror = "1.0"

[dev-dependencies]
tokio-test = "0.4"
Expand Down
4 changes: 2 additions & 2 deletions crates/stun/examples/stun_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ use stun::agent::*;
use stun::client::*;
use stun::message::*;
use stun::xoraddr::*;
use stun::Error;

use anyhow::Result;
use clap::{App, Arg};
use std::sync::Arc;
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> Result<()> {
async fn main() -> Result<(), Error> {
let mut app = App::new("STUN Client")
.version("0.1.0")
.author("Rain Liu <yliu@webrtc.rs>")
Expand Down
5 changes: 2 additions & 3 deletions crates/stun/src/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::attributes::*;
use crate::error::*;
use crate::message::*;

use anyhow::Result;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

Expand Down Expand Up @@ -67,12 +66,12 @@ impl MappedAddress {
pub fn get_from_as(&mut self, m: &Message, t: AttrType) -> Result<()> {
let v = m.get(t)?;
if v.len() <= 4 {
return Err(Error::ErrUnexpectedEof.into());
return Err(Error::ErrUnexpectedEof);
}

let family = u16::from_be_bytes([v[0], v[1]]);
if family != FAMILY_IPV6 && family != FAMILY_IPV4 {
return Err(Error::new(format!("bad value {}", family)).into());
return Err(Error::Other(format!("bad value {}", family)));
}
self.port = u16::from_be_bytes([v[2], v[3]]);

Expand Down
25 changes: 15 additions & 10 deletions crates/stun/src/addr/addr_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ fn test_mapped_address() -> Result<()> {
let message = Message::new();
let result = got.get_from(&message);
if let Err(err) = result {
assert!(
Error::ErrAttributeNotFound.equal(&err),
assert_eq!(
Error::ErrAttributeNotFound,
err,
"should be not found: {}",
err
);
Expand All @@ -46,8 +47,9 @@ fn test_mapped_address() -> Result<()> {
message.add(ATTR_MAPPED_ADDRESS, &[1, 2, 3]);
let result = got.get_from(&message);
if let Err(err) = result {
assert!(
Error::ErrUnexpectedEof.equal(&err),
assert_eq!(
Error::ErrUnexpectedEof,
err,
"<{}> should be <{}>",
err,
Error::ErrUnexpectedEof
Expand Down Expand Up @@ -85,8 +87,9 @@ fn test_mapped_address_v6() -> Result<()> {
let message = Message::new();
let result = got.get_from(&message);
if let Err(err) = result {
assert!(
Error::ErrAttributeNotFound.equal(&err),
assert_eq!(
Error::ErrAttributeNotFound,
err,
"<{}> should be <{}>",
err,
Error::ErrAttributeNotFound,
Expand Down Expand Up @@ -123,8 +126,9 @@ fn test_alternate_server() -> Result<()> {
let message = Message::new();
let result = got.get_from(&message);
if let Err(err) = result {
assert!(
Error::ErrAttributeNotFound.equal(&err),
assert_eq!(
Error::ErrAttributeNotFound,
err,
"<{}> should be <{}>",
err,
Error::ErrAttributeNotFound,
Expand Down Expand Up @@ -162,8 +166,9 @@ fn test_other_address() -> Result<()> {
let message = Message::new();
let result = got.get_from(&message);
if let Err(err) = result {
assert!(
Error::ErrAttributeNotFound.equal(&err),
assert_eq!(
Error::ErrAttributeNotFound,
err,
"<{}> should be <{}>",
err,
Error::ErrAttributeNotFound,
Expand Down
25 changes: 12 additions & 13 deletions crates/stun/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::client::ClientTransaction;
use crate::error::*;
use crate::message::*;

use anyhow::Result;
use rand::Rng;
use std::collections::HashMap;
use std::sync::Arc;
Expand Down Expand Up @@ -126,27 +125,27 @@ impl Agent {
// provided error. Can return ErrTransactionNotExists and ErrAgentClosed.
fn stop_with_error(&mut self, id: TransactionId, error: Error) -> Result<()> {
if self.closed {
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}

let v = self.transactions.remove(&id);
if let Some(t) = v {
if let Some(handler) = &self.handler {
handler.send(Event {
event_type: EventType::Callback(t.id),
event_body: Err(error.into()),
event_body: Err(error),
})?;
}
Ok(())
} else {
Err(Error::ErrTransactionNotExists.into())
Err(Error::ErrTransactionNotExists)
}
}

// process incoming message, synchronously passing it to handler.
fn process(&mut self, message: Message) -> Result<()> {
if self.closed {
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}

self.transactions.remove(&message.transaction_id);
Expand All @@ -167,13 +166,13 @@ impl Agent {
// closed state.
fn close(&mut self) -> Result<()> {
if self.closed {
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}

for id in self.transactions.keys() {
let e = Event {
event_type: EventType::Callback(*id),
event_body: Err(Error::ErrAgentClosed.into()),
event_body: Err(Error::ErrAgentClosed),
};
if let Some(handler) = &self.handler {
handler.send(e)?;
Expand All @@ -192,10 +191,10 @@ impl Agent {
// Agent handler is guaranteed to be eventually called.
fn start(&mut self, id: TransactionId, deadline: Instant) -> Result<()> {
if self.closed {
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}
if self.transactions.contains_key(&id) {
return Err(Error::ErrTransactionExists.into());
return Err(Error::ErrTransactionExists);
}

self.transactions
Expand All @@ -220,7 +219,7 @@ impl Agent {
// Doing nothing if agent is closed.
// All transactions should be already closed
// during Close() call.
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}

let mut to_remove: Vec<TransactionId> = Vec::with_capacity(AGENT_COLLECT_CAP);
Expand All @@ -242,7 +241,7 @@ impl Agent {
for id in to_remove {
let event = Event {
event_type: EventType::Callback(id),
event_body: Err(Error::ErrTransactionTimeOut.into()),
event_body: Err(Error::ErrTransactionTimeOut),
};
if let Some(handler) = &self.handler {
handler.send(event)?;
Expand All @@ -255,7 +254,7 @@ impl Agent {
// set_handler sets agent handler to h.
fn set_handler(&mut self, h: Handler) -> Result<()> {
if self.closed {
return Err(Error::ErrAgentClosed.into());
return Err(Error::ErrAgentClosed);
}
self.handler = h;

Expand All @@ -273,7 +272,7 @@ impl Agent {
};

if let Err(err) = result {
if Error::ErrAgentClosed.equal(&err) {
if Error::ErrAgentClosed == err {
break;
}
}
Expand Down
37 changes: 22 additions & 15 deletions crates/stun/src/agent/agent_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ async fn test_agent_process() -> Result<()> {

let result = a.process(m);
if let Err(err) = result {
assert!(
Error::ErrAgentClosed.equal(&err),
assert_eq!(
Error::ErrAgentClosed,
err,
"closed agent should return <{}>, but got <{}>",
Error::ErrAgentClosed,
err,
Expand All @@ -76,8 +77,9 @@ fn test_agent_start() -> Result<()> {

let result = a.start(id, deadline);
if let Err(err) = result {
assert!(
Error::ErrTransactionExists.equal(&err),
assert_eq!(
Error::ErrTransactionExists,
err,
"duplicate start should return <{}>, got <{}>",
Error::ErrTransactionExists,
err,
Expand All @@ -90,8 +92,9 @@ fn test_agent_start() -> Result<()> {
let id = TransactionId::new();
let result = a.start(id, deadline);
if let Err(err) = result {
assert!(
Error::ErrAgentClosed.equal(&err),
assert_eq!(
Error::ErrAgentClosed,
err,
"start on closed agent should return <{}>, got <{}>",
Error::ErrAgentClosed,
err,
Expand All @@ -102,8 +105,9 @@ fn test_agent_start() -> Result<()> {

let result = a.set_handler(noop_handler());
if let Err(err) = result {
assert!(
Error::ErrAgentClosed.equal(&err),
assert_eq!(
Error::ErrAgentClosed,
err,
"SetHandler on closed agent should return <{}>, got <{}>",
Error::ErrAgentClosed,
err,
Expand All @@ -122,8 +126,9 @@ async fn test_agent_stop() -> Result<()> {

let result = a.stop(TransactionId::default());
if let Err(err) = result {
assert!(
Error::ErrTransactionNotExists.equal(&err),
assert_eq!(
Error::ErrTransactionNotExists,
err,
"unexpected error: {}, should be {}",
Error::ErrTransactionNotExists,
err,
Expand All @@ -143,7 +148,7 @@ async fn test_agent_stop() -> Result<()> {
tokio::select! {
evt = handler_rx.recv() => {
if let Err(err) = evt.unwrap().event_body{
assert!(Error::ErrTransactionStopped.equal(&err),
assert_eq!(Error::ErrTransactionStopped,err,
"unexpected error: {}, should be {}",
err, Error::ErrTransactionStopped);
}else{
Expand All @@ -157,8 +162,9 @@ async fn test_agent_stop() -> Result<()> {

let result = a.close();
if let Err(err) = result {
assert!(
Error::ErrAgentClosed.equal(&err),
assert_eq!(
Error::ErrAgentClosed,
err,
"a.Close returned {} instead of {}",
Error::ErrAgentClosed,
err,
Expand All @@ -169,8 +175,9 @@ async fn test_agent_stop() -> Result<()> {

let result = a.stop(TransactionId::default());
if let Err(err) = result {
assert!(
Error::ErrAgentClosed.equal(&err),
assert_eq!(
Error::ErrAgentClosed,
err,
"unexpected error: {}, should be {}",
Error::ErrAgentClosed,
err,
Expand Down
2 changes: 1 addition & 1 deletion crates/stun/src/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#[cfg(test)]
mod attributes_test;

use crate::error::*;
use crate::message::*;

use anyhow::Result;
use std::fmt;

// Attributes is list of message attributes.
Expand Down
17 changes: 8 additions & 9 deletions crates/stun/src/checks.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
use crate::attributes::*;
use crate::error::*;

use anyhow::Result;
use subtle::ConstantTimeEq;

// check_size returns ErrAttrSizeInvalid if got is not equal to expected.
pub fn check_size(_at: AttrType, got: usize, expected: usize) -> Result<()> {
if got == expected {
Ok(())
} else {
Err(Error::ErrAttributeSizeInvalid.into())
Err(Error::ErrAttributeSizeInvalid)
}
}

// is_attr_size_invalid returns true if error means that attribute size is invalid.
pub fn is_attr_size_invalid(err: &anyhow::Error) -> bool {
Error::ErrAttributeSizeInvalid.equal(err)
pub fn is_attr_size_invalid(err: &Error) -> bool {
Error::ErrAttributeSizeInvalid == *err
}

pub(crate) fn check_hmac(got: &[u8], expected: &[u8]) -> Result<()> {
if got.ct_eq(expected).unwrap_u8() != 1 {
Err(Error::ErrIntegrityMismatch.into())
Err(Error::ErrIntegrityMismatch)
} else {
Ok(())
}
Expand All @@ -30,7 +29,7 @@ pub(crate) fn check_fingerprint(got: u32, expected: u32) -> Result<()> {
if got == expected {
Ok(())
} else {
Err(Error::ErrFingerprintMismatch.into())
Err(Error::ErrFingerprintMismatch)
}
}

Expand All @@ -39,11 +38,11 @@ pub fn check_overflow(_at: AttrType, got: usize, max: usize) -> Result<()> {
if got <= max {
Ok(())
} else {
Err(Error::ErrAttributeSizeOverflow.into())
Err(Error::ErrAttributeSizeOverflow)
}
}

// is_attr_size_overflow returns true if error means that attribute size is too big.
pub fn is_attr_size_overflow(err: &anyhow::Error) -> bool {
Error::ErrAttributeSizeOverflow.equal(err)
pub fn is_attr_size_overflow(err: &Error) -> bool {
Error::ErrAttributeSizeOverflow == *err
}
Loading

0 comments on commit 0edd955

Please sign in to comment.