rustun 0.5.0

A library for implementing STUN server and client asynchronously
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
use fibers_timeout_queue::TimeoutQueue;
use fibers_transport::{PollRecv, PollSend, Result, Transport, UdpTransport};
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use stun_codec::{Attribute, DecodedMessage, Message, MessageClass, TransactionId};

use super::StunTransport;

/// [`StunUdpTransporter`] builder.
///
/// [`StunUdpTransporter`]: ./struct.StunUdpTransporter.html
#[derive(Debug, Clone)]
pub struct StunUdpTransporterBuilder {
    rto: Duration,
    rto_cache_duration: Duration,
    min_transaction_interval: Duration,
    max_outstanding_transactions: usize,
}
impl StunUdpTransporterBuilder {
    /// The default value of RTO (Retransmission TimeOut).
    ///
    /// > A client SHOULD retransmit a STUN request message starting with an
    /// > interval of RTO ("Retransmission TimeOut"), doubling after each
    /// > retransmission.  The RTO is an estimate of the round-trip time (RTT),
    /// > and is computed as described in RFC 2988 [RFC2988], with two
    /// > exceptions.  First, the initial value for RTO SHOULD be configurable
    /// > (rather than the 3 s recommended in RFC 2988) and SHOULD be greater
    /// > than **500 ms**.
    /// >
    /// > [RFC 5389 -- 7.2.1. Sending over UDP]
    ///
    /// [RFC 5389 -- 7.2.1. Sending over UDP]: https://tools.ietf.org/html/rfc5389#section-7.2.1
    pub const DEFAULT_RTO_MS: u64 = 500;

    /// The default duration preserving a cached RTO (Retransmission TimeOut).
    ///
    /// > The value for RTO SHOULD be cached by a client after the completion
    /// > of the transaction, and used as the starting value for RTO for the
    /// > next transaction to the same server (based on equality of IP
    /// > address).  The value SHOULD be considered stale and discarded after
    /// > **10 minutes**.
    /// >
    /// > [RFC 5389 -- 7.2.1. Sending over UDP]
    ///
    /// [RFC 5389 -- 7.2.1. Sending over UDP]: https://tools.ietf.org/html/rfc5389#section-7.2.1
    pub const DEFAULT_RTO_CACHE_DURATION_MS: u64 = 10 * 60 * 1000;

    /// The default max concurrent transactions by a client to a server.
    ///
    /// > At any time, a client MAY have multiple outstanding STUN requests
    /// > with the same STUN server (that is, multiple transactions in
    /// > progress, with different transaction IDs).  Absent other limits to
    /// > the rate of new transactions (such as those specified by ICE for
    /// > connectivity checks or when STUN is run over TCP), a client SHOULD
    /// > space new transactions to a server by RTO and SHOULD limit itself to
    /// > **ten outstanding transactions** to the same server.
    /// >
    /// > [RFC 5389 -- 7.2. Sending the Request or Indication]
    ///
    /// [RFC 5389 -- 7.2. Sending the Request or Indication]: https://tools.ietf.org/html/rfc5389#section-7.2
    pub const DEFAULT_MAX_OUTSTANDING_TRANSACTIONS: usize = 10;

    /// The default interval between transactions issued by a client to a serve.
    ///
    /// > At any time, a client MAY have multiple outstanding STUN requests
    /// > with the same STUN server (that is, multiple transactions in
    /// > progress, with different transaction IDs).  Absent other limits to
    /// > the rate of new transactions (such as those specified by ICE for
    /// > connectivity checks or when STUN is run over TCP), **a client SHOULD
    /// > space new transactions to a server by RTO** and SHOULD limit itself to
    /// > ten outstanding transactions to the same server.
    /// >
    /// > [RFC 5389 -- 7.2. Sending the Request or Indication]
    ///
    /// [RFC 5389 -- 7.2. Sending the Request or Indication]: https://tools.ietf.org/html/rfc5389#section-7.2
    pub const DEFAULT_MIN_TRANSACTION_INTERVAL_MS: u64 = Self::DEFAULT_RTO_MS;

