stun_rs/
types.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use crate::common::{check_buffer_boundaries, sha256};
use crate::error::{StunError, StunErrorType};
use crate::strings::opaque_string_enforce;
use crate::{Algorithm, AlgorithmId, Encode};
use byteorder::{BigEndian, ByteOrder};
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;

pub(crate) const MAGIC_COOKIE_SIZE: usize = 4;
pub(crate) const TRANSACTION_ID_SIZE: usize = 12;

/// STUN message cookie
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Cookie(u32);

impl Cookie {
    /// Returns the [`u32`] representation of the cookie
    pub fn as_u32(&self) -> u32 {
        self.0
    }
}

impl PartialEq<u32> for Cookie {
    fn eq(&self, other: &u32) -> bool {
        self.0 == *other
    }
}

impl PartialEq<Cookie> for u32 {
    fn eq(&self, other: &Cookie) -> bool {
        *self == other.0
    }
}

impl PartialEq<[u8; MAGIC_COOKIE_SIZE]> for Cookie {
    fn eq(&self, other: &[u8; MAGIC_COOKIE_SIZE]) -> bool {
        self.0 == BigEndian::read_u32(other)
    }
}

impl PartialEq<&[u8; MAGIC_COOKIE_SIZE]> for Cookie {
    fn eq(&self, other: &&[u8; MAGIC_COOKIE_SIZE]) -> bool {
        let slice = *other;
        self.0 == BigEndian::read_u32(slice)
    }
}

impl PartialEq<Cookie> for [u8; MAGIC_COOKIE_SIZE] {
    fn eq(&self, other: &Cookie) -> bool {
        other.0 == BigEndian::read_u32(self)
    }
}

impl PartialEq<Cookie> for &[u8; MAGIC_COOKIE_SIZE] {
    fn eq(&self, other: &Cookie) -> bool {
        let slice = *self;
        other.0 == BigEndian::read_u32(slice)
    }
}

impl AsRef<u32> for Cookie {
    fn as_ref(&self) -> &u32 {
        &self.0
    }
}

/// STUN magic cookie
pub const MAGIC_COOKIE: Cookie = Cookie(0x2112_A442);

/// The transaction ID is a 96-bit identifier, used to uniquely identify
/// STUN transactions. It primarily serves to correlate requests with
/// responses, though it also plays a small role in helping to prevent
/// certain types of attacks. The server also uses the transaction ID as
/// a key to identify each transaction uniquely across all clients.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TransactionId([u8; TRANSACTION_ID_SIZE]);
impl TransactionId {
    /// Returns a reference to the bytes that represents the identifier.
    pub fn as_bytes(&self) -> &[u8; TRANSACTION_ID_SIZE] {
        &self.0
    }
}

fn fmt_transcation_id(bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
    for byte in bytes {
        write!(f, "{:02X}", byte)?;
    }
    write!(f, ")")
}

impl fmt::Debug for TransactionId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "TransactionId(0x")?;
        fmt_transcation_id(self.as_ref(), f)
    }
}

impl fmt::Display for TransactionId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "transaction id (0x")?;
        fmt_transcation_id(self.as_ref(), f)
    }
}

impl Deref for TransactionId {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        &self.0
    }
}

impl AsRef<[u8]> for TransactionId {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl From<&[u8; TRANSACTION_ID_SIZE]> for TransactionId {
    fn from(buff: &[u8; TRANSACTION_ID_SIZE]) -> Self {
        Self(*buff)
    }
}

impl From<[u8; TRANSACTION_ID_SIZE]> for TransactionId {
    fn from(buff: [u8; TRANSACTION_ID_SIZE]) -> Self {
        Self(buff)
    }
}

impl Distribution<TransactionId> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> TransactionId {
        let mut buffer = [0u8; TRANSACTION_ID_SIZE];
        rng.fill_bytes(&mut buffer);
        TransactionId::from(buffer)
    }
}

impl Default for TransactionId {
    /// Creates a cryptographically random transaction ID chosen from the interval 0 .. 2**96-1.
    fn default() -> Self {
        let mut rng = rand::thread_rng();
        rng.gen()
    }
}

