1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use std::{
collections::VecDeque,
fmt,
time::Duration,
};
use tokio::net::TcpStream;
use crate::{
ecmg::message::{
self,
ChannelParams,
Ecm,
ParseError,
SectionTsPktFlag,
},
messages::{
RawSimulcryptMessage,
ReadMessageError,
ecmg::{
ECMG_MSG_CHANNEL_CLOSE,
ECMG_MSG_CHANNEL_ERROR,
ECMG_MSG_CHANNEL_STATUS,
ECMG_MSG_CHANNEL_TEST,
ECMG_MSG_ECM_RESPONSE,
ECMG_MSG_STREAM_CLOSE_REQUEST,
ECMG_MSG_STREAM_CLOSE_RESPONSE,
ECMG_MSG_STREAM_ERROR,
ECMG_MSG_STREAM_STATUS,
ECMG_MSG_STREAM_TEST,
ECMG_VAR_CHANNEL_ID,
ECMG_VAR_ERROR_INFO,
ECMG_VAR_ERROR_STATUS,
ECMG_VAR_STREAM_ID,
},
},
};
/// One ECMG connection: the handshake of the channel and its streams is done, `CW_PROVISION`
/// can be sent and events read.
pub struct EcmgSession {
socket: TcpStream,
/// CAS name for logs.
name: String,
channel_id: u16,
streams: Vec<Stream>,
section_ts_pkt_flag: SectionTsPktFlag,
channel_params: ChannelParams,
/// Timeout only for awaiting a specific reply (handshake, `add_stream`). The `read_event`
/// runtime loop reads without a timeout - silence on the channel between ECMs is a normal
/// state, not a lost connection.
response_timeout: Duration,
pending_events: VecDeque<EcmgEvent>,
}
/// A stream the ECMG accepted on this session.
struct Stream {
stream_id: u16,
nominal_cp_duration: u16,
}
/// Event received from the ECMG session runtime loop.
#[derive(Debug)]
pub enum EcmgEvent {
/// Decoded `ECM_RESPONSE`.
Ecm(Ecm),
/// The ECMG sent `CHANNEL_ERROR`.
ChannelError {
/// Error code, if present.
status: Option<u16>,
/// Error description, if present.
info: Option<String>,
},
/// The ECMG sent `STREAM_ERROR`.
StreamError {
/// Stream the error refers to, if present.
stream_id: Option<u16>,
/// Error code, if present.
status: Option<u16>,
/// Error description, if present.
info: Option<String>,
},
/// Message of an unknown type, ignored apart from proving the connection is alive.
Message,
}
#[derive(Clone, Copy, Debug)]
enum SessionPhase {
EcmResponse,
ChannelHandshake,
StreamHandshake,
Runtime,
}
impl fmt::Display for SessionPhase {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match self {
Self::EcmResponse => "ECM response",
Self::ChannelHandshake => "channel handshake",
Self::StreamHandshake => "stream handshake",
Self::Runtime => "runtime",
};
f.write_str(text)
}
}
impl EcmgSession {
/// Runs the handshake of the channel and all its streams with the given reply timeout. An
/// ECMG rejection of `STREAM_SETUP` for a specific stream (`STREAM_ERROR`) does not abort the
/// handshake of the others - that stream is simply left out of the session, the channel and
/// other streams are unaffected (see [`SessionError::is_stream_error`]).
///
/// # Errors
///
/// Returns `Err` if the socket returned an I/O error, the reply could not be parsed/decoded,
/// the ECMG returned `CHANNEL_ERROR`, or no reply arrived within `response_timeout`.
pub async fn open(
socket: TcpStream,
channel_id: u16,
super_cas_id: u32,
streams: &[(u16, u16)],
name: impl Into<String>,
response_timeout: Duration,
) -> Result<Self, SessionError> {
let mut session = Self {
socket,
name: name.into(),
channel_id,
streams: Vec::new(),
section_ts_pkt_flag: SectionTsPktFlag::DEFAULT,
channel_params: ChannelParams::default(),
response_timeout,
pending_events: VecDeque::new(),
};
let (section_ts_pkt_flag, channel_params) = session.channel_handshake(super_cas_id).await?;
session.section_ts_pkt_flag = section_ts_pkt_flag;
session.channel_params = channel_params;
for &(stream_id, nominal_cp_duration) in streams {
if let Err(error) = session.add_stream(stream_id, nominal_cp_duration).await {
if error.is_stream_error() {
tracing::warn!(
name = %session.name,
stream_id,
error = %error,
"STREAM_SETUP rejected, the stream stays unavailable"
);
continue;
}
return Err(error);
}
}
Ok(session)
}
/// Datagram format negotiated in `CHANNEL_STATUS`.
pub fn section_ts_pkt_flag(&self) -> SectionTsPktFlag {
self.section_ts_pkt_flag
}
/// Other parameters negotiated in `CHANNEL_STATUS`.
pub fn channel_params(&self) -> ChannelParams {
self.channel_params
}
/// `stream_id` of all streams currently known to the session.
pub fn stream_ids(&self) -> impl Iterator<Item = u16> + '_ {
self.streams.iter().map(|stream| stream.stream_id)
}
/// Runs `STREAM_SETUP/STREAM_STATUS` for a new stream on an already open channel (adding a
/// stream on a live connection).
///
/// # Errors
///
/// Returns `Err` if the socket returned an I/O error, the reply could not be parsed, the ECMG
/// returned `CHANNEL_ERROR`/`STREAM_ERROR`, or no reply arrived within `response_timeout`.
pub async fn add_stream(
&mut self,
stream_id: u16,
nominal_cp_duration: u16,
) -> Result<(), SessionError> {
self.stream_handshake(stream_id, nominal_cp_duration, self.section_ts_pkt_flag)
.await?;
self.streams.push(Stream {
stream_id,
nominal_cp_duration,
});
Ok(())
}
/// Sends `CHANNEL_TEST` without waiting for the reply - used to catch a half-open connection
/// (TCP looks established, but nothing flows in either direction) during idle time between
/// ECMs, when `read_event` deliberately has no timeout. The `CHANNEL_STATUS` reply (like any
/// other message) arrives as a regular runtime event through `read_event` - receiving it is
/// the confirmation that the channel is alive.
///
/// # Errors
///
/// Returns `Err` on an I/O error.
pub async fn send_channel_test(&mut self) -> Result<(), SessionError> {
let mut message = RawSimulcryptMessage::new(ECMG_MSG_CHANNEL_TEST);
message.set_u16(ECMG_VAR_CHANNEL_ID, self.channel_id);
message.write_to(&mut self.socket).await?;
Ok(())
}
/// Sends `STREAM_CLOSE_REQUEST` for one stream and stops tracking it - used for a graceful
/// close of one stream while the channel keeps serving the others. Does not wait for
/// `STREAM_CLOSE_RESPONSE`: the reply, if any, is silently accepted as a regular runtime event
/// through `read_event`.
///
/// # Errors
///
/// Returns `Err` on an I/O error.
pub async fn close_stream(&mut self, stream_id: u16) -> Result<(), SessionError> {
let mut message = RawSimulcryptMessage::new(ECMG_MSG_STREAM_CLOSE_REQUEST);
message.set_u16(ECMG_VAR_CHANNEL_ID, self.channel_id);
message.set_u16(ECMG_VAR_STREAM_ID, stream_id);
message.write_to(&mut self.socket).await?;
self.streams.retain(|stream| stream.stream_id != stream_id);
Ok(())
}
/// Sends `CHANNEL_CLOSE` before a graceful session shutdown (the whole channel closes, the TCP
/// connection is dropped right after).
///
/// # Errors
///
/// Returns `Err` on an I/O error.
pub async fn close_channel(&mut self) -> Result<(), SessionError> {
let mut message = RawSimulcryptMessage::new(ECMG_MSG_CHANNEL_CLOSE);
message.set_u16(ECMG_VAR_CHANNEL_ID, self.channel_id);
message.write_to(&mut self.socket).await?;
Ok(())
}
/// Sends `CW_PROVISION` to one specific stream of the channel.
///
/// # Errors
///
/// Returns `Err` if `stream_id` is not registered on this channel, `access_criteria` does not
/// fit into the message, or the socket write failed with an I/O error.
pub async fn send_cw_provision_to(
&mut self,
stream_id: u16,
cp_number: u16,
cw_current: &[u8; 8],
cw_next: &[u8; 8],
access_criteria: Option<&[u8]>,
) -> Result<(), SessionError> {
let stream = self
.streams
.iter()
.find(|stream| stream.stream_id == stream_id)
.ok_or(SessionError::UnknownStreamId { stream_id })?;
message::cw_provision(
self.channel_id,
stream_id,
cp_number,
stream.nominal_cp_duration,
cw_current,
cw_next,
access_criteria,
)
.write_to(&mut self.socket)
.await?;
Ok(())
}
/// Waits for the next runtime loop event: an ECM, a channel/stream error or an unrecognized
/// message. Blocks without a timeout - silence between ECMs for a whole crypto period is
/// normal.
///
/// `CHANNEL_ERROR`/`STREAM_ERROR` from the ECMG are not Rust-level errors here - they are
/// returned as `Ok(EcmgEvent::ChannelError { .. })`/`Ok(EcmgEvent::StreamError { .. })`, so the
/// caller can keep reading events of the same runtime loop.
///
/// # Errors
///
/// Returns `Err` if the socket returned an I/O error or the message read could not be
/// parsed/decoded.
pub async fn read_event(&mut self) -> Result<EcmgEvent, SessionError> {
if let Some(event) = self.pending_events.pop_front() {
return Ok(event);
}
loop {
let response = self
.read_message_for_events(self.section_ts_pkt_flag, SessionPhase::Runtime)
.await?;
match response.message_type {
ECMG_MSG_ECM_RESPONSE => {
if !self.has_known_stream_id(&response, SessionPhase::EcmResponse) {
continue;
}
let ecm = Ecm::try_from(response).map_err(SessionError::Decode)?;
return Ok(EcmgEvent::Ecm(ecm));
}
ECMG_MSG_CHANNEL_ERROR => {
return Ok(EcmgEvent::ChannelError {
status: response.get_u16(ECMG_VAR_ERROR_STATUS),
info: Self::error_info(&response),
});
}
ECMG_MSG_STREAM_ERROR => {
return Ok(EcmgEvent::StreamError {
stream_id: response.get_u16(ECMG_VAR_STREAM_ID),
status: response.get_u16(ECMG_VAR_ERROR_STATUS),
info: Self::error_info(&response),
});
}
// Reply to our own close_stream - nothing to wait for or check here, just keep
// it from falling through to EcmgEvent::Message as an unrecognized message.
ECMG_MSG_STREAM_CLOSE_RESPONSE => continue,
_ => return Ok(EcmgEvent::Message),
}
}
}
fn has_known_stream_id(&self, response: &RawSimulcryptMessage, phase: SessionPhase) -> bool {
let Some(stream_id) = response.get_u16(ECMG_VAR_STREAM_ID) else {
tracing::warn!(
name = %self.name,
%phase,
message_type = %format_args!("0x{:04x}", response.message_type),
"ignoring message without stream_id"
);
return false;
};
if self
.streams
.iter()
.any(|stream| stream.stream_id == stream_id)
{
return true;
}
tracing::warn!(
name = %self.name,
%phase,
stream_id,
message_type = %format_args!("0x{:04x}", response.message_type),
"ignoring message for an unknown stream_id"
);
false
}
fn is_expected_stream_id(
&self,
response: &RawSimulcryptMessage,
expected_stream_id: u16,
phase: SessionPhase,
) -> bool {
let Some(response_stream_id) = response.get_u16(ECMG_VAR_STREAM_ID) else {
tracing::warn!(
name = %self.name,
%phase,
message_type = %format_args!("0x{:04x}", response.message_type),
"ignoring message without stream_id"
);
return false;
};
if response_stream_id == expected_stream_id {
return true;
}
tracing::info!(
name = %self.name,
%phase,
stream_id = response_stream_id,
expected_stream_id,
message_type = %format_args!("0x{:04x}", response.message_type),
"ignoring message for an unexpected stream_id"
);
false
}
async fn channel_handshake(
&mut self,
super_cas_id: u32,
) -> Result<(SectionTsPktFlag, ChannelParams), SessionError> {
message::channel_setup(self.channel_id, super_cas_id)
.write_to(&mut self.socket)
.await?;
let response = self
.wait_for_message(
ECMG_MSG_CHANNEL_STATUS,
SectionTsPktFlag::DEFAULT,
SessionPhase::ChannelHandshake,
)
.await?;
let (section_ts_pkt_flag, params) =
message::parse_channel_status(&response).map_err(SessionError::Decode)?;
tracing::info!(
name = %self.name,
%section_ts_pkt_flag,
"received CHANNEL_STATUS"
);
Ok((section_ts_pkt_flag, params))
}
async fn stream_handshake(
&mut self,
stream_id: u16,
nominal_cp_duration: u16,
section_ts_pkt_flag: SectionTsPktFlag,
) -> Result<(), SessionError> {
message::stream_setup(self.channel_id, stream_id, nominal_cp_duration)
.write_to(&mut self.socket)
.await?;
loop {
let response = self
.wait_for_message(
ECMG_MSG_STREAM_STATUS,
section_ts_pkt_flag,
SessionPhase::StreamHandshake,
)
.await?;
if !self.is_expected_stream_id(&response, stream_id, SessionPhase::StreamHandshake) {
continue;
}
break;
}
tracing::info!(
name = %self.name,
stream_id,
"received STREAM_STATUS"
);
Ok(())
}
async fn handle_channel_test(
&mut self,
section_ts_pkt_flag: SectionTsPktFlag,
phase: SessionPhase,
) -> Result<(), SessionError> {
tracing::trace!(
name = %self.name,
%phase,
"received CHANNEL_TEST, replying with CHANNEL_STATUS"
);
message::channel_status(self.channel_id, section_ts_pkt_flag)
.write_to(&mut self.socket)
.await?;
Ok(())
}
async fn handle_stream_test(
&mut self,
request: &RawSimulcryptMessage,
phase: SessionPhase,
) -> Result<(), SessionError> {
let Some(stream_id) = request.get_u16(ECMG_VAR_STREAM_ID) else {
tracing::warn!(
name = %self.name,
%phase,
"received STREAM_TEST without stream_id"
);
return Ok(());
};
tracing::trace!(
name = %self.name,
%phase,
stream_id,
"received STREAM_TEST, replying with STREAM_STATUS"
);
let mut response = RawSimulcryptMessage::new(ECMG_MSG_STREAM_STATUS);
response.set_u16(ECMG_VAR_CHANNEL_ID, self.channel_id);
response.set_u16(ECMG_VAR_STREAM_ID, stream_id);
response.write_to(&mut self.socket).await?;
Ok(())
}
/// Waits for a reply during the handshake/`add_stream`: the timeout is armed, silence means a
/// lost connection.
async fn read_message(
&mut self,
section_ts_pkt_flag: SectionTsPktFlag,
phase: SessionPhase,
) -> Result<RawSimulcryptMessage, SessionError> {
loop {
let response = Self::read_raw(&mut self.socket, Some(self.response_timeout)).await?;
match response.message_type {
ECMG_MSG_CHANNEL_TEST => {
self.handle_channel_test(section_ts_pkt_flag, phase).await?;
continue;
}
ECMG_MSG_STREAM_TEST => {
self.handle_stream_test(&response, phase).await?;
continue;
}
ECMG_MSG_CHANNEL_ERROR => {
return Err(SessionError::ChannelError {
status: response.get_u16(ECMG_VAR_ERROR_STATUS),
info: Self::error_info(&response),
});
}
ECMG_MSG_STREAM_ERROR => {
return Err(SessionError::StreamError {
stream_id: response.get_u16(ECMG_VAR_STREAM_ID),
status: response.get_u16(ECMG_VAR_ERROR_STATUS),
info: Self::error_info(&response),
});
}
_ => {}
}
return Ok(response);
}
}
/// Waits for the next runtime message without a timeout: silence between ECMs for a whole
/// crypto period is a normal state, not a lost connection.
async fn read_message_for_events(
&mut self,
section_ts_pkt_flag: SectionTsPktFlag,
phase: SessionPhase,
) -> Result<RawSimulcryptMessage, SessionError> {
loop {
let response = Self::read_raw(&mut self.socket, None).await?;
match response.message_type {
ECMG_MSG_CHANNEL_TEST => {
self.handle_channel_test(section_ts_pkt_flag, phase).await?;
}
ECMG_MSG_STREAM_TEST => {
self.handle_stream_test(&response, phase).await?;
}
_ => return Ok(response),
}
}
}
fn error_info(response: &RawSimulcryptMessage) -> Option<String> {
response
.find_var(ECMG_VAR_ERROR_INFO)
.map(|var| String::from_utf8_lossy(&var.value).trim().to_owned())
}
async fn read_raw(
socket: &mut TcpStream,
timeout: Option<Duration>,
) -> Result<RawSimulcryptMessage, SessionError> {
let msg = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, RawSimulcryptMessage::read_from(socket)).await??
}
None => RawSimulcryptMessage::read_from(socket).await?,
};
Ok(msg)
}
async fn wait_for_message(
&mut self,
expected_message_type: u16,
section_ts_pkt_flag: SectionTsPktFlag,
phase: SessionPhase,
) -> Result<RawSimulcryptMessage, SessionError> {
loop {
let response = self.read_message(section_ts_pkt_flag, phase).await?;
if response.message_type == expected_message_type {
return Ok(response);
}
tracing::info!(
name = %self.name,
%phase,
message_type = %format_args!("0x{:04x}", response.message_type),
"ignoring message"
);
}
}
}
/// ECMG session error: handshake, `CW_PROVISION` send or runtime loop.
#[derive(Debug, thiserror::Error)]
pub enum SessionError {
/// Socket I/O error.
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
/// Failed to parse a raw `SimulCrypt` message.
#[error("failed to parse SimulCrypt message: {0}")]
MessageParse(#[source] crate::messages::RawSimulcryptMessageError),
/// Failed to decode the message into a typed struct.
#[error("failed to decode SimulCrypt message: {0}")]
Decode(#[source] ParseError),
/// The ECMG returned `CHANNEL_ERROR`.
#[error("ECMG CHANNEL_ERROR: status={status:?} info={info:?}")]
ChannelError {
/// Error code, if present.
status: Option<u16>,
/// Error description, if present.
info: Option<String>,
},
/// The ECMG returned `STREAM_ERROR`.
#[error("ECMG STREAM_ERROR: stream_id={stream_id:?} status={status:?} info={info:?}")]
StreamError {
/// Stream the error refers to, if present.
stream_id: Option<u16>,
/// Error code, if present.
status: Option<u16>,
/// Error description, if present.
info: Option<String>,
},
/// Reply timeout expired.
#[error("timeout while reading from ECMG")]
Timeout(#[from] tokio::time::error::Elapsed),
/// The requested `stream_id` is not registered on this channel.
#[error("unknown stream_id={stream_id} on this channel")]
UnknownStreamId {
/// The requested `stream_id` that was not found.
stream_id: u16,
},
}
impl SessionError {
/// `true` if this is a single-stream rejection (the ECMG returned `STREAM_ERROR` on
/// `STREAM_SETUP`). Unlike I/O, timeout or decoding errors, such a rejection does not mean
/// the session/channel itself is broken - the other streams of the channel are unaffected.
#[must_use]
pub fn is_stream_error(&self) -> bool {
matches!(self, SessionError::StreamError { .. })
}
}
impl From<ReadMessageError> for SessionError {
fn from(error: ReadMessageError) -> Self {
match error {
ReadMessageError::Io(error) => SessionError::Io(error),
ReadMessageError::Parse(error) => SessionError::MessageParse(error),
}
}
}