aboutsummaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-mqtt.c
blob: b83fdd62dd8189bcd91a918808b2ca74551f49a2 (plain)
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
/* packet-mqtt.c
 * Routines for MQTT Protocol dissection
 *
 * MQTT v5.0 support sponsored by 1byt3 <customers at 1byt3.com>
 *
 * By Lakshmi Narayana Madala  <madalanarayana@outlook.com>
 *    Stig Bjorlykke  <stig@bjorlykke.org>
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * Protocol description:
 *
 * MQTT is a Client Server publish/subscribe messaging transport
 * protocol. The protocol runs over TCP/IP, or over other network
 * protocols that provide ordered, lossless, bi-directional
 * connections.
 *
 * MQTT v3.1 specification:
 * http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html
 *
 * MQTT v3.1.1 specification:
 * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/
 *
 * MQTT v5.0 specification:
 * http://docs.oasis-open.org/mqtt/mqtt/v5.0/
 *
 */

#include "config.h"
#include <epan/packet.h>
#include <epan/strutil.h>
#include <epan/uat.h>
#include <epan/dwarf.h>
#include "packet-tcp.h"
#include "packet-ssl.h"

#define MQTT_DEFAULT_PORT     1883 /* IANA registered under service name as mqtt */
#define MQTT_SSL_DEFAULT_PORT 8883 /* IANA registered under service name secure-mqtt */

/* MQTT Protocol Versions */
#define MQTT_PROTO_V31      3
#define MQTT_PROTO_V311     4
#define MQTT_PROTO_V50      5

#define MQTT_HDR_SIZE_BEFORE_LEN 1

/* MQTT Message Types */
#define MQTT_RESERVED        0
#define MQTT_CONNECT         1
#define MQTT_CONNACK         2
#define MQTT_PUBLISH         3
#define MQTT_PUBACK          4
#define MQTT_PUBREC          5
#define MQTT_PUBREL          6
#define MQTT_PUBCOMP         7
#define MQTT_SUBSCRIBE       8
#define MQTT_SUBACK          9
#define MQTT_UNSUBSCRIBE    10
#define MQTT_UNSUBACK       11
#define MQTT_PINGREQ        12
#define MQTT_PINGRESP       13
#define MQTT_DISCONNECT     14
#define MQTT_AUTH           15
#define MQTT_RESERVED_16    16

/* Flag Values to extract fields */
#define MQTT_MASK_MSG_TYPE          0xF0
#define MQTT_MASK_HDR_RESERVED      0x0F
#define MQTT_MASK_HDR_DUP_RESERVED  0x07
#define MQTT_MASK_QOS               0x06
#define MQTT_MASK_DUP_FLAG          0x08
#define MQTT_MASK_RETAIN            0x01

/* MQTT v5.0 Flag Values for the Subscription Options @ Subscribe Packet */
#define MQTT_MASK_SUBS_QOS          0x03
#define MQTT_MASK_SUBS_NL           0x04
#define MQTT_MASK_SUBS_RAP          0x08
#define MQTT_MASK_SUBS_RETAIN       0x30
#define MQTT_MASK_SUBS_RESERVED     0xC0

void proto_register_mqtt(void);
void proto_reg_handoff_mqtt(void);

static const value_string mqtt_protocol_version_vals[] = {
  { MQTT_PROTO_V31,        "MQTT v3.1" },
  { MQTT_PROTO_V311,       "MQTT v3.1.1" },
  { MQTT_PROTO_V50,        "MQTT v5.0" },
  { 0,                     NULL }
};

static const value_string mqtt_msgtype_vals[] = {
  { MQTT_RESERVED,          "Reserved" },
  { MQTT_CONNECT,           "Connect Command" },
  { MQTT_CONNACK,           "Connect Ack" },
  { MQTT_PUBLISH,           "Publish Message" },
  { MQTT_PUBACK,            "Publish Ack" },
  { MQTT_PUBREC,            "Publish Received" },
  { MQTT_PUBREL,            "Publish Release" },
  { MQTT_PUBCOMP,           "Publish Complete" },
  { MQTT_SUBSCRIBE,         "Subscribe Request" },
  { MQTT_SUBACK,            "Subscribe Ack" },
  { MQTT_UNSUBSCRIBE,       "Unsubscribe Request" },
  { MQTT_UNSUBACK,          "Unsubscribe Ack" },
  { MQTT_PINGREQ,           "Ping Request" },
  { MQTT_PINGRESP,          "Ping Response" },
  { MQTT_DISCONNECT,        "Disconnect Req" },
  { MQTT_AUTH,              "Authentication Exchange" },
  { MQTT_RESERVED_16,       "Reserved" },
  { 0,                      NULL }
};
static value_string_ext mqtt_msgtype_vals_ext = VALUE_STRING_EXT_INIT(mqtt_msgtype_vals);

#define MQTT_QOS_ATMOST_ONCE      0
#define MQTT_QOS_ATLEAST_ONCE     1
#define MQTT_QOS_EXACTLY_ONCE     2
#define MQTT_QOS_RESERVED         3

static const value_string mqtt_qos_vals[] = {
  { MQTT_QOS_ATMOST_ONCE,       "At most once delivery (Fire and Forget)" },
  { MQTT_QOS_ATLEAST_ONCE,      "At least once delivery (Acknowledged deliver)" },
  { MQTT_QOS_EXACTLY_ONCE,      "Exactly once delivery (Assured Delivery)" },
  { MQTT_QOS_RESERVED,          "Reserved" },
  { 0,                          NULL }
};

#define MQTT_SUBACK_FAILURE  128

static const value_string mqtt_subqos_vals[] = {
  { MQTT_QOS_ATMOST_ONCE,       "At most once delivery (Fire and Forget)" },
  { MQTT_QOS_ATLEAST_ONCE,      "At least once delivery (Acknowledged deliver)" },
  { MQTT_QOS_EXACTLY_ONCE,      "Exactly once delivery (Assured Delivery)" },
  { MQTT_QOS_RESERVED,          "Reserved" },
  { MQTT_SUBACK_FAILURE,        "Failure" },
  { 0,                          NULL }
};

#define MQTT_CON_ACCEPTED                   0
#define MQTT_CON_REFUSED_VERSION_MISMATCH   1
#define MQTT_CON_REFUSED_ID_REJECTED        2
#define MQTT_CON_REFUSED_SERVER_UNAVAILABLE 3
#define MQTT_CON_REFUSED_BAD_USER_PASSWD    4
#define MQTT_CON_REFUSED_UNAUTHORIZED       5

