#[cfg(test)]
mod compound_packet_test;
#[cfg(test)]
mod validation_test;
use crate::{
header::*, packet::*, receiver_report::*, sender_report::*, source_description::*, util::*,
};
use shared::{
error::{Error, Result},
marshal::{Marshal, MarshalSize, Unmarshal},
};
use bytes::{Buf, Bytes};
use std::any::Any;
use std::fmt;
#[derive(Debug, Default, PartialEq, Clone)]
pub struct CompoundPacket(pub Vec<Box<dyn Packet>>);
impl fmt::Display for CompoundPacket {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl Packet for CompoundPacket {
fn header(&self) -> Header {
Header::default()
}
fn destination_ssrc(&self) -> Vec<u32> {
if self.0.is_empty() {
vec![]
} else {
self.0[0].destination_ssrc()
}
}
fn raw_size(&self) -> usize {
let mut l = 0;
for packet in &self.0 {
l += packet.marshal_size();
}
l
}
fn as_any(&self) -> &dyn Any {
self
}
fn equal(&self, other: &dyn Packet) -> bool {
other.as_any().downcast_ref::<CompoundPacket>() == Some(self)
}
fn cloned(&self) -> Box<dyn Packet> {
Box::new(self.clone())
}
}
impl MarshalSize for CompoundPacket {
fn marshal_size(&self) -> usize {
let l = self.raw_size();
l + get_padding_size(l)
}
}
impl Marshal for CompoundPacket {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
self.validate()?;
for packet in &self.0 {
let n = packet.marshal_to(buf)?;
buf = &mut buf[n..];
}
Ok(self.marshal_size())
}
}
impl Unmarshal for CompoundPacket {
fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
let mut raw = raw_packet.copy_to_bytes(raw_packet.remaining());
validate_headers(&raw, Datagram::Compound)?;
let mut packets = vec![];
while raw.has_remaining() {
let p = unmarshaller(&mut raw)?;
packets.push(p);
}
let c = CompoundPacket(packets);
c.validate()?;
Ok(c)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Datagram {
Compound,
ReducedSize,
}
fn validate_headers(raw: &[u8], kind: Datagram) -> Result<()> {
if raw.is_empty() {
return Err(Error::EmptyCompound);
}
let mut rest = raw;
let mut first = true;
while !rest.is_empty() {
if rest.len() < HEADER_LENGTH {
return Err(Error::PacketTooShort);
}
if (rest[0] >> VERSION_SHIFT) & VERSION_MASK != RTP_VERSION {
return Err(Error::BadVersion);
}
let padding = (rest[0] >> PADDING_SHIFT) & PADDING_MASK != 0;
let packet_type = rest[1];
let length = u16::from_be_bytes([rest[2], rest[3]]) as usize * 4;
if rest.len() < HEADER_LENGTH + length {
return Err(Error::PacketTooShort);
}
let last = rest.len() == HEADER_LENGTH + length;
if first {
match kind {
Datagram::Compound => {
if packet_type != u8::from(PacketType::SenderReport)
&& packet_type != u8::from(PacketType::ReceiverReport)
{
return Err(Error::BadFirstPacket);
}
if padding {
return Err(Error::WrongPadding);
}
}
Datagram::ReducedSize => {
if !(192..=223).contains(&packet_type) {
return Err(Error::BadFirstPacket);
}
}
}
}
if padding {
if !last {
return Err(Error::WrongPadding);
}
let count = rest[HEADER_LENGTH + length - 1] as usize;
if count == 0 || count > length {
return Err(Error::WrongPadding);
}
}
rest = &rest[HEADER_LENGTH + length..];
first = false;
}
Ok(())
}
pub fn validate_compound(raw: &[u8]) -> Result<()> {
CompoundPacket::unmarshal(&mut &raw[..]).map(|_| ())
}
pub fn validate_compound_headers(raw: &[u8]) -> Result<()> {
validate_headers(raw, Datagram::Compound)
}
pub fn validate_reduced_size(raw: &[u8]) -> Result<()> {
validate_headers(raw, Datagram::ReducedSize)
}
impl CompoundPacket {
pub fn validate(&self) -> Result<()> {
if self.0.is_empty() {
return Err(Error::EmptyCompound);
}
if self.0[0].as_any().downcast_ref::<SenderReport>().is_none()
&& self.0[0]
.as_any()
.downcast_ref::<ReceiverReport>()
.is_none()
{
return Err(Error::BadFirstPacket);
}
if let Some((_, all_but_last)) = self.0.split_last()
&& all_but_last.iter().any(|pkt| pkt.header().padding)
{
return Err(Error::WrongPadding);
}
for pkt in &self.0[1..] {
if pkt.as_any().downcast_ref::<ReceiverReport>().is_some() {
continue;
} else if let Some(e) = pkt.as_any().downcast_ref::<SourceDescription>() {
let mut has_cname = false;
for c in &e.chunks {
for it in &c.items {
if it.sdes_type == SdesType::SdesCname {
has_cname = true
}
}
}
if !has_cname {
return Err(Error::MissingCname);
}
return Ok(());
} else {
return Err(Error::PacketBeforeCname);
}
}
Err(Error::MissingCname)
}
pub fn cname(&self) -> Result<Bytes> {
if self.0.is_empty() {
return Err(Error::EmptyCompound);
}
for pkt in &self.0[1..] {
if let Some(sdes) = pkt.as_any().downcast_ref::<SourceDescription>() {
for c in &sdes.chunks {
for it in &c.items {
if it.sdes_type == SdesType::SdesCname {
return Ok(it.text.clone());
}
}
}
} else if pkt.as_any().downcast_ref::<ReceiverReport>().is_none() {
return Err(Error::PacketBeforeCname);
}
}
Err(Error::MissingCname)
}
}