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
use std::io::{BufReader, Read, Take, Cursor};
use std::net::TcpStream;
use std::sync::Arc;
use byteorder::{ReadBytesExt, BigEndian};
use {Error, Result, ConnectReturnCode, SubscribeTopic, SubscribeReturnCodes};
use {PacketType, Header, QoS, LastWill, Protocol, PacketIdentifier, MULTIPLIER};

use mqtt::{
    Packet,
    Connect,
    Connack,
    Publish,
    Subscribe,
    Suback,
    Unsubscribe
};

pub trait MqttRead: ReadBytesExt {
    fn read_packet(&mut self) -> Result<Packet> {
        let hd = try!(self.read_u8());
        let len = try!(self.read_remaining_length());
        let header = try!(Header::new(hd, len));
        //println!("Header {:?}", header);
        if len == 0 {
            // no payload packets
            return match header.typ {
                PacketType::Pingreq => Ok(Packet::Pingreq),
                PacketType::Pingresp => Ok(Packet::Pingresp),
                _ => Err(Error::PayloadRequired)
            };
        }
        let mut raw_packet = self.take(len as u64);

        match header.typ {
            PacketType::Connect => Ok(Packet::Connect(try!(raw_packet.read_connect(header)))),
            PacketType::Connack => Ok(Packet::Connack(try!(raw_packet.read_connack(header)))),
            PacketType::Publish => Ok(Packet::Publish(try!(raw_packet.read_publish(header)))),
            PacketType::Puback => {
                if len != 2 {
                    return Err(Error::PayloadSizeIncorrect)
                }
                let pid = try!(raw_packet.read_u16::<BigEndian>());
                Ok(Packet::Puback(PacketIdentifier(pid)))
            },
            PacketType::Pubrec => {
                if len != 2 {
                    return Err(Error::PayloadSizeIncorrect)
                }
                let pid = try!(raw_packet.read_u16::<BigEndian>());
                Ok(Packet::Pubrec(PacketIdentifier(pid)))
            },
            PacketType::Pubrel => {
                if len != 2 {
                    return Err(Error::PayloadSizeIncorrect)
                }
                let pid = try!(raw_packet.read_u16::<BigEndian>());
                Ok(Packet::Pubrel(PacketIdentifier(pid)))
            },
            PacketType::Pubcomp => {
                if len != 2 {
                    return Err(Error::PayloadSizeIncorrect)
                }
                let pid = try!(raw_packet.read_u16::<BigEndian>());
                Ok(Packet::Pubcomp(PacketIdentifier(pid)))
            },
            PacketType::Subscribe => Ok(Packet::Subscribe(try!(raw_packet.read_subscribe(header)))),
            PacketType::Suback => Ok(Packet::Suback(try!(raw_packet.read_suback(header)))),
            PacketType::Unsubscribe => Ok(Packet::Unsubscribe(try!(raw_packet.read_unsubscribe(header)))),
            PacketType::Unsuback => {
                if len != 2 {
                    return Err(Error::PayloadSizeIncorrect)
                }
                let pid = try!(raw_packet.read_u16::<BigEndian>());
                Ok(Packet::Unsuback(PacketIdentifier(pid)))
            },
            PacketType::Pingreq => Err(Error::IncorrectPacketFormat),
            PacketType::Pingresp => Err(Error::IncorrectPacketFormat),
            _ => Err(Error::UnsupportedPacketType)
        }
    }

