Skip to main content

rtci_stun/
error_code.rs

1//! The `ERROR-CODE` attribute.
2//!
3//! An [`ErrorCodeAttribute`](crate::error_code::ErrorCodeAttribute) is a numeric [`ErrorCode`](crate::error_code::ErrorCode) plus a reason phrase. The codes here span
4//! three specs — STUN's own (400, 401, 420, 500), ICE's role conflict (487), and TURN's
5//! allocation failures (437, 441, 486, 508) — because all three share this attribute.
6//!
7//! [`ERROR_REASONS`](crate::error_code::ERROR_REASONS) maps each known code to the phrase it is normally sent with, so a responder
8//! does not have to invent one.
9#[cfg(test)]
10mod error_code_test;
11
12use crate::attributes::*;
13use crate::checks::*;
14use crate::message::*;
15use shared::error::*;
16
17use std::collections::HashMap;
18use std::fmt;
19
20// ErrorCodeAttribute represents ERROR-CODE attribute.
21//
22// RFC 8489 Section 14.8
23#[derive(Default, Debug, Clone, PartialEq, Eq)]
24/// The `ERROR-CODE` attribute: a numeric code and a human-readable reason.
25pub struct ErrorCodeAttribute {
26    /// The numeric error code.
27    pub code: ErrorCode,
28    /// The reason phrase, as UTF-8 bytes.
29    pub reason: Vec<u8>,
30}
31
32impl fmt::Display for ErrorCodeAttribute {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        write!(
35            f,
36            "{}: {}",
37            self.code.0,
38            String::from_utf8_lossy(&self.reason)
39        )
40    }
41}
42
43// constants for ERROR-CODE encoding.
44const ERROR_CODE_CLASS_BYTE: usize = 2;
45const ERROR_CODE_NUMBER_BYTE: usize = 3;
46const ERROR_CODE_REASON_START: usize = 4;
47/// The longest reason phrase that is sent, in bytes (RFC 8489 section 14.8).
48const ERROR_CODE_REASON_MAX_B: usize = 509;
49/// A reason phrase is fewer than this many characters (RFC 8489 section 14.8).
50const ERROR_CODE_REASON_MAX_CHARS: usize = 128;
51const ERROR_CODE_MODULO: u16 = 100;
52/// The class is the low 3 bits of its byte; the 21 bits ahead of it are reserved.
53const ERROR_CODE_CLASS_MASK: u8 = 0x07;
54
55impl Setter for ErrorCodeAttribute {
56    /// Adds ERROR-CODE to `m`.
57    ///
58    /// # Errors
59    ///
60    /// RFC 8489 section 14.8: the code is 300 to 699 (class 3 to 6, number 0 to 99) and the
61    /// reason phrase is UTF-8 of fewer than 128 characters and at most 509 bytes; anything
62    /// else is refused.
63    fn add_to(&self, m: &mut Message) -> Result<()> {
64        if !(300..=699).contains(&self.code.0) {
65            return Err(Error::Other(format!(
66                "error code {} is outside 300 to 699",
67                self.code.0
68            )));
69        }
70        check_overflow(
71            ATTR_ERROR_CODE,
72            self.reason.len() + ERROR_CODE_REASON_START,
73            ERROR_CODE_REASON_MAX_B + ERROR_CODE_REASON_START,
74        )?;
75        let reason = std::str::from_utf8(&self.reason)
76            .map_err(|_| Error::Other("the reason phrase is not UTF-8".to_owned()))?;
77        if reason.chars().count() >= ERROR_CODE_REASON_MAX_CHARS {
78            return Err(Error::ErrAttributeSizeOverflow);
79        }
80
81        let mut value: Vec<u8> = Vec::with_capacity(ERROR_CODE_REASON_MAX_B);
82
83        let number = (self.code.0 % ERROR_CODE_MODULO) as u8; // error code modulo 100
84        let class = (self.code.0 / ERROR_CODE_MODULO) as u8; // hundred digit
85        value.extend_from_slice(&[0, 0]);
86        value.push(class); // [ERROR_CODE_CLASS_BYTE]
87        value.push(number); //[ERROR_CODE_NUMBER_BYTE] =
88        value.extend_from_slice(&self.reason); //[ERROR_CODE_REASON_START:]
89
90        m.add(ATTR_ERROR_CODE, &value);
91
92        Ok(())
93    }
94}
95
96impl Getter for ErrorCodeAttribute {
97    /// Decodes ERROR-CODE from `m`.
98    ///
99    /// The reserved bits are ignored (RFC 8489 section 14.8). The reason phrase is taken as
100    /// sent, whatever its length: it is diagnostic text.
101    ///
102    /// # Errors
103    ///
104    /// Fails when the attribute is absent or shorter than 4 bytes, or when the class is not 3
105    /// to 6 or the number not 0 to 99, which no error code has.
106    fn get_from(&mut self, m: &Message) -> Result<()> {
107        let v = m.get(ATTR_ERROR_CODE)?;
108
109        if v.len() < ERROR_CODE_REASON_START {
110            return Err(Error::ErrUnexpectedEof);
111        }
112
113        let class = (v[ERROR_CODE_CLASS_BYTE] & ERROR_CODE_CLASS_MASK) as u16;
114        let number = v[ERROR_CODE_NUMBER_BYTE] as u16;
115        if !(3..=6).contains(&class) || number >= ERROR_CODE_MODULO {
116            return Err(Error::Other(format!(
117                "error class {class} and number {number} are not an error code"
118            )));
119        }
120        let code = class * ERROR_CODE_MODULO + number;
121        self.code = ErrorCode(code);
122        self.reason = v[ERROR_CODE_REASON_START..].to_vec();
123
124        Ok(())
125    }
126}
127
128// ErrorCode is code for ERROR-CODE attribute.
129#[derive(PartialEq, Eq, Hash, Copy, Clone, Default, Debug)]
130/// A STUN error code, as carried in `ERROR-CODE`.
131pub struct ErrorCode(pub u16);
132
133impl Setter for ErrorCode {
134    // add_to adds ERROR-CODE with default reason to m. If there
135    // is no default reason, returns ErrNoDefaultReason.
136    fn add_to(&self, m: &mut Message) -> Result<()> {
137        if let Some(reason) = ERROR_REASONS.get(self) {
138            let a = ErrorCodeAttribute {
139                code: *self,
140                reason: reason.clone(),
141            };
142            a.add_to(m)
143        } else {
144            Err(Error::ErrNoDefaultReason)
145        }
146    }
147}
148
149/// Possible error codes.
150pub const CODE_TRY_ALTERNATE: ErrorCode = ErrorCode(300);
151/// 400 Bad Request: the request was malformed.
152pub const CODE_BAD_REQUEST: ErrorCode = ErrorCode(400);
153/// 401 Unauthenticated (RFC 8489; "Unauthorized" in RFC 5389): authentication is required, or
154/// the credentials were wrong.
155pub const CODE_UNAUTHORIZED: ErrorCode = ErrorCode(401);
156/// 420 Unknown Attribute: the request carried a comprehension-required attribute the server
157/// does not understand.
158pub const CODE_UNKNOWN_ATTRIBUTE: ErrorCode = ErrorCode(420);
159/// 438 Stale Nonce: the nonce expired; retry with the one in this response.
160pub const CODE_STALE_NONCE: ErrorCode = ErrorCode(438);
161/// 487 Role Conflict: both ICE agents claimed the same role.
162pub const CODE_ROLE_CONFLICT: ErrorCode = ErrorCode(487);
163/// 500 Server Error: a temporary failure on the server.
164pub const CODE_SERVER_ERROR: ErrorCode = ErrorCode(500);
165
166/// 401 Unauthenticated, under the name RFC 8489 gives it.
167pub const CODE_UNAUTHENTICATED: ErrorCode = CODE_UNAUTHORIZED;
168
169/// DEPRECATED constants.
170/// DEPRECATED, use CODE_UNAUTHORIZED.
171pub const CODE_UNAUTHORISED: ErrorCode = CODE_UNAUTHORIZED;
172
173/// Error codes from RFC 5766.
174///
175/// RFC 5766 Section 15.
176/// Forbidden.
177pub const CODE_FORBIDDEN: ErrorCode = ErrorCode(403);
178/// Allocation Mismatch.
179pub const CODE_ALLOC_MISMATCH: ErrorCode = ErrorCode(437);
180/// Wrong Credentials.
181pub const CODE_WRONG_CREDENTIALS: ErrorCode = ErrorCode(441);
182/// Unsupported Transport Protocol.
183pub const CODE_UNSUPPORTED_TRANS_PROTO: ErrorCode = ErrorCode(442);
184/// Allocation Quota Reached.
185pub const CODE_ALLOC_QUOTA_REACHED: ErrorCode = ErrorCode(486);
186/// Insufficient Capacity.
187pub const CODE_INSUFFICIENT_CAPACITY: ErrorCode = ErrorCode(508);
188
189/// Error codes from RFC 6062.
190///
191/// RFC 6062 Section 6.3.
192pub const CODE_CONN_ALREADY_EXISTS: ErrorCode = ErrorCode(446);
193/// 447 Connection Timeout or Failure: the TURN TCP connection to the peer failed.
194pub const CODE_CONN_TIMEOUT_OR_FAILURE: ErrorCode = ErrorCode(447);
195
196/// Error codes from RFC 6156.
197///
198/// RFC 6156 Section 10.2.
199/// Address Family not Supported.
200pub const CODE_ADDR_FAMILY_NOT_SUPPORTED: ErrorCode = ErrorCode(440);
201/// Peer Address Family Mismatch.
202pub const CODE_PEER_ADDR_FAMILY_MISMATCH: ErrorCode = ErrorCode(443);
203
204lazy_static! {
205    /// The reason phrase each known [`ErrorCode`] is sent with.
206    pub static ref ERROR_REASONS:HashMap<ErrorCode, Vec<u8>> =
207        [
208            (CODE_TRY_ALTERNATE,     b"Try Alternate".to_vec()),
209            (CODE_BAD_REQUEST,       b"Bad Request".to_vec()),
210            (CODE_UNAUTHORIZED,     b"Unauthenticated".to_vec()),
211            (CODE_UNKNOWN_ATTRIBUTE, b"Unknown Attribute".to_vec()),
212            (CODE_STALE_NONCE,       b"Stale Nonce".to_vec()),
213            (CODE_SERVER_ERROR,      b"Server Error".to_vec()),
214            (CODE_ROLE_CONFLICT,     b"Role Conflict".to_vec()),
215
216            // RFC 5766.
217            (CODE_FORBIDDEN,             b"Forbidden".to_vec()),
218            (CODE_ALLOC_MISMATCH,         b"Allocation Mismatch".to_vec()),
219            (CODE_WRONG_CREDENTIALS,      b"Wrong Credentials".to_vec()),
220            (CODE_UNSUPPORTED_TRANS_PROTO, b"Unsupported Transport Protocol".to_vec()),
221            (CODE_ALLOC_QUOTA_REACHED,     b"Allocation Quota Reached".to_vec()),
222            (CODE_INSUFFICIENT_CAPACITY,  b"Insufficient Capacity".to_vec()),
223
224            // RFC 6062.
225            (CODE_CONN_ALREADY_EXISTS,    b"Connection Already Exists".to_vec()),
226            (CODE_CONN_TIMEOUT_OR_FAILURE, b"Connection Timeout or Failure".to_vec()),
227
228            // RFC 6156.
229            (CODE_ADDR_FAMILY_NOT_SUPPORTED, b"Address Family not Supported".to_vec()),
230            (CODE_PEER_ADDR_FAMILY_MISMATCH, b"Peer Address Family Mismatch".to_vec()),
231        ].iter().cloned().collect();
232
233}