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
use bincode;
use std::collections::BTreeMap;
use std::collections::LinkedList;

use num::FromPrimitive;

use message::header;

macro_rules! u8_to_unsigned_be {
    ($src:ident, $start:expr, $end:expr, $t:ty) => ({
        (0 .. $end - $start + 1).rev().fold(0, |acc, i| acc | $src[$start+i] as $t << i * 8)
    })
}

#[derive(PartialEq, Eq, Debug)]
pub enum CoAPOption {
    IfMatch,
    UriHost,
    ETag,
    IfNoneMatch,
    Observe,
    UriPort,
    LocationPath,
    UriPath,
    ContentFormat,
    MaxAge,
    UriQuery,
    Accept,
    LocationQuery,
    Block2,
    Block1,
    ProxyUri,
    ProxyScheme,
    Size1,
}

enum_from_primitive! {
#[derive(PartialEq, Eq, Debug)]
pub enum ContentFormat {
    TextPlain = 0,
    ApplicationLinkFormat = 40,
    ApplicationXML = 41,
    ApplicationOctetStream = 42,
    ApplicationEXI = 47,
    ApplicationJSON = 50,
}
}

enum_from_primitive! {
#[derive(PartialEq, Eq, Debug)]
pub enum ObserveOption {
    Register = 0,
    Deregister = 1,
}
}

#[derive(Debug)]
pub enum PackageError {
    InvalidHeader,
    InvalidPacketLength,
}

#[derive(Debug)]
pub enum ParseError {
    InvalidHeader,
    InvalidTokenLength,
    InvalidOptionDelta,
    InvalidOptionLength,
}

#[derive(Clone, Debug)]
pub struct Packet {
    pub header: header::Header,
    token: Vec<u8>,
    options: BTreeMap<usize, LinkedList<Vec<u8>>>,
    pub payload: Vec<u8>,
}

impl Packet {
    pub fn new() -> Packet {
        Packet {
            header: header::Header::new(),
            token: Vec::new(),
            options: BTreeMap::new(),
            payload: Vec::new(),
        }
    }

    pub fn set_token(&mut self, token: Vec<u8>) {
        self.header.set_token_length(token.len() as u8);
        self.token = token;
    }

    pub fn get_token(&self) -> &Vec<u8> {
        return &self.token;
    }

    pub fn set_option(&mut self, tp: CoAPOption, value: LinkedList<Vec<u8>>) {
        let num = Self::get_option_number(tp);
        self.options.insert(num, value);
    }

    pub fn set_content_format(&mut self, cf: ContentFormat) {
        let content_format = cf as u16;
        let msb = (content_format >> 8) as u8;
        let lsb = (content_format & 0xFF) as u8;

        let content_format: Vec<u8> = vec![msb, lsb];
        self.add_option(CoAPOption::ContentFormat, content_format);
    }

    pub fn set_payload(&mut self, payload: Vec<u8>) {
        self.payload = payload;
    }

    pub fn add_option(&mut self, tp: CoAPOption, value: Vec<u8>) {
        let num = Self::get_option_number(tp);
        match self.options.get_mut(&num) {
            Some(list) => {
                list.push_back(value);
                return;
            }
            None => (),
        };

        let mut list = LinkedList::new();
        list.push_back(value);
        self.options.insert(num, list);
    }

    pub fn get_option(&self, tp: CoAPOption) -> Option<&LinkedList<Vec<u8>>> {
        let num = Self::get_option_number(tp);
        self.options.get(&num)
    }

    pub fn clear_option(&mut self, tp: CoAPOption) {
        let num = Self::get_option_number(tp);
        if let Some(list) = self.options.get_mut(&num) {
            list.clear()
        }
    }

    pub fn get_content_format(&self) -> Option<ContentFormat> {
        if let Some(list) = self.get_option(CoAPOption::ContentFormat) {
            if let Some(vector) = list.front() {
                let msb = vector[0] as u16;
                let lsb = vector[1] as u16;
                let number = (msb << 8) + lsb;

                return ContentFormat::from_u16(number);
            }
        }

        None
    }

    pub fn set_observe(&mut self, value: Vec<u8>) {
        self.clear_option(CoAPOption::Observe);
        self.add_option(CoAPOption::Observe, value);
    }

    pub fn get_observe(&self) -> Option<&Vec<u8>> {
        if let Some(list) = self.get_option(CoAPOption::Observe) {
            if let Some(flag) = list.front() {
                return Some(flag);
            }
        }

        None
    }

