webrtc_turn/proto/
lifetime.rs

1#[cfg(test)]
2mod lifetime_test;
3
4use stun::attributes::*;
5use stun::checks::*;
6use stun::message::*;
7
8use util::Error;
9
10use std::fmt;
11use std::time::Duration;
12
13// DEFAULT_LIFETIME in RFC 5766 is 10 minutes.
14//
15// RFC 5766 Section 2.2
16pub const DEFAULT_LIFETIME: Duration = Duration::from_secs(10 * 60);
17
18// Lifetime represents LIFETIME attribute.
19//
20// The LIFETIME attribute represents the duration for which the server
21// will maintain an allocation in the absence of a refresh. The value
22// portion of this attribute is 4-bytes long and consists of a 32-bit
23// unsigned integral value representing the number of seconds remaining
24// until expiration.
25//
26// RFC 5766 Section 14.2
27#[derive(Default, Debug, PartialEq)]
28pub struct Lifetime(pub Duration);
29
30impl fmt::Display for Lifetime {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "{}s", self.0.as_secs())
33    }
34}
35
36// uint32 seconds
37const LIFETIME_SIZE: usize = 4; // 4 bytes, 32 bits
38
39impl Setter for Lifetime {
40    // AddTo adds LIFETIME to message.
41    fn add_to(&self, m: &mut Message) -> Result<(), Error> {
42        let mut v = vec![0; LIFETIME_SIZE];
43        v.copy_from_slice(&(self.0.as_secs() as u32).to_be_bytes());
44        m.add(ATTR_LIFETIME, &v);
45        Ok(())
46    }
47}
48
49impl Getter for Lifetime {
50    // GetFrom decodes LIFETIME from message.
51    fn get_from(&mut self, m: &Message) -> Result<(), Error> {
52        let v = m.get(ATTR_LIFETIME)?;
53
54        check_size(ATTR_LIFETIME, v.len(), LIFETIME_SIZE)?;
55
56        let seconds = u32::from_be_bytes([v[0], v[1], v[2], v[3]]);
57        self.0 = Duration::from_secs(seconds as u64);
58
59        Ok(())
60    }
61}