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
use super::*;
use crate::protocol::packet::{
    read_mqtt_string, read_u16, write_mqtt_string, write_remaining_length,
};
use crate::protocol::{len_len, property, FixedHeader, PropertyType};
use crate::{qos, QoS, QoSWithPacketId};
use bytes::{Buf, Bytes};
use std::fmt;
use std::sync::Arc;

/// Publish packet
#[derive(Clone, PartialEq, Eq)]
pub struct Publish {
    pub protocol: Protocol,
    pub dup: bool,
    pub qos: QoSWithPacketId,
    pub retain: bool,
    pub topic: Arc<String>,
    pub payload: Arc<Bytes>,
    pub properties: Option<PublishProperties>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishProperties {
    pub payload_format_indicator: Option<u8>,
    pub message_expiry_interval: Option<u32>,
    pub topic_alias: Option<u16>,
    pub response_topic: Option<String>,
    pub correlation_data: Option<Bytes>,
    pub user_properties: Vec<(String, String)>,
    pub subscription_identifiers: Vec<usize>,
    pub content_type: Option<String>,
}

impl Publish {
    pub fn new<S: Into<Arc<String>>, P: Into<Arc<Bytes>>>(
        topic: S,
        qos: QoSWithPacketId,
        payload: P,
        retain: bool,
        protocol: Protocol,
    ) -> Publish {
        let payload = payload.into();
        let topic = topic.into();

        Publish {
            dup: false,
            qos,
            retain,
            topic: topic.into(),
            payload: payload.into(),
            properties: None,
            protocol,
        }
    }

    fn len(&self) -> usize {
        let mut len = 2 + self.topic.len() + self.payload.len();
        if self.qos != QoSWithPacketId::AtMostOnce {
            len += 2;
        }
        if self.protocol.is_v5() {
            if let Some(p) = &self.properties {
                let properties_len = p.len();
                let properties_len_len = len_len(properties_len);
                len += properties_len_len + properties_len;
            } else {
                // just 1 byte representing 0 len
                len += 1;
            }
        }
        len
    }

    pub fn read(
        fixed_header: FixedHeader,
        mut bytes: Bytes,
        protocol: Protocol,
    ) -> Result<Self, PacketParseError> {
        let qos = qos((fixed_header.byte1 & 0b0110) >> 1)?;
        let dup = (fixed_header.byte1 & 0b1000) != 0;
        let retain = (fixed_header.byte1 & 0b0001) != 0;

        let variable_header_index = fixed_header.fixed_header_len;
        bytes.advance(variable_header_index);
        let topic = read_mqtt_string(&mut bytes)?.into();

        // Packet identifier exists where QoS > 0
        let qos = match qos {
            QoS::AtMostOnce => QoSWithPacketId::AtMostOnce,
            QoS::AtLeastOnce => QoSWithPacketId::AtLeastOnce(read_u16(&mut bytes)?),
            QoS::ExactlyOnce => QoSWithPacketId::ExactlyOnce(read_u16(&mut bytes)?),
        };

        let publish = match protocol {
            Protocol::V4 => Publish {
                protocol: Protocol::V4,
                dup,
                retain,
                qos,
                topic,
                payload: Arc::new(bytes.into()),
                properties: None,
            },
            Protocol::V5 => {
                let properties = PublishProperties::read(&mut bytes)?;

                Publish {
                    protocol: Protocol::V5,
                    dup,
                    retain,
                    qos,
                    topic,
                    payload: Arc::new(bytes.into()),
                    properties,
                }
            }
        };

        Ok(publish)
    }

    pub fn write(&self, buffer: &mut BytesMut) -> usize {
        let len = self.len();

        let dup = self.dup as u8;
        let qos = self.qos.qos();
        let retain = self.retain as u8;
        buffer.put_u8(0b0011_0000 | retain | qos << 1 | dup << 3);

        let count = write_remaining_length(buffer, len);
        write_mqtt_string(buffer, self.topic.as_str());

        if let Some(pkid) = self.qos.packet_id() {
            buffer.put_u16(pkid);
        }

        match &self.protocol {
            Protocol::V4 => {
                buffer.extend_from_slice(&self.payload.as_ref());
            }
            Protocol::V5 => {
                if let Some(p) = &self.properties {
                    p.write(buffer);
                } else {
                    write_remaining_length(buffer, 0);
                }
                buffer.extend_from_slice(&self.payload);
            }
        }

        // TODO: Returned length is wrong in other packets. Fix it
        1 + count + len
    }
}

impl fmt::Debug for Publish {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Topic = {}, Qos = {:?}, Retain = {}, Payload = {:?}, properties = {:?}",
            self.topic, self.qos, self.retain, self.payload, self.properties
        )
    }
}
impl PublishProperties {
    pub fn len(&self) -> usize {
        let mut len = 0;

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

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

        if self.topic_alias.is_some() {
            len += 1 + 2;
        }

        if let Some(topic) = &self.response_topic {
            len += 1 + 2 + topic.len()
        }

        if let Some(data) = &self.correlation_data {
            len += 1 + 2 + data.len()
        }

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

        for id in self.subscription_identifiers.iter() {
            len += 1 + len_len(*id);
        }

        if let Some(typ) = &self.content_type {
            len += 1 + 2 + typ.len()
        }

        len
    }

