Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add debug/trace features #35

Merged
merged 4 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,29 @@ jobs:
with:
command: check

test:
name: Test Suite
check_features:
name: Check features
runs-on: ubuntu-latest
strategy:
matrix:
features:
- --features=default
- --all-features
- --features=bigint,serialize,debug
- --features=bigint,serialize,trace
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Cargo update
run: cargo update
- uses: actions-rs/cargo@v1
with:
command: test
args: --all-features
args: ${{ matrix.features }}

no_std:
name: no-std
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,16 @@ default = ["std"]
bigint = ["num-bigint"]
bits = ["bitvec"]
datetime = ["time"]
debug = ["colored"]
serialize = ["cookie-factory"]
std = []
trace = ["debug"]

[dependencies]
asn1-rs-derive = { version="0.5", path="./derive" }
asn1-rs-impl = { version="0.2", path="./impl" }
bitvec = { version="1.0", optional=true }
colored = { version="2.0", optional=true }
cookie-factory = { version="0.3.0", optional=true }
displaydoc = "0.2.2"
nom = { version="7.0", default_features=false, features=["std"] }
Expand Down
37 changes: 25 additions & 12 deletions src/asn1_types/any.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use crate::ber::*;
use crate::*;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::string::String;
use core::convert::{TryFrom, TryInto};

use self::debug::trace;

/// The `Any` object is not strictly an ASN.1 type, but holds a generic description of any object
/// that could be encoded.
///
Expand Down Expand Up @@ -101,10 +104,10 @@ impl<'a> Any<'a> {
let (rem, any) = Any::from_ber(bytes).map_err(Err::convert)?;
any.tag()
.assert_eq(Tag(tag))
.map_err(|e| nom::Err::Error(e.into()))?;
.map_err(|e| Err::Error(e.into()))?;
any.class()
.assert_eq(class)
.map_err(|e| nom::Err::Error(e.into()))?;
.map_err(|e| Err::Error(e.into()))?;
let (_, res) = op(any.data)?;
Ok((rem, res))
}
Expand All @@ -125,10 +128,10 @@ impl<'a> Any<'a> {
let (rem, any) = Any::from_der(bytes).map_err(Err::convert)?;
any.tag()
.assert_eq(Tag(tag))
.map_err(|e| nom::Err::Error(e.into()))?;
.map_err(|e| Err::Error(e.into()))?;
any.class()
.assert_eq(class)
.map_err(|e| nom::Err::Error(e.into()))?;
.map_err(|e| Err::Error(e.into()))?;
let (_, res) = op(any.data)?;
Ok((rem, res))
}
Expand Down Expand Up @@ -320,21 +323,31 @@ impl<'a> Any<'a> {
}
}

pub(crate) fn parse_ber_any(input: &[u8]) -> ParseResult<Any> {
let (i, header) = Header::from_ber(input)?;
let (i, data) = BerParser::get_object_content(i, &header, MAX_RECURSION)?;
Ok((i, Any { header, data }))
}

pub(crate) fn parse_der_any(input: &[u8]) -> ParseResult<Any> {
let (i, header) = Header::from_der(input)?;
// X.690 section 10.1: The definite form of length encoding shall be used
header.length.assert_definite()?;
let (i, data) = DerParser::get_object_content(i, &header, MAX_RECURSION)?;
Ok((i, Any { header, data }))
}

impl<'a> FromBer<'a> for Any<'a> {
#[inline]
fn from_ber(bytes: &'a [u8]) -> ParseResult<Self> {
let (i, header) = Header::from_ber(bytes)?;
let (i, data) = BerParser::get_object_content(i, &header, MAX_RECURSION)?;
Ok((i, Any { header, data }))
trace("Any", parse_ber_any, bytes)
}
}

