str0m 0.23.0

WebRTC library in Sans-IO style
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use std::net::Ipv4Addr;
use std::time::{Duration, Instant};

use netem::NetemConfig;
use str0m::channel::ChannelConfig;
use str0m::{Event, Input, Output, RtcError};

mod common;
use common::{Peer, TestRtc, connect_l_r, init_crypto_default, init_log, progress};

/// Poll one peer while deliberately withholding all of its network output.
///
/// This models an application that keeps driving its local RTC while packets
/// to the peer are delayed. Public events are returned to the test; transmits
/// are dropped instead of being handed to the remote `TestRtc`.
fn poll_without_delivering_network(
    rtc: &mut TestRtc,
    now: Instant,
) -> Result<Vec<Event>, RtcError> {
    rtc.rtc.handle_input(Input::Timeout(now))?;

    let mut events = vec![];
    loop {
        match rtc.rtc.poll_output()? {
            Output::Event(event) => events.push(event),
            Output::Transmit(_) => {}
            Output::Timeout(_) => return Ok(events),
        }
    }
}

#[test]
pub fn data_channel() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mut change = l.sdp_api();
    let cid = change.add_channel("My little channel".into());
    change.add_channel("My little channel 2".into());
    let (offer, pending) = change.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    loop {
        if l.is_connected() || r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    loop {
        if let Some(mut chan) = l.channel(cid) {
            chan.write(false, "Hello world! ".as_bytes())
                .expect("to write string");
        }

        progress(&mut l, &mut r)?;

        if l.duration() > Duration::from_secs(10) {
            break;
        }
    }

    assert!(r.events.len() > 120);

    Ok(())
}

/// Closing a data channel must propagate to the remote peer (via the SCTP
/// stream reset handshake), and once the handshake completes the freed stream
/// id must be reusable by a new in-band channel.
#[test]
pub fn data_channel_close_reopen() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mut change = l.sdp_api();
    let cid = change.add_channel("churn".into());
    let (offer, pending) = change.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    loop {
        if l.is_connected() || r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    // Wait until both sides see the channel open.
    loop {
        progress(&mut l, &mut r)?;

        let l_open = l
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelOpen(id, _) if *id == cid));
        let r_open = r
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelOpen(_, _)));

        if l_open && r_open {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(10),
            "first channel should open on both sides"
        );
    }

    let stream_id = l
        .direct_api()
        .sctp_stream_id_by_channel_id(cid)
        .expect("stream id for open channel");

    // Close locally. The reset handshake must inform the remote, which
    // previously never received ChannelClose.
    l.direct_api().close_data_channel(cid);

    loop {
        progress(&mut l, &mut r)?;

        let l_closed = l
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelClose(id) if *id == cid));
        let r_closed = r
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelClose(_)));

        if l_closed && r_closed {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(20),
            "both sides should see ChannelClose"
        );
    }

    // The reset handshake finishes with round-trips (reciprocal reset and
    // RECONFIG-RESPONSEs) that carry no public events, so there is nothing to
    // wait on here. Creating the next channel immediately is fine: its stream
    // id allocation happens on a later timeout, by which time the handshake
    // rounds have been ferried through. The stream id assertion below fails
    // loudly if the allocator did not release the id in time.
    let cid2 = l.direct_api().create_data_channel(ChannelConfig {
        label: "churn2".into(),
        ..Default::default()
    });
    assert_ne!(cid, cid2);

    loop {
        progress(&mut l, &mut r)?;

        let l_open = l.events.iter().any(
            |(_, e)| matches!(e, Event::ChannelOpen(id, label) if *id == cid2 && label == "churn2"),
        );
        let r_open = r
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelOpen(_, label) if label == "churn2"));

        if l_open && r_open {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(30),
            "reopened channel should open on both sides"
        );
    }

    // The freed stream id must have been reused, proving the allocator
    // released it when the reset handshake completed.
    assert_eq!(
        l.direct_api().sctp_stream_id_by_channel_id(cid2),
        Some(stream_id),
        "reopened channel should reuse the freed stream id"
    );

    // Data flows on the reopened channel.
    loop {
        if let Some(mut chan) = l.channel(cid2) {
            chan.write(false, b"hello again").expect("write to succeed");
        }

        progress(&mut l, &mut r)?;

        let got_data = r.events.iter().any(
            |(_, e)| matches!(e, Event::ChannelData(d) if d.data.as_slice() == b"hello again"),
        );
        if got_data {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(40),
            "data should flow on the reopened channel"
        );
    }

    Ok(())
}

