File: mqtt5_testing_utils.c

package info (click to toggle)
aws-crt-python 0.20.4%2Bdfsg-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 72,656 kB
  • sloc: ansic: 381,805; python: 23,008; makefile: 6,251; sh: 4,536; cpp: 699; ruby: 208; java: 77; perl: 73; javascript: 46; xml: 11
file content (1742 lines) | stat: -rw-r--r-- 73,106 bytes parent folder | download
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
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#include "mqtt5_testing_utils.h"

#include <aws/common/clock.h>
#include <aws/io/channel_bootstrap.h>
#include <aws/io/event_loop.h>
#include <aws/io/host_resolver.h>
#include <aws/mqtt/private/v5/mqtt5_decoder.h>
#include <aws/mqtt/private/v5/mqtt5_encoder.h>
#include <aws/mqtt/private/v5/mqtt5_utils.h>
#include <aws/mqtt/v5/mqtt5_client.h>

#include <aws/testing/aws_test_harness.h>

#include <inttypes.h>

int aws_mqtt5_test_verify_user_properties_raw(
    size_t property_count,
    const struct aws_mqtt5_user_property *properties,
    size_t expected_count,
    const struct aws_mqtt5_user_property *expected_properties) {

    ASSERT_UINT_EQUALS(expected_count, property_count);

    for (size_t i = 0; i < expected_count; ++i) {
        const struct aws_mqtt5_user_property *expected_property = &expected_properties[i];
        struct aws_byte_cursor expected_name = expected_property->name;
        struct aws_byte_cursor expected_value = expected_property->value;

        bool found = false;
        for (size_t j = 0; j < property_count; ++j) {
            const struct aws_mqtt5_user_property *nv_pair = &properties[j];

            if (aws_byte_cursor_compare_lexical(&expected_name, &nv_pair->name) == 0 &&
                aws_byte_cursor_compare_lexical(&expected_value, &nv_pair->value) == 0) {
                found = true;
                break;
            }
        }

        if (!found) {
            return AWS_OP_ERR;
        }
    }

    return AWS_OP_SUCCESS;
}

static int s_compute_connack_variable_length_fields(
    const struct aws_mqtt5_packet_connack_view *connack_view,
    uint32_t *total_remaining_length,
    uint32_t *property_length) {

    size_t local_property_length =
        aws_mqtt5_compute_user_property_encode_length(connack_view->user_properties, connack_view->user_property_count);

    ADD_OPTIONAL_U32_PROPERTY_LENGTH(connack_view->session_expiry_interval, local_property_length);
    ADD_OPTIONAL_U16_PROPERTY_LENGTH(connack_view->receive_maximum, local_property_length);
    ADD_OPTIONAL_U8_PROPERTY_LENGTH(connack_view->maximum_qos, local_property_length);
    ADD_OPTIONAL_U8_PROPERTY_LENGTH(connack_view->retain_available, local_property_length);
    ADD_OPTIONAL_U32_PROPERTY_LENGTH(connack_view->maximum_packet_size, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->assigned_client_identifier, local_property_length);
    ADD_OPTIONAL_U16_PROPERTY_LENGTH(connack_view->topic_alias_maximum, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->reason_string, local_property_length);
    ADD_OPTIONAL_U8_PROPERTY_LENGTH(connack_view->wildcard_subscriptions_available, local_property_length);
    ADD_OPTIONAL_U8_PROPERTY_LENGTH(connack_view->subscription_identifiers_available, local_property_length);
    ADD_OPTIONAL_U8_PROPERTY_LENGTH(connack_view->shared_subscriptions_available, local_property_length);
    ADD_OPTIONAL_U16_PROPERTY_LENGTH(connack_view->server_keep_alive, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->response_information, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->server_reference, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->authentication_method, local_property_length);
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(connack_view->authentication_data, local_property_length);

    *property_length = (uint32_t)local_property_length;

    size_t property_length_encoding_length = 0;
    if (aws_mqtt5_get_variable_length_encode_size(local_property_length, &property_length_encoding_length)) {
        return AWS_OP_ERR;
    }

    /* reason code (1 byte) + flags (1 byte) */
    *total_remaining_length = *property_length + (uint32_t)property_length_encoding_length + 2;

    return AWS_OP_SUCCESS;
}

int aws_mqtt5_encoder_begin_connack(struct aws_mqtt5_encoder *encoder, const void *packet_view) {

    const struct aws_mqtt5_packet_connack_view *connack_view = packet_view;

    uint32_t total_remaining_length = 0;
    uint32_t property_length = 0;
    if (s_compute_connack_variable_length_fields(connack_view, &total_remaining_length, &property_length)) {
        int error_code = aws_last_error();
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) mqtt5 client encoder - failed to compute variable length values for CONNACK packet with error "
            "%d(%s)",
            (void *)encoder->config.client,
            error_code,
            aws_error_debug_str(error_code));
        return AWS_OP_ERR;
    }

    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "(%p) mqtt5 client encoder - setting up encode for a CONNACK packet with remaining length %" PRIu32,
        (void *)encoder->config.client,
        total_remaining_length);

    uint8_t flags = connack_view->session_present ? 1 : 0;

    ADD_ENCODE_STEP_U8(encoder, aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_CONNACK, 0));
    ADD_ENCODE_STEP_VLI(encoder, total_remaining_length);
    ADD_ENCODE_STEP_U8(encoder, flags);
    ADD_ENCODE_STEP_U8(encoder, (uint8_t)connack_view->reason_code);
    ADD_ENCODE_STEP_VLI(encoder, property_length);

    if (property_length > 0) {
        ADD_ENCODE_STEP_OPTIONAL_U32_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_SESSION_EXPIRY_INTERVAL, connack_view->session_expiry_interval);
        ADD_ENCODE_STEP_OPTIONAL_U16_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_RECEIVE_MAXIMUM, connack_view->receive_maximum);
        ADD_ENCODE_STEP_OPTIONAL_U8_PROPERTY(encoder, AWS_MQTT5_PROPERTY_TYPE_MAXIMUM_QOS, connack_view->maximum_qos);
        ADD_ENCODE_STEP_OPTIONAL_U8_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_RETAIN_AVAILABLE, connack_view->retain_available);
        ADD_ENCODE_STEP_OPTIONAL_U32_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_MAXIMUM_PACKET_SIZE, connack_view->maximum_packet_size);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_ASSIGNED_CLIENT_IDENTIFIER, connack_view->assigned_client_identifier);
        ADD_ENCODE_STEP_OPTIONAL_U16_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_TOPIC_ALIAS_MAXIMUM, connack_view->topic_alias_maximum);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_REASON_STRING, connack_view->reason_string);
        ADD_ENCODE_STEP_OPTIONAL_U8_PROPERTY(
            encoder,
            AWS_MQTT5_PROPERTY_TYPE_WILDCARD_SUBSCRIPTIONS_AVAILABLE,
            connack_view->wildcard_subscriptions_available);
        ADD_ENCODE_STEP_OPTIONAL_U8_PROPERTY(
            encoder,
            AWS_MQTT5_PROPERTY_TYPE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE,
            connack_view->subscription_identifiers_available);
        ADD_ENCODE_STEP_OPTIONAL_U8_PROPERTY(
            encoder,
            AWS_MQTT5_PROPERTY_TYPE_SHARED_SUBSCRIPTIONS_AVAILABLE,
            connack_view->shared_subscriptions_available);
        ADD_ENCODE_STEP_OPTIONAL_U16_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_SERVER_KEEP_ALIVE, connack_view->server_keep_alive);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_RESPONSE_INFORMATION, connack_view->response_information);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_SERVER_REFERENCE, connack_view->server_reference);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_AUTHENTICATION_METHOD, connack_view->authentication_method);
        ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
            encoder, AWS_MQTT5_PROPERTY_TYPE_AUTHENTICATION_DATA, connack_view->authentication_data);

        aws_mqtt5_add_user_property_encoding_steps(
            encoder, connack_view->user_properties, connack_view->user_property_count);
    }

    return AWS_OP_SUCCESS;
}

int aws_mqtt5_encoder_begin_pingresp(struct aws_mqtt5_encoder *encoder, const void *packet_view) {
    (void)packet_view;

    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "(%p) mqtt5 client encoder - setting up encode for a PINGRESP packet",
        (void *)encoder->config.client);

    /* A ping response is just a fixed header with a 0-valued remaining length which we encode as a 0 u8 */
    ADD_ENCODE_STEP_U8(encoder, aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_PINGRESP, 0));
    ADD_ENCODE_STEP_U8(encoder, 0);

    return AWS_OP_SUCCESS;
}

