stun_rs/attributes/turn/
address_error_code.rs

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
use crate::attributes::{stunt_attribute, DecodeAttributeValue, EncodeAttributeValue};
use crate::context::{AttributeDecoderContext, AttributeEncoderContext};
use crate::Decode;
use crate::Encode;
use crate::{AddressFamily, ErrorCode, StunError};

const ADDRESS_ERROR_CODE: u16 = 0x8001;

/// This attribute is used by servers to signal the reason for not
/// allocating the requested address family.
/// # Examples
///```rust
/// # use stun_rs::attributes::turn::AddressErrorCode;
/// # use stun_rs::AddressFamily;
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let error = stun_rs::ErrorCode::new(508, "Insufficient Capacity")?;
/// let attr = AddressErrorCode::new(AddressFamily::IPv4, error);
/// assert_eq!(attr.error_code().class(), 5);
/// assert_eq!(attr.error_code().number(), 8);
/// assert_eq!(attr.error_code().reason(), "Insufficient Capacity");
/// assert_eq!(attr.family(), AddressFamily::IPv4);
/// #  Ok(())
/// # }
///```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressErrorCode {
    family: AddressFamily,
    error_code: ErrorCode,
}

impl AddressErrorCode {
    /// Creates a new [`ErrorCode`] attribute.
    /// # Arguments:
    /// * `family` - The address family.
    /// * `error_code` - The error code.
    pub fn new(family: AddressFamily, error_code: ErrorCode) -> Self {
        Self { family, error_code }
    }

    /// Returns the error code value .
    pub fn family(&self) -> AddressFamily {
        self.family
    }

    /// Returns the error code value .
    pub fn error_code(&self) -> &ErrorCode {
        &self.error_code
    }
}

// Format of Address-Error-Code Attribute:
//  0                   1                   2                   3
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |  Family       |    Reserved             |Class|     Number    |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |      Reason Phrase (variable)                                ..
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

impl DecodeAttributeValue for AddressErrorCode {
    fn decode(ctx: AttributeDecoderContext) -> Result<(Self, usize), StunError> {
        let raw_value = ctx.raw_value();
        let (family, _) = AddressFamily::decode(raw_value)?;
        let (error_code, size) = ErrorCode::decode(raw_value)?;
        Ok((AddressErrorCode::new(family, error_code), size))
    }
}

impl EncodeAttributeValue for AddressErrorCode {
    fn encode(&self, mut ctx: AttributeEncoderContext) -> Result<usize, StunError> {
        // let's first encode ErrorCode  that will set the first byte (family)
        // to zero and then encode family
        let raw_value = ctx.raw_value_mut();
        let size = self.error_code().encode(raw_value)?;
        self.family.encode(raw_value)?;
        Ok(size)
    }
}

impl crate::attributes::AsVerifiable for AddressErrorCode {}

stunt_attribute!(AddressErrorCode, ADDRESS_ERROR_CODE);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::attributes::{DecodeAttributeValue, EncodeAttributeValue};
    use crate::error::StunErrorType;
    use crate::StunAttribute;

    #[test]
    fn decode_address_error_code() {
        let dummy_msg: [u8; 0] = [0x0; 0];
        let buffer = [
            0x01, 0x00, 0x04, 0x28, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) = AddressErrorCode::decode(ctx).expect("Can not decode AddressErrorCode");
        assert_eq!(size, 32);
        assert_eq!(attr.family(), AddressFamily::IPv4);
        let error = attr.error_code();
        assert_eq!(error.error_code(), 440);
        assert_eq!(error.class(), 4);
        assert_eq!(error.number(), 40);
        assert_eq!(error.reason(), "Address Family not Supported");

        let buffer = [
            0x02, 0x00, 0x04, 0x28, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) = AddressErrorCode::decode(ctx).expect("Can not decode AddressErrorCode");
        assert_eq!(size, 32);
        assert_eq!(attr.family(), AddressFamily::IPv6);
        let error = attr.error_code();
        assert_eq!(error.error_code(), 440);
        assert_eq!(error.class(), 4);
        assert_eq!(error.number(), 40);
        assert_eq!(error.reason(), "Address Family not Supported");
        // short buffer
        let buffer = [0x01, 0x00, 0x03];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let result = AddressErrorCode::decode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        // Invalid Ip address family
        let buffer = [
            0x03, 0x00, 0x04, 0x28, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let result = AddressErrorCode::decode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::InvalidParam
        );

        // Wrong class: 2
        let buffer = [
            0x02, 0x00, 0x02, 0x28, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let result = AddressErrorCode::decode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::InvalidParam
        );

        // Wrong number: 112
        let buffer = [
            0x02, 0x00, 0x04, 0x70, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let result = AddressErrorCode::decode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::InvalidParam
        );
    }

    #[test]
    fn encode_address_error_code() {
        let dummy_msg: [u8; 0] = [0x0; 0];
        let error_code =
            ErrorCode::new(440, "Address Family not Supported").expect("Can not create ErrorCode");
        let attr = AddressErrorCode::new(AddressFamily::IPv6, error_code);

        let mut buffer: [u8; 31] = [0x0; 31];
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        let mut buffer: [u8; 32] = [0x0; 32];
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(result, Ok(32));

        let expected = [
            0x02, 0x00, 0x04, 0x28, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x20, 0x46, 0x61,
            0x6D, 0x69, 0x6C, 0x79, 0x20, 0x6E, 0x6F, 0x74, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6F,
            0x72, 0x74, 0x65, 0x64,
        ];

        assert_eq!(&buffer, &expected);
    }

    #[test]
    fn address_error_code_stunt_attribute() {
        let error = ErrorCode::new(533, "test").expect("Can not create error code");
        let attr =
            StunAttribute::AddressErrorCode(AddressErrorCode::new(AddressFamily::IPv4, error));
        assert!(attr.is_address_error_code());
        assert!(attr.as_address_error_code().is_ok());
        assert!(attr.as_error_code().is_err());

        assert!(!attr.attribute_type().is_comprehension_required());
        assert!(attr.attribute_type().is_comprehension_optional());

        let dbg_fmt = format!("{:?}", attr);
        assert_eq!("AddressErrorCode(AddressErrorCode { family: IPv4, error_code: ErrorCode { error_code: 533, reason: \"test\" } })", dbg_fmt);
    }
}