rtci-stream-driver 0.6.0

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Driven connections on virtual time: two `PeerDriver`s on one `MockRuntime`, its in-memory
//! network between them. Nothing touches a socket and the clock moves only when every task
//! waits, so a 30-second timeout costs no wall time and every run is the same.

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));
/// The longest a driver waits in one step.
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());
    // Every datagram went over the mock network, from the drivers' own (mock) sockets.
    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:?}"
    );
    // With 20 ms each way the connection takes several round trips of virtual time.
    assert!(
        runtime.clock().elapsed() >= Duration::from_millis(80),
        "{:?}",
        runtime.clock().elapsed()
    );
    Ok(())
}

/// RFC 7675 section 5.1: "Consent expires after 30 seconds". The path between the two peers
/// goes dark after they connected; each driver reports its ICE connection (and its peer
/// connection) disconnected, then failed: at most 30 seconds after the last consent response
/// it had, or as the PAC timer expires when that is later (W3C webrtc-pc 5.6.4; the drivers'
/// applications relay the end of the candidates), and the whole wait takes no wall time worth
/// the name.
#[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)?;
    // The application relays the end of the candidates: lost consent is "failed" then (W3C
    // webrtc-pc 5.6.4), "disconnected" without it.
    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();
    // "failed" also waits for the PAC timer, 39.5 s after the checks began (W3C webrtc-pc
    // 5.6.4, RFC 8863): consent that expires before that fails the connection then.
    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");
        // The last consent response came at most one consent interval (5 s, drawn up to
        // 1.2 times) before the path went dark: consent expires 24 to 30 s after that.
        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(())
}

/// A DTLS ClientHello record (content type 22, a DTLS version, handshake type 1).
fn is_client_hello(data: &[u8]) -> bool {
    data.len() > 13 && data[0] == 22 && data[1] == 0xfe && data[13] == 1
}

/// RFC 6347 section 4.2.4 (RFC 9147 section 5.8): a flight that gets no answer is sent again
/// when its timer fires. The network drops the first ClientHello; the client sends it again
/// when its first timer runs out on virtual time, and the peers connect. The engine's first
/// timer for DTLS-SRTP follows RFC 9147 section 5.8.2: 400 ms, or 1.5 times ICE's round trip
/// time and never under 100 ms (`DtlsFlightInterval::Rfc9147`).
#[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);
            // The first one is lost.
            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(())
}

/// RFC 8445 section 19.1: ICE implementations "are RECOMMENDED to provide a programmatic or user
/// interface that provides control over which network interfaces are used to generate
/// candidates". The driver's is `PeerDriverConfig::addresses`: it binds, gathers host candidates
/// and sends on the addresses it is given and on no other, here one address of a host that has
/// two, then both.
#[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(())
}

/// W3C webrtc-stats 8.20: `packetsDiscardedOnSend` / `bytesDiscardedOnSend`, the candidate
/// pair's packets "discarded due to socket errors". Once connected, a's socket refuses every
/// send to b; the data channel message (SCTP over DTLS, on the selected pair) it then writes is
/// counted on the selected pair, packets and bytes. Before that the members are absent.
#[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(())
}

/// RFC 8888 section 3: "the arrival time at the receiver needs to be recorded at the earliest
/// available opportunity". b's message reaches a's socket and a's reader at once, but the
/// application steps a's driver only half a second later; the engine is given the time the
/// reader took the datagram off the socket, which a's candidate pair reports as its
/// `lastPacketReceivedTimestamp`, half a second before the report.
#[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(())
}

/// RFC 8261 section 5 and RFC 9260 section 6.9, the driver's part: each datagram leaves with the
/// Don't Fragment state the engine gives it (`RTCPeerConnection::dont_fragment`). While SCTP
/// discovers the path MTU (on by default) a's DTLS datagrams go with DF; its STUN (consent
/// checks) after them goes without it again.
#[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))?;
    // Let consent checks follow the DTLS traffic.
    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(())
}

/// A mock runtime that answers AAAA and A lookups apart (`Runtime::resolve_family`), and records
/// the order in which the lookups start (are first polled, as a query is sent).
#[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
    }
}

/// RFC 8305 section 3: the client "SHOULD send the AAAA and A queries together", AAAA first,
/// and each answer is used as it comes. Given a runtime that looks the families up apart, the
/// driver starts both lookups for one `Resolve`, the AAAA lookup first, and hands each answer
/// to the engine apart (`StreamEvent::ResolvedFamily`).
#[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()]),
        ]
    );
}

/// RFC 8834 section 4.7 (symmetric RTP and RTCP, RFC 4961): an endpoint sends from the transport
/// address it receives on. The driver sends each datagram the engine writes from the socket of
/// the datagram's local address: with host candidates on two addresses, each of a's sockets
/// sends (its connectivity checks at least) from its own address and port, and b's datagrams
/// to a arrive at addresses a sends from.
#[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(())
}