webrtc_turn/proto/
channum.rs

1#[cfg(test)]
2mod channnum_test;
3
4use stun::attributes::*;
5use stun::checks::*;
6use stun::message::*;
7
8use util::Error;
9
10use std::fmt;
11
12// 16 bits of uint + 16 bits of RFFU = 0.
13const CHANNEL_NUMBER_SIZE: usize = 4;
14
15// See https://tools.ietf.org/html/rfc5766#section-11:
16//
17// 0x4000 through 0x7FFF: These values are the allowed channel
18// numbers (16,383 possible values).
19pub const MIN_CHANNEL_NUMBER: u16 = 0x4000;
20pub const MAX_CHANNEL_NUMBER: u16 = 0x7FFF;
21
22// ChannelNumber represents CHANNEL-NUMBER attribute.
23//
24// The CHANNEL-NUMBER attribute contains the number of the channel.
25//
26// RFC 5766 Section 14.1
27// encoded as uint16
28#[derive(Default, Eq, PartialEq, Debug, Copy, Clone, Hash)]
29pub struct ChannelNumber(pub u16);
30
31impl fmt::Display for ChannelNumber {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "{}", self.0)
34    }
35}
36
37impl Setter for ChannelNumber {
38    // AddTo adds CHANNEL-NUMBER to message.
39    fn add_to(&self, m: &mut Message) -> Result<(), Error> {
40        let mut v = vec![0; CHANNEL_NUMBER_SIZE];
41        v[..2].copy_from_slice(&self.0.to_be_bytes());
42        // v[2:4] are zeroes (RFFU = 0)
43        m.add(ATTR_CHANNEL_NUMBER, &v);
44        Ok(())
45    }
46}
47
48impl Getter for ChannelNumber {
49    // GetFrom decodes CHANNEL-NUMBER from message.
50    fn get_from(&mut self, m: &Message) -> Result<(), Error> {
51        let v = m.get(ATTR_CHANNEL_NUMBER)?;
52
53        check_size(ATTR_CHANNEL_NUMBER, v.len(), CHANNEL_NUMBER_SIZE)?;
54
55        //_ = v[CHANNEL_NUMBER_SIZE-1] // asserting length
56        self.0 = u16::from_be_bytes([v[0], v[1]]);
57        // v[2:4] is RFFU and equals to 0.
58        Ok(())
59    }
60}
61
62impl ChannelNumber {
63    // is_channel_number_valid returns true if c in [0x4000, 0x7FFF].
64    fn is_channel_number_valid(&self) -> bool {
65        self.0 >= MIN_CHANNEL_NUMBER && self.0 <= MAX_CHANNEL_NUMBER
66    }
67
68    // Valid returns true if channel number has correct value that complies RFC 5766 Section 11 range.
69    pub fn valid(&self) -> bool {
70        self.is_channel_number_valid()
71    }
72}