    /// Decodes a byte slice and construct the equivalent Packet.
    pub fn from_bytes(buf: &[u8]) -> Result<Packet, ParseError> {
        let header_result: bincode::DecodingResult<header::HeaderRaw> = bincode::decode(buf);
        match header_result {
            Ok(raw_header) => {
                let header = header::Header::from_raw(&raw_header);
                let token_length = header.get_token_length();
                let options_start: usize = 4 + token_length as usize;

                if token_length > 8 {
                    return Err(ParseError::InvalidTokenLength);
                }

                if options_start > buf.len() {
                    return Err(ParseError::InvalidTokenLength);
                }

                let token = buf[4..options_start].to_vec();

                let mut idx = options_start;
                let mut options_number = 0;
                let mut options: BTreeMap<usize, LinkedList<Vec<u8>>> = BTreeMap::new();
                while idx < buf.len() {
                    let byte = buf[idx];

                    if byte == 255 || idx > buf.len() {
                        break;
                    }

                    let mut delta = (byte >> 4) as usize;
                    let mut length = (byte & 0xF) as usize;

                    idx += 1;

                    // Check for special delta characters
                    match delta {
                        13 => {
                            if idx >= buf.len() {
                                return Err(ParseError::InvalidOptionLength);
                            }
                            delta = buf[idx] as usize + 13;
                            idx += 1;
                        }
                        14 => {
                            if idx + 1 >= buf.len() {
                                return Err(ParseError::InvalidOptionLength);
                            }

                            delta = (u16::from_be(u8_to_unsigned_be!(buf, idx, idx + 1, u16)) +
                                     269) as usize;
                            idx += 2;
                        }
                        15 => {
                            return Err(ParseError::InvalidOptionDelta);
                        }
                        _ => {}
                    };

                    // Check for special length characters
                    match length {
                        13 => {
                            if idx >= buf.len() {
                                return Err(ParseError::InvalidOptionLength);
                            }

                            length = buf[idx] as usize + 13;
                            idx += 1;
                        }
                        14 => {
                            if idx + 1 >= buf.len() {
                                return Err(ParseError::InvalidOptionLength);
                            }

                            length = (u16::from_be(u8_to_unsigned_be!(buf, idx, idx + 1, u16)) +
                                      269) as usize;
                            idx += 2;
                        }
                        15 => {
                            return Err(ParseError::InvalidOptionLength);
                        }
                        _ => {}
                    };

                    options_number += delta;

                    let end = idx + length;
                    if end > buf.len() {
                        return Err(ParseError::InvalidOptionLength);
                    }
                    let options_value = buf[idx..end].to_vec();

                    if options.contains_key(&options_number) {
                        let mut options_list = options.get_mut(&options_number).unwrap();
                        options_list.push_back(options_value);
                    } else {
                        let mut list = LinkedList::new();
                        list.push_back(options_value);
                        options.insert(options_number, list);
                    }

                    idx += length;
                }

                let mut payload = Vec::new();
                if idx < buf.len() {
                    payload = buf[(idx + 1)..buf.len()].to_vec();
                }


                Ok(Packet {
                    header: header,
                    token: token,
                    options: options,
                    payload: payload,
                })
            }
            Err(_) => Err(ParseError::InvalidHeader),
        }
    }