    /// Makes a new `StunUdpTransporterBuilder` instance with the default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the RTO of the resulting instance.
    ///
    /// The default value is `Duration::from_millis(DEFAULT_RTO_MS)`.
    pub fn rto(&mut self, rto: Duration) -> &mut Self {
        self.rto = rto;
        self
    }

    /// Sets the RTO cache duration of the resulting instance.
    ///
    /// The default value is `Duration::from_millis(DEFAULT_RTO_CACHE_DURATION_MS)`.
    pub fn rto_cache_duration(&mut self, duration: Duration) -> &mut Self {
        self.rto_cache_duration = duration;
        self
    }

    /// Sets the minimum interval of the consecutive request/response transactions of
    /// the resulting instance.
    ///
    /// The default value is `Duration::from_millis(DEFAULT_MIN_TRANSACTION_INTERVAL_MS)`.
    pub fn min_transaction_interval(&mut self, interval: Duration) -> &mut Self {
        self.min_transaction_interval = interval;
        self
    }

    /// Sets the number of the maximum outstanding transactions of the resulting instance.
    ///
    /// The default value is `DEFAULT_MAX_OUTSTANDING_TRANSACTIONS`.
    pub fn max_outstanding_transactions(&mut self, max: usize) -> &mut Self {
        self.max_outstanding_transactions = max;
        self
    }

    /// Makes a new `StunUdpTransporter` instance with the given settings.
    pub fn finish<A, T>(&self, inner: T) -> StunUdpTransporter<A, T>
    where
        A: Attribute,
        T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
    {
        let inner = RetransmitTransporter {
            inner,
            timeout_queue: TimeoutQueue::new(),
            peers: HashMap::new(),
            rto: self.rto,
            rto_cache_duration: self.rto_cache_duration,
            min_transaction_interval: self.min_transaction_interval,
            max_outstanding_transactions: self.max_outstanding_transactions,
        };
        StunUdpTransporter { inner }
    }
}
impl Default for StunUdpTransporterBuilder {
    fn default() -> Self {
        StunUdpTransporterBuilder {
            rto: Duration::from_millis(Self::DEFAULT_RTO_MS),
            rto_cache_duration: Duration::from_millis(Self::DEFAULT_RTO_CACHE_DURATION_MS),
            min_transaction_interval: Duration::from_millis(
                Self::DEFAULT_MIN_TRANSACTION_INTERVAL_MS,
            ),
            max_outstanding_transactions: Self::DEFAULT_MAX_OUTSTANDING_TRANSACTIONS,
        }
    }
}

/// UDP transport layer that can be used for STUN.
#[derive(Debug)]
pub struct StunUdpTransporter<A, T> {
    inner: RetransmitTransporter<A, T>,
}
impl<A, T> StunUdpTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    /// Makes a new `StunUdpTransporter` instance.
    ///
    /// This is equivalent to `StunUdpTransporterBuilder::new().finish(inner)`.
    pub fn new(inner: T) -> Self {
        StunUdpTransporterBuilder::new().finish(inner)
    }

    /// Returns a reference to the inner transporter.
    pub fn inner_ref(&self) -> &T {
        &self.inner.inner
    }

    /// Returns a mutable reference to the inner transporter.
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner.inner
    }
}
impl<A, T> Transport for StunUdpTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    type PeerAddr = SocketAddr;
    type SendItem = Message<A>;
    type RecvItem = DecodedMessage<A>;

    fn start_send(&mut self, peer: Self::PeerAddr, item: Self::SendItem) -> Result<()> {
        track!(self.inner.start_send(peer, item))
    }

    fn poll_send(&mut self) -> PollSend {
        track!(self.inner.poll_send())
    }

    fn poll_recv(&mut self) -> PollRecv<(Self::PeerAddr, Self::RecvItem)> {
        track!(self.inner.poll_recv())
    }
}
impl<A, T> StunTransport<A> for StunUdpTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    fn finish_transaction(
        &mut self,
        peer: &SocketAddr,
        transaction_id: TransactionId,
    ) -> Result<()> {
        track!(self.inner.finish_transaction(peer, transaction_id))
    }
}

