//! 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>, sdp_type: parking_lot::Mutex>, candidates: parking_lot::Mutex>, gathering_complete: AtomicBool, dc_open: AtomicBool, dc_id: AtomicI32, recv_messages: parking_lot::Mutex>>, } 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 = alice.candidates.lock().clone(); let bob_cands: Vec = 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 = (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(); } }