mod helpers;
use std::panic::catch_unwind;
use proptest::{
collection::vec,
prelude::{ProptestConfig, Strategy, any},
prop_assert, prop_oneof, proptest,
};
use sciparse::{
core::view::{View, ViewConversionError},
header::view::ScionHeaderView,
packet::view::ScionRawPacketView,
};
use crate::helpers::view_function_checks;
#[test]
fn parsing_random_packet_data_must_not_panic() {
proptest!(
ProptestConfig::with_cases(5_000),
| (data in rand_packet_data()) | {
random_packet_data_must_not_panic_impl(data)?;
}
);
fn random_packet_data_must_not_panic_impl(
data: Vec<u8>,
) -> Result<(), proptest::prelude::TestCaseError> {
let unwind = catch_unwind(|| {
let mut data = data;
match ScionRawPacketView::from_mut_slice(&mut data) {
Ok((view, _rest)) => {
view_function_checks::packet::exec_every_view_function(view);
}
Err(ViewConversionError::BufferTooSmall { .. })
| Err(ViewConversionError::Other(_)) => {
return Ok(());
}
}
Ok(())
});
match unwind {
Ok(res) => res,
Err(panic) => {
println!("{:?}", panic.downcast_ref::<&str>());
prop_assert!(false, "Panic during random packet data parsing");
Ok(())
}
}
}
fn rand_packet_data() -> impl Strategy<Value = Vec<u8>> {
fn bias_to_packet_shape(mut data: Vec<u8>) -> Vec<u8> {
if data.len() < 36 {
return data;
}
let rand_byte = data.len() % data[5].max(1) as usize;
let len = data.len();
let view = unsafe { ScionHeaderView::from_mut_slice_unchecked(&mut data) };
view.set_version(0);
if rand_byte.is_multiple_of(3) {
let header_len = ((len.min(1000) / 4) * 4) as u16;
unsafe {
view.set_header_len(header_len);
}
}
if rand_byte.is_multiple_of(5) {
let hl = view.header_len() as usize;
let remaining = len.saturating_sub(hl);
unsafe {
view.set_payload_len(remaining.min(u16::MAX as usize) as u16);
}
}
if rand_byte.is_multiple_of(7) {
let proto = if rand_byte.is_multiple_of(2) {
17u8
} else {
202u8
};
view.set_next_header(proto);
}
data
}
prop_oneof![
6 => vec(any::<u8>(), 36..=256).prop_map(bias_to_packet_shape),
3 => vec(any::<u8>(), 36..=1024).prop_map(bias_to_packet_shape),
1 => vec(any::<u8>(), 0..=1024),
]
}
}