rtci-stun 0.1.0

STUN messages, attributes and a sans-I/O client (RFC 8489), for WebRTC
Documentation
//! The `ERROR-CODE` attribute.
//!
//! An [`ErrorCodeAttribute`](crate::error_code::ErrorCodeAttribute) is a numeric [`ErrorCode`](crate::error_code::ErrorCode) plus a reason phrase. The codes here span
//! three specs — STUN's own (400, 401, 420, 500), ICE's role conflict (487), and TURN's
//! allocation failures (437, 441, 486, 508) — because all three share this attribute.
//!
//! [`ERROR_REASONS`](crate::error_code::ERROR_REASONS) maps each known code to the phrase it is normally sent with, so a responder
//! does not have to invent one.
#[cfg(test)]
mod error_code_test;

use crate::attributes::*;
use crate::checks::*;
use crate::message::*;
use shared::error::*;

use std::collections::HashMap;
use std::fmt;

// ErrorCodeAttribute represents ERROR-CODE attribute.
//
// RFC 8489 Section 14.8
#[derive(Default, Debug, Clone, PartialEq, Eq)]
/// The `ERROR-CODE` attribute: a numeric code and a human-readable reason.
pub struct ErrorCodeAttribute {
    /// The numeric error code.
    pub code: ErrorCode,
    /// The reason phrase, as UTF-8 bytes.
    pub reason: Vec<u8>,
}

impl fmt::Display for ErrorCodeAttribute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {}",
            self.code.0,
            String::from_utf8_lossy(&self.reason)
        )
    }
}

// constants for ERROR-CODE encoding.
const ERROR_CODE_CLASS_BYTE: usize = 2;
const ERROR_CODE_NUMBER_BYTE: usize = 3;
const ERROR_CODE_REASON_START: usize = 4;
/// The longest reason phrase that is sent, in bytes (RFC 8489 section 14.8).
const ERROR_CODE_REASON_MAX_B: usize = 509;
/// A reason phrase is fewer than this many characters (RFC 8489 section 14.8).
const ERROR_CODE_REASON_MAX_CHARS: usize = 128;
const ERROR_CODE_MODULO: u16 = 100;
/// The class is the low 3 bits of its byte; the 21 bits ahead of it are reserved.
const ERROR_CODE_CLASS_MASK: u8 = 0x07;

impl Setter for ErrorCodeAttribute {
    /// Adds ERROR-CODE to `m`.
    ///
    /// # Errors
    ///
    /// RFC 8489 section 14.8: the code is 300 to 699 (class 3 to 6, number 0 to 99) and the
    /// reason phrase is UTF-8 of fewer than 128 characters and at most 509 bytes; anything
    /// else is refused.
    fn add_to(&self, m: &mut Message) -> Result<()> {
        if !(300..=699).contains(&self.code.0) {
            return Err(Error::Other(format!(
                "error code {} is outside 300 to 699",
                self.code.0
            )));
        }
        check_overflow(
            ATTR_ERROR_CODE,
            self.reason.len() + ERROR_CODE_REASON_START,
            ERROR_CODE_REASON_MAX_B + ERROR_CODE_REASON_START,
        )?;
        let reason = std::str::from_utf8(&self.reason)
            .map_err(|_| Error::Other("the reason phrase is not UTF-8".to_owned()))?;
        if reason.chars().count() >= ERROR_CODE_REASON_MAX_CHARS {
            return Err(Error::ErrAttributeSizeOverflow);
        }

        let mut value: Vec<u8> = Vec::with_capacity(ERROR_CODE_REASON_MAX_B);

        let number = (self.code.0 % ERROR_CODE_MODULO) as u8; // error code modulo 100
        let class = (self.code.0 / ERROR_CODE_MODULO) as u8; // hundred digit
        value.extend_from_slice(&[0, 0]);
        value.push(class); // [ERROR_CODE_CLASS_BYTE]
        value.push(number); //[ERROR_CODE_NUMBER_BYTE] =
        value.extend_from_slice(&self.reason); //[ERROR_CODE_REASON_START:]

        m.add(ATTR_ERROR_CODE, &value);

        Ok(())
    }
}

impl Getter for ErrorCodeAttribute {
    /// Decodes ERROR-CODE from `m`.
    ///
    /// The reserved bits are ignored (RFC 8489 section 14.8). The reason phrase is taken as
    /// sent, whatever its length: it is diagnostic text.
    ///
    /// # Errors
    ///
    /// Fails when the attribute is absent or shorter than 4 bytes, or when the class is not 3
    /// to 6 or the number not 0 to 99, which no error code has.
    fn get_from(&mut self, m: &Message) -> Result<()> {
        let v = m.get(ATTR_ERROR_CODE)?;

        if v.len() < ERROR_CODE_REASON_START {
            return Err(Error::ErrUnexpectedEof);
        }

        let class = (v[ERROR_CODE_CLASS_BYTE] & ERROR_CODE_CLASS_MASK) as u16;
        let number = v[ERROR_CODE_NUMBER_BYTE] as u16;
        if !(3..=6).contains(&class) || number >= ERROR_CODE_MODULO {
            return Err(Error::Other(format!(
                "error class {class} and number {number} are not an error code"
            )));
        }
        let code = class * ERROR_CODE_MODULO + number;
        self.code = ErrorCode(code);
        self.reason = v[ERROR_CODE_REASON_START..].to_vec();

        Ok(())
    }
}

// ErrorCode is code for ERROR-CODE attribute.
#[derive(PartialEq, Eq, Hash, Copy, Clone, Default, Debug)]
/// A STUN error code, as carried in `ERROR-CODE`.
pub struct ErrorCode(pub u16);

