Skip to main content

rtci_stun/
attributes.rs

1//! STUN attribute types.
2//!
3//! Every attribute is a type code, a length and a value ([`RawAttribute`]). This module defines
4//! the code points — those from STUN itself ([RFC 8489]) plus the ones TURN, ICE and the NAT
5//! behaviour discovery extensions add — while the typed accessors live in
6//! [`textattrs`](crate::textattrs), [`xoraddr`](crate::xoraddr),
7//! [`error_code`](crate::error_code) and friends.
8//!
9//! Codes below `0x8000` are *comprehension-required*: a receiver that does not understand one
10//! must reject the message. Codes at or above `0x8000` are comprehension-optional and may be
11//! ignored, which is how `FINGERPRINT` and the ICE attributes can be added without breaking
12//! older peers. [`STUN_ATTRIBUTES`] is the
13//! comprehension-required set of STUN itself; a usage adds its own and hands the list to
14//! [`Validator::known_attributes`](crate::validated::Validator::known_attributes).
15//!
16//! [RFC 8489]: https://datatracker.ietf.org/doc/html/rfc8489
17
18#[cfg(test)]
19mod attributes_test;
20
21use crate::message::*;
22use shared::error::*;
23
24use std::fmt;
25
26/// Attributes is list of message attributes.
27#[derive(Default, PartialEq, Eq, Debug, Clone)]
28pub struct Attributes(pub Vec<RawAttribute>);
29
30impl Attributes {
31    /// get returns first attribute from list by the type.
32    /// If attribute is present the RawAttribute is returned and the
33    /// boolean is true. Otherwise the returned RawAttribute will be
34    /// empty and boolean will be false.
35    pub fn get(&self, t: AttrType) -> (RawAttribute, bool) {
36        for candidate in &self.0 {
37            if candidate.typ == t {
38                return (candidate.clone(), true);
39            }
40        }
41
42        (RawAttribute::default(), false)
43    }
44}
45
46/// AttrType is attribute type.
47#[derive(PartialEq, Debug, Eq, Default, Copy, Clone)]
48pub struct AttrType(pub u16);
49
50impl fmt::Display for AttrType {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let other = format!("0x{:x}", self.0);
53
54        let s = match *self {
55            ATTR_MAPPED_ADDRESS => "MAPPED-ADDRESS",
56            ATTR_USERNAME => "USERNAME",
57            ATTR_ERROR_CODE => "ERROR-CODE",
58            ATTR_MESSAGE_INTEGRITY => "MESSAGE-INTEGRITY",
59            ATTR_UNKNOWN_ATTRIBUTES => "UNKNOWN-ATTRIBUTES",
60            ATTR_REALM => "REALM",
61            ATTR_NONCE => "NONCE",
62            ATTR_XORMAPPED_ADDRESS => "XOR-MAPPED-ADDRESS",
63            ATTR_SOFTWARE => "SOFTWARE",
64            ATTR_ALTERNATE_SERVER => "ALTERNATE-SERVER",
65            ATTR_FINGERPRINT => "FINGERPRINT",
66            ATTR_PRIORITY => "PRIORITY",
67            ATTR_USE_CANDIDATE => "USE-CANDIDATE",
68            ATTR_ICE_CONTROLLED => "ICE-CONTROLLED",
69            ATTR_ICE_CONTROLLING => "ICE-CONTROLLING",
70            ATTR_CHANNEL_NUMBER => "CHANNEL-NUMBER",
71            ATTR_LIFETIME => "LIFETIME",
72            ATTR_XOR_PEER_ADDRESS => "XOR-PEER-ADDRESS",
73            ATTR_DATA => "DATA",
74            ATTR_XOR_RELAYED_ADDRESS => "XOR-RELAYED-ADDRESS",
75            ATTR_EVEN_PORT => "EVEN-PORT",
76            ATTR_REQUESTED_TRANSPORT => "REQUESTED-TRANSPORT",
77            ATTR_DONT_FRAGMENT => "DONT-FRAGMENT",
78            ATTR_RESERVATION_TOKEN => "RESERVATION-TOKEN",
79            ATTR_CONNECTION_ID => "CONNECTION-ID",
80            ATTR_REQUESTED_ADDRESS_FAMILY => "REQUESTED-ADDRESS-FAMILY",
81            ATTR_MESSAGE_INTEGRITY_SHA256 => "MESSAGE-INTEGRITY-SHA256",
82            ATTR_PASSWORD_ALGORITHM => "PASSWORD-ALGORITHM",
83            ATTR_USER_HASH => "USERHASH",
84            ATTR_PASSWORD_ALGORITHMS => "PASSWORD-ALGORITHMS",
85            ATTR_ALTERNATE_DOMAIN => "ALTERNATE-DOMAIN",
86            _ => other.as_str(),
87        };
88
89        write!(f, "{s}")
90    }
91}
92
93impl AttrType {
94    /// required returns true if type is from comprehension-required range (0x0000-0x7FFF).
95    pub fn required(&self) -> bool {
96        self.0 <= 0x7FFF
97    }
98
99    /// optional returns true if type is from comprehension-optional range (0x8000-0xFFFF).
100    pub fn optional(&self) -> bool {
101        self.0 >= 0x8000
102    }
103
104    /// value returns uint16 representation of attribute type.
105    pub fn value(&self) -> u16 {
106        self.0
107    }
108}
109
110/// Attributes from comprehension-required range (0x0000-0x7FFF).
111/// MAPPED-ADDRESS.
112pub const ATTR_MAPPED_ADDRESS: AttrType = AttrType(0x0001);
113/// USERNAME.
114pub const ATTR_USERNAME: AttrType = AttrType(0x0006);
115/// MESSAGE-INTEGRITY.
116pub const ATTR_MESSAGE_INTEGRITY: AttrType = AttrType(0x0008);
117/// ERROR-CODE.
118pub const ATTR_ERROR_CODE: AttrType = AttrType(0x0009);
119/// UNKNOWN-ATTRIBUTES.
120pub const ATTR_UNKNOWN_ATTRIBUTES: AttrType = AttrType(0x000A);
121/// REALM.
122pub const ATTR_REALM: AttrType = AttrType(0x0014);
123/// NONCE.
124pub const ATTR_NONCE: AttrType = AttrType(0x0015);
125/// XOR-MAPPED-ADDRESS.
126pub const ATTR_XORMAPPED_ADDRESS: AttrType = AttrType(0x0020);
127
128/// Attributes from comprehension-optional range (0x8000-0xFFFF).
129/// SOFTWARE.
130pub const ATTR_SOFTWARE: AttrType = AttrType(0x8022);
131/// ALTERNATE-SERVER.
132pub const ATTR_ALTERNATE_SERVER: AttrType = AttrType(0x8023);
133/// FINGERPRINT.
134pub const ATTR_FINGERPRINT: AttrType = AttrType(0x8028);
135
136/// Attributes from RFC 5245 ICE.
137/// PRIORITY.
138pub const ATTR_PRIORITY: AttrType = AttrType(0x0024);
139/// USE-CANDIDATE.
140pub const ATTR_USE_CANDIDATE: AttrType = AttrType(0x0025);
141/// ICE-CONTROLLED.
142pub const ATTR_ICE_CONTROLLED: AttrType = AttrType(0x8029);
143/// ICE-CONTROLLING.
144pub const ATTR_ICE_CONTROLLING: AttrType = AttrType(0x802A);
145/// NETWORK-COST.
146pub const ATTR_NETWORK_COST: AttrType = AttrType(0xC057);
147
148/// Attributes from RFC 5766 TURN.
149/// CHANNEL-NUMBER.
150pub const ATTR_CHANNEL_NUMBER: AttrType = AttrType(0x000C);
151/// LIFETIME.
152pub const ATTR_LIFETIME: AttrType = AttrType(0x000D);
153/// XOR-PEER-ADDRESS.
154pub const ATTR_XOR_PEER_ADDRESS: AttrType = AttrType(0x0012);
155/// DATA.
156pub const ATTR_DATA: AttrType = AttrType(0x0013);
157/// XOR-RELAYED-ADDRESS.
158pub const ATTR_XOR_RELAYED_ADDRESS: AttrType = AttrType(0x0016);
159/// EVEN-PORT.
160pub const ATTR_EVEN_PORT: AttrType = AttrType(0x0018);
161/// REQUESTED-TRANSPORT.
162pub const ATTR_REQUESTED_TRANSPORT: AttrType = AttrType(0x0019);
163/// DONT-FRAGMENT.
164pub const ATTR_DONT_FRAGMENT: AttrType = AttrType(0x001A);
165/// RESERVATION-TOKEN.
166pub const ATTR_RESERVATION_TOKEN: AttrType = AttrType(0x0022);
167
168/// Attributes from RFC 5780 NAT Behavior Discovery
169/// CHANGE-REQUEST.
170pub const ATTR_CHANGE_REQUEST: AttrType = AttrType(0x0003);
171/// PADDING.
172pub const ATTR_PADDING: AttrType = AttrType(0x0026);
173/// RESPONSE-PORT.
174pub const ATTR_RESPONSE_PORT: AttrType = AttrType(0x0027);
175/// CACHE-TIMEOUT.
176pub const ATTR_CACHE_TIMEOUT: AttrType = AttrType(0x8027);
177/// RESPONSE-ORIGIN.
178pub const ATTR_RESPONSE_ORIGIN: AttrType = AttrType(0x802b);
179/// OTHER-ADDRESS.
180pub const ATTR_OTHER_ADDRESS: AttrType = AttrType(0x802C);
181
182/// Attributes from RFC 3489, removed by RFC 5389,
183///  but still used by RFC5389-implementing software like Vovida.org, reTURNServer, etc.
184/// SOURCE-ADDRESS.
185pub const ATTR_SOURCE_ADDRESS: AttrType = AttrType(0x0004);
186/// CHANGED-ADDRESS.
187pub const ATTR_CHANGED_ADDRESS: AttrType = AttrType(0x0005);
188
189/// Attributes from RFC 6062 TURN Extensions for TCP Allocations.
190/// CONNECTION-ID.
191pub const ATTR_CONNECTION_ID: AttrType = AttrType(0x002a);
192
193/// Attributes from RFC 6156 TURN IPv6.
194/// REQUESTED-ADDRESS-FAMILY.
195pub const ATTR_REQUESTED_ADDRESS_FAMILY: AttrType = AttrType(0x0017);
196
197/// Attributes from An Origin Attribute for the STUN Protocol.
198pub const ATTR_ORIGIN: AttrType = AttrType(0x802F);
199
200/// Attributes from RFC 8489 STUN.
201/// MESSAGE-INTEGRITY-SHA256.
202pub const ATTR_MESSAGE_INTEGRITY_SHA256: AttrType = AttrType(0x001C);
203/// PASSWORD-ALGORITHM.
204pub const ATTR_PASSWORD_ALGORITHM: AttrType = AttrType(0x001D);
205/// USER-HASH.
206pub const ATTR_USER_HASH: AttrType = AttrType(0x001E);
207/// PASSWORD-ALGORITHMS.
208pub const ATTR_PASSWORD_ALGORITHMS: AttrType = AttrType(0x8002);
209/// ALTERNATE-DOMAIN.
210pub const ATTR_ALTERNATE_DOMAIN: AttrType = AttrType(0x8003);
211
212/// The comprehension-required attributes RFC 8489 itself defines (section 18.3), which every
213/// STUN agent understands.
214///
215/// A usage's list of known attributes is this plus the comprehension-required attributes the
216/// usage defines (ICE: PRIORITY and USE-CANDIDATE; TURN: CHANNEL-NUMBER, LIFETIME and so on).
217/// See [`Message::unknown_required_attributes`] and
218/// [`Validator::known_attributes`](crate::validated::Validator::known_attributes).
219pub const STUN_ATTRIBUTES: [AttrType; 11] = [
220    ATTR_MAPPED_ADDRESS,
221    ATTR_USERNAME,
222    ATTR_MESSAGE_INTEGRITY,
223    ATTR_ERROR_CODE,
224    ATTR_UNKNOWN_ATTRIBUTES,
225    ATTR_REALM,
226    ATTR_NONCE,
227    ATTR_MESSAGE_INTEGRITY_SHA256,
228    ATTR_PASSWORD_ALGORITHM,
229    ATTR_USER_HASH,
230    ATTR_XORMAPPED_ADDRESS,
231];
232
233/// RawAttribute is a Type-Length-Value (TLV) object that
234/// can be added to a STUN message. Attributes are divided into two
235/// types: comprehension-required and comprehension-optional.  STUN
236/// agents can safely ignore comprehension-optional attributes they
237/// don't understand, but cannot successfully process a message if it
238/// contains comprehension-required attributes that are not
239/// understood.
240#[derive(Default, Debug, Clone, PartialEq, Eq)]
241pub struct RawAttribute {
242    /// Which attribute this is.
243    pub typ: AttrType,
244    /// The value length in bytes; recomputed when encoding, so it is ignored there.
245    pub length: u16, // ignored while encoding
246    /// The attribute's raw value.
247    pub value: Vec<u8>,
248}
249
250impl fmt::Display for RawAttribute {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        write!(f, "{}: {:?}", self.typ, self.value)
253    }
254}
255
256impl Setter for RawAttribute {
257    /// add_to implements Setter, adding attribute as a.Type with a.Value and ignoring
258    /// the Length field.
259    fn add_to(&self, m: &mut Message) -> Result<()> {
260        m.add(self.typ, &self.value);
261        Ok(())
262    }
263}
264
265pub(crate) const PADDING: usize = 4;
266
267/// STUN aligns attributes on 32-bit boundaries, attributes whose content
268/// is not a multiple of 4 bytes are padded with 1, 2, or 3 bytes of
269/// padding so that its value contains a multiple of 4 bytes.  The
270/// padding bits are ignored, and may be any value.
271///
272/// RFC 8489 section 14.
273pub(crate) fn nearest_padded_value_length(l: usize) -> usize {
274    let mut n = PADDING * (l / PADDING);
275    if n < l {
276        n += PADDING
277    }
278    n
279}
280
281/// This method converts uint16 vlue to AttrType. If it finds an old attribute
282/// type value, it also translates it to the new value to enable backward
283/// compatibility.
284pub(crate) fn compat_attr_type(val: u16) -> AttrType {
285    if val == 0x8020 {
286        // draft-ietf-behave-rfc3489bis-02, MS-TURN
287        ATTR_XORMAPPED_ADDRESS // new: 0x0020 (from draft-ietf-behave-rfc3489bis-03 on)
288    } else {
289        AttrType(val)
290    }
291}