/// Authentication and message-integrity mechanisms.
/// The STUN [`RFC8489`](https://datatracker.ietf.org/doc/html/rfc8489)
/// defines two mechanisms for STUN that a client and server
/// can use to provide authentication and message integrity; these two
/// mechanisms are known as the short-term credential mechanism and the
/// long-term credential mechanism.  These two mechanisms are optional,
/// and each usage must specify if and when these mechanisms are used.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum CredentialMechanism {
    /// [short-term credential mechanism](https://datatracker.ietf.org/doc/html/rfc8489#section-9.1)
    ShortTerm,
    /// [long-term credential mechanism](https://datatracker.ietf.org/doc/html/rfc8489#section-9.2)
    LongTerm,
}

impl CredentialMechanism {
    /// Returns true if this is a short-term-credential mechanism
    pub fn is_short_term(&self) -> bool {
        matches!(self, CredentialMechanism::ShortTerm)
    }

    /// Returns true if this is a long-term-credential mechanism
    pub fn is_long_term(&self) -> bool {
        matches!(self, CredentialMechanism::LongTerm)
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
struct HMACKeyPriv {
    mechanism: CredentialMechanism,
    key: Vec<u8>,
}

/// Key used for authentication and message integrity
///
/// # Examples:
///```rust
/// # use stun_rs::{Algorithm, AlgorithmId, CredentialMechanism, HMACKey};
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// // Creates a new long term credential key using MD5 algorithm
/// let algorithm = Algorithm::from(AlgorithmId::MD5);
/// let key = HMACKey::new_long_term("user", "realm", "pass", algorithm)?;
/// assert_eq!(key.credential_mechanism(), CredentialMechanism::LongTerm);
///
/// let expected_hash = [
///     0x84, 0x93, 0xFB, 0xC5, 0x3B, 0xA5, 0x82, 0xFB,
///     0x4C, 0x04, 0x4C, 0x45, 0x6B, 0xDC, 0x40, 0xEB,
/// ];
/// assert_eq!(key.as_bytes(), expected_hash);
/// #
/// #   Ok(())
/// # }
///```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct HMACKey(Rc<HMACKeyPriv>);

impl HMACKey {
    /// Creates a [`CredentialMechanism::ShortTerm`] key
    /// # Returns
    /// The new [`HMACKey`] used for short term credential mechanism, or a `StunError` if
    /// the password can not be processed using the opaque string profile.
    pub fn new_short_term<S>(password: S) -> Result<Self, StunError>
    where
        S: AsRef<str>,
    {
        let key = opaque_string_enforce(password.as_ref())?
            .as_ref()
            .as_bytes()
            .to_vec();
        let mechanism = CredentialMechanism::ShortTerm;
        Ok(HMACKey(Rc::new(HMACKeyPriv { mechanism, key })))
    }

    /// Creates a [`CredentialMechanism::LongTerm`] key.
    /// # Arguments:
    /// - `username` - The user name
    /// - `realm` - The realm.
    /// - `algorithm`- Optional value for the algorithm used to generate the key. If
    ///      algorithm is None, [`AlgorithmId::MD5`](crate::AlgorithmId::MD5) will be used.
    ///      The resulting key length is 16 bytes when `MD5` is used, or 32 bytes if
    ///      SHA-256 algorithm is used.
    /// # Returns
    /// The new [`HMACKey`] used for long term credential mechanism, or a `StunError` if
    /// `username`, `realm` or `password` can not be processed using the opaque string profile.
    pub fn new_long_term<A, B, C, T>(
        username: A,
        realm: B,
        password: C,
        algorithm: T,
    ) -> Result<Self, StunError>
    where
        A: AsRef<str>,
        B: AsRef<str>,
        C: AsRef<str>,
        T: AsRef<Algorithm>,
    {
        let realm = opaque_string_enforce(realm.as_ref())?;
        let password = opaque_string_enforce(password.as_ref())?;
        let key_str = format!("{}:{}:{}", username.as_ref(), realm, password);
        let key = HMACKey::get_key(&key_str, algorithm.as_ref())?;

        let mechanism = CredentialMechanism::LongTerm;
        Ok(HMACKey(Rc::new(HMACKeyPriv { mechanism, key })))
    }

    /// Gets the bytes representation of the key
    pub fn as_bytes(&self) -> &[u8] {
        &self.0.key
    }

    /// Gets the bytes representation of the key
    pub fn credential_mechanism(&self) -> CredentialMechanism {
        self.0.mechanism
    }

    fn get_key(key: &str, params: &Algorithm) -> Result<Vec<u8>, StunError> {
        match params.algorithm() {
            AlgorithmId::MD5 => {
                // Ignore the parameters argument (must be empty)
                let digest = md5::compute(key);
                Ok(digest.0.to_vec())
            }
            AlgorithmId::SHA256 => {
                // Ignore the parameters argument (must be empty)
                Ok(sha256(key))
            }
            _ => Err(StunError::new(
                StunErrorType::InvalidParam,
                format!("Invalid algorithm: {}", params.algorithm()),
            )),
        }
    }
}

const ADDRESS_FAMILY_SIZE: usize = 1;

/// Address family
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AddressFamily {
    /// IP version 4
    IPv4,
    /// IP version 6
    IPv6,
}

impl TryFrom<u8> for AddressFamily {
    type Error = StunError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x01 => Ok(AddressFamily::IPv4),
            0x02 => Ok(AddressFamily::IPv6),
            _ => Err(StunError::new(
                StunErrorType::InvalidParam,
                format!("Invalid address family ({:#02x})", value),
            )),
        }
    }
}