    pub fn read(bytes: &mut Bytes) -> Result<Option<PublishProperties>, PacketParseError> {
        let mut payload_format_indicator = None;
        let mut message_expiry_interval = None;
        let mut topic_alias = None;
        let mut response_topic = None;
        let mut correlation_data = None;
        let mut user_properties = Vec::new();
        let mut subscription_identifiers = Vec::new();
        let mut content_type = None;

        let (properties_len_len, properties_len) = length(bytes.iter())?;
        bytes.advance(properties_len_len);
        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor = 0;
        // read until cursor reaches property length. properties_len = 0 will skip this loop
        while cursor < properties_len {
            let prop = read_u8(bytes)?;
            cursor += 1;

            match property(prop)? {
                PropertyType::PayloadFormatIndicator => {
                    payload_format_indicator = Some(read_u8(bytes)?);
                    cursor += 1;
                }
                PropertyType::MessageExpiryInterval => {
                    message_expiry_interval = Some(read_u32(bytes)?);
                    cursor += 4;
                }
                PropertyType::TopicAlias => {
                    topic_alias = Some(read_u16(bytes)?);
                    cursor += 2;
                }
                PropertyType::ResponseTopic => {
                    let topic = read_mqtt_string(bytes)?;
                    cursor += 2 + topic.len();
                    response_topic = Some(topic);
                }
                PropertyType::CorrelationData => {
                    let data = read_mqtt_bytes(bytes)?;
                    cursor += 2 + data.len();
                    correlation_data = Some(data);
                }
                PropertyType::UserProperty => {
                    let key = read_mqtt_string(bytes)?;
                    let value = read_mqtt_string(bytes)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    user_properties.push((key, value));
                }
                PropertyType::SubscriptionIdentifier => {
                    let (id_len, id) = length(bytes.iter())?;
                    cursor += 1 + id_len;
                    bytes.advance(id_len);
                    subscription_identifiers.push(id);
                }
                PropertyType::ContentType => {
                    let typ = read_mqtt_string(bytes)?;
                    cursor += 2 + typ.len();
                    content_type = Some(typ);
                }
                _ => return Err(PacketParseError::InvalidPropertyType(prop)),
            }
        }

        Ok(Some(PublishProperties {
            payload_format_indicator,
            message_expiry_interval,
            topic_alias,
            response_topic,
            correlation_data,
            user_properties,
            subscription_identifiers,
            content_type,
        }))
    }

    pub fn write(&self, buffer: &mut BytesMut) {
        let len = self.len();
        write_remaining_length(buffer, len);

        if let Some(payload_format_indicator) = &self.payload_format_indicator {
            buffer.put_u8(PropertyType::PayloadFormatIndicator as u8);
            buffer.put_u8(*payload_format_indicator);
        }

        if let Some(message_expiry_interval) = &self.message_expiry_interval {
            buffer.put_u8(PropertyType::MessageExpiryInterval as u8);
            buffer.put_u32(*message_expiry_interval);
        }

        if let Some(topic_alias) = &self.topic_alias {
            buffer.put_u8(PropertyType::TopicAlias as u8);
            buffer.put_u16(*topic_alias);
        }

        if let Some(topic) = &&self.response_topic {
            buffer.put_u8(PropertyType::ResponseTopic as u8);
            write_mqtt_string(buffer, topic);
        }

        if let Some(data) = &&self.correlation_data {
            buffer.put_u8(PropertyType::CorrelationData as u8);
            write_mqtt_bytes(buffer, data);
        }

        for (key, value) in self.user_properties.iter() {
            buffer.put_u8(PropertyType::UserProperty as u8);
            write_mqtt_string(buffer, key);
            write_mqtt_string(buffer, value);
        }

        for id in self.subscription_identifiers.iter() {
            buffer.put_u8(PropertyType::SubscriptionIdentifier as u8);
            write_remaining_length(buffer, *id);
        }

        if let Some(typ) = &self.content_type {
            buffer.put_u8(PropertyType::ContentType as u8);
            write_mqtt_string(buffer, typ);
        }
    }
}