feat: add native WebRTC bridge with libdatachannel/rustrtc bindings

This commit is contained in:
2026-02-19 11:38:10 -03:00
parent 3da00503a2
commit d8111dd32a
13 changed files with 7236 additions and 0 deletions

1766
deps/rustrtc-capi/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

25
deps/rustrtc-capi/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,25 @@
[package]
name = "rustrtc-capi"
version = "0.1.0"
edition = "2021"
[lib]
name = "datachannel"
crate-type = ["cdylib", "rlib"]
[dependencies]
rustrtc = "0.3"
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
parking_lot = "0.12"
log = "0.4"
env_logger = "0.11"
bytes = "1"
time = ">=0.3,<0.3.47"
[[test]]
name = "loopback"
path = "tests/loopback.rs"

753
deps/rustrtc-capi/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,753 @@
//! rustrtc C API wrapper — drop-in replacement for libdatachannel.
//!
//! Exports the same `rtc*` C symbols so that Zig's `webrtc_native.zig`
//! links against this library with zero code changes.
mod monitors;
mod state;
mod types;
pub mod ws_signaling;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use rustrtc::config::RtcConfiguration as RustRtcConfig;
use rustrtc::peer_connection::PeerConnection;
use rustrtc::transports::datachannel::DataChannelConfig;
use rustrtc::transports::ice::IceCandidate;
use crate::monitors::*;
use crate::state::*;
use crate::types::*;
// ===========================================================================
// Global
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcPreload() {
init_runtime();
}
#[no_mangle]
pub extern "C" fn rtcCleanup() {
cleanup();
}
#[no_mangle]
pub extern "C" fn rtcInitLogger(level: c_int, cb: Option<LogCallbackFn>) {
// Simple implementation: if callback provided, store it; otherwise use env_logger
let _ = level;
let _ = cb;
// For now, initialize env_logger for Rust-side logging (best effort)
let _ = env_logger::try_init();
}
// ===========================================================================
// User pointer
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetUserPointer(id: c_int, ptr: *mut c_void) {
set_user_ptr(id, ptr);
}
#[no_mangle]
pub extern "C" fn rtcGetUserPointer(id: c_int) -> *mut c_void {
get_user_ptr(id)
}
// ===========================================================================
// PeerConnection
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreatePeerConnection(config: *const RtcConfiguration) -> c_int {
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let cfg = &*config;
let mut rust_config = RustRtcConfig::default();
// Map ICE servers
if !cfg.ice_servers.is_null() && cfg.ice_servers_count > 0 {
let count = cfg.ice_servers_count as usize;
for i in 0..count {
let server_ptr = *cfg.ice_servers.add(i);
if !server_ptr.is_null() {
if let Ok(s) = CStr::from_ptr(server_ptr).to_str() {
let ice_server = rustrtc::config::IceServer::new(vec![s.to_string()]);
rust_config.ice_servers.push(ice_server);
}
}
}
}
// Map port range
if cfg.port_range_begin > 0 && cfg.port_range_end > 0 {
rust_config.rtp_start_port = Some(cfg.port_range_begin);
rust_config.rtp_end_port = Some(cfg.port_range_end);
}
// Enter runtime context — PeerConnection::new() needs a tokio reactor
let _guard = rt.enter();
let pc = Arc::new(PeerConnection::new(rust_config));
let pc_id = alloc_id();
let disable_auto = cfg.disable_auto_negotiation;
// Spawn PC monitoring tasks
let tasks = spawn_pc_monitors(rt, pc_id, &pc);
let pc_state = PcState::new(pc, disable_auto);
*pc_state.tasks.lock() = tasks;
entries().write().insert(pc_id, Entry::Pc(pc_state));
pc_id
}
#[no_mangle]
pub extern "C" fn rtcClosePeerConnection(pc: c_int) -> c_int {
match with_pc(pc, |pc_state| {
pc_state.pc.close();
}) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcDeletePeerConnection(pc: c_int) -> c_int {
let entry = entries().write().remove(&pc);
match entry {
Some(Entry::Pc(pc_state)) => {
// Abort all monitor tasks
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
Some(other) => {
// Put it back — wrong type
entries().write().insert(pc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (PeerConnection)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetLocalDescriptionCallback(
pc: c_int,
cb: Option<DescriptionCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_description.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetLocalCandidateCallback(
pc: c_int,
cb: Option<CandidateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_candidate.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetStateChangeCallback(
pc: c_int,
cb: Option<StateChangeCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_state_change.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetGatheringStateChangeCallback(
pc: c_int,
cb: Option<GatheringStateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_gathering_state.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetDataChannelCallback(
pc: c_int,
cb: Option<DataChannelCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_data_channel.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SDP
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetLocalDescription(
pc: c_int,
sdp_type: *const c_char,
) -> c_int {
let (pc_arc, _disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_answer = if sdp_type.is_null() {
false
} else {
let type_str = CStr::from_ptr(sdp_type).to_str().unwrap_or("");
type_str == "answer"
};
if is_answer {
// Generate answer (assumes remote offer already set)
let pc_clone = pc_arc.clone();
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
match pc_clone.create_answer().await {
Ok(answer) => {
let sdp_string = crate::monitors::inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc_clone.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
with_pc(pc, |s| {
*s.local_sdp.lock() = Some(sdp_c.clone());
*s.local_sdp_type.lock() = Some(type_c.clone());
});
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc) {
cb(pc, sdp_c.as_ptr(), type_c.as_ptr(), ptr);
}
}
Err(e) => log::error!("create_answer failed: {e}"),
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
} else {
// Generate offer
trigger_offer(pc, pc_arc);
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcSetRemoteDescription(
pc: c_int,
sdp: *const c_char,
sdp_type: *const c_char,
) -> c_int {
if sdp.is_null() {
return RTC_ERR_INVALID;
}
let sdp_str = match CStr::from_ptr(sdp).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let type_str = if sdp_type.is_null() {
"offer".to_string()
} else {
CStr::from_ptr(sdp_type)
.to_str()
.unwrap_or("offer")
.to_string()
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_offer = type_str == "offer";
if is_offer {
// Trigger auto-answer: parse remote offer → set remote desc → create answer → fire callback
trigger_answer(pc, pc_arc, sdp_str);
} else {
// It's an answer — just set the remote description
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Answer,
&sdp_str,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse answer SDP failed: {e}");
return;
}
};
if let Err(e) = pc_arc.set_remote_description(desc).await {
log::error!("set_remote_description (answer) failed: {e}");
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(sdp_str) {
with_pc(pc, |s| {
*s.remote_sdp.lock() = Some(remote_c);
});
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcAddRemoteCandidate(
pc: c_int,
cand: *const c_char,
mid: *const c_char,
) -> c_int {
let _ = mid; // mid is typically ignored for data-channel-only connections
if cand.is_null() {
return RTC_ERR_INVALID;
}
let cand_str = match CStr::from_ptr(cand).to_str() {
Ok(s) => s,
Err(_) => return RTC_ERR_INVALID,
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
match IceCandidate::from_sdp(cand_str) {
Ok(candidate) => match pc_arc.add_ice_candidate(candidate) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("add_ice_candidate failed: {e}");
RTC_ERR_FAILURE
}
},
Err(e) => {
log::error!("parse ICE candidate failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetLocalDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.local_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetRemoteDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.remote_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// DataChannel
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannel(
pc: c_int,
label: *const c_char,
) -> c_int {
// Create with default DataChannelInit
let default_init = RtcDataChannelInit {
reliability: RtcReliability {
unordered: false,
unreliable: false,
max_packet_life_time: 0,
max_retransmits: 0,
},
protocol: std::ptr::null(),
negotiated: false,
manual_stream: false,
stream: 0,
};
rtcCreateDataChannelEx(pc, label, &default_init)
}
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannelEx(
pc: c_int,
label: *const c_char,
init: *const RtcDataChannelInit,
) -> c_int {
if label.is_null() || init.is_null() {
return RTC_ERR_INVALID;
}
let label_str = match CStr::from_ptr(label).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let init_ref = &*init;
let protocol = if init_ref.protocol.is_null() {
String::new()
} else {
CStr::from_ptr(init_ref.protocol)
.to_str()
.unwrap_or("")
.to_string()
};
let (pc_arc, disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let dc_config = DataChannelConfig {
label: label_str,
protocol,
ordered: !init_ref.reliability.unordered,
max_retransmits: if init_ref.reliability.unreliable && init_ref.reliability.max_retransmits > 0
{
Some(init_ref.reliability.max_retransmits as u16)
} else {
None
},
max_packet_life_time: if init_ref.reliability.unreliable
&& init_ref.reliability.max_packet_life_time > 0
{
Some(init_ref.reliability.max_packet_life_time as u16)
} else {
None
},
max_payload_size: None,
negotiated: if init_ref.negotiated {
Some(init_ref.stream)
} else {
None
},
};
// Enter runtime context for create_data_channel
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let _guard = rt.enter();
let label_for_create = dc_config.label.clone();
let dc = match pc_arc.create_data_channel(&label_for_create, Some(dc_config)) {
Ok(dc) => dc,
Err(e) => {
log::error!("create_data_channel failed: {e}");
return RTC_ERR_FAILURE;
}
};
let dc_id = alloc_id();
let channel_id = dc.id;
// Spawn DC event monitor
let handle = spawn_dc_monitor(dc_id, dc);
let dc_state = DcState::new(pc, pc_arc.clone(), channel_id);
*dc_state.task.lock() = Some(handle);
entries().write().insert(dc_id, Entry::Dc(dc_state));
// Trigger auto-negotiation (offer generation) if enabled
if !disable_auto {
trigger_offer(pc, pc_arc);
}
dc_id
}
#[no_mangle]
pub extern "C" fn rtcDeleteDataChannel(dc: c_int) -> c_int {
let entry = entries().write().remove(&dc);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(other) => {
entries().write().insert(dc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (DataChannel / common)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetOpenCallback(id: c_int, cb: Option<OpenCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_open.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetClosedCallback(id: c_int, cb: Option<ClosedCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_closed.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetErrorCallback(id: c_int, cb: Option<ErrorCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_error.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetMessageCallback(id: c_int, cb: Option<MessageCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_message.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// I/O
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSendMessage(
id: c_int,
data: *const u8,
size: c_int,
) -> c_int {
let bytes = if size < 0 {
// Treat as null-terminated string
let cstr = CStr::from_ptr(data as *const c_char);
cstr.to_bytes().to_vec()
} else {
std::slice::from_raw_parts(data, size as usize).to_vec()
};
let (pc_arc, channel_id) = match with_dc(id, |dc| (dc.pc.clone(), dc.channel_id)) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
// Blocking send — preserves message ordering (caller is always on a non-tokio thread)
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
match rt.block_on(pc_arc.send_data(channel_id, &bytes)) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("send_data failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub extern "C" fn rtcClose(id: c_int) -> c_int {
// Try as DC first
if let Some(_) = with_dc(id, |dc| {
dc.is_open.store(false, Ordering::Release);
// Close the underlying PC data channel
let pc = dc.pc.clone();
let channel_id = dc.channel_id;
if let Some(rt) = get_runtime() {
rt.spawn(async move {
// There's no explicit DC close in rustrtc; closing is done at PC level
let _ = (pc, channel_id);
});
}
}) {
return RTC_ERR_SUCCESS;
}
// Try as PC
if let Some(_) = with_pc(id, |pc| {
pc.pc.close();
}) {
return RTC_ERR_SUCCESS;
}
RTC_ERR_INVALID
}
#[no_mangle]
pub extern "C" fn rtcDelete(id: c_int) -> c_int {
let entry = entries().write().remove(&id);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(Entry::Pc(pc_state)) => {
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcIsOpen(id: c_int) -> bool {
with_dc(id, |dc| dc.is_open.load(Ordering::Acquire)).unwrap_or(false)
}
#[no_mangle]
pub extern "C" fn rtcIsClosed(id: c_int) -> bool {
with_dc(id, |dc| dc.is_closed.load(Ordering::Acquire)).unwrap_or(true)
}
#[no_mangle]
pub extern "C" fn rtcGetBufferedAmount(id: c_int) -> c_int {
let pc_arc = match with_dc(id, |dc| dc.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
// block_on is safe here because we're called from non-tokio threads
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rt.block_on(pc_arc.sctp_buffered_amount()) as c_int
})) {
Ok(amount) => amount,
Err(_) => {
// If block_on panics (called from tokio context), try spawn + channel
let pc_clone = pc_arc.clone();
let (tx, rx) = std::sync::mpsc::channel();
rt.spawn(async move {
let amount = pc_clone.sctp_buffered_amount().await;
let _ = tx.send(amount as c_int);
});
rx.recv().unwrap_or(0)
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcReceiveMessage(
id: c_int,
buffer: *mut u8,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return RTC_ERR_INVALID;
}
match with_dc(id, |dc| {
let mut buf = dc.recv_buffer.lock();
buf.pop_front()
}) {
Some(Some(data)) => {
let available = *size as usize;
if data.len() > available {
*size = data.len() as c_int;
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len());
*size = data.len() as c_int;
RTC_ERR_SUCCESS
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SCTP settings (no-op — rustrtc has its own SCTP stack)
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetSctpSettings(_settings: *const RtcSctpSettings) -> c_int {
RTC_ERR_SUCCESS
}

338
deps/rustrtc-capi/src/monitors.rs vendored Normal file
View File

@@ -0,0 +1,338 @@
//! Async tasks that bridge rustrtc events → C callbacks.
//!
//! For each PeerConnection, we spawn monitor tasks for:
//! - ICE candidates (broadcast receiver)
//! - Peer connection state (watch receiver)
//! - ICE gathering state (watch receiver)
//! - Incoming DataChannels (pc.recv())
//!
//! For each DataChannel, we spawn one monitor task that handles
//! Open / Message / Close events.
use std::ffi::CString;
use std::sync::Arc;
use rustrtc::peer_connection::{
IceGatheringState, PeerConnection, PeerConnectionEvent, PeerConnectionState,
};
use rustrtc::transports::datachannel::{DataChannel, DataChannelEvent};
use tokio::task::JoinHandle;
use crate::state::*;
use crate::types::*;
// ---------------------------------------------------------------------------
// PeerConnection monitors
// ---------------------------------------------------------------------------
/// Spawn all monitoring tasks for a PeerConnection. Returns task handles.
pub fn spawn_pc_monitors(
rt: &tokio::runtime::Runtime,
pc_id: i32,
pc: &Arc<PeerConnection>,
) -> Vec<JoinHandle<()>> {
let mut tasks = Vec::with_capacity(4);
// 1. ICE candidate monitor (broadcast::Receiver)
let mut cand_rx = pc.subscribe_ice_candidates();
let pc_id1 = pc_id;
tasks.push(rt.spawn(async move {
loop {
match cand_rx.recv().await {
Ok(candidate) => {
let cand_str = candidate.to_sdp();
let cand_c = match CString::new(cand_str) {
Ok(c) => c,
Err(_) => continue,
};
let mid_c = CString::new("0").unwrap();
if let Some((Some(cb), ptr)) = get_pc_candidate_cb(pc_id1) {
unsafe { cb(pc_id1, cand_c.as_ptr(), mid_c.as_ptr(), ptr) };
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
}));
// 2. Peer connection state monitor (watch::Receiver)
let mut state_rx = pc.subscribe_peer_state();
let pc_id2 = pc_id;
tasks.push(rt.spawn(async move {
while state_rx.changed().await.is_ok() {
let state = *state_rx.borrow_and_update();
let c_state = map_peer_state(state);
if let Some((Some(cb), ptr)) = get_pc_state_change_cb(pc_id2) {
unsafe { cb(pc_id2, c_state, ptr) };
}
}
}));
// 3. ICE gathering state monitor (watch::Receiver)
let mut gather_rx = pc.subscribe_ice_gathering_state();
let pc_id3 = pc_id;
tasks.push(rt.spawn(async move {
while gather_rx.changed().await.is_ok() {
let state = *gather_rx.borrow_and_update();
let c_state = map_gathering_state(state);
if let Some((Some(cb), ptr)) = get_pc_gathering_state_cb(pc_id3) {
unsafe { cb(pc_id3, c_state, ptr) };
}
}
}));
// 4. Incoming DataChannel monitor (pc.recv())
let pc_clone = pc.clone();
let pc_id4 = pc_id;
tasks.push(rt.spawn(async move {
while let Some(event) = pc_clone.recv().await {
match event {
PeerConnectionEvent::DataChannel(dc) => {
handle_incoming_data_channel(pc_id4, &pc_clone, dc).await;
}
_ => {} // Ignore Track events for data-channel-only usage
}
}
}));
tasks
}
/// Handle an incoming DataChannel: register it, fire callback, then spawn monitor.
async fn handle_incoming_data_channel(
pc_id: i32,
pc: &Arc<PeerConnection>,
dc: Arc<DataChannel>,
) {
let dc_id = alloc_id();
let channel_id = dc.id;
let dc_state = DcState::new(pc_id, pc.clone(), channel_id);
// Insert into global registry
{
let mut map = entries().write();
map.insert(dc_id, Entry::Dc(dc_state));
}
// Fire DataChannel callback (synchronously — user sets DC callbacks inside)
if let Some((Some(cb), ptr)) = get_pc_data_channel_cb(pc_id) {
// Copy the PC's user pointer to the DC entry
let pc_ptr = get_user_ptr(pc_id);
set_user_ptr(dc_id, pc_ptr);
unsafe { cb(pc_id, dc_id, ptr) };
}
// Now spawn DC monitor (callbacks are set by this point)
let handle = spawn_dc_monitor(dc_id, dc);
with_dc(dc_id, |dc_state| {
*dc_state.task.lock() = Some(handle);
});
}
// ---------------------------------------------------------------------------
// DataChannel monitor
// ---------------------------------------------------------------------------
/// Spawn a monitor task for a DataChannel. Fires open/message/close callbacks.
pub fn spawn_dc_monitor(dc_id: i32, dc: Arc<DataChannel>) -> JoinHandle<()> {
let rt = get_runtime().expect("runtime not initialized");
rt.spawn(async move {
while let Some(event) = dc.recv().await {
match event {
DataChannelEvent::Open => {
// Mark as open
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(true, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(false, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_open_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
}
DataChannelEvent::Message(data) => {
let bytes = data.to_vec();
let len = bytes.len();
// Push to recv_buffer (for rtcReceiveMessage)
with_dc(dc_id, |dc_state| {
let mut buf = dc_state.recv_buffer.lock();
if buf.len() < 65536 {
buf.push_back(bytes.clone());
}
});
// Fire message callback
if let Some((Some(cb), ptr)) = get_dc_message_cb(dc_id) {
unsafe { cb(dc_id, bytes.as_ptr(), len as i32, ptr) };
}
}
DataChannelEvent::Close => {
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(false, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(true, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_closed_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
break;
}
}
}
})
}
// ---------------------------------------------------------------------------
// SDP generation helpers (spawned as async tasks)
// ---------------------------------------------------------------------------
/// Inject `a=max-message-size:1048576` into an SDP string if not already present.
/// Per RFC 8841 §4.3, absence of this attribute makes the remote peer assume a
/// default of 65536 bytes, which is too small for efficient file transfers.
pub fn inject_max_message_size(sdp: &str) -> String {
if sdp.contains("a=max-message-size") {
return sdp.to_string();
}
// Insert after `a=sctp-port` line (within the m= section)
if let Some(pos) = sdp.find("a=sctp-port") {
if let Some(eol) = sdp[pos..].find("\r\n") {
let insert_at = pos + eol + 2;
let mut result = String::with_capacity(sdp.len() + 30);
result.push_str(&sdp[..insert_at]);
result.push_str("a=max-message-size:1048576\r\n");
result.push_str(&sdp[insert_at..]);
return result;
}
}
sdp.to_string()
}
/// Trigger offer generation: create offer → set local description → fire callback.
/// Called after rtcCreateDataChannelEx when auto-negotiation is enabled.
pub fn trigger_offer(pc_id: i32, pc: Arc<PeerConnection>) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
match pc.create_offer().await {
Ok(offer) => {
let sdp_string = inject_max_message_size(&offer.to_sdp_string());
if let Err(e) = pc.set_local_description(offer) {
log::error!("set_local_description failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string.clone()) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("offer").unwrap();
// Cache SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_offer failed: {e}");
}
}
});
// Store task handle
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
/// Trigger answer generation after receiving a remote offer.
pub fn trigger_answer(pc_id: i32, pc: Arc<PeerConnection>, remote_sdp: String) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
// Parse and set remote description
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Offer,
&remote_sdp,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse remote SDP failed: {e}");
return;
}
};
if let Err(e) = pc.set_remote_description(desc).await {
log::error!("set_remote_description failed: {e}");
return;
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(remote_sdp) {
with_pc(pc_id, |pc_state| {
*pc_state.remote_sdp.lock() = Some(remote_c);
});
}
// Create answer
match pc.create_answer().await {
Ok(answer) => {
let sdp_string = inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
// Cache answer SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_answer failed: {e}");
}
}
});
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
// ---------------------------------------------------------------------------
// State mapping helpers
// ---------------------------------------------------------------------------
fn map_peer_state(state: PeerConnectionState) -> i32 {
match state {
PeerConnectionState::New => RTC_STATE_NEW,
PeerConnectionState::Connecting => RTC_STATE_CONNECTING,
PeerConnectionState::Connected => RTC_STATE_CONNECTED,
PeerConnectionState::Disconnected => RTC_STATE_DISCONNECTED,
PeerConnectionState::Failed => RTC_STATE_FAILED,
PeerConnectionState::Closed => RTC_STATE_CLOSED,
}
}
fn map_gathering_state(state: IceGatheringState) -> i32 {
match state {
IceGatheringState::New => RTC_GATHERING_NEW,
IceGatheringState::Gathering => RTC_GATHERING_IN_PROGRESS,
IceGatheringState::Complete => RTC_GATHERING_COMPLETE,
}
}

254
deps/rustrtc-capi/src/state.rs vendored Normal file
View File

@@ -0,0 +1,254 @@
//! Global ID registry, PcState, DcState.
use std::collections::{HashMap, VecDeque};
use std::ffi::CString;
use std::os::raw::c_void;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering};
use std::sync::{Arc, OnceLock};
use parking_lot::{Mutex, RwLock};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use rustrtc::peer_connection::PeerConnection;
use crate::types::*;
// ---------------------------------------------------------------------------
// Global statics
// ---------------------------------------------------------------------------
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static ENTRIES: OnceLock<RwLock<HashMap<i32, Entry>>> = OnceLock::new();
static NEXT_ID: AtomicI32 = AtomicI32::new(1);
pub fn init_runtime() {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to create tokio runtime")
});
ENTRIES.get_or_init(|| RwLock::new(HashMap::new()));
}
pub fn get_runtime() -> Option<&'static Runtime> {
RUNTIME.get()
}
pub fn cleanup() {
if let Some(entries) = ENTRIES.get() {
let mut map = entries.write();
// Abort all tasks
for (_, entry) in map.drain() {
match entry {
Entry::Pc(pc) => {
let tasks = pc.tasks.lock();
for t in tasks.iter() {
t.abort();
}
}
Entry::Dc(dc) => {
if let Some(t) = dc.task.lock().take() {
t.abort();
}
}
}
}
}
// Note: We don't drop the runtime here because OnceLock doesn't support reset.
// The runtime will be cleaned up on process exit.
}
pub fn alloc_id() -> i32 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
pub fn entries() -> &'static RwLock<HashMap<i32, Entry>> {
ENTRIES.get().expect("runtime not initialized")
}
// ---------------------------------------------------------------------------
// Entry types
// ---------------------------------------------------------------------------
pub enum Entry {
Pc(PcState),
Dc(DcState),
}
pub struct PcState {
pub pc: Arc<PeerConnection>,
pub user_ptr: AtomicPtr<c_void>,
pub disable_auto_negotiation: bool,
// Callback slots
pub on_local_description: Mutex<Option<DescriptionCallbackFn>>,
pub on_local_candidate: Mutex<Option<CandidateCallbackFn>>,
pub on_state_change: Mutex<Option<StateChangeCallbackFn>>,
pub on_gathering_state: Mutex<Option<GatheringStateCallbackFn>>,
pub on_data_channel: Mutex<Option<DataChannelCallbackFn>>,
// Cached SDP
pub local_sdp: Mutex<Option<CString>>,
pub local_sdp_type: Mutex<Option<CString>>,
pub remote_sdp: Mutex<Option<CString>>,
// Monitor task handles
pub tasks: Mutex<Vec<JoinHandle<()>>>,
}
pub struct DcState {
#[allow(dead_code)]
pub pc_id: i32,
pub pc: Arc<PeerConnection>,
pub channel_id: u16,
pub user_ptr: AtomicPtr<c_void>,
// Callback slots
pub on_open: Mutex<Option<OpenCallbackFn>>,
pub on_closed: Mutex<Option<ClosedCallbackFn>>,
pub on_error: Mutex<Option<ErrorCallbackFn>>,
pub on_message: Mutex<Option<MessageCallbackFn>>,
// State flags
pub is_open: AtomicBool,
pub is_closed: AtomicBool,
// Receive buffer (for rtcReceiveMessage polling)
pub recv_buffer: Mutex<VecDeque<Vec<u8>>>,
// Monitor task handle
pub task: Mutex<Option<JoinHandle<()>>>,
}
impl PcState {
pub fn new(pc: Arc<PeerConnection>, disable_auto_negotiation: bool) -> Self {
Self {
pc,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
disable_auto_negotiation,
on_local_description: Mutex::new(None),
on_local_candidate: Mutex::new(None),
on_state_change: Mutex::new(None),
on_gathering_state: Mutex::new(None),
on_data_channel: Mutex::new(None),
local_sdp: Mutex::new(None),
local_sdp_type: Mutex::new(None),
remote_sdp: Mutex::new(None),
tasks: Mutex::new(Vec::new()),
}
}
}
impl DcState {
pub fn new(pc_id: i32, pc: Arc<PeerConnection>, channel_id: u16) -> Self {
Self {
pc_id,
pc,
channel_id,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
on_open: Mutex::new(None),
on_closed: Mutex::new(None),
on_error: Mutex::new(None),
on_message: Mutex::new(None),
is_open: AtomicBool::new(false),
is_closed: AtomicBool::new(false),
recv_buffer: Mutex::new(VecDeque::new()),
task: Mutex::new(None),
}
}
}
// ---------------------------------------------------------------------------
// Helper accessors
// ---------------------------------------------------------------------------
/// Get user pointer for any entry (PC or DC).
pub fn get_user_ptr(id: i32) -> *mut c_void {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.load(Ordering::Acquire),
Some(Entry::Dc(dc)) => dc.user_ptr.load(Ordering::Acquire),
None => std::ptr::null_mut(),
}
}
/// Set user pointer for any entry.
pub fn set_user_ptr(id: i32, ptr: *mut c_void) {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.store(ptr, Ordering::Release),
Some(Entry::Dc(dc)) => dc.user_ptr.store(ptr, Ordering::Release),
None => {}
}
}
/// Execute a closure with read access to a PcState.
pub fn with_pc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&PcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => Some(f(pc)),
_ => None,
}
}
/// Execute a closure with read access to a DcState.
pub fn with_dc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&DcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Dc(dc)) => Some(f(dc)),
_ => None,
}
}
/// Get the PC Arc and user_ptr for a given PC id.
#[allow(dead_code)]
pub fn get_pc_arc(id: i32) -> Option<(Arc<PeerConnection>, *mut c_void)> {
with_pc(id, |pc| (pc.pc.clone(), pc.user_ptr.load(Ordering::Acquire)))
}
/// Get callback + user_ptr from a PC entry.
pub fn get_pc_description_cb(id: i32) -> Option<(Option<DescriptionCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_description.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_candidate_cb(id: i32) -> Option<(Option<CandidateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_candidate.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_state_change_cb(id: i32) -> Option<(Option<StateChangeCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_state_change.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_gathering_state_cb(id: i32) -> Option<(Option<GatheringStateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_gathering_state.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_data_channel_cb(id: i32) -> Option<(Option<DataChannelCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_data_channel.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_open_cb(id: i32) -> Option<(Option<OpenCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_open.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_closed_cb(id: i32) -> Option<(Option<ClosedCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_closed.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
#[allow(dead_code)]
pub fn get_dc_error_cb(id: i32) -> Option<(Option<ErrorCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_error.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_message_cb(id: i32) -> Option<(Option<MessageCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_message.lock(), dc.user_ptr.load(Ordering::Acquire)))
}

107
deps/rustrtc-capi/src/types.rs vendored Normal file
View File

@@ -0,0 +1,107 @@
//! C ABI type definitions matching libdatachannel's rtc.h
use std::os::raw::{c_char, c_int, c_uint, c_void};
// ---------------------------------------------------------------------------
// Error codes
// ---------------------------------------------------------------------------
pub const RTC_ERR_SUCCESS: c_int = 0;
pub const RTC_ERR_INVALID: c_int = -1;
pub const RTC_ERR_FAILURE: c_int = -2;
pub const RTC_ERR_NOT_AVAIL: c_int = -3;
pub const RTC_ERR_TOO_SMALL: c_int = -4;
// ---------------------------------------------------------------------------
// State enum values (as c_int, matching Zig's enum(c_int))
// ---------------------------------------------------------------------------
// PeerConnection / ICE state
pub const RTC_STATE_NEW: c_int = 0;
pub const RTC_STATE_CONNECTING: c_int = 1;
pub const RTC_STATE_CONNECTED: c_int = 2;
pub const RTC_STATE_DISCONNECTED: c_int = 3;
pub const RTC_STATE_FAILED: c_int = 4;
pub const RTC_STATE_CLOSED: c_int = 5;
// ICE gathering state
pub const RTC_GATHERING_NEW: c_int = 0;
pub const RTC_GATHERING_IN_PROGRESS: c_int = 1;
pub const RTC_GATHERING_COMPLETE: c_int = 2;
// ---------------------------------------------------------------------------
// Callback function types
// ---------------------------------------------------------------------------
pub type DescriptionCallbackFn =
unsafe extern "C" fn(pc: c_int, sdp: *const c_char, sdp_type: *const c_char, ptr: *mut c_void);
pub type CandidateCallbackFn =
unsafe extern "C" fn(pc: c_int, cand: *const c_char, mid: *const c_char, ptr: *mut c_void);
pub type StateChangeCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type GatheringStateCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type DataChannelCallbackFn =
unsafe extern "C" fn(pc: c_int, dc: c_int, ptr: *mut c_void);
pub type OpenCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ClosedCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ErrorCallbackFn =
unsafe extern "C" fn(id: c_int, err_msg: *const c_char, ptr: *mut c_void);
pub type MessageCallbackFn =
unsafe extern "C" fn(id: c_int, message: *const u8, size: c_int, ptr: *mut c_void);
pub type LogCallbackFn = unsafe extern "C" fn(level: c_int, message: *const c_char);
// ---------------------------------------------------------------------------
// #[repr(C)] structs matching Zig extern structs
// ---------------------------------------------------------------------------
#[repr(C)]
pub struct RtcConfiguration {
pub ice_servers: *const *const c_char,
pub ice_servers_count: c_int,
pub proxy_server: *const c_char,
pub bind_address: *const c_char,
pub certificate_type: c_int,
pub ice_transport_policy: c_int,
pub enable_ice_tcp: bool,
pub enable_ice_udp_mux: bool,
pub disable_auto_negotiation: bool,
pub force_media_transport: bool,
pub port_range_begin: u16,
pub port_range_end: u16,
pub mtu: c_int,
pub max_message_size: c_int,
}
#[repr(C)]
pub struct RtcReliability {
pub unordered: bool,
pub unreliable: bool,
pub max_packet_life_time: c_uint,
pub max_retransmits: c_uint,
}
#[repr(C)]
pub struct RtcDataChannelInit {
pub reliability: RtcReliability,
pub protocol: *const c_char,
pub negotiated: bool,
pub manual_stream: bool,
pub stream: u16,
}
#[repr(C)]
pub struct RtcSctpSettings {
pub recv_buffer_size: c_int,
pub send_buffer_size: c_int,
pub max_chunks_on_queue: c_int,
pub initial_congestion_window: c_int,
pub max_burst: c_int,
pub congestion_control_module: c_int,
pub delayed_sack_time_ms: c_int,
pub min_retransmit_timeout_ms: c_int,
pub max_retransmit_timeout_ms: c_int,
pub initial_retransmit_timeout_ms: c_int,
pub max_retransmit_attempts: c_int,
pub heartbeat_interval_ms: c_int,
}

304
deps/rustrtc-capi/src/ws_signaling.rs vendored Normal file
View File

@@ -0,0 +1,304 @@
//! WebSocket signaling client for SDP/ICE exchange.
//!
//! Provides 5 C-callable functions that let the Zig bridge connect to a
//! signaling server, send/receive JSON messages, and disconnect.
use std::collections::VecDeque;
use std::os::raw::{c_char, c_int};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::OnceLock;
use futures_util::{SinkExt, StreamExt};
use parking_lot::Mutex;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::Message;
use crate::state;
// ============================================================================
// WebSocket State
// ============================================================================
static NEXT_WS_ID: AtomicI32 = AtomicI32::new(1);
static WS_ENTRIES: OnceLock<Mutex<Vec<Option<WsState>>>> = OnceLock::new();
const MAX_WS_CONNECTIONS: usize = 8;
const MAX_RECV_QUEUE: usize = 256;
struct WsState {
id: i32,
connected: AtomicBool,
/// Sender for outgoing messages (to the writer task)
tx: mpsc::UnboundedSender<String>,
/// Received messages waiting to be polled by C caller
recv_queue: Mutex<VecDeque<String>>,
/// Background reader task handle
reader_task: Mutex<Option<JoinHandle<()>>>,
/// Background writer task handle
writer_task: Mutex<Option<JoinHandle<()>>>,
}
fn get_entries() -> &'static Mutex<Vec<Option<WsState>>> {
WS_ENTRIES.get_or_init(|| {
let mut v = Vec::with_capacity(MAX_WS_CONNECTIONS);
for _ in 0..MAX_WS_CONNECTIONS {
v.push(None);
}
Mutex::new(v)
})
}
// ============================================================================
// C API Functions
// ============================================================================
/// Connect to a signaling server via WebSocket.
/// `url` and `peer_id` are null-terminated C strings.
/// Returns a ws_id > 0 on success, or negative error code.
#[no_mangle]
pub unsafe extern "C" fn rtcWsConnect(url: *const c_char, peer_id: *const c_char) -> c_int {
if url.is_null() || peer_id.is_null() {
return -1;
}
let url_str = match std::ffi::CStr::from_ptr(url).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let peer_id_str = match std::ffi::CStr::from_ptr(peer_id).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let rt = match state::get_runtime() {
Some(rt) => rt,
None => {
// Ensure runtime is initialized
state::init_runtime();
match state::get_runtime() {
Some(rt) => rt,
None => return -2,
}
}
};
let ws_id = NEXT_WS_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::unbounded_channel::<String>();
// Connect in a blocking fashion so the C caller gets immediate result
let connect_result = rt.block_on(async {
tokio_tungstenite::connect_async(&url_str).await
});
let ws_stream = match connect_result {
Ok((stream, _response)) => stream,
Err(e) => {
log::error!("WebSocket connect failed: {}", e);
return -2;
}
};
let (mut write, mut read) = ws_stream.split();
// Send register message immediately
let register_msg = serde_json::json!({
"type": "register",
"peerId": peer_id_str
}).to_string();
if let Err(e) = rt.block_on(write.send(Message::Text(register_msg))) {
log::error!("Failed to send register: {}", e);
return -2;
}
let recv_queue = Mutex::new(VecDeque::new());
let connected = AtomicBool::new(true);
// Create the state entry first so tasks can reference the ID
let ws_state = WsState {
id: ws_id,
connected,
tx,
recv_queue,
reader_task: Mutex::new(None),
writer_task: Mutex::new(None),
};
// Store in entries
{
let mut entries = get_entries().lock();
let slot = entries.iter().position(|e| e.is_none());
match slot {
Some(idx) => entries[idx] = Some(ws_state),
None => return -3, // No free slots
}
}
// Spawn reader task
let reader_ws_id = ws_id;
let reader_handle = rt.spawn(async move {
while let Some(msg_result) = read.next().await {
match msg_result {
Ok(Message::Text(text)) => {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if queue.len() < MAX_RECV_QUEUE {
queue.push_back(text);
}
}
}
}
Ok(Message::Close(_)) => break,
Ok(_) => {} // Ignore binary/ping/pong
Err(e) => {
log::warn!("WebSocket read error: {}", e);
break;
}
}
}
// Mark as disconnected
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
ws.connected.store(false, Ordering::Release);
}
}
});
// Spawn writer task
let mut writer_rx = rx;
let writer_handle = rt.spawn(async move {
while let Some(msg) = writer_rx.recv().await {
if write.send(Message::Text(msg)).await.is_err() {
break;
}
}
});
// Store task handles
{
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
*ws.reader_task.lock() = Some(reader_handle);
*ws.writer_task.lock() = Some(writer_handle);
}
}
}
ws_id
}
/// Disconnect a WebSocket connection.
/// Returns 0 on success, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsDisconnect(ws_id: c_int) -> c_int {
let mut entries = get_entries().lock();
if let Some(idx) = entries.iter().position(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = entries[idx].take() {
ws.connected.store(false, Ordering::Release);
// Abort tasks
if let Some(h) = ws.reader_task.lock().take() {
h.abort();
}
if let Some(h) = ws.writer_task.lock().take() {
h.abort();
}
}
return 0;
}
-1
}
/// Send a message on a WebSocket connection.
/// `message` points to a buffer of `size` bytes (not null-terminated).
/// Returns 0 on success, negative on error.
#[no_mangle]
pub unsafe extern "C" fn rtcWsSend(ws_id: c_int, message: *const c_char, size: c_int) -> c_int {
if message.is_null() || size <= 0 {
return -1;
}
let bytes = std::slice::from_raw_parts(message as *const u8, size as usize);
let text = match std::str::from_utf8(bytes) {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
if !ws.connected.load(Ordering::Acquire) {
return -2;
}
match ws.tx.send(text) {
Ok(_) => return 0,
Err(_) => return -2,
}
}
}
-1
}
/// Non-blocking receive: polls for the next message.
/// If a message is available, copies it into `buffer` (up to `*size` bytes),
/// updates `*size` to the actual message length, and returns 0.
/// If no message is available, returns 1 (would-block).
/// On error returns negative.
#[no_mangle]
pub unsafe extern "C" fn rtcWsRecv(
ws_id: c_int,
buffer: *mut c_char,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return -1;
}
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if let Some(msg) = queue.pop_front() {
let buf_size = *size as usize;
let msg_bytes = msg.as_bytes();
let copy_len = msg_bytes.len().min(buf_size);
std::ptr::copy_nonoverlapping(msg_bytes.as_ptr(), buffer as *mut u8, copy_len);
*size = msg_bytes.len() as c_int;
return 0;
}
return 1; // Would-block: no messages
}
}
-1
}
/// Check if a WebSocket connection is still connected.
/// Returns 1 if connected, 0 if not, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsIsConnected(ws_id: c_int) -> c_int {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
return if ws.connected.load(Ordering::Acquire) { 1 } else { 0 };
}
}
-1
}

573
deps/rustrtc-capi/tests/loopback.rs vendored Normal file
View File

@@ -0,0 +1,573 @@
//! Rust-side integration test: two PeerConnections exchange SDP/ICE and
//! send messages over a DataChannel.
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::Arc;
use std::time::Duration;
// Use the crate's C API functions directly (rlib link)
use datachannel::*;
// Re-declare the #[repr(C)] types for test use (must match types.rs layout)
#[repr(C)]
struct TestConfiguration {
ice_servers: *const *const c_char,
ice_servers_count: c_int,
proxy_server: *const c_char,
bind_address: *const c_char,
certificate_type: c_int,
ice_transport_policy: c_int,
enable_ice_tcp: bool,
enable_ice_udp_mux: bool,
disable_auto_negotiation: bool,
force_media_transport: bool,
port_range_begin: u16,
port_range_end: u16,
mtu: c_int,
max_message_size: c_int,
}
#[repr(C)]
struct TestReliability {
unordered: bool,
unreliable: bool,
max_packet_life_time: u32,
max_retransmits: u32,
}
#[repr(C)]
struct TestDataChannelInit {
reliability: TestReliability,
protocol: *const c_char,
negotiated: bool,
manual_stream: bool,
stream: u16,
}
impl Default for TestConfiguration {
fn default() -> Self {
Self {
ice_servers: std::ptr::null(),
ice_servers_count: 0,
proxy_server: std::ptr::null(),
bind_address: std::ptr::null(),
certificate_type: 0,
ice_transport_policy: 0,
enable_ice_tcp: false,
enable_ice_udp_mux: false,
disable_auto_negotiation: false,
force_media_transport: false,
port_range_begin: 0,
port_range_end: 0,
mtu: 0,
max_message_size: 0,
}
}
}
// ---------------------------------------------------------------------------
// Shared test state
// ---------------------------------------------------------------------------
struct TestState {
sdp: parking_lot::Mutex<Option<String>>,
sdp_type: parking_lot::Mutex<Option<String>>,
candidates: parking_lot::Mutex<Vec<String>>,
gathering_complete: AtomicBool,
dc_open: AtomicBool,
dc_id: AtomicI32,
recv_messages: parking_lot::Mutex<Vec<Vec<u8>>>,
}
impl TestState {
fn new() -> Self {
Self {
sdp: parking_lot::Mutex::new(None),
sdp_type: parking_lot::Mutex::new(None),
candidates: parking_lot::Mutex::new(Vec::new()),
gathering_complete: AtomicBool::new(false),
dc_open: AtomicBool::new(false),
dc_id: AtomicI32::new(-1),
recv_messages: parking_lot::Mutex::new(Vec::new()),
}
}
}
// ---------------------------------------------------------------------------
// C callbacks
// ---------------------------------------------------------------------------
unsafe extern "C" fn on_description(
_pc: c_int,
sdp: *const c_char,
sdp_type: *const c_char,
ptr: *mut c_void,
) {
let state = &*(ptr as *const TestState);
let s = CStr::from_ptr(sdp).to_str().unwrap().to_string();
let t = CStr::from_ptr(sdp_type).to_str().unwrap().to_string();
*state.sdp.lock() = Some(s);
*state.sdp_type.lock() = Some(t);
}
unsafe extern "C" fn on_candidate(
_pc: c_int,
cand: *const c_char,
_mid: *const c_char,
ptr: *mut c_void,
) {
let state = &*(ptr as *const TestState);
let c = CStr::from_ptr(cand).to_str().unwrap().to_string();
state.candidates.lock().push(c);
}
unsafe extern "C" fn on_state_change(_pc: c_int, _state: c_int, _ptr: *mut c_void) {}
unsafe extern "C" fn on_gathering_state(_pc: c_int, state: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
if state == 2 {
ts.gathering_complete.store(true, Ordering::Release);
}
}
unsafe extern "C" fn on_data_channel(_pc: c_int, dc: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_id.store(dc, Ordering::Release);
rtcSetOpenCallback(dc, Some(on_open));
rtcSetClosedCallback(dc, Some(on_closed));
rtcSetErrorCallback(dc, Some(on_error));
rtcSetMessageCallback(dc, Some(on_message));
rtcSetUserPointer(dc, ptr);
}
unsafe extern "C" fn on_open(_id: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_open.store(true, Ordering::Release);
}
unsafe extern "C" fn on_closed(_id: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_open.store(false, Ordering::Release);
}
unsafe extern "C" fn on_error(_id: c_int, _err: *const c_char, _ptr: *mut c_void) {}
unsafe extern "C" fn on_message(_id: c_int, data: *const u8, size: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
if size > 0 {
let bytes = std::slice::from_raw_parts(data, size as usize).to_vec();
ts.recv_messages.lock().push(bytes);
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn wait_for(flag: &AtomicBool, timeout: Duration) -> bool {
let start = std::time::Instant::now();
while !flag.load(Ordering::Acquire) {
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
true
}
fn wait_for_sdp(state: &TestState, timeout: Duration) -> bool {
let start = std::time::Instant::now();
loop {
if state.sdp.lock().is_some() {
return true;
}
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn wait_for_recv(state: &TestState, timeout: Duration) -> bool {
let start = std::time::Instant::now();
loop {
if !state.recv_messages.lock().is_empty() {
return true;
}
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn default_dc_init() -> TestDataChannelInit {
TestDataChannelInit {
reliability: TestReliability {
unordered: false,
unreliable: false,
max_packet_life_time: 0,
max_retransmits: 0,
},
protocol: std::ptr::null(),
negotiated: false,
manual_stream: false,
stream: 0,
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[test]
fn test_preload_cleanup() {
unsafe {
rtcPreload();
rtcCleanup();
}
}
#[test]
fn test_create_pc_and_dc() {
unsafe {
rtcPreload();
let config = TestConfiguration::default();
let pc = rtcCreatePeerConnection(&config as *const _ as *const _);
assert!(pc > 0, "PC ID should be positive, got {pc}");
let label = CString::new("test").unwrap();
let init = default_dc_init();
let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _);
assert!(dc > 0, "DC ID should be positive, got {dc}");
rtcDeleteDataChannel(dc);
rtcClosePeerConnection(pc);
rtcDeletePeerConnection(pc);
rtcCleanup();
}
}
#[test]
fn test_sdp_generation() {
unsafe {
rtcPreload();
let alice_state = Arc::new(TestState::new());
let config = TestConfiguration::default();
let pc = rtcCreatePeerConnection(&config as *const _ as *const _);
let ptr = Arc::as_ptr(&alice_state) as *mut c_void;
rtcSetUserPointer(pc, ptr);
rtcSetLocalDescriptionCallback(pc, Some(on_description));
rtcSetLocalCandidateCallback(pc, Some(on_candidate));
rtcSetGatheringStateChangeCallback(pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _);
assert!(dc > 0);
rtcSetUserPointer(dc, ptr);
rtcSetOpenCallback(dc, Some(on_open));
rtcSetMessageCallback(dc, Some(on_message));
// Wait for SDP offer
assert!(
wait_for_sdp(&alice_state, Duration::from_secs(10)),
"Should generate SDP offer"
);
let sdp = alice_state.sdp.lock().clone().unwrap();
let sdp_type = alice_state.sdp_type.lock().clone().unwrap();
println!("SDP type: {sdp_type}");
println!("SDP length: {}", sdp.len());
assert_eq!(sdp_type, "offer");
assert!(sdp.contains("v=0"), "SDP should contain v=0");
rtcDeleteDataChannel(dc);
rtcClosePeerConnection(pc);
rtcDeletePeerConnection(pc);
rtcCleanup();
}
}
#[test]
fn test_loopback_exchange() {
unsafe {
rtcPreload();
let timeout = Duration::from_secs(15);
// --- Alice (offerer) ---
let alice = Arc::new(TestState::new());
let alice_config = TestConfiguration::default();
let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _);
let alice_ptr = Arc::as_ptr(&alice) as *mut c_void;
rtcSetUserPointer(alice_pc, alice_ptr);
rtcSetLocalDescriptionCallback(alice_pc, Some(on_description));
rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate));
rtcSetStateChangeCallback(alice_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let alice_dc =
rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _);
assert!(alice_dc > 0);
rtcSetUserPointer(alice_dc, alice_ptr);
rtcSetOpenCallback(alice_dc, Some(on_open));
rtcSetClosedCallback(alice_dc, Some(on_closed));
rtcSetErrorCallback(alice_dc, Some(on_error));
rtcSetMessageCallback(alice_dc, Some(on_message));
// Wait for Alice's offer
assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer");
let alice_sdp = alice.sdp.lock().clone().unwrap();
assert_eq!(alice.sdp_type.lock().clone().unwrap(), "offer");
println!("Alice offer SDP ({} bytes)", alice_sdp.len());
// Wait for Alice's gathering to complete
assert!(
wait_for(&alice.gathering_complete, timeout),
"Alice gathering should complete"
);
println!(
"Alice candidates: {}",
alice.candidates.lock().len()
);
// --- Bob (answerer) ---
let bob = Arc::new(TestState::new());
let bob_config = TestConfiguration::default();
let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _);
let bob_ptr = Arc::as_ptr(&bob) as *mut c_void;
rtcSetUserPointer(bob_pc, bob_ptr);
rtcSetLocalDescriptionCallback(bob_pc, Some(on_description));
rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate));
rtcSetStateChangeCallback(bob_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state));
rtcSetDataChannelCallback(bob_pc, Some(on_data_channel));
// Bob sets Alice's offer as remote description
let alice_sdp_c = CString::new(alice_sdp).unwrap();
let offer_type = CString::new("offer").unwrap();
let res = rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr());
assert_eq!(res, 0, "setRemoteDescription should succeed");
// Wait for Bob's answer
assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer");
let bob_sdp = bob.sdp.lock().clone().unwrap();
assert_eq!(bob.sdp_type.lock().clone().unwrap(), "answer");
println!("Bob answer SDP ({} bytes)", bob_sdp.len());
// Wait for Bob's gathering
assert!(
wait_for(&bob.gathering_complete, timeout),
"Bob gathering should complete"
);
println!("Bob candidates: {}", bob.candidates.lock().len());
// Exchange SDP: Alice receives Bob's answer
let bob_sdp_c = CString::new(bob_sdp).unwrap();
let answer_type = CString::new("answer").unwrap();
let res = rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr());
assert_eq!(res, 0);
// Exchange ICE candidates
let alice_cands: Vec<String> = alice.candidates.lock().clone();
let bob_cands: Vec<String> = bob.candidates.lock().clone();
for c in &alice_cands {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null());
}
for c in &bob_cands {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null());
}
// Wait for DataChannels to open
assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open");
println!("Alice DC open");
let bob_dc = bob.dc_id.load(Ordering::Acquire);
assert!(bob_dc > 0, "Bob should receive incoming DC, got {bob_dc}");
assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open");
println!("Bob DC open");
// --- Send message: Alice → Bob ---
let msg = b"hello from alice";
let res = rtcSendMessage(alice_dc, msg.as_ptr(), msg.len() as c_int);
assert_eq!(res, 0, "send should succeed");
assert!(wait_for_recv(&bob, timeout), "Bob should receive message");
let received = bob.recv_messages.lock().first().unwrap().clone();
assert_eq!(received, msg.to_vec());
println!("Bob received: {:?}", String::from_utf8_lossy(&received));
// --- Send message: Bob → Alice ---
let reply = b"hello from bob";
let res = rtcSendMessage(bob_dc, reply.as_ptr(), reply.len() as c_int);
assert_eq!(res, 0);
assert!(wait_for_recv(&alice, timeout), "Alice should receive reply");
let received = alice.recv_messages.lock().first().unwrap().clone();
assert_eq!(received, reply.to_vec());
println!(
"Alice received: {:?}",
String::from_utf8_lossy(&received)
);
// Cleanup
rtcDeleteDataChannel(alice_dc);
rtcDeleteDataChannel(bob_dc);
rtcClosePeerConnection(alice_pc);
rtcDeletePeerConnection(alice_pc);
rtcClosePeerConnection(bob_pc);
rtcDeletePeerConnection(bob_pc);
rtcCleanup();
}
}
/// Test large message delivery at various chunk sizes (32KB, 64KB, 128KB, 256KB).
/// Validates 100% delivery at each size to find the SCTP drop threshold.
#[test]
fn test_large_message_delivery() {
unsafe {
rtcPreload();
let timeout = Duration::from_secs(30);
// --- Alice (offerer) ---
let alice = Arc::new(TestState::new());
let alice_config = TestConfiguration::default();
let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _);
let alice_ptr = Arc::as_ptr(&alice) as *mut c_void;
rtcSetUserPointer(alice_pc, alice_ptr);
rtcSetLocalDescriptionCallback(alice_pc, Some(on_description));
rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate));
rtcSetStateChangeCallback(alice_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let alice_dc =
rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _);
assert!(alice_dc > 0);
rtcSetUserPointer(alice_dc, alice_ptr);
rtcSetOpenCallback(alice_dc, Some(on_open));
rtcSetClosedCallback(alice_dc, Some(on_closed));
rtcSetMessageCallback(alice_dc, Some(on_message));
assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer");
let alice_sdp = alice.sdp.lock().clone().unwrap();
assert!(
wait_for(&alice.gathering_complete, timeout),
"Alice gathering should complete"
);
// --- Bob (answerer) ---
let bob = Arc::new(TestState::new());
let bob_config = TestConfiguration::default();
let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _);
let bob_ptr = Arc::as_ptr(&bob) as *mut c_void;
rtcSetUserPointer(bob_pc, bob_ptr);
rtcSetLocalDescriptionCallback(bob_pc, Some(on_description));
rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate));
rtcSetStateChangeCallback(bob_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state));
rtcSetDataChannelCallback(bob_pc, Some(on_data_channel));
let alice_sdp_c = CString::new(alice_sdp).unwrap();
let offer_type = CString::new("offer").unwrap();
rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr());
assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer");
let bob_sdp = bob.sdp.lock().clone().unwrap();
assert!(
wait_for(&bob.gathering_complete, timeout),
"Bob gathering should complete"
);
let bob_sdp_c = CString::new(bob_sdp).unwrap();
let answer_type = CString::new("answer").unwrap();
rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr());
// Exchange ICE candidates
for c in alice.candidates.lock().iter() {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null());
}
for c in bob.candidates.lock().iter() {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null());
}
assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open");
let bob_dc = bob.dc_id.load(Ordering::Acquire);
assert!(bob_dc > 0);
assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open");
// --- Test message delivery at various chunk sizes ---
let sizes: &[usize] = &[32 * 1024, 64 * 1024, 128 * 1024, 256 * 1024];
let msg_count = 100;
for &chunk_size in sizes {
// Clear previous messages
bob.recv_messages.lock().clear();
let payload: Vec<u8> = (0..chunk_size).map(|i| (i % 256) as u8).collect();
for _ in 0..msg_count {
let res = rtcSendMessage(alice_dc, payload.as_ptr(), payload.len() as c_int);
assert_eq!(res, 0, "send should succeed for {chunk_size}B messages");
}
// Wait for all messages to arrive (generous timeout)
let wait_start = std::time::Instant::now();
loop {
let count = bob.recv_messages.lock().len();
if count >= msg_count {
break;
}
if wait_start.elapsed() > Duration::from_secs(20) {
println!(
"SCTP drop threshold found: {chunk_size}B — only {count}/{msg_count} delivered"
);
break;
}
std::thread::sleep(Duration::from_millis(50));
}
let received = bob.recv_messages.lock().len();
println!(
"Chunk size {chunk_size}B: {received}/{msg_count} messages delivered ({}%)",
received * 100 / msg_count
);
// Verify payload integrity for received messages
for msg in bob.recv_messages.lock().iter() {
assert_eq!(msg.len(), chunk_size, "Message size mismatch");
assert_eq!(msg[0], 0u8, "First byte should be 0");
assert_eq!(msg[chunk_size - 1], ((chunk_size - 1) % 256) as u8);
}
}
// Cleanup
rtcDeleteDataChannel(alice_dc);
rtcDeleteDataChannel(bob_dc);
rtcClosePeerConnection(alice_pc);
rtcDeletePeerConnection(alice_pc);
rtcClosePeerConnection(bob_pc);
rtcDeletePeerConnection(bob_pc);
rtcCleanup();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,653 @@
//! DHT-based WebRTC Signaling
//!
//! Exchanges WebRTC SDP offers/answers and ICE candidates via the DHT,
//! eliminating the need for a separate signaling server.
//!
//! Pattern: Both peers derive the same base signaling key from their public keys
//! (order-independent). Each peer stores its messages at a key derived from
//! the base key + their own pubkey, and reads the other peer's messages from
//! the base key + the other's pubkey. This prevents collisions.
//!
//! Flow (Alice → Bob):
//! 1. Alice computes signaling_key = computeSignalingKey(alice_pk, bob_pk)
//! 2. Alice stores her offer at SHA-256(signaling_key || alice_pk || "offer")
//! 3. Bob polls for Alice's offer at the same key
//! 4. Bob stores his answer at SHA-256(signaling_key || bob_pk || "answer")
//! 5. Alice polls for Bob's answer at the same key
//! 6. ICE candidates exchanged similarly with versioned keys
const std = @import("std");
const platform_time = @import("time.zig");
const Allocator = std.mem.Allocator;
const signaling = @import("webrtc_signaling.zig");
pub const SignalingMessage = signaling.SignalingMessage;
pub const MessageType = signaling.MessageType;
pub const computeSignalingKey = signaling.computeSignalingKey;
/// DHT interface — caller provides store/find functions.
/// Avoids circular dependency with the p2p module.
pub const DHTOps = struct {
context: *anyopaque,
storeFn: *const fn (ctx: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void,
findFn: *const fn (ctx: *anyopaque, key: [32]u8) anyerror!?[]u8,
};
/// Default TTL for signaling messages (60 seconds — connection should complete faster).
pub const DEFAULT_SIGNALING_TTL: u32 = 60;
/// Default timeout for waiting for a signaling response (30 seconds).
pub const DEFAULT_WAIT_TIMEOUT_MS: u64 = 30_000;
/// Default poll interval when waiting for signaling messages.
pub const DEFAULT_POLL_INTERVAL_MS: u64 = 200;
/// Derive a directional signaling DHT key for a specific message type.
/// key = SHA-256(signaling_key || publisher_pubkey || label)
/// This ensures the offerer and answerer store at different keys.
pub fn deriveSignalingSubkey(signaling_key: [32]u8, publisher_pubkey: [32]u8, label: []const u8) [32]u8 {
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
hasher.update(&signaling_key);
hasher.update(&publisher_pubkey);
hasher.update(label);
return hasher.finalResult();
}
/// Derive a versioned ICE candidate DHT key from a base ICE key + version number.
pub fn deriveIceVersionKey(base_ice_key: [32]u8, version: u32) [32]u8 {
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
hasher.update(&base_ice_key);
var version_bytes: [4]u8 = undefined;
std.mem.writeInt(u32, &version_bytes, version, .little);
hasher.update(&version_bytes);
return hasher.finalResult();
}
/// WebRTC DHT Signaling session — manages SDP/ICE exchange for one connection.
pub const SignalingSession = struct {
allocator: Allocator,
dht: DHTOps,
our_pubkey: [32]u8,
their_pubkey: [32]u8,
/// Pre-computed base signaling key (order-independent).
signaling_key: [32]u8,
/// TTL for DHT store operations.
ttl: u32,
/// Next version to store when using trickle ICE (storeCandidateBatch).
ice_send_version: u32 = 0,
/// Next version to read when using trickle ICE (findNextCandidateBatch).
ice_recv_version: u32 = 0,
pub fn init(
allocator: Allocator,
dht: DHTOps,
our_pubkey: [32]u8,
their_pubkey: [32]u8,
) SignalingSession {
return .{
.allocator = allocator,
.dht = dht,
.our_pubkey = our_pubkey,
.their_pubkey = their_pubkey,
.signaling_key = computeSignalingKey(our_pubkey, their_pubkey),
.ttl = DEFAULT_SIGNALING_TTL,
};
}
// =========================================================================
// Store operations (publish our signaling data)
// =========================================================================
/// Store our SDP offer in the DHT.
pub fn storeOffer(self: *SignalingSession, sdp_payload: []const u8) !void {
const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "offer");
const msg = SignalingMessage{
.msg_type = .offer,
.from_pubkey = self.our_pubkey,
.timestamp_ms = platform_time.milliTimestamp(),
.payload = sdp_payload,
.signature = [_]u8{0} ** 64, // TODO: sign with Ed25519
};
const wire = try msg.serialize(self.allocator);
defer self.allocator.free(wire);
try self.dht.storeFn(self.dht.context, key, wire, self.ttl);
}
/// Store our SDP answer in the DHT.
pub fn storeAnswer(self: *SignalingSession, sdp_payload: []const u8) !void {
const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "answer");
const msg = SignalingMessage{
.msg_type = .answer,
.from_pubkey = self.our_pubkey,
.timestamp_ms = platform_time.milliTimestamp(),
.payload = sdp_payload,
.signature = [_]u8{0} ** 64, // TODO: sign with Ed25519
};
const wire = try msg.serialize(self.allocator);
defer self.allocator.free(wire);
try self.dht.storeFn(self.dht.context, key, wire, self.ttl);
}
/// Store our ICE candidates in the DHT (batched as one message).
pub fn storeCandidates(self: *SignalingSession, candidates_payload: []const u8) !void {
const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice");
const msg = SignalingMessage{
.msg_type = .ice_candidate,
.from_pubkey = self.our_pubkey,
.timestamp_ms = platform_time.milliTimestamp(),
.payload = candidates_payload,
.signature = [_]u8{0} ** 64,
};
const wire = try msg.serialize(self.allocator);
defer self.allocator.free(wire);
try self.dht.storeFn(self.dht.context, key, wire, self.ttl);
}
/// Store a batch of ICE candidates at a versioned key (trickle ICE).
/// Each call increments the version, so candidates are stored at
/// ice-0, ice-1, etc. The peer reads them in order via findNextCandidateBatch.
pub fn storeCandidateBatch(self: *SignalingSession, candidates_payload: []const u8) !void {
const base_key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice");
const versioned_key = deriveIceVersionKey(base_key, self.ice_send_version);
const msg = SignalingMessage{
.msg_type = .ice_candidate,
.from_pubkey = self.our_pubkey,
.timestamp_ms = platform_time.milliTimestamp(),
.payload = candidates_payload,
.signature = [_]u8{0} ** 64,
};
const wire = try msg.serialize(self.allocator);
defer self.allocator.free(wire);
try self.dht.storeFn(self.dht.context, versioned_key, wire, self.ttl);
self.ice_send_version += 1;
}
// =========================================================================
// Find operations (retrieve peer's signaling data)
// =========================================================================
/// Find the peer's SDP offer in the DHT (non-blocking).
/// Returns the deserialized SignalingMessage or null if not found.
/// Caller does NOT own the payload — it borrows from the returned wire data.
pub fn findOffer(self: *SignalingSession) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer");
return self.findMessage(key);
}
/// Find the peer's SDP answer in the DHT (non-blocking).
pub fn findAnswer(self: *SignalingSession) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer");
return self.findMessage(key);
}
/// Find the peer's ICE candidates in the DHT (non-blocking).
pub fn findCandidates(self: *SignalingSession) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice");
return self.findMessage(key);
}
/// Find the next batch of trickle ICE candidates from the peer (non-blocking).
/// Returns the next unseen batch, or null if no new batch is available.
/// Automatically advances the receive version on success.
pub fn findNextCandidateBatch(self: *SignalingSession) !?SignalingMessage {
const base_key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice");
const versioned_key = deriveIceVersionKey(base_key, self.ice_recv_version);
const result = try self.findMessage(versioned_key);
if (result != null) {
self.ice_recv_version += 1;
}
return result;
}
/// Drain all available trickle ICE candidate batches from the peer (non-blocking).
/// Returns all unseen batches as a slice. Caller owns the returned slice.
/// Advances the receive version past all returned batches.
pub fn drainCandidateBatches(self: *SignalingSession) ![]SignalingMessage {
var batches: std.ArrayList(SignalingMessage) = .{};
errdefer batches.deinit(self.allocator);
while (try self.findNextCandidateBatch()) |msg| {
try batches.append(self.allocator, msg);
}
return batches.toOwnedSlice(self.allocator);
}
fn findMessage(self: *SignalingSession, key: [32]u8) !?SignalingMessage {
const value = self.dht.findFn(self.dht.context, key) catch return null;
if (value) |v| {
defer self.allocator.free(v);
return SignalingMessage.deserialize(v) catch null;
}
return null;
}
// =========================================================================
// Blocking wait operations (poll-based)
// =========================================================================
/// Wait for the peer's SDP offer (blocking with timeout).
/// Polls the DHT at regular intervals. MUST call p2p.update() externally
/// if the DHT requires it for network I/O.
pub fn waitForOffer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer");
return self.waitForMessage(key, timeout_ms);
}
/// Wait for the peer's SDP answer (blocking with timeout).
pub fn waitForAnswer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer");
return self.waitForMessage(key, timeout_ms);
}
/// Wait for the peer's ICE candidates (blocking with timeout).
pub fn waitForCandidates(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage {
const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice");
return self.waitForMessage(key, timeout_ms);
}
/// Wait for the next trickle ICE candidate batch (blocking with timeout).
/// Returns the next unseen batch, or null on timeout.
pub fn waitForNextCandidateBatch(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage {
var elapsed: u64 = 0;
while (elapsed < timeout_ms) {
if (try self.findNextCandidateBatch()) |msg| {
return msg;
}
platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms);
elapsed += DEFAULT_POLL_INTERVAL_MS;
}
return null;
}
fn waitForMessage(self: *SignalingSession, key: [32]u8, timeout_ms: u64) !?SignalingMessage {
var elapsed: u64 = 0;
while (elapsed < timeout_ms) {
if (try self.findMessage(key)) |msg| {
return msg;
}
platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms);
elapsed += DEFAULT_POLL_INTERVAL_MS;
}
return null;
}
};
// ============================================================================
// Tests
// ============================================================================
test "deriveSignalingSubkey: different labels produce different keys" {
const base = [_]u8{0xAA} ** 32;
const pubkey = [_]u8{0xBB} ** 32;
const offer_key = deriveSignalingSubkey(base, pubkey, "offer");
const answer_key = deriveSignalingSubkey(base, pubkey, "answer");
const ice_key = deriveSignalingSubkey(base, pubkey, "ice");
try std.testing.expect(!std.mem.eql(u8, &offer_key, &answer_key));
try std.testing.expect(!std.mem.eql(u8, &offer_key, &ice_key));
try std.testing.expect(!std.mem.eql(u8, &answer_key, &ice_key));
}
test "deriveSignalingSubkey: different pubkeys produce different keys" {
const base = [_]u8{0xAA} ** 32;
const alice_pk = [_]u8{0x01} ** 32;
const bob_pk = [_]u8{0x02} ** 32;
const alice_offer = deriveSignalingSubkey(base, alice_pk, "offer");
const bob_offer = deriveSignalingSubkey(base, bob_pk, "offer");
try std.testing.expect(!std.mem.eql(u8, &alice_offer, &bob_offer));
}
test "SignalingSession: store and find with mock DHT" {
const allocator = std.testing.allocator;
// Simple in-memory DHT mock
const MockDHT = struct {
store: std.AutoHashMap([32]u8, []u8),
allocator: Allocator,
fn init(alloc: Allocator) @This() {
return .{
.store = std.AutoHashMap([32]u8, []u8).init(alloc),
.allocator = alloc,
};
}
fn deinit(self: *@This()) void {
var iter = self.store.valueIterator();
while (iter.next()) |v| {
self.allocator.free(v.*);
}
self.store.deinit();
}
fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void {
const self: *@This() = @ptrCast(@alignCast(ctx));
// Replace existing value if any
if (self.store.fetchRemove(key)) |kv| {
self.allocator.free(kv.value);
}
const copy = try self.allocator.dupe(u8, value);
try self.store.put(key, copy);
}
fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.get(key)) |v| {
return try self.allocator.dupe(u8, v);
}
return null;
}
fn ops(self: *@This()) DHTOps {
return .{
.context = @ptrCast(self),
.storeFn = storeFn,
.findFn = findFn,
};
}
};
var mock = MockDHT.init(allocator);
defer mock.deinit();
const alice_pk = [_]u8{0x01} ** 32;
const bob_pk = [_]u8{0x02} ** 32;
// Alice's session
var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk);
// Bob's session
var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk);
// Verify both compute the same signaling key
try std.testing.expectEqualSlices(u8, &alice.signaling_key, &bob.signaling_key);
// Alice stores her offer
try alice.storeOffer("v=0\r\no=alice SDP");
// Bob finds Alice's offer
const offer = try bob.findOffer();
try std.testing.expect(offer != null);
try std.testing.expectEqual(MessageType.offer, offer.?.msg_type);
try std.testing.expectEqualSlices(u8, &alice_pk, &offer.?.from_pubkey);
// Bob stores his answer
try bob.storeAnswer("v=0\r\no=bob SDP answer");
// Alice finds Bob's answer
const answer = try alice.findAnswer();
try std.testing.expect(answer != null);
try std.testing.expectEqual(MessageType.answer, answer.?.msg_type);
try std.testing.expectEqualSlices(u8, &bob_pk, &answer.?.from_pubkey);
// Alice stores her ICE candidates
try alice.storeCandidates("candidate:1 1 UDP 2130706431 127.0.0.1 12345 typ host");
// Bob finds Alice's candidates
const ice = try bob.findCandidates();
try std.testing.expect(ice != null);
try std.testing.expectEqual(MessageType.ice_candidate, ice.?.msg_type);
// Verify Alice can't find an offer from Bob (Bob never stored one)
const wrong = try alice.findOffer();
// alice.findOffer() looks for bob's offer, but Bob only stored an answer
try std.testing.expect(wrong == null);
}
test "SignalingSession: findOffer returns null when DHT empty" {
const allocator = std.testing.allocator;
const EmptyDHT = struct {
fn storeFn(_: *anyopaque, _: [32]u8, _: []const u8, _: u32) anyerror!void {}
fn findFn(_: *anyopaque, _: [32]u8) anyerror!?[]u8 {
return null;
}
};
var dummy: u8 = 0;
var session = SignalingSession.init(allocator, .{
.context = @ptrCast(&dummy),
.storeFn = EmptyDHT.storeFn,
.findFn = EmptyDHT.findFn,
}, [_]u8{0x01} ** 32, [_]u8{0x02} ** 32);
const result = try session.findOffer();
try std.testing.expect(result == null);
}
test "deriveIceVersionKey: different versions produce different keys" {
const base = [_]u8{0xCC} ** 32;
const key0 = deriveIceVersionKey(base, 0);
const key1 = deriveIceVersionKey(base, 1);
const key2 = deriveIceVersionKey(base, 2);
try std.testing.expect(!std.mem.eql(u8, &key0, &key1));
try std.testing.expect(!std.mem.eql(u8, &key0, &key2));
try std.testing.expect(!std.mem.eql(u8, &key1, &key2));
}
test "trickle ICE: store and find versioned candidate batches" {
const allocator = std.testing.allocator;
const MockDHT = struct {
store: std.AutoHashMap([32]u8, []u8),
alloc: Allocator,
fn init(alloc: Allocator) @This() {
return .{
.store = std.AutoHashMap([32]u8, []u8).init(alloc),
.alloc = alloc,
};
}
fn deinit(self: *@This()) void {
var iter = self.store.valueIterator();
while (iter.next()) |v| self.alloc.free(v.*);
self.store.deinit();
}
fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value);
const copy = try self.alloc.dupe(u8, value);
try self.store.put(key, copy);
}
fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v);
return null;
}
fn ops(self: *@This()) DHTOps {
return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn };
}
};
var mock = MockDHT.init(allocator);
defer mock.deinit();
const alice_pk = [_]u8{0x01} ** 32;
const bob_pk = [_]u8{0x02} ** 32;
var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk);
var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk);
// Alice stores 3 batches of trickle ICE candidates
try alice.storeCandidateBatch("candidate:1 1 UDP 2130706431 192.168.1.1 10000 typ host");
try alice.storeCandidateBatch("candidate:2 1 UDP 1694498815 10.0.0.1 10001 typ srflx");
try alice.storeCandidateBatch("candidate:3 1 UDP 16777215 1.2.3.4 10002 typ relay");
// Verify Alice's send version advanced
try std.testing.expectEqual(@as(u32, 3), alice.ice_send_version);
// Bob hasn't read any yet
try std.testing.expectEqual(@as(u32, 0), bob.ice_recv_version);
// Bob reads batch 0
const batch0 = try bob.findNextCandidateBatch();
try std.testing.expect(batch0 != null);
try std.testing.expectEqual(MessageType.ice_candidate, batch0.?.msg_type);
try std.testing.expectEqual(@as(u32, 1), bob.ice_recv_version);
// Bob reads batch 1
const batch1 = try bob.findNextCandidateBatch();
try std.testing.expect(batch1 != null);
try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version);
// Bob reads batch 2
const batch2 = try bob.findNextCandidateBatch();
try std.testing.expect(batch2 != null);
try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version);
// No more batches
const batch3 = try bob.findNextCandidateBatch();
try std.testing.expect(batch3 == null);
// Version should NOT advance on null
try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version);
}
test "trickle ICE: drainCandidateBatches returns all unseen" {
const allocator = std.testing.allocator;
const MockDHT = struct {
store: std.AutoHashMap([32]u8, []u8),
alloc: Allocator,
fn init(alloc: Allocator) @This() {
return .{
.store = std.AutoHashMap([32]u8, []u8).init(alloc),
.alloc = alloc,
};
}
fn deinit(self: *@This()) void {
var iter = self.store.valueIterator();
while (iter.next()) |v| self.alloc.free(v.*);
self.store.deinit();
}
fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value);
const copy = try self.alloc.dupe(u8, value);
try self.store.put(key, copy);
}
fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v);
return null;
}
fn ops(self: *@This()) DHTOps {
return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn };
}
};
var mock = MockDHT.init(allocator);
defer mock.deinit();
const alice_pk = [_]u8{0x01} ** 32;
const bob_pk = [_]u8{0x02} ** 32;
var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk);
var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk);
// Alice stores 4 batches
try alice.storeCandidateBatch("candidate:host");
try alice.storeCandidateBatch("candidate:srflx");
try alice.storeCandidateBatch("candidate:relay");
try alice.storeCandidateBatch("candidate:prflx");
// Bob drains all at once
const batches = try bob.drainCandidateBatches();
defer allocator.free(batches);
try std.testing.expectEqual(@as(usize, 4), batches.len);
try std.testing.expectEqual(@as(u32, 4), bob.ice_recv_version);
// Drain again — should be empty
const empty = try bob.drainCandidateBatches();
defer allocator.free(empty);
try std.testing.expectEqual(@as(usize, 0), empty.len);
}
test "trickle ICE: bidirectional exchange" {
const allocator = std.testing.allocator;
const MockDHT = struct {
store: std.AutoHashMap([32]u8, []u8),
alloc: Allocator,
fn init(alloc: Allocator) @This() {
return .{
.store = std.AutoHashMap([32]u8, []u8).init(alloc),
.alloc = alloc,
};
}
fn deinit(self: *@This()) void {
var iter = self.store.valueIterator();
while (iter.next()) |v| self.alloc.free(v.*);
self.store.deinit();
}
fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value);
const copy = try self.alloc.dupe(u8, value);
try self.store.put(key, copy);
}
fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v);
return null;
}
fn ops(self: *@This()) DHTOps {
return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn };
}
};
var mock = MockDHT.init(allocator);
defer mock.deinit();
const alice_pk = [_]u8{0x01} ** 32;
const bob_pk = [_]u8{0x02} ** 32;
var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk);
var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk);
// Both sides trickle candidates independently
try alice.storeCandidateBatch("alice-candidate:host");
try bob.storeCandidateBatch("bob-candidate:host");
try alice.storeCandidateBatch("alice-candidate:srflx");
try bob.storeCandidateBatch("bob-candidate:srflx");
// Alice reads Bob's candidates
const alice_batches = try alice.drainCandidateBatches();
defer allocator.free(alice_batches);
try std.testing.expectEqual(@as(usize, 2), alice_batches.len);
// Verify they came from Bob
for (alice_batches) |batch| {
try std.testing.expectEqualSlices(u8, &bob_pk, &batch.from_pubkey);
}
// Bob reads Alice's candidates
const bob_batches = try bob.drainCandidateBatches();
defer allocator.free(bob_batches);
try std.testing.expectEqual(@as(usize, 2), bob_batches.len);
// Verify they came from Alice
for (bob_batches) |batch| {
try std.testing.expectEqualSlices(u8, &alice_pk, &batch.from_pubkey);
}
// Both versions advanced independently
try std.testing.expectEqual(@as(u32, 2), alice.ice_send_version);
try std.testing.expectEqual(@as(u32, 2), alice.ice_recv_version);
try std.testing.expectEqual(@as(u32, 2), bob.ice_send_version);
try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version);
}

