Skip to content

Commit

Permalink
Remove thiserror from dependencies and replace with handwritten imple…
Browse files Browse the repository at this point in the history
…mentation
  • Loading branch information
rnijveld authored and davidv1992 committed Apr 18, 2024
1 parent c8f911c commit 6d9f33f
Show file tree
Hide file tree
Showing 17 changed files with 285 additions and 99 deletions.
23 changes: 0 additions & 23 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@ serde_json = "1.0"
serde_test = "1.0.176"
rand = "0.8.0"
arbitrary = { version = "1.0" }
thiserror = "1.0.10"
libc = "0.2.145"
tokio = "1.32"
toml = ">=0.5.0,<0.9.0"
toml = { version = ">=0.5.0,<0.9.0", default-features = false, features = ["parse"] }
async-trait = "0.1.22"
timestamped-socket = "0.2.1"
clock-steering = "0.2.0"
Expand Down
1 change: 0 additions & 1 deletion ntp-proto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ tracing.workspace = true
serde.workspace = true
arbitrary = { workspace = true, optional = true }
rustls.workspace = true
thiserror.workspace = true
aead.workspace = true
aes-siv.workspace = true
zeroize.workspace = true
Expand Down
74 changes: 56 additions & 18 deletions ntp-proto/src/nts_record.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
fmt::Display,
io::{Read, Write},
ops::ControlFlow,
sync::Arc,
Expand Down Expand Up @@ -642,38 +643,75 @@ impl NtsRecordDecoder {
}
}

#[derive(Debug, thiserror::Error)]
#[derive(Debug)]
pub enum KeyExchangeError {
#[error("Unrecognized record is marked as critical")]
UnrecognizedCriticalRecord,
#[error("Remote: Bad request")]
BadRequest,
#[error("Remote: Internal server error")]
InternalServerError,
#[error("Remote: Error with unknown code {0}")]
UnknownErrorCode(u16),
#[error("The server response is invalid")]
BadResponse,
#[error("No continuation protocol supported by both us and server")]
NoValidProtocol,
#[error("No encryption algorithm supported by both us and server")]
NoValidAlgorithm,
#[error("The length of a fixed key does not match the algorithm used")]
InvalidFixedKeyLength,
#[error("Missing cookies")]
NoCookies,
#[error("{0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
Tls(#[from] rustls::Error),
#[error("{0}")]
Io(std::io::Error),
Tls(rustls::Error),
Certificate(rustls::Error),
#[error("{0}")]
DnsName(#[from] rustls::pki_types::InvalidDnsNameError),
#[error("Incomplete response")]
DnsName(rustls::pki_types::InvalidDnsNameError),
IncompleteResponse,
}

impl Display for KeyExchangeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnrecognizedCriticalRecord => {
write!(f, "Unrecognized record is marked as critical")
}
Self::BadRequest => write!(f, "Remote: Bad request"),
Self::InternalServerError => write!(f, "Remote: Internal server error"),
Self::UnknownErrorCode(e) => write!(f, "Remote: Error with unknown code {e}"),
Self::BadResponse => write!(f, "The server response is invalid"),
Self::NoValidProtocol => write!(
f,
"No continuation protocol supported by both us and server"
),
Self::NoValidAlgorithm => {
write!(f, "No encryption algorithm supported by both us and server")
}
Self::InvalidFixedKeyLength => write!(
f,
"The length of a fixed key does not match the algorithm used"
),
Self::NoCookies => write!(f, "Missing cookies"),
Self::Io(e) => write!(f, "{e}"),
Self::Tls(e) => write!(f, "{e}"),
Self::Certificate(e) => write!(f, "{e}"),
Self::DnsName(e) => write!(f, "{e}"),
Self::IncompleteResponse => write!(f, "Incomplete response"),
}
}
}

impl From<std::io::Error> for KeyExchangeError {
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}

impl From<rustls::Error> for KeyExchangeError {
fn from(value: rustls::Error) -> Self {
Self::Tls(value)
}
}

impl From<rustls::pki_types::InvalidDnsNameError> for KeyExchangeError {
fn from(value: rustls::pki_types::InvalidDnsNameError) -> Self {
Self::DnsName(value)
}
}

impl std::error::Error for KeyExchangeError {}

impl KeyExchangeError {
pub(crate) fn from_error_code(error_code: u16) -> Self {
match error_code {
Expand Down
25 changes: 20 additions & 5 deletions ntp-proto/src/packet/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
use std::fmt::Display;

use aes_siv::{siv::Aes128Siv, siv::Aes256Siv, Key, KeyInit};
use rand::Rng;
use tracing::error;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::keyset::DecodedServerCookie;

use super::extension_fields::ExtensionField;

#[derive(Debug, thiserror::Error)]
#[error("Could not decrypt ciphertext")]
#[derive(Debug)]
pub struct DecryptError;

#[derive(Debug, thiserror::Error)]
#[error("Invalid key")]
impl Display for DecryptError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Could not decrypt ciphertext")
}
}

impl std::error::Error for DecryptError {}

#[derive(Debug)]
pub struct KeyError;

impl Display for KeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Invalid key")
}
}