/// An implementation of [`StunTransport`] that retransmits request messages for improving reliability.
///
/// [`StunTransport`]: ./trait.StunTransport.html
#[derive(Debug)]
struct RetransmitTransporter<A, T> {
    inner: T,
    timeout_queue: TimeoutQueue<TimeoutEntry<A>>,
    peers: HashMap<SocketAddr, PeerState<A>>,
    rto: Duration,
    rto_cache_duration: Duration,
    min_transaction_interval: Duration,
    max_outstanding_transactions: usize,
}
impl<A, T> RetransmitTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    fn waiting_time(&self, peer: SocketAddr) -> Option<Duration> {
        self.peers[&peer]
            .last_transaction_start_time
            .elapsed()
            .ok()
            .and_then(|d| self.min_transaction_interval.checked_sub(d))
    }

    fn peer_mut(&mut self, peer: SocketAddr) -> &mut PeerState<A> {
        self.peers.get_mut(&peer).expect("never fails")
    }

    #[allow(clippy::map_entry)]
    fn start_transaction(
        &mut self,
        peer: SocketAddr,
        request: Message<A>,
        first: bool,
    ) -> Result<()> {
        if !self.peers.contains_key(&peer) {
            self.peers.insert(peer, PeerState::new(peer, self.rto));
        }

        if self.peers[&peer].waiting {
            self.peer_mut(peer).pending(request, first);
        } else if let Some(duration) = self.waiting_time(peer) {
            self.peer_mut(peer).waiting = true;
            self.timeout_queue
                .push(TimeoutEntry::AllowNextRequest { peer }, duration);
            self.peer_mut(peer).pending(request, first);
        } else if self.peers[&peer].transactions.len() >= self.max_outstanding_transactions {
            self.peer_mut(peer).pending(request, first);
        } else {
            track!(self.inner.start_send(peer, request.clone()))?;
            let timeout = self.peer_mut(peer).start_transaction(request);
            self.timeout_queue.push(timeout.0, timeout.1);
        }
        Ok(())
    }

    fn poll_timeout(&mut self) -> Option<TimeoutEntry<A>> {
        let peers = &self.peers;
        self.timeout_queue.filter_pop(|entry| {
            if let TimeoutEntry::Retransmit { peer, request, .. } = entry {
                peers.get(peer).map_or(false, |p| {
                    p.transactions.contains(&request.transaction_id())
                })
            } else {
                true
            }
        })
    }

    fn handle_pending_request(&mut self, peer: SocketAddr) -> Result<()> {
        if !self.peers.contains_key(&peer) {
            return Ok(());
        }
        if let Some(request) = self.peer_mut(peer).pop_pending_request() {
            track!(self.start_transaction(peer, request, false))?;
        }
        if self.peers[&peer].is_idle() {
            self.peers.remove(&peer);
        }
        Ok(())
    }

    fn handle_retransmit(
        &mut self,
        peer: SocketAddr,
        request: Message<A>,
        rto: Duration,
    ) -> Result<()> {
        if let Some(p) = self.peers.get_mut(&peer) {
            if let Some(request) = p.retransmit(
                request,
                rto,
                self.rto_cache_duration,
                &mut self.timeout_queue,
            ) {
                track!(self.inner.start_send(peer, request))?;
            }
        }
        Ok(())
    }
}
impl<A, T> Transport for RetransmitTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    type PeerAddr = SocketAddr;
    type SendItem = Message<A>;
    type RecvItem = DecodedMessage<A>;

    fn start_send(&mut self, peer: SocketAddr, item: Self::SendItem) -> Result<()> {
        if item.class() == MessageClass::Request {
            track!(self.start_transaction(peer, item, true))
        } else {
            track!(self.inner.start_send(peer, item))
        }
    }

    fn poll_send(&mut self) -> PollSend {
        while let Some(entry) = self.poll_timeout() {
            match entry {
                TimeoutEntry::Retransmit {
                    peer,
                    request,
                    next_rto,
                } => {
                    track!(self.handle_retransmit(peer, request, next_rto))?;
                }
                TimeoutEntry::ExpireRtoCache { peer, cached_rto } => {
                    if let Some(p) = self.peers.get_mut(&peer) {
                        if p.cached_rto == cached_rto {
                            p.cached_rto = self.rto;
                        }
                    }
                }
                TimeoutEntry::AllowNextRequest { peer } => {
                    self.peer_mut(peer).waiting = false;
                    track!(self.handle_pending_request(peer))?;
                }
            }
        }

        track!(self.inner.poll_send())
    }

    fn poll_recv(&mut self) -> PollRecv<(Self::PeerAddr, Self::RecvItem)> {
        track!(self.inner.poll_recv())
    }
}
impl<A, T> StunTransport<A> for RetransmitTransporter<A, T>
where
    A: Attribute,
    T: UdpTransport<SendItem = Message<A>, RecvItem = DecodedMessage<A>>,
{
    fn finish_transaction(
        &mut self,
        peer: &SocketAddr,
        transaction_id: TransactionId,
    ) -> Result<()> {
        if let Some(p) = self.peers.get_mut(peer) {
            p.finish_transaction(transaction_id);
        }
        track!(self.handle_pending_request(*peer))
    }
}

