feat(core): add safe Rust wire session core

This commit is contained in:
sechmachine
2026-08-12 14:03:53 +07:00
parent 12ad2a4daa
commit 48ee082c0b
15 changed files with 2115 additions and 0 deletions
+67
View File
@@ -0,0 +1,67 @@
use std::fmt;
/// Stable, provider-free failures returned by the safe core.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CoreError {
InvalidArgument,
AuthorityRejected,
Expired,
QueueFull,
Cancelled,
Truncated,
UnsupportedVersion,
UnknownChannel,
Fragment,
FragmentLimit,
Length,
LengthMismatch,
Magic,
Kind,
Reserved,
Utf8,
Field,
Direction,
Type,
UnsupportedFeature,
ConflictingDuplicate,
}
impl CoreError {
/// Returns a stable, provider-free machine code.
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::InvalidArgument => "invalid_argument",
Self::AuthorityRejected => "authority_rejected",
Self::Expired => "expired",
Self::QueueFull => "queue_full",
Self::Cancelled => "cancelled",
Self::Truncated => "truncated",
Self::UnsupportedVersion => "unsupported_version",
Self::UnknownChannel => "unknown_channel",
Self::Fragment => "fragment",
Self::FragmentLimit => "fragment_limit",
Self::Length => "length",
Self::LengthMismatch => "length_mismatch",
Self::Magic => "magic",
Self::Kind => "kind",
Self::Reserved => "reserved",
Self::Utf8 => "utf8",
Self::Field => "field",
Self::Direction => "direction",
Self::Type => "type",
Self::UnsupportedFeature => "unsupported_feature",
Self::ConflictingDuplicate => "conflicting_duplicate",
}
}
}
impl fmt::Display for CoreError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.code())
}
}
impl std::error::Error for CoreError {}
pub type Result<T> = std::result::Result<T, CoreError>;
+418
View File
@@ -0,0 +1,418 @@
use crate::error::{CoreError, Result};
const INPUT_HEADER: usize = 6;
const FEEDBACK_HEADER: usize = 8;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ControllerState {
pub controller: u8,
pub active_mask: u16,
pub button_flags: u16,
pub left_trigger: u8,
pub right_trigger: u8,
pub left_x: i16,
pub left_y: i16,
pub right_x: i16,
pub right_y: i16,
pub extra_button_flags: u16,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InputEvent {
Keyboard {
pressed: bool,
modifiers: u8,
scancode: u16,
},
MouseButton {
pressed: bool,
button: u8,
},
RelativeMouse {
delta_x: i16,
delta_y: i16,
},
Text(char),
Controller(ControllerState),
AbsoluteMouse {
x: u16,
y: u16,
viewport_width: u16,
viewport_height: u16,
},
Scroll {
vertical_delta: i16,
horizontal_delta: i16,
},
}
fn feature(features: &[&str], wanted: &str) -> Result<()> {
features
.contains(&wanted)
.then_some(())
.ok_or(CoreError::UnsupportedFeature)
}
fn state(value: u8) -> Result<bool> {
match value {
0 => Ok(false),
1 => Ok(true),
_ => Err(CoreError::Field),
}
}
fn i16_at(bytes: &[u8], offset: usize) -> i16 {
i16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
fn u16_at(bytes: &[u8], offset: usize) -> u16 {
u16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
/// Decodes one bounded VGI1 input envelope.
///
/// # Errors
///
/// Returns a stable protocol error for malformed bytes or a missing negotiated feature.
pub fn decode_input(bytes: &[u8], features: &[&str]) -> Result<InputEvent> {
if bytes.len() < INPUT_HEADER {
return Err(CoreError::Truncated);
}
if &bytes[..4] != b"VGI1" {
return Err(CoreError::Magic);
}
let body_length = usize::from(bytes[5]);
if bytes.len() != INPUT_HEADER + body_length {
return Err(CoreError::Length);
}
let body = &bytes[INPUT_HEADER..];
match bytes[4] {
0x01 if body.len() == 4 => {
let scancode = u16_at(body, 2);
if scancode == 0 {
return Err(CoreError::Field);
}
Ok(InputEvent::Keyboard {
pressed: state(body[0])?,
modifiers: body[1],
scancode,
})
}
0x02 if body.len() == 3 => {
if !(1..=5).contains(&body[1]) {
return Err(CoreError::Field);
}
if body[2] != 0 {
return Err(CoreError::Reserved);
}
Ok(InputEvent::MouseButton {
pressed: state(body[0])?,
button: body[1],
})
}
0x03 if body.len() == 4 => Ok(InputEvent::RelativeMouse {
delta_x: i16_at(body, 0),
delta_y: i16_at(body, 2),
}),
0x04 if (1..=4).contains(&body.len()) => {
let text = std::str::from_utf8(body).map_err(|_| CoreError::Utf8)?;
let mut chars = text.chars();
let value = chars.next().ok_or(CoreError::Utf8)?;
if chars.next().is_some() {
return Err(CoreError::Utf8);
}
Ok(InputEvent::Text(value))
}
0x05 if body.len() == 17 => {
if body[0] > 15 {
return Err(CoreError::Field);
}
Ok(InputEvent::Controller(ControllerState {
controller: body[0],
active_mask: u16_at(body, 1),
button_flags: u16_at(body, 3),
left_trigger: body[5],
right_trigger: body[6],
left_x: i16_at(body, 7),
left_y: i16_at(body, 9),
right_x: i16_at(body, 11),
right_y: i16_at(body, 13),
extra_button_flags: u16_at(body, 15),
}))
}
0x06 if body.len() == 8 => {
feature(features, "input.absolute.v1")?;
let x = u16_at(body, 0);
let y = u16_at(body, 2);
let viewport_width = u16_at(body, 4);
let viewport_height = u16_at(body, 6);
if viewport_width == 0
|| viewport_height == 0
|| x >= viewport_width
|| y >= viewport_height
{
return Err(CoreError::Field);
}
Ok(InputEvent::AbsoluteMouse {
x,
y,
viewport_width,
viewport_height,
})
}
0x07 if body.len() == 4 => {
feature(features, "input.scroll.v1")?;
Ok(InputEvent::Scroll {
vertical_delta: i16_at(body, 0),
horizontal_delta: i16_at(body, 2),
})
}
0x01..=0x07 => Err(CoreError::Length),
_ => Err(CoreError::Kind),
}
}
fn push_i16(output: &mut Vec<u8>, value: i16) {
output.extend_from_slice(&value.to_be_bytes());
}
fn push_u16(output: &mut Vec<u8>, value: u16) {
output.extend_from_slice(&value.to_be_bytes());
}
/// Encodes one bounded VGI1 input envelope.
///
/// # Errors
///
/// Returns a stable protocol error for invalid fields or a missing negotiated feature.
pub fn encode_input(event: &InputEvent, features: &[&str]) -> Result<Vec<u8>> {
let (kind, body) = match event {
InputEvent::Keyboard {
pressed,
modifiers,
scancode,
} => {
if *scancode == 0 {
return Err(CoreError::Field);
}
let mut body = vec![u8::from(*pressed), *modifiers];
push_u16(&mut body, *scancode);
(0x01, body)
}
InputEvent::MouseButton { pressed, button } => {
if !(1..=5).contains(button) {
return Err(CoreError::Field);
}
(0x02, vec![u8::from(*pressed), *button, 0])
}
InputEvent::RelativeMouse { delta_x, delta_y } => {
let mut body = Vec::with_capacity(4);
push_i16(&mut body, *delta_x);
push_i16(&mut body, *delta_y);
(0x03, body)
}
InputEvent::Text(value) => {
let mut bytes = [0_u8; 4];
(0x04, value.encode_utf8(&mut bytes).as_bytes().to_vec())
}
InputEvent::Controller(controller) => {
if controller.controller > 15 {
return Err(CoreError::Field);
}
let mut body = vec![controller.controller];
push_u16(&mut body, controller.active_mask);
push_u16(&mut body, controller.button_flags);
body.extend_from_slice(&[controller.left_trigger, controller.right_trigger]);
push_i16(&mut body, controller.left_x);
push_i16(&mut body, controller.left_y);
push_i16(&mut body, controller.right_x);
push_i16(&mut body, controller.right_y);
push_u16(&mut body, controller.extra_button_flags);
(0x05, body)
}
InputEvent::AbsoluteMouse {
x,
y,
viewport_width,
viewport_height,
} => {
feature(features, "input.absolute.v1")?;
if *viewport_width == 0
|| *viewport_height == 0
|| x >= viewport_width
|| y >= viewport_height
{
return Err(CoreError::Field);
}
let mut body = Vec::with_capacity(8);
push_u16(&mut body, *x);
push_u16(&mut body, *y);
push_u16(&mut body, *viewport_width);
push_u16(&mut body, *viewport_height);
(0x06, body)
}
InputEvent::Scroll {
vertical_delta,
horizontal_delta,
} => {
feature(features, "input.scroll.v1")?;
let mut body = Vec::with_capacity(4);
push_i16(&mut body, *vertical_delta);
push_i16(&mut body, *horizontal_delta);
(0x07, body)
}
};
let mut output = Vec::with_capacity(INPUT_HEADER + body.len());
output.extend_from_slice(b"VGI1");
output.push(kind);
output.push(u8::try_from(body.len()).map_err(|_| CoreError::Length)?);
output.extend_from_slice(&body);
Ok(output)
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FecStatus {
pub frame_index: u32,
pub highest_received_sequence: u16,
pub next_contiguous_sequence: u16,
pub missing_before_highest: u16,
pub total_data_packets: u16,
pub total_parity_packets: u16,
pub received_data_packets: u16,
pub received_parity_packets: u16,
pub fec_percentage: u8,
pub multi_fec_block_index: u8,
pub multi_fec_block_count: u8,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FeedbackEvent {
IdrRequest,
Fec(FecStatus),
TerminalReceipt,
Termination {
exit_code: u32,
},
Rumble {
controller: u8,
low_frequency: u16,
high_frequency: u16,
},
Hdr {
enabled: bool,
},
}
fn u32_at(bytes: &[u8], offset: usize) -> u32 {
u32::from_be_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
])
}
/// Decodes one bounded VGF1 feedback envelope.
///
/// # Errors
///
/// Returns a stable protocol error for malformed bytes, direction, type, or size.
pub fn decode_feedback(bytes: &[u8]) -> Result<FeedbackEvent> {
if bytes.len() < FEEDBACK_HEADER {
return Err(CoreError::Truncated);
}
if &bytes[..4] != b"VGF1" {
return Err(CoreError::Magic);
}
let direction = bytes[4];
if direction > 1 {
return Err(CoreError::Direction);
}
let body_length = usize::from(u16_at(bytes, 6));
if bytes.len() != FEEDBACK_HEADER + body_length {
return Err(CoreError::Length);
}
let body = &bytes[FEEDBACK_HEADER..];
match (direction, bytes[5]) {
(0, 0x01) if body.is_empty() => Ok(FeedbackEvent::IdrRequest),
(0, 0x02) if body.len() == 21 => Ok(FeedbackEvent::Fec(FecStatus {
frame_index: u32_at(body, 0),
highest_received_sequence: u16_at(body, 4),
next_contiguous_sequence: u16_at(body, 6),
missing_before_highest: u16_at(body, 8),
total_data_packets: u16_at(body, 10),
total_parity_packets: u16_at(body, 12),
received_data_packets: u16_at(body, 14),
received_parity_packets: u16_at(body, 16),
fec_percentage: body[18],
multi_fec_block_index: body[19],
multi_fec_block_count: body[20],
})),
(0, 0x03) if body.is_empty() => Ok(FeedbackEvent::TerminalReceipt),
(1, 0x10) if body.len() == 4 => Ok(FeedbackEvent::Termination {
exit_code: u32_at(body, 0),
}),
(1, 0x11) if body.len() == 5 => Ok(FeedbackEvent::Rumble {
controller: body[0],
low_frequency: u16_at(body, 1),
high_frequency: u16_at(body, 3),
}),
(1, 0x12) if body.len() == 1 && body[0] <= 1 => Ok(FeedbackEvent::Hdr {
enabled: body[0] == 1,
}),
(0, 0x10..=0x12) | (1, 0x01..=0x03) => Err(CoreError::Direction),
(0, 0x01..=0x03) | (1, 0x10..=0x12) => Err(CoreError::Length),
_ => Err(CoreError::Type),
}
}
/// Encodes one bounded VGF1 feedback envelope.
///
/// # Errors
///
/// Returns a stable protocol error if the body size is not representable.
pub fn encode_feedback(event: &FeedbackEvent) -> Result<Vec<u8>> {
let (direction, kind, body) = match event {
FeedbackEvent::IdrRequest => (0, 0x01, Vec::new()),
FeedbackEvent::Fec(status) => {
let mut body = Vec::with_capacity(21);
body.extend_from_slice(&status.frame_index.to_be_bytes());
push_u16(&mut body, status.highest_received_sequence);
push_u16(&mut body, status.next_contiguous_sequence);
push_u16(&mut body, status.missing_before_highest);
push_u16(&mut body, status.total_data_packets);
push_u16(&mut body, status.total_parity_packets);
push_u16(&mut body, status.received_data_packets);
push_u16(&mut body, status.received_parity_packets);
body.extend_from_slice(&[
status.fec_percentage,
status.multi_fec_block_index,
status.multi_fec_block_count,
]);
(0, 0x02, body)
}
FeedbackEvent::TerminalReceipt => (0, 0x03, Vec::new()),
FeedbackEvent::Termination { exit_code } => (1, 0x10, exit_code.to_be_bytes().to_vec()),
FeedbackEvent::Rumble {
controller,
low_frequency,
high_frequency,
} => {
let mut body = vec![*controller];
push_u16(&mut body, *low_frequency);
push_u16(&mut body, *high_frequency);
(1, 0x11, body)
}
FeedbackEvent::Hdr { enabled } => (1, 0x12, vec![u8::from(*enabled)]),
};
let mut output = Vec::with_capacity(FEEDBACK_HEADER + body.len());
output.extend_from_slice(b"VGF1");
output.extend_from_slice(&[direction, kind]);
output.extend_from_slice(
&u16::try_from(body.len())
.map_err(|_| CoreError::Length)?
.to_be_bytes(),
);
output.extend_from_slice(&body);
Ok(output)
}
+18
View File
@@ -0,0 +1,18 @@
#![forbid(unsafe_code, unsafe_op_in_unsafe_fn)]
//! Provider-free wire codecs and bounded session primitives for `VerseVDI` clients.
//!
//! ```
//! use versevdi_core::media::MediaFragment;
//!
//! let fragment = MediaFragment::new_video(1, 2, 0, 1, vec![1, 2, 3])?;
//! let encoded = fragment.encode()?;
//! assert_eq!(MediaFragment::decode(&encoded)?, fragment);
//! # Ok::<(), versevdi_core::error::CoreError>(())
//! ```
pub mod error;
pub mod input;
pub mod media;
pub mod session;
pub mod wire;
+299
View File
@@ -0,0 +1,299 @@
use std::collections::VecDeque;
use crate::error::{CoreError, Result};
pub const DATAGRAM_HEADER_BYTES: usize = 23;
pub const MAX_DATAGRAM_BYTES: usize = 1_200;
pub const MAX_FRAGMENT_PAYLOAD_BYTES: usize = 1_177;
pub const MAX_FRAGMENT_COUNT: u16 = 891;
pub const MAX_COMPLETE_UNIT_BYTES: usize = 1_048_576;
const MAX_INCOMPLETE_UNITS: usize = 4;
const EXPIRY_MILLISECONDS: u64 = 250;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MediaChannel {
Video,
Audio,
}
impl MediaChannel {
const fn wire(self) -> u8 {
match self {
Self::Video => 10,
Self::Audio => 11,
}
}
fn from_wire(value: u8) -> Result<Self> {
match value {
10 => Ok(Self::Video),
11 => Ok(Self::Audio),
_ => Err(CoreError::UnknownChannel),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MediaFragment {
pub channel: MediaChannel,
pub sequence: u32,
pub timestamp_ms: u64,
pub fragment_index: u16,
pub fragment_count: u16,
pub payload: Vec<u8>,
}
impl MediaFragment {
/// Creates a validated video fragment.
///
/// # Errors
///
/// Returns a stable protocol error when fragment or payload bounds are invalid.
pub fn new_video(
sequence: u32,
timestamp_ms: u64,
fragment_index: u16,
fragment_count: u16,
payload: Vec<u8>,
) -> Result<Self> {
let fragment = Self {
channel: MediaChannel::Video,
sequence,
timestamp_ms,
fragment_index,
fragment_count,
payload,
};
fragment.validate()?;
Ok(fragment)
}
/// Creates a validated audio fragment.
///
/// # Errors
///
/// Returns a stable protocol error when fragment or payload bounds are invalid.
pub fn new_audio(
sequence: u32,
timestamp_ms: u64,
fragment_index: u16,
fragment_count: u16,
payload: Vec<u8>,
) -> Result<Self> {
let fragment = Self {
channel: MediaChannel::Audio,
sequence,
timestamp_ms,
fragment_index,
fragment_count,
payload,
};
fragment.validate()?;
Ok(fragment)
}
fn validate(&self) -> Result<()> {
if self.fragment_count == 0 || self.fragment_index >= self.fragment_count {
return Err(CoreError::Fragment);
}
if self.fragment_count > MAX_FRAGMENT_COUNT {
return Err(CoreError::FragmentLimit);
}
if self.payload.len() > MAX_FRAGMENT_PAYLOAD_BYTES {
return Err(CoreError::LengthMismatch);
}
Ok(())
}
/// Decodes one datagram-v2 fragment.
///
/// # Errors
///
/// Returns a stable protocol error for malformed or out-of-bound bytes.
pub fn decode(bytes: &[u8]) -> Result<Self> {
if bytes.len() < DATAGRAM_HEADER_BYTES {
return Err(CoreError::Truncated);
}
if &bytes[..2] != b"VD" {
return Err(CoreError::Magic);
}
if bytes[2] != 2 {
return Err(CoreError::UnsupportedVersion);
}
let channel = MediaChannel::from_wire(bytes[3])?;
if bytes[4] != 0 {
return Err(CoreError::Field);
}
let sequence = u32::from_be_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]);
let timestamp_ms = u64::from_be_bytes([
bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], bytes[16],
]);
let fragment_index = u16::from_be_bytes([bytes[17], bytes[18]]);
let fragment_count = u16::from_be_bytes([bytes[19], bytes[20]]);
let payload_length = usize::from(u16::from_be_bytes([bytes[21], bytes[22]]));
if bytes.len() != DATAGRAM_HEADER_BYTES + payload_length || bytes.len() > MAX_DATAGRAM_BYTES
{
return Err(CoreError::LengthMismatch);
}
let fragment = Self {
channel,
sequence,
timestamp_ms,
fragment_index,
fragment_count,
payload: bytes[DATAGRAM_HEADER_BYTES..].to_vec(),
};
fragment.validate()?;
Ok(fragment)
}
/// Encodes one datagram-v2 fragment.
///
/// # Errors
///
/// Returns a stable protocol error when fragment or payload bounds are invalid.
pub fn encode(&self) -> Result<Vec<u8>> {
self.validate()?;
let mut output = Vec::with_capacity(DATAGRAM_HEADER_BYTES + self.payload.len());
output.extend_from_slice(b"VD");
output.extend_from_slice(&[2, self.channel.wire(), 0]);
output.extend_from_slice(&self.sequence.to_be_bytes());
output.extend_from_slice(&self.timestamp_ms.to_be_bytes());
output.extend_from_slice(&self.fragment_index.to_be_bytes());
output.extend_from_slice(&self.fragment_count.to_be_bytes());
output.extend_from_slice(
&u16::try_from(self.payload.len())
.map_err(|_| CoreError::LengthMismatch)?
.to_be_bytes(),
);
output.extend_from_slice(&self.payload);
Ok(output)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EncodedUnit {
pub channel: MediaChannel,
pub sequence: u32,
pub timestamp_ms: u64,
pub payload: Vec<u8>,
}
#[derive(Debug)]
struct IncompleteUnit {
channel: MediaChannel,
sequence: u32,
timestamp_ms: u64,
fragment_count: u16,
started_at_ms: u64,
total_bytes: usize,
fragments: Vec<Option<Vec<u8>>>,
}
#[derive(Debug, Default)]
pub struct Reassembler {
incomplete: VecDeque<IncompleteUnit>,
evicted_units: u64,
expired_units: u64,
}
impl Reassembler {
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Adds a fragment and returns a complete encoded unit when all fragments arrive.
///
/// # Errors
///
/// Returns a stable protocol error for conflicting fragments or size-bound violations.
pub fn push(&mut self, fragment: MediaFragment, now_ms: u64) -> Result<Option<EncodedUnit>> {
fragment.validate()?;
let before = self.incomplete.len();
self.incomplete
.retain(|unit| now_ms.saturating_sub(unit.started_at_ms) <= EXPIRY_MILLISECONDS);
self.expired_units += u64::try_from(before - self.incomplete.len()).unwrap_or(u64::MAX);
let position = self.incomplete.iter().position(|unit| {
unit.channel == fragment.channel && unit.sequence == fragment.sequence
});
let position = if let Some(position) = position {
position
} else {
if self.incomplete.len() == MAX_INCOMPLETE_UNITS {
self.incomplete.pop_front();
self.evicted_units += 1;
}
self.incomplete.push_back(IncompleteUnit {
channel: fragment.channel,
sequence: fragment.sequence,
timestamp_ms: fragment.timestamp_ms,
fragment_count: fragment.fragment_count,
started_at_ms: now_ms,
total_bytes: 0,
fragments: vec![None; usize::from(fragment.fragment_count)],
});
self.incomplete.len() - 1
};
let unit = &mut self.incomplete[position];
if unit.timestamp_ms != fragment.timestamp_ms
|| unit.fragment_count != fragment.fragment_count
{
self.incomplete.remove(position);
return Err(CoreError::ConflictingDuplicate);
}
let index = usize::from(fragment.fragment_index);
if let Some(existing) = &unit.fragments[index] {
if existing == &fragment.payload {
return Ok(None);
}
self.incomplete.remove(position);
return Err(CoreError::ConflictingDuplicate);
}
let total_bytes = unit
.total_bytes
.checked_add(fragment.payload.len())
.ok_or(CoreError::FragmentLimit)?;
if total_bytes > MAX_COMPLETE_UNIT_BYTES {
self.incomplete.remove(position);
return Err(CoreError::FragmentLimit);
}
unit.total_bytes = total_bytes;
unit.fragments[index] = Some(fragment.payload);
if unit.fragments.iter().any(Option::is_none) {
return Ok(None);
}
let complete = self
.incomplete
.remove(position)
.ok_or(CoreError::InvalidArgument)?;
let mut payload = Vec::with_capacity(complete.total_bytes);
for bytes in complete.fragments {
payload.extend(bytes.ok_or(CoreError::InvalidArgument)?);
}
Ok(Some(EncodedUnit {
channel: complete.channel,
sequence: complete.sequence,
timestamp_ms: complete.timestamp_ms,
payload,
}))
}
#[must_use]
pub fn incomplete_units(&self) -> usize {
self.incomplete.len()
}
#[must_use]
pub const fn evicted_units(&self) -> u64 {
self.evicted_units
}
#[must_use]
pub const fn expired_units(&self) -> u64 {
self.expired_units
}
}
+220
View File
@@ -0,0 +1,220 @@
use std::collections::VecDeque;
use crate::error::{CoreError, Result};
use crate::media::EncodedUnit;
pub const INPUT_QUEUE_CAPACITY: usize = 64;
pub const CONTROL_QUEUE_CAPACITY: usize = 64;
const MEDIA_QUEUE_CAPACITY: usize = 4;
const MAX_CONTROL_BYTES: usize = 128 * 1024;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct SessionStats {
pub dropped_media_units: u64,
}
#[derive(Debug, Default)]
pub struct SessionCore {
input: VecDeque<Vec<u8>>,
control: VecDeque<Vec<u8>>,
media: VecDeque<EncodedUnit>,
cancelled: bool,
stats: SessionStats,
}
impl SessionCore {
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Enqueues one already-validated VGI1 envelope without blocking.
///
/// # Errors
///
/// Returns `invalid_argument`, `queue_full`, or `cancelled`.
pub fn enqueue_input(&mut self, bytes: Vec<u8>) -> Result<()> {
if self.cancelled {
return Err(CoreError::Cancelled);
}
if bytes.is_empty() || bytes.len() > 23 {
return Err(CoreError::InvalidArgument);
}
if self.input.len() == INPUT_QUEUE_CAPACITY {
return Err(CoreError::QueueFull);
}
self.input.push_back(bytes);
Ok(())
}
/// Enqueues one bounded reliable control body without blocking.
///
/// # Errors
///
/// Returns `invalid_argument`, `queue_full`, or `cancelled`.
pub fn enqueue_control(&mut self, bytes: Vec<u8>) -> Result<()> {
if self.cancelled {
return Err(CoreError::Cancelled);
}
if bytes.len() > MAX_CONTROL_BYTES {
return Err(CoreError::InvalidArgument);
}
if self.control.len() == CONTROL_QUEUE_CAPACITY {
return Err(CoreError::QueueFull);
}
self.control.push_back(bytes);
Ok(())
}
/// Enqueues one bounded complete encoded media unit.
///
/// # Errors
///
/// Returns `invalid_argument` for an oversized unit or `cancelled` after cancellation.
pub fn enqueue_media(&mut self, unit: EncodedUnit) -> Result<()> {
if unit.payload.len() > crate::media::MAX_COMPLETE_UNIT_BYTES {
return Err(CoreError::InvalidArgument);
}
if self.cancelled {
self.stats.dropped_media_units += 1;
return Err(CoreError::Cancelled);
}
if self.media.len() == MEDIA_QUEUE_CAPACITY {
let position = self
.media
.iter()
.position(|queued| queued.channel == unit.channel);
if let Some(position) = position {
self.media.remove(position);
} else {
self.stats.dropped_media_units += 1;
return Ok(());
}
self.stats.dropped_media_units += 1;
}
self.media.push_back(unit);
Ok(())
}
pub fn pop_media(&mut self) -> Option<EncodedUnit> {
self.media.pop_front()
}
pub fn cancel(&mut self) {
self.cancelled = true;
self.input.clear();
self.control.clear();
self.media.clear();
}
#[must_use]
pub const fn is_cancelled(&self) -> bool {
self.cancelled
}
#[must_use]
pub const fn stats(&self) -> SessionStats {
self.stats
}
}
#[cfg(test)]
#[derive(Debug, Default)]
struct InProcessSession {
incoming: VecDeque<Vec<u8>>,
}
#[cfg(test)]
impl InProcessSession {
fn push_incoming(&mut self, bytes: Vec<u8>) {
self.incoming.push_back(bytes);
}
fn pop_incoming(&mut self) -> Option<Vec<u8>> {
self.incoming.pop_front()
}
}
#[cfg(test)]
mod tests {
use super::{InProcessSession, SessionCore, CONTROL_QUEUE_CAPACITY, INPUT_QUEUE_CAPACITY};
use crate::error::CoreError;
use crate::media::{EncodedUnit, MediaChannel};
#[test]
fn queues_are_bounded_and_cancellation_is_idempotent() {
let mut session = SessionCore::new();
assert_eq!(
session.enqueue_input(vec![0; 24]),
Err(CoreError::InvalidArgument)
);
for value in 0..INPUT_QUEUE_CAPACITY {
session
.enqueue_input(vec![u8::try_from(value).expect("capacity fits u8")])
.expect("within bound");
}
assert_eq!(session.enqueue_input(vec![0]), Err(CoreError::QueueFull));
for value in 0..CONTROL_QUEUE_CAPACITY {
session
.enqueue_control(vec![u8::try_from(value).expect("capacity fits u8")])
.expect("within bound");
}
assert_eq!(session.enqueue_control(vec![0]), Err(CoreError::QueueFull));
let mut oversized_control = SessionCore::new();
assert_eq!(
oversized_control.enqueue_control(vec![0; 128 * 1024 + 1]),
Err(CoreError::InvalidArgument)
);
session
.enqueue_media(EncodedUnit {
channel: MediaChannel::Audio,
sequence: 1,
timestamp_ms: 1,
payload: vec![1],
})
.expect("bounded media");
session.cancel();
session.cancel();
assert!(session.is_cancelled());
assert_eq!(session.enqueue_input(vec![0]), Err(CoreError::Cancelled));
assert!(session.pop_media().is_none());
}
#[test]
fn media_queue_evicts_oldest_same_channel_at_four_units() {
let mut session = SessionCore::new();
assert_eq!(
session.enqueue_media(EncodedUnit {
channel: MediaChannel::Video,
sequence: 99,
timestamp_ms: 0,
payload: vec![0; 1_048_577],
}),
Err(CoreError::InvalidArgument)
);
for sequence in 0..5 {
session
.enqueue_media(EncodedUnit {
channel: MediaChannel::Video,
sequence,
timestamp_ms: u64::from(sequence),
payload: vec![u8::try_from(sequence).expect("test sequence fits u8")],
})
.expect("bounded media");
}
assert_eq!(session.stats().dropped_media_units, 1);
assert_eq!(session.pop_media().expect("media").sequence, 1);
}
#[test]
fn private_in_process_session_preserves_byte_order() {
let mut transport = InProcessSession::default();
transport.push_incoming(vec![1, 2]);
transport.push_incoming(vec![3]);
assert_eq!(transport.pop_incoming(), Some(vec![1, 2]));
assert_eq!(transport.pop_incoming(), Some(vec![3]));
}
}
+507
View File
@@ -0,0 +1,507 @@
use serde::de::DeserializeOwned;
use serde::Deserialize;
use crate::error::{CoreError, Result};
const MAX_MANIFEST_JSON_BYTES: usize = 128 * 1024;
const MAX_CREDENTIAL_JSON_BYTES: usize = 196 * 1024;
const MAX_ADMISSION_JSON_BYTES: usize = 16 * 1024;
fn decode_strict<T: DeserializeOwned>(bytes: &[u8], maximum: usize) -> Result<T> {
if bytes.is_empty() || bytes.len() > maximum {
return Err(CoreError::InvalidArgument);
}
serde_json::from_slice(bytes).map_err(|_| CoreError::InvalidArgument)
}
fn bounded(value: &str, minimum: usize, maximum: usize) -> bool {
(minimum..=maximum).contains(&value.len())
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Timestamp {
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanosecond: u32,
}
fn timestamp(value: &str, exact_seconds: bool) -> Option<Timestamp> {
let bytes = value.as_bytes();
if bytes.len() < 20
|| bytes.len() > 30
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| bytes[10] != b'T'
|| bytes[13] != b':'
|| bytes[16] != b':'
|| *bytes.last()? != b'Z'
{
return None;
}
let digits = |start: usize, end: usize| {
bytes
.get(start..end)?
.iter()
.try_fold(0_u32, |number, byte| {
byte.is_ascii_digit()
.then_some(number * 10 + u32::from(*byte - b'0'))
})
};
let year = u16::try_from(digits(0, 4)?).ok()?;
let month = u8::try_from(digits(5, 7)?).ok()?;
let day = u8::try_from(digits(8, 10)?).ok()?;
let hour = u8::try_from(digits(11, 13)?).ok()?;
let minute = u8::try_from(digits(14, 16)?).ok()?;
let second = u8::try_from(digits(17, 19)?).ok()?;
if hour > 23 || minute > 59 || second > 59 {
return None;
}
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let maximum_day = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return None,
};
if day == 0 || day > maximum_day {
return None;
}
let nanosecond = if bytes.len() == 20 {
0
} else {
if exact_seconds || bytes[19] != b'.' {
return None;
}
let fraction = bytes.get(20..bytes.len() - 1)?;
if fraction.is_empty()
|| fraction.len() > 9
|| !fraction.iter().all(u8::is_ascii_digit)
|| *fraction.last()? == b'0'
{
return None;
}
let mut value = fraction
.iter()
.fold(0_u32, |number, byte| number * 10 + u32::from(*byte - b'0'));
for _ in fraction.len()..9 {
value *= 10;
}
value
};
Some(Timestamp {
year,
month,
day,
hour,
minute,
second,
nanosecond,
})
}
fn valid_dns_name(value: &str) -> bool {
bounded(value, 1, 253)
&& value.split('.').all(|label| {
bounded(label, 1, 63)
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
})
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CapabilityProfile {
transport: String,
framing: String,
media: String,
audio: String,
source_rate_control: String,
client_decode: Vec<String>,
}
impl CapabilityProfile {
/// Creates and validates an RC5 capability profile.
///
/// # Errors
///
/// Returns `invalid_argument` when a field violates RC5 bounds or registry values.
pub fn new(
transport: &str,
framing: &str,
media: &str,
audio: &str,
source_rate_control: &str,
client_decode: Vec<String>,
) -> Result<Self> {
let profile = Self {
transport: transport.to_owned(),
framing: framing.to_owned(),
media: media.to_owned(),
audio: audio.to_owned(),
source_rate_control: source_rate_control.to_owned(),
client_decode,
};
profile.validate()?;
Ok(profile)
}
fn validate(&self) -> Result<()> {
if !bounded(&self.transport, 1, 64)
|| !matches!(self.framing.as_str(), "datagram-v1" | "datagram-v2")
|| !bounded(&self.media, 1, 64)
|| !bounded(&self.audio, 1, 64)
|| !bounded(&self.source_rate_control, 1, 64)
|| !(1..=2).contains(&self.client_decode.len())
|| self
.client_decode
.iter()
.any(|value| !matches!(value.as_str(), "h264-opus" | "hevc-opus"))
|| self.client_decode.len()
!= self
.client_decode
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
{
return Err(CoreError::InvalidArgument);
}
Ok(())
}
fn is_subset_of(&self, offered: &Self) -> bool {
self.transport == offered.transport
&& self.framing == offered.framing
&& self.media == offered.media
&& self.audio == offered.audio
&& self.source_rate_control == offered.source_rate_control
&& self
.client_decode
.iter()
.all(|codec| offered.client_decode.contains(codec))
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestGateway {
id: String,
addresses: Vec<String>,
public_identity: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestTunnel {
versions: Vec<String>,
features: Vec<String>,
}
#[allow(clippy::struct_field_names)]
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestBounds {
minimum_kbps: u64,
target_kbps: u64,
maximum_kbps: u64,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct DisplayMode {
resolution_width: u16,
resolution_height: u16,
fps: u16,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestProfile {
id: String,
bounds: ManifestBounds,
display_mode: Option<DisplayMode>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct GrantReference {
opaque_value: String,
expires_at: String,
audience: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConnectionManifest {
version: String,
purpose: String,
session_id: String,
reconnect_sequence: u64,
gateway: ManifestGateway,
tunnel: ManifestTunnel,
profile: ManifestProfile,
grant: GrantReference,
correlation_id: String,
}
impl ConnectionManifest {
/// Strictly decodes and validates an RC5 connection manifest.
///
/// # Errors
///
/// Returns `invalid_argument` for malformed, duplicate, trailing, unknown, or invalid data.
pub fn decode(bytes: &[u8]) -> Result<Self> {
let manifest: Self = decode_strict(bytes, MAX_MANIFEST_JSON_BYTES)?;
manifest.validate()?;
Ok(manifest)
}
fn validate(&self) -> Result<()> {
let bounds = &self.profile.bounds;
let valid_display = self.profile.display_mode.as_ref().is_none_or(|mode| {
(320..=16_384).contains(&mode.resolution_width)
&& (200..=8_640).contains(&mode.resolution_height)
&& (1..=240).contains(&mode.fps)
});
if self.version != "1"
|| !matches!(self.purpose.as_str(), "launch" | "reconnect")
|| !bounded(&self.session_id, 1, 128)
|| !bounded(&self.gateway.id, 1, 128)
|| !(1..=4).contains(&self.gateway.addresses.len())
|| self
.gateway
.addresses
.iter()
.any(|address| !bounded(address, 1, 256))
|| !valid_dns_name(&self.gateway.public_identity)
|| !(1..=4).contains(&self.tunnel.versions.len())
|| self
.tunnel
.versions
.iter()
.any(|version| !bounded(version, 1, 64))
|| self.tunnel.features.len() > 32
|| self
.tunnel
.features
.iter()
.any(|feature| !bounded(feature, 1, 64))
|| !bounded(&self.profile.id, 1, 128)
|| !(1..=100_000_000).contains(&bounds.minimum_kbps)
|| !(1..=100_000_000).contains(&bounds.target_kbps)
|| !(1..=100_000_000).contains(&bounds.maximum_kbps)
|| bounds.minimum_kbps > bounds.target_kbps
|| bounds.target_kbps > bounds.maximum_kbps
|| !valid_display
|| !bounded(&self.grant.opaque_value, 43, 256)
|| timestamp(&self.grant.expires_at, false).is_none()
|| !bounded(&self.grant.audience, 1, 128)
|| !bounded(&self.correlation_id, 1, 128)
{
return Err(CoreError::InvalidArgument);
}
Ok(())
}
/// Checks expiry and the supported tunnel binding at a supplied UTC instant.
///
/// # Errors
///
/// Returns `invalid_argument` for unsupported input or `expired` for an expired grant.
pub fn validate_at(&self, now_utc: &str) -> Result<()> {
let now = timestamp(now_utc, false).ok_or(CoreError::InvalidArgument)?;
if timestamp(&self.grant.expires_at, false).ok_or(CoreError::InvalidArgument)? <= now {
return Err(CoreError::Expired);
}
if !self
.tunnel
.versions
.iter()
.any(|value| value == "verse-gateway-v1/1")
|| !self
.tunnel
.features
.iter()
.any(|value| value == "control.v1")
{
return Err(CoreError::InvalidArgument);
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeTunnelCredential {
client_device_id: String,
device_key_id: String,
certificate_chain_pem: String,
trust_bundle_pem: String,
expires_at: String,
}
impl NativeTunnelCredential {
/// Strictly decodes and validates an RC5 native tunnel credential.
///
/// # Errors
///
/// Returns `invalid_argument` for malformed, unknown, or out-of-bound data.
pub fn decode(bytes: &[u8]) -> Result<Self> {
let credential: Self = decode_strict(bytes, MAX_CREDENTIAL_JSON_BYTES)?;
if !bounded(&credential.client_device_id, 1, 128)
|| !bounded(&credential.device_key_id, 1, 128)
|| !bounded(&credential.certificate_chain_pem, 1, 65_536)
|| !bounded(&credential.trust_bundle_pem, 1, 65_536)
|| timestamp(&credential.expires_at, false).is_none()
{
return Err(CoreError::InvalidArgument);
}
Ok(credential)
}
/// Checks credential expiry at a supplied UTC instant.
///
/// # Errors
///
/// Returns `invalid_argument` for an invalid instant or `expired` after expiry.
pub fn validate_at(&self, now_utc: &str) -> Result<()> {
let now = timestamp(now_utc, false).ok_or(CoreError::InvalidArgument)?;
if timestamp(&self.expires_at, false).ok_or(CoreError::InvalidArgument)? <= now {
return Err(CoreError::Expired);
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TunnelAdmissionRequest {
version: String,
session_id: String,
gateway_id: String,
audience: String,
grant: String,
reconnect_sequence: u64,
client_nonce: String,
device_signature: String,
capabilities: CapabilityProfile,
}
impl TunnelAdmissionRequest {
/// Strictly decodes and validates an RC5 tunnel admission request.
///
/// # Errors
///
/// Returns `invalid_argument` for malformed, unknown, or out-of-bound data.
pub fn decode(bytes: &[u8]) -> Result<Self> {
let request: Self = decode_strict(bytes, MAX_ADMISSION_JSON_BYTES)?;
if request.version != "1"
|| !bounded(&request.session_id, 1, 128)
|| !bounded(&request.gateway_id, 1, 128)
|| !bounded(&request.audience, 1, 256)
|| !bounded(&request.grant, 43, 256)
|| !bounded(&request.client_nonce, 16, 128)
|| request.device_signature.len() != 86
{
return Err(CoreError::InvalidArgument);
}
request.capabilities.validate()?;
Ok(request)
}
#[must_use]
pub fn admission_transcript(&self) -> Vec<u8> {
let reconnect_sequence = self.reconnect_sequence.to_string();
let decode_count = self.capabilities.client_decode.len().to_string();
let mut fields = vec![
self.session_id.as_str(),
self.gateway_id.as_str(),
self.audience.as_str(),
self.grant.as_str(),
reconnect_sequence.as_str(),
self.client_nonce.as_str(),
self.capabilities.transport.as_str(),
self.capabilities.framing.as_str(),
self.capabilities.media.as_str(),
self.capabilities.audio.as_str(),
self.capabilities.source_rate_control.as_str(),
decode_count.as_str(),
];
fields.extend(self.capabilities.client_decode.iter().map(String::as_str));
let mut transcript = String::from("versevdi/tunnel-admission/v1");
for field in fields {
transcript.push_str(&field.len().to_string());
transcript.push(':');
transcript.push_str(field);
}
transcript.into_bytes()
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ClientSessionAuthority {
version: String,
session_id: String,
gateway_id: String,
audience: String,
reconnect_sequence: u64,
expires_at: String,
capabilities: CapabilityProfile,
}
impl ClientSessionAuthority {
/// Strictly decodes and validates a provider-free RC5 client authority.
///
/// # Errors
///
/// Returns `invalid_argument` for malformed, unknown, provider-shaped, or invalid data.
pub fn decode(bytes: &[u8]) -> Result<Self> {
let authority: Self = decode_strict(bytes, MAX_ADMISSION_JSON_BYTES)?;
if authority.version != "1"
|| !bounded(&authority.session_id, 1, 128)
|| !bounded(&authority.gateway_id, 1, 128)
|| !bounded(&authority.audience, 1, 256)
|| timestamp(&authority.expires_at, true).is_none()
{
return Err(CoreError::InvalidArgument);
}
authority.capabilities.validate()?;
Ok(authority)
}
/// Checks session, gateway, audience, reconnect, expiry, and capability bindings.
///
/// # Errors
///
/// Returns `invalid_argument` for an invalid clock value or `authority_rejected` on mismatch.
pub fn validate_binding(
&self,
manifest: &ConnectionManifest,
offered: &CapabilityProfile,
now_utc: &str,
) -> Result<()> {
let now = timestamp(now_utc, false).ok_or(CoreError::InvalidArgument)?;
let expires = timestamp(&self.expires_at, true).ok_or(CoreError::AuthorityRejected)?;
let grant_expires =
timestamp(&manifest.grant.expires_at, false).ok_or(CoreError::AuthorityRejected)?;
if self.session_id != manifest.session_id
|| self.gateway_id != manifest.gateway.id
|| self.audience != manifest.grant.audience
|| self.reconnect_sequence != manifest.reconnect_sequence
|| expires <= now
|| expires > grant_expires
|| !self.capabilities.is_subset_of(offered)
{
return Err(CoreError::AuthorityRejected);
}
Ok(())
}
}