impl std::error::Error for KeyError {}

struct Buffer<'a> {
buffer: &'a mut [u8],
valid: usize,
Expand Down
37 changes: 31 additions & 6 deletions ntp-proto/src/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::{
};
use serde::{Deserialize, Serialize};
use std::{
fmt::Display,
io::Cursor,
net::{IpAddr, SocketAddr},
};
Expand All @@ -22,12 +23,21 @@ const MAX_STRATUM: u8 = 16;
const POLL_WINDOW: std::time::Duration = std::time::Duration::from_secs(5);
const STARTUP_TRIES_THRESHOLD: usize = 3;

#[derive(Debug, thiserror::Error)]
#[derive(Debug)]
pub enum NtsError {
#[error("Ran out of nts cookies")]
OutOfCookies,
}

impl Display for NtsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::OutOfCookies => write!(f, "Ran out of NTS cookies"),
}
}
}

impl std::error::Error for NtsError {}

pub struct PeerNtsData {
pub(crate) cookies: CookieStash,
// Note: we use Box<dyn Cipher> to support the use
Expand Down Expand Up @@ -323,14 +333,29 @@ pub enum Update {
NewMeasurement(PeerSnapshot, Measurement),
}

#[derive(Debug, thiserror::Error)]
#[derive(Debug)]
pub enum PollError {
#[error("{0}")]
Io(#[from] std::io::Error),
#[error("peer unreachable")]
Io(std::io::Error),
PeerUnreachable,
}

impl Display for PollError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "{e}"),
Self::PeerUnreachable => write!(f, "peer unreachable"),
}
}
}

impl std::error::Error for PollError {}

impl From<std::io::Error> for PollError {
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ProtocolVersion {
V4,
Expand Down
27 changes: 21 additions & 6 deletions ntp-proto/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::{
collections::hash_map::RandomState,
fmt::Display,
io::Cursor,
net::{AddrParseError, IpAddr},
sync::Arc,
time::{Duration, Instant},
};

use serde::{de, Deserialize, Deserializer};
use thiserror::Error;

use crate::{
ipfilter::IpFilter, KeySet, NoCipher, NtpClock, NtpPacket, NtpTimestamp, PacketParsingError,
Expand Down Expand Up @@ -341,16 +341,31 @@ pub struct IpSubnet {
pub mask: u8,
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubnetParseError {
#[error("Invalid subnet syntax")]
Subnet,
#[error("{0} in subnet")]
Ip(#[from] AddrParseError),
#[error("Invalid subnet mask")]
Ip(AddrParseError),
Mask,
}

impl std::error::Error for SubnetParseError {}

impl Display for SubnetParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Subnet => write!(f, "Invalid subnet syntax"),
Self::Ip(e) => write!(f, "{e} in subnet"),
Self::Mask => write!(f, "Invalid subnet mask"),
}
}
}

impl From<AddrParseError> for SubnetParseError {
fn from(value: AddrParseError) -> Self {
Self::Ip(value)
}
}

impl std::str::FromStr for IpSubnet {
type Err = SubnetParseError;

Expand Down
1 change: 0 additions & 1 deletion ntpd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ tokio = { workspace = true, features = ["rt-multi-thread", "io-util", "io-std",
tracing.workspace = true
tracing-subscriber.workspace = true
toml.workspace = true
thiserror.workspace = true
rand.workspace = true
libc.workspace = true
async-trait.workspace = true
Expand Down
33 changes: 27 additions & 6 deletions ntpd/src/daemon/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ pub use peer::*;
use serde::{Deserialize, Deserializer};
pub use server::*;
use std::{
fmt::Display,
io::ErrorKind,
net::SocketAddr,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
str::FromStr,
};
use thiserror::Error;
use timestamped_socket::interface::InterfaceName;
use tokio::{fs::read_to_string, io};
use tracing::{info, warn};
Expand Down Expand Up @@ -454,12 +454,33 @@ impl Config {
}
}

#[derive(Error, Debug)]
#[derive(Debug)]
pub enum ConfigError {
#[error("io error while reading config: {0}")]
Io(#[from] io::Error),
#[error("config toml parsing error: {0}")]
Toml(#[from] toml::de::Error),
Io(io::Error),
Toml(toml::de::Error),
}

impl std::error::Error for ConfigError {}

impl Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "io error while reading config: {e}"),
Self::Toml(e) => write!(f, "config toml parsing error: {e}"),
}
}
}

impl From<io::Error> for ConfigError {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}

impl From<toml::de::Error> for ConfigError {
fn from(value: toml::de::Error) -> Self {
Self::Toml(value)
}
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 6d9f33f

Please sign in to comment.