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
pub mod attributes;
pub mod methods;
use super::{
Attributes, Error,
crypto::{Password, fingerprint, hmac_sha1},
message::{
attributes::{Attribute, AttributeType, MessageIntegrity, MessageIntegritySha256},
methods::Method,
},
};
use bytes::{BufMut, BytesMut};
static MAGIC_NUMBER: u32 = 0x2112A442;
pub struct MessageEncoder<'a> {
transaction_id: &'a [u8],
bytes: &'a mut BytesMut,
}
impl<'a> MessageEncoder<'a> {
pub fn new(method: Method, transaction_id: &'a [u8; 12], bytes: &'a mut BytesMut) -> Self {
bytes.clear();
bytes.put_u16(method.into());
bytes.put_u16(0);
bytes.put_u32(MAGIC_NUMBER);
bytes.put(transaction_id.as_slice());
Self {
bytes,
transaction_id,
}
}
/// rely on old message to create new message.
///
/// # Test
///
/// ```
/// use bytes::BytesMut;
/// use std::convert::TryFrom;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let mut attributes = Attributes::default();
/// let mut buf = BytesMut::new();
/// let old = Message::decode(&buffer[..], &mut attributes).unwrap();
/// MessageEncoder::extend(Method::Binding(MethodType::Request), &old, &mut buf);
///
/// assert_eq!(&buf[..], &buffer[..]);
/// ```
pub fn extend(method: Method, reader: &Message<'a>, bytes: &'a mut BytesMut) -> Self {
let transaction_id = reader.transaction_id();
bytes.clear();
bytes.put_u16(method.into());
bytes.put_u16(0);
bytes.put_u32(MAGIC_NUMBER);
bytes.put(transaction_id);
Self {
bytes,
transaction_id,
}
}
/// append attribute.
///
/// append attribute to message attribute list.
///
/// # Test
///
/// ```
/// use bytes::BytesMut;
/// use std::convert::TryFrom;
/// use turn_server::codec::message::attributes::*;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let new_buf = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b, 0x00, 0x06, 0x00,
/// 0x05, 0x70, 0x61, 0x6e, 0x64, 0x61, 0x00, 0x00, 0x00,
/// ];
///
/// let mut buf = BytesMut::new();
/// let mut attributes = Attributes::default();
/// let old = Message::decode(&buffer[..], &mut attributes).unwrap();
/// let mut message =
/// MessageEncoder::extend(Method::Binding(MethodType::Request), &old, &mut buf);
///
/// message.append::<UserName>("panda");
///
/// assert_eq!(&new_buf[..], &buf[..]);
/// ```
pub fn append<'c, T: Attribute<'c>>(&'c mut self, value: T::Item) {
self.bytes.put_u16(T::TYPE as u16);
// record the current position,
// and then advance the internal cursor 2 bytes,
// here is to reserve the position.
let os = self.bytes.len();
unsafe { self.bytes.advance_mut(2) }
T::serialize(value, self.bytes, self.transaction_id);
// compute write index,
// back to source index write size.
let size = self.bytes.len() - os - 2;
let size_buf = (size as u16).to_be_bytes();
self.bytes[os] = size_buf[0];
self.bytes[os + 1] = size_buf[1];
// if you need to padding,
// padding in the zero bytes.
let psize = alignment_32(size);
if psize > 0 {
self.bytes.put(&[0u8; 10][0..psize]);
}
}
/// try decoder bytes as message.
///
/// # Test
///
/// ```
/// use bytes::BytesMut;
/// use std::convert::TryFrom;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let result = [
/// 0, 1, 0, 32, 33, 18, 164, 66, 114, 109, 73, 66, 114, 82, 100, 72, 87,
/// 98, 75, 43, 0, 8, 0, 20, 69, 14, 110, 68, 82, 30, 232, 222, 44, 240,
/// 250, 182, 156, 92, 25, 23, 152, 198, 217, 222, 128, 40, 0, 4, 74, 165,
/// 171, 86,
/// ];
///
/// let mut attributes = Attributes::default();
/// let mut buf = BytesMut::with_capacity(1280);
/// let old = Message::decode(&buffer[..], &mut attributes).unwrap();
/// let mut message =
/// MessageEncoder::extend(Method::Binding(MethodType::Request), &old, &mut buf);
///
/// message
/// .flush(Some(&turn_server::codec::crypto::generate_password(
/// "panda",
/// "panda",
/// "raspberry",
/// turn_server::codec::message::attributes::PasswordAlgorithm::Md5,
/// )))
/// .unwrap();
///
/// assert_eq!(&buf[..], &result);
/// ```
pub fn flush(&mut self, password: Option<&Password>) -> Result<(), Error> {
// write attribute list size.
self.set_len(self.bytes.len() - 20);
// if need message integrity?
if let Some(it) = password {
self.verify(it)?;
}
Ok(())
}
/// append MessageIntegrity attribute.
///
/// add the `MessageIntegrity` attribute to the stun message
/// and serialize the message into a buffer.
///
/// # Test
///
/// ```
/// use bytes::BytesMut;
/// use std::convert::TryFrom;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let result = [
/// 0, 1, 0, 32, 33, 18, 164, 66, 114, 109, 73, 66, 114, 82, 100, 72, 87,
/// 98, 75, 43, 0, 8, 0, 20, 69, 14, 110, 68, 82, 30, 232, 222, 44, 240,
/// 250, 182, 156, 92, 25, 23, 152, 198, 217, 222, 128, 40, 0, 4, 74, 165,
/// 171, 86,
/// ];
///
/// let mut attributes = Attributes::default();
/// let mut buf = BytesMut::from(&buffer[..]);
/// let old = Message::decode(&buffer[..], &mut attributes).unwrap();
/// let mut message =
/// MessageEncoder::extend(Method::Binding(MethodType::Request), &old, &mut buf);
///
/// message
/// .flush(Some(&turn_server::codec::crypto::generate_password(
/// "panda",
/// "panda",
/// "raspberry",
/// turn_server::codec::message::attributes::PasswordAlgorithm::Md5,
/// )))
/// .unwrap();
///
/// assert_eq!(&buf[..], &result);
/// ```
fn verify(&mut self, password: &Password) -> Result<(), Error> {
assert!(self.bytes.len() >= 20);
let len = self.bytes.len();
// compute new size,
// new size include the MessageIntegrity attribute size.
self.set_len(len + 4);
// write MessageIntegrity attribute.
{
let hmac = hmac_sha1(password, &[self.bytes]);
self.bytes.put_u16(match password {
Password::Md5(_) => AttributeType::MessageIntegrity as u16,
Password::Sha256(_) => AttributeType::MessageIntegritySha256 as u16,
});
self.bytes.put_u16(20);
self.bytes.put(hmac.as_slice());
}
// compute new size,
// new size include the Fingerprint attribute size.
self.set_len(len + 4 + 8);
// CRC Fingerprint
let fingerprint = fingerprint(self.bytes);
self.bytes.put_u16(AttributeType::Fingerprint as u16);
self.bytes.put_u16(4);
self.bytes.put_u32(fingerprint);
Ok(())
}
// set stun message header size.
fn set_len(&mut self, len: usize) {
self.bytes[2..4].copy_from_slice((len as u16).to_be_bytes().as_slice());
}
}
pub struct Message<'a> {
/// message method.
method: Method,
/// message source bytes.
bytes: &'a [u8],
/// message payload size.
size: u16,
// message attribute list.
attributes: &'a Attributes,
}
impl<'a> Message<'a> {
/// message method.
#[inline]
pub fn method(&self) -> Method {
self.method
}
/// message transaction id.
#[inline]
pub fn transaction_id(&self) -> &'a [u8] {
&self.bytes[8..20]
}
/// get attribute.
///
/// get attribute from message attribute list.
///
/// # Test
///
/// ```
/// use std::convert::TryFrom;
/// use turn_server::codec::message::attributes::*;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let mut attributes = Attributes::default();
/// let message = Message::decode(&buffer[..], &mut attributes).unwrap();
///
/// assert!(message.get::<UserName>().is_none());
/// ```
pub fn get<T: Attribute<'a>>(&self) -> Option<T::Item> {
let range = self.attributes.get(&T::TYPE)?;
T::deserialize(&self.bytes[range], self.transaction_id()).ok()
}
/// get attribute for type.
///
/// get attribute from message attribute list.
///
/// # Test
///
/// ```
/// use std::convert::TryFrom;
/// use turn_server::codec::message::attributes::*;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let mut attributes = Attributes::default();
/// let message = Message::decode(&buffer[..], &mut attributes).unwrap();
///
/// assert!(message.get_for_type(AttributeType::UserName).is_none());
/// ```
pub fn get_for_type(&self, attr_type: AttributeType) -> Option<&'a [u8]> {
let range = self.attributes.get(&attr_type)?;
Some(&self.bytes[range])
}
/// Gets all the values of an attribute from a list.
///
/// Normally a stun message can have multiple attributes with the same name,
/// and this function will all the values of the current attribute.
///
/// # Test
///
/// ```
/// use std::convert::TryFrom;
/// use turn_server::codec::message::attributes::*;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49,
/// 0x42, 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let mut attributes = Attributes::default();
/// let message = Message::decode(&buffer[..], &mut attributes).unwrap();
///
/// assert_eq!(message.get_all::<UserName>().next(), None);
/// ```
pub fn get_all<T: Attribute<'a>>(&self) -> impl Iterator<Item = T::Item> {
self.attributes
.get_all(&T::TYPE)
.map(|it| T::deserialize(&self.bytes[it.clone()], self.transaction_id()))
.filter(|it| it.is_ok())
.flatten()
}
/// check MessageRefIntegrity attribute.
///
/// return whether the `MessageRefIntegrity` attribute contained in the message
/// can pass the check.
///
///
/// # Test
///
/// ```
/// use std::convert::TryFrom;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer = [
/// 0x00u8, 0x03, 0x00, 0x50, 0x21, 0x12, 0xa4, 0x42, 0x64, 0x4f, 0x5a,
/// 0x78, 0x6a, 0x56, 0x33, 0x62, 0x4b, 0x52, 0x33, 0x31, 0x00, 0x19, 0x00,
/// 0x04, 0x11, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x05, 0x70, 0x61, 0x6e,
/// 0x64, 0x61, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x09, 0x72, 0x61, 0x73,
/// 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x15, 0x00,
/// 0x10, 0x31, 0x63, 0x31, 0x33, 0x64, 0x32, 0x62, 0x32, 0x34, 0x35, 0x62,
/// 0x33, 0x61, 0x37, 0x33, 0x34, 0x00, 0x08, 0x00, 0x14, 0xd6, 0x78, 0x26,
/// 0x99, 0x0e, 0x15, 0x56, 0x15, 0xe5, 0xf4, 0x24, 0x74, 0xe2, 0x3c, 0x26,
/// 0xc5, 0xb1, 0x03, 0xb2, 0x6d,
/// ];
///
/// let mut attributes = Attributes::default();
/// let message = Message::decode(&buffer[..], &mut attributes).unwrap();
/// let result = message
/// .verify(&turn_server::codec::crypto::generate_password(
/// "panda",
/// "panda",
/// "raspberry",
/// turn_server::codec::message::attributes::PasswordAlgorithm::Md5,
/// ))
/// .is_ok();
///
/// assert!(result);
/// ```
pub fn verify(&self, password: &Password) -> Result<(), Error> {
if self.bytes.is_empty() || self.size < 20 {
return Err(Error::InvalidInput);
}
// unwrap MessageIntegrity attribute,
// an error occurs if not found.
let integrity = match password {
Password::Md5(_) => self.get::<MessageIntegrity>(),
Password::Sha256(_) => self.get::<MessageIntegritySha256>(),
}
.ok_or(Error::NotFoundIntegrity)?;
// create multiple submit.
let size_buf = (self.size + 4).to_be_bytes();
let body = [
&self.bytes[0..2],
&size_buf,
&self.bytes[4..self.size as usize],
];
// digest the message buffer.
{
// Compare local and original attribute.
if integrity != hmac_sha1(password, &body).as_slice() {
return Err(Error::IntegrityFailed);
}
}
Ok(())
}
/// # Test
///
/// ```
/// use std::convert::TryFrom;
/// use turn_server::codec::message::attributes::*;
/// use turn_server::codec::message::methods::*;
/// use turn_server::codec::message::*;
/// use turn_server::codec::*;
///
/// let buffer: [u8; 20] = [
/// 0x00, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49, 0x42,
/// 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let mut attributes = Attributes::default();
/// let message = Message::decode(&buffer[..], &mut attributes).unwrap();
///
/// assert_eq!(
/// message.method(),
/// Method::Binding(MethodType::Request)
/// );
///
/// assert!(message.get::<UserName>().is_none());
/// ```
pub fn decode(bytes: &'a [u8], attributes: &'a mut Attributes) -> Result<Self, Error> {
let len = bytes.len();
// There must be at least a complete header.
if len < 20 {
return Err(Error::InvalidInput);
}
let method = Method::try_from(u16::from_be_bytes(bytes[..2].try_into()?))?;
// First check whether the message length is valid. Here, the length needs
// to add the 20 bytes of the header, because the length field here does
// not include the header length.
{
let size = u16::from_be_bytes(bytes[2..4].try_into()?) as usize + 20;
if len < size {
return Err(Error::InvalidInput);
}
}
// Check whether the magic number is the same.
if bytes[4..8] != MAGIC_NUMBER.to_be_bytes() {
return Err(Error::NotFoundMagicNumber);
}
let mut find_integrity = false;
let mut content_len = 0;
let mut offset = 20;
loop {
// if the buf length is not long enough to continue,
// jump out of the loop.
if len - offset < 4 {
break;
}
// get attribute type
let key = u16::from_be_bytes([bytes[offset], bytes[offset + 1]]);
// whether the MessageIntegrity attribute has been found,
// if found, record the current offset position.
if !find_integrity {
content_len = offset as u16;
}
// get attribute size
let size = u16::from_be_bytes([bytes[offset + 2], bytes[offset + 3]]) as usize;
// check if the attribute length has overflowed.
offset += 4;
if len - offset < size {
break;
}
// body range.
let range = offset..(offset + size);
// if there are padding bytes,
// skip padding size.
if size > 0 {
offset += size + alignment_32(size);
}
// skip the attributes that are not supported.
let attrkind = if let Ok(kind) = AttributeType::try_from(key) {
// check whether the current attribute is MessageIntegrity,
// if it is, mark this attribute has been found.
if kind == AttributeType::MessageIntegrity {
find_integrity = true;
}
kind
} else {
continue;
};
// get attribute body
// insert attribute to attributes list.
attributes.append(attrkind, range);
}
Ok(Self {
size: content_len,
attributes,
method,
bytes,
})
}
/// # Test
///
/// ```
/// use turn_server::codec::message::*;
///
/// let buffer: [u8; 20] = [
/// 0x00, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42, 0x72, 0x6d, 0x49, 0x42,
/// 0x72, 0x52, 0x64, 0x48, 0x57, 0x62, 0x4b, 0x2b,
/// ];
///
/// let size = Message::message_size(&buffer[..]).unwrap();
///
/// assert_eq!(size, 20);
/// ```
pub fn message_size(buffer: &[u8]) -> Result<usize, Error> {
if buffer[0] >> 6 != 0 || buffer.len() < 20 {
return Err(Error::InvalidInput);
}
Ok((u16::from_be_bytes(buffer[2..4].try_into()?) + 20) as usize)
}
}
/// compute padding size.
///
/// RFC5766 stipulates that the attribute content is a multiple of 4.
///
/// # Test
///
/// ```
/// use turn_server::codec::message::alignment_32;
///
/// assert_eq!(alignment_32(4), 0);
/// assert_eq!(alignment_32(0), 0);
/// assert_eq!(alignment_32(5), 3);
/// ```
#[inline(always)]
pub fn alignment_32(size: usize) -> usize {
let range = size % 4;
if size == 0 || range == 0 {
return 0;
}
4 - range
}