impl<'a> FromDer<'a> for Any<'a> {
#[inline]
fn from_der(bytes: &'a [u8]) -> ParseResult<Self> {
let (i, header) = Header::from_der(bytes)?;
// X.690 section 10.1: The definite form of length encoding shall be used
header.length.assert_definite()?;
let (i, data) = DerParser::get_object_content(i, &header, MAX_RECURSION)?;
Ok((i, Any { header, data }))
trace("Any", parse_der_any, bytes)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/asn1_types/generalizedtime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::datetime::decode_decimal;
use crate::*;
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::String;
use core::convert::TryFrom;
use core::fmt;
Expand Down
48 changes: 31 additions & 17 deletions src/asn1_types/integer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,26 @@ macro_rules! impl_int {
type Error = Error;

fn try_from(any: &'b Any<'a>) -> Result<Self> {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let uint = if is_highest_bit_set(any.as_bytes()) {
<$uint>::from_be_bytes(decode_array_int(&any)?)
} else {
// read as uint, but check if the value will fit in a signed integer
let u = <$uint>::from_be_bytes(decode_array_uint(&any)?);
if u > <$int>::MAX as $uint {
return Err(Error::IntegerTooLarge);
}
u
};
Ok(uint as $int)
$crate::debug::trace_generic(
core::any::type_name::<$int>(),
"Conversion to int",
|any| {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let uint = if is_highest_bit_set(any.as_bytes()) {
<$uint>::from_be_bytes(decode_array_int(&any)?)
} else {
// read as uint, but check if the value will fit in a signed integer
let u = <$uint>::from_be_bytes(decode_array_uint(&any)?);
if u > <$int>::MAX as $uint {
return Err(Error::IntegerTooLarge);
}
u
};
Ok(uint as $int)
},
any,
)
}
}

Expand Down Expand Up @@ -162,10 +169,17 @@ macro_rules! impl_uint {
type Error = Error;

fn try_from(any: &'b Any<'a>) -> Result<Self> {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let result = Self::from_be_bytes(decode_array_uint(any)?);
Ok(result)
$crate::debug::trace_generic(
core::any::type_name::<$ty>(),
"Conversion to uint",
|any| {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let result = Self::from_be_bytes(decode_array_uint(any)?);
Ok(result)
},
any,
)
}
}
impl CheckDerConstraints for $ty {
Expand Down
1 change: 1 addition & 0 deletions src/asn1_types/object_descriptor.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{asn1_string, TestValidCharset};
use crate::{Error, Result};
#[cfg(not(feature = "std"))]
use alloc::string::String;

// X.680 section 44.3
Expand Down
5 changes: 2 additions & 3 deletions src/asn1_types/oid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ use crate::*;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::{String, ToString};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::{
convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr,
};

#[cfg(feature = "bigint")]
use num_bigint::BigUint;
use num_traits::Num;

/// An error for OID parsing functions.
Expand Down
1 change: 0 additions & 1 deletion src/asn1_types/real.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::*;
use alloc::format;
use core::convert::TryFrom;
use nom::Needed;

mod f32;
mod f64;
Expand Down
3 changes: 2 additions & 1 deletion src/asn1_types/sequence.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::*;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::convert::TryFrom;

Expand Down Expand Up @@ -179,7 +180,7 @@ impl<'a> Sequence<'a> {
{
match self.content {
Cow::Borrowed(b) => f(b),
_ => Err(nom::Err::Error(Error::LifetimeError.into())),
_ => Err(Err::Error(Error::LifetimeError.into())),
}
}

Expand Down
30 changes: 21 additions & 9 deletions src/asn1_types/sequence/sequence_of.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use crate::*;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::fmt::{Debug, Display};
use core::iter::FromIterator;
use core::ops::{Deref, DerefMut};

use self::debug::{trace, trace_generic};

/// The `SEQUENCE OF` object is an ordered list of homogeneous types.
///
/// This type implements `Deref<Target = [T]>` and `DerefMut<Target = [T]>`, so all methods
Expand Down Expand Up @@ -128,17 +132,25 @@ where
impl<'a, T, E> FromDer<'a, E> for SequenceOf<T>
where
T: FromDer<'a, E>,
E: From<Error>,
E: From<Error> + Display + Debug,
{
fn from_der(bytes: &'a [u8]) -> ParseResult<Self, E> {
let (rem, any) = Any::from_der(bytes).map_err(Err::convert)?;
any.header
.assert_tag(Self::TAG)
.map_err(|e| nom::Err::Error(e.into()))?;
let items = SequenceIterator::<T, DerParser, E>::new(any.data)
.collect::<Result<Vec<T>, E>>()
.map_err(nom::Err::Error)?;
Ok((rem, SequenceOf::new(items)))
trace_generic(
core::any::type_name::<Self>(),
"SequenceOf::from_der",
|bytes| {
let (rem, any) = trace(core::any::type_name::<Self>(), parse_der_any, bytes)
.map_err(Err::convert)?;
any.header
.assert_tag(Self::TAG)
.map_err(|e| Err::Error(e.into()))?;
let items = SequenceIterator::<T, DerParser, E>::new(any.data)
.collect::<Result<Vec<T>, E>>()
.map_err(Err::Error)?;
Ok((rem, SequenceOf::new(items)))
},
bytes,
)
}
}

Expand Down
54 changes: 41 additions & 13 deletions src/asn1_types/sequence/vec.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use crate::*;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::fmt::Debug;

use self::debug::{trace, trace_generic};

// // XXX this compiles but requires bound TryFrom :/
// impl<'a, 'b, T> TryFrom<&'b Any<'a>> for Vec<T>
Expand Down Expand Up @@ -49,10 +53,26 @@ where
type Error = Error;

fn try_from(any: Any<'a>) -> Result<Self> {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_constructed()?;
let items = SetIterator::<T, BerParser>::new(any.data).collect::<Result<Vec<T>>>()?;
Ok(items)
trace_generic(
core::any::type_name::<Self>(),
"T::from(Any)",
|any| {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_constructed()?;
let items = SetIterator::<T, BerParser>::new(any.data)
.collect::<Result<Vec<T>>>()
.map_err(|e| {
debug_eprintln!(
core::any::type_name::<T>(),
"≠ {}",
"Conversion from Any failed".red()
);
e
})?;
Ok(items)
},
any,
)
}
}

Expand Down Expand Up @@ -91,17 +111,25 @@ impl<T> Tagged for Vec<T> {
impl<'a, T, E> FromDer<'a, E> for Vec<T>
where
T: FromDer<'a, E>,
E: From<Error>,
E: From<Error> + Debug,
{
fn from_der(bytes: &'a [u8]) -> ParseResult<Self, E> {
let (rem, any) = Any::from_der(bytes).map_err(Err::convert)?;
any.header
.assert_tag(Self::TAG)
.map_err(|e| nom::Err::Error(e.into()))?;
let v = SequenceIterator::<T, DerParser, E>::new(any.data)
.collect::<Result<Vec<T>, E>>()
.map_err(nom::Err::Error)?;
Ok((rem, v))
trace_generic(
core::any::type_name::<Self>(),
"Sequence::from_der",
|bytes| {
let (rem, any) = trace(core::any::type_name::<Self>(), parse_der_any, bytes)
.map_err(Err::convert)?;
any.header
.assert_tag(Self::TAG)
.map_err(|e| Err::Error(e.into()))?;
let v = SequenceIterator::<T, DerParser, E>::new(any.data)
.collect::<Result<Vec<T>, E>>()
.map_err(Err::Error)?;
Ok((rem, v))
},
bytes,
)
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/asn1_types/set.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::*;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::convert::TryFrom;

Expand Down Expand Up @@ -180,7 +181,7 @@ impl<'a> Set<'a> {
{
match self.content {
Cow::Borrowed(b) => f(b),
_ => Err(nom::Err::Error(Error::LifetimeError.into())),
_ => Err(Err::Error(Error::LifetimeError.into())),
}
}

Expand Down
Loading
Loading