    /// Returns a vector of bytes representing the Packet.
    pub fn to_bytes(&self) -> Result<Vec<u8>, PackageError> {
        let mut options_delta_length = 0;
        let mut options_bytes: Vec<u8> = Vec::new();
        for (number, value_list) in self.options.iter() {
            for value in value_list.iter() {
                let mut header: Vec<u8> = Vec::with_capacity(1 + 2 + 2);
                let delta = number - options_delta_length;

                let mut byte: u8 = 0;
                if delta <= 12 {
                    byte |= (delta << 4) as u8;
                } else if delta < 269 {
                    byte |= 13 << 4;
                } else {
                    byte |= 14 << 4;
                }
                if value.len() <= 12 {
                    byte |= value.len() as u8;
                } else if value.len() < 269 {
                    byte |= 13;
                } else {
                    byte |= 14;
                }
                header.push(byte);

                if delta > 12 && delta < 269 {
                    header.push((delta - 13) as u8);
                } else if delta >= 269 {
                    let fix = (delta - 269) as u16;
                    header.push((fix >> 8) as u8);
                    header.push((fix & 0xFF) as u8);
                }

                if value.len() > 12 && value.len() < 269 {
                    header.push((value.len() - 13) as u8);
                } else if value.len() >= 269 {
                    let fix = (value.len() - 269) as u16;
                    header.push((fix >> 8) as u8);
                    header.push((fix & 0xFF) as u8);
                }

                options_delta_length += delta;

                options_bytes.reserve(header.len() + value.len());
                unsafe {
                    use std::ptr;
                    let buf_len = options_bytes.len();
                    ptr::copy(header.as_ptr(),
                              options_bytes.as_mut_ptr().offset(buf_len as isize),
                              header.len());
                    ptr::copy(value.as_ptr(),
                              options_bytes.as_mut_ptr().offset((buf_len + header.len()) as isize),
                              value.len());
                    options_bytes.set_len(buf_len + header.len() + value.len());
                }
            }
        }

        let mut buf_length = 4 + self.payload.len() + self.token.len();
        if self.header.code != header::MessageClass::Empty && self.payload.len() != 0 {
            buf_length += 1;
        }
        buf_length += options_bytes.len();

        if buf_length > 1280 {
            return Err(PackageError::InvalidPacketLength);
        }

        let mut buf: Vec<u8> = Vec::with_capacity(buf_length);
        let header_result: bincode::EncodingResult<()> =
            bincode::encode_into(&self.header.to_raw(),
                                 &mut buf,
                                 bincode::SizeLimit::Infinite);
        match header_result {
            Ok(_) => {
                buf.reserve(self.token.len() + options_bytes.len());
                unsafe {
                    use std::ptr;
                    let buf_len = buf.len();
                    ptr::copy(self.token.as_ptr(),
                              buf.as_mut_ptr().offset(buf_len as isize),
                              self.token.len());
                    ptr::copy(options_bytes.as_ptr(),
                              buf.as_mut_ptr().offset((buf_len + self.token.len()) as isize),
                              options_bytes.len());
                    buf.set_len(buf_len + self.token.len() + options_bytes.len());
                }

                if self.header.code != header::MessageClass::Empty && self.payload.len() != 0 {
                    buf.push(0xFF);
                    buf.reserve(self.payload.len());
                    unsafe {
                        use std::ptr;
                        let buf_len = buf.len();
                        ptr::copy(self.payload.as_ptr(),
                                  buf.as_mut_ptr().offset(buf.len() as isize),
                                  self.payload.len());
                        buf.set_len(buf_len + self.payload.len());
                    }
                }
                Ok(buf)
            }
            Err(_) => Err(PackageError::InvalidHeader),
        }
    }

