rtc-turn 0.21.0-alpha.1

RTC TURN in Rust
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
use super::*;
use sansio::Protocol;
use std::collections::HashSet;
use std::net::UdpSocket;

/// Tests may resolve the built-in provider; library code never does.
fn test_crypto_provider() -> std::sync::Arc<dyn crypto::RTCCryptoProvider> {
    crypto::default_provider().expect("a built-in crypto provider must be enabled for tests")
}

fn create_listening_test_client(rto_in_ms: u64) -> Result<(UdpSocket, Client)> {
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;

    let client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: String::new(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: String::new(),
            password: String::new(),
            realm: String::new(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms,
        },
        test_crypto_provider(),
    )?;

    Ok((udp_socket, client))
}

fn create_listening_test_client_with_stun_serv() -> Result<(UdpSocket, Client)> {
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;

    let client = Client::new(
        ClientConfig {
            stun_serv_addr: "stun1.l.google.com:19302".to_owned(),
            turn_serv_addr: String::new(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: String::new(),
            password: String::new(),
            realm: String::new(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
        },
        test_crypto_provider(),
    )?;

    Ok((udp_socket, client))
}

#[test]
fn test_client_with_stun_send_binding_request() -> Result<()> {
    //env_logger::init();

    let (conn, mut client) = create_listening_test_client_with_stun_serv()?;
    let local_addr = conn.local_addr()?;

    let tid = client.send_binding_request(Instant::now())?;

    while let Some(transmit) = client.poll_write() {
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }

    let mut buffer = vec![0u8; 2048];
    let (n, peer_addr) = conn.recv_from(&mut buffer)?;
    client.handle_read(TransportMessage {
        now: Instant::now(),
        transport: TransportContext {
            local_addr,
            peer_addr,
            transport_protocol: TransportProtocol::UDP,
            ecn: None,
        },
        message: BytesMut::from(&buffer[..n]),
    })?;

    if let Some(event) = client.poll_event() {
        match event {
            Event::BindingResponse(id, refl_addr) => {
                assert_eq!(tid, id);
                debug!("mapped-addr: {}", refl_addr);
            }
            _ => assert!(false),
        }
    } else {
        assert!(false);
    }

    assert_eq!(0, client.tr_map.size(), "should be no transaction left");

    client.close()
}

#[test]
fn test_client_with_stun_send_binding_request_to_parallel() -> Result<()> {
    //env_logger::init();

    let (conn, mut client) = create_listening_test_client(0)?;
    let local_addr = conn.local_addr()?;

    let to = lookup_host(true, "stun1.l.google.com:19302")?;

    let tid1 = client.send_binding_request_to(Instant::now(), to)?;
    let tid2 = client.send_binding_request_to(Instant::now(), to)?;
    while let Some(transmit) = client.poll_write() {
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }

    let mut buffer = vec![0u8; 2048];
    for _ in 0..2 {
        let (n, peer_addr) = conn.recv_from(&mut buffer)?;
        client.handle_read(TransportMessage {
            now: Instant::now(),
            transport: TransportContext {
                local_addr,
                peer_addr,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&buffer[..n]),
        })?;
    }

    let mut tids = HashSet::new();
    while let Some(event) = client.poll_event() {
        match event {
            Event::BindingResponse(tid, refl_addr) => {
                tids.insert(tid);
                debug!("mapped-addr: {}", refl_addr);
            }
            _ => {}
        }
    }

    assert_eq!(2, tids.len());
    assert!(tids.contains(&tid1));
    assert!(tids.contains(&tid2));

    client.close()
}

#[test]
fn test_client_with_stun_send_binding_request_to_timeout() -> Result<()> {
    //env_logger::init();

    let (conn, mut client) = create_listening_test_client(10)?;

    let to = lookup_host(true, "127.0.0.1:9")?;

    let tid = client.send_binding_request_to(Instant::now(), to)?;
    while let Some(transmit) = client.poll_write() {
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }

    while let Some(to) = client.poll_timeout() {
        client.handle_timeout(to)?;
    }

    if let Some(event) = client.poll_event() {
        match event {
            Event::TransactionTimeout(id) => {
                assert_eq!(tid, id);
            }
            _ => assert!(false),
        }
    } else {
        assert!(false);
    }

    client.close()
}

/// The allocation-refresh timer is seeded from the instant passed to `RelayState::new` and
/// compared against the instant passed to `handle_timeout`, so a refresh can be observed by
/// arithmetic on a base instant with no wall-clock time passing and no sleeping.
#[test]
fn test_relay_refresh_timers_run_on_injected_time() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
        },
        test_crypto_provider(),
    )?;

    // Stand in for a granted allocation, seeded at t(0) with a 10-minute lifetime.
    let lifetime = Duration::from_secs(600);
    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            vec![0u8; 16],
            Nonce::new(ATTR_NONCE, "nonce".to_owned()),
            lifetime,
        ),
    );

    // The allocation is refreshed at half its lifetime; permissions sooner, at 120s.
    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(120)));

    // One second before the allocation deadline nothing is sent for it. (The permission
    // refresh at t(120) has already fired by then, so drain whatever it queued first.)
    client.relay(relayed_addr)?.handle_timeout(t(120));
    while client.poll_write().is_some() {}
    client.relay(relayed_addr)?.handle_timeout(t(299));
    assert!(
        client.poll_write().is_none(),
        "no refresh is due one second before the deadline"
    );

    // At the deadline the Refresh request goes out, stamped with the caller's instant.
    client.relay(relayed_addr)?.handle_timeout(t(300));
    let transmit = client
        .poll_write()
        .expect("the allocation must be refreshed at half its lifetime");
    assert_eq!(
        transmit.now,
        t(300),
        "the request carries the instant the caller supplied, not an ambient reading"
    );

    let mut msg = Message::new();
    msg.raw = transmit.message.to_vec();
    msg.decode()?;
    assert_eq!(msg.typ.method, METHOD_REFRESH);

    // Both timers advance by a fixed step from where they were, rather than being recomputed
    // against the wall clock: permissions are next again at 360s, the allocation at 600s.
    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(360)));

    client.relay(relayed_addr)?.handle_timeout(t(600));
    let transmit = client
        .poll_write()
        .expect("the allocation must be refreshed again a half-lifetime later");
    assert_eq!(transmit.now, t(600));

    client.close()
}