    fn read_connect(&mut self, _: Header) -> Result<Box<Connect>> {
        let protocol_name = try!(self.read_mqtt_string());
        let protocol_level = try!(self.read_u8());
        let protocol = try!(Protocol::new(protocol_name.as_ref(), protocol_level));

        let connect_flags = try!(self.read_u8());
        let keep_alive = try!(self.read_u16::<BigEndian>());
        let client_id = try!(self.read_mqtt_string());

        let last_will = match connect_flags & 0b100 {
            0 => {
                if (connect_flags & 0b00111000) != 0 {
                    return Err(Error::IncorrectPacketFormat)
                }
                None
            },
            _ => {
                let will_topic = try!(self.read_mqtt_string());
                let will_message = try!(self.read_mqtt_string());
                let will_qod = try!(QoS::from_u8((connect_flags & 0b11000) >> 3));
                Some(LastWill {
                    topic: will_topic,
                    message: will_message,
                    qos: will_qod,
                    retain: (connect_flags & 0b00100000) != 0
                })
            }
        };

        let username = match connect_flags & 0b10000000 {
            0 => None,
            _ => Some(try!(self.read_mqtt_string()))
        };

        let password = match connect_flags & 0b01000000 {
            0 => None,
            _ => Some(try!(self.read_mqtt_string()))
        };

        Ok(Box::new(
            Connect {
                protocol: protocol,
                keep_alive: keep_alive,
                client_id: client_id,
                clean_session: (connect_flags & 0b10) != 0,
                last_will: last_will,
                username: username,
                password: password
            }
        ))
    }

    fn read_connack(&mut self, header: Header) -> Result<Connack> {
        if header.len != 2 {
            return Err(Error::PayloadSizeIncorrect)
        }
        let flags = try!(self.read_u8());
        let return_code = try!(self.read_u8());
        Ok(Connack {
            session_present: (flags & 0x01) == 1,
            code: try!(ConnectReturnCode::from_u8(return_code))
        })
    }

    fn read_publish(&mut self, header: Header) -> Result<Box<Publish>> {
        let topic_name = self.read_mqtt_string();
        // Packet identifier exists where QoS > 0
        let pid = if header.qos().unwrap() != QoS::AtMostOnce {
            Some(PacketIdentifier(try!(self.read_u16::<BigEndian>())))
        } else {
            None
        };
        let mut payload = Vec::new();
        try!(self.read_to_end(&mut payload));

        Ok(Box::new(
            Publish {
                dup: header.dup(),
                qos: try!(header.qos()),
                retain: header.retain(),
                topic_name: try!(topic_name),
                pid: pid,
                payload: Arc::new(payload)
            }
        ))
    }

    fn read_subscribe(&mut self, header: Header) -> Result<Box<Subscribe>> {
        let pid = try!(self.read_u16::<BigEndian>());
        let mut remaining_bytes = header.len - 2;
        let mut topics = Vec::with_capacity(1);

        while remaining_bytes > 0 {
            let topic_filter = try!(self.read_mqtt_string());
            let requested_qod = try!(self.read_u8());
            remaining_bytes -= topic_filter.len() + 3;
            topics.push(SubscribeTopic { topic_path: topic_filter, qos: try!(QoS::from_u8(requested_qod)) });
        };

        Ok(Box::new(Subscribe {
            pid: PacketIdentifier(pid),
            topics: topics
        }))
    }

    fn read_suback(&mut self, header: Header) -> Result<Box<Suback>> {
        let pid = try!(self.read_u16::<BigEndian>());
        let mut remaining_bytes = header.len - 2;
        let mut return_codes = Vec::with_capacity(remaining_bytes);

        while remaining_bytes > 0 {
            let return_code = try!(self.read_u8());
            if return_code >> 7 == 1 {
                return_codes.push(SubscribeReturnCodes::Failure)
            } else {
                return_codes.push(SubscribeReturnCodes::Success(try!(QoS::from_u8(return_code & 0x3))));
            }
            remaining_bytes -= 1
        };

        Ok(Box::new(Suback {
            pid: PacketIdentifier(pid),
            return_codes: return_codes
        }))
    }

    fn read_unsubscribe(&mut self, header: Header) -> Result<Box<Unsubscribe>> {
        let pid = try!(self.read_u16::<BigEndian>());
        let mut remaining_bytes = header.len - 2;
        let mut topics = Vec::with_capacity(1);

        while remaining_bytes > 0 {
            let topic_filter = try!(self.read_mqtt_string());
            remaining_bytes -= topic_filter.len() + 2;
            topics.push(topic_filter);
        };

        Ok(Box::new(Unsubscribe {
            pid: PacketIdentifier(pid),
            topics: topics
        }))
    }