static int s_compute_suback_variable_length_fields(
    const struct aws_mqtt5_packet_suback_view *suback_view,
    uint32_t *total_remaining_length,
    uint32_t *property_length) {
    /* User Properties length */
    size_t local_property_length =
        aws_mqtt5_compute_user_property_encode_length(suback_view->user_properties, suback_view->user_property_count);
    /* Optional Reason String */
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(suback_view->reason_string, local_property_length);

    *property_length = (uint32_t)local_property_length;

    size_t local_total_remaining_length = 0;
    if (aws_mqtt5_get_variable_length_encode_size(local_property_length, &local_total_remaining_length)) {
        return AWS_OP_ERR;
    }

    /* Packet Identifier (2 bytes) */
    local_total_remaining_length += 2;

    /* Reason Codes (1 byte each) */
    local_total_remaining_length += suback_view->reason_code_count;

    /* Add property length */
    *total_remaining_length = *property_length + (uint32_t)local_total_remaining_length;

    return AWS_OP_SUCCESS;
}

int aws_mqtt5_encoder_begin_suback(struct aws_mqtt5_encoder *encoder, const void *packet_view) {

    const struct aws_mqtt5_packet_suback_view *suback_view = packet_view;

    uint32_t total_remaining_length = 0;
    uint32_t property_length = 0;
    if (s_compute_suback_variable_length_fields(suback_view, &total_remaining_length, &property_length)) {
        int error_code = aws_last_error();
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) mqtt5 client encoder - failed to compute variable length values for SUBACK packet with error "
            "%d(%s)",
            (void *)encoder->config.client,
            error_code,
            aws_error_debug_str(error_code));
        return AWS_OP_ERR;
    }

    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "(%p) mqtt5 client encoder - setting up encode for a SUBACK packet with remaining length %" PRIu32,
        (void *)encoder->config.client,
        total_remaining_length);

    ADD_ENCODE_STEP_U8(encoder, aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_SUBACK, 0));
    ADD_ENCODE_STEP_VLI(encoder, total_remaining_length);
    ADD_ENCODE_STEP_U16(encoder, suback_view->packet_id);
    ADD_ENCODE_STEP_VLI(encoder, property_length);

    ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
        encoder, AWS_MQTT5_PROPERTY_TYPE_REASON_STRING, suback_view->reason_string);

    aws_mqtt5_add_user_property_encoding_steps(encoder, suback_view->user_properties, suback_view->user_property_count);

    for (size_t i = 0; i < suback_view->reason_code_count; ++i) {
        ADD_ENCODE_STEP_U8(encoder, suback_view->reason_codes[i]);
    }

    return AWS_OP_SUCCESS;
}

static int s_compute_unsuback_variable_length_fields(
    const struct aws_mqtt5_packet_unsuback_view *unsuback_view,
    uint32_t *total_remaining_length,
    uint32_t *property_length) {
    /* User Properties length */
    size_t local_property_length = aws_mqtt5_compute_user_property_encode_length(
        unsuback_view->user_properties, unsuback_view->user_property_count);
    /* Optional Reason String */
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(unsuback_view->reason_string, local_property_length);

    *property_length = (uint32_t)local_property_length;

    size_t local_total_remaining_length = 0;
    if (aws_mqtt5_get_variable_length_encode_size(local_property_length, &local_total_remaining_length)) {
        return AWS_OP_ERR;
    }

    /* Packet Identifier (2 bytes) */
    local_total_remaining_length += 2;

    /* Reason Codes (1 byte each) */
    local_total_remaining_length += unsuback_view->reason_code_count;

    /* Add property length */
    *total_remaining_length = *property_length + (uint32_t)local_total_remaining_length;

    return AWS_OP_SUCCESS;
}

int aws_mqtt5_encoder_begin_unsuback(struct aws_mqtt5_encoder *encoder, const void *packet_view) {

    const struct aws_mqtt5_packet_unsuback_view *unsuback_view = packet_view;

    uint32_t total_remaining_length = 0;
    uint32_t property_length = 0;
    if (s_compute_unsuback_variable_length_fields(unsuback_view, &total_remaining_length, &property_length)) {
        int error_code = aws_last_error();
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) mqtt5 client encoder - failed to compute variable length values for UNSUBACK packet with error "
            "%d(%s)",
            (void *)encoder->config.client,
            error_code,
            aws_error_debug_str(error_code));
        return AWS_OP_ERR;
    }

    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "(%p) mqtt5 client encoder - setting up encode for an UNSUBACK packet with remaining length %" PRIu32,
        (void *)encoder->config.client,
        total_remaining_length);

    ADD_ENCODE_STEP_U8(encoder, aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_UNSUBACK, 0));
    ADD_ENCODE_STEP_VLI(encoder, total_remaining_length);
    ADD_ENCODE_STEP_U16(encoder, unsuback_view->packet_id);
    ADD_ENCODE_STEP_VLI(encoder, property_length);

    ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
        encoder, AWS_MQTT5_PROPERTY_TYPE_REASON_STRING, unsuback_view->reason_string);

    aws_mqtt5_add_user_property_encoding_steps(
        encoder, unsuback_view->user_properties, unsuback_view->user_property_count);

    for (size_t i = 0; i < unsuback_view->reason_code_count; ++i) {
        ADD_ENCODE_STEP_U8(encoder, unsuback_view->reason_codes[i]);
    }

    return AWS_OP_SUCCESS;
}

static int s_compute_puback_variable_length_fields(
    const struct aws_mqtt5_packet_puback_view *puback_view,
    uint32_t *total_remaining_length,
    uint32_t *property_length) {
    /* User Properties length */
    size_t local_property_length =
        aws_mqtt5_compute_user_property_encode_length(puback_view->user_properties, puback_view->user_property_count);
    /* Optional Reason String */
    ADD_OPTIONAL_CURSOR_PROPERTY_LENGTH(puback_view->reason_string, local_property_length);

    *property_length = (uint32_t)local_property_length;

    size_t local_total_remaining_length = 0;
    if (aws_mqtt5_get_variable_length_encode_size(local_property_length, &local_total_remaining_length)) {
        return AWS_OP_ERR;
    }

    /* Packet Identifier (2 bytes) */
    local_total_remaining_length += 2;

    /* Reason Code */
    local_total_remaining_length += 1;

    /* Add property length */
    *total_remaining_length = *property_length + (uint32_t)local_total_remaining_length;

    return AWS_OP_SUCCESS;
}

int aws_mqtt5_encoder_begin_puback(struct aws_mqtt5_encoder *encoder, const void *packet_view) {

    const struct aws_mqtt5_packet_puback_view *puback_view = packet_view;

    uint32_t total_remaining_length = 0;
    uint32_t property_length = 0;
    if (s_compute_puback_variable_length_fields(puback_view, &total_remaining_length, &property_length)) {
        int error_code = aws_last_error();
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) mqtt5 client encoder - failed to compute variable length values for PUBACK packet with error "
            "%d(%s)",
            (void *)encoder->config.client,
            error_code,
            aws_error_debug_str(error_code));
        return AWS_OP_ERR;
    }

    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "(%p) mqtt5 client encoder - setting up encode for an PUBACK packet with remaining length %" PRIu32,
        (void *)encoder->config.client,
        total_remaining_length);

    ADD_ENCODE_STEP_U8(encoder, aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_PUBACK, 0));
    ADD_ENCODE_STEP_VLI(encoder, total_remaining_length);
    ADD_ENCODE_STEP_U16(encoder, puback_view->packet_id);
    ADD_ENCODE_STEP_U8(encoder, puback_view->reason_code);
    ADD_ENCODE_STEP_VLI(encoder, property_length);
    ADD_ENCODE_STEP_OPTIONAL_CURSOR_PROPERTY(
        encoder, AWS_MQTT5_PROPERTY_TYPE_REASON_STRING, puback_view->reason_string);
    aws_mqtt5_add_user_property_encoding_steps(encoder, puback_view->user_properties, puback_view->user_property_count);

    return AWS_OP_SUCCESS;
}