#[test]
pub fn negotiated_reuse_waits_for_reset_before_channel_open() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let (mut l, mut r) = connect_l_r();
    let stream_id = 10;
    let config = ChannelConfig {
        label: "old-generation".into(),
        negotiated: Some(stream_id),
        ..Default::default()
    };
    let old_l = l.direct_api().create_data_channel(config.clone());
    let _old_r = r.direct_api().create_data_channel(config);

    loop {
        progress(&mut l, &mut r)?;
        let left_open = l
            .events
            .iter()
            .any(|(_, event)| matches!(event, Event::ChannelOpen(id, _) if *id == old_l));
        let right_open = r
            .events
            .iter()
            .any(|(_, event)| matches!(event, Event::ChannelOpen(_, _)));
        if left_open && right_open {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(10),
            "negotiated channel should open on both peers"
        );
    }

    l.events.clear();
    l.direct_api().close_data_channel(old_l);

    // Process the local close, but withhold its RE-CONFIG packets. The old
    // SCTP stream therefore still exists and its reset cannot be complete.
    let close_at = l.last;
    let close_events = poll_without_delivering_network(&mut l, close_at)?;
    assert!(
        close_events
            .iter()
            .any(|event| matches!(event, Event::ChannelClose(id) if *id == old_l)),
        "the old local channel should close"
    );

    let replacement = l.direct_api().create_data_channel(ChannelConfig {
        label: "replacement".into(),
        negotiated: Some(stream_id),
        ..Default::default()
    });
    let replacement_events =
        poll_without_delivering_network(&mut l, close_at + Duration::from_millis(1))?;

    assert!(
        !replacement_events
            .iter()
            .any(|event| matches!(event, Event::ChannelOpen(id, _) if *id == replacement)),
        "a negotiated replacement must not open before the old reset completes"
    );

    Ok(())
}

#[test]
pub fn unconfirmed_reset_keeps_stream_id_reserved() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let (mut l, mut r) = connect_l_r();
    let old = l.direct_api().create_data_channel(ChannelConfig::default());

    loop {
        progress(&mut l, &mut r)?;
        if l.events
            .iter()
            .any(|(_, event)| matches!(event, Event::ChannelOpen(id, _) if *id == old))
        {
            break;
        }
        assert!(
            l.duration() < Duration::from_secs(10),
            "first channel should open"
        );
    }

    let old_stream_id = l
        .direct_api()
        .sctp_stream_id_by_channel_id(old)
        .expect("old channel should have a stream ID");
    l.direct_api().close_data_channel(old);

    // Drop all local reset traffic and advance well past the close. No peer response
    // has made the old ID safe during this interval, so it stays reserved.
    let close_at = l.last;
    let close_events = poll_without_delivering_network(&mut l, close_at)?;
    assert!(
        close_events
            .iter()
            .any(|event| matches!(event, Event::ChannelClose(id) if *id == old)),
        "the old local channel should close"
    );
    poll_without_delivering_network(&mut l, close_at + Duration::from_secs(31))?;

    let replacement = l.direct_api().create_data_channel(ChannelConfig::default());
    poll_without_delivering_network(
        &mut l,
        close_at + Duration::from_secs(31) + Duration::from_millis(1),
    )?;

    let replacement_stream_id = l
        .direct_api()
        .sctp_stream_id_by_channel_id(replacement)
        .expect("replacement should have a stream ID");
    assert_ne!(
        replacement_stream_id, old_stream_id,
        "elapsed time cannot make an unconfirmed reset safe; another free ID should be used"
    );

    Ok(())
}

#[test]
pub fn data_channel_flood() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mut change = l.sdp_api();
    let cid = change.add_channel("My little channel".into());
    let (offer, pending) = change.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    loop {
        if l.is_connected() || r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    while l.channel(cid).is_none() {
        progress(&mut l, &mut r)?;
    }

    r.set_netem(NetemConfig::new().latency(Duration::from_millis(1000)));

    let mut count = 0;

    for _ in 0..10_000 {
        let mut chan = l.channel(cid).unwrap();
        let did_write = chan.write(true, &[0u8; 1400]).expect("to write string");
        if did_write {
            count += 1;
        }
        progress(&mut l, &mut r)?;
    }

    loop {
        progress(&mut l, &mut r)?;

        if l.duration() > Duration::from_secs(10) {
            break;
        }
    }
    assert!(count > 9000, "Too few events: {}", count);

    Ok(())
}