    fn read_payload(&mut self, len: usize) -> Result<Box<Vec<u8>>> {
        let mut payload = Box::new(Vec::with_capacity(len));
        try!(self.take(len as u64).read_to_end(&mut *payload));
        Ok(payload)
    }

    fn read_mqtt_string(&mut self) -> Result<String> {
        let len = try!(self.read_u16::<BigEndian>()) as usize;
        let mut data = Vec::with_capacity(len);
        try!(self.take(len as u64).read_to_end(&mut data));
        Ok(try!(String::from_utf8(data)))
    }

    fn read_remaining_length(&mut self) -> Result<usize> {
        let mut mult: usize = 1;
        let mut len: usize = 0;
        let mut done = false;


        while !done {
            let byte = try!(self.read_u8()) as usize;
            len += (byte & 0x7F) * mult;
            mult *= 0x80;
            if mult > MULTIPLIER {
                return Err(Error::MalformedRemainingLength);
            }
            done = (byte & 0x80) == 0
        }

        Ok(len)
    }
}

impl MqttRead for TcpStream {}
impl MqttRead for Cursor<Vec<u8>> {}
impl<T: Read> MqttRead for Take<T> where T: Read {}
impl<T: Read> MqttRead for BufReader<T> {}

#[cfg(test)]
mod test {
    use std::io::Cursor;
    use std::sync::Arc;
    use super::MqttRead;
    use {Protocol, LastWill, QoS, PacketIdentifier, ConnectReturnCode, SubscribeTopic, SubscribeReturnCodes};
    use mqtt::{
        Packet,
        Connect,
        Connack,
        Publish,
        Subscribe,
        Suback,
        Unsubscribe
    };

