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
extern crate byteorder;

#[macro_use]
extern crate failure;
#[macro_use]
extern crate derive_more;

mod error;
mod mqtt;
mod read;
mod write;
mod topic;
mod msg;

pub use error::{
    Error,
    Result
};

pub use msg::{
    Message
};

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

pub use topic::{
    Topic,
    TopicPath,
    ToTopicPath
};

pub use read::MqttRead;
pub use write::MqttWrite;

const MULTIPLIER: usize = 0x80 * 0x80 * 0x80 * 0x80;
const MAX_PAYLOAD_SIZE: usize = 268435455;

use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
    MQIsdp(u8),
    MQTT(u8)
}

impl Protocol {
    pub fn new(name: &str, level: u8) -> Result<Protocol> {
        match name {
            "MQIsdp" => match level {
                3 => Ok(Protocol::MQIsdp(3)),
                _ => Err(Error::UnsupportedProtocolVersion)
            },
            "MQTT" => match level {
                4 => Ok(Protocol::MQTT(4)),
                _ => Err(Error::UnsupportedProtocolVersion)
            },
            _ => Err(Error::UnsupportedProtocolName)
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            &Protocol::MQIsdp(_) => "MQIsdp",
            &Protocol::MQTT(_) => "MQTT"
        }
    }