static const value_string mqtt_conack_vals[] = {
  { MQTT_CON_ACCEPTED,                   "Connection Accepted" },
  { MQTT_CON_REFUSED_VERSION_MISMATCH,   "Connection Refused: unacceptable protocol version" },
  { MQTT_CON_REFUSED_ID_REJECTED,        "Connection Refused: identifier rejected" },
  { MQTT_CON_REFUSED_SERVER_UNAVAILABLE, "Connection Refused: server unavailable" },
  { MQTT_CON_REFUSED_BAD_USER_PASSWD,    "Connection Refused: bad user name or password" },
  { MQTT_CON_REFUSED_UNAUTHORIZED,       "Connection Refused: not authorized" },
  { 0,                                   NULL }
};

#define MQTT_CONMASK_USER        0x80
#define MQTT_CONMASK_PASSWD      0x40
#define MQTT_CONMASK_RETAIN      0x20
#define MQTT_CONMASK_QOS         0x18
#define MQTT_CONMASK_WILLFLAG    0x04
#define MQTT_CONMASK_CLEANSESS   0x02
#define MQTT_CONMASK_RESERVED    0x01

#define MQTT_CONACKMASK_RESERVED 0xFE
#define MQTT_CONACKMASK_SP       0x01

/* The protocol version is present in the CONNECT message. */
typedef struct {
    guint8 runtime_proto_version;
} mqtt_conv_t;

typedef struct _mqtt_message_decode_t {
  guint   match_criteria;
  char   *topic_pattern;
  GRegex *topic_regex;
  char   *payload_proto_name;
  dissector_handle_t payload_proto;
} mqtt_message_decode_t;

#define MATCH_CRITERIA_EQUAL        0
#define MATCH_CRITERIA_CONTAINS     1
#define MATCH_CRITERIA_STARTS_WITH  2
#define MATCH_CRITERIA_ENDS_WITH    3
#define MATCH_CRITERIA_REGEX        4

static const value_string match_criteria[] = {
  { MATCH_CRITERIA_EQUAL,       "Equal to" },
  { MATCH_CRITERIA_CONTAINS,    "Contains" },
  { MATCH_CRITERIA_STARTS_WITH, "Starts with" },
  { MATCH_CRITERIA_ENDS_WITH,   "Ends with" },
  { MATCH_CRITERIA_REGEX,       "Regular Expression" },
  { 0, NULL }
};

#define PROP_PAYLOAD_FORMAT_INDICATOR          0x01
#define PROP_PUBLICATION_EXPIRY_INTERVAL       0x02
#define PROP_CONTENT_TYPE                      0x03
#define PROP_RESPONSE_TOPIC                    0x08
#define PROP_CORRELATION_DATA                  0x09
#define PROP_SUBSCRIPTION_IDENTIFIER           0x0B
#define PROP_SESSION_EXPIRY_INTERVAL           0x11
#define PROP_ASSIGNED_CLIENT_IDENTIFIER        0x12
#define PROP_SERVER_KEEP_ALIVE                 0x13
#define PROP_AUTH_METHOD                       0x15
#define PROP_AUTH_DATA                         0x16
#define PROP_REQUEST_PROBLEM_INFORMATION       0x17
#define PROP_WILL_DELAY_INTERVAL               0x18
#define PROP_REQUEST_RESPONSE_INFORMATION      0x19
#define PROP_RESPONSE_INFORMATION              0x1A
#define PROP_SERVER_REFERENCE                  0x1C
#define PROP_REASON_STRING                     0x1F
#define PROP_RECEIVE_MAXIMUM                   0x21
#define PROP_TOPIC_ALIAS_MAXIMUM               0x22
#define PROP_TOPIC_ALIAS                       0x23
#define PROP_MAXIMUM_QOS                       0x24
#define PROP_RETAIN_AVAILABLE                  0x25
#define PROP_USER_PROPERTY                     0x26
#define PROP_MAXIMUM_PACKET_SIZE               0x27
#define PROP_WILDCARD_SUBSCRIPTION_AVAILABLE   0x28
#define PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE 0x29
#define PROP_SHARED_SUBSCRIPTION_AVAILABLE     0x2A

static const value_string mqtt_property_vals[] = {
  { PROP_PAYLOAD_FORMAT_INDICATOR,          "Payload Format Indicator" },
  { PROP_PUBLICATION_EXPIRY_INTERVAL,       "Publication Expiry Interval" },
  { PROP_CONTENT_TYPE,                      "Content Type" },
  { PROP_RESPONSE_TOPIC,                    "Response Topic" },
  { PROP_CORRELATION_DATA,                  "Correlation Data" },
  { PROP_SUBSCRIPTION_IDENTIFIER,           "Subscription Identifier" },
  { PROP_SESSION_EXPIRY_INTERVAL,           "Session Expiry Interval" },
  { PROP_ASSIGNED_CLIENT_IDENTIFIER,        "Assigned Client Identifier" },
  { PROP_SERVER_KEEP_ALIVE,                 "Server Keep Alive" },
  { PROP_AUTH_METHOD,                       "Authentication Method" },
  { PROP_AUTH_DATA,                         "Authentication Data" },
  { PROP_REQUEST_PROBLEM_INFORMATION,       "Request Problem Information" },
  { PROP_WILL_DELAY_INTERVAL,               "Will Delay Interval" },
  { PROP_REQUEST_RESPONSE_INFORMATION,      "Request Response Information" },
  { PROP_RESPONSE_INFORMATION,              "Response Information" },
  { PROP_SERVER_REFERENCE,                  "Server Reference" },
  { PROP_REASON_STRING,                     "Reason String" },
  { PROP_RECEIVE_MAXIMUM,                   "Receive Maximum" },
  { PROP_TOPIC_ALIAS_MAXIMUM,               "Topic Alias Maximum" },
  { PROP_TOPIC_ALIAS,                       "Topic Alias" },
  { PROP_MAXIMUM_QOS,                       "Maximum QoS" },
  { PROP_RETAIN_AVAILABLE,                  "Retain Available" },
  { PROP_USER_PROPERTY,                     "User Property" },
  { PROP_MAXIMUM_PACKET_SIZE,               "Maximum Packet Size" },
  { PROP_WILDCARD_SUBSCRIPTION_AVAILABLE,   "Wildcard Subscription Available" },
  { PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, "Subscription Identifier Available" },
  { PROP_SHARED_SUBSCRIPTION_AVAILABLE,     "Shared Subscription Available" },
  { 0, NULL }
};

/* MQTT v5.0 Subscription Options, Retain Handling option */
#define SUBSCRIPTION_RETAIN_SEND            0x00
#define SUBSCRIPTION_RETAIN_SEND_DONT_EXIST 0x01
#define SUBSCRIPTION_RETAIN_DONT_SEND       0x02
#define SUBSCRIPTION_RETAIN_RESERVED        0x03