impl<'a> crate::Decode<'a> for AddressFamily {
    fn decode(raw_value: &[u8]) -> Result<(Self, usize), StunError> {
        check_buffer_boundaries(raw_value, ADDRESS_FAMILY_SIZE)?;
        Ok((AddressFamily::try_from(raw_value[0])?, ADDRESS_FAMILY_SIZE))
    }
}

impl Encode for AddressFamily {
    fn encode(&self, raw_value: &mut [u8]) -> Result<usize, StunError> {
        check_buffer_boundaries(raw_value, ADDRESS_FAMILY_SIZE)?;
        raw_value[0] = match self {
            AddressFamily::IPv4 => 0x01,
            AddressFamily::IPv6 => 0x02,
        };
        Ok(ADDRESS_FAMILY_SIZE)
    }
}

const MIN_ERROR_CODE: u16 = 300;
const MAX_ERROR_CODE: u16 = 700;
const MAX_REASON_PHRASE_ENCODED_SIZE: usize = 509;
const MAX_REASON_PHRASE_DECODED_SIZE: usize = 763;

/// The `ErrorCode` contains a numeric error code value in the range of 300
/// to 699 plus a textual reason phrase encoded in UTF-8
/// [`RFC3629`](https://datatracker.ietf.org/doc/html/rfc3629); it is also
/// consistent in its code assignments and semantics with SIP
/// [`RFC3261`](https://datatracker.ietf.org/doc/html/rfc3261)
/// and HTTP [`RFC7231`](https://datatracker.ietf.org/doc/html/rfc7231).
/// The reason phrase is meant for diagnostic purposes and can be anything
/// appropriate for the error code.
/// Recommended reason phrases for the defined error codes are included
/// in the `IANA` registry for error codes.  The reason phrase MUST be a
/// UTF-8-encoded [`RFC3629`](https://datatracker.ietf.org/doc/html/rfc3629)
/// sequence of fewer than 128 characters (which can be as long as 509 bytes
/// when encoding them or 763 bytes when decoding them).
/// # Examples
///```rust
/// # use stun_rs::ErrorCode;
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let attr = ErrorCode::new(420, "Unknown Attribute")?;
/// assert_eq!(attr.class(), 4);
/// assert_eq!(attr.number(), 20);
/// assert_eq!(attr.error_code(), 420);
/// assert_eq!(attr.reason(), "Unknown Attribute");
/// #  Ok(())
/// # }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorCode {
    error_code: u16,
    reason: String,
}

impl ErrorCode {
    /// Creates a new `ErrorCode` type.
    /// # Arguments:
    /// * `error_code` - The numeric error code.
    /// * `reason` - The reason phrase.
    /// # Return:
    /// The `ErrorCode` type or a [`StunError`] if the numeric
    /// error value is not in the range of 300 to 699.
    pub fn new(error_code: u16, reason: &str) -> Result<Self, StunError> {
        (MIN_ERROR_CODE..MAX_ERROR_CODE)
            .contains(&error_code)
            .then(|| Self {
                error_code,
                reason: String::from(reason),
            })
            .ok_or_else(|| {
                StunError::new(
                    StunErrorType::InvalidParam,
                    format!("Error code is not ({}..{})", MIN_ERROR_CODE, MAX_ERROR_CODE),
                )
            })
    }

    /// Returns the numeric error code value .
    pub fn error_code(&self) -> u16 {
        self.error_code
    }

    /// Returns the class of the error code (the hundreds digit).
    pub fn class(&self) -> u8 {
        ((self.error_code - self.number() as u16) / 100)
            .try_into()
            .unwrap()
    }