/// A relay whose lifetime has gone to zero must not hand the caller a deadline that never
/// advances.
///
/// This is the root cause behind [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862).
/// `Relay::handle_timeout` advances the allocation timer by adding to the timer's **own**
/// previous value rather than to `now`:
///
/// ```ignore
/// relay.refresh_alloc_timer = relay.refresh_alloc_timer.add(relay.lifetime / 2);
/// ```
///
/// so the step size is `lifetime / 2`. `lifetime` is assigned straight from the server's
/// LIFETIME attribute on every refresh response, with no floor — and `Relay::close` refreshes
/// with `LIFETIME=0`, which is how RFC 5766 deallocates. Once the server echoes that back the
/// step becomes zero, the timer is frozen, and because nothing ever removes the entry from
/// `client.relays` the relay keeps reporting it forever.
///
/// The peer-connection driver treats an expired deadline as "handle it and loop again", so a
/// frozen expired deadline is an unbounded hot loop — starving the very `Close` that triggered
/// it. That matches the report: cleanup never completes and the process will not exit.
#[test]
fn test_zero_lifetime_relay_does_not_freeze_its_deadline() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            vec![0u8; 16],
            Nonce::new(ATTR_NONCE, "nonce".to_owned()),
            Duration::from_secs(600),
        ),
    );

    // What the server's response to `close()`'s LIFETIME=0 refresh does.
    client.relays.get_mut(&relayed_addr).unwrap().lifetime = Duration::from_secs(0);

    // Drive past both timers, exactly as the driver does: read the deadline, handle it,
    // read again. The deadline must move, or the caller is told to act on the same instant
    // forever.
    let mut previous = client.relay(relayed_addr)?.poll_timeout();
    for iteration in 0..10 {
        let now = t(1000 + iteration);
        client.relay(relayed_addr)?.handle_timeout(now);
        let next = client.relay(relayed_addr)?.poll_timeout();

        assert!(
            next != previous || next.is_none(),
            "iteration {iteration}: deadline did not advance ({previous:?} -> {next:?}) while \
             `now` is {:?} past it. The driver reads this as a zero delay, calls handle_timeout \
             and loops — forever.",
            now.saturating_duration_since(previous.unwrap_or(now)),
        );
        previous = next;
    }

    Ok(())
}

