rtci_stun/message.rs
1//! The STUN message: header, attributes, and encoding.
2//!
3//! A [`Message`](crate::message::Message) is a class and method ([`MessageType`](crate::message::MessageType)), a 96-bit [`TransactionId`](crate::message::TransactionId), and a
4//! list of attributes. Build one by applying [`Setter`](crate::message::Setter)s, read one back with [`Getter`](crate::message::Getter)s, and
5//! move it across the wire with `marshal`/`unmarshal`.
6//!
7//! Two attributes are special, because their value covers the *encoded* message: `FINGERPRINT`
8//! and `MESSAGE-INTEGRITY` must be appended last and are validated through [`Checker`](crate::message::Checker). That is
9//! why [`Message::raw`](crate::message::Message::raw) is kept alongside the parsed attributes โ those checks are computed over
10//! it rather than over a re-encoding.
11
12#[cfg(test)]
13mod message_length_test;
14#[cfg(test)]
15mod message_test;
16
17use crate::attributes::*;
18use shared::error::*;
19
20use base64::prelude::*;
21use rand::RngExt;
22use std::fmt;
23use std::io::{Read, Write};
24
25/// Fixed value that aids in distinguishing STUN packets
26/// from packets of other protocols when STUN is multiplexed with those
27/// other protocols on the same Port.
28///
29/// The magic cookie field MUST contain the fixed value 0x2112A442 in
30/// network byte order.
31///
32/// Defined in "STUN Message Structure", section 6.
33pub const MAGIC_COOKIE: u32 = 0x2112A442;
34/// Bytes of type and length preceding each attribute value.
35pub const ATTRIBUTE_HEADER_SIZE: usize = 4;
36/// Bytes in the STUN message header.
37pub const MESSAGE_HEADER_SIZE: usize = 20;
38
39/// Length of transaction id array (in bytes).
40/// 96 bit.
41pub const TRANSACTION_ID_SIZE: usize = 12;
42
43#[derive(PartialEq, Eq, Hash, Copy, Clone, Default, Debug)]
44/// A 96-bit transaction id, which pairs a response with its request.
45///
46/// A request takes [`TransactionId::new`]: RFC 8489 section 5 has the id "uniformly and
47/// randomly chosen from the interval 0 .. 2**96-1, and MUST be cryptographically random".
48/// [`Default`] is the all-zero id, for decoding into and for tests, never for a request.
49pub struct TransactionId(pub [u8; TRANSACTION_ID_SIZE]);
50
51impl TransactionId {
52 /// Creates a random transaction ID with `rand`'s cryptographically secure thread RNG.
53 ///
54 /// Transaction IDs remain independent of [`crypto::RTCCryptoProvider`] because ordinary STUN
55 /// message construction does not otherwise own a provider.
56 pub fn new() -> Self {
57 let mut b = TransactionId([0u8; TRANSACTION_ID_SIZE]);
58 rand::rng().fill(&mut b.0);
59 b
60 }
61}
62
63impl Setter for TransactionId {
64 fn add_to(&self, m: &mut Message) -> Result<()> {
65 m.transaction_id = *self;
66 m.write_transaction_id();
67 Ok(())
68 }
69}
70
71/// Interfaces that are implemented by message attributes, shorthands for them,
72/// or helpers for message fields as type or transaction id.
73pub trait Setter {
74 // Setter sets *Message attribute.
75 /// Encodes this value into `m` as an attribute.
76 ///
77 /// # Errors
78 ///
79 /// Fails if the value cannot be encoded, or the message has no room for it.
80 fn add_to(&self, m: &mut Message) -> Result<()>;
81}
82
83/// Getter parses attribute from *Message.
84pub trait Getter {
85 /// Decodes this value from the corresponding attribute of `m`.
86 ///
87 /// # Errors
88 ///
89 /// Fails if the attribute is absent or malformed.
90 fn get_from(&mut self, m: &Message) -> Result<()>;
91}
92
93/// Checker checks *Message attribute.
94pub trait Checker {
95 /// Validates this value against `m`.
96 ///
97 /// Used by attributes whose value depends on the encoded message, such as
98 /// `MESSAGE-INTEGRITY` and `FINGERPRINT`.
99 ///
100 /// # Errors
101 ///
102 /// Fails if the check does not hold.
103 fn check(&self, m: &Message) -> Result<()>;
104}
105
106/// Is_stun_message returns true if b looks like STUN message: at least a header, the first two
107/// bits zero and the magic cookie in place (RFC 8489 section 6.3).
108/// Useful for multiplexing. is_stun_message does not guarantee
109/// that decoding will be successful.
110pub fn is_stun_message(b: &[u8]) -> bool {
111 b.len() >= MESSAGE_HEADER_SIZE
112 && b[0] & 0xc0 == 0
113 && u32::from_be_bytes([b[4], b[5], b[6], b[7]]) == MAGIC_COOKIE
114}
115// Message represents a single STUN packet. It uses aggressive internal
116// buffering to enable zero-allocation encoding and decoding,
117// so there are some usage constraints:
118//
119// Message, its fields, results of m.Get or any attribute a.GetFrom
120// are valid only until Message.Raw is not modified.
121#[derive(Default, Debug, Clone)]
122/// A STUN message: type, transaction id, and attributes, plus the encoded bytes.
123pub struct Message {
124 /// The message class and method โ request, response or indication, and which method.
125 pub typ: MessageType,
126 /// The attribute section's length in bytes, header excluded.
127 pub length: u32, // len(Raw) not including header
128 /// The transaction id, echoed by the responder.
129 pub transaction_id: TransactionId,
130 /// The message's attributes.
131 pub attributes: Attributes,
132 /// The encoded message. Attributes whose value covers the message are computed over this.
133 pub raw: Vec<u8>,
134}
135
136impl fmt::Display for Message {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 let t_id = BASE64_STANDARD.encode(self.transaction_id.0);
139 write!(
140 f,
141 "{} l={} attrs={} id={}",
142 self.typ,
143 self.length,
144 self.attributes.0.len(),
145 t_id
146 )
147 }
148}
149
150// Equal returns true if Message b equals to m.
151// Ignores m.Raw.
152impl PartialEq for Message {
153 fn eq(&self, other: &Self) -> bool {
154 if self.typ != other.typ {
155 return false;
156 }
157 if self.transaction_id != other.transaction_id {
158 return false;
159 }
160 if self.length != other.length {
161 return false;
162 }
163 if self.attributes != other.attributes {
164 return false;
165 }
166 true
167 }
168}
169
170const DEFAULT_RAW_CAPACITY: usize = 120;
171
172impl Setter for Message {
173 // add_to sets b.TransactionID to m.TransactionID.
174 //
175 // Implements Setter to aid in crafting responses.
176 fn add_to(&self, b: &mut Message) -> Result<()> {
177 b.transaction_id = self.transaction_id;
178 b.write_transaction_id();
179 Ok(())
180 }
181}
182
183impl Message {
184 /// New returns *Message with pre-allocated Raw.
185 pub fn new() -> Self {
186 Message {
187 raw: {
188 let mut raw = Vec::with_capacity(DEFAULT_RAW_CAPACITY);
189 raw.extend_from_slice(&[0; MESSAGE_HEADER_SIZE]);
190 raw
191 },
192 ..Default::default()
193 }
194 }
195
196 /// Marshal_binary implements the encoding.BinaryMarshaler interface.
197 pub fn marshal_binary(&self) -> Result<Vec<u8>> {
198 // We can't return m.Raw, allocation is expected by implicit interface
199 // contract induced by other implementations.
200 Ok(self.raw.clone())
201 }
202
203 /// Unmarshal_binary implements the encoding.BinaryUnmarshaler interface.
204 pub fn unmarshal_binary(&mut self, data: &[u8]) -> Result<()> {
205 // We can't retain data, copy is expected by interface contract.
206 self.raw.clear();
207 self.raw.extend_from_slice(data);
208 self.decode()
209 }
210
211 /// Replaces the transaction ID using `rand`'s cryptographically secure thread RNG.
212 ///
213 /// Transaction IDs remain independent of [`crypto::RTCCryptoProvider`] because a general
214 /// [`Message`] does not otherwise own a provider.
215 pub fn new_transaction_id(&mut self) -> Result<()> {
216 rand::rng().fill(&mut self.transaction_id.0);
217 self.write_transaction_id();
218 Ok(())
219 }
220
221 /// Reset resets Message, attributes and underlying buffer length.
222 pub fn reset(&mut self) {
223 self.raw.clear();
224 self.length = 0;
225 self.attributes.0.clear();
226 }
227
228 // grow ensures that internal buffer has n length.
229 fn grow(&mut self, n: usize, resize: bool) {
230 if self.raw.len() >= n {
231 if resize {
232 self.raw.resize(n, 0);
233 }
234 return;
235 }
236 self.raw.extend_from_slice(&vec![0; n - self.raw.len()]);
237 }
238
239 /// Add appends new attribute to message. Not goroutine-safe.
240 ///
241 /// Value of attribute is copied to internal buffer so
242 /// it is safe to reuse v.
243 pub fn add(&mut self, t: AttrType, v: &[u8]) {
244 // Allocating buffer for TLV (type-length-value).
245 // T = t, L = len(v), V = v.
246 // m.Raw will look like:
247 // [0:20] <- message header
248 // [20:20+m.Length] <- existing message attributes
249 // [20+m.Length:20+m.Length+len(v) + 4] <- allocated buffer for new TLV
250 // [first:last] <- same as previous
251 // [0 1|2 3|4 4 + len(v)] <- mapping for allocated buffer
252 // T L V
253 let alloc_size = ATTRIBUTE_HEADER_SIZE + v.len(); // ~ len(TLV) = len(TL) + len(V)
254 let first = MESSAGE_HEADER_SIZE + self.length as usize; // first byte number
255 let mut last = first + alloc_size; // last byte number
256 self.grow(last, true); // growing cap(Raw) to fit TLV
257 self.length += alloc_size as u32; // rendering length change
258
259 // Encoding attribute TLV to allocated buffer.
260 let buf = &mut self.raw[first..last];
261 buf[0..2].copy_from_slice(&t.value().to_be_bytes()); // T
262 // L. A value too long for the field saturates rather than wrapping; the message it
263 // goes into is then too long as well, which `build` refuses.
264 let length = u16::try_from(v.len()).unwrap_or(u16::MAX);
265 buf[2..4].copy_from_slice(&length.to_be_bytes()); // L
266
267 let value = &mut buf[ATTRIBUTE_HEADER_SIZE..];
268 value.copy_from_slice(v); // V
269
270 let attr = RawAttribute {
271 typ: t, // T
272 length, // L
273 value: value.to_vec(), // V
274 };
275
276 // Checking that attribute value needs padding.
277 if !v.len().is_multiple_of(PADDING) {
278 // Performing padding.
279 let bytes_to_add = nearest_padded_value_length(v.len()) - v.len();
280 last += bytes_to_add;
281 self.grow(last, true);
282 // setting all padding bytes to zero
283 // to prevent data leak from previous
284 // data in next bytes_to_add bytes
285 let buf = &mut self.raw[last - bytes_to_add..last];
286 for b in buf {
287 *b = 0;
288 }
289 self.length += bytes_to_add as u32; // rendering length change
290 }
291 self.attributes.0.push(attr);
292 self.write_length();
293 }
294
295 /// WriteLength writes m.Length to m.Raw.
296 ///
297 /// A length past what the 16-bit field holds is written as `u16::MAX` rather than wrapped
298 /// to a small value; [`build`](Self::build) refuses such a message.
299 pub fn write_length(&mut self) {
300 self.grow(4, false);
301 let length = u16::try_from(self.length).unwrap_or(u16::MAX);
302 self.raw[2..4].copy_from_slice(&length.to_be_bytes());
303 }
304
305 /// WriteHeader writes header to underlying buffer. Not goroutine-safe.
306 pub fn write_header(&mut self) {
307 self.grow(MESSAGE_HEADER_SIZE, false);
308
309 self.write_type();
310 self.write_length();
311 self.raw[4..8].copy_from_slice(&MAGIC_COOKIE.to_be_bytes()); // magic cookie
312 self.raw[8..MESSAGE_HEADER_SIZE].copy_from_slice(&self.transaction_id.0);
313 // transaction ID
314 }
315
316 /// WriteTransactionID writes m.TransactionID to m.Raw.
317 pub fn write_transaction_id(&mut self) {
318 self.raw[8..MESSAGE_HEADER_SIZE].copy_from_slice(&self.transaction_id.0);
319 // transaction ID
320 }
321
322 /// WriteAttributes encodes all m.Attributes to m.
323 pub fn write_attributes(&mut self) {
324 let attributes: Vec<RawAttribute> = std::mem::take(&mut self.attributes.0);
325 for a in &attributes {
326 self.add(a.typ, &a.value);
327 }
328 self.attributes = Attributes(attributes);
329 }
330
331 /// WriteType writes m.Type to m.Raw.
332 pub fn write_type(&mut self) {
333 self.grow(2, false);
334 self.raw[..2].copy_from_slice(&self.typ.value().to_be_bytes()); // message type
335 }
336
337 /// SetType sets m.Type and writes it to m.Raw.
338 pub fn set_type(&mut self, t: MessageType) {
339 self.typ = t;
340 self.write_type();
341 }
342
343 /// Encode re-encodes message into m.Raw.
344 pub fn encode(&mut self) {
345 self.raw.clear();
346 self.write_header();
347 self.length = 0;
348 self.write_attributes();
349 }
350
351 /// Decode decodes m.Raw into m.
352 ///
353 /// `raw` is one whole message, as a datagram or a framed stream delivers it. The checks of
354 /// RFC 8489 section 6.3 that need no context are made here: the first two bits are zero,
355 /// the magic cookie is in place, and the length is a multiple of four (section 5) that
356 /// describes all of `raw`, no more and no less.
357 ///
358 /// # Errors
359 ///
360 /// Fails when `raw` is not such a message, or an attribute runs past its end.
361 pub fn decode(&mut self) -> Result<()> {
362 // decoding message header
363 let buf = &self.raw;
364 if buf.len() < MESSAGE_HEADER_SIZE {
365 return Err(Error::ErrUnexpectedHeaderEof);
366 }
367
368 let t = u16::from_be_bytes([buf[0], buf[1]]); // first 2 bytes
369 let size = u16::from_be_bytes([buf[2], buf[3]]) as usize; // second 2 bytes
370 let cookie = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); // last 4 bytes
371 let full_size = MESSAGE_HEADER_SIZE + size; // len(m.Raw)
372
373 if buf[0] & 0xc0 != 0 {
374 return Err(Error::Other(format!(
375 "the first two bits of a STUN message are zero, got first byte {:#04x}",
376 buf[0]
377 )));
378 }
379 if cookie != MAGIC_COOKIE {
380 return Err(Error::Other(format!(
381 "{cookie:x} is invalid magic cookie (should be {MAGIC_COOKIE:x})"
382 )));
383 }
384 if !size.is_multiple_of(PADDING) {
385 return Err(Error::Other(format!(
386 "message length {size} is not a multiple of {PADDING}"
387 )));
388 }
389 if buf.len() < full_size {
390 return Err(Error::Other(format!(
391 "buffer length {} is less than {} (expected message size)",
392 buf.len(),
393 full_size
394 )));
395 }
396 if buf.len() > full_size {
397 return Err(Error::Other(format!(
398 "buffer length {} is more than {} (expected message size)",
399 buf.len(),
400 full_size
401 )));
402 }
403
404 // saving header data
405 self.typ.read_value(t);
406 self.length = size as u32;
407 self.transaction_id
408 .0
409 .copy_from_slice(&buf[8..MESSAGE_HEADER_SIZE]);
410
411 self.attributes.0.clear();
412 let mut offset = 0;
413 let mut b = &buf[MESSAGE_HEADER_SIZE..full_size];
414
415 while offset < size {
416 // checking that we have enough bytes to read header
417 if b.len() < ATTRIBUTE_HEADER_SIZE {
418 return Err(Error::Other(format!(
419 "buffer length {} is less than {} (expected header size)",
420 b.len(),
421 ATTRIBUTE_HEADER_SIZE
422 )));
423 }
424
425 let mut a = RawAttribute {
426 typ: compat_attr_type(u16::from_be_bytes([b[0], b[1]])), // first 2 bytes
427 length: u16::from_be_bytes([b[2], b[3]]), // second 2 bytes
428 ..Default::default()
429 };
430 let a_l = a.length as usize; // attribute length
431 let a_buff_l = nearest_padded_value_length(a_l); // expected buffer length (with padding)
432
433 b = &b[ATTRIBUTE_HEADER_SIZE..]; // slicing again to simplify value read
434 offset += ATTRIBUTE_HEADER_SIZE;
435 if b.len() < a_buff_l {
436 // checking size
437 return Err(Error::Other(format!(
438 "buffer length {} is less than {} (expected value size for {})",
439 b.len(),
440 a_buff_l,
441 a.typ
442 )));
443 }
444 a.value = b[..a_l].to_vec();
445 offset += a_buff_l;
446 b = &b[a_buff_l..];
447
448 self.attributes.0.push(a);
449 }
450
451 Ok(())
452 }
453
454 /// WriteTo implements WriterTo via calling Write(m.Raw) on w and returning
455 /// call result.
456 pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<usize> {
457 let n = writer.write(&self.raw)?;
458 Ok(n)
459 }
460
461 /// ReadFrom implements ReaderFrom. Reads message from r into m.Raw,
462 /// Decodes it and return error if any. If m.Raw is too small, will return
463 /// ErrUnexpectedEOF, ErrUnexpectedHeaderEOF or *DecodeErr.
464 ///
465 /// Can return *DecodeErr while decoding too.
466 ///
467 /// The reader is read to its end: it holds one message, of any length the 16-bit length
468 /// field allows.
469 pub fn read_from<R: Read>(&mut self, reader: &mut R) -> Result<usize> {
470 let mut t_buf = Vec::with_capacity(DEFAULT_RAW_CAPACITY);
471 // One byte past the largest message, so that an oversized input is refused by `decode`
472 // rather than read without bound.
473 let limit = (MESSAGE_HEADER_SIZE + usize::from(u16::MAX) + 1) as u64;
474 let n = reader.take(limit).read_to_end(&mut t_buf)?;
475 self.raw = t_buf;
476 self.decode()?;
477 Ok(n)
478 }
479
480 /// Write decodes message and return error if any.
481 ///
482 /// Any error is unrecoverable, but message could be partially decoded.
483 pub fn write(&mut self, t_buf: &[u8]) -> Result<usize> {
484 self.raw.clear();
485 self.raw.extend_from_slice(t_buf);
486 self.decode()?;
487 Ok(t_buf.len())
488 }
489
490 /// CloneTo clones m to b securing any further m mutations.
491 pub fn clone_to(&self, b: &mut Message) -> Result<()> {
492 b.raw.clear();
493 b.raw.extend_from_slice(&self.raw);
494 b.decode()
495 }
496
497 /// Contains return true if message contain t attribute.
498 pub fn contains(&self, t: AttrType) -> bool {
499 for a in &self.attributes.0 {
500 if a.typ == t {
501 return true;
502 }
503 }
504 false
505 }
506
507 /// Get returns byte slice that represents attribute value,
508 /// if there is no attribute with such type,
509 /// ErrAttributeNotFound is returned.
510 pub fn get(&self, t: AttrType) -> Result<Vec<u8>> {
511 let (v, ok) = self.attributes.get(t);
512 if ok {
513 Ok(v.value)
514 } else {
515 Err(Error::ErrAttributeNotFound)
516 }
517 }
518
519 /// The offset in [`raw`](Self::raw) of the attribute at `index` (its type field), or of the
520 /// end of the attributes when `index` is their count.
521 ///
522 /// Computed from the attribute list, which mirrors `raw` after `decode`, `build` or `add`.
523 pub(crate) fn attribute_offset(&self, index: usize) -> usize {
524 MESSAGE_HEADER_SIZE
525 + self
526 .attributes
527 .0
528 .iter()
529 .take(index)
530 .map(|a| ATTRIBUTE_HEADER_SIZE + nearest_padded_value_length(a.value.len()))
531 .sum::<usize>()
532 }
533
534 /// The position of the first attribute of type `t`.
535 pub(crate) fn position(&self, t: AttrType) -> Option<usize> {
536 self.attributes.0.iter().position(|a| a.typ == t)
537 }
538
539 /// The comprehension-required attributes of this message (types below `0x8000`) that are
540 /// not in `known`, in the order they appear, each once.
541 ///
542 /// RFC 8489 section 6.3: a request that has any is answered 420 (Unknown Attribute) with
543 /// them in UNKNOWN-ATTRIBUTES (section 6.3.1); an indication or a response that has any is
544 /// discarded (sections 6.3.2 to 6.3.4). `known` is what the usage understands:
545 /// [`STUN_ATTRIBUTES`] plus its own.
546 ///
547 /// This looks at every attribute. In an authenticated message only the attributes ahead
548 /// of the integrity attribute count: use
549 /// [`Validator`](crate::validated::Validator), which does both.
550 pub fn unknown_required_attributes(&self, known: &[AttrType]) -> Vec<AttrType> {
551 let mut unknown: Vec<AttrType> = vec![];
552 for a in &self.attributes.0 {
553 if a.typ.required() && !known.contains(&a.typ) && !unknown.contains(&a.typ) {
554 unknown.push(a.typ);
555 }
556 }
557 unknown
558 }
559
560 /// Resets the message and applies `setters` to it in order, returning on the first
561 /// error.
562 ///
563 /// Each setter writes its attribute into the message as it is applied, so the encoded
564 /// [`raw`](Self::raw) bytes are complete once this returns. Order matters for setters
565 /// that cover the attributes before them โ a
566 /// [`MessageIntegrity`](crate::integrity::MessageIntegrity) or
567 /// [`FINGERPRINT`](crate::fingerprint::FINGERPRINT) therefore goes last.
568 ///
569 /// ```
570 /// use rtci_stun::attributes::ATTR_SOFTWARE;
571 /// use rtci_stun::message::{BINDING_REQUEST, Message, TransactionId};
572 /// use rtci_stun::textattrs::TextAttribute;
573 ///
574 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
575 /// let mut m = Message::new();
576 /// m.build(&[
577 /// Box::new(BINDING_REQUEST),
578 /// Box::new(TransactionId::new()),
579 /// Box::new(TextAttribute::new(ATTR_SOFTWARE, "webrtc-rs".to_owned())),
580 /// ])?;
581 ///
582 /// assert!(!m.raw.is_empty());
583 /// # Ok(())
584 /// # }
585 /// ```
586 ///
587 /// # Errors
588 ///
589 /// Fails with the first setter's error, or with [`Error::ErrPacketTooBig`] once the
590 /// attributes no longer fit the 16-bit message length (RFC 8489 ยง5).
591 pub fn build(&mut self, setters: &[Box<dyn Setter + '_>]) -> Result<()> {
592 self.reset();
593 self.write_header();
594 for s in setters {
595 s.add_to(self)?;
596 // Checked after every setter, so MESSAGE-INTEGRITY and FINGERPRINT are never
597 // computed over a header whose length does not describe the message.
598 if self.length > u32::from(u16::MAX) {
599 return Err(Error::ErrPacketTooBig);
600 }
601 }
602 Ok(())
603 }
604
605 /// Check applies checkers to message in batch, returning on first error.
606 pub fn check<C: Checker>(&self, checkers: &[C]) -> Result<()> {
607 for c in checkers {
608 c.check(self)?;
609 }
610 Ok(())
611 }
612
613 /// Parse applies getters to message in batch, returning on first error.
614 pub fn parse<G: Getter>(&self, getters: &mut [G]) -> Result<()> {
615 for c in getters {
616 c.get_from(self)?;
617 }
618 Ok(())
619 }
620}
621
622// MessageClass is 8-bit representation of 2-bit class of STUN Message Class.
623#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
624/// A STUN message class: request, indication, success response or error response.
625pub struct MessageClass(u8);
626
627/// Possible values for message class in STUN Message Type.
628/// 0b00.
629pub const CLASS_REQUEST: MessageClass = MessageClass(0x00);
630/// 0b01.
631pub const CLASS_INDICATION: MessageClass = MessageClass(0x01);
632/// 0b10.
633pub const CLASS_SUCCESS_RESPONSE: MessageClass = MessageClass(0x02);
634/// 0b11.
635pub const CLASS_ERROR_RESPONSE: MessageClass = MessageClass(0x03);
636
637impl fmt::Display for MessageClass {
638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
639 let s = match *self {
640 CLASS_REQUEST => "request",
641 CLASS_INDICATION => "indication",
642 CLASS_SUCCESS_RESPONSE => "success response",
643 CLASS_ERROR_RESPONSE => "error response",
644 _ => "unknown message class",
645 };
646
647 write!(f, "{s}")
648 }
649}
650
651// Method is uint16 representation of 12-bit STUN method.
652#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
653/// A STUN method, such as Binding or one of TURN's.
654pub struct Method(u16);
655
656/// Possible methods for STUN Message.
657pub const METHOD_BINDING: Method = Method(0x001);
658/// TURN Allocate: asks a relay for a public address.
659pub const METHOD_ALLOCATE: Method = Method(0x003);
660/// TURN Refresh: extends or releases an allocation.
661pub const METHOD_REFRESH: Method = Method(0x004);
662/// TURN Send: an indication carrying data to a peer through the relay.
663pub const METHOD_SEND: Method = Method(0x006);
664/// TURN Data: an indication carrying data from a peer through the relay.
665pub const METHOD_DATA: Method = Method(0x007);
666/// TURN CreatePermission: authorizes traffic to and from a peer address.
667pub const METHOD_CREATE_PERMISSION: Method = Method(0x008);
668/// TURN ChannelBind: binds a channel number to a peer for compact framing.
669pub const METHOD_CHANNEL_BIND: Method = Method(0x009);
670
671/// Methods from RFC 6062.
672pub const METHOD_CONNECT: Method = Method(0x000a);
673/// TURN-TCP ConnectionBind: associates a new TCP connection with an allocation.
674pub const METHOD_CONNECTION_BIND: Method = Method(0x000b);
675/// TURN-TCP ConnectionAttempt: notifies the client of an inbound TCP connection.
676pub const METHOD_CONNECTION_ATTEMPT: Method = Method(0x000c);
677
678impl fmt::Display for Method {
679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 let unknown = format!("0x{:x}", self.0);
681
682 let s = match *self {
683 METHOD_BINDING => "Binding",
684 METHOD_ALLOCATE => "Allocate",
685 METHOD_REFRESH => "Refresh",
686 METHOD_SEND => "Send",
687 METHOD_DATA => "Data",
688 METHOD_CREATE_PERMISSION => "CreatePermission",
689 METHOD_CHANNEL_BIND => "ChannelBind",
690
691 // RFC 6062.
692 METHOD_CONNECT => "Connect",
693 METHOD_CONNECTION_BIND => "ConnectionBind",
694 METHOD_CONNECTION_ATTEMPT => "ConnectionAttempt",
695 _ => unknown.as_str(),
696 };
697
698 write!(f, "{s}")
699 }
700}
701
702// MessageType is STUN Message Type Field.
703#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
704/// A message's class and method together, as encoded in the first two header bytes.
705pub struct MessageType {
706 /// The method, such as Binding or Allocate.
707 pub method: Method, // e.g. binding
708 /// The class: request, indication, success response, or error response.
709 pub class: MessageClass, // e.g. request
710}
711
712/// Common STUN message types.
713/// Binding request message type.
714pub const BINDING_REQUEST: MessageType = MessageType {
715 method: METHOD_BINDING,
716 class: CLASS_REQUEST,
717};
718/// Binding success response message type.
719pub const BINDING_SUCCESS: MessageType = MessageType {
720 method: METHOD_BINDING,
721 class: CLASS_SUCCESS_RESPONSE,
722};
723/// Binding error response message type.
724pub const BINDING_ERROR: MessageType = MessageType {
725 method: METHOD_BINDING,
726 class: CLASS_ERROR_RESPONSE,
727};
728
729impl fmt::Display for MessageType {
730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731 write!(f, "{} {}", self.method, self.class)
732 }
733}
734
735const METHOD_ABITS: u16 = 0xf; // 0b0000000000001111
736const METHOD_BBITS: u16 = 0x70; // 0b0000000001110000
737const METHOD_DBITS: u16 = 0xf80; // 0b0000111110000000
738
739const METHOD_BSHIFT: u16 = 1;
740const METHOD_DSHIFT: u16 = 2;
741
742const FIRST_BIT: u16 = 0x1;
743const SECOND_BIT: u16 = 0x2;
744
745const C0BIT: u16 = FIRST_BIT;
746const C1BIT: u16 = SECOND_BIT;
747
748const CLASS_C0SHIFT: u16 = 4;
749const CLASS_C1SHIFT: u16 = 7;
750
751impl Setter for MessageType {
752 // add_to sets m type to t.
753 fn add_to(&self, m: &mut Message) -> Result<()> {
754 m.set_type(*self);
755 Ok(())
756 }
757}
758
759impl MessageType {
760 /// NewType returns new message type with provided method and class.
761 pub fn new(method: Method, class: MessageClass) -> Self {
762 MessageType { method, class }
763 }
764
765 /// Value returns bit representation of messageType.
766 pub fn value(&self) -> u16 {
767 // 0 1
768 // 2 3 4 5 6 7 8 9 0 1 2 3 4 5
769 // +--+--+-+-+-+-+-+-+-+-+-+-+-+-+
770 // |M |M |M|M|M|C|M|M|M|C|M|M|M|M|
771 // |11|10|9|8|7|1|6|5|4|0|3|2|1|0|
772 // +--+--+-+-+-+-+-+-+-+-+-+-+-+-+
773 // Figure 3: Format of STUN Message Type Field
774
775 // Warning: Abandon all hope ye who enter here.
776 // Splitting M into A(M0-M3), B(M4-M6), D(M7-M11).
777 let method = self.method.0;
778 let a = method & METHOD_ABITS; // A = M * 0b0000000000001111 (right 4 bits)
779 let b = method & METHOD_BBITS; // B = M * 0b0000000001110000 (3 bits after A)
780 let d = method & METHOD_DBITS; // D = M * 0b0000111110000000 (5 bits after B)
781
782 // Shifting to add "holes" for C0 (at 4 bit) and C1 (8 bit).
783 let method = a + (b << METHOD_BSHIFT) + (d << METHOD_DSHIFT);
784
785 // C0 is zero bit of C, C1 is first bit.
786 // C0 = C * 0b01, C1 = (C * 0b10) >> 1
787 // Ct = C0 << 4 + C1 << 8.
788 // Optimizations: "((C * 0b10) >> 1) << 8" as "(C * 0b10) << 7"
789 // We need C0 shifted by 4, and C1 by 8 to fit "11" and "7" positions
790 // (see figure 3).
791 let c = self.class.0 as u16;
792 let c0 = (c & C0BIT) << CLASS_C0SHIFT;
793 let c1 = (c & C1BIT) << CLASS_C1SHIFT;
794 let class = c0 + c1;
795
796 method + class
797 }
798
799 /// ReadValue decodes uint16 into MessageType.
800 pub fn read_value(&mut self, value: u16) {
801 // Decoding class.
802 // We are taking first bit from v >> 4 and second from v >> 7.
803 let c0 = (value >> CLASS_C0SHIFT) & C0BIT;
804 let c1 = (value >> CLASS_C1SHIFT) & C1BIT;
805 let class = c0 + c1;
806 self.class = MessageClass(class as u8);
807
808 // Decoding method.
809 let a = value & METHOD_ABITS; // A(M0-M3)
810 let b = (value >> METHOD_BSHIFT) & METHOD_BBITS; // B(M4-M6)
811 let d = (value >> METHOD_DSHIFT) & METHOD_DBITS; // D(M7-M11)
812 let m = a + b + d;
813 self.method = Method(m);
814 }
815}