    /// Returns the binary encoding of the error code modulo 100.
    pub fn number(&self) -> u8 {
        (self.error_code % 100).try_into().unwrap()
    }

    /// Returns the reason phrase associated to this error.
    pub fn reason(&self) -> &str {
        self.reason.as_str()
    }
}

// ErrorCode format
//  0                   1                   2                   3
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |           Reserved, should be 0         |Class|     Number    |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |      Reason Phrase (variable)                                ..
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

impl<'a> crate::Decode<'a> for ErrorCode {
    fn decode(raw_value: &[u8]) -> Result<(Self, usize), StunError> {
        check_buffer_boundaries(raw_value, 4)?;

        let class = raw_value[2] & 0x07;
        if !(3..=6).contains(&class) {
            return Err(StunError::new(
                StunErrorType::InvalidParam,
                format!("Error class {} is not in the range (3..=6)", class),
            ));
        }

        let number = raw_value[3];
        if !(0..=99).contains(&number) {
            return Err(StunError::new(
                StunErrorType::InvalidParam,
                format!("Error number {} is not in the range (0..=99)", number),
            ));
        }

        let reason = std::str::from_utf8(&raw_value[4..])?;

        if reason.len() > MAX_REASON_PHRASE_DECODED_SIZE {
            return Err(StunError::new(
                StunErrorType::ValueTooLong,
                format!(
                    "Reason length ({}) > Max. decoded size ({})",
                    reason.len(),
                    MAX_REASON_PHRASE_DECODED_SIZE
                ),
            ));
        }

        let error_code = class as u16 * 100 + number as u16;
        Ok((ErrorCode::new(error_code, reason)?, raw_value.len()))
    }
}

impl Encode for ErrorCode {
    fn encode(&self, raw_value: &mut [u8]) -> Result<usize, StunError> {
        let mut len = 4; // (Reserved + class + number)
        let reason_len = self.reason.len();

        if reason_len > MAX_REASON_PHRASE_ENCODED_SIZE {
            return Err(StunError::new(
                StunErrorType::ValueTooLong,
                format!(
                    "Reason length ({}) > Max. encoded size ({})",
                    reason_len, MAX_REASON_PHRASE_ENCODED_SIZE
                ),
            ));
        }

        len += reason_len;

        check_buffer_boundaries(raw_value, len)?;

        raw_value[0] = 0;
        raw_value[1] = 0;
        raw_value[2] = self.class();
        raw_value[3] = self.number();
        raw_value[4..reason_len + 4].clone_from_slice(self.reason.as_bytes());
        Ok(len)
    }
}

#[cfg(test)]
mod stun_cookie {
    use super::*;

    #[test]
    fn stun_cookie() {
        let cookie = [0x21, 0x12, 0xa4, 0x42];
        assert!(MAGIC_COOKIE.eq(&cookie));
        assert!(cookie.eq(&MAGIC_COOKIE));
        assert_eq!(MAGIC_COOKIE, cookie);
        assert_eq!(cookie, MAGIC_COOKIE);

        let default_value = 0x2112_A442;
        assert!(MAGIC_COOKIE.eq(&default_value));
        assert!(default_value.eq(&MAGIC_COOKIE));
        assert_eq!(MAGIC_COOKIE, default_value);
        assert_eq!(default_value, MAGIC_COOKIE);
        assert_eq!(MAGIC_COOKIE, &cookie);
        assert_eq!(&cookie, MAGIC_COOKIE);

        let val: &u32 = MAGIC_COOKIE.as_ref();
        assert_eq!(*val, default_value);
    }
}

#[cfg(test)]
mod error_code_tests {
    use super::*;
    use crate::Decode;

    #[test]
    fn constructor() {
        assert!(ErrorCode::new(299, "Invalid code").is_err());
        assert!(ErrorCode::new(300, "Try alternate").is_ok());
        assert!(ErrorCode::new(699, "Test error").is_ok());
        assert!(ErrorCode::new(700, "Invalid code").is_err());
    }

    #[test]
    fn check_properties() {
        let result = ErrorCode::new(300, "Try alternate");
        assert!(result.is_ok());
        let error_code = result.unwrap();
        assert_eq!(error_code.number(), 0);
        assert_eq!(error_code.class(), 3);

        let result = ErrorCode::new(512, "Try alternate");
        assert!(result.is_ok());
        let error_code = result.unwrap();
        assert_eq!(error_code.number(), 12);
        assert_eq!(error_code.class(), 5);

        let result = ErrorCode::new(699, "Try alternate");
        assert!(result.is_ok());
        let error_code = result.unwrap();
        assert_eq!(error_code.number(), 99);
        assert_eq!(error_code.class(), 6);
    }