/// A server confirming deallocation must leave no relay behind.
///
/// `close()` refreshes the allocation with `LIFETIME=0`; the server echoes that back to confirm
/// the allocation is gone. Before the fix for
/// [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862) the response handler stored the
/// zero and nothing else — the entry stayed in `client.relays` forever, still reporting refresh
/// deadlines for an allocation that no longer existed, and still trying to refresh it.
///
/// Flooring the refresh step stops the *hot loop*; only removing the relay stops the dead
/// allocation. Both are needed, and this covers the second.
#[test]
fn test_zero_lifetime_response_drops_the_relay() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            vec![0u8; 16],
            Nonce::new(ATTR_NONCE, "nonce".to_owned()),
            Duration::from_secs(600),
        ),
    );
    assert!(client.relay(relayed_addr)?.poll_timeout().is_some());

    // What the TURN server sends back when it honours `close()`'s LIFETIME=0 refresh.
    let mut res = Message::new();
    res.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_REFRESH, CLASS_SUCCESS_RESPONSE)),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(0))),
    ])?;

    client
        .relay(relayed_addr)?
        .handle_refresh_allocation_response(res)?;

    assert!(
        !client.relays.contains_key(&relayed_addr),
        "a deallocated allocation must not stay in the relay map — it would keep reporting \
         refresh deadlines and keep trying to refresh something that no longer exists"
    );

    Ok(())
}

/// An Allocate success response carrying `LIFETIME=0` is rejected, not accepted as a
/// degenerate allocation.
///
/// RFC 5766 §6.2 has the server take `min(client proposed, server maximum)` and fall back to
/// the *default* lifetime (600 s) whenever that does not exceed it, so a successful Allocate
/// never returns a lifetime below the default — zero is a protocol violation. Zero is
/// meaningful only on the Refresh path (§7), where it means the allocation was deleted.
///
/// Accepting it would insert a `RelayState` whose `refresh_alloc_timer` is `now.add(0)` —
/// already expired at construction — for an allocation that does not exist. That relay then
/// reports an expired refresh deadline forever, which is the hot loop in
/// [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862), reached here without any
/// close being involved.
#[test]
fn test_zero_lifetime_allocate_response_is_an_error() -> Result<()> {
    let base = Instant::now();
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
        },
        test_crypto_provider(),
    )?;

    let mut res = Message::new();
    res.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_SUCCESS_RESPONSE)),
        Box::new(RelayedAddress {
            ip: "127.0.0.1".parse().unwrap(),
            port: 50000,
        }),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(0))),
    ])?;

    client.handle_allocate_response(
        base,
        res,
        TransactionType::AllocateRequest(Nonce::new(ATTR_NONCE, "nonce".to_owned())),
    )?;

    assert!(
        client.relays.is_empty(),
        "a zero-lifetime Allocate response must not create a relay — the allocation does not \
         exist, and the relay would report an already-expired refresh deadline forever"
    );

    match client.poll_event() {
        Some(Event::AllocateError(_, _)) => Ok(()),
        other => {
            panic!("expected AllocateError for a zero-lifetime Allocate response, got {other:?}")
        }
    }
}