void aws_mqtt5_encode_init_testing_function_table(struct aws_mqtt5_encoder_function_table *function_table) {
    *function_table = *g_aws_mqtt5_encoder_default_function_table;
    function_table->encoders_by_packet_type[AWS_MQTT5_PT_PINGRESP] = &aws_mqtt5_encoder_begin_pingresp;
    function_table->encoders_by_packet_type[AWS_MQTT5_PT_CONNACK] = &aws_mqtt5_encoder_begin_connack;
    function_table->encoders_by_packet_type[AWS_MQTT5_PT_SUBACK] = &aws_mqtt5_encoder_begin_suback;
    function_table->encoders_by_packet_type[AWS_MQTT5_PT_UNSUBACK] = &aws_mqtt5_encoder_begin_unsuback;
    function_table->encoders_by_packet_type[AWS_MQTT5_PT_PUBACK] = &aws_mqtt5_encoder_begin_puback;
}

static int s_aws_mqtt5_decoder_decode_pingreq(struct aws_mqtt5_decoder *decoder) {
    if (decoder->packet_cursor.len != 0) {
        goto error;
    }

    uint8_t expected_first_byte = aws_mqtt5_compute_fixed_header_byte1(AWS_MQTT5_PT_PINGREQ, 0);
    if (decoder->packet_first_byte != expected_first_byte || decoder->remaining_length != 0) {
        goto error;
    }

    if (decoder->options.on_packet_received != NULL) {
        (*decoder->options.on_packet_received)(AWS_MQTT5_PT_PINGREQ, NULL, decoder->options.callback_user_data);
    }

    return AWS_OP_SUCCESS;

error:

    AWS_LOGF_ERROR(
        AWS_LS_MQTT5_GENERAL, "(%p) aws_mqtt5_decoder - PINGREQ decode failure", decoder->options.callback_user_data);
    return aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
}

