Skip to main content

rtci_turn/proto/
addrerror.rs

1#[cfg(test)]
2mod addrerror_test;
3
4use std::fmt;
5
6use stun::attributes::*;
7use stun::error_code::ErrorCode;
8use stun::message::*;
9
10use super::reqfamily::{REQUESTED_FAMILY_IPV4, REQUESTED_FAMILY_IPV6, RequestedAddressFamily};
11use shared::error::{Error, Result};
12
13/// The `ADDRESS-ERROR-CODE` attribute type (0x8001), comprehension-optional.
14pub const ATTR_ADDRESS_ERROR_CODE: AttrType = AttrType(0x8001);
15
16/// `AddressErrorCode` represents the `ADDRESS-ERROR-CODE` attribute as defined in
17/// [RFC 8656 Section 18.12](https://www.rfc-editor.org/rfc/rfc8656#section-18.12).
18///
19/// A server puts it in the success response to an Allocate that asked for two address
20/// families when it could allocate only one: it names the family it did not allocate and why,
21/// with 440 (Address Family not Supported) or 508 (Insufficient Capacity).
22#[derive(Default, PartialEq, Eq, Clone)]
23pub struct AddressErrorCode {
24    /// The address family that was not allocated.
25    pub family: RequestedAddressFamily,
26    /// Why: the error code, as in `ERROR-CODE`.
27    pub code: ErrorCode,
28    /// The reason phrase, UTF-8.
29    pub reason: Vec<u8>,
30}
31
32impl fmt::Debug for AddressErrorCode {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.debug_struct("AddressErrorCode")
35            .field("family", &self.family)
36            .field("code", &self.code.0)
37            .field("reason", &String::from_utf8_lossy(&self.reason))
38            .finish()
39    }
40}
41
42impl fmt::Display for AddressErrorCode {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(
45            f,
46            "{}: {} {}",
47            self.family,
48            self.code.0,
49            String::from_utf8_lossy(&self.reason)
50        )
51    }
52}
53
54const ADDRESS_ERROR_CODE_HEADER: usize = 4;
55/// RFC 8656 §18.12: fewer than 128 characters, at most 763 bytes when decoding.
56const ADDRESS_ERROR_CODE_REASON_MAX: usize = 763;
57const ERROR_CODE_MODULO: u16 = 100;
58
59impl Setter for AddressErrorCode {
60    /// Adds `ADDRESS-ERROR-CODE` to message. The reserved bits are zero.
61    fn add_to(&self, m: &mut Message) -> Result<()> {
62        if self.family != REQUESTED_FAMILY_IPV4 && self.family != REQUESTED_FAMILY_IPV6 {
63            return Err(Error::ErrInvalidRequestedFamilyValue);
64        }
65        let (class, number) = (
66            self.code.0 / ERROR_CODE_MODULO,
67            self.code.0 % ERROR_CODE_MODULO,
68        );
69        if !(3..=6).contains(&class) || self.reason.len() > ADDRESS_ERROR_CODE_REASON_MAX {
70            return Err(Error::Other(format!(
71                "ADDRESS-ERROR-CODE cannot carry {}",
72                self.code.0
73            )));
74        }
75        let mut v = Vec::with_capacity(ADDRESS_ERROR_CODE_HEADER + self.reason.len());
76        v.extend_from_slice(&[self.family.0, 0, class as u8, number as u8]);
77        v.extend_from_slice(&self.reason);
78        m.add(ATTR_ADDRESS_ERROR_CODE, &v);
79        Ok(())
80    }
81}
82
83impl Getter for AddressErrorCode {
84    /// Decodes `ADDRESS-ERROR-CODE` from message. The 13 reserved bits are ignored, as
85    /// RFC 8656 §18.12 has a client do.
86    fn get_from(&mut self, m: &Message) -> Result<()> {
87        let v = m.get(ATTR_ADDRESS_ERROR_CODE)?;
88        if v.len() < ADDRESS_ERROR_CODE_HEADER {
89            return Err(Error::ErrUnexpectedEof);
90        }
91        if v[0] != REQUESTED_FAMILY_IPV4.0 && v[0] != REQUESTED_FAMILY_IPV6.0 {
92            return Err(Error::ErrInvalidRequestedFamilyValue);
93        }
94        // Byte 1 and the upper five bits of byte 2 are reserved; the class is three bits.
95        let class = u16::from(v[2] & 0x07);
96        let number = u16::from(v[3]);
97        self.family = RequestedAddressFamily(v[0]);
98        self.code = ErrorCode(class * ERROR_CODE_MODULO + number);
99        self.reason = v[ADDRESS_ERROR_CODE_HEADER..].to_vec();
100        Ok(())
101    }
102}