static const value_string mqtt_subscription_retain_handling[] = {
  { SUBSCRIPTION_RETAIN_SEND,            "Send msgs at subscription time" },
  { SUBSCRIPTION_RETAIN_SEND_DONT_EXIST, "Send msgs if subscription does not exist" },
  { SUBSCRIPTION_RETAIN_DONT_SEND,       "Do not send msgs at subscription time" },
  { SUBSCRIPTION_RETAIN_RESERVED,        "Reserved" },
  { 0, NULL }
};

static mqtt_message_decode_t *mqtt_message_decodes;
static guint num_mqtt_message_decodes;

static dissector_handle_t mqtt_handle;

/* Initialize the protocol and registered fields */
static int proto_mqtt = -1;

/* Message */
static int hf_mqtt_hdrflags = -1;
static int hf_mqtt_msg_len = -1;
static int hf_mqtt_msg_type = -1;
static int hf_mqtt_reserved = -1;
static int hf_mqtt_dup_flag = -1;
static int hf_mqtt_qos_level = -1;
static int hf_mqtt_retain = -1;
static int hf_mqtt_retain_reserved = -1;
static int hf_mqtt_conack_reserved = -1;
static int hf_mqtt_conack_flags = -1;
static int hf_mqtt_conackflag_reserved = -1;
static int hf_mqtt_conackflag_sp = -1;
static int hf_mqtt_conack_code = -1;
static int hf_mqtt_msgid = -1;
static int hf_mqtt_sub_qos = -1;
static int hf_mqtt_suback_qos = -1;
static int hf_mqtt_topic_len = -1;
static int hf_mqtt_topic = -1;
static int hf_mqtt_will_topic_len = -1;
static int hf_mqtt_will_topic = -1;
static int hf_mqtt_will_msg_len = -1;
static int hf_mqtt_will_msg = -1;
static int hf_mqtt_username_len = -1;
static int hf_mqtt_username = -1;
static int hf_mqtt_passwd_len = -1;
static int hf_mqtt_passwd = -1;
static int hf_mqtt_pubmsg = -1;
static int hf_mqtt_pubmsg_decoded = -1;
static int hf_mqtt_proto_len = -1;
static int hf_mqtt_proto_name = -1;
static int hf_mqtt_client_id_len = -1;
static int hf_mqtt_client_id = -1;
static int hf_mqtt_proto_ver = -1;
static int hf_mqtt_conflags = -1;
static int hf_mqtt_conflag_user = -1;
static int hf_mqtt_conflag_passwd = -1;
static int hf_mqtt_conflag_will_retain = -1;
static int hf_mqtt_conflag_will_qos = -1;
static int hf_mqtt_conflag_will_flag = -1;
static int hf_mqtt_conflag_clean_sess = -1;
static int hf_mqtt_conflag_reserved = -1;
static int hf_mqtt_keep_alive = -1;
static int hf_mqtt_subscription_options = -1;
static int hf_mqtt_reason_code = -1;

/* MQTT v5.0 Subscribe Options */
static int hf_mqtt_subscription_qos = -1;
static int hf_mqtt_subscription_nl = -1;
static int hf_mqtt_subscription_rap = -1;
static int hf_mqtt_subscription_retain = -1;
static int hf_mqtt_subscription_reserved = -1;

/* MQTT v5.0 Properties */
static int hf_mqtt_property_len = -1;
static int hf_mqtt_property = -1;
static int hf_mqtt_property_id = -1;
static int hf_mqtt_prop_num = -1;
static int hf_mqtt_prop_max_qos = -1;
static int hf_mqtt_prop_unknown = -1;
static int hf_mqtt_prop_string_len = -1;
static int hf_mqtt_prop_string = -1;
static int hf_mqtt_prop_key_len = -1;
static int hf_mqtt_prop_key = -1;
static int hf_mqtt_prop_value_len = -1;
static int hf_mqtt_prop_value = -1;

/* Initialize the subtree pointers */
static gint ett_mqtt_hdr = -1;
static gint ett_mqtt_msg = -1;
static gint ett_mqtt_hdr_flags = -1;
static gint ett_mqtt_con_flags = -1;
static gint ett_mqtt_conack_flags = -1;
static gint ett_mqtt_property = -1;
static gint ett_mqtt_subscription_flags = -1;

/* Reassemble SMPP TCP segments */
static gboolean reassemble_mqtt_over_tcp = TRUE;

#define GET_MQTT_PDU_LEN(msg_len, len_offset)    (msg_len + len_offset + MQTT_HDR_SIZE_BEFORE_LEN)

static guint get_mqtt_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb,
                              int offset, void *data _U_)
{
  guint64 msg_len;
  guint len_offset;

  len_offset = dissect_uleb128(tvb, (offset + MQTT_HDR_SIZE_BEFORE_LEN), &msg_len);

  /* Explicitly downcast the value, because the length can never be more than 4 bytes */
  return (guint)(GET_MQTT_PDU_LEN(msg_len, len_offset));
}

static void *mqtt_message_decode_copy_cb(void *dest, const void *orig, size_t len _U_)
{
  const mqtt_message_decode_t *o = (const mqtt_message_decode_t *)orig;
  mqtt_message_decode_t *d = (mqtt_message_decode_t *)dest;

  d->topic_pattern = g_strdup(o->topic_pattern);
  d->payload_proto_name = g_strdup(o->payload_proto_name);

  return d;
}

static gboolean mqtt_message_decode_update_cb(void *record, char **error)
{
  mqtt_message_decode_t *u = (mqtt_message_decode_t *)record;

  if (u->topic_pattern == NULL || strlen(u->topic_pattern) == 0)
  {
    *error = g_strdup("Missing topic pattern");
    return FALSE;
  }

  if (u->match_criteria == MATCH_CRITERIA_REGEX)
  {
    u->topic_regex = g_regex_new(u->topic_pattern, (GRegexCompileFlags) G_REGEX_OPTIMIZE, (GRegexMatchFlags) 0, NULL);
    if (!u->topic_regex)
    {
      *error = g_strdup_printf("Invalid regex: %s", u->topic_pattern);
      return FALSE;
    }
  }

  return TRUE;
}

static void mqtt_message_decode_free_cb(void *record)
{
  mqtt_message_decode_t *u = (mqtt_message_decode_t *)record;

  g_free(u->topic_pattern);
  if (u->topic_regex)
  {
    g_regex_unref(u->topic_regex);
  }
  g_free(u->payload_proto_name);
}