/* decode function for all CONNECT properties.  Movable to test-only code if we switched to a decoding function table */
static int s_read_connect_property(
    struct aws_mqtt5_packet_connect_storage *storage,
    struct aws_byte_cursor *packet_cursor) {
    int result = AWS_OP_ERR;

    uint8_t property_type = 0;
    AWS_MQTT5_DECODE_U8(packet_cursor, &property_type, done);

    struct aws_mqtt5_packet_connect_view *storage_view = &storage->storage_view;

    switch (property_type) {
        case AWS_MQTT5_PROPERTY_TYPE_SESSION_EXPIRY_INTERVAL:
            AWS_MQTT5_DECODE_U32_OPTIONAL(
                packet_cursor,
                &storage->session_expiry_interval_seconds,
                &storage_view->session_expiry_interval_seconds,
                done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_RECEIVE_MAXIMUM:
            AWS_MQTT5_DECODE_U16_OPTIONAL(
                packet_cursor, &storage->receive_maximum, &storage_view->receive_maximum, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_MAXIMUM_PACKET_SIZE:
            AWS_MQTT5_DECODE_U32_OPTIONAL(
                packet_cursor, &storage->maximum_packet_size_bytes, &storage_view->maximum_packet_size_bytes, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_TOPIC_ALIAS_MAXIMUM:
            AWS_MQTT5_DECODE_U16_OPTIONAL(
                packet_cursor, &storage->topic_alias_maximum, &storage_view->topic_alias_maximum, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_REQUEST_RESPONSE_INFORMATION:
            AWS_MQTT5_DECODE_U8_OPTIONAL(
                packet_cursor,
                &storage->request_response_information,
                &storage_view->request_response_information,
                done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_REQUEST_PROBLEM_INFORMATION:
            AWS_MQTT5_DECODE_U8_OPTIONAL(
                packet_cursor, &storage->request_problem_information, &storage_view->request_problem_information, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_AUTHENTICATION_METHOD:
            AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
                packet_cursor, &storage->authentication_method, &storage_view->authentication_method, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_AUTHENTICATION_DATA:
            AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
                packet_cursor, &storage->authentication_data, &storage_view->authentication_data, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_USER_PROPERTY:
            if (aws_mqtt5_decode_user_property(packet_cursor, &storage->user_properties)) {
                goto done;
            }
            break;

        default:
            goto done;
    }

    result = AWS_OP_SUCCESS;

done:

    if (result != AWS_OP_SUCCESS) {
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    return result;
}

/* decode function for all will properties.  Movable to test-only code if we switched to a decoding function table */
static int s_read_will_property(
    struct aws_mqtt5_packet_connect_storage *connect_storage,
    struct aws_mqtt5_packet_publish_storage *will_storage,
    struct aws_byte_cursor *packet_cursor) {
    int result = AWS_OP_ERR;

    uint8_t property_type = 0;
    AWS_MQTT5_DECODE_U8(packet_cursor, &property_type, done);

    struct aws_mqtt5_packet_connect_view *connect_storage_view = &connect_storage->storage_view;
    struct aws_mqtt5_packet_publish_view *will_storage_view = &will_storage->storage_view;

    switch (property_type) {
        case AWS_MQTT5_PROPERTY_TYPE_WILL_DELAY_INTERVAL:
            AWS_MQTT5_DECODE_U32_OPTIONAL(
                packet_cursor,
                &connect_storage->will_delay_interval_seconds,
                &connect_storage_view->will_delay_interval_seconds,
                done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_PAYLOAD_FORMAT_INDICATOR:
            AWS_MQTT5_DECODE_U8_OPTIONAL(
                packet_cursor, &will_storage->payload_format, &will_storage_view->payload_format, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_MESSAGE_EXPIRY_INTERVAL:
            AWS_MQTT5_DECODE_U32_OPTIONAL(
                packet_cursor,
                &will_storage->message_expiry_interval_seconds,
                &will_storage_view->message_expiry_interval_seconds,
                done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_CONTENT_TYPE:
            AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
                packet_cursor, &will_storage->content_type, &will_storage_view->content_type, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_RESPONSE_TOPIC:
            AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
                packet_cursor, &will_storage->response_topic, &will_storage_view->response_topic, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_CORRELATION_DATA:
            AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
                packet_cursor, &will_storage->correlation_data, &will_storage_view->correlation_data, done);
            break;

        case AWS_MQTT5_PROPERTY_TYPE_USER_PROPERTY:
            if (aws_mqtt5_decode_user_property(packet_cursor, &will_storage->user_properties)) {
                goto done;
            }
            break;

        default:
            goto done;
    }

    result = AWS_OP_SUCCESS;

done:

    if (result != AWS_OP_SUCCESS) {
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    return result;
}

/*
 * Decodes a CONNECT packet whose data must be in the scratch buffer.
 * Could be moved to test-only if we used a function table for per-packet-type decoding.
 */
static int s_aws_mqtt5_decoder_decode_connect(struct aws_mqtt5_decoder *decoder) {
    struct aws_mqtt5_packet_connect_storage connect_storage;
    struct aws_mqtt5_packet_publish_storage publish_storage;
    int result = AWS_OP_ERR;
    bool has_will = false;

    if (aws_mqtt5_packet_connect_storage_init_from_external_storage(&connect_storage, decoder->allocator)) {
        return AWS_OP_ERR;
    }

    if (aws_mqtt5_packet_publish_storage_init_from_external_storage(&publish_storage, decoder->allocator)) {
        goto done;
    }

    uint8_t first_byte = decoder->packet_first_byte;
    /* CONNECT flags must be zero by protocol */
    if ((first_byte & 0x0F) != 0) {
        goto done;
    }

    struct aws_byte_cursor packet_cursor = decoder->packet_cursor;
    if (decoder->remaining_length != (uint32_t)packet_cursor.len) {
        goto done;
    }

    struct aws_byte_cursor protocol_cursor = aws_byte_cursor_advance(&packet_cursor, 7);
    if (!aws_byte_cursor_eq(&protocol_cursor, &g_aws_mqtt5_connect_protocol_cursor)) {
        goto done;
    }

    uint8_t connect_flags = 0;
    AWS_MQTT5_DECODE_U8(&packet_cursor, &connect_flags, done);

    struct aws_mqtt5_packet_connect_view *connect_storage_view = &connect_storage.storage_view;
    struct aws_mqtt5_packet_publish_view *will_storage_view = &publish_storage.storage_view;

    connect_storage_view->clean_start = (connect_flags & AWS_MQTT5_CONNECT_FLAGS_CLEAN_START_BIT) != 0;

    AWS_MQTT5_DECODE_U16(&packet_cursor, &connect_storage_view->keep_alive_interval_seconds, done);

    uint32_t connect_property_length = 0;
    AWS_MQTT5_DECODE_VLI(&packet_cursor, &connect_property_length, done);
    if (connect_property_length > packet_cursor.len) {
        goto done;
    }

    struct aws_byte_cursor connect_property_cursor = aws_byte_cursor_advance(&packet_cursor, connect_property_length);
    while (connect_property_cursor.len > 0) {
        if (s_read_connect_property(&connect_storage, &connect_property_cursor)) {
            goto done;
        }
    }

    connect_storage_view->user_property_count = aws_mqtt5_user_property_set_size(&connect_storage.user_properties);
    connect_storage_view->user_properties = connect_storage.user_properties.properties.data;

    AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR(&packet_cursor, &connect_storage_view->client_id, done);

    has_will = (connect_flags & AWS_MQTT5_CONNECT_FLAGS_WILL_BIT) != 0;
    if (has_will) {
        uint32_t will_property_length = 0;
        AWS_MQTT5_DECODE_VLI(&packet_cursor, &will_property_length, done);
        if (will_property_length > packet_cursor.len) {
            goto done;
        }

        struct aws_byte_cursor will_property_cursor = aws_byte_cursor_advance(&packet_cursor, will_property_length);
        while (will_property_cursor.len > 0) {
            if (s_read_will_property(&connect_storage, &publish_storage, &will_property_cursor)) {
                goto done;
            }
        }

        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR(&packet_cursor, &will_storage_view->topic, done);
        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR(&packet_cursor, &will_storage_view->payload, done);

        /* apply will flags from the connect flags to the will's storage */
        will_storage_view->qos = (enum aws_mqtt5_qos)(
            (connect_flags >> AWS_MQTT5_CONNECT_FLAGS_WILL_QOS_BIT_POSITION) &
            AWS_MQTT5_CONNECT_FLAGS_WILL_QOS_BIT_MASK);
        will_storage_view->retain = (connect_flags & AWS_MQTT5_CONNECT_FLAGS_WILL_RETAIN_BIT) != 0;

        will_storage_view->user_property_count = aws_mqtt5_user_property_set_size(&publish_storage.user_properties);
        will_storage_view->user_properties = publish_storage.user_properties.properties.data;
    }

    if ((connect_flags & AWS_MQTT5_CONNECT_FLAGS_USER_NAME_BIT) != 0) {
        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
            &packet_cursor, &connect_storage.username, &connect_storage_view->username, done);
    }

    if ((connect_flags & AWS_MQTT5_CONNECT_FLAGS_PASSWORD_BIT) != 0) {
        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR_OPTIONAL(
            &packet_cursor, &connect_storage.password, &connect_storage_view->password, done);
    }

    if (packet_cursor.len == 0) {
        result = AWS_OP_SUCCESS;
    }

done:

    if (result == AWS_OP_SUCCESS) {
        if (decoder->options.on_packet_received != NULL) {
            if (has_will) {
                connect_storage.storage_view.will = &publish_storage.storage_view;
            }

            result = (*decoder->options.on_packet_received)(
                AWS_MQTT5_PT_CONNECT, &connect_storage.storage_view, decoder->options.callback_user_data);
        }
    } else {
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) aws_mqtt5_decoder - CONNECT decode failure",
            decoder->options.callback_user_data);
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    aws_mqtt5_packet_publish_storage_clean_up(&publish_storage);
    aws_mqtt5_packet_connect_storage_clean_up(&connect_storage);

    return result;
}

/* decode function for subscribe properties.  Movable to test-only code if we switched to a decoding function table */
static int s_read_subscribe_property(
    struct aws_mqtt5_packet_subscribe_storage *subscribe_storage,
    struct aws_byte_cursor *packet_cursor) {
    int result = AWS_OP_ERR;

    uint8_t property_type = 0;
    AWS_MQTT5_DECODE_U8(packet_cursor, &property_type, done);

    struct aws_mqtt5_packet_subscribe_view *storage_view = &subscribe_storage->storage_view;

    switch (property_type) {
        case AWS_MQTT5_PROPERTY_TYPE_SUBSCRIPTION_IDENTIFIER:
            AWS_MQTT5_DECODE_VLI(packet_cursor, &subscribe_storage->subscription_identifier, done);
            storage_view->subscription_identifier = &subscribe_storage->subscription_identifier;

            break;
        case AWS_MQTT5_PROPERTY_TYPE_USER_PROPERTY:
            if (aws_mqtt5_decode_user_property(packet_cursor, &subscribe_storage->user_properties)) {
                goto done;
            }
            break;

        default:
            goto done;
    }

    result = AWS_OP_SUCCESS;

done:

    if (result != AWS_OP_SUCCESS) {
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    return result;
}

/*
 * Decodes a SUBSCRIBE packet whose data must be in the scratch buffer.
 */
static int s_aws_mqtt5_decoder_decode_subscribe(struct aws_mqtt5_decoder *decoder) {
    struct aws_mqtt5_packet_subscribe_storage subscribe_storage;
    int result = AWS_OP_ERR;

    if (aws_mqtt5_packet_subscribe_storage_init_from_external_storage(&subscribe_storage, decoder->allocator)) {
        goto done;
    }

    struct aws_mqtt5_packet_subscribe_view *storage_view = &subscribe_storage.storage_view;

    /* SUBSCRIBE flags must be 2 by protocol*/
    uint8_t first_byte = decoder->packet_first_byte;
    if ((first_byte & 0x0F) != 2) {
        goto done;
    }

    struct aws_byte_cursor packet_cursor = decoder->packet_cursor;
    if (decoder->remaining_length != (uint32_t)packet_cursor.len) {
        goto done;
    }

    uint16_t packet_id = 0;
    AWS_MQTT5_DECODE_U16(&packet_cursor, &packet_id, done);
    subscribe_storage.storage_view.packet_id = packet_id;

    uint32_t property_length = 0;
    AWS_MQTT5_DECODE_VLI(&packet_cursor, &property_length, done);
    if (property_length > packet_cursor.len) {
        goto done;
    }

    struct aws_byte_cursor property_cursor = aws_byte_cursor_advance(&packet_cursor, property_length);
    while (property_cursor.len > 0) {
        if (s_read_subscribe_property(&subscribe_storage, &property_cursor)) {
            goto done;
        }
    }

    while (packet_cursor.len > 0) {
        struct aws_mqtt5_subscription_view subscription_view;
        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR(&packet_cursor, &subscription_view.topic_filter, done);

        uint8_t subscription_options = 0;
        AWS_MQTT5_DECODE_U8(&packet_cursor, &subscription_options, done);

        subscription_view.no_local = (subscription_options & AWS_MQTT5_SUBSCRIBE_FLAGS_NO_LOCAL) != 0;
        subscription_view.retain_as_published =
            (subscription_options & AWS_MQTT5_SUBSCRIBE_FLAGS_RETAIN_AS_PUBLISHED) != 0;
        subscription_view.qos = (enum aws_mqtt5_qos)(
            (subscription_options >> AWS_MQTT5_SUBSCRIBE_FLAGS_QOS_BIT_POSITION) &
            AWS_MQTT5_SUBSCRIBE_FLAGS_QOS_BIT_MASK);
        subscription_view.retain_handling_type = (enum aws_mqtt5_retain_handling_type)(
            (subscription_options >> AWS_MQTT5_SUBSCRIBE_FLAGS_RETAIN_HANDLING_TYPE_BIT_POSITION) &
            AWS_MQTT5_SUBSCRIBE_FLAGS_RETAIN_HANDLING_TYPE_BIT_MASK);

        if (aws_array_list_push_back(&subscribe_storage.subscriptions, &subscription_view)) {
            goto done;
        }
    }

    storage_view->subscription_count = aws_array_list_length(&subscribe_storage.subscriptions);
    storage_view->subscriptions = subscribe_storage.subscriptions.data;
    storage_view->user_property_count = aws_mqtt5_user_property_set_size(&subscribe_storage.user_properties);
    storage_view->user_properties = subscribe_storage.user_properties.properties.data;

    if (packet_cursor.len == 0) {
        result = AWS_OP_SUCCESS;
    }

done:

    if (result == AWS_OP_SUCCESS) {
        if (decoder->options.on_packet_received != NULL) {
            result = (*decoder->options.on_packet_received)(
                AWS_MQTT5_PT_SUBSCRIBE, &subscribe_storage.storage_view, decoder->options.callback_user_data);
        }
    } else {
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) aws_mqtt5_decoder - SUBSCRIBE decode failure",
            decoder->options.callback_user_data);
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    aws_mqtt5_packet_subscribe_storage_clean_up(&subscribe_storage);

    return result;
}

/* decode function for unsubscribe properties.  Movable to test-only code if we switched to a decoding function table */
static int s_read_unsubscribe_property(
    struct aws_mqtt5_packet_unsubscribe_storage *unsubscribe_storage,
    struct aws_byte_cursor *packet_cursor) {
    int result = AWS_OP_ERR;

    uint8_t property_type = 0;
    AWS_MQTT5_DECODE_U8(packet_cursor, &property_type, done);

    switch (property_type) {
        case AWS_MQTT5_PROPERTY_TYPE_USER_PROPERTY:
            if (aws_mqtt5_decode_user_property(packet_cursor, &unsubscribe_storage->user_properties)) {
                goto done;
            }
            break;

        default:
            goto done;
    }

    result = AWS_OP_SUCCESS;

done:

    if (result != AWS_OP_SUCCESS) {
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    return result;
}

/*
 * Decodes an UNSUBSCRIBE packet whose data must be in the scratch buffer.
 */
static int s_aws_mqtt5_decoder_decode_unsubscribe(struct aws_mqtt5_decoder *decoder) {
    struct aws_mqtt5_packet_unsubscribe_storage unsubscribe_storage;
    int result = AWS_OP_ERR;

    if (aws_mqtt5_packet_unsubscribe_storage_init_from_external_storage(&unsubscribe_storage, decoder->allocator)) {
        goto done;
    }

    struct aws_mqtt5_packet_unsubscribe_view *storage_view = &unsubscribe_storage.storage_view;

    /* UNSUBSCRIBE flags must be 2 by protocol*/
    uint8_t first_byte = decoder->packet_first_byte;
    if ((first_byte & 0x0F) != 2) {
        goto done;
    }

    struct aws_byte_cursor packet_cursor = decoder->packet_cursor;
    if (decoder->remaining_length != (uint32_t)packet_cursor.len) {
        goto done;
    }

    uint16_t packet_id = 0;
    AWS_MQTT5_DECODE_U16(&packet_cursor, &packet_id, done);
    unsubscribe_storage.storage_view.packet_id = packet_id;

    uint32_t property_length = 0;
    AWS_MQTT5_DECODE_VLI(&packet_cursor, &property_length, done);
    if (property_length > packet_cursor.len) {
        goto done;
    }

    struct aws_byte_cursor property_cursor = aws_byte_cursor_advance(&packet_cursor, property_length);
    while (property_cursor.len > 0) {
        if (s_read_unsubscribe_property(&unsubscribe_storage, &property_cursor)) {
            goto done;
        }
    }

    while (packet_cursor.len > 0) {
        struct aws_byte_cursor topic;
        AWS_MQTT5_DECODE_LENGTH_PREFIXED_CURSOR(&packet_cursor, &topic, done);
        if (aws_array_list_push_back(&unsubscribe_storage.topic_filters, &topic)) {
            goto done;
        }
    }

    storage_view->topic_filter_count = aws_array_list_length(&unsubscribe_storage.topic_filters);
    storage_view->topic_filters = unsubscribe_storage.topic_filters.data;
    storage_view->user_property_count = aws_mqtt5_user_property_set_size(&unsubscribe_storage.user_properties);
    storage_view->user_properties = unsubscribe_storage.user_properties.properties.data;

    result = AWS_OP_SUCCESS;

done:

    if (result == AWS_OP_SUCCESS) {
        if (decoder->options.on_packet_received != NULL) {
            result = (*decoder->options.on_packet_received)(
                AWS_MQTT5_PT_UNSUBSCRIBE, &unsubscribe_storage.storage_view, decoder->options.callback_user_data);
        }
    } else {
        AWS_LOGF_ERROR(
            AWS_LS_MQTT5_GENERAL,
            "(%p) aws_mqtt5_decoder - UNSUBSCRIBE decode failure",
            decoder->options.callback_user_data);
        aws_raise_error(AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR);
    }

    aws_mqtt5_packet_unsubscribe_storage_clean_up(&unsubscribe_storage);

    return result;
}

void aws_mqtt5_decode_init_testing_function_table(struct aws_mqtt5_decoder_function_table *function_table) {
    *function_table = *g_aws_mqtt5_default_decoder_table;
    function_table->decoders_by_packet_type[AWS_MQTT5_PT_PINGREQ] = &s_aws_mqtt5_decoder_decode_pingreq;
    function_table->decoders_by_packet_type[AWS_MQTT5_PT_CONNECT] = &s_aws_mqtt5_decoder_decode_connect;
    function_table->decoders_by_packet_type[AWS_MQTT5_PT_SUBSCRIBE] = &s_aws_mqtt5_decoder_decode_subscribe;
    function_table->decoders_by_packet_type[AWS_MQTT5_PT_UNSUBSCRIBE] = &s_aws_mqtt5_decoder_decode_unsubscribe;
}

static int s_aws_mqtt5_mock_test_fixture_on_packet_received_fn(
    enum aws_mqtt5_packet_type type,
    void *packet_view,
    void *decoder_callback_user_data) {

    struct aws_mqtt5_mock_server_packet_record packet_record;
    AWS_ZERO_STRUCT(packet_record);

    struct aws_mqtt5_server_mock_connection_context *server_connection = decoder_callback_user_data;
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = server_connection->test_fixture;

    switch (type) {
        case AWS_MQTT5_PT_CONNECT:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_connect_storage));
            aws_mqtt5_packet_connect_storage_init(packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        case AWS_MQTT5_PT_DISCONNECT:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_disconnect_storage));
            aws_mqtt5_packet_disconnect_storage_init(
                packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        case AWS_MQTT5_PT_SUBSCRIBE:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_subscribe_storage));
            aws_mqtt5_packet_subscribe_storage_init(packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        case AWS_MQTT5_PT_UNSUBSCRIBE:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_unsubscribe_storage));
            aws_mqtt5_packet_unsubscribe_storage_init(
                packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        case AWS_MQTT5_PT_PUBLISH:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_publish_storage));
            aws_mqtt5_packet_publish_storage_init(packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        case AWS_MQTT5_PT_PUBACK:
            packet_record.packet_storage =
                aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_packet_puback_storage));
            aws_mqtt5_packet_puback_storage_init(packet_record.packet_storage, test_fixture->allocator, packet_view);
            break;

        default:
            break;
    }

    packet_record.storage_allocator = test_fixture->allocator;
    packet_record.timestamp = (*test_fixture->client_vtable.get_current_time_fn)();
    packet_record.packet_type = type;

    aws_mutex_lock(&test_fixture->lock);
    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL, "mqtt5 mock server received packet of type %s", aws_mqtt5_packet_type_to_c_string(type));
    aws_array_list_push_back(&test_fixture->server_received_packets, &packet_record);
    aws_mutex_unlock(&test_fixture->lock);
    aws_condition_variable_notify_all(&test_fixture->signal);

    int result = AWS_OP_SUCCESS;
    aws_mqtt5_on_mock_server_packet_received_fn *packet_handler =
        test_fixture->server_function_table->packet_handlers[type];
    if (packet_handler != NULL) {
        result =
            (*packet_handler)(packet_view, server_connection, server_connection->test_fixture->mock_server_user_data);
    }

    return result;
}

static int s_process_read_message(
    struct aws_channel_handler *handler,
    struct aws_channel_slot *slot,
    struct aws_io_message *message) {

    struct aws_mqtt5_server_mock_connection_context *server_connection = handler->impl;

    if (message->message_type != AWS_IO_MESSAGE_APPLICATION_DATA) {
        return AWS_OP_ERR;
    }

    struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);

    int result = aws_mqtt5_decoder_on_data_received(&server_connection->decoder, message_cursor);
    if (result != AWS_OP_SUCCESS) {
        aws_channel_shutdown(server_connection->channel, aws_last_error());
        goto done;
    }

    aws_channel_slot_increment_read_window(slot, message->message_data.len);

done:

    aws_mem_release(message->allocator, message);

    return AWS_OP_SUCCESS;
}

