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
#[cfg(test)]
mod evenport_test;

use stun::attributes::*;
use stun::checks::*;
use stun::message::*;

use util::Error;

use std::fmt;

// EvenPort represents EVEN-PORT attribute.
//
// This attribute allows the client to request that the port in the
// relayed transport address be even, and (optionally) that the server
// reserve the next-higher port number.
//
// RFC 5766 Section 14.6
#[derive(Default, Debug, PartialEq)]
pub struct EvenPort {
    // reserve_port means that the server is requested to reserve
    // the next-higher port number (on the same IP address)
    // for a subsequent allocation.
    reserve_port: bool,
}

impl fmt::Display for EvenPort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.reserve_port {
            write!(f, "reserve: true")
        } else {
            write!(f, "reserve: false")
        }
    }
}

const EVEN_PORT_SIZE: usize = 1;
const FIRST_BIT_SET: u8 = 0b10000000; //FIXME? (1 << 8) - 1;

impl Setter for EvenPort {
    // AddTo adds EVEN-PORT to message.
    fn add_to(&self, m: &mut Message) -> Result<(), Error> {
        let mut v = vec![0; EVEN_PORT_SIZE];
        if self.reserve_port {
            // Set first bit to 1.
            v[0] = FIRST_BIT_SET;
        }
        m.add(ATTR_EVEN_PORT, &v);
        Ok(())
    }
}

impl Getter for EvenPort {
    // GetFrom decodes EVEN-PORT from message.
    fn get_from(&mut self, m: &Message) -> Result<(), Error> {
        let v = m.get(ATTR_EVEN_PORT)?;

        check_size(ATTR_EVEN_PORT, v.len(), EVEN_PORT_SIZE)?;

        if v[0] & FIRST_BIT_SET > 0 {
            self.reserve_port = true;
        }
        Ok(())
    }
}