View File

@@ -0,0 +1,880 @@
//! Native WebRTC transport via runtime-loaded libdatachannel C API.
//!
//! Provides DataChannel-based transport for peer-to-peer communication.
//! The library is loaded at runtime via dlopen — if the dylib is present
//! next to the executable (or in WEBRTC_LIB_PATH), WebRTC is available.
//! If not, the binary still works with TCP/UDP only.
//!
//! Callbacks from the WebRTC library fire from an internal thread — all
//! state is accessed atomically or via mutex-protected queues.
const std = @import("std");
const Mutex = @import("sync").Mutex;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core");
const CoreTransport = core.transport.Transport;
const TransportState = core.transport.TransportState;
const TransportMode = core.transport.TransportMode;
const CoreError = core.errors.Error;
// ============================================================================
// libdatachannel C API bindings — runtime-loaded via dlopen
// ============================================================================
pub const rtc = struct {
// Error codes
pub const ERR_SUCCESS: c_int = 0;
pub const ERR_INVALID: c_int = -1;
pub const ERR_FAILURE: c_int = -2;
pub const ERR_NOT_AVAIL: c_int = -3;
pub const ERR_TOO_SMALL: c_int = -4;
// State enums
pub const State = enum(c_int) {
new = 0,
connecting = 1,
connected = 2,
disconnected = 3,
failed = 4,
closed = 5,
};
pub const IceState = enum(c_int) {
new = 0,
checking = 1,
connected = 2,
completed = 3,
failed = 4,
disconnected = 5,
closed = 6,
};
pub const GatheringState = enum(c_int) {
new = 0,
in_progress = 1,
complete = 2,
};
pub const LogLevel = enum(c_int) {
none = 0,
fatal = 1,
err = 2,
warning = 3,
info = 4,
debug = 5,
verbose = 6,
};
pub const CertificateType = enum(c_int) {
default = 0,
ecdsa = 1,
rsa = 2,
};
pub const TransportPolicy = enum(c_int) {
all = 0,
relay = 1,
};
// Callback function types
pub const DescriptionCallbackFunc = *const fn (pc: c_int, sdp: [*:0]const u8, sdp_type: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void;
pub const CandidateCallbackFunc = *const fn (pc: c_int, cand: [*:0]const u8, mid: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void;
pub const StateChangeCallbackFunc = *const fn (pc: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const GatheringStateCallbackFunc = *const fn (pc: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const DataChannelCallbackFunc = *const fn (pc: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const OpenCallbackFunc = *const fn (id: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const ClosedCallbackFunc = *const fn (id: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const ErrorCallbackFunc = *const fn (id: c_int, err_msg: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void;
pub const MessageCallbackFunc = *const fn (id: c_int, message: [*]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void;
pub const LogCallbackFunc = *const fn (level: c_int, message: [*:0]const u8) callconv(.c) void;
// Configuration structs
pub const Configuration = extern struct {
iceServers: ?[*]const [*:0]const u8 = null,
iceServersCount: c_int = 0,
proxyServer: ?[*:0]const u8 = null,
bindAddress: ?[*:0]const u8 = null,
certificateType: CertificateType = .default,
iceTransportPolicy: TransportPolicy = .all,
enableIceTcp: bool = false,
enableIceUdpMux: bool = false,
disableAutoNegotiation: bool = false,
forceMediaTransport: bool = false,
portRangeBegin: u16 = 0,
portRangeEnd: u16 = 0,
mtu: c_int = 0,
maxMessageSize: c_int = 0,
};
pub const Reliability = extern struct {
unordered: bool = false,
unreliable: bool = false,
maxPacketLifeTime: c_uint = 0,
maxRetransmits: c_uint = 0,
};
pub const DataChannelInit = extern struct {
reliability: Reliability = .{},
protocol: ?[*:0]const u8 = null,
negotiated: bool = false,
manualStream: bool = false,
stream: u16 = 0,
};
pub const SctpSettings = extern struct {
recvBufferSize: c_int = 0,
sendBufferSize: c_int = 0,
maxChunksOnQueue: c_int = 0,
initialCongestionWindow: c_int = 0,
maxBurst: c_int = 0,
congestionControlModule: c_int = 0,
delayedSackTimeMs: c_int = 0,
minRetransmitTimeoutMs: c_int = 0,
maxRetransmitTimeoutMs: c_int = 0,
initialRetransmitTimeoutMs: c_int = 0,
maxRetransmitAttempts: c_int = 0,
heartbeatIntervalMs: c_int = 0,
};
// ========================================================================
// Runtime library loading
// ========================================================================
const lib_name: [:0]const u8 = switch (builtin.os.tag) {
.macos, .ios, .tvos, .watchos => "libdatachannel.dylib",
.windows => "datachannel.dll",
else => "libdatachannel.so",
};
/// Function pointer table — all symbols resolved from the dynamic library.
const Fns = struct {
// Global
rtcPreload: *const fn () callconv(.c) void,
rtcCleanup: *const fn () callconv(.c) void,
rtcInitLogger: *const fn (c_int, ?LogCallbackFunc) callconv(.c) void,
// User pointer
rtcSetUserPointer: *const fn (c_int, ?*anyopaque) callconv(.c) void,
rtcGetUserPointer: *const fn (c_int) callconv(.c) ?*anyopaque,
// PeerConnection
rtcCreatePeerConnection: *const fn (*const Configuration) callconv(.c) c_int,
rtcClosePeerConnection: *const fn (c_int) callconv(.c) c_int,
rtcDeletePeerConnection: *const fn (c_int) callconv(.c) c_int,
// PC callbacks
rtcSetLocalDescriptionCallback: *const fn (c_int, ?DescriptionCallbackFunc) callconv(.c) c_int,
rtcSetLocalCandidateCallback: *const fn (c_int, ?CandidateCallbackFunc) callconv(.c) c_int,
rtcSetStateChangeCallback: *const fn (c_int, ?StateChangeCallbackFunc) callconv(.c) c_int,
rtcSetGatheringStateChangeCallback: *const fn (c_int, ?GatheringStateCallbackFunc) callconv(.c) c_int,
rtcSetDataChannelCallback: *const fn (c_int, ?DataChannelCallbackFunc) callconv(.c) c_int,
// SDP
rtcSetLocalDescription: *const fn (c_int, ?[*:0]const u8) callconv(.c) c_int,
rtcSetRemoteDescription: *const fn (c_int, [*:0]const u8, ?[*:0]const u8) callconv(.c) c_int,
rtcAddRemoteCandidate: *const fn (c_int, [*:0]const u8, ?[*:0]const u8) callconv(.c) c_int,
rtcGetLocalDescription: *const fn (c_int, [*]u8, c_int) callconv(.c) c_int,
rtcGetRemoteDescription: *const fn (c_int, [*]u8, c_int) callconv(.c) c_int,
// DataChannel
rtcCreateDataChannel: *const fn (c_int, [*:0]const u8) callconv(.c) c_int,
rtcCreateDataChannelEx: *const fn (c_int, [*:0]const u8, *const DataChannelInit) callconv(.c) c_int,
rtcDeleteDataChannel: *const fn (c_int) callconv(.c) c_int,
// DC callbacks
rtcSetOpenCallback: *const fn (c_int, ?OpenCallbackFunc) callconv(.c) c_int,
rtcSetClosedCallback: *const fn (c_int, ?ClosedCallbackFunc) callconv(.c) c_int,
rtcSetErrorCallback: *const fn (c_int, ?ErrorCallbackFunc) callconv(.c) c_int,
rtcSetMessageCallback: *const fn (c_int, ?MessageCallbackFunc) callconv(.c) c_int,
// I/O
rtcSendMessage: *const fn (c_int, [*]const u8, c_int) callconv(.c) c_int,
rtcClose: *const fn (c_int) callconv(.c) c_int,
rtcDelete: *const fn (c_int) callconv(.c) c_int,
rtcIsOpen: *const fn (c_int) callconv(.c) bool,
rtcIsClosed: *const fn (c_int) callconv(.c) bool,
rtcGetBufferedAmount: *const fn (c_int) callconv(.c) c_int,
rtcReceiveMessage: *const fn (c_int, [*]u8, *c_int) callconv(.c) c_int,
// SCTP
rtcSetSctpSettings: *const fn (*const SctpSettings) callconv(.c) c_int,
// WebSocket signaling (optional — may not be present in all builds)
rtcWsConnect: ?*const fn ([*:0]const u8, [*:0]const u8) callconv(.c) c_int,
rtcWsDisconnect: ?*const fn (c_int) callconv(.c) c_int,
rtcWsSend: ?*const fn (c_int, [*]const u8, c_int) callconv(.c) c_int,
rtcWsRecv: ?*const fn (c_int, [*]u8, *c_int) callconv(.c) c_int,
rtcWsIsConnected: ?*const fn (c_int) callconv(.c) c_int,
};
var dynlib: if (is_wasm) ?void else ?std.DynLib = null;
var fns: Fns = undefined;
/// Attempt to load the WebRTC library. Returns true if successful.
/// Search order: WEBRTC_LIB_PATH env var, next to executable, system default.
pub fn load() bool {
if (is_wasm) return false; // No dynamic library loading on WASM
if (dynlib != null) return true;
// 1. Try WEBRTC_LIB_PATH environment variable
if (std.posix.getenv("WEBRTC_LIB_PATH")) |env_path| {
if (tryOpen(env_path)) return true;
}
// 2. Try next to the executable
if (tryLoadNextToExe()) return true;
// 3. Try system default (dlopen search paths)
if (tryOpen(lib_name)) return true;
return false;
}
/// Whether the WebRTC library is loaded and available.
pub fn isAvailable() bool {
if (is_wasm) return false;
return dynlib != null;
}
/// Unload the library (for cleanup).
pub fn unload() void {
if (is_wasm) return;
if (dynlib) |*lib| {
lib.close();
dynlib = null;
}
}
fn tryLoadNextToExe() bool {
if (is_wasm) return false;
var exe_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const exe_path = std.fs.selfExePath(&exe_path_buf) catch return false;
const exe_dir = std.fs.path.dirname(exe_path) orelse return false;
var lib_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const lib_path = std.fmt.bufPrintZ(&lib_path_buf, "{s}/{s}", .{ exe_dir, lib_name }) catch return false;
return tryOpen(lib_path);
}
fn tryOpen(path: [:0]const u8) bool {
if (is_wasm) return false;
var lib = std.DynLib.open(path) catch return false;
if (resolveAllSymbols(&lib)) |resolved| {
fns = resolved;
dynlib = lib;
return true;
}
lib.close();
return false;
}
fn resolveAllSymbols(lib: *std.DynLib) ?Fns {
if (is_wasm) return null;
var result: Fns = undefined;
inline for (std.meta.fields(Fns)) |field| {
const FieldType = field.type;
const type_info = @typeInfo(FieldType);
if (type_info == .optional) {
// Optional symbols: try lookup, set null if not found
@field(result, field.name) = lib.lookup(type_info.optional.child, field.name);
} else {
// Required symbols: fail if not found
@field(result, field.name) = lib.lookup(FieldType, field.name) orelse return null;
}
}
return result;
}
// ========================================================================
// Public wrapper functions — same call syntax as the old extern declarations
// ========================================================================
// Global
pub fn rtcPreload() void {
fns.rtcPreload();
}
pub fn rtcCleanup() void {
fns.rtcCleanup();
}
pub fn rtcInitLogger(level: LogLevel, cb: ?LogCallbackFunc) void {
fns.rtcInitLogger(@intFromEnum(level), cb);
}
// User pointer
pub fn rtcSetUserPointer(id: c_int, ptr: ?*anyopaque) void {
fns.rtcSetUserPointer(id, ptr);
}
pub fn rtcGetUserPointer(id: c_int) ?*anyopaque {
return fns.rtcGetUserPointer(id);
}
// PeerConnection
pub fn rtcCreatePeerConnection(config: *const Configuration) c_int {
return fns.rtcCreatePeerConnection(config);
}
pub fn rtcClosePeerConnection(pc: c_int) c_int {
return fns.rtcClosePeerConnection(pc);
}
pub fn rtcDeletePeerConnection(pc: c_int) c_int {
return fns.rtcDeletePeerConnection(pc);
}
// PC callbacks
pub fn rtcSetLocalDescriptionCallback(pc: c_int, cb: ?DescriptionCallbackFunc) c_int {
return fns.rtcSetLocalDescriptionCallback(pc, cb);
}
pub fn rtcSetLocalCandidateCallback(pc: c_int, cb: ?CandidateCallbackFunc) c_int {
return fns.rtcSetLocalCandidateCallback(pc, cb);
}
pub fn rtcSetStateChangeCallback(pc: c_int, cb: ?StateChangeCallbackFunc) c_int {
return fns.rtcSetStateChangeCallback(pc, cb);
}
pub fn rtcSetGatheringStateChangeCallback(pc: c_int, cb: ?GatheringStateCallbackFunc) c_int {
return fns.rtcSetGatheringStateChangeCallback(pc, cb);
}
pub fn rtcSetDataChannelCallback(pc: c_int, cb: ?DataChannelCallbackFunc) c_int {
return fns.rtcSetDataChannelCallback(pc, cb);
}
// SDP
pub fn rtcSetLocalDescription(pc: c_int, sdp_type: ?[*:0]const u8) c_int {
return fns.rtcSetLocalDescription(pc, sdp_type);
}
pub fn rtcSetRemoteDescription(pc: c_int, sdp: [*:0]const u8, sdp_type: ?[*:0]const u8) c_int {
return fns.rtcSetRemoteDescription(pc, sdp, sdp_type);
}
pub fn rtcAddRemoteCandidate(pc: c_int, cand: [*:0]const u8, mid: ?[*:0]const u8) c_int {
return fns.rtcAddRemoteCandidate(pc, cand, mid);
}
pub fn rtcGetLocalDescription(pc: c_int, buffer: [*]u8, size: c_int) c_int {
return fns.rtcGetLocalDescription(pc, buffer, size);
}
pub fn rtcGetRemoteDescription(pc: c_int, buffer: [*]u8, size: c_int) c_int {
return fns.rtcGetRemoteDescription(pc, buffer, size);
}
// DataChannel
pub fn rtcCreateDataChannel(pc: c_int, label: [*:0]const u8) c_int {
return fns.rtcCreateDataChannel(pc, label);
}
pub fn rtcCreateDataChannelEx(pc: c_int, label: [*:0]const u8, init_cfg: *const DataChannelInit) c_int {
return fns.rtcCreateDataChannelEx(pc, label, init_cfg);
}
pub fn rtcDeleteDataChannel(dc: c_int) c_int {
return fns.rtcDeleteDataChannel(dc);
}
// DC callbacks
pub fn rtcSetOpenCallback(id: c_int, cb: ?OpenCallbackFunc) c_int {
return fns.rtcSetOpenCallback(id, cb);
}
pub fn rtcSetClosedCallback(id: c_int, cb: ?ClosedCallbackFunc) c_int {
return fns.rtcSetClosedCallback(id, cb);
}
pub fn rtcSetErrorCallback(id: c_int, cb: ?ErrorCallbackFunc) c_int {
return fns.rtcSetErrorCallback(id, cb);
}
pub fn rtcSetMessageCallback(id: c_int, cb: ?MessageCallbackFunc) c_int {
return fns.rtcSetMessageCallback(id, cb);
}
// I/O
pub fn rtcSendMessage(id: c_int, data: [*]const u8, size: c_int) c_int {
return fns.rtcSendMessage(id, data, size);
}
pub fn rtcClose(id: c_int) c_int {
return fns.rtcClose(id);
}
pub fn rtcDelete(id: c_int) c_int {
return fns.rtcDelete(id);
}
pub fn rtcIsOpen(id: c_int) bool {
return fns.rtcIsOpen(id);
}
pub fn rtcIsClosed(id: c_int) bool {
return fns.rtcIsClosed(id);
}
pub fn rtcGetBufferedAmount(id: c_int) c_int {
return fns.rtcGetBufferedAmount(id);
}
pub fn rtcReceiveMessage(id: c_int, buffer: [*]u8, size: *c_int) c_int {
return fns.rtcReceiveMessage(id, buffer, size);
}
// SCTP
pub fn rtcSetSctpSettings(settings: *const SctpSettings) c_int {
return fns.rtcSetSctpSettings(settings);
}
// WebSocket signaling
pub fn rtcWsConnect(url: [*:0]const u8, peer_id: [*:0]const u8) c_int {
if (fns.rtcWsConnect) |f| return f(url, peer_id);
return -1;
}
pub fn rtcWsDisconnect(ws_id: c_int) c_int {
if (fns.rtcWsDisconnect) |f| return f(ws_id);
return -1;
}
pub fn rtcWsSend(ws_id: c_int, message: [*]const u8, size: c_int) c_int {
if (fns.rtcWsSend) |f| return f(ws_id, message, size);
return -1;
}
pub fn rtcWsRecv(ws_id: c_int, buffer: [*]u8, size: *c_int) c_int {
if (fns.rtcWsRecv) |f| return f(ws_id, buffer, size);
return -1;
}
pub fn rtcWsIsConnected(ws_id: c_int) c_int {
if (fns.rtcWsIsConnected) |f| return f(ws_id);
return -1;
}
pub fn wsAvailable() bool {
return fns.rtcWsConnect != null;
}
};
// ============================================================================
// ChannelState — thread-safe state shared between libdatachannel callbacks
// and the Zig update loop.
// ============================================================================
/// Maximum receive queue depth before dropping messages.
const MAX_RECV_QUEUE: usize = 256;
/// Maximum accumulated SDP/candidate string length.
const MAX_SDP_SIZE: usize = 8192;
/// Maximum number of ICE candidates to buffer.
const MAX_CANDIDATES: usize = 64;
/// Thread-safe state for a single WebRTC DataChannel.
/// libdatachannel callbacks write from an internal thread;
/// the Zig update loop reads from the main thread.
pub const ChannelState = struct {
/// PeerConnection id from libdatachannel
pc_id: c_int,
/// DataChannel id from libdatachannel (-1 if not yet created/received)
dc_id: std.atomic.Value(c_int),
/// Connection state (atomic for lock-free reads)
state: std.atomic.Value(rtc.State),
/// Gathering state (atomic for lock-free reads)
gathering_state: std.atomic.Value(rtc.GatheringState),
/// DataChannel open flag
dc_open: std.atomic.Value(bool),
/// Error message (null if no error)
last_error: ?[]const u8,
/// Mutex for recv_queue, local_sdp, local_candidates, last_error
mutex: Mutex,
/// Received messages queue (SPSC: callback thread pushes, update loop pops)
recv_queue: std.ArrayListUnmanaged(RecvMessage),
/// Local SDP (set by description callback)
local_sdp: ?[]u8,
/// Local SDP type ("offer" or "answer")
local_sdp_type: ?[]u8,
/// Buffered local ICE candidates
local_candidates: std.ArrayListUnmanaged([]u8),
/// Whether ICE gathering is complete
gathering_complete: std.atomic.Value(bool),
/// Allocator for dynamic data
allocator: std.mem.Allocator,
pub const RecvMessage = struct {
data: []u8,
};
pub fn init(allocator: std.mem.Allocator, pc_id: c_int) ChannelState {
return .{
.pc_id = pc_id,
.dc_id = std.atomic.Value(c_int).init(-1),
.state = std.atomic.Value(rtc.State).init(.new),
.gathering_state = std.atomic.Value(rtc.GatheringState).init(.new),
.dc_open = std.atomic.Value(bool).init(false),
.last_error = null,
.mutex = .{},
.recv_queue = .{},
.local_sdp = null,
.local_sdp_type = null,
.local_candidates = .{},
.gathering_complete = std.atomic.Value(bool).init(false),
.allocator = allocator,
};
}
pub fn deinit(self: *ChannelState) void {
self.mutex.lock();
defer self.mutex.unlock();
for (self.recv_queue.items) |msg| {
self.allocator.free(msg.data);
}
self.recv_queue.deinit(self.allocator);
if (self.local_sdp) |sdp| self.allocator.free(sdp);
if (self.local_sdp_type) |t| self.allocator.free(t);
for (self.local_candidates.items) |cand| {
self.allocator.free(cand);
}
self.local_candidates.deinit(self.allocator);
}
/// Push a received message (called from libdatachannel callback thread).
pub fn pushRecvMessage(self: *ChannelState, data: []const u8) void {
self.mutex.lock();
defer self.mutex.unlock();
if (self.recv_queue.items.len >= MAX_RECV_QUEUE) {
return; // drop if queue full
}
const copy = self.allocator.dupe(u8, data) catch return;
self.recv_queue.append(self.allocator, .{ .data = copy }) catch {
self.allocator.free(copy);
};
}
/// Pop a received message (called from main/update thread).
pub fn popRecvMessage(self: *ChannelState) ?RecvMessage {
self.mutex.lock();
defer self.mutex.unlock();
if (self.recv_queue.items.len == 0) return null;
return self.recv_queue.orderedRemove(0);
}
/// Set local SDP (called from description callback thread).
pub fn setLocalSdp(self: *ChannelState, sdp: []const u8, sdp_type: []const u8) void {
self.mutex.lock();
defer self.mutex.unlock();
if (self.local_sdp) |old| self.allocator.free(old);
if (self.local_sdp_type) |old| self.allocator.free(old);
self.local_sdp = self.allocator.dupe(u8, sdp) catch null;
self.local_sdp_type = self.allocator.dupe(u8, sdp_type) catch null;
}
/// Get local SDP (called from main thread). Caller does NOT own the memory.
pub fn getLocalSdp(self: *ChannelState) ?[]const u8 {
self.mutex.lock();
defer self.mutex.unlock();
return self.local_sdp;
}
/// Add a local ICE candidate (called from candidate callback thread).
pub fn addLocalCandidate(self: *ChannelState, candidate: []const u8) void {
self.mutex.lock();
defer self.mutex.unlock();
if (self.local_candidates.items.len >= MAX_CANDIDATES) return;
const copy = self.allocator.dupe(u8, candidate) catch return;
self.local_candidates.append(self.allocator, copy) catch {
self.allocator.free(copy);
};
}
/// Drain all local candidates (called from main thread). Caller owns returned slices.
pub fn drainLocalCandidates(self: *ChannelState, allocator: std.mem.Allocator) ![][]u8 {
self.mutex.lock();
defer self.mutex.unlock();
if (self.local_candidates.items.len == 0) return &[_][]u8{};
const result = try allocator.dupe([]u8, self.local_candidates.items);
self.local_candidates.items.len = 0;
return result;
}
/// Map libdatachannel state to our TransportState.
pub fn getTransportState(self: *const ChannelState) TransportState {
return mapRtcState(self.state.load(.acquire));
}
};
/// Map rtc.State → TransportState.
pub fn mapRtcState(state: rtc.State) TransportState {
return switch (state) {
.new => .connecting,
.connecting => .connecting,
.connected => .connected,
.disconnected => .closed,
.failed => .closed,
.closed => .closed,
};
}
// ============================================================================
// C→Zig callback bridge functions
// ============================================================================
fn onLocalDescription(pc: c_int, sdp: [*:0]const u8, sdp_type: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void {
_ = pc;
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.setLocalSdp(std.mem.span(sdp), std.mem.span(sdp_type));
}
fn onLocalCandidate(pc: c_int, cand: [*:0]const u8, _: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void {
_ = pc;
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.addLocalCandidate(std.mem.span(cand));
}
fn onStateChange(_: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.state.store(@enumFromInt(state), .release);
}
fn onGatheringStateChange(_: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
const gs: rtc.GatheringState = @enumFromInt(state);
cs.gathering_state.store(gs, .release);
if (gs == .complete) {
cs.gathering_complete.store(true, .release);
}
}
fn onDataChannel(_: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.dc_id.store(dc, .release);
// Wire DataChannel callbacks
_ = rtc.rtcSetOpenCallback(dc, onOpen);
_ = rtc.rtcSetClosedCallback(dc, onClosed);
_ = rtc.rtcSetErrorCallback(dc, onError);
_ = rtc.rtcSetMessageCallback(dc, onMessage);
rtc.rtcSetUserPointer(dc, ptr);
}
fn onOpen(_: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.dc_open.store(true, .release);
}
fn onClosed(_: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.dc_open.store(false, .release);
}
fn onError(_: c_int, err_msg: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
cs.mutex.lock();
defer cs.mutex.unlock();
cs.last_error = std.mem.span(err_msg);
}
fn onMessage(_: c_int, message: [*]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void {
const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return));
if (size > 0) {
cs.pushRecvMessage(message[0..@intCast(size)]);
}
}
// ============================================================================
// NativeWebRTCManager — high-level API for creating WebRTC connections
// ============================================================================
pub const NativeWebRTCManager = struct {
allocator: std.mem.Allocator,
mtu: c_int = 0,
max_message_size: c_int = 0,
unordered: bool = false,
pub const InitError = error{WebRTCUnavailable};
pub fn init(allocator: std.mem.Allocator) InitError!NativeWebRTCManager {
if (!rtc.load()) return error.WebRTCUnavailable;
rtc.rtcPreload();
return .{ .allocator = allocator };
}
/// Configure global SCTP transport settings.
pub fn setSctpSettings(self: *NativeWebRTCManager, settings: rtc.SctpSettings) void {
_ = self;
_ = rtc.rtcSetSctpSettings(&settings);
}
pub fn deinit(self: *NativeWebRTCManager) void {
_ = self;
rtc.rtcCleanup();
}
/// Create a new WebRTC PeerConnection and DataChannel (offerer).
pub fn createOffer(self: *NativeWebRTCManager, ice_servers: ?[]const [*:0]const u8) !*ChannelState {
var config = rtc.Configuration{
.mtu = self.mtu,
.maxMessageSize = self.max_message_size,
};
if (ice_servers) |servers| {
config.iceServers = servers.ptr;
config.iceServersCount = @intCast(servers.len);
}
const pc_id = rtc.rtcCreatePeerConnection(&config);
if (pc_id < 0) return error.OutOfMemory;
const cs = try self.allocator.create(ChannelState);
cs.* = ChannelState.init(self.allocator, pc_id);
// Wire PeerConnection callbacks
rtc.rtcSetUserPointer(pc_id, cs);
_ = rtc.rtcSetLocalDescriptionCallback(pc_id, onLocalDescription);
_ = rtc.rtcSetLocalCandidateCallback(pc_id, onLocalCandidate);
_ = rtc.rtcSetStateChangeCallback(pc_id, onStateChange);
_ = rtc.rtcSetGatheringStateChangeCallback(pc_id, onGatheringStateChange);
// Create DataChannel (triggers SDP offer generation)
const dc_init = rtc.DataChannelInit{
.reliability = .{ .unordered = self.unordered },
.protocol = "zig-p2p",
};
const dc_id = rtc.rtcCreateDataChannelEx(pc_id, "zig-p2p", &dc_init);
if (dc_id < 0) {
_ = rtc.rtcDeletePeerConnection(pc_id);
self.allocator.destroy(cs);
return error.OutOfMemory;
}
cs.dc_id.store(dc_id, .release);
// Wire DataChannel callbacks
rtc.rtcSetUserPointer(dc_id, cs);
_ = rtc.rtcSetOpenCallback(dc_id, onOpen);
_ = rtc.rtcSetClosedCallback(dc_id, onClosed);
_ = rtc.rtcSetErrorCallback(dc_id, onError);
_ = rtc.rtcSetMessageCallback(dc_id, onMessage);
return cs;
}
/// Accept a remote offer SDP: create PeerConnection, set remote description,
/// generate answer. Returns ChannelState to poll.
pub fn acceptOffer(self: *NativeWebRTCManager, remote_sdp: [:0]const u8, ice_servers: ?[]const [*:0]const u8) !*ChannelState {
var config = rtc.Configuration{
.mtu = self.mtu,
.maxMessageSize = self.max_message_size,
};
if (ice_servers) |servers| {
config.iceServers = servers.ptr;
config.iceServersCount = @intCast(servers.len);
}
const pc_id = rtc.rtcCreatePeerConnection(&config);
if (pc_id < 0) return error.OutOfMemory;
const cs = try self.allocator.create(ChannelState);
cs.* = ChannelState.init(self.allocator, pc_id);
// Wire PeerConnection callbacks
rtc.rtcSetUserPointer(pc_id, cs);
_ = rtc.rtcSetLocalDescriptionCallback(pc_id, onLocalDescription);
_ = rtc.rtcSetLocalCandidateCallback(pc_id, onLocalCandidate);
_ = rtc.rtcSetStateChangeCallback(pc_id, onStateChange);
_ = rtc.rtcSetGatheringStateChangeCallback(pc_id, onGatheringStateChange);
_ = rtc.rtcSetDataChannelCallback(pc_id, onDataChannel);
// Set remote description (triggers answer generation)
const result = rtc.rtcSetRemoteDescription(pc_id, remote_sdp, "offer");
if (result < 0) {
_ = rtc.rtcDeletePeerConnection(pc_id);
self.allocator.destroy(cs);
return error.OutOfMemory;
}
return cs;
}
/// Send data via the DataChannel.
pub fn send(self: *NativeWebRTCManager, cs: *ChannelState, data: []const u8) !usize {
_ = self;
const dc_id = cs.dc_id.load(.acquire);
if (dc_id < 0) return error.OutOfMemory;
if (!cs.dc_open.load(.acquire)) return CoreError.ConnectionTimeout;
const result = rtc.rtcSendMessage(dc_id, data.ptr, @intCast(data.len));
if (result < 0) return CoreError.SocketSendFailed;
return data.len;
}
/// Add a remote ICE candidate.
pub fn addRemoteCandidate(self: *NativeWebRTCManager, cs: *ChannelState, candidate: [:0]const u8) void {
_ = self;
_ = rtc.rtcAddRemoteCandidate(cs.pc_id, candidate, null);
}
/// Close and clean up a channel.
pub fn destroyChannel(self: *NativeWebRTCManager, cs: *ChannelState) void {
const dc_id = cs.dc_id.load(.acquire);
if (dc_id >= 0) {
_ = rtc.rtcClose(dc_id);
_ = rtc.rtcDelete(dc_id);
}
_ = rtc.rtcClosePeerConnection(cs.pc_id);
_ = rtc.rtcDeletePeerConnection(cs.pc_id);
cs.deinit();
self.allocator.destroy(cs);
}
};
// ============================================================================
// WebRTCChannelTransport — Transport vtable conforming wrapper
// ============================================================================
/// Wraps a ChannelState to conform to the Transport vtable interface.
pub const WebRTCChannelTransport = struct {
cs: *ChannelState,
manager: *NativeWebRTCManager,
pub fn init(manager: *NativeWebRTCManager, cs: *ChannelState) WebRTCChannelTransport {
return .{ .cs = cs, .manager = manager };
}
// Transport vtable conformance
pub fn send(self: *WebRTCChannelTransport, data: []const u8) CoreError!usize {
return self.manager.send(self.cs, data) catch |err| {
return switch (err) {
error.OutOfMemory => CoreError.SystemError,
else => err,
};
};
}
pub fn receive(self: *WebRTCChannelTransport, buffer: []u8) CoreError!usize {
const msg = self.cs.popRecvMessage() orelse return CoreError.ConnectionTimeout;
defer self.cs.allocator.free(msg.data);
const copy_len = @min(msg.data.len, buffer.len);
@memcpy(buffer[0..copy_len], msg.data[0..copy_len]);
return copy_len;
}
pub fn sendTo(_: *WebRTCChannelTransport, _: []const u8, _: core.Address) CoreError!usize {
return CoreError.OperationNotSupported;
}
pub fn receiveFrom(_: *WebRTCChannelTransport, _: []u8) CoreError!core.transport.ReceiveFromResult {
return CoreError.OperationNotSupported;
}
pub fn canSend(self: *WebRTCChannelTransport) bool {
return self.cs.dc_open.load(.acquire);
}
pub fn canReceive(self: *WebRTCChannelTransport) bool {
self.cs.mutex.lock();
defer self.cs.mutex.unlock();
return self.cs.recv_queue.items.len > 0;
}
pub fn close(self: *WebRTCChannelTransport) void {
const dc_id = self.cs.dc_id.load(.acquire);
if (dc_id >= 0) {
_ = rtc.rtcClose(dc_id);
}
}
pub fn getState(self: *WebRTCChannelTransport) TransportState {
return self.cs.getTransportState();
}
pub fn getRemoteAddress(_: *WebRTCChannelTransport) ?core.Address {
return null;
}
pub fn getMode(_: *WebRTCChannelTransport) TransportMode {
return .stream;
}
pub fn transport(self: *WebRTCChannelTransport) CoreTransport {
return CoreTransport.init(self);
}
};

View File

@@ -0,0 +1,219 @@
//! WebRTC Signaling Message format for DHT-based SDP/ICE exchange.
//!
//! When two peers want to establish a WebRTC connection, they need to exchange
//! SDP offers/answers and ICE candidates. This module defines the wire format
//! for these signaling messages, which are stored/retrieved via the DHT.
//!
//! The signaling key is derived from both peers' public keys (same as MWP
//! meeting point derivation), ensuring only the intended peers can find
//! each other's signaling data.
const std = @import("std");
/// Maximum SDP/candidate payload size.
pub const MAX_PAYLOAD_SIZE: usize = 8192;
/// Signaling message types.
pub const MessageType = enum(u8) {
offer = 1,
answer = 2,
ice_candidate = 3,
};
/// Wire format for a signaling message.
/// Layout: [type:1][pubkey:32][timestamp:8 LE][payload_len:2 LE][payload:N][signature:64]
pub const SignalingMessage = struct {
msg_type: MessageType,
from_pubkey: [32]u8,
timestamp_ms: i64,
payload: []const u8,
signature: [64]u8,
/// Minimum wire size (no payload).
pub const HEADER_SIZE = 1 + 32 + 8 + 2; // type + pubkey + timestamp + payload_len
pub const SIGNATURE_SIZE = 64;
pub const MIN_WIRE_SIZE = HEADER_SIZE + SIGNATURE_SIZE;
/// Serialize to wire format.
pub fn serialize(self: *const SignalingMessage, allocator: std.mem.Allocator) ![]u8 {
if (self.payload.len > MAX_PAYLOAD_SIZE) return error.PayloadTooLarge;
const total = HEADER_SIZE + self.payload.len + SIGNATURE_SIZE;
const buf = try allocator.alloc(u8, total);
var offset: usize = 0;
// type
buf[offset] = @intFromEnum(self.msg_type);
offset += 1;
// from_pubkey
@memcpy(buf[offset..][0..32], &self.from_pubkey);
offset += 32;
// timestamp (little-endian i64)
std.mem.writeInt(i64, buf[offset..][0..8], self.timestamp_ms, .little);
offset += 8;
// payload_len (little-endian u16)
std.mem.writeInt(u16, buf[offset..][0..2], @intCast(self.payload.len), .little);
offset += 2;
// payload
@memcpy(buf[offset..][0..self.payload.len], self.payload);
offset += self.payload.len;
// signature
@memcpy(buf[offset..][0..64], &self.signature);
return buf;
}
/// Deserialize from wire format.
pub fn deserialize(data: []const u8) !SignalingMessage {
if (data.len < MIN_WIRE_SIZE) return error.BufferTooSmall;
var offset: usize = 0;
// type
const msg_type_raw = data[offset];
offset += 1;
const msg_type: MessageType = std.meta.intToEnum(MessageType, msg_type_raw) catch
return error.InvalidMessageType;
// from_pubkey
var pubkey: [32]u8 = undefined;
@memcpy(&pubkey, data[offset..][0..32]);
offset += 32;
// timestamp
const timestamp_ms = std.mem.readInt(i64, data[offset..][0..8], .little);
offset += 8;
// payload_len
const payload_len = std.mem.readInt(u16, data[offset..][0..2], .little);
offset += 2;
if (data.len < HEADER_SIZE + payload_len + SIGNATURE_SIZE) return error.BufferTooSmall;
// payload (borrowed from input)
const payload = data[offset..][0..payload_len];
offset += payload_len;
// signature
var signature: [64]u8 = undefined;
@memcpy(&signature, data[offset..][0..64]);
return .{
.msg_type = msg_type,
.from_pubkey = pubkey,
.timestamp_ms = timestamp_ms,
.payload = payload,
.signature = signature,
};
}
/// Get the signed data portion (everything except the signature).
pub fn getSignedData(data: []const u8) ![]const u8 {
if (data.len < MIN_WIRE_SIZE) return error.BufferTooSmall;
return data[0 .. data.len - SIGNATURE_SIZE];
}
};
/// Compute a deterministic signaling key from two peers' public keys.
/// Uses SHA-256(sorted_key_a || sorted_key_b || "webrtc-signaling-v1").
/// Both peers compute the same key regardless of order.
pub fn computeSignalingKey(pubkey_a: [32]u8, pubkey_b: [32]u8) [32]u8 {
const order = std.mem.order(u8, &pubkey_a, &pubkey_b);
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
if (order == .lt or order == .eq) {
hasher.update(&pubkey_a);
hasher.update(&pubkey_b);
} else {
hasher.update(&pubkey_b);
hasher.update(&pubkey_a);
}
hasher.update("webrtc-signaling-v1");
return hasher.finalResult();
}
// ============================================================================
// Tests
// ============================================================================
test "SignalingMessage: roundtrip serialize/deserialize" {
const allocator = std.testing.allocator;
const original = SignalingMessage{
.msg_type = .offer,
.from_pubkey = [_]u8{0xAA} ** 32,
.timestamp_ms = 1700000000000,
.payload = "v=0\r\no=- 123 456 IN IP4 127.0.0.1\r\n",
.signature = [_]u8{0xBB} ** 64,
};
const wire = try original.serialize(allocator);
defer allocator.free(wire);
const decoded = try SignalingMessage.deserialize(wire);
try std.testing.expectEqual(MessageType.offer, decoded.msg_type);
try std.testing.expectEqualSlices(u8, &original.from_pubkey, &decoded.from_pubkey);
try std.testing.expectEqual(original.timestamp_ms, decoded.timestamp_ms);
try std.testing.expectEqualStrings(original.payload, decoded.payload);
try std.testing.expectEqualSlices(u8, &original.signature, &decoded.signature);
}
test "SignalingMessage: ice_candidate type" {
const allocator = std.testing.allocator;
const msg = SignalingMessage{
.msg_type = .ice_candidate,
.from_pubkey = [_]u8{0x11} ** 32,
.timestamp_ms = 42,
.payload = "candidate:0 1 UDP 2130706431 127.0.0.1 12345 typ host",
.signature = [_]u8{0} ** 64,
};
const wire = try msg.serialize(allocator);
defer allocator.free(wire);
const decoded = try SignalingMessage.deserialize(wire);
try std.testing.expectEqual(MessageType.ice_candidate, decoded.msg_type);
}
test "SignalingMessage: deserialize rejects too-small buffer" {
const small = [_]u8{0} ** 10;
const result = SignalingMessage.deserialize(&small);
try std.testing.expectError(error.BufferTooSmall, result);
}
test "SignalingMessage: deserialize rejects invalid type" {
var buf: [SignalingMessage.MIN_WIRE_SIZE]u8 = [_]u8{0} ** SignalingMessage.MIN_WIRE_SIZE;
buf[0] = 0xFF; // invalid type
const result = SignalingMessage.deserialize(&buf);
try std.testing.expectError(error.InvalidMessageType, result);
}
test "computeSignalingKey: order-independent" {
const key_a = [_]u8{0x01} ** 32;
const key_b = [_]u8{0x02} ** 32;
const result_ab = computeSignalingKey(key_a, key_b);
const result_ba = computeSignalingKey(key_b, key_a);
try std.testing.expectEqualSlices(u8, &result_ab, &result_ba);
}
test "computeSignalingKey: different keys produce different results" {
const key_a = [_]u8{0x01} ** 32;
const key_b = [_]u8{0x02} ** 32;
const key_c = [_]u8{0x03} ** 32;
const result_ab = computeSignalingKey(key_a, key_b);
const result_ac = computeSignalingKey(key_a, key_c);
try std.testing.expect(!std.mem.eql(u8, &result_ab, &result_ac));
}

View File

@@ -0,0 +1,252 @@
//! WASM WebRTC Transport
//!
//! Transport vtable implementation for browser WebRTC DataChannels.
//! Calls `extern "env"` functions provided by the JS host for sending data,
//! and receives data via exported callbacks that JS invokes when messages arrive.
//!
//! Single-threaded (WASM has no threads), so no mutex needed for the recv queue.
const std = @import("std");
const core = @import("core");
const CoreError = core.errors.Error;
const CoreTransport = core.transport.Transport;
const TransportState = core.transport.TransportState;
const TransportMode = core.transport.TransportMode;
const Address = core.Address;
// ============================================================================
// JS extern imports — provided by the JS host layer
// ============================================================================
extern "env" fn js_datachannel_send(channel_id: u32, data_ptr: [*]const u8, data_len: u32) i32;
extern "env" fn js_datachannel_close(channel_id: u32) void;
extern "env" fn js_datachannel_buffered_amount(channel_id: u32) u32;
extern "env" fn js_log(ptr: [*]const u8, len: u32) void;
// ============================================================================
// WasmWebRTCTransport — one per DataChannel
// ============================================================================
/// Maximum receive queue size per transport. Must be large enough to hold
/// all messages that arrive between update() ticks. With DataChannel flow
/// control on the sender (bufferedAmount check), this is typically small,
/// but burst arrivals on fast connections can queue thousands of messages.
pub const MAX_RECV_QUEUE = 100_000;
pub const WasmWebRTCTransport = struct {
channel_id: u32,
state: TransportState,
recv_queue: std.ArrayListUnmanaged([]u8),
/// Read index for O(1) FIFO dequeue (avoids O(n) orderedRemove shifts).
recv_read_idx: usize,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator, channel_id: u32) WasmWebRTCTransport {
return .{
.channel_id = channel_id,
.state = .connected,
.recv_queue = .{},
.recv_read_idx = 0,
.allocator = allocator,
};
}
pub fn deinit(self: *WasmWebRTCTransport) void {
// Free unread messages
for (self.recv_queue.items[self.recv_read_idx..]) |msg| {
self.allocator.free(msg);
}
self.recv_queue.deinit(self.allocator);
}
/// Push a received message (called from wasm_on_datachannel_message).
pub fn pushRecvMessage(self: *WasmWebRTCTransport, data: []const u8) void {
const pending = self.recv_queue.items.len - self.recv_read_idx;
if (pending >= MAX_RECV_QUEUE) {
// Drop oldest unread message if queue is full
self.allocator.free(self.recv_queue.items[self.recv_read_idx]);
self.recv_read_idx += 1;
}
const copy = self.allocator.dupe(u8, data) catch return;
self.recv_queue.append(self.allocator, copy) catch {
self.allocator.free(copy);
};
}
/// Compact the queue when all messages have been read (reclaims memory).
fn compactIfDrained(self: *WasmWebRTCTransport) void {
if (self.recv_read_idx > 0 and self.recv_read_idx >= self.recv_queue.items.len) {
self.recv_queue.clearRetainingCapacity();
self.recv_read_idx = 0;
}
}
// -- Transport vtable conformance --
pub fn send(self: *WasmWebRTCTransport, data: []const u8) CoreError!usize {
if (self.state != .connected) return CoreError.ConnectionClosed;
const result = js_datachannel_send(self.channel_id, data.ptr, @intCast(data.len));
if (result < 0) return CoreError.NetworkError;
return data.len;
}
pub fn receive(self: *WasmWebRTCTransport, buffer: []u8) CoreError!usize {
if (self.recv_read_idx >= self.recv_queue.items.len) {
self.compactIfDrained();
if (self.state == .closed) return CoreError.ConnectionClosed;
return CoreError.ConnectionTimeout;
}
const msg = self.recv_queue.items[self.recv_read_idx];
self.recv_read_idx += 1;
defer self.allocator.free(msg);
// Compact after draining all messages (O(1) amortized)
self.compactIfDrained();
const copy_len = @min(msg.len, buffer.len);
@memcpy(buffer[0..copy_len], msg[0..copy_len]);
return copy_len;
}
pub fn sendTo(_: *WasmWebRTCTransport, _: []const u8, _: Address) CoreError!usize {
return CoreError.OperationNotSupported;
}
pub fn receiveFrom(_: *WasmWebRTCTransport, _: []u8) CoreError!core.transport.ReceiveFromResult {
return CoreError.OperationNotSupported;
}
pub fn canSend(self: *WasmWebRTCTransport) bool {
if (self.state != .connected) return false;
// Check JS-side buffered amount; allow sending if under 1MB
return js_datachannel_buffered_amount(self.channel_id) < 1_048_576;
}
pub fn canReceive(self: *WasmWebRTCTransport) bool {
return self.recv_read_idx < self.recv_queue.items.len;
}
pub fn close(self: *WasmWebRTCTransport) void {
if (self.state == .closed) return;
self.state = .closed;
js_datachannel_close(self.channel_id);
}
pub fn getState(self: *WasmWebRTCTransport) TransportState {
return self.state;
}
pub fn getRemoteAddress(_: *WasmWebRTCTransport) ?Address {
return null; // WebRTC doesn't expose remote IP to JS
}
pub fn getMode(_: *WasmWebRTCTransport) TransportMode {
return .stream; // Reliable ordered DataChannel
}
/// Wrap this transport into the generic Transport vtable.
pub fn transport(self: *WasmWebRTCTransport) CoreTransport {
return CoreTransport.init(self);
}
};
// ============================================================================
// WasmChannelManager — manages active WASM WebRTC transports
// ============================================================================
pub const MAX_CHANNELS = 32;
pub const WasmChannelManager = struct {
channels: [MAX_CHANNELS]?*WasmWebRTCTransport,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) WasmChannelManager {
return .{
.channels = .{null} ** MAX_CHANNELS,
.allocator = allocator,
};
}
pub fn deinit(self: *WasmChannelManager) void {
for (&self.channels) |*slot| {
if (slot.*) |t| {
t.deinit();
self.allocator.destroy(t);
slot.* = null;
}
}
}
/// Create a transport for a newly opened channel.
/// Returns the transport or null if no slots available.
pub fn createTransport(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport {
// Find a free slot
for (&self.channels) |*slot| {
if (slot.* == null) {
const t = self.allocator.create(WasmWebRTCTransport) catch return null;
t.* = WasmWebRTCTransport.init(self.allocator, channel_id);
slot.* = t;
return t;
}
}
return null;
}
/// Find transport by channel ID.
pub fn getTransport(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport {
for (self.channels) |slot| {
if (slot) |t| {
if (t.channel_id == channel_id) return t;
}
}
return null;
}
/// Remove and destroy a transport by channel ID.
pub fn removeTransport(self: *WasmChannelManager, channel_id: u32) void {
for (&self.channels) |*slot| {
if (slot.*) |t| {
if (t.channel_id == channel_id) {
t.deinit();
self.allocator.destroy(t);
slot.* = null;
return;
}
}
}
}
// -- Event handlers called from WASM exports --
/// Handle DataChannel open event.
pub fn onChannelOpen(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport {
// If transport already exists, just mark it connected
if (self.getTransport(channel_id)) |t| {
t.state = .connected;
return t;
}
// Otherwise create a new transport
return self.createTransport(channel_id);
}
/// Handle DataChannel message event.
pub fn onChannelMessage(self: *WasmChannelManager, channel_id: u32, data: []const u8) void {
if (self.getTransport(channel_id)) |t| {
t.pushRecvMessage(data);
}
}
/// Handle DataChannel close event.
pub fn onChannelClose(self: *WasmChannelManager, channel_id: u32) void {
if (self.getTransport(channel_id)) |t| {
t.state = .closed;
}
}
/// Handle DataChannel error event.
pub fn onChannelError(self: *WasmChannelManager, channel_id: u32) void {
if (self.getTransport(channel_id)) |t| {
t.state = .closed;
}
}
};