gmqtt 0.1.1

A no_std, no_alloc MQTTv5 packet parsing library for embedded devices
Documentation
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
use core::convert::TryFrom;
use heapless::Vec;
use num_enum::TryFromPrimitive;

use crate::{utils::*, MqttError};

use super::{PacketType, PropertyType};

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Disconnect<'a> {
    pub reason: DisconnectReason,
    pub properties: Option<DisconnectProperties<'a>>,
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901208)
#[derive(Debug, Clone, PartialEq, Copy, TryFromPrimitive)]
#[repr(u8)]
pub enum DisconnectReason {
    /// Close the connection normally. Do not send the Will Message.
    NormalDisconnection = 0x00,

    /// The Client wishes to disconnect but requires that the Server also publishes its Will Message.
    DisconnectWithWillMessage = 0x04,

    /// The Connection is closed but the sender either does not wish to reveal the reason, or none of the other Reason Codes apply.
    UnspecifiedError = 0x80,

    /// The received packet does not conform to this specification.
    MalformedPacket = 0x81,

    /// An unexpected or out of order packet was received.
    ProtocolError = 0x82,

    /// The packet received is valid but cannot be processed by this implementation.
    ImplementationSpecificError = 0x83,

    /// The request is not authorized.
    NotAuthorized = 0x87,

    /// The Server is busy and cannot continue processing requests from this Client.
    ServerBusy = 0x89,

    /// The Server is shutting down.
    ServerShuttingDown = 0x8B,

    /// The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
    KeepAliveTimeout = 0x8D,

    /// Another Connection using the same ClientID has connected causing this Connection to be closed.
    SessionTakenOver = 0x8E,

    /// The Topic Filter is correctly formed, but is not accepted by this Sever.
    TopicFilterInvalid = 0x8F,

    /// The Topic Name is correctly formed, but is not accepted by this Client or Server.
    TopicNameInvalid = 0x90,

    /// The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
    ReceiveMaximumExceeded = 0x93,

    /// The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
    TopicAliasInvalid = 0x94,

    /// The packet size is greater than Maximum Packet Size for this Client or Server.
    PacketTooLarge = 0x95,

    /// The received data rate is too high.
    MessageRateTooHigh = 0x96,

    /// An implementation or administrative imposed limit has been exceeded.
    QuotaExceeded = 0x97,

    /// The Connection is closed due to an administrative action.
    AdministrativeAction = 0x98,

    /// The payload format does not match the one specified by the Payload Format Indicator.
    PayloadFormatInvalid = 0x99,

    /// The Server has does not support retained messages.
    RetainNotSupported = 0x9A,

    /// The Client specified a QoS greater than the QoS specified in a Maximum QoS in the CONNACK.
    QoSNotSupported = 0x9B,

    /// The Client should temporarily change its Server.
    UseAnotherServer = 0x9C,

    /// The Server is moved and the Client should permanently change its server location.
    ServerMoved = 0x9D,

    /// The Server does not support Shared Subscriptions.
    SharedSubscriptionsNotSupported = 0x9E,

    /// This connection is closed because the connection rate is too high.
    ConnectionRateExceeded = 0x9F,

    /// The maximum connection time authorized for this connection has been exceeded.
    MaximumConnectTime = 0xA0,

    /// The Server does not support Subscription Identifiers; the subscription is not accepted.
    SubscriptionIdentifiersNotSupported = 0xA1,

    /// The Server does not support Wildcard Subscriptions; the subscription is not accepted.
    WildcardSubscriptionsNotSupported = 0xA2,
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901209)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DisconnectProperties<'a> {
    /// 17 (0x11) Byte, Identifier of the Session Expiry Interval.
    ///
    /// Followed by the Four Byte Integer representing the Session Expiry Interval in seconds. It is a Protocol Error to include the Session Expiry Interval more than once.
    pub session_expiry_interval: Option<u32>,

    /// 31 (0x1F) Byte, Identifier of the Reason String.
    ///
    /// Followed by the UTF-8 Encoded String representing the reason for the disconnect. This Reason String is human readable, designed for diagnostics and SHOULD NOT be parsed by the receiver.
    pub reason_string: Option<&'a str>,

    /// `38 (0x26)` Byte, Identifier of the User Property.
    ///
    /// Followed by a UTF-8 String Pair. This property may be used to provide additional diagnostic or other information.
    /// The User Property is allowed to appear multiple times to represent multiple name, value pairs.
    /// The same name is allowed to appear more than once.
    pub user_properties: Vec<(&'a str, &'a str), 8>,

    /// 28 (0x1C) Byte, Identifier of the Server Reference.
    ///
    /// Followed by a UTF-8 Encoded String which can be used by the Client to identify another Server to use. It is a Protocol Error to include the Server Reference more than once.
    pub server_reference: Option<&'a str>,
}