impl Setter for ErrorCode {
    // add_to adds ERROR-CODE with default reason to m. If there
    // is no default reason, returns ErrNoDefaultReason.
    fn add_to(&self, m: &mut Message) -> Result<()> {
        if let Some(reason) = ERROR_REASONS.get(self) {
            let a = ErrorCodeAttribute {
                code: *self,
                reason: reason.clone(),
            };
            a.add_to(m)
        } else {
            Err(Error::ErrNoDefaultReason)
        }
    }
}

/// Possible error codes.
pub const CODE_TRY_ALTERNATE: ErrorCode = ErrorCode(300);
/// 400 Bad Request: the request was malformed.
pub const CODE_BAD_REQUEST: ErrorCode = ErrorCode(400);
/// 401 Unauthenticated (RFC 8489; "Unauthorized" in RFC 5389): authentication is required, or
/// the credentials were wrong.
pub const CODE_UNAUTHORIZED: ErrorCode = ErrorCode(401);
/// 420 Unknown Attribute: the request carried a comprehension-required attribute the server
/// does not understand.
pub const CODE_UNKNOWN_ATTRIBUTE: ErrorCode = ErrorCode(420);
/// 438 Stale Nonce: the nonce expired; retry with the one in this response.
pub const CODE_STALE_NONCE: ErrorCode = ErrorCode(438);
/// 487 Role Conflict: both ICE agents claimed the same role.
pub const CODE_ROLE_CONFLICT: ErrorCode = ErrorCode(487);
/// 500 Server Error: a temporary failure on the server.
pub const CODE_SERVER_ERROR: ErrorCode = ErrorCode(500);

/// 401 Unauthenticated, under the name RFC 8489 gives it.
pub const CODE_UNAUTHENTICATED: ErrorCode = CODE_UNAUTHORIZED;

/// DEPRECATED constants.
/// DEPRECATED, use CODE_UNAUTHORIZED.
pub const CODE_UNAUTHORISED: ErrorCode = CODE_UNAUTHORIZED;

/// Error codes from RFC 5766.
///
/// RFC 5766 Section 15.
/// Forbidden.
pub const CODE_FORBIDDEN: ErrorCode = ErrorCode(403);
/// Allocation Mismatch.
pub const CODE_ALLOC_MISMATCH: ErrorCode = ErrorCode(437);
/// Wrong Credentials.
pub const CODE_WRONG_CREDENTIALS: ErrorCode = ErrorCode(441);
/// Unsupported Transport Protocol.
pub const CODE_UNSUPPORTED_TRANS_PROTO: ErrorCode = ErrorCode(442);
/// Allocation Quota Reached.
pub const CODE_ALLOC_QUOTA_REACHED: ErrorCode = ErrorCode(486);
/// Insufficient Capacity.
pub const CODE_INSUFFICIENT_CAPACITY: ErrorCode = ErrorCode(508);

/// Error codes from RFC 6062.
///
/// RFC 6062 Section 6.3.
pub const CODE_CONN_ALREADY_EXISTS: ErrorCode = ErrorCode(446);
/// 447 Connection Timeout or Failure: the TURN TCP connection to the peer failed.
pub const CODE_CONN_TIMEOUT_OR_FAILURE: ErrorCode = ErrorCode(447);

/// Error codes from RFC 6156.
///
/// RFC 6156 Section 10.2.
/// Address Family not Supported.
pub const CODE_ADDR_FAMILY_NOT_SUPPORTED: ErrorCode = ErrorCode(440);
/// Peer Address Family Mismatch.
pub const CODE_PEER_ADDR_FAMILY_MISMATCH: ErrorCode = ErrorCode(443);

lazy_static! {
    /// The reason phrase each known [`ErrorCode`] is sent with.
    pub static ref ERROR_REASONS:HashMap<ErrorCode, Vec<u8>> =
        [
            (CODE_TRY_ALTERNATE,     b"Try Alternate".to_vec()),
            (CODE_BAD_REQUEST,       b"Bad Request".to_vec()),
            (CODE_UNAUTHORIZED,     b"Unauthenticated".to_vec()),
            (CODE_UNKNOWN_ATTRIBUTE, b"Unknown Attribute".to_vec()),
            (CODE_STALE_NONCE,       b"Stale Nonce".to_vec()),
            (CODE_SERVER_ERROR,      b"Server Error".to_vec()),
            (CODE_ROLE_CONFLICT,     b"Role Conflict".to_vec()),

            // RFC 5766.
            (CODE_FORBIDDEN,             b"Forbidden".to_vec()),
            (CODE_ALLOC_MISMATCH,         b"Allocation Mismatch".to_vec()),
            (CODE_WRONG_CREDENTIALS,      b"Wrong Credentials".to_vec()),
            (CODE_UNSUPPORTED_TRANS_PROTO, b"Unsupported Transport Protocol".to_vec()),
            (CODE_ALLOC_QUOTA_REACHED,     b"Allocation Quota Reached".to_vec()),
            (CODE_INSUFFICIENT_CAPACITY,  b"Insufficient Capacity".to_vec()),

            // RFC 6062.
            (CODE_CONN_ALREADY_EXISTS,    b"Connection Already Exists".to_vec()),
            (CODE_CONN_TIMEOUT_OR_FAILURE, b"Connection Timeout or Failure".to_vec()),

            // RFC 6156.
            (CODE_ADDR_FAMILY_NOT_SUPPORTED, b"Address Family not Supported".to_vec()),
            (CODE_PEER_ADDR_FAMILY_MISMATCH, b"Peer Address Family Mismatch".to_vec()),
        ].iter().cloned().collect();

}