use std::{
collections::HashMap,
net::IpAddr,
sync::{
Arc,
Mutex,
atomic::{
AtomicU64,
Ordering,
},
},
};
use bytes::Bytes;
use tokio::{
net::TcpStream,
sync::mpsc,
};
use crate::{
ecmg::SectionTsPktFlag,
emmg::message::{
ChannelCloseMessage,
ChannelSetupMessage,
ChannelTestMessage,
DataProvisionMessage,
EmmgMessage,
ParsedFields,
StreamBwRequestMessage,
StreamCloseRequestMessage,
StreamSetupMessage,
StreamTestMessage,
},
lock_ext::MutexExt,
messages::{
RawSimulcryptMessage,
emmg::{
EMMG_ERR_CHANNEL_IN_USE,
EMMG_ERR_INVALID_MESSAGE,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
EMMG_ERR_UNKNOWN_STREAM_ID,
EMMG_ERR_UNKNOWN_SUPER_CAS_ID,
EMMG_MSG_CHANNEL_ERROR,
EMMG_MSG_CHANNEL_STATUS,
EMMG_MSG_DATA_PROVISION,
EMMG_MSG_STREAM_BW_ALLOC,
EMMG_MSG_STREAM_CLOSE_RESPONSE,
EMMG_MSG_STREAM_ERROR,
EMMG_MSG_STREAM_STATUS,
EMMG_VAR_BANDWIDTH,
EMMG_VAR_CHANNEL_ID,
EMMG_VAR_DATA_ID,
EMMG_VAR_DATA_TYPE,
EMMG_VAR_ERROR_INFO,
EMMG_VAR_ERROR_STATUS,
EMMG_VAR_SECTION_TS_PKT_FLAG,
EMMG_VAR_STREAM_ID,
EMMG_VAR_SUPER_CAS_ID,
},
},
};
#[derive(Debug)]
pub struct EmmEvent {
pub stream_id: u16,
pub data_id: u16,
pub data_type: u8,
pub format: SectionTsPktFlag,
pub data: Bytes,
}
#[derive(Debug, thiserror::Error)]
pub enum DispatchError {
#[error("channel_id={channel_id} is already registered on this EMMG dispatcher")]
ChannelInUse {
channel_id: u16,
},
#[error("channel_id={channel_id} is not registered on this EMMG dispatcher")]
UnknownChannel {
channel_id: u16,
},
}
struct StreamEntry {
sink: mpsc::UnboundedSender<EmmEvent>,
setup: Option<(u16, u8)>,
}
struct ChannelEntry {
super_cas_id: u32,
owner: Option<Connection>,
broadcast: bool,
section_ts_pkt_flag: SectionTsPktFlag,
streams: HashMap<u16, StreamEntry>,
}
impl ChannelEntry {
fn release(&mut self) {
self.owner = None;
for stream in self.streams.values_mut() {
stream.setup = None;
}
}
fn deliver(&self, stream_id: u16, data: &Bytes) {
let targets = self
.streams
.iter()
.filter(|(id, _)| self.broadcast || **id == stream_id);
for (&stream_id, stream) in targets {
if let Some((data_id, data_type)) = stream.setup {
let _ = stream.sink.send(EmmEvent {
stream_id,
data_id,
data_type,
format: self.section_ts_pkt_flag,
data: data.clone(),
});
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Connection {
id: u64,
ip: IpAddr,
}
impl Connection {
#[must_use]
pub fn new(id: u64, ip: IpAddr) -> Self {
Self {
id,
ip: ip.to_canonical(),
}
}
}
fn owned_mut(
channels: &mut HashMap<u16, ChannelEntry>,
connection: Connection,
channel_id: u16,
) -> Option<&mut ChannelEntry> {
channels
.get_mut(&channel_id)
.filter(|entry| entry.owner == Some(connection))
}
#[derive(Clone, Default)]
pub struct Dispatch {
channels: Arc<Mutex<HashMap<u16, ChannelEntry>>>,
next_connection: Arc<AtomicU64>,
}
impl Dispatch {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register_channel(
&self,
super_cas_id: u32,
channel_id: u16,
broadcast: bool,
) -> Result<(), DispatchError> {
let mut channels = self.channels.lock_or_recover();
if channels.contains_key(&channel_id) {
return Err(DispatchError::ChannelInUse { channel_id });
}
channels.insert(
channel_id,
ChannelEntry {
super_cas_id,
owner: None,
broadcast,
section_ts_pkt_flag: SectionTsPktFlag::DEFAULT,
streams: HashMap::new(),
},
);
Ok(())
}
pub fn register_stream(
&self,
channel_id: u16,
stream_id: u16,
sink: mpsc::UnboundedSender<EmmEvent>,
) -> Result<(), DispatchError> {
let mut channels = self.channels.lock_or_recover();
let entry = channels
.get_mut(&channel_id)
.ok_or(DispatchError::UnknownChannel { channel_id })?;
entry
.streams
.insert(stream_id, StreamEntry { sink, setup: None });
Ok(())
}
pub fn unregister_stream(&self, channel_id: u16, stream_id: u16) {
if let Some(entry) = self.channels.lock_or_recover().get_mut(&channel_id) {
entry.streams.remove(&stream_id);
}
}
pub fn update_channel(&self, channel_id: u16, super_cas_id: u32, broadcast: bool) {
if let Some(entry) = self.channels.lock_or_recover().get_mut(&channel_id) {
if entry.super_cas_id != super_cas_id {
entry.super_cas_id = super_cas_id;
entry.release();
}
entry.broadcast = broadcast;
}
}
pub fn unregister_channel(&self, channel_id: u16) {
self.channels.lock_or_recover().remove(&channel_id);
}
#[must_use]
pub fn handle(
&self,
connection: Connection,
raw: RawSimulcryptMessage,
) -> Option<RawSimulcryptMessage> {
let super_cas_id = raw.get_u32(EMMG_VAR_SUPER_CAS_ID).unwrap_or(0);
let channel_id = raw.get_u16(EMMG_VAR_CHANNEL_ID).unwrap_or(0);
let stream_id = raw.get_u16(EMMG_VAR_STREAM_ID);
match EmmgMessage::try_from(raw) {
Ok(EmmgMessage::ChannelSetup(msg)) => Some(self.channel_setup(connection, &msg)),
Ok(EmmgMessage::ChannelTest(msg)) => Some(self.channel_test(connection, &msg)),
Ok(EmmgMessage::ChannelClose(msg)) => self.channel_close(connection, &msg),
Ok(EmmgMessage::StreamSetup(msg)) => Some(self.stream_setup(connection, &msg)),
Ok(EmmgMessage::StreamTest(msg)) => Some(self.stream_test(connection, &msg)),
Ok(EmmgMessage::StreamCloseRequest(msg)) => Some(self.stream_close(connection, &msg)),
Ok(EmmgMessage::StreamBwRequest(msg)) => Some(self.stream_bw_request(connection, &msg)),
Ok(EmmgMessage::DataProvision(msg)) => self.data_provision(connection, msg),
Err(_) => Some(Self::invalid_message_error(
super_cas_id,
channel_id,
stream_id,
)),
}
}
fn channel_setup(
&self,
connection: Connection,
msg: &ChannelSetupMessage,
) -> RawSimulcryptMessage {
let mut channels = self.channels.lock_or_recover();
match channels.get_mut(&msg.channel_id) {
Some(entry)
if entry.super_cas_id == msg.super_cas_id
&& entry.owner.is_some_and(|owner| owner != connection) =>
{
Self::channel_error(msg.super_cas_id, msg.channel_id, EMMG_ERR_CHANNEL_IN_USE)
}
Some(entry) if entry.super_cas_id == msg.super_cas_id => {
entry.owner = Some(connection);
entry.section_ts_pkt_flag =
SectionTsPktFlag::from(u8::from(msg.section_ts_pkt_flag));
Self::channel_status(msg.super_cas_id, msg.channel_id, entry.section_ts_pkt_flag)
}
Some(_) => Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_SUPER_CAS_ID,
),
None => Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
),
}
}
fn channel_test(
&self,
connection: Connection,
msg: &ChannelTestMessage,
) -> RawSimulcryptMessage {
let channels = self.channels.lock_or_recover();
match channels.get(&msg.channel_id) {
Some(entry) if entry.super_cas_id != msg.super_cas_id => Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_SUPER_CAS_ID,
),
Some(entry) if entry.owner == Some(connection) => {
Self::channel_status(msg.super_cas_id, msg.channel_id, entry.section_ts_pkt_flag)
}
_ => Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
),
}
}
fn channel_close(
&self,
connection: Connection,
msg: &ChannelCloseMessage,
) -> Option<RawSimulcryptMessage> {
let mut channels = self.channels.lock_or_recover();
match channels.get_mut(&msg.channel_id) {
Some(entry) if entry.super_cas_id != msg.super_cas_id => Some(Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_SUPER_CAS_ID,
)),
Some(entry) if entry.owner == Some(connection) => {
entry.release();
None
}
_ => Some(Self::channel_error(
msg.super_cas_id,
msg.channel_id,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
)),
}
}
fn stream_setup(
&self,
connection: Connection,
msg: &StreamSetupMessage,
) -> RawSimulcryptMessage {
let mut channels = self.channels.lock_or_recover();
let Some(entry) = owned_mut(&mut channels, connection, msg.channel_id) else {
return Self::stream_error(0, msg.channel_id, None, EMMG_ERR_UNKNOWN_CHANNEL_ID);
};
let super_cas_id = entry.super_cas_id;
let Some(stream) = entry.streams.get_mut(&msg.stream_id) else {
return Self::stream_error(
super_cas_id,
msg.channel_id,
Some(msg.stream_id),
EMMG_ERR_UNKNOWN_STREAM_ID,
);
};
stream.setup = Some((msg.data_id, msg.data_type));
Self::stream_status(
super_cas_id,
msg.channel_id,
msg.stream_id,
msg.data_id,
msg.data_type,
)
}
fn stream_test(&self, connection: Connection, msg: &StreamTestMessage) -> RawSimulcryptMessage {
let mut channels = self.channels.lock_or_recover();
let Some(entry) = owned_mut(&mut channels, connection, msg.channel_id) else {
return Self::stream_error(0, msg.channel_id, None, EMMG_ERR_UNKNOWN_CHANNEL_ID);
};
let super_cas_id = entry.super_cas_id;
match entry.streams.get(&msg.stream_id).and_then(|s| s.setup) {
Some((data_id, data_type)) => Self::stream_status(
super_cas_id,
msg.channel_id,
msg.stream_id,
data_id,
data_type,
),
None => Self::stream_error(
super_cas_id,
msg.channel_id,
Some(msg.stream_id),
EMMG_ERR_UNKNOWN_STREAM_ID,
),
}
}
fn stream_close(
&self,
connection: Connection,
msg: &StreamCloseRequestMessage,
) -> RawSimulcryptMessage {
let mut channels = self.channels.lock_or_recover();
let Some(entry) = owned_mut(&mut channels, connection, msg.channel_id) else {
return Self::stream_error(0, msg.channel_id, None, EMMG_ERR_UNKNOWN_CHANNEL_ID);
};
let super_cas_id = entry.super_cas_id;
let Some(stream) = entry.streams.get_mut(&msg.stream_id) else {
return Self::stream_error(
super_cas_id,
msg.channel_id,
Some(msg.stream_id),
EMMG_ERR_UNKNOWN_STREAM_ID,
);
};
stream.setup = None;
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_STREAM_CLOSE_RESPONSE);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, msg.channel_id);
raw.set_u16(EMMG_VAR_STREAM_ID, msg.stream_id);
raw
}
fn stream_bw_request(
&self,
connection: Connection,
msg: &StreamBwRequestMessage,
) -> RawSimulcryptMessage {
let mut channels = self.channels.lock_or_recover();
let Some(entry) = owned_mut(&mut channels, connection, msg.channel_id) else {
return Self::stream_error(0, msg.channel_id, None, EMMG_ERR_UNKNOWN_CHANNEL_ID);
};
let super_cas_id = entry.super_cas_id;
match entry.streams.get(&msg.stream_id).and_then(|s| s.setup) {
Some(_) => {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_STREAM_BW_ALLOC);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, msg.channel_id);
raw.set_u16(EMMG_VAR_STREAM_ID, msg.stream_id);
raw.set_u16(EMMG_VAR_BANDWIDTH, msg.bandwidth);
raw
}
None => Self::stream_error(
super_cas_id,
msg.channel_id,
Some(msg.stream_id),
EMMG_ERR_UNKNOWN_STREAM_ID,
),
}
}
fn data_provision(
&self,
connection: Connection,
msg: DataProvisionMessage,
) -> Option<RawSimulcryptMessage> {
let mut channels = self.channels.lock_or_recover();
let Some(entry) = owned_mut(&mut channels, connection, msg.channel_id) else {
return Some(Self::stream_error(
0,
msg.channel_id,
None,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
));
};
if entry
.streams
.get(&msg.stream_id)
.and_then(|s| s.setup)
.is_none()
{
return Some(Self::stream_error(
entry.super_cas_id,
msg.channel_id,
Some(msg.stream_id),
EMMG_ERR_UNKNOWN_STREAM_ID,
));
}
entry.deliver(msg.stream_id, &Bytes::from(msg.data));
None
}
pub fn handle_datagram(
&self,
source: IpAddr,
raw: RawSimulcryptMessage,
) -> Result<(), &'static str> {
let source = source.to_canonical();
if raw.message_type != EMMG_MSG_DATA_PROVISION {
return Err("not a DATA_PROVISION");
}
let ParsedFields {
super_cas_id: client_id,
channel_id,
stream_id,
data_id,
datagram,
..
} = ParsedFields::parse(raw.vars).map_err(|_| "malformed field")?;
let data = datagram.ok_or("missing datagram")?;
let channels = self.channels.lock_or_recover();
let (entry, stream_id) = match (channel_id, stream_id) {
(Some(channel_id), Some(stream_id)) => {
let entry = channels
.get(&channel_id)
.filter(|entry| entry.owner.is_some())
.ok_or("unknown channel_id")?;
if entry.owner.is_some_and(|owner| owner.ip != source) {
return Err("source is not the channel owner");
}
let (setup_data_id, _) = entry
.streams
.get(&stream_id)
.and_then(|stream| stream.setup)
.ok_or("unknown stream_id")?;
if client_id.is_some_and(|id| id != entry.super_cas_id) {
return Err("client_id mismatch");
}
if data_id.is_some_and(|id| id != setup_data_id) {
return Err("data_id mismatch");
}
(entry, stream_id)
}
(None, None) => {
let (Some(client_id), Some(data_id)) = (client_id, data_id) else {
return Err("no stream address");
};
channels
.values()
.filter(|entry| {
entry.owner.is_some_and(|owner| owner.ip == source)
&& entry.super_cas_id == client_id
})
.find_map(|entry| {
entry
.streams
.iter()
.find(|(_, stream)| {
stream
.setup
.is_some_and(|(setup_data_id, _)| setup_data_id == data_id)
})
.map(|(stream_id, _)| (entry, *stream_id))
})
.ok_or("unknown client_id/data_id")?
}
_ => return Err("channel_id without stream_id or vice versa"),
};
entry.deliver(stream_id, &Bytes::from(data));
Ok(())
}
fn channel_status(
super_cas_id: u32,
channel_id: u16,
section_ts_pkt_flag: SectionTsPktFlag,
) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_CHANNEL_STATUS);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
raw.set_u8(EMMG_VAR_SECTION_TS_PKT_FLAG, section_ts_pkt_flag.as_u8());
raw
}
fn stream_status(
super_cas_id: u32,
channel_id: u16,
stream_id: u16,
data_id: u16,
data_type: u8,
) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_STREAM_STATUS);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
raw.set_u16(EMMG_VAR_STREAM_ID, stream_id);
raw.set_u16(EMMG_VAR_DATA_ID, data_id);
raw.set_u8(EMMG_VAR_DATA_TYPE, data_type);
raw
}
fn channel_error(super_cas_id: u32, channel_id: u16, status: u16) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_CHANNEL_ERROR);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
raw.set_u16(EMMG_VAR_ERROR_STATUS, status);
raw.add_var(EMMG_VAR_ERROR_INFO, Self::error_info(status).into_bytes());
raw
}
fn stream_error(
super_cas_id: u32,
channel_id: u16,
stream_id: Option<u16>,
status: u16,
) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_STREAM_ERROR);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
raw.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
if let Some(stream_id) = stream_id {
raw.set_u16(EMMG_VAR_STREAM_ID, stream_id);
}
raw.set_u16(EMMG_VAR_ERROR_STATUS, status);
raw.add_var(EMMG_VAR_ERROR_INFO, Self::error_info(status).into_bytes());
raw
}
fn invalid_message_error(
super_cas_id: u32,
channel_id: u16,
stream_id: Option<u16>,
) -> RawSimulcryptMessage {
Self::stream_error(
super_cas_id,
channel_id,
stream_id,
EMMG_ERR_INVALID_MESSAGE,
)
}
fn error_info(status: u16) -> String {
match status {
EMMG_ERR_INVALID_MESSAGE => "invalid message",
EMMG_ERR_UNKNOWN_STREAM_ID => "unknown data_stream_id value",
EMMG_ERR_UNKNOWN_CHANNEL_ID => "unknown data_channel_id value",
EMMG_ERR_UNKNOWN_SUPER_CAS_ID => "unknown client_id value",
EMMG_ERR_CHANNEL_IN_USE => "data_channel_id value already in use",
_ => "-",
}
.to_owned()
}
pub async fn serve_connection(self, mut stream: TcpStream) {
let Ok(peer) = stream.peer_addr() else {
return;
};
let connection = Connection::new(
self.next_connection.fetch_add(1, Ordering::Relaxed),
peer.ip(),
);
while let Ok(raw) = RawSimulcryptMessage::read_from(&mut stream).await {
if let Some(response) = self.handle(connection, raw)
&& response.write_to(&mut stream).await.is_err()
{
break;
}
}
self.release_connection(connection);
}
pub fn release_connection(&self, connection: Connection) {
for entry in self.channels.lock_or_recover().values_mut() {
if entry.owner == Some(connection) {
entry.release();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::emmg::{
EMMG_ERR_CHANNEL_IN_USE,
EMMG_ERR_UNKNOWN_CHANNEL_ID,
EMMG_ERR_UNKNOWN_STREAM_ID,
EMMG_MSG_CHANNEL_CLOSE,
EMMG_MSG_CHANNEL_SETUP,
EMMG_MSG_CHANNEL_STATUS,
EMMG_MSG_DATA_PROVISION,
EMMG_MSG_STREAM_CLOSE_REQUEST,
EMMG_MSG_STREAM_CLOSE_RESPONSE,
EMMG_MSG_STREAM_SETUP,
EMMG_MSG_STREAM_STATUS,
EMMG_VAR_CHANNEL_ID,
EMMG_VAR_DATA_ID,
EMMG_VAR_DATA_TYPE,
EMMG_VAR_DATAGRAM,
EMMG_VAR_ERROR_STATUS,
EMMG_VAR_SECTION_TS_PKT_FLAG,
EMMG_VAR_STREAM_ID,
EMMG_VAR_SUPER_CAS_ID,
};
const SUPER_CAS_ID: u32 = 0x0B00_0001;
const CHANNEL_ID: u16 = 1;
const STREAM_ID: u16 = 5;
const LOCAL: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
const A: Connection = Connection { id: 1, ip: LOCAL };
const B: Connection = Connection { id: 2, ip: LOCAL };
fn channel_message(message_type: u16) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(message_type);
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, SUPER_CAS_ID);
raw.set_u16(EMMG_VAR_CHANNEL_ID, CHANNEL_ID);
if message_type == EMMG_MSG_CHANNEL_SETUP {
raw.set_u8(EMMG_VAR_SECTION_TS_PKT_FLAG, 0);
}
raw
}
fn stream_message(message_type: u16) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(message_type);
raw.set_u16(EMMG_VAR_CHANNEL_ID, CHANNEL_ID);
raw.set_u16(EMMG_VAR_STREAM_ID, STREAM_ID);
match message_type {
EMMG_MSG_STREAM_SETUP => {
raw.set_u16(EMMG_VAR_DATA_ID, 1);
raw.set_u8(EMMG_VAR_DATA_TYPE, 0);
}
EMMG_MSG_DATA_PROVISION => raw.add_var(EMMG_VAR_DATAGRAM, vec![0xAA]),
_ => {}
}
raw
}
fn error_status(reply: Option<RawSimulcryptMessage>) -> Option<u16> {
reply?.get_u16(EMMG_VAR_ERROR_STATUS)
}
fn setup() -> (Dispatch, mpsc::UnboundedReceiver<EmmEvent>) {
let dispatch = Dispatch::new();
dispatch
.register_channel(SUPER_CAS_ID, CHANNEL_ID, false)
.unwrap();
let (tx, rx) = mpsc::unbounded_channel();
dispatch.register_stream(CHANNEL_ID, STREAM_ID, tx).unwrap();
(dispatch, rx)
}
fn open(dispatch: &Dispatch, connection: Connection) {
let reply = dispatch.handle(connection, channel_message(EMMG_MSG_CHANNEL_SETUP));
assert_eq!(reply.unwrap().message_type, EMMG_MSG_CHANNEL_STATUS);
let reply = dispatch.handle(connection, stream_message(EMMG_MSG_STREAM_SETUP));
assert_eq!(reply.unwrap().message_type, EMMG_MSG_STREAM_STATUS);
}
#[test]
fn channel_belongs_to_the_connection_that_set_it_up() {
let (dispatch, mut rx) = setup();
open(&dispatch, A);
let reply = dispatch.handle(B, channel_message(EMMG_MSG_CHANNEL_SETUP));
assert_eq!(error_status(reply), Some(EMMG_ERR_CHANNEL_IN_USE));
let reply = dispatch.handle(B, stream_message(EMMG_MSG_DATA_PROVISION));
assert_eq!(error_status(reply), Some(EMMG_ERR_UNKNOWN_CHANNEL_ID));
assert!(rx.try_recv().is_err());
assert!(
dispatch
.handle(A, stream_message(EMMG_MSG_DATA_PROVISION))
.is_none()
);
assert_eq!(rx.try_recv().unwrap().stream_id, STREAM_ID);
}
#[test]
fn disconnect_releases_the_channel_and_its_stream_setups() {
let (dispatch, _rx) = setup();
open(&dispatch, A);
dispatch.release_connection(A);
let reply = dispatch.handle(B, channel_message(EMMG_MSG_CHANNEL_SETUP));
assert_eq!(reply.unwrap().message_type, EMMG_MSG_CHANNEL_STATUS);
let reply = dispatch.handle(B, stream_message(EMMG_MSG_DATA_PROVISION));
assert_eq!(error_status(reply), Some(EMMG_ERR_UNKNOWN_STREAM_ID));
}
#[test]
fn stream_close_and_channel_close_release_setups() {
let (dispatch, _rx) = setup();
open(&dispatch, A);
let reply = dispatch.handle(A, stream_message(EMMG_MSG_STREAM_CLOSE_REQUEST));
assert_eq!(reply.unwrap().message_type, EMMG_MSG_STREAM_CLOSE_RESPONSE);
let reply = dispatch.handle(A, stream_message(EMMG_MSG_DATA_PROVISION));
assert_eq!(error_status(reply), Some(EMMG_ERR_UNKNOWN_STREAM_ID));
assert!(
dispatch
.handle(A, channel_message(EMMG_MSG_CHANNEL_CLOSE))
.is_none()
);
let reply = dispatch.handle(A, stream_message(EMMG_MSG_DATA_PROVISION));
assert_eq!(error_status(reply), Some(EMMG_ERR_UNKNOWN_CHANNEL_ID));
open(&dispatch, B);
}
fn datagram(
ids: Option<(u16, u16)>,
client_id: Option<u32>,
data_id: Option<u16>,
) -> RawSimulcryptMessage {
let mut raw = RawSimulcryptMessage::new(EMMG_MSG_DATA_PROVISION);
if let Some((channel_id, stream_id)) = ids {
raw.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
raw.set_u16(EMMG_VAR_STREAM_ID, stream_id);
}
if let Some(client_id) = client_id {
raw.set_u32(EMMG_VAR_SUPER_CAS_ID, client_id);
}
if let Some(data_id) = data_id {
raw.set_u16(EMMG_VAR_DATA_ID, data_id);
}
raw.add_var(EMMG_VAR_DATAGRAM, vec![0xAA]);
raw
}
#[test]
fn datagram_with_ids_needs_a_set_up_stream_but_no_connection() {
let (dispatch, mut rx) = setup();
open(&dispatch, A);
let raw = datagram(Some((CHANNEL_ID, STREAM_ID)), Some(SUPER_CAS_ID), Some(1));
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Ok(()));
assert_eq!(rx.try_recv().unwrap().stream_id, STREAM_ID);
}
#[test]
fn datagram_without_ids_resolves_by_client_id_and_data_id() {
let (dispatch, mut rx) = setup();
open(&dispatch, A);
let raw = datagram(None, Some(SUPER_CAS_ID), Some(1));
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Ok(()));
let event = rx.try_recv().unwrap();
assert_eq!((event.stream_id, event.data_id), (STREAM_ID, 1));
}
#[test]
fn datagram_is_accepted_only_from_the_owner_ip() {
let (dispatch, mut rx) = setup();
open(&dispatch, A);
let ids = Some((CHANNEL_ID, STREAM_ID));
let other = IpAddr::from([10, 0, 0, 1]);
assert_eq!(
dispatch.handle_datagram(other, datagram(ids, None, None)),
Err("source is not the channel owner")
);
assert_eq!(
dispatch.handle_datagram(other, datagram(None, Some(SUPER_CAS_ID), Some(1))),
Err("unknown client_id/data_id")
);
assert!(rx.try_recv().is_err());
let mapped = IpAddr::from(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped());
assert_eq!(
dispatch.handle_datagram(mapped, datagram(ids, None, None)),
Ok(())
);
assert!(rx.try_recv().is_ok());
}
#[test]
fn unresolved_datagram_is_dropped() {
let (dispatch, mut rx) = setup();
let ids = Some((CHANNEL_ID, STREAM_ID));
let by_data_id = || datagram(None, Some(SUPER_CAS_ID), Some(1));
let not_set_up = [
(datagram(ids, None, None), "unknown channel_id"),
(by_data_id(), "unknown client_id/data_id"),
];
for (raw, reason) in not_set_up {
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Err(reason));
}
let reply = dispatch.handle(A, channel_message(EMMG_MSG_CHANNEL_SETUP));
assert_eq!(reply.unwrap().message_type, EMMG_MSG_CHANNEL_STATUS);
let no_stream_setup = [
(datagram(ids, None, None), "unknown stream_id"),
(by_data_id(), "unknown client_id/data_id"),
];
for (raw, reason) in no_stream_setup {
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Err(reason));
}
open(&dispatch, A);
let mut only_channel = by_data_id();
only_channel.set_u16(EMMG_VAR_CHANNEL_ID, CHANNEL_ID);
let mut short_channel_id = by_data_id();
short_channel_id.add_var(EMMG_VAR_CHANNEL_ID, vec![0]);
short_channel_id.add_var(EMMG_VAR_STREAM_ID, vec![0]);
let mut two_datagrams = datagram(ids, None, None);
two_datagrams.add_var(EMMG_VAR_DATAGRAM, vec![0xBB]);
let mut two_channel_ids = datagram(ids, None, None);
two_channel_ids.add_var(EMMG_VAR_CHANNEL_ID, CHANNEL_ID.to_be_bytes().to_vec());
let mut no_datagram = datagram(ids, None, None);
no_datagram.vars.retain(|var| var.tag != EMMG_VAR_DATAGRAM);
let mut wrong_type = datagram(ids, None, None);
wrong_type.message_type = EMMG_MSG_STREAM_SETUP;
let set_up = [
(
datagram(Some((CHANNEL_ID + 1, STREAM_ID)), None, None),
"unknown channel_id",
),
(
datagram(Some((CHANNEL_ID, STREAM_ID + 1)), None, None),
"unknown stream_id",
),
(
datagram(ids, Some(SUPER_CAS_ID + 1), None),
"client_id mismatch",
),
(datagram(ids, None, Some(2)), "data_id mismatch"),
(
datagram(None, Some(SUPER_CAS_ID + 1), Some(1)),
"unknown client_id/data_id",
),
(
datagram(None, Some(SUPER_CAS_ID), Some(2)),
"unknown client_id/data_id",
),
(
datagram(None, Some(SUPER_CAS_ID), None),
"no stream address",
),
(datagram(None, None, Some(1)), "no stream address"),
(only_channel, "channel_id without stream_id or vice versa"),
(short_channel_id, "malformed field"),
(two_datagrams, "malformed field"),
(two_channel_ids, "malformed field"),
(no_datagram, "missing datagram"),
(wrong_type, "not a DATA_PROVISION"),
];
for (raw, reason) in set_up {
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Err(reason));
}
dispatch.release_connection(A);
let released = [
(datagram(ids, None, None), "unknown channel_id"),
(by_data_id(), "unknown client_id/data_id"),
];
for (raw, reason) in released {
assert_eq!(dispatch.handle_datagram(LOCAL, raw), Err(reason));
}
assert!(rx.try_recv().is_err());
}
}