    #[test]
    fn read_packet_connect_mqtt_protocol_test() {
        let mut stream = Cursor::new(vec![
            0x10, 39,
            0x00, 0x04, 'M' as u8, 'Q' as u8, 'T' as u8, 'T' as u8,
            0x04,
            0b11001110, // +username, +password, -will retain, will qos=1, +last_will, +clean_session
            0x00, 0x0a, // 10 sec
            0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, // client_id
            0x00, 0x02, '/' as u8, 'a' as u8, // will topic = '/a'
            0x00, 0x07, 'o' as u8, 'f' as u8, 'f' as u8, 'l' as u8, 'i' as u8, 'n' as u8, 'e' as u8, // will msg = 'offline'
            0x00, 0x04, 'r' as u8, 'u' as u8, 's' as u8, 't' as u8, // username = 'rust'
            0x00, 0x02, 'm' as u8, 'q' as u8 // password = 'mq'
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Connect(Box::new(Connect {
            protocol: Protocol::MQTT(4),
            keep_alive: 10,
            client_id: "test".to_owned(),
            clean_session: true,
            last_will: Some(LastWill {
                topic: "/a".to_owned(),
                message: "offline".to_owned(),
                retain: false,
                qos: QoS::AtLeastOnce
            }),
            username: Some("rust".to_owned()),
            password: Some("mq".to_owned())
        })));
    }

    #[test]
    fn read_packet_connect_mqisdp_protocol_test() {
        let mut stream = Cursor::new(vec![
            0x10, 18,
            0x00, 0x06, 'M' as u8, 'Q' as u8, 'I' as u8, 's' as u8, 'd' as u8, 'p' as u8,
            0x03,
            0b00000000, // -username, -password, -will retain, will qos=0, -last_will, -clean_session
            0x00, 0x3c, // 60 sec
            0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8 // client_id
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Connect(Box::new(Connect {
            protocol: Protocol::MQIsdp(3),
            keep_alive: 60,
            client_id: "test".to_owned(),
            clean_session: false,
            last_will: None,
            username: None,
            password: None
        })));
    }

    #[test]
    fn read_packet_connack_test() {
        let mut stream = Cursor::new(vec![0b00100000, 0x02, 0x01, 0x00]);
        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Connack(Connack {
            session_present: true,
            code: ConnectReturnCode::Accepted
        }));
    }

    #[test]
    fn read_packet_publish_qos1_test() {
        let mut stream = Cursor::new(vec![
            0b00110010, 11,
            0x00, 0x03, 'a' as u8, '/' as u8, 'b' as u8, // topic name = 'a/b'
            0x00, 0x0a, // pid = 10
            0xF1, 0xF2, 0xF3, 0xF4
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Publish(Box::new(Publish {
            dup: false,
            qos: QoS::AtLeastOnce,
            retain: false,
            topic_name: "a/b".to_owned(),
            pid: Some(PacketIdentifier(10)),
            payload: Arc::new(vec![0xF1, 0xF2, 0xF3, 0xF4])
        })));
    }

    #[test]
    fn read_packet_publish_qos0_test() {
        let mut stream = Cursor::new(vec![
            0b00110000, 7,
            0x00, 0x03, 'a' as u8, '/' as u8, 'b' as u8, // topic name = 'a/b'
            0x01, 0x02
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Publish(Box::new(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: false,
            topic_name: "a/b".to_owned(),
            pid: None,
            payload: Arc::new(vec![0x01, 0x02])
        })));
    }

    #[test]
    fn read_packet_puback_test() {
        let mut stream = Cursor::new(vec![0b01000000, 0x02, 0x00, 0x0A]);
        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Puback(PacketIdentifier(10)));
    }

    #[test]
    fn read_packet_subscribe_test() {
        let mut stream = Cursor::new(vec![
            0b10000010, 20,
            0x01, 0x04, // pid = 260
            0x00, 0x03, 'a' as u8, '/' as u8, '+' as u8, // topic filter = 'a/+'
            0x00, // qos = 0
            0x00, 0x01, '#' as u8, // topic filter = '#'
            0x01, // qos = 1
            0x00, 0x05, 'a' as u8, '/' as u8, 'b' as u8, '/' as u8, 'c' as u8, // topic filter = 'a/b/c'
            0x02 // qos = 2
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Subscribe(Box::new(Subscribe {
            pid: PacketIdentifier(260),
            topics: vec![
                SubscribeTopic { topic_path: "a/+".to_owned(), qos: QoS::AtMostOnce },
                SubscribeTopic { topic_path: "#".to_owned(), qos: QoS::AtLeastOnce },
                SubscribeTopic { topic_path: "a/b/c".to_owned(), qos: QoS::ExactlyOnce }
            ]
        })));
    }

    #[test]
    fn read_packet_unsubscribe_test() {
        let mut stream = Cursor::new(vec![
            0b10100010, 17,
            0x00, 0x0F, // pid = 15
            0x00, 0x03, 'a' as u8, '/' as u8, '+' as u8, // topic filter = 'a/+'
            0x00, 0x01, '#' as u8, // topic filter = '#'
            0x00, 0x05, 'a' as u8, '/' as u8, 'b' as u8, '/' as u8, 'c' as u8, // topic filter = 'a/b/c'
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Unsubscribe(Box::new(Unsubscribe {
            pid: PacketIdentifier(15),
            topics: vec![
                "a/+".to_owned(),
                "#".to_owned(),
                "a/b/c".to_owned()
            ]
        })));
    }

    #[test]
    fn read_packet_suback_test() {
        let mut stream = Cursor::new(vec![
            0x90, 4,
            0x00, 0x0F, // pid = 15
            0x01, 0x80
        ]);

        let packet = stream.read_packet().unwrap();

        assert_eq!(packet, Packet::Suback(Box::new(Suback {
            pid: PacketIdentifier(15),
            return_codes: vec![SubscribeReturnCodes::Success(QoS::AtLeastOnce), SubscribeReturnCodes::Failure]
        })));
    }
}