    pub fn level(&self) -> u8 {
        match self {
            &Protocol::MQIsdp(level) => level,
            &Protocol::MQTT(level) => level
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QoS {
    AtMostOnce,
    AtLeastOnce,
    ExactlyOnce
}

impl QoS {
    pub fn from_u8(byte: u8) -> Result<QoS> {
        match byte {
            0 => Ok(QoS::AtMostOnce),
            1 => Ok(QoS::AtLeastOnce),
            2 => Ok(QoS::ExactlyOnce),
            _ => Err(Error::UnsupportedQualityOfService)
        }
    }

    #[inline]
    pub fn from_hd(hd: u8) -> Result<QoS> {
        Self::from_u8((hd & 0b110) >> 1)
    }

    pub fn to_u8(&self) -> u8 {
        match *self {
            QoS::AtMostOnce => 0,
            QoS::AtLeastOnce => 1,
            QoS::ExactlyOnce => 2
        }
    }

    pub fn min(&self, other: QoS) -> QoS {
        match *self {
            QoS::AtMostOnce => QoS::AtMostOnce,
            QoS::AtLeastOnce => {
                if other == QoS::AtMostOnce {
                    QoS::AtMostOnce
                } else {
                    QoS::AtLeastOnce
                }
            },
            QoS::ExactlyOnce => other
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PacketType {
	Connect,
	Connack,
	Publish,
	Puback,
	Pubrec,
	Pubrel,
	Pubcomp,
	Subscribe,
	Suback,
	Unsubscribe,
	Unsuback,
	Pingreq,
	Pingresp,
	Disconnect
}

impl PacketType {
    pub fn to_u8(&self) -> u8 {
        match *self {
            PacketType::Connect => 1,
            PacketType::Connack => 2,
            PacketType::Publish => 3,
            PacketType::Puback => 4,
            PacketType::Pubrec => 5,
            PacketType::Pubrel => 6,
            PacketType::Pubcomp => 7,
            PacketType::Subscribe => 8,
            PacketType::Suback => 9,
            PacketType::Unsubscribe => 10,
            PacketType::Unsuback => 11,
            PacketType::Pingreq => 12,
            PacketType::Pingresp => 13,
            PacketType::Disconnect => 14
        }
    }

    pub fn from_u8(byte: u8) -> Result<PacketType> {
        match byte {
            1 => Ok(PacketType::Connect),
            2 => Ok(PacketType::Connack),
            3 => Ok(PacketType::Publish),
            4 => Ok(PacketType::Puback),
            5 => Ok(PacketType::Pubrec),
            6 => Ok(PacketType::Pubrel),
            7 => Ok(PacketType::Pubcomp),
            8 => Ok(PacketType::Subscribe),
            9 => Ok(PacketType::Suback),
            10 => Ok(PacketType::Unsubscribe),
            11 => Ok(PacketType::Unsuback),
            12 => Ok(PacketType::Pingreq),
            13 => Ok(PacketType::Pingresp),
            14 => Ok(PacketType::Disconnect),
            _ => Err(Error::UnsupportedPacketType)
        }
    }

    #[inline]
    pub fn from_hd(hd: u8) -> Result<PacketType> {
        Self::from_u8(hd >> 4)
    }
}

impl fmt::Display for PacketType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let str = format!("{:?}", self);
        let first_space = str.find(' ').unwrap_or(str.len());
        let (str, _) = str.split_at(first_space);
        f.write_str(&str)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConnectReturnCode {
    Accepted,
    RefusedProtocolVersion,
    RefusedIdentifierRejected,
    ServerUnavailable,
    BadUsernamePassword,
    NotAuthorized
}

impl ConnectReturnCode {
    pub fn to_u8(&self) -> u8 {
        match *self {
            ConnectReturnCode::Accepted => 0,
            ConnectReturnCode::RefusedProtocolVersion => 1,
            ConnectReturnCode::RefusedIdentifierRejected => 2,
            ConnectReturnCode::ServerUnavailable => 3,
            ConnectReturnCode::BadUsernamePassword => 4,
            ConnectReturnCode::NotAuthorized => 5
        }
    }

    pub fn from_u8(byte: u8) -> Result<ConnectReturnCode> {
        match byte {
            0 => Ok(ConnectReturnCode::Accepted),
            1 => Ok(ConnectReturnCode::RefusedProtocolVersion),
            2 => Ok(ConnectReturnCode::RefusedIdentifierRejected),
            3 => Ok(ConnectReturnCode::ServerUnavailable),
            4 => Ok(ConnectReturnCode::BadUsernamePassword),
            5 => Ok(ConnectReturnCode::NotAuthorized),
            _ => Err(Error::UnsupportedConnectReturnCode)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PacketIdentifier(pub u16);

impl PacketIdentifier {
    pub fn zero() -> PacketIdentifier {
        PacketIdentifier(0)
    }

    pub fn next(&self) -> PacketIdentifier {
        PacketIdentifier(self.0 + 1)
    }
}

impl From<PacketIdentifier> for u16 {
    fn from(pkid : PacketIdentifier) -> Self {
        pkid.0
    }
}


//          7                          3                          0
//          +--------------------------+--------------------------+
// byte 1   | MQTT Control Packet Type | Flags for each type      |
//          +--------------------------+--------------------------+
// byte 2   |                  Remaining Length                   |
//          +-----------------------------------------------------+
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
    hd: u8,
    pub typ: PacketType,
    pub len: usize
}

impl Header {
    pub fn new(hd: u8, len: usize) -> Result<Header> {
        Ok(Header {
            hd: hd,
            typ: PacketType::from_hd(hd)?,
            len
        })
    }

    #[inline]
    pub fn dup(&self) -> bool {
        (self.hd & 0b1000) != 0
    }

    #[inline]
    pub fn qos(&self) -> Result<QoS> {
        QoS::from_hd(self.hd)
    }

    #[inline]
    pub fn retain(&self) -> bool {
        (self.hd & 1) != 0
    }

    /// NOTE: Length of remaining_len field can vary from 1 - 4 bytes.
    ///       This can be calculated using the value of remaining_len.
    ///       This function give full length of the header (including control + flags byte)
    #[inline]
    pub fn len(&self) -> usize {
        let remaining_len = self.len;
        if remaining_len >= 2_097_152 {
            4 + 1
        } else if remaining_len >= 16_384 {
            3 + 1
        } else if remaining_len >= 128 {
            2 + 1
        } else {
            1 + 1
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct LastWill {
    pub topic: String,
    pub message: String,
    pub qos: QoS,
    pub retain: bool
}

#[cfg(test)]
mod test {
    use super::{QoS, Protocol, PacketIdentifier};

    #[test]
    fn protocol_test() {
        assert_eq!(Protocol::new("MQTT", 4).unwrap(), Protocol::MQTT(4));
        assert_eq!(Protocol::new("MQIsdp", 3).unwrap(), Protocol::MQIsdp(3));
        assert_eq!(Protocol::MQIsdp(3).name(), "MQIsdp");
        assert_eq!(Protocol::MQTT(4).name(), "MQTT");
        assert_eq!(Protocol::MQTT(3).level(), 3);
        assert_eq!(Protocol::MQTT(4).level(), 4);
    }

    #[test]
    fn qos_min_test() {
        assert_eq!(QoS::AtMostOnce.min(QoS::AtMostOnce), QoS::AtMostOnce);
        assert_eq!(QoS::AtMostOnce.min(QoS::AtLeastOnce), QoS::AtMostOnce);
        assert_eq!(QoS::AtLeastOnce.min(QoS::AtMostOnce), QoS::AtMostOnce);
        assert_eq!(QoS::AtLeastOnce.min(QoS::ExactlyOnce), QoS::AtLeastOnce);
        assert_eq!(QoS::ExactlyOnce.min(QoS::AtMostOnce), QoS::AtMostOnce);
        assert_eq!(QoS::ExactlyOnce.min(QoS::ExactlyOnce), QoS::ExactlyOnce);
    }

    #[test]
    fn packet_identifier_test() {
        let pkid = PacketIdentifier::zero();
        assert_eq!(pkid, PacketIdentifier(0));
        assert_eq!(pkid.next(), PacketIdentifier(1));
    }
}