    fn get_option_number(tp: CoAPOption) -> usize {
        match tp {
            CoAPOption::IfMatch => 1,
            CoAPOption::UriHost => 3,
            CoAPOption::ETag => 4,
            CoAPOption::IfNoneMatch => 5,
            CoAPOption::Observe => 6,
            CoAPOption::UriPort => 7,
            CoAPOption::LocationPath => 8,
            CoAPOption::UriPath => 11,
            CoAPOption::ContentFormat => 12,
            CoAPOption::MaxAge => 14,
            CoAPOption::UriQuery => 15,
            CoAPOption::Accept => 17,
            CoAPOption::LocationQuery => 20,
            CoAPOption::Block2 => 23,
            CoAPOption::Block1 => 27,
            CoAPOption::ProxyUri => 35,
            CoAPOption::ProxyScheme => 39,
            CoAPOption::Size1 => 60,
        }
    }
}

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

    #[test]
    fn test_decode_packet_with_options() {
        let buf = [0x44, 0x01, 0x84, 0x9e, 0x51, 0x55, 0x77, 0xe8, 0xb2, 0x48, 0x69, 0x04, 0x54,
                   0x65, 0x73, 0x74, 0x43, 0x61, 0x3d, 0x31];
        let packet = Packet::from_bytes(&buf);
        assert!(packet.is_ok());
        let packet = packet.unwrap();
        assert_eq!(packet.header.get_version(), 1);
        assert_eq!(packet.header.get_type(), header::MessageType::Confirmable);
        assert_eq!(packet.header.get_token_length(), 4);
        assert_eq!(packet.header.code,
                   header::MessageClass::Request(header::RequestType::Get));
        assert_eq!(packet.header.get_message_id(), 33950);
        assert_eq!(*packet.get_token(), vec![0x51, 0x55, 0x77, 0xE8]);
        assert_eq!(packet.options.len(), 2);

        let uri_path = packet.get_option(CoAPOption::UriPath);
        assert!(uri_path.is_some());
        let uri_path = uri_path.unwrap();
        let mut expected_uri_path = LinkedList::new();
        expected_uri_path.push_back("Hi".as_bytes().to_vec());
        expected_uri_path.push_back("Test".as_bytes().to_vec());
        assert_eq!(*uri_path, expected_uri_path);

        let uri_query = packet.get_option(CoAPOption::UriQuery);
        assert!(uri_query.is_some());
        let uri_query = uri_query.unwrap();
        let mut expected_uri_query = LinkedList::new();
        expected_uri_query.push_back("a=1".as_bytes().to_vec());
        assert_eq!(*uri_query, expected_uri_query);
    }

    #[test]
    fn test_decode_packet_with_payload() {
        let buf = [0x64, 0x45, 0x13, 0xFD, 0xD0, 0xE2, 0x4D, 0xAC, 0xFF, 0x48, 0x65, 0x6C, 0x6C,
                   0x6F];
        let packet = Packet::from_bytes(&buf);
        assert!(packet.is_ok());
        let packet = packet.unwrap();
        assert_eq!(packet.header.get_version(), 1);
        assert_eq!(packet.header.get_type(),
                   header::MessageType::Acknowledgement);
        assert_eq!(packet.header.get_token_length(), 4);
        assert_eq!(packet.header.code,
                   header::MessageClass::Response(header::ResponseType::Content));
        assert_eq!(packet.header.get_message_id(), 5117);
        assert_eq!(*packet.get_token(), vec![0xD0, 0xE2, 0x4D, 0xAC]);
        assert_eq!(packet.payload, "Hello".as_bytes().to_vec());
    }

    #[test]
    fn test_encode_packet_with_options() {
        let mut packet = Packet::new();
        packet.header.set_version(1);
        packet.header.set_type(header::MessageType::Confirmable);
        packet.header.code = header::MessageClass::Request(header::RequestType::Get);
        packet.header.set_message_id(33950);
        packet.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
        packet.add_option(CoAPOption::UriPath, b"Hi".to_vec());
        packet.add_option(CoAPOption::UriPath, b"Test".to_vec());
        packet.add_option(CoAPOption::UriQuery, b"a=1".to_vec());
        assert_eq!(packet.to_bytes().unwrap(),
                   vec![0x44, 0x01, 0x84, 0x9e, 0x51, 0x55, 0x77, 0xe8, 0xb2, 0x48, 0x69, 0x04,
                        0x54, 0x65, 0x73, 0x74, 0x43, 0x61, 0x3d, 0x31]);
    }

    #[test]
    fn test_encode_packet_with_payload() {
        let mut packet = Packet::new();
        packet.header.set_version(1);
        packet.header.set_type(header::MessageType::Acknowledgement);
        packet.header.code = header::MessageClass::Response(header::ResponseType::Content);
        packet.header.set_message_id(5117);
        packet.set_token(vec![0xD0, 0xE2, 0x4D, 0xAC]);
        packet.payload = "Hello".as_bytes().to_vec();
        assert_eq!(packet.to_bytes().unwrap(),
                   vec![0x64, 0x45, 0x13, 0xFD, 0xD0, 0xE2, 0x4D, 0xAC, 0xFF, 0x48, 0x65, 0x6C,
                        0x6C, 0x6F]);
    }

    #[test]
    fn test_encode_decode_content_format() {
        let mut packet = Packet::new();
        packet.set_content_format(ContentFormat::ApplicationJSON);
        assert_eq!(ContentFormat::ApplicationJSON, packet.get_content_format().unwrap())
    }

    #[test]
    fn test_decode_empty_content_format() {
        let packet = Packet::new();
        assert!(packet.get_content_format().is_none());
    }

    #[test]
    fn test_malicious_packet() {
        use rand;
        use quickcheck::{QuickCheck, StdGen, TestResult};

        fn run(x: Vec<u8>) -> TestResult {
            match Packet::from_bytes(&x[..]) {
                Ok(packet) => {
                    TestResult::from_bool(packet.get_token().len() ==
                                          packet.header.get_token_length() as usize)
                }
                Err(_) => TestResult::passed(),
            }
        }
        QuickCheck::new()
            .tests(10000)
            .gen(StdGen::new(rand::thread_rng(), 1500))
            .quickcheck(run as fn(Vec<u8>) -> TestResult)
    }
}