use std::{
collections::HashMap,
net::SocketAddr,
time::Duration,
};
use bytes::Bytes;
use tokio::{
net::TcpStream,
sync::{
mpsc,
oneshot,
},
time::Instant,
};
use crate::ecmg::{
ChannelParams,
SectionTsPktFlag,
session::{
EcmgEvent,
EcmgSession,
SessionError,
},
};
#[derive(Clone, Debug)]
pub struct DriverConfig {
pub name: String,
pub channel_id: u16,
pub super_cas_id: u32,
pub addr: SocketAddr,
pub reconnect_delay: Duration,
pub response_timeout: Duration,
pub idle_probe_interval: Duration,
}
impl DriverConfig {
async fn connect(&self, known_streams: &[(u16, u16)]) -> Result<EcmgSession, SessionError> {
tracing::info!(
name = %self.name,
addr = %self.addr,
"connecting to ECMG"
);
let tcp_stream =
tokio::time::timeout(self.response_timeout, TcpStream::connect(self.addr)).await??;
EcmgSession::open(
tcp_stream,
self.channel_id,
self.super_cas_id,
known_streams,
&self.name,
self.response_timeout,
)
.await
}
async fn run(
self,
mut cmd_rx: mpsc::UnboundedReceiver<DriverCommand>,
events_tx: mpsc::UnboundedSender<DriverEvent>,
) {
let mut known_streams: Vec<(u16, u16)> = Vec::new();
let mut last_provision: HashMap<u16, ProvisionRecord> = HashMap::new();
loop {
if cmd_rx.is_closed() {
return;
}
let _ = events_tx.send(DriverEvent::State(DriverState::Connecting));
match self.connect(&known_streams).await {
Ok(mut session) => {
for (stream_id, record) in &last_provision {
if let Err(error) = session
.send_cw_provision_to(
*stream_id,
record.cp_number,
&record.current,
&record.next,
record.access_criteria.as_deref(),
)
.await
{
tracing::warn!(
name = %self.name,
stream_id,
error = %error,
"failed to replay CW_PROVISION after reconnect"
);
}
}
let _ = events_tx.send(DriverEvent::State(DriverState::Ready {
section_ts_pkt_flag: session.section_ts_pkt_flag(),
params: session.channel_params(),
ready_stream_ids: session.stream_ids().collect(),
}));
run_session(
&self,
&mut session,
&mut cmd_rx,
&events_tx,
&mut known_streams,
&mut last_provision,
)
.await;
}
Err(error) => {
tracing::warn!(
name = %self.name,
error = %error,
"ECMG connection failed"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: None,
info: Some(error.to_string()),
}));
}
}
let _ = events_tx.send(DriverEvent::State(DriverState::Disconnected));
tokio::time::sleep(self.reconnect_delay).await;
}
}
}
#[derive(Debug)]
pub enum DriverEvent {
Ecm {
stream_id: u16,
cp_number: Option<u16>,
format: SectionTsPktFlag,
data: Bytes,
},
StaleEcm {
stream_id: u16,
},
State(DriverState),
}
#[derive(Clone, Debug)]
pub enum DriverState {
Connecting,
Ready {
section_ts_pkt_flag: SectionTsPktFlag,
params: ChannelParams,
ready_stream_ids: Vec<u16>,
},
Error {
code: Option<u16>,
info: Option<String>,
},
Disconnected,
}
#[derive(Debug, thiserror::Error)]
pub enum DriverError {
#[error("ECMG driver task is no longer running")]
Closed,
#[error("ECMG stream setup failed: {0}")]
Session(#[source] SessionError),
}
enum DriverCommand {
AddStream {
stream_id: u16,
nominal_cp_duration: u16,
reply: oneshot::Sender<Result<(), DriverError>>,
},
ProvisionCw {
stream_id: u16,
cp_number: u16,
current: [u8; 8],
next: [u8; 8],
access_criteria: Option<Vec<u8>>,
},
RemoveStream {
stream_id: u16,
},
}
#[derive(Clone)]
pub struct DriverHandle {
tx: mpsc::UnboundedSender<DriverCommand>,
}
impl DriverHandle {
pub async fn add_stream(
&self,
stream_id: u16,
nominal_cp_duration: u16,
) -> Result<(), DriverError> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(DriverCommand::AddStream {
stream_id,
nominal_cp_duration,
reply: reply_tx,
})
.map_err(|_| DriverError::Closed)?;
reply_rx.await.map_err(|_| DriverError::Closed)?
}
pub fn remove_stream(&self, stream_id: u16) -> Result<(), DriverError> {
self.tx
.send(DriverCommand::RemoveStream { stream_id })
.map_err(|_| DriverError::Closed)
}
pub fn provision_cw(
&self,
stream_id: u16,
cp_number: u16,
current: [u8; 8],
next: [u8; 8],
access_criteria: Option<Vec<u8>>,
) -> Result<(), DriverError> {
self.tx
.send(DriverCommand::ProvisionCw {
stream_id,
cp_number,
current,
next,
access_criteria,
})
.map_err(|_| DriverError::Closed)
}
#[must_use]
pub fn spawn(config: DriverConfig, events_tx: mpsc::UnboundedSender<DriverEvent>) -> Self {
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let name = config.name.clone();
crate::spawn::spawn_supervised(name, config.run(cmd_rx, events_tx));
Self { tx: cmd_tx }
}
}
struct ProvisionRecord {
cp_number: u16,
current: [u8; 8],
next: [u8; 8],
access_criteria: Option<Vec<u8>>,
}
struct Liveness {
last_activity: Instant,
probe_sent_at: Option<Instant>,
}
impl Liveness {
fn new() -> Self {
Self {
last_activity: Instant::now(),
probe_sent_at: None,
}
}
fn on_activity(&mut self) {
self.last_activity = Instant::now();
self.probe_sent_at = None;
}
fn deadline(&self, idle_probe_interval: Duration, response_timeout: Duration) -> Instant {
match self.probe_sent_at {
None => self.last_activity + idle_probe_interval,
Some(sent_at) => sent_at + response_timeout,
}
}
}
async fn run_session(
config: &DriverConfig,
session: &mut EcmgSession,
cmd_rx: &mut mpsc::UnboundedReceiver<DriverCommand>,
events_tx: &mpsc::UnboundedSender<DriverEvent>,
known_streams: &mut Vec<(u16, u16)>,
last_provision: &mut HashMap<u16, ProvisionRecord>,
) {
let mut liveness = Liveness::new();
loop {
let idle_deadline = liveness.deadline(config.idle_probe_interval, config.response_timeout);
let keep_running = tokio::select! {
command = cmd_rx.recv() => {
handle_command(command, config, session, known_streams, last_provision, events_tx).await
}
event = session.read_event() => {
handle_read_event(event, config, session, last_provision, events_tx, &mut liveness)
}
() = tokio::time::sleep_until(idle_deadline) => {
handle_idle_probe(config, session, &mut liveness, events_tx).await
}
};
if !keep_running {
return;
}
}
}
async fn handle_command(
command: Option<DriverCommand>,
config: &DriverConfig,
session: &mut EcmgSession,
known_streams: &mut Vec<(u16, u16)>,
last_provision: &mut HashMap<u16, ProvisionRecord>,
events_tx: &mpsc::UnboundedSender<DriverEvent>,
) -> bool {
match command {
None => {
if let Err(error) = session.close_channel().await {
tracing::warn!(
name = %config.name,
error = %error,
"failed to send CHANNEL_CLOSE"
);
}
false
}
Some(DriverCommand::RemoveStream { stream_id }) => {
known_streams.retain(|(id, _)| *id != stream_id);
last_provision.remove(&stream_id);
if let Err(error) = session.close_stream(stream_id).await {
tracing::warn!(
name = %config.name,
stream_id,
error = %error,
"failed to send STREAM_CLOSE_REQUEST"
);
}
true
}
Some(DriverCommand::AddStream {
stream_id,
nominal_cp_duration,
reply,
}) => {
let result = session.add_stream(stream_id, nominal_cp_duration).await;
match result {
Ok(()) => {
known_streams.push((stream_id, nominal_cp_duration));
let _ = reply.send(Ok(()));
true
}
Err(error) if error.is_stream_error() => {
tracing::warn!(
name = %config.name,
stream_id,
error = %error,
"STREAM_SETUP rejected"
);
let _ = reply.send(Err(DriverError::Session(error)));
true
}
Err(error) => {
tracing::warn!(
name = %config.name,
stream_id,
error = %error,
"failed to add stream"
);
let _ = reply.send(Err(DriverError::Session(error)));
false
}
}
}
Some(DriverCommand::ProvisionCw {
stream_id,
cp_number,
current,
next,
access_criteria,
}) => {
last_provision.insert(
stream_id,
ProvisionRecord {
cp_number,
current,
next,
access_criteria: access_criteria.clone(),
},
);
if let Err(error) = session
.send_cw_provision_to(
stream_id,
cp_number,
¤t,
&next,
access_criteria.as_deref(),
)
.await
{
tracing::warn!(
name = %config.name,
stream_id,
error = %error,
"failed to send CW_PROVISION"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: None,
info: Some(error.to_string()),
}));
return false;
}
true
}
}
}
fn handle_read_event(
event: Result<EcmgEvent, SessionError>,
config: &DriverConfig,
session: &EcmgSession,
last_provision: &HashMap<u16, ProvisionRecord>,
events_tx: &mpsc::UnboundedSender<DriverEvent>,
liveness: &mut Liveness,
) -> bool {
if event.is_ok() {
liveness.on_activity();
}
match event {
Ok(EcmgEvent::Ecm(ecm)) => {
let Some(stream_id) = ecm.stream_id() else {
tracing::warn!(
name = %config.name,
"ignoring ECM_RESPONSE without stream_id"
);
return true;
};
let cp_number = ecm.cp_number();
if let Some(cp_number) = cp_number
&& last_provision
.get(&stream_id)
.map(|record| record.cp_number)
!= Some(cp_number)
{
tracing::warn!(
name = %config.name,
stream_id,
cp_number,
"dropping ECM_RESPONSE for a past crypto period"
);
let _ = events_tx.send(DriverEvent::StaleEcm { stream_id });
return true;
}
let format = session.section_ts_pkt_flag();
let _ = events_tx.send(DriverEvent::Ecm {
stream_id,
cp_number,
format,
data: Bytes::from(ecm.into_datagram()),
});
true
}
Ok(EcmgEvent::ChannelError { status, info }) => {
tracing::error!(
name = %config.name,
status = ?status,
info = ?info,
"ECMG CHANNEL_ERROR"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: status,
info,
}));
false
}
Ok(EcmgEvent::StreamError {
stream_id,
status,
info,
}) => {
tracing::error!(
name = %config.name,
stream_id = ?stream_id,
status = ?status,
info = ?info,
"ECMG STREAM_ERROR"
);
true
}
Ok(EcmgEvent::Message) => true,
Err(error) => {
tracing::warn!(
name = %config.name,
error = %error,
"ECMG session error"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: None,
info: Some(error.to_string()),
}));
false
}
}
}
async fn handle_idle_probe(
config: &DriverConfig,
session: &mut EcmgSession,
liveness: &mut Liveness,
events_tx: &mpsc::UnboundedSender<DriverEvent>,
) -> bool {
if liveness.probe_sent_at.is_some() {
tracing::warn!(
name = %config.name,
timeout = ?config.response_timeout,
"no reply to idle-probe CHANNEL_TEST, the connection is dead"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: None,
info: Some("half-open connection: no response to idle-probe CHANNEL_TEST".to_owned()),
}));
return false;
}
if let Err(error) = session.send_channel_test().await {
tracing::warn!(
name = %config.name,
error = %error,
"failed to send idle-probe CHANNEL_TEST"
);
let _ = events_tx.send(DriverEvent::State(DriverState::Error {
code: None,
info: Some(error.to_string()),
}));
return false;
}
liveness.probe_sent_at = Some(Instant::now());
true
}