UAT_VS_DEF(message_decode, match_criteria, mqtt_message_decode_t, guint, MATCH_CRITERIA_EQUAL, "Equal to")
UAT_CSTRING_CB_DEF(message_decode, topic_pattern, mqtt_message_decode_t)
UAT_PROTO_DEF(message_decode, payload_proto, payload_proto, payload_proto_name, mqtt_message_decode_t)

static void mqtt_user_decode_message(proto_tree *tree, proto_tree *mqtt_tree, packet_info *pinfo, const guint8 *topic_str, tvbuff_t *msg_tvb)
{
  mqtt_message_decode_t *message_decode_entry = NULL;
  size_t topic_str_len = strlen(topic_str);
  size_t topic_pattern_len;
  gboolean match_found = FALSE;

  if (topic_str_len == 0)
  {
    /* No topic to match */
    return;
  }

  for (guint i = 0; i < num_mqtt_message_decodes && !match_found; i++)
  {
    message_decode_entry = &mqtt_message_decodes[i];
    switch (message_decode_entry->match_criteria)
    {
      case MATCH_CRITERIA_EQUAL:
        match_found = (strcmp(topic_str, message_decode_entry->topic_pattern) == 0);
        break;
      case MATCH_CRITERIA_CONTAINS:
        match_found = (strstr(topic_str, message_decode_entry->topic_pattern) != NULL);
        break;
      case MATCH_CRITERIA_STARTS_WITH:
        topic_pattern_len = strlen(message_decode_entry->topic_pattern);
        match_found = ((topic_str_len >= topic_pattern_len) &&
                       (strncmp(topic_str, message_decode_entry->topic_pattern, topic_pattern_len) == 0));
        break;
      case MATCH_CRITERIA_ENDS_WITH:
        topic_pattern_len = strlen(message_decode_entry->topic_pattern);
        match_found = ((topic_str_len >= topic_pattern_len) &&
                       (strcmp(topic_str + (topic_str_len - topic_pattern_len), message_decode_entry->topic_pattern) == 0));
        break;
      case MATCH_CRITERIA_REGEX:
        if (message_decode_entry->topic_regex)
        {
          GMatchInfo *match_info = NULL;
          g_regex_match(message_decode_entry->topic_regex, topic_str, (GRegexMatchFlags) 0, &match_info);
          match_found = g_match_info_matches(match_info);
          g_match_info_free(match_info);
        }
        break;
      default:
        /* Unknown match criteria */
        break;
    }
  }

  if (match_found)
  {
    proto_item *ti = proto_tree_add_string(mqtt_tree, hf_mqtt_pubmsg_decoded, msg_tvb, 0, -1,
                                           message_decode_entry->payload_proto_name);
    PROTO_ITEM_SET_GENERATED(ti);

    call_dissector(message_decode_entry->payload_proto, msg_tvb, pinfo, tree);
  }
}

static guint32 dissect_string(tvbuff_t *tvb, proto_tree *tree, guint32 offset, int hf_len, int hf_value)
{
  guint16 prop_len;

  prop_len = tvb_get_guint16(tvb, offset, ENC_BIG_ENDIAN);
  proto_tree_add_uint(tree, hf_len, tvb, offset, 2, prop_len);
  proto_tree_add_item(tree, hf_value, tvb, offset + 2, prop_len, ENC_UTF_8|ENC_NA);

  return 2 + prop_len;
}

