Skip to main content

o_sfu_rfc/
stun.rs

1//! STUN message framing from [RFC 8489 section 5](https://www.rfc-editor.org/rfc/rfc8489.html#section-5).
2
3/// Fixed STUN header length, including the 96-bit transaction ID.
4const HEADER_BYTES: usize = 20;
5/// Message length follows the two-byte message type.
6const LENGTH_OFFSET: usize = 2;
7/// Magic cookie follows the two-byte type and two-byte length.
8const COOKIE_OFFSET: usize = 4;
9/// Attributes are padded to 32-bit boundaries, so message length is a multiple of four.
10const ATTRIBUTE_ALIGNMENT_BYTES: u16 = 4;
11/// Network-order STUN magic cookie identifying the updated message format.
12const MAGIC_COOKIE: [u8; 4] = [0x21, 0x12, 0xa4, 0x42];
13
14/// Checks framing after the WebRTC multiplexer has selected STUN.
15/// Attributes, method validity, integrity and fingerprints remain unchecked.
16pub(crate) fn has_datagram_shape(packet: &[u8]) -> bool {
17    let Some(header) = packet.first_chunk::<HEADER_BYTES>() else {
18        return false;
19    };
20    let length = u16::from_be_bytes([header[LENGTH_OFFSET], header[LENGTH_OFFSET + 1]]);
21    header.get(COOKIE_OFFSET..COOKIE_OFFSET + MAGIC_COOKIE.len()) == Some(MAGIC_COOKIE.as_slice())
22        && length.is_multiple_of(ATTRIBUTE_ALIGNMENT_BYTES)
23        && usize::from(length) + HEADER_BYTES == packet.len()
24}