static int s_shutdown(
    struct aws_channel_handler *handler,
    struct aws_channel_slot *slot,
    enum aws_channel_direction dir,
    int error_code,
    bool free_scarce_resources_immediately) {

    (void)handler;

    return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
}

static size_t s_initial_window_size(struct aws_channel_handler *handler) {
    (void)handler;

    return SIZE_MAX;
}

static void s_destroy(struct aws_channel_handler *handler) {
    struct aws_mqtt5_server_mock_connection_context *server_connection = handler->impl;

    aws_event_loop_cancel_task(
        aws_channel_get_event_loop(server_connection->channel), &server_connection->service_task);

    aws_mqtt5_decoder_clean_up(&server_connection->decoder);
    aws_mqtt5_encoder_clean_up(&server_connection->encoder);
    aws_mqtt5_inbound_topic_alias_resolver_clean_up(&server_connection->inbound_alias_resolver);

    aws_mem_release(server_connection->allocator, server_connection);
}

static size_t s_message_overhead(struct aws_channel_handler *handler) {
    (void)handler;

    return 0;
}

static struct aws_channel_handler_vtable s_mqtt5_mock_server_channel_handler_vtable = {
    .process_read_message = &s_process_read_message,
    .process_write_message = NULL,
    .increment_read_window = NULL,
    .shutdown = &s_shutdown,
    .initial_window_size = &s_initial_window_size,
    .message_overhead = &s_message_overhead,
    .destroy = &s_destroy,
};

