mod common;
use common::{Peer, Result, connect_and_exchange, run_until};
use rtci::peer_connection::configuration::setting_engine::SettingEngineBuilder;
use rtci::peer_connection::state::{RTCIceConnectionState, RTCPeerConnectionState};
use rtci::peer_connection::transport::RTCIceCandidateType;
use rtci::statistics::StatsSelector;
use rtci_stream_driver::peer::PeerDriverConfig;
use rtci_stream_driver::runtime::mock::{Fate, LinkConfig, MockDatagram};
use rtci_stream_driver::runtime::{
AsyncTcpListener, AsyncTcpStream, AsyncUdpSocket, BoxFuture, JoinHandle, MockRuntime,
MulticastConfig, Runtime,
};
use rtci_stream_driver::{DriverConfig, DriverInput, StreamDriver};
use shared::stream::{StreamCommand, StreamEvent};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const A: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
const B: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2));
const STEP: Duration = Duration::from_millis(10);
fn peers(runtime: &MockRuntime) -> Result<(Peer, Peer)> {
let shared: Arc<dyn Runtime> = Arc::new(runtime.clone());
Ok((Peer::new(shared.clone(), A)?, Peer::new(shared, B)?))
}
#[test]
fn two_drivers_connect_and_exchange_a_data_channel_message_on_virtual_time() -> Result<()> {
let runtime = MockRuntime::new();
runtime.net().set_links(
A,
B,
LinkConfig::new().with_delay(Duration::from_millis(20)),
);
let (mut a, mut b) = peers(&runtime)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
assert!(a.connected() && b.connected());
let log = runtime.net().log();
assert!(log.iter().any(|d| d.from.ip() == A && d.to.ip() == B));
assert!(log.iter().any(|d| d.from.ip() == B && d.to.ip() == A));
assert!(
log.iter().all(|d| matches!(d.fate, Fate::Delivered(1))),
"{log:?}"
);
assert!(
runtime.clock().elapsed() >= Duration::from_millis(80),
"{:?}",
runtime.clock().elapsed()
);
Ok(())
}
#[test]
fn consent_expiry_after_30_seconds_elapses_on_virtual_time_and_the_driver_reports_the_failure()
-> Result<()> {
let runtime = MockRuntime::new();
let (mut a, mut b) = peers(&runtime)?;
a.relay_end_of_candidates = true;
b.relay_end_of_candidates = true;
let begun = runtime.now();
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
let dark = runtime.now();
let pac = (begun + Duration::from_millis(39_500)).saturating_duration_since(dark);
runtime
.net()
.set_links(A, B, LinkConfig::new().with_blocked(true));
let wall = Instant::now();
let failed = |p: &Peer| {
p.ice_states
.iter()
.any(|(s, _)| *s == RTCIceConnectionState::Failed)
};
let both = runtime.run(run_until(&mut a, &mut b, STEP, 100_000, |a, b| {
failed(a) && failed(b)
}))?;
let wall = wall.elapsed();
assert!(
both,
"both ICE connections fail: {:?} / {:?}",
a.ice_states, b.ice_states
);
for (who, peer) in [("a", &a), ("b", &b)] {
let at = |state| {
peer.ice_states
.iter()
.find(|(s, t)| *s == state && *t >= dark)
.map(|(_, t)| t.duration_since(dark))
};
let disconnected = at(RTCIceConnectionState::Disconnected).ok_or("disconnected")?;
let failed = at(RTCIceConnectionState::Failed).ok_or("failed")?;
assert!(disconnected < failed, "{who}: disconnected first");
assert!(
failed >= Duration::from_secs(20)
&& failed <= Duration::from_secs(31).max(pac + Duration::from_millis(250)),
"{who}: failed {failed:?} after the path went dark (PAC timer {pac:?})"
);
assert!(
peer.states
.iter()
.any(|(s, t)| *s == RTCPeerConnectionState::Failed && *t >= dark),
"{who}: the peer connection reports failed: {:?}",
peer.states
);
}
assert!(
wall < Duration::from_secs(10),
"30 s of virtual time took {wall:?} of wall time"
);
Ok(())
}
fn is_client_hello(data: &[u8]) -> bool {
data.len() > 13 && data[0] == 22 && data[1] == 0xfe && data[13] == 1
}
#[test]
fn a_lost_client_hello_is_retransmitted_on_virtual_time_and_the_peers_connect() -> Result<()> {
let runtime = MockRuntime::new();
let hellos: Arc<Mutex<Vec<Instant>>> = Arc::default();
let seen = hellos.clone();
runtime
.net()
.set_filter(Box::new(move |d: &MockDatagram<'_>| {
if !is_client_hello(d.data) {
return true;
}
let mut seen = seen.lock().unwrap();
seen.push(d.at);
seen.len() > 1
}));
let (mut a, mut b) = peers(&runtime)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
let hellos = hellos.lock().unwrap().clone();
assert!(
hellos.len() >= 2,
"the ClientHello was sent again: {hellos:?}"
);
let gap = hellos[1].duration_since(hellos[0]);
assert!(
gap >= Duration::from_millis(100) && gap <= Duration::from_millis(400),
"retransmitted after its timer: {gap:?}"
);
let filtered = runtime
.net()
.log()
.iter()
.filter(|d| d.fate == Fate::Filtered)
.count();
assert_eq!(filtered, 1, "exactly one datagram was lost");
Ok(())
}
#[test]
fn the_driver_gathers_only_on_the_addresses_it_is_given() -> Result<()> {
const A2: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 3));
for addresses in [vec![A], vec![A, A2]] {
let runtime = MockRuntime::new();
let shared: Arc<dyn Runtime> = Arc::new(runtime.clone());
let mut a = Peer::with_config(
shared.clone(),
SettingEngineBuilder::new(),
PeerDriverConfig::on(addresses.clone()),
)?;
let mut b = Peer::new(shared, B)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
let mut bound: Vec<IpAddr> = a
.driver
.local_addresses()
.iter()
.map(|local| local.ip())
.collect();
bound.sort();
bound.dedup();
assert_eq!(bound, addresses, "sockets only on the addresses given");
let hosts: Vec<String> = a
.driver
.pc()
.dtls_transports()
.iter()
.flat_map(|t| t.ice_transport().get_local_candidates())
.filter(|c| c.typ == RTCIceCandidateType::Host)
.map(|c| c.address)
.collect();
assert!(!hosts.is_empty(), "host candidates were gathered");
assert!(
hosts
.iter()
.all(|h| addresses.iter().any(|ip| ip.to_string() == *h)),
"host candidates only on {addresses:?}: {hosts:?}"
);
let log = runtime.net().log();
assert!(
log.iter()
.filter(|d| d.from.ip() != B)
.all(|d| addresses.contains(&d.from.ip())),
"a sent only from {addresses:?}: {log:?}"
);
}
Ok(())
}
#[test]
fn sends_the_socket_refuses_are_counted_as_discarded_on_the_selected_pair() -> Result<()> {
let runtime = MockRuntime::new();
let (mut a, mut b) = peers(&runtime)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
let discarded = |a: &mut Peer| {
let now = a.now();
let report = a.driver.pc_mut().get_stats(now, StatsSelector::None);
report
.candidate_pairs()
.filter_map(|p| Some((p.packets_discarded_on_send?, p.bytes_discarded_on_send?)))
.fold((0u32, 0u64), |(n, b), (pn, pb)| (n + pn, b + pb))
};
assert_eq!(
discarded(&mut a),
(0, 0),
"nothing discarded while sends go through"
);
runtime
.net()
.set_send_error(B, Some(std::io::ErrorKind::ConnectionRefused));
let before = a.driver.unsent_datagrams();
a.send(b"refused by the socket")?;
assert!(
a.driver.unsent_datagrams() > before,
"the socket refused the send"
);
let (packets, bytes) = discarded(&mut a);
assert!(packets >= 1, "counted on the pair: {packets} packets");
assert!(
bytes > b"refused by the socket".len() as u64,
"{bytes} bytes"
);
Ok(())
}
#[test]
fn a_datagram_is_stamped_when_its_socket_hands_it_over_not_when_the_driver_is_stepped() -> Result<()>
{
let runtime = MockRuntime::new();
let (mut a, mut b) = peers(&runtime)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
b.send(b"read late")?;
runtime.run_until_idle();
let late = Duration::from_millis(500);
runtime.clock().advance(late);
runtime.run(a.driver.step(Duration::ZERO))?;
let now = a.now();
let report = a.driver.pc_mut().get_stats(now, StatsSelector::None);
let (reported, last) = report
.candidate_pairs()
.filter_map(|p| {
Some((
p.stats.timestamp.duration_since_unix_epoch(),
p.last_packet_received_timestamp?
.duration_since_unix_epoch(),
))
})
.max_by_key(|(_, last)| *last)
.expect("a pair that received");
let waited = reported.saturating_sub(last);
assert!(
waited >= late - Duration::from_millis(50),
"arrival stamped {waited:?} before the report, the driver was stepped {late:?} late"
);
Ok(())
}
#[test]
fn each_datagram_leaves_with_the_dont_fragment_state_the_engine_gives_it() -> Result<()> {
let runtime = MockRuntime::new();
let first_bytes = Arc::new(Mutex::new(Vec::new()));
let seen = first_bytes.clone();
runtime
.net()
.set_filter(Box::new(move |d: &MockDatagram<'_>| {
seen.lock().unwrap().push(d.data.first().copied());
true
}));
let (mut a, mut b) = peers(&runtime)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
runtime.run(run_until(&mut a, &mut b, STEP, 2_000, |a, _| {
a.now() > Instant::now() + Duration::from_secs(1_000_000)
}))?;
let log = runtime.net().log();
let first_bytes = first_bytes.lock().unwrap();
let from_a: Vec<(u8, bool)> = log
.iter()
.filter(|d| !matches!(d.fate, Fate::SendError))
.zip(first_bytes.iter())
.filter(|(d, _)| d.from.ip() == A)
.filter_map(|(d, first)| Some(((*first)?, d.dont_fragment)))
.collect();
let first_df = from_a
.iter()
.position(|(byte, df)| (20..=63).contains(byte) && *df)
.unwrap_or_else(|| {
panic!("a DTLS datagram with DF (SCTP discovers the path MTU): {from_a:?}")
});
assert!(
from_a[first_df..]
.iter()
.any(|(byte, df)| *byte <= 3 && !*df),
"STUN after DTLS goes without DF: {from_a:?}"
);
Ok(())
}
#[derive(Debug)]
struct FamilyResolver {
inner: MockRuntime,
started: Arc<Mutex<Vec<bool>>>,
}
impl Runtime for FamilyResolver {
fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle> {
self.inner.spawn(future)
}
fn now(&self) -> Instant {
self.inner.now()
}
fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()> {
self.inner.sleep_until(deadline)
}
fn bind_udp(&self, local: SocketAddr) -> std::io::Result<Arc<dyn AsyncUdpSocket>> {
self.inner.bind_udp(local)
}
fn bind_udp_multicast(
&self,
config: &MulticastConfig,
) -> std::io::Result<Arc<dyn AsyncUdpSocket>> {
self.inner.bind_udp_multicast(config)
}
fn listen_tcp(
&self,
local: SocketAddr,
reuse_address: bool,
) -> std::io::Result<Arc<dyn AsyncTcpListener>> {
self.inner.listen_tcp(local, reuse_address)
}
fn connect_tcp(
&self,
local: SocketAddr,
remote: SocketAddr,
reuse_address: bool,
) -> BoxFuture<'static, std::io::Result<Arc<dyn AsyncTcpStream>>> {
self.inner.connect_tcp(local, remote, reuse_address)
}
fn resolve_host(
&self,
host: &str,
port: u16,
) -> BoxFuture<'static, std::io::Result<Vec<SocketAddr>>> {
self.inner.resolve_host(host, port)
}
fn resolve_family(
&self,
_host: &str,
port: u16,
ipv6: bool,
) -> Option<BoxFuture<'static, Vec<SocketAddr>>> {
let started = self.started.clone();
let ip: IpAddr = if ipv6 {
"2001:db8::7".parse().unwrap()
} else {
"192.0.2.7".parse().unwrap()
};
Some(Box::pin(async move {
started.lock().unwrap().push(ipv6);
vec![SocketAddr::new(ip, port)]
}))
}
fn block_on(&self, future: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>>) {
self.inner.block_on(future)
}
fn virtual_clock(&self) -> bool {
true
}
}
#[test]
fn aaaa_and_a_are_asked_together_aaaa_first_and_answered_apart() {
let started = Arc::new(Mutex::new(Vec::new()));
let inner = MockRuntime::new();
let runtime = FamilyResolver {
inner: inner.clone(),
started: started.clone(),
};
let mut driver = StreamDriver::with_runtime(Arc::new(runtime), DriverConfig::default());
driver.execute(StreamCommand::Resolve {
query: 7,
host: "turn.example".into(),
port: 3478,
});
inner.run_until_idle();
assert_eq!(
*started.lock().unwrap(),
vec![true, false],
"AAAA asked first, then A"
);
let mut answers = Vec::new();
while let Some(input) = driver.try_next() {
if let DriverInput::Event(StreamEvent::ResolvedFamily {
query,
ipv6,
addresses,
}) = input
{
answers.push((query, ipv6, addresses));
}
}
assert_eq!(
answers,
vec![
(7, true, vec!["[2001:db8::7]:3478".parse().unwrap()]),
(7, false, vec!["192.0.2.7:3478".parse().unwrap()]),
]
);
}
#[test]
fn the_driver_sends_each_datagram_from_the_socket_of_its_local_address() -> Result<()> {
const A2: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 3));
let runtime = MockRuntime::new();
let shared: Arc<dyn Runtime> = Arc::new(runtime.clone());
let mut a = Peer::with_config(
shared.clone(),
SettingEngineBuilder::new(),
PeerDriverConfig::on(vec![A, A2]),
)?;
let mut b = Peer::new(shared, B)?;
runtime.run(connect_and_exchange(&mut a, &mut b, STEP, 10_000))?;
let log = runtime.net().log();
let sent_from: std::collections::HashSet<SocketAddr> = log
.iter()
.filter(|d| d.to.ip() == B && d.from.ip() != B)
.map(|d| d.from)
.collect();
for local in a.driver.local_addresses() {
assert!(
sent_from.contains(&local),
"{local} sent from itself: {sent_from:?}"
);
}
for d in log.iter().filter(|d| d.from.ip() == B && d.to.ip() != B) {
assert!(
sent_from.contains(&d.to),
"b sent to {} that a never sent from",
d.to
);
}
Ok(())
}