/* MQTT v5.0: dissect the MQTT properties */
static guint32 dissect_mqtt_properties(tvbuff_t *tvb, proto_tree *mqtt_tree, guint32 offset)
{
  proto_tree *mqtt_prop_tree;
  proto_item *ti;
  guint64 vbi;

  const guint32 mqtt_prop_offset = dissect_uleb128(tvb, offset, &vbi);
  /* Property Length field can be stored in uint32 */
  const guint32 mqtt_prop_len = (guint32)vbi;

  /* Add the MQTT branch to the main tree */
  ti = proto_tree_add_item(mqtt_tree, hf_mqtt_property, tvb, offset, mqtt_prop_offset + mqtt_prop_len, ENC_NA);
  mqtt_prop_tree = proto_item_add_subtree(ti, ett_mqtt_property);

  proto_tree_add_item(mqtt_prop_tree, hf_mqtt_property_len, tvb, offset, mqtt_prop_offset, ENC_BIG_ENDIAN);
  offset += mqtt_prop_offset;

  const guint32 bytes_to_read = offset + mqtt_prop_len;
  while (offset < bytes_to_read)
  {
    guint8 prop_id = tvb_get_guint8(tvb, offset);
    proto_tree_add_uint(mqtt_prop_tree, hf_mqtt_property_id, tvb, offset, 1, prop_id);
    offset += 1;

    switch (prop_id)
    {
      case PROP_PAYLOAD_FORMAT_INDICATOR:
      case PROP_REQUEST_PROBLEM_INFORMATION:
      case PROP_REQUEST_RESPONSE_INFORMATION:
      case PROP_RETAIN_AVAILABLE:
      case PROP_WILDCARD_SUBSCRIPTION_AVAILABLE:
      case PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE:
      case PROP_SHARED_SUBSCRIPTION_AVAILABLE:
        proto_tree_add_item(mqtt_prop_tree, hf_mqtt_prop_num, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset += 1;
        break;
      case PROP_MAXIMUM_QOS:
        proto_tree_add_item(mqtt_prop_tree, hf_mqtt_prop_max_qos, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset += 1;
        break;
      case PROP_SERVER_KEEP_ALIVE:
      case PROP_RECEIVE_MAXIMUM:
      case PROP_TOPIC_ALIAS_MAXIMUM:
      case PROP_TOPIC_ALIAS:
        proto_tree_add_item(mqtt_prop_tree, hf_mqtt_prop_num, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;
        break;
      case PROP_PUBLICATION_EXPIRY_INTERVAL:
      case PROP_SESSION_EXPIRY_INTERVAL:
      case PROP_WILL_DELAY_INTERVAL:
      case PROP_MAXIMUM_PACKET_SIZE:
        proto_tree_add_item(mqtt_prop_tree, hf_mqtt_prop_num, tvb, offset, 4, ENC_BIG_ENDIAN);
        offset += 4;
        break;
      case PROP_SUBSCRIPTION_IDENTIFIER:
      {
        guint8 vbi_offset = dissect_uleb128(tvb, offset, &vbi);
        proto_tree_add_uint(mqtt_prop_tree, hf_mqtt_prop_num, tvb, offset, vbi_offset, (guint32)vbi);
        offset += vbi_offset;
        break;
      }
      case PROP_CONTENT_TYPE:
      case PROP_RESPONSE_TOPIC:
      case PROP_CORRELATION_DATA:
      case PROP_ASSIGNED_CLIENT_IDENTIFIER:
      case PROP_AUTH_METHOD:
      case PROP_AUTH_DATA:
      case PROP_RESPONSE_INFORMATION:
      case PROP_SERVER_REFERENCE:
      case PROP_REASON_STRING:
        offset += dissect_string(tvb, mqtt_prop_tree, offset, hf_mqtt_prop_string_len, hf_mqtt_prop_string);
        break;
      case PROP_USER_PROPERTY:
        offset += dissect_string(tvb, mqtt_prop_tree, offset, hf_mqtt_prop_key_len, hf_mqtt_prop_key);
        offset += dissect_string(tvb, mqtt_prop_tree, offset, hf_mqtt_prop_value_len, hf_mqtt_prop_value);
        break;
      default:
        proto_tree_add_item(mqtt_prop_tree, hf_mqtt_prop_unknown, tvb, offset, bytes_to_read - offset, ENC_UTF_8|ENC_NA);
        offset += (bytes_to_read - offset);
        break;
    }
  }

  return mqtt_prop_offset + mqtt_prop_len;
}

/* Dissect the MQTT message */
static int dissect_mqtt(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
    guint8  mqtt_fixed_hdr;
    guint8  mqtt_msg_type;
    proto_item *ti;
    const guint8 *topic_str;

    proto_tree *mqtt_tree;

    guint64     mqtt_con_flags;
    guint64     msg_len      = 0;
    gint        mqtt_msg_len = 0;
    guint16     mqtt_str_len;
    guint16     mqtt_len_offset;
    gint        mqtt_payload_len;
    conversation_t *conv;
    mqtt_conv_t *mqtt;

    guint32 offset = 0;
    static const int *publish_fields[] = {
        &hf_mqtt_msg_type,
        &hf_mqtt_dup_flag,
        &hf_mqtt_qos_level,
        &hf_mqtt_retain,
        NULL
    };
    static const int *v31_pubrel_sub_unsub_fields[] = {
        &hf_mqtt_msg_type,
        &hf_mqtt_dup_flag,
        &hf_mqtt_qos_level,
        &hf_mqtt_retain_reserved,
        NULL
    };
    static const int *other_fields[] = {
        &hf_mqtt_msg_type,
        &hf_mqtt_reserved,
        NULL
    };
    static const int *connect_flags[] = {
        &hf_mqtt_conflag_user,
        &hf_mqtt_conflag_passwd,
        &hf_mqtt_conflag_will_retain,
        &hf_mqtt_conflag_will_qos,
        &hf_mqtt_conflag_will_flag,
        &hf_mqtt_conflag_clean_sess,
        &hf_mqtt_conflag_reserved,
        NULL
    };
    static const int *connack_flags[] = {
        &hf_mqtt_conackflag_reserved,
        &hf_mqtt_conackflag_sp,
        NULL
    };
    static const int *v50_subscription_flags[] = {
      &hf_mqtt_subscription_reserved,
      &hf_mqtt_subscription_retain,
      &hf_mqtt_subscription_rap,
      &hf_mqtt_subscription_nl,
      &hf_mqtt_subscription_qos,
      NULL
    };

    /* Extract the message ID */
    mqtt_fixed_hdr = tvb_get_guint8(tvb, offset);
    mqtt_msg_type = mqtt_fixed_hdr >> 4;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "MQTT");
    col_append_sep_str(pinfo->cinfo, COL_INFO, ", ", val_to_str_ext(mqtt_msg_type, &mqtt_msgtype_vals_ext, "Unknown (0x%02x)"));

    /* Add the MQTT branch to the main tree */
    ti = proto_tree_add_item(tree, proto_mqtt, tvb, 0, -1, ENC_NA);
    mqtt_tree = proto_item_add_subtree(ti, ett_mqtt_hdr);

    conv = find_or_create_conversation(pinfo);
    mqtt = (mqtt_conv_t *)conversation_get_proto_data(conv, proto_mqtt);
    if (mqtt == NULL)
    {
      mqtt = wmem_new0(wmem_file_scope(), mqtt_conv_t);
      conversation_add_proto_data(conv, proto_mqtt, mqtt);
    }

    mqtt_len_offset = dissect_uleb128(tvb, (offset + MQTT_HDR_SIZE_BEFORE_LEN), &msg_len);

    /* Explicit downcast, typically maximum length of message could be 4 bytes */
    mqtt_msg_len = (gint) msg_len;

    /* Add the type to the MQTT tree item */
    proto_item_append_text(mqtt_tree, ", %s", val_to_str_ext(mqtt_msg_type, &mqtt_msgtype_vals_ext, "Unknown (0x%02x)"));

    if (mqtt_msg_type == MQTT_PUBLISH)
    {
      proto_tree_add_bitmask(mqtt_tree, tvb, offset, hf_mqtt_hdrflags, ett_mqtt_hdr_flags, publish_fields, ENC_BIG_ENDIAN);
    }
    else if (mqtt->runtime_proto_version == MQTT_PROTO_V31 &&
             (mqtt_msg_type == MQTT_PUBREL ||
              mqtt_msg_type == MQTT_SUBSCRIBE ||
              mqtt_msg_type == MQTT_UNSUBSCRIBE))
    {
      proto_tree_add_bitmask(mqtt_tree, tvb, offset, hf_mqtt_hdrflags, ett_mqtt_hdr_flags, v31_pubrel_sub_unsub_fields, ENC_BIG_ENDIAN);
    }
    else
    {
      proto_tree_add_bitmask(mqtt_tree, tvb, offset, hf_mqtt_hdrflags, ett_mqtt_hdr_flags, other_fields, ENC_BIG_ENDIAN);
    }

    offset += 1;

    /* Add the MQTT message length */
    proto_tree_add_uint64(mqtt_tree, hf_mqtt_msg_len, tvb, offset, mqtt_len_offset, msg_len);
    offset += mqtt_len_offset;

    switch(mqtt_msg_type)
    {
      case MQTT_CONNECT:
        mqtt_str_len = tvb_get_ntohs(tvb, offset);
        proto_tree_add_item(mqtt_tree, hf_mqtt_proto_len, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        proto_tree_add_item(mqtt_tree, hf_mqtt_proto_name, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
        offset += mqtt_str_len;

        mqtt->runtime_proto_version = tvb_get_guint8(tvb, offset);

        proto_tree_add_item(mqtt_tree, hf_mqtt_proto_ver, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset += 1;


        proto_tree_add_bitmask_ret_uint64(mqtt_tree, tvb, offset, hf_mqtt_conflags,
                           ett_mqtt_con_flags, connect_flags, ENC_BIG_ENDIAN, &mqtt_con_flags);
        offset += 1;

        proto_tree_add_item(mqtt_tree, hf_mqtt_keep_alive, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);
        }

        mqtt_str_len = tvb_get_ntohs(tvb, offset);
        proto_tree_add_item(mqtt_tree, hf_mqtt_client_id_len, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        proto_tree_add_item(mqtt_tree, hf_mqtt_client_id, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
        offset += mqtt_str_len;

        if(mqtt_con_flags & MQTT_CONMASK_WILLFLAG)
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_will_topic_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_will_topic, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
          offset += mqtt_str_len;
        }
        if(mqtt_con_flags & MQTT_CONMASK_WILLFLAG)
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_will_msg_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_will_msg, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
          offset += mqtt_str_len;
        }
        if((mqtt_con_flags & MQTT_CONMASK_USER) && (tvb_reported_length_remaining(tvb, offset) > 0))
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_username_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_username, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
          offset += mqtt_str_len;
        }
        if((mqtt_con_flags & MQTT_CONMASK_PASSWD) && (tvb_reported_length_remaining(tvb, offset) > 0))
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_passwd_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_passwd, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
        }
        break;

      case MQTT_CONNACK:
        if (mqtt->runtime_proto_version == MQTT_PROTO_V31)
        {
          /* v3.1 Connection Ack only contains a reserved byte and the Return Code. */
          proto_tree_add_item(mqtt_tree, hf_mqtt_conack_reserved, tvb, offset, 1, ENC_BIG_ENDIAN);
        }
        else
        {
          /* v3.1.1 Conn Ack contains the Conn Ack Flags and the Return Code. */
          proto_tree_add_bitmask(mqtt_tree, tvb, offset, hf_mqtt_conack_flags,
                           ett_mqtt_conack_flags, connack_flags, ENC_BIG_ENDIAN);
        }
        offset += 1;

        proto_tree_add_item(mqtt_tree, hf_mqtt_conack_code, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset += 1;

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);
        }
        break;
      case MQTT_PUBLISH:
        /* TopicName|MsgID|Message| */
        mqtt_str_len = tvb_get_ntohs(tvb, offset);
        proto_tree_add_item(mqtt_tree, hf_mqtt_topic_len, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        proto_tree_add_item_ret_string(mqtt_tree, hf_mqtt_topic, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA,
                                       wmem_epan_scope(), &topic_str);
        offset += mqtt_str_len;

        /* Message ID is included only when QoS > 0 */
        if(mqtt_fixed_hdr & MQTT_MASK_QOS)
        {
          proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;
        }

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          guint32 mqtt_prop_offset = dissect_mqtt_properties(tvb, mqtt_tree, offset);
          offset += mqtt_prop_offset;
        }

        mqtt_payload_len = tvb_reported_length(tvb) - offset;
        proto_tree_add_item(mqtt_tree, hf_mqtt_pubmsg, tvb, offset, mqtt_payload_len, ENC_UTF_8|ENC_NA);

        if (num_mqtt_message_decodes > 0)
        {
          tvbuff_t *msg_tvb = tvb_new_subset_length(tvb, offset, mqtt_payload_len);
          mqtt_user_decode_message(tree, mqtt_tree, pinfo, topic_str, msg_tvb);
        }
        break;

      case MQTT_SUBSCRIBE:
        /* After the Message Id field is found, the following fields must appear
         * at least once:
         * |TopicName|QoS|
         */
        proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          guint32 mqtt_prop_offset = dissect_mqtt_properties(tvb, mqtt_tree, offset);
          offset += mqtt_prop_offset;
        }

        while (offset < (guint32)tvb_reported_length(tvb))
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_topic_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_topic, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
          offset += mqtt_str_len;

          if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
          {
            proto_tree_add_bitmask(mqtt_tree, tvb, offset, hf_mqtt_subscription_options,
                                   ett_mqtt_subscription_flags, v50_subscription_flags, ENC_BIG_ENDIAN);

          }
          else
          {
            proto_tree_add_item(mqtt_tree, hf_mqtt_sub_qos, tvb, offset, 1, ENC_BIG_ENDIAN);
          }

          offset += 1;
        }
        break;

      case MQTT_UNSUBSCRIBE:
        /* After the Message Id field is found, the following fields must appear
         * at least once:
         * |TopicName|
         */
        proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        while (offset < (guint32)tvb_reported_length(tvb))
        {
          mqtt_str_len = tvb_get_ntohs(tvb, offset);
          proto_tree_add_item(mqtt_tree, hf_mqtt_topic_len, tvb, offset, 2, ENC_BIG_ENDIAN);
          offset += 2;

          proto_tree_add_item(mqtt_tree, hf_mqtt_topic, tvb, offset, mqtt_str_len, ENC_UTF_8|ENC_NA);
          offset += mqtt_str_len;
        }
        break;

      case MQTT_SUBACK:
        /* The SUBACK message contains a list of granted QoS levels that come
         * after the Message Id field. The size of each QoS entry is 1 byte.
         */
        proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);
        }

        while (offset < (guint32)tvb_reported_length(tvb))
        {
          proto_tree_add_item(mqtt_tree, hf_mqtt_suback_qos, tvb, offset, 1, ENC_BIG_ENDIAN);
          offset += 1;
        }
        break;

      case MQTT_PUBACK:
      case MQTT_PUBREC:
      case MQTT_PUBREL:
      case MQTT_PUBCOMP:
        proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;
        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          proto_tree_add_item(mqtt_tree, hf_mqtt_reason_code, tvb, offset, 1, ENC_BIG_ENDIAN);
          offset += 1;

          offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);
        }
        break;

      case MQTT_UNSUBACK:
        proto_tree_add_item(mqtt_tree, hf_mqtt_msgid, tvb, offset, 2, ENC_BIG_ENDIAN);
        offset += 2;

        if (mqtt->runtime_proto_version == MQTT_PROTO_V50)
        {
          offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);

          while (offset < tvb_reported_length(tvb))
          {
            proto_tree_add_item(mqtt_tree, hf_mqtt_reason_code, tvb, offset, 1, ENC_BIG_ENDIAN);
            offset += 1;
          }
        }
        break;

      /* The following messages don't have variable header */
      case MQTT_PINGREQ:
      case MQTT_PINGRESP:
        break;

      case MQTT_DISCONNECT:
        /* MQTT v5.0: Byte 1 in the Variable Header is the Disconnect Reason Code.
         * If the Remaining Length is less than 1 the value of 0x00
         * (Normal disconnection) is used.
         */
         /* FALLTHROUGH */
      case MQTT_AUTH:
        /* MQTT v5.0: The Reason Code and Property Length can be omitted if
         * the Reason Code is 0x00 (Success) and there are no Properties.
         * In this case the AUTH has a Remaining Length of 0.
         */
        if (mqtt->runtime_proto_version == MQTT_PROTO_V50 && mqtt_msg_len > 0)
        {
          proto_tree_add_item(mqtt_tree, hf_mqtt_reason_code, tvb, offset, 1, ENC_BIG_ENDIAN);
          offset += 1;

          /* 3.14.2.2 DISCONNECT Properties:
           * If the Remaining Length is less than 2, a value of 0 is used.
           * Let's assume that it also applies to AUTH, why? DISCONNECT and AUTH
           * share the same structure with no payload.
           */
          if (mqtt_msg_len >= 2)
          {
            offset += dissect_mqtt_properties(tvb, mqtt_tree, offset);
          }
        }

        break;
    }

    return tvb_captured_length(tvb);
}