static void s_mock_server_service_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
    if (status != AWS_TASK_STATUS_RUN_READY) {
        return;
    }

    struct aws_mqtt5_server_mock_connection_context *server_connection = arg;

    aws_mqtt5_mock_server_service_fn *service_fn =
        server_connection->test_fixture->server_function_table->service_task_fn;
    if (service_fn != NULL) {
        (*service_fn)(server_connection, server_connection->test_fixture->mock_server_user_data);
    }

    uint64_t now = 0;
    aws_high_res_clock_get_ticks(&now);
    uint64_t next_service_time = now + aws_timestamp_convert(1, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);

    aws_event_loop_schedule_task_future(
        aws_channel_get_event_loop(server_connection->channel), task, next_service_time);
}

static void s_on_incoming_channel_setup_fn(
    struct aws_server_bootstrap *bootstrap,
    int error_code,
    struct aws_channel *channel,
    void *user_data) {
    (void)bootstrap;
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = user_data;

    if (!error_code) {
        struct aws_channel_slot *test_handler_slot = aws_channel_slot_new(channel);
        aws_channel_slot_insert_end(channel, test_handler_slot);

        struct aws_mqtt5_server_mock_connection_context *server_connection =
            aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_server_mock_connection_context));
        server_connection->allocator = test_fixture->allocator;
        server_connection->channel = channel;
        server_connection->test_fixture = test_fixture;
        server_connection->slot = test_handler_slot;
        server_connection->handler.alloc = server_connection->allocator;
        server_connection->handler.vtable = &s_mqtt5_mock_server_channel_handler_vtable;
        server_connection->handler.impl = server_connection;

        aws_task_init(
            &server_connection->service_task,
            s_mock_server_service_task_fn,
            server_connection,
            "mock_server_service_task_fn");
        aws_event_loop_schedule_task_now(aws_channel_get_event_loop(channel), &server_connection->service_task);

        aws_channel_slot_set_handler(server_connection->slot, &server_connection->handler);

        aws_mqtt5_encode_init_testing_function_table(&server_connection->encoding_table);

        struct aws_mqtt5_encoder_options encoder_options = {
            .client = NULL,
            .encoders = &server_connection->encoding_table,
        };

        aws_mqtt5_encoder_init(&server_connection->encoder, server_connection->allocator, &encoder_options);

        aws_mqtt5_decode_init_testing_function_table(&server_connection->decoding_table);

        struct aws_mqtt5_decoder_options decoder_options = {
            .callback_user_data = server_connection,
            .on_packet_received = s_aws_mqtt5_mock_test_fixture_on_packet_received_fn,
            .decoder_table = &server_connection->decoding_table,
        };

        aws_mqtt5_decoder_init(&server_connection->decoder, server_connection->allocator, &decoder_options);
        aws_mqtt5_inbound_topic_alias_resolver_init(
            &server_connection->inbound_alias_resolver, server_connection->allocator);
        aws_mqtt5_inbound_topic_alias_resolver_reset(
            &server_connection->inbound_alias_resolver, test_fixture->maximum_inbound_topic_aliases);
        aws_mqtt5_decoder_set_inbound_topic_alias_resolver(
            &server_connection->decoder, &server_connection->inbound_alias_resolver);

        aws_mutex_lock(&test_fixture->lock);
        test_fixture->server_channel = channel;
        aws_mutex_unlock(&test_fixture->lock);

        /*
         * Just like the tls tests in aws-c-io, it's possible for the server channel setup to execute after the client
         * channel setup has already posted data to the socket.  In this case, the read notification gets lost because
         * the server hasn't subscribed to it yet and then we hang and time out.  So do the same thing we do for
         * tls server channel setup and force a read of the socket after we're fully initialized.
         */
        aws_channel_trigger_read(channel);
    }
}

static void s_on_incoming_channel_shutdown_fn(
    struct aws_server_bootstrap *bootstrap,
    int error_code,
    struct aws_channel *channel,
    void *user_data) {
    (void)bootstrap;
    (void)error_code;
    (void)channel;
    (void)user_data;
}

static void s_on_listener_destroy(struct aws_server_bootstrap *bootstrap, void *user_data) {
    (void)bootstrap;
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = user_data;
    aws_mutex_lock(&test_fixture->lock);
    test_fixture->listener_destroyed = true;
    aws_mutex_unlock(&test_fixture->lock);
    aws_condition_variable_notify_one(&test_fixture->signal);
}

static bool s_is_listener_destroyed(void *arg) {
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = arg;
    return test_fixture->listener_destroyed;
}

static void s_wait_on_listener_cleanup(struct aws_mqtt5_client_mock_test_fixture *test_fixture) {
    aws_mutex_lock(&test_fixture->lock);
    aws_condition_variable_wait_pred(&test_fixture->signal, &test_fixture->lock, s_is_listener_destroyed, test_fixture);
    aws_mutex_unlock(&test_fixture->lock);
}

static bool s_has_client_terminated(void *arg) {
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = arg;
    return test_fixture->client_terminated;
}

static void s_wait_for_client_terminated(struct aws_mqtt5_client_mock_test_fixture *test_context) {
    aws_mutex_lock(&test_context->lock);
    aws_condition_variable_wait_pred(&test_context->signal, &test_context->lock, s_has_client_terminated, test_context);
    aws_mutex_unlock(&test_context->lock);
}

void s_aws_mqtt5_test_fixture_lifecycle_event_handler(const struct aws_mqtt5_client_lifecycle_event *event) {
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = event->user_data;

    struct aws_mqtt5_lifecycle_event_record *record =
        aws_mem_calloc(test_fixture->allocator, 1, sizeof(struct aws_mqtt5_lifecycle_event_record));
    record->allocator = test_fixture->allocator;
    aws_high_res_clock_get_ticks(&record->timestamp);
    record->event = *event;

    if (event->settings != NULL) {
        record->settings_storage = *event->settings;
        record->event.settings = &record->settings_storage;
    }

    if (event->disconnect_data != NULL) {
        aws_mqtt5_packet_disconnect_storage_init(
            &record->disconnect_storage, record->allocator, event->disconnect_data);
        record->event.disconnect_data = &record->disconnect_storage.storage_view;
    }

    if (event->connack_data != NULL) {
        aws_mqtt5_packet_connack_storage_init(&record->connack_storage, record->allocator, event->connack_data);
        record->event.connack_data = &record->connack_storage.storage_view;
    }

    aws_mutex_lock(&test_fixture->lock);
    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "mqtt5 mock server received lifecycle event of type %s",
        aws_mqtt5_client_lifecycle_event_type_to_c_string(event->event_type));
    aws_array_list_push_back(&test_fixture->lifecycle_events, &record);
    aws_mutex_unlock(&test_fixture->lock);
    aws_condition_variable_notify_all(&test_fixture->signal);

    aws_mqtt5_client_connection_event_callback_fn *event_callback = test_fixture->original_lifecycle_event_handler;
    if (event_callback != NULL) {
        struct aws_mqtt5_client_lifecycle_event event_copy = *event;
        event_copy.user_data = test_fixture->original_lifecycle_event_handler_user_data;

        (*event_callback)(&event_copy);
    }
}

void s_aws_mqtt5_test_fixture_state_changed_callback(
    struct aws_mqtt5_client *client,
    enum aws_mqtt5_client_state old_state,
    enum aws_mqtt5_client_state new_state,
    void *vtable_user_data) {
    (void)old_state;
    (void)client;

    struct aws_mqtt5_client_mock_test_fixture *test_fixture = vtable_user_data;

    aws_mutex_lock(&test_fixture->lock);
    AWS_LOGF_DEBUG(
        AWS_LS_MQTT5_GENERAL,
        "mqtt5 mock server received client state change to %s",
        aws_mqtt5_client_state_to_c_string(new_state));
    aws_array_list_push_back(&test_fixture->client_states, &new_state);
    aws_mutex_unlock(&test_fixture->lock);
}