    #[test]
    fn decode_error_code() {
        let buffer = [
            0xda, 0xa5, 0xfb, 0x12, 0x74, 0x65, 0x73, 0x74, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f,
            0x6e,
        ];
        let (error_code, size) = ErrorCode::decode(&buffer).expect("Can not decode ErrorCode");
        assert_eq!(size, 15);
        assert_eq!(error_code.error_code(), 318);
        assert_eq!(error_code.class(), 3);
        assert_eq!(error_code.number(), 18);
        assert_eq!(error_code.reason(), "test reason");

        let buffer = [0x00, 0x00, 0x03, 0x12];
        let (error_code, size) = ErrorCode::decode(&buffer).expect("Can not decode ERROR-CODE");
        assert_eq!(size, 4);
        assert_eq!(error_code.error_code(), 318);
        assert_eq!(error_code.class(), 3);
        assert_eq!(error_code.number(), 18);
        assert!(error_code.reason().is_empty());

        // short buffer
        let buffer = [0x00, 0x00, 0x03];
        let result = ErrorCode::decode(&buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        // Wrong class: 2
        let buffer = [
            0x00, 0x00, 0x02, 0x12, 0x74, 0x65, 0x73, 0x74, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f,
            0x6e,
        ];
        let result = ErrorCode::decode(&buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::InvalidParam
        );

        // Wrong number: 112
        let buffer = [
            0x00, 0x00, 0x03, 0x70, 0x74, 0x65, 0x73, 0x74, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f,
            0x6e,
        ];
        let result = ErrorCode::decode(&buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::InvalidParam
        );

        // Test MAX_REASON_PHRASE_DECODED_SIZE
        const EXTRA_BYTES: usize = 4; //(Reserved + class + number)
        let mut buffer: [u8; MAX_REASON_PHRASE_DECODED_SIZE + EXTRA_BYTES] =
            [0x0; MAX_REASON_PHRASE_DECODED_SIZE + EXTRA_BYTES];
        buffer[..EXTRA_BYTES].clone_from_slice(&[0x00, 0x00, 0x03, 0x12]);
        buffer[EXTRA_BYTES..]
            .clone_from_slice("\u{0041}".repeat(MAX_REASON_PHRASE_DECODED_SIZE).as_bytes());
        let (error_code, size) = ErrorCode::decode(&buffer).expect("Can not decode ErrorCode");
        assert_eq!(size, MAX_REASON_PHRASE_DECODED_SIZE + EXTRA_BYTES);
        assert_eq!(error_code.error_code(), 318);
        assert_eq!(error_code.class(), 3);
        assert_eq!(error_code.number(), 18);
        assert_eq!(
            error_code.reason(),
            "\u{0041}".repeat(MAX_REASON_PHRASE_DECODED_SIZE)
        );

        // Test with reason phrase longer than MAX_REASON_PHRASE_DECODED_SIZE
        const REASON_SIZE: usize = MAX_REASON_PHRASE_DECODED_SIZE + 1;
        let mut buffer: [u8; REASON_SIZE + EXTRA_BYTES] = [0x0; REASON_SIZE + EXTRA_BYTES];
        buffer[..EXTRA_BYTES].clone_from_slice(&[0x00, 0x00, 0x03, 0x12]);
        buffer[EXTRA_BYTES..].clone_from_slice("\u{0041}".repeat(REASON_SIZE).as_bytes());
        let result = ErrorCode::decode(&buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::ValueTooLong
        );
    }

    #[test]
    fn encode_error_code() {
        let error_code = ErrorCode::new(318, "test reason").expect("Can not encode ErroCode");

        let mut buffer: [u8; 14] = [0x0; 14];
        let result = error_code.encode(&mut buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        let mut buffer: [u8; 15] = [0x0; 15];
        let result = error_code.encode(&mut buffer);
        assert_eq!(result, Ok(15));

        let cmp_buffer = [
            0x00, 0x00, 0x03, 0x12, 0x74, 0x65, 0x73, 0x74, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f,
            0x6e,
        ];
        assert_eq!(&buffer[..], &cmp_buffer[..]);

        // Test MAX_REASON_PHRASE_ENCODED_SIZE
        const EXTRA_BYTES: usize = 4; //(Reserved + class + number)
        let error_code = ErrorCode::new(318, "x".repeat(MAX_REASON_PHRASE_ENCODED_SIZE).as_str())
            .expect("Can not encode ErroCode");
        let mut buffer: [u8; MAX_REASON_PHRASE_ENCODED_SIZE + EXTRA_BYTES] =
            [0x0; MAX_REASON_PHRASE_ENCODED_SIZE + EXTRA_BYTES];
        let result = error_code.encode(&mut buffer);
        assert_eq!(result, Ok(MAX_REASON_PHRASE_ENCODED_SIZE + EXTRA_BYTES));

        // Test with reason phrase longer than MAX_REASON_PHRASE_ENCODED_SIZE
        const REASON_SIZE: usize = MAX_REASON_PHRASE_ENCODED_SIZE + 1;
        let error_code = ErrorCode::new(318, "\u{0041}".repeat(REASON_SIZE).as_str())
            .expect("Can not encode ErroCode");
        let mut buffer: [u8; REASON_SIZE + EXTRA_BYTES] = [0x0; REASON_SIZE + EXTRA_BYTES];
        let result = error_code.encode(&mut buffer);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::ValueTooLong
        );
    }
}

#[cfg(test)]
mod transaction_id_tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn constructor() {
        let tr1 = TransactionId::default();
        let tr2 = TransactionId::default();
        assert_ne!(tr1, tr2);