/**
"The minimum size of MQTT Packet is 2 bytes(Ping Req, Ping Rsp,
Disconnect), and the maximum size is 256MB.  Hence minimum fixed
length should be 2 bytes for tcp_dissect_pdu.

If the length filed is spread across two TCP segments, then we have a
problem, because exception will be raised.  So long as MQTT length
field(although spread over 4 bytes) is present within single TCP
segment we shouldn't have any issue by calling tcp_dissect_pdu with
minimum length set to 2."

XXX: ToDo: Commit a fix for the case of the length field spread across TCP segments.
**/

static int dissect_mqtt_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
  col_clear(pinfo->cinfo, COL_INFO);

  tcp_dissect_pdus(tvb, pinfo, tree,
                   reassemble_mqtt_over_tcp,
                   2,                           /* Length can be determined within 5 bytes */
                   get_mqtt_pdu_len,
                   dissect_mqtt, data);

  return tvb_captured_length(tvb);
}

/*
 * Register the protocol with Wireshark
 */
void proto_register_mqtt(void)
{
  static hf_register_info hf_mqtt[] = {
    { &hf_mqtt_msg_len,
      { "Msg Len", "mqtt.len",
        FT_UINT64, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_hdrflags,
      { "Header Flags", "mqtt.hdrflags",
        FT_UINT8, BASE_HEX, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_msg_type,
      { "Message Type", "mqtt.msgtype",
        FT_UINT8, BASE_DEC | BASE_EXT_STRING, &mqtt_msgtype_vals_ext, MQTT_MASK_MSG_TYPE,
        NULL, HFILL }},
    { &hf_mqtt_reserved,
      { "Reserved", "mqtt.hdr_reserved",
        FT_UINT8, BASE_DEC, NULL, MQTT_MASK_HDR_RESERVED,
        "Fixed Header Reserved Field", HFILL }},
    { &hf_mqtt_retain_reserved,
      { "Reserved", "mqtt.retain_reserved",
        FT_UINT8, BASE_DEC, NULL, MQTT_MASK_RETAIN,
        "Fixed Header Reserved Field", HFILL }},
    { &hf_mqtt_dup_flag,
      { "DUP Flag", "mqtt.dupflag",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_MASK_DUP_FLAG,
        NULL, HFILL }},
    { &hf_mqtt_qos_level,
      { "QoS Level", "mqtt.qos",
        FT_UINT8, BASE_DEC, VALS(mqtt_qos_vals), MQTT_MASK_QOS,
        NULL, HFILL }},
    { &hf_mqtt_retain,
      { "Retain", "mqtt.retain",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_MASK_RETAIN,
        NULL, HFILL }},
    /* Conn-Ack */
    { &hf_mqtt_conack_reserved,
      { "Reserved", "mqtt.conack.flags.reserved",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), 0,
        NULL, HFILL }},
    { &hf_mqtt_conack_flags,
      { "Acknowledge Flags", "mqtt.conack.flags",
        FT_UINT8, BASE_HEX, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_conackflag_reserved,
      { "Reserved", "mqtt.conack.flags.reserved",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONACKMASK_RESERVED,
        NULL, HFILL }},
    { &hf_mqtt_conackflag_sp,
      { "Session Present", "mqtt.conack.flags.sp",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONACKMASK_SP,
        "Session Present (version 3.1.1)", HFILL }},
    { &hf_mqtt_conack_code,
      { "Return Code", "mqtt.conack.val",
        FT_UINT8, BASE_DEC, VALS(mqtt_conack_vals), 0,
        NULL, HFILL }},
    /* Publish-Ack / Publish-Rec / Publish-Rel / Publish-Comp / Unsubscribe-Ack */
    { &hf_mqtt_msgid,
      { "Message Identifier", "mqtt.msgid",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_sub_qos,
      { "Requested QoS", "mqtt.sub.qos",
        FT_UINT8, BASE_DEC, VALS(mqtt_qos_vals), 0,
        NULL, HFILL }},
    { &hf_mqtt_suback_qos,
      { "Granted QoS", "mqtt.suback.qos",
        FT_UINT8, BASE_DEC, VALS(mqtt_subqos_vals), 0,
        NULL, HFILL }},
      { &hf_mqtt_topic_len,
      { "Topic Length", "mqtt.topic_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_topic,
      { "Topic", "mqtt.topic",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_will_topic_len,
      { "Will Topic Length", "mqtt.willtopic_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_will_topic,
      { "Will Topic", "mqtt.willtopic",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_will_msg,
      { "Will Message", "mqtt.willmsg",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_will_msg_len,
      { "Will Message Length", "mqtt.willmsg_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_username_len,
      { "User Name Length", "mqtt.username_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_username,
      { "User Name", "mqtt.username",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_passwd_len,
      { "Password Length", "mqtt.passwd_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_passwd,
      { "Password", "mqtt.passwd",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_pubmsg,
      { "Message", "mqtt.msg",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_pubmsg_decoded,
      { "Message decoded as", "mqtt.msg_decoded_as",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_proto_len,
      { "Protocol Name Length", "mqtt.proto_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_proto_name,
      { "Protocol Name", "mqtt.protoname",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_client_id_len,
      { "Client ID Length", "mqtt.clientid_len",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_client_id,
      { "Client ID", "mqtt.clientid",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_proto_ver,
      { "Version", "mqtt.ver",
        FT_UINT8, BASE_DEC, VALS(mqtt_protocol_version_vals), 0,
        "MQTT version", HFILL }},
    /* Connect Flags */
    { &hf_mqtt_conflags,
      { "Connect Flags", "mqtt.conflags",
        FT_UINT8, BASE_HEX, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_conflag_user,
      { "User Name Flag", "mqtt.conflag.uname",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_USER,
        NULL, HFILL }},
    { &hf_mqtt_conflag_passwd,
      { "Password Flag", "mqtt.conflag.passwd",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_PASSWD,
        NULL, HFILL }},
    { &hf_mqtt_conflag_will_retain,
      { "Will Retain", "mqtt.conflag.retain",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_RETAIN,
        NULL, HFILL }},
    { &hf_mqtt_conflag_will_qos,
      { "QoS Level", "mqtt.conflag.qos",
        FT_UINT8, BASE_DEC, VALS(mqtt_qos_vals), MQTT_CONMASK_QOS,
        NULL, HFILL }},
    { &hf_mqtt_conflag_will_flag,
      { "Will Flag", "mqtt.conflag.willflag",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_WILLFLAG,
        NULL, HFILL }},
    { &hf_mqtt_conflag_clean_sess,
      { "Clean Session Flag", "mqtt.conflag.cleansess",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_CLEANSESS,
        NULL, HFILL }},
    { &hf_mqtt_conflag_reserved,
      { "(Reserved)", "mqtt.conflag.reserved",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_CONMASK_RESERVED,
        NULL, HFILL }},
    { &hf_mqtt_keep_alive,
      { "Keep Alive", "mqtt.kalive",
        FT_UINT16, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_subscription_options,
      { "Subscription Options", "mqtt.subscription_options",
        FT_UINT8, BASE_HEX, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_subscription_qos,
      { "QoS", "mqtt.subscription_options_qos",
        FT_UINT8, BASE_DEC, VALS(mqtt_qos_vals), MQTT_MASK_SUBS_QOS,
        NULL, HFILL }},
    { &hf_mqtt_subscription_nl,
      { "No Local", "mqtt.subscription_options_nl",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_MASK_SUBS_NL,
        NULL, HFILL }},
    { &hf_mqtt_subscription_rap,
      { "Retain As Published", "mqtt.subscription_options_rap",
        FT_BOOLEAN, 8, TFS(&tfs_set_notset), MQTT_MASK_SUBS_RAP,
        NULL, HFILL }},
    { &hf_mqtt_subscription_retain,
      { "Retain Handling", "mqtt.subscription_options_retain",
        FT_UINT8, BASE_DEC, VALS(mqtt_subscription_retain_handling), MQTT_MASK_SUBS_RETAIN,
        NULL, HFILL }},
    { &hf_mqtt_subscription_reserved,
      { "Reserved", "mqtt.subscription_options_reserved",
        FT_UINT8, BASE_HEX, NULL, MQTT_MASK_SUBS_RESERVED,
        NULL, HFILL }},
    { &hf_mqtt_reason_code,
      { "Reason Code", "mqtt.reason_code",
        FT_UINT8, BASE_DEC, NULL, 0,
        "MQTT Reason Code", HFILL }},

    /* Properties */
    { &hf_mqtt_property,
      { "Properties", "mqtt.properties",
        FT_NONE, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_property_len,
      { "Total Length", "mqtt.property_len",
        FT_UINT64, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_property_id,
      { "ID", "mqtt.property_id",
        FT_UINT8, BASE_HEX, VALS(mqtt_property_vals), 0,
        "Property Id", HFILL }},
    { &hf_mqtt_prop_num,
      { "Value", "mqtt.prop_number",
        FT_UINT32, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_max_qos,
      { "QoS", "mqtt.prop_max_qos_value",
        FT_UINT8, BASE_DEC, VALS(mqtt_qos_vals), 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_unknown,
      { "Unknown Property", "mqtt.prop_unknown",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_string_len,
      { "Length", "mqtt.prop_string_len",
        FT_UINT32, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_string,
      { "Value", "mqtt.prop_string",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_key_len,
      { "Key Length", "mqtt.prop_key_len",
        FT_UINT32, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_key,
      { "Key", "mqtt.prop_key",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_value_len,
      { "Value Length", "mqtt.prop_value_len",
        FT_UINT32, BASE_DEC, NULL, 0,
        NULL, HFILL }},
    { &hf_mqtt_prop_value,
      { "Value", "mqtt.prop_value",
        FT_STRING, BASE_NONE, NULL, 0,
        NULL, HFILL }},
  };

  /* Setup protocol subtree arrays */
  static gint* ett_mqtt[] = {
    &ett_mqtt_hdr,
    &ett_mqtt_msg,
    &ett_mqtt_hdr_flags,
    &ett_mqtt_con_flags,
    &ett_mqtt_conack_flags,
    &ett_mqtt_property,
    &ett_mqtt_subscription_flags,
  };

  static uat_field_t mqtt_message_decode_flds[] = {
    UAT_FLD_VS(message_decode, match_criteria, "Match criteria", match_criteria, "Match criteria"),
    UAT_FLD_CSTRING(message_decode, topic_pattern, "Topic pattern", "Pattern to match for the topic"),
    UAT_FLD_PROTO(message_decode, payload_proto, "Payload protocol",
                  "Protocol to be used for the message part of the matching topic"),
    UAT_END_FIELDS
  };

  uat_t *message_uat = uat_new("Message Decoding",
                               sizeof(mqtt_message_decode_t),
                               "mqtt_message_decoding",
                               TRUE,
                               &mqtt_message_decodes,
                               &num_mqtt_message_decodes,
                               UAT_AFFECTS_DISSECTION, /* affects dissection of packets, but not set of named fields */
                               "ChMQTTMessageDecoding",
                               mqtt_message_decode_copy_cb,
                               mqtt_message_decode_update_cb,
                               mqtt_message_decode_free_cb,
                               NULL,
                               NULL,
                               mqtt_message_decode_flds);

  module_t *mqtt_module;

  /* Register protocol names and descriptions */
  proto_mqtt = proto_register_protocol("MQ Telemetry Transport Protocol", "MQTT", "mqtt");

  /* Register the dissector */
  mqtt_handle = register_dissector("mqtt", dissect_mqtt_data, proto_mqtt);

  proto_register_field_array(proto_mqtt, hf_mqtt, array_length(hf_mqtt));
  proto_register_subtree_array(ett_mqtt, array_length(ett_mqtt));

  mqtt_module = prefs_register_protocol(proto_mqtt, NULL);

  prefs_register_uat_preference(mqtt_module, "message_decode_table",
                                "Message Decoding",
                                "A table that enumerates custom message decodes to be used for a certain topic",
                                message_uat);
}

/*
 *  Dissector Handoff
 */
void proto_reg_handoff_mqtt(void)
{
  dissector_add_uint_with_preference("tcp.port", MQTT_DEFAULT_PORT, mqtt_handle);
  ssl_dissector_add(MQTT_SSL_DEFAULT_PORT, mqtt_handle);
}

/*
 * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 2
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=2 tabstop=8 expandtab:
 * :indentSize=2:tabSize=8:noTabs=true:
 */