static void s_aws_mqtt5_test_fixture_statistics_changed_callback(
    struct aws_mqtt5_client *client,
    struct aws_mqtt5_operation *operation,
    void *vtable_user_data) {
    (void)operation;

    struct aws_mqtt5_client_mock_test_fixture *test_fixture = vtable_user_data;

    struct aws_mqtt5_client_operation_statistics stats;
    AWS_ZERO_STRUCT(stats);

    aws_mutex_lock(&test_fixture->lock);
    aws_mqtt5_client_get_stats(client, &stats);
    aws_array_list_push_back(&test_fixture->client_statistics, &stats);
    aws_mutex_unlock(&test_fixture->lock);
}

static void s_on_test_client_termination(void *user_data) {
    struct aws_mqtt5_client_mock_test_fixture *test_fixture = user_data;

    aws_mutex_lock(&test_fixture->lock);
    test_fixture->client_terminated = true;
    aws_mutex_unlock(&test_fixture->lock);
    aws_condition_variable_notify_all(&test_fixture->signal);
}

int aws_mqtt5_client_mock_test_fixture_init(
    struct aws_mqtt5_client_mock_test_fixture *test_fixture,
    struct aws_allocator *allocator,
    struct aws_mqtt5_client_mqtt5_mock_test_fixture_options *options) {

    AWS_ZERO_STRUCT(*test_fixture);

    test_fixture->allocator = allocator;

    aws_mutex_init(&test_fixture->lock);
    aws_condition_variable_init(&test_fixture->signal);

    test_fixture->server_function_table = options->server_function_table;
    test_fixture->mock_server_user_data = options->mock_server_user_data;

    struct aws_socket_options socket_options = {
        .connect_timeout_ms = 1000,
        .domain = AWS_SOCKET_LOCAL,
    };

    test_fixture->socket_options = socket_options;
    test_fixture->server_elg = aws_event_loop_group_new_default(allocator, 1, NULL);
    test_fixture->server_bootstrap = aws_server_bootstrap_new(allocator, test_fixture->server_elg);

    test_fixture->client_elg = aws_event_loop_group_new_default(allocator, 4, NULL);
    struct aws_host_resolver_default_options resolver_options = {
        .el_group = test_fixture->client_elg,
        .max_entries = 1,
    };
    test_fixture->host_resolver = aws_host_resolver_new_default(allocator, &resolver_options);

    struct aws_client_bootstrap_options bootstrap_options = {
        .event_loop_group = test_fixture->client_elg,
        .user_data = test_fixture,
        .host_resolver = test_fixture->host_resolver,
    };

    test_fixture->client_bootstrap = aws_client_bootstrap_new(allocator, &bootstrap_options);

    aws_socket_endpoint_init_local_address_for_test(&test_fixture->endpoint);

    struct aws_server_socket_channel_bootstrap_options server_bootstrap_options = {
        .bootstrap = test_fixture->server_bootstrap,
        .host_name = test_fixture->endpoint.address,
        .port = test_fixture->endpoint.port,
        .socket_options = &test_fixture->socket_options,
        .incoming_callback = s_on_incoming_channel_setup_fn,
        .shutdown_callback = s_on_incoming_channel_shutdown_fn,
        .destroy_callback = s_on_listener_destroy,
        .user_data = test_fixture,
    };
    test_fixture->listener = aws_server_bootstrap_new_socket_listener(&server_bootstrap_options);

    test_fixture->original_lifecycle_event_handler = options->client_options->lifecycle_event_handler;
    test_fixture->original_lifecycle_event_handler_user_data =
        options->client_options->lifecycle_event_handler_user_data;
    options->client_options->lifecycle_event_handler = &s_aws_mqtt5_test_fixture_lifecycle_event_handler;
    options->client_options->lifecycle_event_handler_user_data = test_fixture;

    options->client_options->host_name = aws_byte_cursor_from_c_str(test_fixture->endpoint.address);
    options->client_options->port = test_fixture->endpoint.port;
    options->client_options->socket_options = &test_fixture->socket_options;
    options->client_options->bootstrap = test_fixture->client_bootstrap;

    options->client_options->client_termination_handler = s_on_test_client_termination;
    options->client_options->client_termination_handler_user_data = test_fixture;

    test_fixture->client = aws_mqtt5_client_new(allocator, options->client_options);

    test_fixture->client_vtable = *aws_mqtt5_client_get_default_vtable();
    test_fixture->client_vtable.on_client_state_change_callback_fn = s_aws_mqtt5_test_fixture_state_changed_callback;
    test_fixture->client_vtable.on_client_statistics_changed_callback_fn =
        s_aws_mqtt5_test_fixture_statistics_changed_callback;
    test_fixture->client_vtable.vtable_user_data = test_fixture;

    aws_mqtt5_client_set_vtable(test_fixture->client, &test_fixture->client_vtable);

    aws_array_list_init_dynamic(
        &test_fixture->server_received_packets, allocator, 10, sizeof(struct aws_mqtt5_mock_server_packet_record));

    aws_array_list_init_dynamic(
        &test_fixture->lifecycle_events, allocator, 10, sizeof(struct aws_mqtt5_lifecycle_event_record *));

    aws_array_list_init_dynamic(&test_fixture->client_states, allocator, 10, sizeof(enum aws_mqtt5_client_state));
    aws_array_list_init_dynamic(
        &test_fixture->client_statistics, allocator, 10, sizeof(struct aws_mqtt5_client_operation_statistics));

    return AWS_OP_SUCCESS;
}

static void s_destroy_packet_storage(
    void *packet_storage,
    struct aws_allocator *allocator,
    enum aws_mqtt5_packet_type packet_type) {
    switch (packet_type) {
        case AWS_MQTT5_PT_CONNECT:
            aws_mqtt5_packet_connect_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_DISCONNECT:
            aws_mqtt5_packet_disconnect_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_SUBSCRIBE:
            aws_mqtt5_packet_subscribe_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_SUBACK:
            aws_mqtt5_packet_suback_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_UNSUBSCRIBE:
            aws_mqtt5_packet_unsubscribe_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_UNSUBACK:
            aws_mqtt5_packet_unsuback_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_PUBLISH:
            aws_mqtt5_packet_publish_storage_clean_up(packet_storage);
            break;

        case AWS_MQTT5_PT_PUBACK:
            /* TODO */
            break;

        case AWS_MQTT5_PT_PINGREQ:
            AWS_FATAL_ASSERT(packet_storage == NULL);
            break;

        default:
            AWS_FATAL_ASSERT(false);
    }

    if (packet_storage != NULL) {
        aws_mem_release(allocator, packet_storage);
    }
}

static void s_destroy_lifecycle_event_storage(struct aws_mqtt5_lifecycle_event_record *event) {
    aws_mqtt5_packet_connack_storage_clean_up(&event->connack_storage);
    aws_mqtt5_packet_disconnect_storage_clean_up(&event->disconnect_storage);

    aws_mem_release(event->allocator, event);
}

void aws_mqtt5_client_mock_test_fixture_clean_up(struct aws_mqtt5_client_mock_test_fixture *test_fixture) {
    aws_mqtt5_client_release(test_fixture->client);
    s_wait_for_client_terminated(test_fixture);
    aws_client_bootstrap_release(test_fixture->client_bootstrap);
    aws_host_resolver_release(test_fixture->host_resolver);
    aws_server_bootstrap_destroy_socket_listener(test_fixture->server_bootstrap, test_fixture->listener);

    s_wait_on_listener_cleanup(test_fixture);

    aws_server_bootstrap_release(test_fixture->server_bootstrap);
    aws_event_loop_group_release(test_fixture->server_elg);
    aws_event_loop_group_release(test_fixture->client_elg);

    aws_thread_join_all_managed();

    for (size_t i = 0; i < aws_array_list_length(&test_fixture->server_received_packets); ++i) {
        struct aws_mqtt5_mock_server_packet_record *packet = NULL;
        aws_array_list_get_at_ptr(&test_fixture->server_received_packets, (void **)&packet, i);

        s_destroy_packet_storage(packet->packet_storage, packet->storage_allocator, packet->packet_type);
    }

    aws_array_list_clean_up(&test_fixture->server_received_packets);

    for (size_t i = 0; i < aws_array_list_length(&test_fixture->lifecycle_events); ++i) {
        struct aws_mqtt5_lifecycle_event_record *event = NULL;
        aws_array_list_get_at(&test_fixture->lifecycle_events, &event, i);

        s_destroy_lifecycle_event_storage(event);
    }

    aws_array_list_clean_up(&test_fixture->lifecycle_events);
    aws_array_list_clean_up(&test_fixture->client_states);
    aws_array_list_clean_up(&test_fixture->client_statistics);

    aws_mutex_clean_up(&test_fixture->lock);
    aws_condition_variable_clean_up(&test_fixture->signal);
}

