PDU improvements and additions #24

Merged
muellerr merged 7 commits from pdu-additions into main 2023-08-28 16:52:26 +02:00
4 changed files with 235 additions and 65 deletions
Showing only changes of commit 62533bb91c - Show all commits

View File

@ -10,6 +10,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## Changed
- The `Tlv` and `Lv` API return `&[u8]` instead of `Option<&[u8]>`.
## Added
- Added `raw_data` API for `Tlv` and `Lv` to retrieve the whole `Lv`/`Tlv` slice if the object
was created from a raw bytestream.
- Added `MsgToUserTlv` helper class which wraps a regular `Tlv` and adds some useful functionality.
- `UnsignedByteField` and `GenericUnsignedByteField` `new` methods are `const` now.
- `PduError` variants which contained a tuple variant with multiple fields were converted to a
struct variant.

View File

@ -11,14 +11,26 @@ pub const MIN_LV_LEN: usize = 1;
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
///
/// Please note that this class is zero-copy and does not generate a copy of the value data for
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
///
/// # Lifetimes
/// * `data`: If the LV is generated from a raw bytestream, this will be the lifetime of
/// the raw bytestream. If the LV is generated from a raw slice or a similar data reference,
/// this will be the lifetime of that data reference.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Lv<'data> {
data: Option<&'data [u8]>,
data: &'data [u8],
// If the LV was generated from a raw bytestream, this will contain the start of the
// full LV.
pub(crate) raw_data: Option<&'data [u8]>,
}
impl PartialEq for Lv<'_> {
fn eq(&self, other: &Self) -> bool {
self.data == other.data
}
}
pub(crate) fn generic_len_check_data_serialization(
@ -53,12 +65,18 @@ impl<'data> Lv<'data> {
if data.len() > u8::MAX as usize {
return Err(TlvLvError::DataTooLarge(data.len()));
}
Ok(Lv { data: Some(data) })
Ok(Lv {
data,
raw_data: None,
})
}
/// Creates a LV with an empty value field.
pub fn new_empty() -> Lv<'data> {
Lv { data: None }
Lv {
data: &[],
raw_data: None,
}
}
/// Helper function to build a string LV. This is especially useful for the file or directory
@ -77,10 +95,7 @@ impl<'data> Lv<'data> {
/// Returns the length of the value part, not including the length byte.
pub fn len_value(&self) -> usize {
if self.data.is_none() {
return 0;
}
self.data.unwrap().len()
self.data.len()
}
/// Returns the full raw length, including the length byte.
@ -90,18 +105,26 @@ impl<'data> Lv<'data> {
/// Checks whether the value field is empty.
pub fn is_empty(&self) -> bool {
self.data.is_none()
self.data.len() == 0
}
pub fn value(&self) -> Option<&[u8]> {
pub fn value(&self) -> &[u8] {
self.data
}
/// If the LV was generated from a raw bytestream using [Self::from_bytes], the raw start
/// of the LV can be retrieved with this method.
pub fn raw_data(&self) -> Option<&[u8]> {
self.raw_data
}
/// Convenience function to extract the value as a [str]. This is useful if the LV is
/// known to contain a [str], for example being a file name.
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
self.data?;
Some(core::str::from_utf8(self.data.unwrap()))
if self.is_empty() {
return None;
}
Some(core::str::from_utf8(self.data))
}
/// Writes the LV to a raw buffer. Please note that the first byte will contain the length
@ -118,15 +141,14 @@ impl<'data> Lv<'data> {
}
pub(crate) fn write_to_be_bytes_no_len_check(&self, buf: &mut [u8]) -> usize {
if self.data.is_none() {
if self.is_empty() {
buf[0] = 0;
return MIN_LV_LEN;
}
let data = self.data.unwrap();
// Length check in constructor ensures the length always has a valid value.
buf[0] = data.len() as u8;
buf[MIN_LV_LEN..data.len() + MIN_LV_LEN].copy_from_slice(data);
MIN_LV_LEN + data.len()
buf[0] = self.data.len() as u8;
buf[MIN_LV_LEN..self.data.len() + MIN_LV_LEN].copy_from_slice(self.data);
MIN_LV_LEN + self.data.len()
}
pub(crate) fn from_be_bytes_no_len_check(
@ -134,11 +156,10 @@ impl<'data> Lv<'data> {
) -> Result<Lv<'data>, ByteConversionError> {
let value_len = buf[0] as usize;
generic_len_check_deserialization(buf, value_len + MIN_LV_LEN)?;
let mut data = None;
if value_len > 0 {
data = Some(&buf[MIN_LV_LEN..MIN_LV_LEN + value_len])
}
Ok(Self { data })
Ok(Self {
data: &buf[MIN_LV_LEN..MIN_LV_LEN + value_len],
raw_data: Some(buf),
})
}
}
@ -155,8 +176,8 @@ pub mod tests {
let lv_res = Lv::new(&lv_data);
assert!(lv_res.is_ok());
let lv = lv_res.unwrap();
assert!(lv.value().is_some());
let val = lv.value().unwrap();
assert!(lv.value().len() > 0);
let val = lv.value();
assert_eq!(val[0], 1);
assert_eq!(val[1], 2);
assert_eq!(val[2], 3);
@ -172,7 +193,6 @@ pub mod tests {
assert_eq!(lv_empty.len_value(), 0);
assert_eq!(lv_empty.len_full(), 1);
assert!(lv_empty.is_empty());
assert_eq!(lv_empty.value(), None);
let mut buf: [u8; 4] = [0xff; 4];
let res = lv_empty.write_to_be_bytes(&mut buf);
assert!(res.is_ok());
@ -211,10 +231,11 @@ pub mod tests {
assert!(lv.is_ok());
let lv = lv.unwrap();
assert!(!lv.is_empty());
assert!(lv.value().is_some());
assert_eq!(lv.len_value(), 4);
assert_eq!(lv.len_full(), 5);
let val = lv.value().unwrap();
assert!(lv.raw_data().is_some());
assert_eq!(lv.raw_data().unwrap(), buf);
let val = lv.value();
assert_eq!(val[0], 1);
assert_eq!(val[1], 2);
assert_eq!(val[2], 3);
@ -228,7 +249,6 @@ pub mod tests {
assert!(lv_empty.is_ok());
let lv_empty = lv_empty.unwrap();
assert!(lv_empty.is_empty());
assert!(lv_empty.value().is_none());
}
#[test]
@ -282,14 +302,14 @@ pub mod tests {
let res = res.unwrap();
assert_eq!(res, 8 + 1);
assert_eq!(buf[0], 8);
assert_eq!(buf[1], 't' as u8);
assert_eq!(buf[2], 'e' as u8);
assert_eq!(buf[3], 's' as u8);
assert_eq!(buf[4], 't' as u8);
assert_eq!(buf[5], '.' as u8);
assert_eq!(buf[6], 'b' as u8);
assert_eq!(buf[7], 'i' as u8);
assert_eq!(buf[8], 'n' as u8);
assert_eq!(buf[1], b't');
assert_eq!(buf[2], b'e');
assert_eq!(buf[3], b's');
assert_eq!(buf[4], b't');
assert_eq!(buf[5], b'.');
assert_eq!(buf[6], b'b');
assert_eq!(buf[7], b'i');
assert_eq!(buf[8], b'n');
}
#[test]
fn test_str_helper() {

View File

@ -9,6 +9,8 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
pub mod msg_to_user;
pub const MIN_TLV_LEN: usize = 2;
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
@ -70,6 +72,9 @@ impl From<TlvTypeField> for u8 {
/// Generic CFDP type-length-value (TLV) abstraction as specified in CFDP 5.1.9.
///
/// Please note that this class is zero-copy and does not generate a copy of the value data for
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
///
/// # Lifetimes
/// * `data`: If the TLV is generated from a raw bytestream, this will be the lifetime of
/// the raw bytestream. If the TLV is generated from a raw slice or a similar data reference,
@ -98,22 +103,41 @@ impl<'data> Tlv<'data> {
}
}
/// Checks whether the type field contains one of the standard types specified in the CFDP
/// standard and is part of the [TlvType] enum.
pub fn is_standard_tlv(&self) -> bool {
if let TlvTypeField::Standard(_) = self.tlv_type_field {
return true;
}
false
}
/// Returns the standard TLV type if the TLV field is not a custom field
pub fn tlv_type(&self) -> Option<TlvType> {
if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field {
Some(tlv_type)
} else {
None
}
}
pub fn tlv_type_field(&self) -> TlvTypeField {
self.tlv_type_field
}
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
generic_len_check_data_serialization(buf, self.len_value(), MIN_TLV_LEN)?;
generic_len_check_data_serialization(buf, self.value().len(), MIN_TLV_LEN)?;
buf[0] = self.tlv_type_field.into();
self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
Ok(self.len_full())
}
pub fn value(&self) -> Option<&[u8]> {
pub fn value(&self) -> &[u8] {
self.lv.value()
}
/// Returns the length of the value part, not including the length byte.
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
/// [Self::value]
pub fn len_value(&self) -> usize {
self.lv.len_value()
}
@ -134,10 +158,20 @@ impl<'data> Tlv<'data> {
/// [Self::len_full].
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, TlvLvError> {
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
Ok(Self {
let mut tlv = Self {
tlv_type_field: TlvTypeField::from(buf[0]),
lv: Lv::from_bytes(&buf[MIN_LV_LEN..])?,
})
};
// We re-use this field so we do not need an additional struct field to store the raw start
// of the TLV.
tlv.lv.raw_data = Some(buf);
Ok(tlv)
}
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
/// of the TLV can be retrieved with this method.
pub fn raw_data(&self) -> Option<&[u8]> {
self.lv.raw_data()
}
}
@ -234,21 +268,19 @@ impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
)));
}
}
if value.len_value() != 1
&& value.len_value() != 2
&& value.len_value() != 4
&& value.len_value() != 8
{
return Err(TlvLvError::InvalidValueLength(value.len_value()));
let len_value = value.value().len();
if len_value != 1 && len_value != 2 && len_value != 4 && len_value != 8 {
return Err(TlvLvError::InvalidValueLength(len_value));
}
Ok(Self::new(
UnsignedByteField::new_from_be_bytes(value.len_value(), value.value().unwrap())
.map_err(|e| match e {
UnsignedByteField::new_from_be_bytes(len_value, value.value()).map_err(
|e| match e {
UnsignedByteFieldError::ByteConversionError(e) => e,
// This can not happen, we checked for the length validity, and the data is always smaller than
// 255 bytes.
_ => panic!("unexpected error"),
})?,
},
)?,
))
}
}
@ -454,8 +486,8 @@ mod tests {
use crate::cfdp::TlvLvError;
use crate::util::{UbfU8, UnsignedEnum};
const TLV_TEST_STR_0: &'static str = "hello.txt";
const TLV_TEST_STR_1: &'static str = "hello2.txt";
const TLV_TEST_STR_0: &str = "hello.txt";
const TLV_TEST_STR_1: &str = "hello2.txt";
#[test]
fn test_basic() {
@ -470,10 +502,10 @@ mod tests {
TlvTypeField::Standard(TlvType::EntityId)
);
assert_eq!(tlv_res.len_full(), 3);
assert_eq!(tlv_res.value().len(), 1);
assert_eq!(tlv_res.len_value(), 1);
assert!(!tlv_res.is_empty());
assert!(tlv_res.value().is_some());
assert_eq!(tlv_res.value().unwrap()[0], 5);
assert_eq!(tlv_res.value()[0], 5);
}
#[test]
@ -498,26 +530,27 @@ mod tests {
assert!(entity_id.write_to_be_bytes(&mut buf[2..]).is_ok());
buf[0] = TlvType::EntityId as u8;
buf[1] = 1;
let tlv_from_raw = Tlv::from_bytes(&mut buf);
let tlv_from_raw = Tlv::from_bytes(&buf);
assert!(tlv_from_raw.is_ok());
let tlv_from_raw = tlv_from_raw.unwrap();
assert!(tlv_from_raw.raw_data().is_some());
assert_eq!(tlv_from_raw.raw_data().unwrap(), buf);
assert_eq!(
tlv_from_raw.tlv_type_field(),
TlvTypeField::Standard(TlvType::EntityId)
);
assert_eq!(tlv_from_raw.len_value(), 1);
assert_eq!(tlv_from_raw.value().len(), 1);
assert_eq!(tlv_from_raw.len_full(), 3);
assert!(tlv_from_raw.value().is_some());
assert_eq!(tlv_from_raw.value().unwrap()[0], 5);
assert_eq!(tlv_from_raw.value()[0], 5);
}
#[test]
fn test_empty() {
let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
assert!(tlv_empty.value().is_none());
assert_eq!(tlv_empty.value().len(), 0);
assert!(tlv_empty.is_empty());
assert_eq!(tlv_empty.len_full(), 2);
assert_eq!(tlv_empty.len_value(), 0);
assert!(tlv_empty.value().is_empty());
assert_eq!(
tlv_empty.tlv_type_field(),
TlvTypeField::Standard(TlvType::MsgToUser)
@ -538,17 +571,17 @@ mod tests {
let mut buf: [u8; 4] = [0; 4];
buf[0] = TlvType::MsgToUser as u8;
buf[1] = 0;
let tlv_empty = Tlv::from_bytes(&mut buf);
let tlv_empty = Tlv::from_bytes(&buf);
assert!(tlv_empty.is_ok());
let tlv_empty = tlv_empty.unwrap();
assert!(tlv_empty.is_empty());
assert!(tlv_empty.value().is_none());
assert_eq!(tlv_empty.value().len(), 0);
assert_eq!(
tlv_empty.tlv_type_field(),
TlvTypeField::Standard(TlvType::MsgToUser)
);
assert_eq!(tlv_empty.len_full(), 2);
assert_eq!(tlv_empty.len_value(), 0);
assert!(tlv_empty.value().is_empty());
}
#[test]
@ -570,11 +603,11 @@ mod tests {
buf[0] = 3;
buf[1] = 1;
buf[2] = 5;
let tlv = Tlv::from_bytes(&mut buf);
let tlv = Tlv::from_bytes(&buf);
assert!(tlv.is_ok());
let tlv = tlv.unwrap();
assert_eq!(tlv.tlv_type_field(), TlvTypeField::Custom(3));
assert_eq!(tlv.len_value(), 1);
assert_eq!(tlv.value().len(), 1);
assert_eq!(tlv.len_full(), 3);
}

110
src/cfdp/tlv/msg_to_user.rs Normal file
View File

@ -0,0 +1,110 @@
//! Abstractions for the Message to User CFDP TLV subtype.
use super::{Tlv, TlvLvError, TlvType, TlvTypeField};
use crate::ByteConversionError;
use delegate::delegate;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct MsgToUserTlv<'data> {
pub tlv: Tlv<'data>,
}
impl<'data> MsgToUserTlv<'data> {
/// Create a new message to user TLV where the type field is set correctly.
pub fn new(value: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
Ok(Self {
tlv: Tlv::new(TlvType::MsgToUser, value)?,
})
}
delegate! {
to self.tlv {
pub fn tlv_type_field(&self) -> TlvTypeField;
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
pub fn value(&self) -> &[u8];
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
/// [Self::value]
pub fn len_value(&self) -> usize;
/// Returns the full raw length, including the length byte.
pub fn len_full(&self) -> usize;
/// Checks whether the value field is empty.
pub fn is_empty(&self) -> bool;
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
/// of the TLV can be retrieved with this method.
pub fn raw_data(&self) -> Option<&[u8]>;
}
}
pub fn is_standard_tlv(&self) -> bool {
true
}
pub fn tlv_type(&self) -> Option<TlvType> {
Some(TlvType::MsgToUser)
}
/// Check whether this message is a reserved CFDP message like a Proxy Operation Message.
pub fn is_reserved_cfdp_msg(&self) -> bool {
if self.value().len() < 4 {
return false;
}
let value = self.value();
if value[0] == b'c' && value[1] == b'f' && value[2] == b'd' && value[3] == b'p' {
return true;
}
false
}
/// This is a thin wrapper around [Tlv::from_bytes] with the additional type check.
pub fn from_bytes(buf: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
let msg_to_user = Self {
tlv: Tlv::from_bytes(buf)?,
};
match msg_to_user.tlv_type_field() {
TlvTypeField::Standard(tlv_type) => {
if tlv_type != TlvType::MsgToUser {
return Err(TlvLvError::InvalidTlvTypeField((
tlv_type as u8,
Some(TlvType::MsgToUser as u8),
)));
}
}
TlvTypeField::Custom(raw) => {
return Err(TlvLvError::InvalidTlvTypeField((
raw,
Some(TlvType::MsgToUser as u8),
)));
}
}
Ok(msg_to_user)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic() {
let custom_value: [u8; 4] = [1, 2, 3, 4];
let msg_to_user = MsgToUserTlv::new(&custom_value);
assert!(msg_to_user.is_ok());
let msg_to_user = msg_to_user.unwrap();
assert!(msg_to_user.is_standard_tlv());
assert_eq!(msg_to_user.tlv_type().unwrap(), TlvType::MsgToUser);
assert_eq!(msg_to_user.value(), custom_value);
assert_eq!(msg_to_user.value().len(), 4);
assert_eq!(msg_to_user.len_value(), 4);
assert_eq!(msg_to_user.len_full(), 6);
assert!(!msg_to_user.is_empty());
assert!(msg_to_user.raw_data().is_none());
assert!(!msg_to_user.is_reserved_cfdp_msg());
}
#[test]
fn test_reserved_msg() {
let reserved_str = "cfdp";
let msg_to_user = MsgToUserTlv::new(reserved_str.as_bytes());
assert!(msg_to_user.is_ok());
let msg_to_user = msg_to_user.unwrap();
assert!(msg_to_user.is_reserved_cfdp_msg());
}
}