impl<'a> Disconnect<'a> {
    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<usize, MqttError> {
        check_remaining(buf, offset, 2)?;

        let header: u8 = 0xE0;
        let length: u8;
        write_u8(buf, offset, header);

        if self.reason == DisconnectReason::NormalDisconnection && self.properties.is_none() {
            length = 0x00;
            write_u8(buf, offset, length);
        } else if let Some(ref properties) = self.properties {
            length = 0x02 + properties.len() as u8;
            write_u8(buf, offset, length);
            write_u8(buf, offset, self.reason as u8);
            properties.write(buf, offset)?;
        } else {
            length = 0x01;
            write_u8(buf, offset, length);
            write_u8(buf, offset, self.reason as u8);
        }

        Ok(2 + length as usize)
    }

    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Self, MqttError> {
        let packet_identifier = buf[*offset];

        if packet_identifier & 0x0F != 0x00 {
            return Err(MqttError::MalformedPacket);
        }

        if packet_identifier >> 4 != PacketType::Disconnect as u8 {
            return Err(MqttError::InvalidHeader);
        }

        *offset += 1;

        let remaining_len = buf[*offset];

        let packet = match remaining_len {
            0 => Self {
                reason: DisconnectReason::NormalDisconnection,
                properties: None,
            },
            1 => {
                *offset += 1;
                let rc = buf[*offset];

                let reason = DisconnectReason::try_from(rc)
                    .map_err(|_| MqttError::InvalidDisconnectReason(rc))?;

                Self {
                    reason,
                    properties: None,
                }
            }
            _ => {
                *offset += 1;
                let rc = buf[*offset];

                let reason = DisconnectReason::try_from(rc)
                    .map_err(|_| MqttError::InvalidDisconnectReason(rc))?;

                *offset += 1;

                let properties = DisconnectProperties::read(buf, offset)?;

                Self { reason, properties }
            }
        };

        Ok(packet)
    }
}

impl Default for DisconnectReason {
    fn default() -> Self {
        Self::NormalDisconnection
    }
}

impl DisconnectReason {
    pub fn reason_str(&self) -> &'static str {
        match *self {
            DisconnectReason::NormalDisconnection => "Normal Disconnection",
            DisconnectReason::DisconnectWithWillMessage => "Disconnect With Will Message",
            DisconnectReason::UnspecifiedError => "Unspecified Error",
            DisconnectReason::MalformedPacket => "Malformed Packet",
            DisconnectReason::ProtocolError => "Protocol Error",
            DisconnectReason::ImplementationSpecificError => "Implementation Specific Error",
            DisconnectReason::NotAuthorized => "Not Authorized",
            DisconnectReason::ServerBusy => "Server Busy",
            DisconnectReason::ServerShuttingDown => "Server Shutting Down",
            DisconnectReason::KeepAliveTimeout => "Keep Alive Timeout",
            DisconnectReason::SessionTakenOver => "Session Taken Over",
            DisconnectReason::TopicFilterInvalid => "Topic Filter Invalid",
            DisconnectReason::TopicNameInvalid => "Topic Name Invalid",
            DisconnectReason::ReceiveMaximumExceeded => "Receive Maximum Exceeded",
            DisconnectReason::TopicAliasInvalid => "Topic Alias Invalid",
            DisconnectReason::PacketTooLarge => "Packet Too Large",
            DisconnectReason::MessageRateTooHigh => "Message Rate Too High",
            DisconnectReason::QuotaExceeded => "Quota Exceeded",
            DisconnectReason::AdministrativeAction => "Administrative Action",
            DisconnectReason::PayloadFormatInvalid => "Payload Format Invalid",
            DisconnectReason::RetainNotSupported => "Retain Not Supported",
            DisconnectReason::QoSNotSupported => "QoS Not Supported",
            DisconnectReason::UseAnotherServer => "Use Another Server",
            DisconnectReason::ServerMoved => "Server Moved",
            DisconnectReason::SharedSubscriptionsNotSupported => {
                "Shared Subscriptions Not Supported"
            }
            DisconnectReason::ConnectionRateExceeded => "Connection Rate Exceeded",
            DisconnectReason::MaximumConnectTime => "Maximum Connect Time",
            DisconnectReason::SubscriptionIdentifiersNotSupported => {
                "Subscription Identifiers Not Supported"
            }
            DisconnectReason::WildcardSubscriptionsNotSupported => {
                "Wildcard Subscriptions Not Supported"
            }
        }
    }
}