#define AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs, rhs)                                                               \
    if ((lhs) != (rhs)) {                                                                                              \
        return false;                                                                                                  \
    }

#define AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs, rhs)                                                      \
    if (((lhs) != NULL) != ((rhs) != NULL)) {                                                                          \
        return false;                                                                                                  \
    }                                                                                                                  \
    if (((lhs) != NULL) && ((rhs) != NULL) && (*(lhs) != *(rhs))) {                                                    \
        return false;                                                                                                  \
    }

#define AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs, rhs)                                                            \
    if (!aws_byte_cursor_eq(&(lhs), &(rhs))) {                                                                         \
        return false;                                                                                                  \
    }

#define AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs, rhs)                                                   \
    if (((lhs) != NULL) != ((rhs) != NULL)) {                                                                          \
        return false;                                                                                                  \
    }                                                                                                                  \
    if (((lhs) != NULL) && ((rhs) != NULL) && (!aws_byte_cursor_eq(lhs, rhs))) {                                       \
        return false;                                                                                                  \
    }

#define AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(lhs_props, lhs_prop_count, rhs_props, rhs_prop_count)              \
    if (aws_mqtt5_test_verify_user_properties_raw((lhs_prop_count), (lhs_props), (rhs_prop_count), (rhs_props)) !=     \
        AWS_OP_SUCCESS) {                                                                                              \
        return false;                                                                                                  \
    }

static bool s_aws_publish_packets_equal(
    const struct aws_mqtt5_packet_publish_view *lhs,
    const struct aws_mqtt5_packet_publish_view *rhs) {

    // Don't check packet id intentionally

    AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs->payload, rhs->payload);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->qos, rhs->qos);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->duplicate, rhs->duplicate);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->retain, rhs->retain);
    AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs->topic, rhs->topic);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->payload_format, rhs->payload_format);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(
        lhs->message_expiry_interval_seconds, rhs->message_expiry_interval_seconds);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->topic_alias, rhs->topic_alias);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->response_topic, rhs->response_topic);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->correlation_data, rhs->correlation_data);

    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->subscription_identifier_count, rhs->subscription_identifier_count);
    for (size_t i = 0; i < lhs->subscription_identifier_count; ++i) {
        AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->subscription_identifiers[i], rhs->subscription_identifiers[i]);
    }

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    return true;
}

static bool s_aws_connect_packets_equal(
    const struct aws_mqtt5_packet_connect_view *lhs,
    const struct aws_mqtt5_packet_connect_view *rhs) {
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->keep_alive_interval_seconds, rhs->keep_alive_interval_seconds);
    AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs->client_id, rhs->client_id);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->username, rhs->username);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->password, rhs->password);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->clean_start, rhs->clean_start);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(
        lhs->session_expiry_interval_seconds, rhs->session_expiry_interval_seconds);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(
        lhs->request_response_information, rhs->request_response_information);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->request_problem_information, rhs->request_problem_information);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->receive_maximum, rhs->receive_maximum);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->topic_alias_maximum, rhs->topic_alias_maximum);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->maximum_packet_size_bytes, rhs->maximum_packet_size_bytes);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->will_delay_interval_seconds, rhs->will_delay_interval_seconds);

    if ((lhs->will != NULL) != (rhs->will != NULL)) {
        return false;
    }

    if (lhs->will) {
        if (!s_aws_publish_packets_equal(lhs->will, rhs->will)) {
            return false;
        }
    }

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->authentication_method, rhs->authentication_method);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->authentication_data, rhs->authentication_data);

    return true;
}

static bool s_aws_disconnect_packets_equal(
    const struct aws_mqtt5_packet_disconnect_view *lhs,
    const struct aws_mqtt5_packet_disconnect_view *rhs) {

    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->reason_code, rhs->reason_code);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->reason_string, rhs->reason_string);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(
        lhs->session_expiry_interval_seconds, rhs->session_expiry_interval_seconds);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->server_reference, rhs->server_reference);

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    return true;
}

static bool s_are_subscription_views_equal(
    const struct aws_mqtt5_subscription_view *lhs,
    const struct aws_mqtt5_subscription_view *rhs) {
    AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs->topic_filter, rhs->topic_filter);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->qos, rhs->qos);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->no_local, rhs->no_local);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->retain_as_published, rhs->retain_as_published);
    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->retain_handling_type, rhs->retain_handling_type);

    return true;
}

static bool s_aws_subscribe_packets_equal(
    const struct aws_mqtt5_packet_subscribe_view *lhs,
    const struct aws_mqtt5_packet_subscribe_view *rhs) {

    // Don't check packet id intentionally

    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->subscription_count, rhs->subscription_count);
    for (size_t i = 0; i < lhs->subscription_count; ++i) {
        const struct aws_mqtt5_subscription_view *lhs_sub_view = &lhs->subscriptions[i];
        const struct aws_mqtt5_subscription_view *rhs_sub_view = &rhs->subscriptions[i];

        if (!s_are_subscription_views_equal(lhs_sub_view, rhs_sub_view)) {
            return false;
        }
    }

    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_INT_EQUALS(lhs->subscription_identifier, rhs->subscription_identifier);

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    return true;
}

static bool s_aws_unsubscribe_packets_equal(
    const struct aws_mqtt5_packet_unsubscribe_view *lhs,
    const struct aws_mqtt5_packet_unsubscribe_view *rhs) {

    // Don't check packet id intentionally

    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->topic_filter_count, rhs->topic_filter_count);
    for (size_t i = 0; i < lhs->topic_filter_count; ++i) {
        struct aws_byte_cursor lhs_topic_filter = lhs->topic_filters[i];
        struct aws_byte_cursor rhs_topic_filter = rhs->topic_filters[i];

        AWS_MQTT5_CLIENT_TEST_CHECK_CURSOR_EQUALS(lhs_topic_filter, rhs_topic_filter);
    }

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    return true;
}

static bool s_aws_puback_packets_equal(
    const struct aws_mqtt5_packet_puback_view *lhs,
    const struct aws_mqtt5_packet_puback_view *rhs) {

    // Don't check packet id intentionally

    AWS_MQTT5_CLIENT_TEST_CHECK_INT_EQUALS(lhs->reason_code, rhs->reason_code);
    AWS_MQTT5_CLIENT_TEST_CHECK_OPTIONAL_CURSOR_EQUALS(lhs->reason_string, rhs->reason_string);

    AWS_MQTT5_CLIENT_TEST_CHECK_USER_PROPERTIES(
        lhs->user_properties, lhs->user_property_count, rhs->user_properties, rhs->user_property_count);

    return true;
}

bool aws_mqtt5_client_test_are_packets_equal(
    enum aws_mqtt5_packet_type packet_type,
    void *lhs_packet_storage,
    void *rhs_packet_storage) {
    switch (packet_type) {
        case AWS_MQTT5_PT_CONNECT:
            return s_aws_connect_packets_equal(
                &((struct aws_mqtt5_packet_connect_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_connect_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_DISCONNECT:
            return s_aws_disconnect_packets_equal(
                &((struct aws_mqtt5_packet_disconnect_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_disconnect_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_SUBSCRIBE:
            return s_aws_subscribe_packets_equal(
                &((struct aws_mqtt5_packet_subscribe_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_subscribe_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_UNSUBSCRIBE:
            return s_aws_unsubscribe_packets_equal(
                &((struct aws_mqtt5_packet_unsubscribe_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_unsubscribe_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_PUBLISH:
            return s_aws_publish_packets_equal(
                &((struct aws_mqtt5_packet_publish_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_publish_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_PUBACK:
            return s_aws_puback_packets_equal(
                &((struct aws_mqtt5_packet_puback_storage *)lhs_packet_storage)->storage_view,
                &((struct aws_mqtt5_packet_puback_storage *)rhs_packet_storage)->storage_view);

        case AWS_MQTT5_PT_PINGREQ:
        case AWS_MQTT5_PT_PINGRESP:
            return true;

        default:
            return false;
    }
}

size_t aws_mqtt5_linked_list_length(struct aws_linked_list *list) {
    size_t length = 0;
    struct aws_linked_list_node *node = aws_linked_list_begin(list);
    while (node != aws_linked_list_end(list)) {
        ++length;
        node = aws_linked_list_next(node);
    }

    return length;
}