        let tr3 = TransactionId::from(tr1.as_bytes());
        assert_eq!(tr1, tr3);

        // Check deref
        let slice: &[u8] = &tr3;
        assert_eq!(slice, tr3.as_bytes());

        format!("{}", tr1);
        format!("{:?}", tr1);
    }

    #[test]
    fn check_random() {
        let mut transactions = HashSet::new();

        while transactions.len() < 1000 {
            let tr = TransactionId::default();
            assert!(!transactions.contains(&tr));
            transactions.insert(tr);
        }
    }
}

#[cfg(test)]
mod credential_tests {
    use super::*;

    #[test]
    fn short_term_credential() {
        let key = HMACKey::new_short_term("foo\u{1680}bar").expect("Could not create HMACKey");

        // `OGHAM` SPACE MARK (U+1680) is mapped to SPACE (U+0020)
        // thus, the full string is mapped to <foo bar>
        assert!(key.credential_mechanism().is_short_term());

        let expected = "foo bar".as_bytes();
        assert_eq!(key.as_bytes(), expected);
    }

    #[test]
    fn long_term_credential() {
        // Example taken from RFC5389 15.4
        let algorithm = Algorithm::from(AlgorithmId::MD5);
        let key = HMACKey::new_long_term("user", "realm", "pass", algorithm)
            .expect("Could not create HMACKey");

        assert!(key.credential_mechanism().is_long_term());

        let md5_hash = [
            0x84, 0x93, 0xFB, 0xC5, 0x3B, 0xA5, 0x82, 0xFB, 0x4C, 0x04, 0x4C, 0x45, 0x6B, 0xDC,
            0x40, 0xEB,
        ];
        assert_eq!(key.as_bytes(), md5_hash);
        assert_eq!(key.as_bytes().len(), 16);

        let algorithm = Algorithm::from(AlgorithmId::SHA256);
        let key = HMACKey::new_long_term("user", "realm", "pass", algorithm)
            .expect("Could not create HMACKey");

        let sha256_hash = [
            0x07, 0xE9, 0x34, 0x11, 0x7A, 0xBD, 0x40, 0x83, 0x6E, 0x7C, 0x63, 0x29, 0xB5, 0x47,
            0x31, 0xB2, 0xB2, 0xD2, 0xA5, 0xF9, 0xA7, 0x1F, 0x54, 0x49, 0x22, 0xD7, 0x5E, 0x07,
            0x30, 0xD8, 0x25, 0x1B,
        ];
        assert_eq!(key.credential_mechanism(), CredentialMechanism::LongTerm);
        assert_eq!(key.as_bytes(), sha256_hash);
        assert_eq!(key.as_bytes().len(), 32);

        let algorithm = Algorithm::from(AlgorithmId::Unassigned(15));
        let error = HMACKey::new_long_term("user", "realm", "pass", algorithm)
            .expect_err("No HMACKey with unassigned algorithm must be created");
        assert_eq!(error, StunErrorType::InvalidParam);
    }
}