#[derive(Debug)]
enum TimeoutEntry<A> {
    Retransmit {
        peer: SocketAddr,
        request: Message<A>,
        next_rto: Duration,
    },
    ExpireRtoCache {
        peer: SocketAddr,
        cached_rto: Duration,
    },
    AllowNextRequest {
        peer: SocketAddr,
    },
}

#[derive(Debug)]
struct PeerState<A> {
    peer: SocketAddr,
    transactions: HashSet<TransactionId>,
    pending_requests: VecDeque<Message<A>>,
    waiting: bool,
    last_transaction_start_time: SystemTime,
    cached_rto: Duration,
}
impl<A: Attribute> PeerState<A> {
    fn new(peer: SocketAddr, rto: Duration) -> Self {
        PeerState {
            peer,
            transactions: HashSet::new(),
            pending_requests: VecDeque::new(),
            waiting: false,
            last_transaction_start_time: UNIX_EPOCH,
            cached_rto: rto,
        }
    }

    fn pending(&mut self, request: Message<A>, first: bool) {
        if first {
            self.pending_requests.push_back(request);
        } else {
            self.pending_requests.push_front(request);
        }
    }

    fn is_idle(&self) -> bool {
        self.transactions.is_empty() && !self.waiting
    }

    fn pop_pending_request(&mut self) -> Option<Message<A>> {
        while let Some(request) = self.pending_requests.pop_front() {
            if self.transactions.contains(&request.transaction_id()) {
                return Some(request);
            }
        }
        None
    }

    fn retransmit(
        &mut self,
        request: Message<A>,
        rto: Duration,
        rto_cache_duration: Duration,
        queue: &mut TimeoutQueue<TimeoutEntry<A>>,
    ) -> Option<Message<A>> {
        if self.transactions.contains(&request.transaction_id()) {
            queue.push(
                TimeoutEntry::Retransmit {
                    peer: self.peer,
                    request: request.clone(),
                    next_rto: rto * 2,
                },
                rto,
            );
            if self.cached_rto < rto {
                self.cached_rto = rto;
                queue.push(
                    TimeoutEntry::ExpireRtoCache {
                        peer: self.peer,
                        cached_rto: rto,
                    },
                    rto_cache_duration,
                );
            }
            Some(request)
        } else {
            None
        }
    }

    fn start_transaction(&mut self, request: Message<A>) -> (TimeoutEntry<A>, Duration) {
        self.transactions.insert(request.transaction_id());
        self.last_transaction_start_time = SystemTime::now();
        let entry = TimeoutEntry::Retransmit {
            peer: self.peer,
            request,
            next_rto: self.cached_rto * 2,
        };
        (entry, self.cached_rto)
    }

    fn finish_transaction(&mut self, transaction_id: TransactionId) {
        self.transactions.remove(&transaction_id);
    }
}