#[test]
pub fn channel_config_inband() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    // Create in-band negotiated channel (DCEP)
    let mut change = l.sdp_api();
    let cid = change.add_channel("DCEP Channel".into());
    let (offer, pending) = change.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    // Wait for connection
    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    let mut l_channel_opened = false;
    let mut r_channel_opened = false;
    let mut l_config_available_on_open = false;
    let mut r_config_available_on_open = false;

    // Process events and verify config availability immediately when ChannelOpen is fired
    loop {
        progress(&mut l, &mut r)?;

        // Check L side events and collect channel ID if found
        let mut l_found_id = None;
        for (_, event) in &l.events {
            if let Event::ChannelOpen(id, label) = event {
                if *id == cid && label == "DCEP Channel" {
                    l_channel_opened = true;
                    l_found_id = Some(*id);
                    break;
                }
            }
        }

        // Check R side events and collect channel ID if found
        let mut r_found_id = None;
        for (_, event) in &r.events {
            if let Event::ChannelOpen(id, label) = event {
                if label == "DCEP Channel" {
                    r_channel_opened = true;
                    r_found_id = Some(*id);
                    break;
                }
            }
        }

        // Verify config is available immediately when ChannelOpen is emitted
        if let Some(id) = l_found_id {
            if let Some(channel) = l.channel(id) {
                l_config_available_on_open = channel.config().is_some();
            }
        }

        if let Some(id) = r_found_id {
            if let Some(channel) = r.channel(id) {
                r_config_available_on_open = channel.config().is_some();
            }
        }

        if (l_channel_opened && r_channel_opened) || l.duration() > Duration::from_secs(10) {
            break;
        }
    }

    assert!(l_channel_opened, "L side should receive ChannelOpen event");
    assert!(r_channel_opened, "R side should receive ChannelOpen event");
    assert!(
        l_config_available_on_open,
        "L side config should be available on ChannelOpen"
    );
    assert!(
        r_config_available_on_open,
        "R side config should be available on ChannelOpen"
    );

    Ok(())
}

#[test]
pub fn channel_config_outband_local() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    // Enable SCTP by adding a temporary channel (will be removed)
    let mut change_l = l.sdp_api();
    let _temp_cid = change_l.add_channel("temp".into());
    let (offer, pending) = change_l.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    // Wait for connection
    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    // Wait for SCTP to be established first
    loop {
        progress(&mut l, &mut r)?;

        // Check for SCTP connection via any channel events
        let connected = l
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelOpen(_, _)))
            || r.events
                .iter()
                .any(|(_, e)| matches!(e, Event::ChannelOpen(_, _)));

        if connected || l.duration() > Duration::from_secs(5) {
            break;
        }
    }

    // Create out-of-band negotiated channel on both sides
    let config = ChannelConfig {
        negotiated: Some(10),
        label: "OutOfBand Local".into(),
        ..Default::default()
    };

    let cid_l = l.direct_api().create_data_channel(config.clone());
    let cid_r = r.direct_api().create_data_channel(config);

    // Allow some time for channels to be established
    for _ in 0..10 {
        progress(&mut l, &mut r)?;
    }

    // Verify config is immediately available for locally created out-of-band channels
    let l_channel = l.channel(cid_l).expect("L channel should be available");
    let r_channel = r.channel(cid_r).expect("R channel should be available");

    assert!(
        l_channel.config().is_some(),
        "L side config should be immediately available for local out-of-band channel"
    );
    assert!(
        r_channel.config().is_some(),
        "R side config should be immediately available for local out-of-band channel"
    );

    let l_config = l_channel.config().unwrap();
    let r_config = r_channel.config().unwrap();

    assert_eq!(l_config.label, "OutOfBand Local");
    assert_eq!(r_config.label, "OutOfBand Local");
    assert_eq!(l_config.negotiated, Some(10));
    assert_eq!(r_config.negotiated, Some(10));

    Ok(())
}

#[test]
pub fn channel_config_with_protocol() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let mut l = TestRtc::new(Peer::Left);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mut change = l.sdp_api();
    let _temp_cid = change.add_channel("temp".into());
    let (offer, pending) = change.apply().unwrap();

    let answer = r.rtc.sdp_api().accept_offer(offer)?;
    l.rtc.sdp_api().accept_answer(pending, answer)?;

    // Wait for connection
    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    // Wait for SCTP to be established
    loop {
        progress(&mut l, &mut r)?;
        let connected = l
            .events
            .iter()
            .any(|(_, e)| matches!(e, Event::ChannelOpen(_, _)));
        if connected || l.duration() > Duration::from_secs(5) {
            break;
        }
    }

    // Create channels with custom protocol
    let custom_protocol = "my-custom-protocol";
    let config = ChannelConfig {
        negotiated: Some(20),
        protocol: custom_protocol.into(),
        ..Default::default()
    };

    let cid_l = l.direct_api().create_data_channel(config.clone());
    let cid_r = r.direct_api().create_data_channel(config);

    for _ in 0..10 {
        progress(&mut l, &mut r)?;
    }

    // Verify protocol is correctly set on both sides
    let l_channel = l.channel(cid_l).unwrap();
    let r_channel = r.channel(cid_r).unwrap();
    let l_config = l_channel.config().unwrap();
    let r_config = r_channel.config().unwrap();

    assert_eq!(l_config.protocol, custom_protocol);
    assert_eq!(r_config.protocol, custom_protocol);

    Ok(())
}