symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! CONNECT and CONNACK packet encoding/decoding [MQTTv5-3.1, MQTTv5-3.2]
//!
//! ```text
//! CONNECT [MQTTv5-3.1]:
//!
//!   Fixed Header:
//!     Byte 1: 0x10 (type=1, flags=0b0000)
//!     Byte 2..N: Remaining Length
//!
//!   Variable Header:
//!     Protocol Name:    2-byte length + "MQTT" (6 bytes total)
//!     Protocol Level:   1 byte (0x05 for v5)
//!     Connect Flags:    1 byte
//!       Bit 7: Username Flag
//!       Bit 6: Password Flag
//!       Bit 5: Will Retain
//!       Bit 4-3: Will QoS
//!       Bit 2: Will Flag
//!       Bit 1: Clean Start
//!       Bit 0: Reserved (must be 0)
//!     Keep Alive:       2 bytes (big-endian seconds)
//!     Properties:       Connect Properties
//!
//!   Payload (in order, presence determined by flags):
//!     Client Identifier:  UTF-8 string (always present)
//!     Will Properties:    (if Will Flag = 1)
//!     Will Topic:         UTF-8 string (if Will Flag = 1)
//!     Will Payload:       binary data  (if Will Flag = 1)
//!     Username:           UTF-8 string (if Username Flag = 1)
//!     Password:           binary data  (if Password Flag = 1)
//!
//! CONNACK [MQTTv5-3.2]:
//!
//!   Fixed Header:
//!     Byte 1: 0x20 (type=2, flags=0b0000)
//!     Byte 2..N: Remaining Length
//!
//!   Variable Header:
//!     Connect Acknowledge Flags: 1 byte (bit 0 = Session Present)
//!     Connect Reason Code:       1 byte
//!     Properties:                ConnAck Properties
//!
//!   No payload.
//! ```

use bytes::{Buf, Bytes, BytesMut};

use super::property::{self, PROP_ID_LEN, PropertyId, properties_encoded_len, write_properties_len};
use super::reason_code::ReasonCode;
use crate::{DecodeError, EncodeError, PacketType, QoS, primitives};

/// Connect properties [MQTTv5-3.1.2.11]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConnectProperties {
    /// Session expiry interval in seconds
    pub session_expiry_interval: Option<u32>,
    /// Client receive maximum
    pub receive_maximum: Option<u16>,
    /// Maximum packet size the client will accept
    pub maximum_packet_size: Option<u32>,
    /// Maximum topic alias the client will accept
    pub topic_alias_maximum: Option<u16>,
    /// Request response information from the server
    pub request_response_information: Option<u8>,
    /// Request problem information from the server
    pub request_problem_information: Option<u8>,
    /// User-defined key-value properties
    pub user_properties: Vec<(String, String)>,
    /// Authentication method name
    pub authentication_method: Option<String>,
    /// Authentication data
    pub authentication_data: Option<Bytes>,
}

impl ConnectProperties {
    fn encoded_len(&self) -> usize {
        let mut len = 0;
        if self.session_expiry_interval.is_some() {
            len += PROP_ID_LEN + PropertyId::SESSION_EXPIRY_INTERVAL_LEN;
        }
        if self.receive_maximum.is_some() {
            len += PROP_ID_LEN + PropertyId::RECEIVE_MAXIMUM_LEN;
        }
        if self.maximum_packet_size.is_some() {
            len += PROP_ID_LEN + PropertyId::MAXIMUM_PACKET_SIZE_LEN;
        }
        if self.topic_alias_maximum.is_some() {
            len += PROP_ID_LEN + PropertyId::TOPIC_ALIAS_MAXIMUM_LEN;
        }
        if self.request_response_information.is_some() {
            len += PROP_ID_LEN + PropertyId::REQUEST_RESPONSE_INFORMATION_LEN;
        }
        if self.request_problem_information.is_some() {
            len += PROP_ID_LEN + PropertyId::REQUEST_PROBLEM_INFORMATION_LEN;
        }
        for (k, v) in &self.user_properties {
            len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
        }
        if let Some(ref s) = self.authentication_method {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref d) = self.authentication_data {
            len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
        }
        len
    }

    fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        write_properties_len(self.encoded_len(), buf);
        if let Some(v) = self.session_expiry_interval {
            primitives::write_u8(PropertyId::SessionExpiryInterval as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(v) = self.receive_maximum {
            primitives::write_u8(PropertyId::ReceiveMaximum as u8, buf);
            primitives::write_u16(v, buf);
        }
        if let Some(v) = self.maximum_packet_size {
            primitives::write_u8(PropertyId::MaximumPacketSize as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(v) = self.topic_alias_maximum {
            primitives::write_u8(PropertyId::TopicAliasMaximum as u8, buf);
            primitives::write_u16(v, buf);
        }
        if let Some(v) = self.request_response_information {
            primitives::write_u8(PropertyId::RequestResponseInformation as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.request_problem_information {
            primitives::write_u8(PropertyId::RequestProblemInformation as u8, buf);
            primitives::write_u8(v, buf);
        }
        for (k, v) in &self.user_properties {
            primitives::write_u8(PropertyId::UserProperty as u8, buf);
            primitives::write_string_pair(k, v, buf)?;
        }
        if let Some(ref s) = self.authentication_method {
            primitives::write_u8(PropertyId::AuthenticationMethod as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref d) = self.authentication_data {
            primitives::write_u8(PropertyId::AuthenticationData as u8, buf);
            primitives::write_binary(d, buf)?;
        }
        Ok(())
    }

    fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
        let mut props = Self::default();
        while buf.has_remaining() {
            let id_byte = primitives::read_u8(&mut buf)?;
            let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
                packet_type: PacketType::Connect,
                id: id_byte,
            })?;
            match id {
                PropertyId::SessionExpiryInterval => {
                    if props.session_expiry_interval.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.session_expiry_interval = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::ReceiveMaximum => {
                    if props.receive_maximum.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.receive_maximum = Some(primitives::read_u16(&mut buf)?);
                }
                PropertyId::MaximumPacketSize => {
                    if props.maximum_packet_size.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.maximum_packet_size = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::TopicAliasMaximum => {
                    if props.topic_alias_maximum.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.topic_alias_maximum = Some(primitives::read_u16(&mut buf)?);
                }
                PropertyId::RequestResponseInformation => {
                    if props.request_response_information.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.request_response_information = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::RequestProblemInformation => {
                    if props.request_problem_information.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.request_problem_information = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::UserProperty => {
                    props.user_properties.push(primitives::read_string_pair(&mut buf)?);
                }
                PropertyId::AuthenticationMethod => {
                    if props.authentication_method.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.authentication_method = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::AuthenticationData => {
                    if props.authentication_data.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.authentication_data = Some(primitives::read_binary(&mut buf)?);
                }
                _ => {
                    return Err(DecodeError::InvalidProperty {
                        packet_type: PacketType::Connect,
                        id: id_byte,
                    });
                }
            }
        }
        Ok(props)
    }
}

/// Will properties [MQTTv5-3.1.3.2]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WillProperties {
    /// Delay in seconds before the server publishes the will
    pub will_delay_interval: Option<u32>,
    /// Payload format: 0 = unspecified bytes, 1 = UTF-8
    pub payload_format_indicator: Option<u8>,
    /// Lifetime in seconds for the will message
    pub message_expiry_interval: Option<u32>,
    /// MIME content type of the will payload
    pub content_type: Option<String>,
    /// Response topic for request/response
    pub response_topic: Option<String>,
    /// Correlation data for request/response
    pub correlation_data: Option<Bytes>,
    /// User-defined key-value properties
    pub user_properties: Vec<(String, String)>,
}

impl WillProperties {
    fn encoded_len(&self) -> usize {
        let mut len = 0;
        if self.will_delay_interval.is_some() {
            len += PROP_ID_LEN + PropertyId::WILL_DELAY_INTERVAL_LEN;
        }
        if self.payload_format_indicator.is_some() {
            len += PROP_ID_LEN + PropertyId::PAYLOAD_FORMAT_INDICATOR_LEN;
        }
        if self.message_expiry_interval.is_some() {
            len += PROP_ID_LEN + PropertyId::MESSAGE_EXPIRY_INTERVAL_LEN;
        }
        if let Some(ref s) = self.content_type {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref s) = self.response_topic {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref d) = self.correlation_data {
            len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
        }
        for (k, v) in &self.user_properties {
            len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
        }
        len
    }

    fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        write_properties_len(self.encoded_len(), buf);
        if let Some(v) = self.will_delay_interval {
            primitives::write_u8(PropertyId::WillDelayInterval as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(v) = self.payload_format_indicator {
            primitives::write_u8(PropertyId::PayloadFormatIndicator as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.message_expiry_interval {
            primitives::write_u8(PropertyId::MessageExpiryInterval as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(ref s) = self.content_type {
            primitives::write_u8(PropertyId::ContentType as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref s) = self.response_topic {
            primitives::write_u8(PropertyId::ResponseTopic as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref d) = self.correlation_data {
            primitives::write_u8(PropertyId::CorrelationData as u8, buf);
            primitives::write_binary(d, buf)?;
        }
        for (k, v) in &self.user_properties {
            primitives::write_u8(PropertyId::UserProperty as u8, buf);
            primitives::write_string_pair(k, v, buf)?;
        }
        Ok(())
    }

    fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
        let mut props = Self::default();
        while buf.has_remaining() {
            let id_byte = primitives::read_u8(&mut buf)?;
            let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
                packet_type: PacketType::Connect,
                id: id_byte,
            })?;
            match id {
                PropertyId::WillDelayInterval => {
                    if props.will_delay_interval.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.will_delay_interval = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::PayloadFormatIndicator => {
                    if props.payload_format_indicator.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.payload_format_indicator = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::MessageExpiryInterval => {
                    if props.message_expiry_interval.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.message_expiry_interval = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::ContentType => {
                    if props.content_type.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.content_type = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::ResponseTopic => {
                    if props.response_topic.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.response_topic = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::CorrelationData => {
                    if props.correlation_data.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.correlation_data = Some(primitives::read_binary(&mut buf)?);
                }
                PropertyId::UserProperty => {
                    props.user_properties.push(primitives::read_string_pair(&mut buf)?);
                }
                _ => {
                    return Err(DecodeError::InvalidProperty {
                        packet_type: PacketType::Connect,
                        id: id_byte,
                    });
                }
            }
        }
        Ok(props)
    }
}

/// Will message carried in a CONNECT packet [MQTTv5-3.1.3.2]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Will {
    /// Will properties
    pub properties: WillProperties,
    /// Will topic
    pub topic: String,
    /// Will payload
    pub payload: Bytes,
    /// Will QoS
    pub qos: QoS,
    /// Whether the will is retained
    pub retain: bool,
}

/// CONNECT packet [MQTTv5-3.1]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
    /// Clean Start flag
    pub clean_start: bool,
    /// Keep Alive in seconds
    pub keep_alive: u16,
    /// CONNECT properties
    pub properties: ConnectProperties,
    /// Client identifier
    pub client_id: String,
    /// Last Will and Testament
    pub will: Option<Will>,
    /// User name
    pub username: Option<String>,
    /// Password
    pub password: Option<Bytes>,
}

impl Connect {
    const FLAGS: u8 = 0b0000;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        let mut len = 0;
        len += 6 + 1 + 1 + 2;
        len += properties_encoded_len(self.properties.encoded_len());
        len += 2 + self.client_id.len();
        if let Some(ref will) = self.will {
            len += properties_encoded_len(will.properties.encoded_len());
            len += 2 + will.topic.len();
            len += 2 + will.payload.len();
        }
        if let Some(ref u) = self.username {
            len += 2 + u.len();
        }
        if let Some(ref p) = self.password {
            len += 2 + p.len();
        }
        len
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        primitives::write_string("MQTT", buf)?;
        primitives::write_u8(0x05, buf);

        let mut flags: u8 = 0;
        if self.clean_start {
            flags |= 0x02;
        }
        if let Some(ref will) = self.will {
            flags |= 0x04;
            flags |= (will.qos as u8) << 3;
            if will.retain {
                flags |= 0x20;
            }
        }
        if self.username.is_some() {
            flags |= 0x80;
        }
        if self.password.is_some() {
            flags |= 0x40;
        }
        primitives::write_u8(flags, buf);

        primitives::write_u16(self.keep_alive, buf);
        self.properties.encode(buf)?;

        primitives::write_string(&self.client_id, buf)?;
        if let Some(ref will) = self.will {
            will.properties.encode(buf)?;
            primitives::write_string(&will.topic, buf)?;
            primitives::write_binary(&will.payload, buf)?;
        }
        if let Some(ref u) = self.username {
            primitives::write_string(u, buf)?;
        }
        if let Some(ref p) = self.password {
            primitives::write_binary(p, buf)?;
        }
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Connect,
                flags: header_flags,
            });
        }

        let protocol_name = primitives::read_string(&mut buf)?;
        if protocol_name != "MQTT" {
            return Err(DecodeError::ProtocolError {
                reason: "invalid protocol name",
            });
        }
        let level = primitives::read_u8(&mut buf)?;
        if level != 0x05 {
            return Err(DecodeError::ProtocolError {
                reason: "unsupported protocol level for v5",
            });
        }

        let flags_byte = primitives::read_u8(&mut buf)?;
        if flags_byte & 0x01 != 0 {
            return Err(DecodeError::ProtocolError {
                reason: "reserved flag bit must be 0",
            });
        }
        let clean_start = flags_byte & 0x02 != 0;
        let has_will = flags_byte & 0x04 != 0;
        let will_qos = QoS::try_from((flags_byte >> 3) & 0x03)?;
        let will_retain = flags_byte & 0x20 != 0;
        let has_password = flags_byte & 0x40 != 0;
        let has_username = flags_byte & 0x80 != 0;

        let keep_alive = primitives::read_u16(&mut buf)?;
        let props_buf = property::read_properties_bytes(&mut buf)?;
        let properties = ConnectProperties::decode(props_buf)?;

        let client_id = primitives::read_string(&mut buf)?;
        let will = if has_will {
            let will_props_buf = property::read_properties_bytes(&mut buf)?;
            let will_properties = WillProperties::decode(will_props_buf)?;
            let topic = primitives::read_string(&mut buf)?;
            let payload = primitives::read_binary(&mut buf)?;
            Some(Will {
                properties: will_properties,
                topic,
                payload,
                qos: will_qos,
                retain: will_retain,
            })
        } else {
            None
        };
        let username = if has_username {
            Some(primitives::read_string(&mut buf)?)
        } else {
            None
        };
        let password = if has_password {
            Some(primitives::read_binary(&mut buf)?)
        } else {
            None
        };

        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }

        Ok(Self {
            clean_start,
            keep_alive,
            properties,
            client_id,
            will,
            username,
            password,
        })
    }
}

/// ConnAck properties [MQTTv5-3.2.2.3]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConnAckProperties {
    /// Session expiry interval in seconds
    pub session_expiry_interval: Option<u32>,
    /// Server receive maximum
    pub receive_maximum: Option<u16>,
    /// Maximum QoS the server supports
    pub maximum_qos: Option<u8>,
    /// Whether retain is available
    pub retain_available: Option<u8>,
    /// Maximum packet size the server will accept
    pub maximum_packet_size: Option<u32>,
    /// Client identifier assigned by the server
    pub assigned_client_identifier: Option<String>,
    /// Maximum topic alias the server will accept
    pub topic_alias_maximum: Option<u16>,
    /// Human-readable reason
    pub reason_string: Option<String>,
    /// User-defined key-value properties
    pub user_properties: Vec<(String, String)>,
    /// Whether wildcard subscriptions are available
    pub wildcard_subscription_available: Option<u8>,
    /// Whether subscription identifiers are available
    pub subscription_identifier_available: Option<u8>,
    /// Whether shared subscriptions are available
    pub shared_subscription_available: Option<u8>,
    /// Server keep alive in seconds
    pub server_keep_alive: Option<u16>,
    /// Response information
    pub response_information: Option<String>,
    /// Alternate server reference
    pub server_reference: Option<String>,
    /// Authentication method name
    pub authentication_method: Option<String>,
    /// Authentication data
    pub authentication_data: Option<Bytes>,
}

impl ConnAckProperties {
    fn encoded_len(&self) -> usize {
        let mut len = 0;
        if self.session_expiry_interval.is_some() {
            len += PROP_ID_LEN + PropertyId::SESSION_EXPIRY_INTERVAL_LEN;
        }
        if self.receive_maximum.is_some() {
            len += PROP_ID_LEN + PropertyId::RECEIVE_MAXIMUM_LEN;
        }
        if self.maximum_qos.is_some() {
            len += PROP_ID_LEN + PropertyId::MAXIMUM_QOS_LEN;
        }
        if self.retain_available.is_some() {
            len += PROP_ID_LEN + PropertyId::RETAIN_AVAILABLE_LEN;
        }
        if self.maximum_packet_size.is_some() {
            len += PROP_ID_LEN + PropertyId::MAXIMUM_PACKET_SIZE_LEN;
        }
        if let Some(ref s) = self.assigned_client_identifier {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if self.topic_alias_maximum.is_some() {
            len += PROP_ID_LEN + PropertyId::TOPIC_ALIAS_MAXIMUM_LEN;
        }
        if let Some(ref s) = self.reason_string {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        for (k, v) in &self.user_properties {
            len += PROP_ID_LEN + primitives::string_pair_encoded_len(k.len(), v.len());
        }
        if self.wildcard_subscription_available.is_some() {
            len += PROP_ID_LEN + PropertyId::WILDCARD_SUBSCRIPTION_AVAILABLE_LEN;
        }
        if self.subscription_identifier_available.is_some() {
            len += PROP_ID_LEN + PropertyId::SUBSCRIPTION_IDENTIFIER_AVAILABLE_LEN;
        }
        if self.shared_subscription_available.is_some() {
            len += PROP_ID_LEN + PropertyId::SHARED_SUBSCRIPTION_AVAILABLE_LEN;
        }
        if self.server_keep_alive.is_some() {
            len += PROP_ID_LEN + PropertyId::SERVER_KEEP_ALIVE_LEN;
        }
        if let Some(ref s) = self.response_information {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref s) = self.server_reference {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref s) = self.authentication_method {
            len += PROP_ID_LEN + primitives::string_encoded_len(s.len());
        }
        if let Some(ref d) = self.authentication_data {
            len += PROP_ID_LEN + primitives::binary_encoded_len(d.len());
        }
        len
    }

    fn encode(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        write_properties_len(self.encoded_len(), buf);
        if let Some(v) = self.session_expiry_interval {
            primitives::write_u8(PropertyId::SessionExpiryInterval as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(v) = self.receive_maximum {
            primitives::write_u8(PropertyId::ReceiveMaximum as u8, buf);
            primitives::write_u16(v, buf);
        }
        if let Some(v) = self.maximum_qos {
            primitives::write_u8(PropertyId::MaximumQoS as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.retain_available {
            primitives::write_u8(PropertyId::RetainAvailable as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.maximum_packet_size {
            primitives::write_u8(PropertyId::MaximumPacketSize as u8, buf);
            primitives::write_u32(v, buf);
        }
        if let Some(ref s) = self.assigned_client_identifier {
            primitives::write_u8(PropertyId::AssignedClientIdentifier as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(v) = self.topic_alias_maximum {
            primitives::write_u8(PropertyId::TopicAliasMaximum as u8, buf);
            primitives::write_u16(v, buf);
        }
        if let Some(ref s) = self.reason_string {
            primitives::write_u8(PropertyId::ReasonString as u8, buf);
            primitives::write_string(s, buf)?;
        }
        for (k, v) in &self.user_properties {
            primitives::write_u8(PropertyId::UserProperty as u8, buf);
            primitives::write_string_pair(k, v, buf)?;
        }
        if let Some(v) = self.wildcard_subscription_available {
            primitives::write_u8(PropertyId::WildcardSubscriptionAvailable as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.subscription_identifier_available {
            primitives::write_u8(PropertyId::SubscriptionIdentifierAvailable as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.shared_subscription_available {
            primitives::write_u8(PropertyId::SharedSubscriptionAvailable as u8, buf);
            primitives::write_u8(v, buf);
        }
        if let Some(v) = self.server_keep_alive {
            primitives::write_u8(PropertyId::ServerKeepAlive as u8, buf);
            primitives::write_u16(v, buf);
        }
        if let Some(ref s) = self.response_information {
            primitives::write_u8(PropertyId::ResponseInformation as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref s) = self.server_reference {
            primitives::write_u8(PropertyId::ServerReference as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref s) = self.authentication_method {
            primitives::write_u8(PropertyId::AuthenticationMethod as u8, buf);
            primitives::write_string(s, buf)?;
        }
        if let Some(ref d) = self.authentication_data {
            primitives::write_u8(PropertyId::AuthenticationData as u8, buf);
            primitives::write_binary(d, buf)?;
        }
        Ok(())
    }

    fn decode(mut buf: Bytes) -> Result<Self, DecodeError> {
        let mut props = Self::default();
        while buf.has_remaining() {
            let id_byte = primitives::read_u8(&mut buf)?;
            let id = PropertyId::try_from(id_byte).map_err(|_| DecodeError::InvalidProperty {
                packet_type: PacketType::ConnAck,
                id: id_byte,
            })?;
            match id {
                PropertyId::SessionExpiryInterval => {
                    if props.session_expiry_interval.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.session_expiry_interval = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::ReceiveMaximum => {
                    if props.receive_maximum.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.receive_maximum = Some(primitives::read_u16(&mut buf)?);
                }
                PropertyId::MaximumQoS => {
                    if props.maximum_qos.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.maximum_qos = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::RetainAvailable => {
                    if props.retain_available.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.retain_available = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::MaximumPacketSize => {
                    if props.maximum_packet_size.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.maximum_packet_size = Some(primitives::read_u32(&mut buf)?);
                }
                PropertyId::AssignedClientIdentifier => {
                    if props.assigned_client_identifier.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.assigned_client_identifier = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::TopicAliasMaximum => {
                    if props.topic_alias_maximum.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.topic_alias_maximum = Some(primitives::read_u16(&mut buf)?);
                }
                PropertyId::ReasonString => {
                    if props.reason_string.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.reason_string = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::UserProperty => {
                    props.user_properties.push(primitives::read_string_pair(&mut buf)?);
                }
                PropertyId::WildcardSubscriptionAvailable => {
                    if props.wildcard_subscription_available.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.wildcard_subscription_available = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::SubscriptionIdentifierAvailable => {
                    if props.subscription_identifier_available.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.subscription_identifier_available = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::SharedSubscriptionAvailable => {
                    if props.shared_subscription_available.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.shared_subscription_available = Some(primitives::read_u8(&mut buf)?);
                }
                PropertyId::ServerKeepAlive => {
                    if props.server_keep_alive.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.server_keep_alive = Some(primitives::read_u16(&mut buf)?);
                }
                PropertyId::ResponseInformation => {
                    if props.response_information.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.response_information = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::ServerReference => {
                    if props.server_reference.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.server_reference = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::AuthenticationMethod => {
                    if props.authentication_method.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.authentication_method = Some(primitives::read_string(&mut buf)?);
                }
                PropertyId::AuthenticationData => {
                    if props.authentication_data.is_some() {
                        return Err(DecodeError::DuplicateProperty { id: id_byte });
                    }
                    props.authentication_data = Some(primitives::read_binary(&mut buf)?);
                }
                _ => {
                    return Err(DecodeError::InvalidProperty {
                        packet_type: PacketType::ConnAck,
                        id: id_byte,
                    });
                }
            }
        }
        Ok(props)
    }
}

/// CONNACK packet [MQTTv5-3.2]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnAck {
    /// Session Present flag
    pub session_present: bool,
    /// Connect reason code
    pub reason_code: ReasonCode,
    /// CONNACK properties
    pub properties: ConnAckProperties,
}

impl ConnAck {
    const FLAGS: u8 = 0b0000;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        1 + 1 + properties_encoded_len(self.properties.encoded_len())
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        primitives::write_u8(if self.session_present { 0x01 } else { 0x00 }, buf);
        primitives::write_u8(self.reason_code as u8, buf);
        self.properties.encode(buf)?;
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::ConnAck,
                flags: header_flags,
            });
        }
        let ack_flags = primitives::read_u8(&mut buf)?;
        if ack_flags & 0xFE != 0 {
            return Err(DecodeError::ProtocolError {
                reason: "reserved bits in CONNACK flags",
            });
        }
        let session_present = ack_flags & 0x01 != 0;
        let reason_byte = primitives::read_u8(&mut buf)?;
        let reason_code = ReasonCode::try_from(reason_byte)?;
        let props_buf = property::read_properties_bytes(&mut buf)?;
        let properties = ConnAckProperties::decode(props_buf)?;
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }
        Ok(Self {
            session_present,
            reason_code,
            properties,
        })
    }
}

#[cfg(test)]
mod tests {
    use bytes::{Bytes, BytesMut};

    use super::*;
    use crate::v5::Packet;
    use crate::{DecodeError, PacketType, QoS};

    fn roundtrip(packet: Packet) -> Packet {
        let mut buf = BytesMut::new();
        packet.encode(&mut buf).unwrap();
        Packet::decode(&mut buf).unwrap().unwrap()
    }

    #[test]
    fn connect_minimal() {
        let pkt = Packet::Connect(Connect {
            clean_start: true,
            keep_alive: 0,
            properties: ConnectProperties::default(),
            client_id: String::new(),
            will: None,
            username: None,
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_full() {
        let pkt = Packet::Connect(Connect {
            clean_start: false,
            keep_alive: 120,
            properties: ConnectProperties {
                session_expiry_interval: Some(3600),
                receive_maximum: Some(100),
                maximum_packet_size: Some(1024 * 1024),
                topic_alias_maximum: Some(10),
                request_response_information: Some(1),
                request_problem_information: Some(1),
                user_properties: vec![("key".to_owned(), "val".to_owned())],
                authentication_method: Some("SCRAM".to_owned()),
                authentication_data: Some(Bytes::from_static(b"auth-data")),
            },
            client_id: "my-client-v5".to_owned(),
            will: Some(Will {
                properties: WillProperties {
                    will_delay_interval: Some(30),
                    payload_format_indicator: Some(1),
                    message_expiry_interval: Some(60),
                    content_type: Some("text/plain".to_owned()),
                    response_topic: Some("resp".to_owned()),
                    correlation_data: Some(Bytes::from_static(b"\x01\x02")),
                    user_properties: vec![("wp".to_owned(), "wv".to_owned())],
                },
                topic: "will/topic".to_owned(),
                payload: Bytes::from_static(b"goodbye"),
                qos: QoS::ExactlyOnce,
                retain: true,
            }),
            username: Some("admin".to_owned()),
            password: Some(Bytes::from_static(b"secret")),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_clean_start_false() {
        let pkt = Packet::Connect(Connect {
            clean_start: false,
            keep_alive: 60,
            properties: ConnectProperties::default(),
            client_id: "c".to_owned(),
            will: None,
            username: None,
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_with_user_properties() {
        let pkt = Packet::Connect(Connect {
            clean_start: true,
            keep_alive: 30,
            properties: ConnectProperties {
                user_properties: vec![
                    ("k1".to_owned(), "v1".to_owned()),
                    ("k2".to_owned(), "v2".to_owned()),
                    ("k1".to_owned(), "v3".to_owned()), // duplicate key allowed
                ],
                ..Default::default()
            },
            client_id: "c".to_owned(),
            will: None,
            username: None,
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_decode_wrong_protocol_level() {
        let mut raw = BytesMut::new();
        primitives::write_string("MQTT", &mut raw).unwrap();
        primitives::write_u8(0x04, &mut raw); // v3.1.1 level
        primitives::write_u8(0x02, &mut raw); // clean_start
        primitives::write_u16(60, &mut raw);
        // empty properties
        raw.extend_from_slice(&[0x00]);
        // client_id
        primitives::write_string("c", &mut raw).unwrap();
        let buf = raw.freeze();
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "unsupported protocol level for v5"
            })
        );
    }

    #[test]
    fn connect_decode_duplicate_property() {
        // Build CONNECT with session_expiry_interval appearing twice
        let mut raw = BytesMut::new();
        primitives::write_string("MQTT", &mut raw).unwrap();
        primitives::write_u8(0x05, &mut raw);
        primitives::write_u8(0x02, &mut raw); // clean_start
        primitives::write_u16(60, &mut raw);
        // properties: two session_expiry_interval (id=0x11)
        let mut props_buf = BytesMut::new();
        primitives::write_u8(0x11, &mut props_buf);
        primitives::write_u32(100, &mut props_buf);
        primitives::write_u8(0x11, &mut props_buf);
        primitives::write_u32(200, &mut props_buf);
        // write properties length as varint
        let props_len = props_buf.len() as u32;
        let mut varint_dst = [0u8; 4];
        let vlen = crate::varint::encode_to(props_len, &mut varint_dst);
        raw.extend_from_slice(&varint_dst[..vlen]);
        raw.extend_from_slice(&props_buf);
        // client_id
        primitives::write_string("c", &mut raw).unwrap();
        let buf = raw.freeze();
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::DuplicateProperty { id: 0x11 })
        );
    }

    #[test]
    fn connack_minimal() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: false,
            reason_code: ReasonCode::Success,
            properties: ConnAckProperties::default(),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_session_present() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: true,
            reason_code: ReasonCode::Success,
            properties: ConnAckProperties::default(),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_with_all_properties() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: false,
            reason_code: ReasonCode::Success,
            properties: ConnAckProperties {
                session_expiry_interval: Some(7200),
                receive_maximum: Some(50),
                maximum_qos: Some(1),
                retain_available: Some(1),
                maximum_packet_size: Some(1_048_576),
                assigned_client_identifier: Some("assigned-id".to_owned()),
                topic_alias_maximum: Some(20),
                reason_string: Some("all good".to_owned()),
                user_properties: vec![("x".to_owned(), "y".to_owned())],
                wildcard_subscription_available: Some(1),
                subscription_identifier_available: Some(1),
                shared_subscription_available: Some(1),
                server_keep_alive: Some(300),
                response_information: Some("resp-info".to_owned()),
                server_reference: Some("other-server".to_owned()),
                authentication_method: Some("PLAIN".to_owned()),
                authentication_data: Some(Bytes::from_static(b"data")),
            },
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_error_reason_code() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: false,
            reason_code: ReasonCode::NotAuthorized,
            properties: ConnAckProperties::default(),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_invalid_flags() {
        let buf = Bytes::from_static(&[0x00, 0x00, 0x00]); // ack_flags, reason, props_len=0
        assert_eq!(
            ConnAck::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::ConnAck,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn connack_reserved_bits_in_ack_flags() {
        let buf = Bytes::from_static(&[0x02, 0x00, 0x00]); // bit1 set
        assert_eq!(
            ConnAck::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "reserved bits in CONNACK flags"
            })
        );
    }
}