impl<'a> DisconnectProperties<'a> {
    fn len(&self) -> usize {
        let mut len = 0;

        if self.session_expiry_interval.is_some() {
            len += 1 + 4;
        }

        if let Some(reason) = &self.reason_string {
            len += 1 + 2 + reason.len();
        }

        for (key, value) in self.user_properties.iter() {
            len += 1 + 2 + key.len() + 2 + value.len();
        }

        if let Some(reference) = &self.server_reference {
            len += 1 + 2 + reference.len();
        }

        len
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        write_length(buf, offset, self.len())?;

        if let Some(session_expiry_interval) = self.session_expiry_interval {
            write_u8(buf, offset, PropertyType::SessionExpiryInterval as u8);
            write_bytes(buf, offset, &session_expiry_interval.to_be_bytes());
        }

        if let Some(reason_string) = self.reason_string {
            write_u8(buf, offset, PropertyType::ReasonString as u8);
            write_bytes_with_len(buf, offset, reason_string.as_bytes());
        }

        for (key, value) in self.user_properties.iter() {
            write_u8(buf, offset, PropertyType::UserProperty as u8);
            write_bytes_with_len(buf, offset, key.as_bytes());
            write_bytes_with_len(buf, offset, value.as_bytes());
        }

        if let Some(server_reference) = self.server_reference {
            write_u8(buf, offset, PropertyType::ServerReference as u8);
            write_bytes_with_len(buf, offset, server_reference.as_bytes());
        }

        Ok(())
    }

    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
        let mut properties = Self::default();

        let properties_len = buf[*offset];

        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor: usize = 1;

        while cursor < properties_len.into() {
            let mut prop_offset = *offset + cursor;
            let property_code = buf[prop_offset];

            prop_offset += 1;
            cursor += 1;

            match super::property(property_code)? {
                PropertyType::SessionExpiryInterval => {
                    properties.session_expiry_interval = Some(read_u32(buf, *offset + cursor));
                    cursor += 4;
                }

                PropertyType::ReasonString => {
                    let reason_string = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + reason_string.len();
                    properties.reason_string = Some(reason_string);
                }

                PropertyType::UserProperty => {
                    let key = read_str(buf, &mut prop_offset)?;
                    let value = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    properties
                        .user_properties
                        .push((key, value))
                        .map_err(|_| MqttError::TooManyUserProperties)?;
                }

                PropertyType::ServerReference => {
                    let server_reference = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + server_reference.len();
                    properties.server_reference = Some(server_reference);
                }

                other => return Err(MqttError::InvalidPropertyType(other)),
            }
        }

        *offset += properties.len();

        Ok(Some(properties))
    }
}

#[cfg(test)]
mod tests {
    use super::{Disconnect, DisconnectProperties, DisconnectReason};

    #[test]
    fn encode_disconnect() {
        let mut buf = [0u8; 2];
        let expected = [0xE0, 0x00];
        let disconnect = Disconnect::default();

        disconnect.write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected, buf);
    }

    #[test]
    fn encode_disconnect_with_reason() {
        let mut buf = [0u8; 3];
        let expected = [0xe0, 0x01, DisconnectReason::UnspecifiedError as u8];
        let disconnect = Disconnect {
            reason: DisconnectReason::UnspecifiedError,
            properties: None,
        };

        disconnect.write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected, buf);
    }

    #[test]
    fn encode_disconnect_with_properties() {
        let mut buf = [0u8; 64];
        let mut offset = 0;
        let expected = [
            0xe0,                                     // header type
            0x09,                                     // remaining length
            DisconnectReason::UnspecifiedError as u8, // reason code
            0x07,                                     // properties len
            // Reason string
            0x1f,
            0x00,
            0x04,
            b't',
            b'e',
            b's',
            b't',
        ];

        let properties = DisconnectProperties {
            reason_string: Some("test"),
            ..DisconnectProperties::default()
        };

        let disconnect = Disconnect {
            reason: DisconnectReason::UnspecifiedError,
            properties: Some(properties),
        };

        disconnect.write(&mut buf, &mut offset).unwrap();

        assert_eq!(&expected, &buf[..offset]);
    }

    #[test]
    fn decode_disconnect() {
        let bytes = [0xe0, 0x01, 0x81];
        let mut offset = 0;
        let expected = Disconnect {
            reason: DisconnectReason::MalformedPacket,
            properties: None,
        };

        let disconnect = Disconnect::read(&bytes, &mut offset).unwrap();

        assert_eq!(expected, disconnect)
    }

    #[test]
    fn decode_disconnect_with_properties() {
        let bytes = [
            0xe0,                                     // header type
            0x09,                                     // remaining length
            DisconnectReason::UnspecifiedError as u8, // reason code
            0x07,                                     // properties len
            // Reason string
            0x1f,
            0x00,
            0x04,
            b't',
            b'e',
            b's',
            b't',
        ];

        let mut offset = 0;

        let properties = DisconnectProperties {
            reason_string: Some("test"),
            ..DisconnectProperties::default()
        };

        let expected = Disconnect {
            reason: DisconnectReason::UnspecifiedError,
            properties: Some(properties),
        };

        let disconnect = Disconnect::read(&bytes, &mut offset).unwrap();

        assert_eq!(expected, disconnect)
    }
}