aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/restricted/aws/aws-c-event-stream/source/event_stream.c
blob: 224690f1009123a6b1f197226e77f7aab7a356eb (plain) (blame)
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
/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#include <aws/event-stream/event_stream.h>

#include <aws/checksums/crc.h>

#include <aws/common/encoding.h>
#include <aws/io/io.h>

#include <inttypes.h>

#define LIB_NAME "libaws-c-event-stream"

#if _MSC_VER
#    pragma warning(push)
#    pragma warning(disable : 4221) /* aggregate initializer using local variable addresses */
#    pragma warning(disable : 4204) /* non-constant aggregate initializer */
#    pragma warning(disable : 4306) /* msft doesn't trust us to do pointer arithmetic. */
#endif

static struct aws_error_info s_errors[] = {
    AWS_DEFINE_ERROR_INFO(AWS_ERROR_EVENT_STREAM_BUFFER_LENGTH_MISMATCH, "Buffer length mismatch", LIB_NAME),
    AWS_DEFINE_ERROR_INFO(AWS_ERROR_EVENT_STREAM_INSUFFICIENT_BUFFER_LEN, "insufficient buffer length", LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED,
        "a field for the message was too large",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(AWS_ERROR_EVENT_STREAM_PRELUDE_CHECKSUM_FAILURE, "prelude checksum was incorrect", LIB_NAME),
    AWS_DEFINE_ERROR_INFO(AWS_ERROR_EVENT_STREAM_MESSAGE_CHECKSUM_FAILURE, "message checksum was incorrect", LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_MESSAGE_INVALID_HEADERS_LEN,
        "message headers length was incorrect",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_MESSAGE_UNKNOWN_HEADER_TYPE,
        "An unknown header type was encountered",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_MESSAGE_PARSER_ILLEGAL_STATE,
        "message parser encountered an illegal state",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_RPC_CONNECTION_CLOSED,
        "event stream rpc connection has been closed",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR,
        "event stream rpc connection has encountered a protocol error",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_RPC_STREAM_CLOSED,
        "event stream rpc connection stream is closed.",
        LIB_NAME),
    AWS_DEFINE_ERROR_INFO(
        AWS_ERROR_EVENT_STREAM_RPC_STREAM_NOT_ACTIVATED,
        "event stream rpc stream continuation was not successfully activated before use. Call "
        "aws_event_stream_rpc_client_continuation_activate()"
        " before using a stream continuation token.",
        LIB_NAME),
};

static struct aws_error_info_list s_list = {
    .error_list = s_errors,
    .count = sizeof(s_errors) / sizeof(struct aws_error_info),
};

static bool s_event_stream_library_initialized = false;

static struct aws_log_subject_info s_event_stream_log_subject_infos[] = {
    DEFINE_LOG_SUBJECT_INFO(
        AWS_LS_EVENT_STREAM_GENERAL,
        "event-stream-general",
        "Subject for aws-c-event-stream logging that defies categorization."),
    DEFINE_LOG_SUBJECT_INFO(
        AWS_LS_EVENT_STREAM_CHANNEL_HANDLER,
        "event-stream-channel-handler",
        "Subject for event-stream channel handler related logging."),
    DEFINE_LOG_SUBJECT_INFO(
        AWS_LS_EVENT_STREAM_RPC_SERVER,
        "event-stream-rpc-server",
        "Subject for event-stream rpc server."),
    DEFINE_LOG_SUBJECT_INFO(
        AWS_LS_EVENT_STREAM_RPC_CLIENT,
        "event-stream-rpc-client",
        "Subject for event-stream rpc client."),
};

static struct aws_log_subject_info_list s_event_stream_log_subject_list = {
    .subject_list = s_event_stream_log_subject_infos,
    .count = AWS_ARRAY_SIZE(s_event_stream_log_subject_infos),
};

void aws_event_stream_library_init(struct aws_allocator *allocator) {
    if (!s_event_stream_library_initialized) {
        s_event_stream_library_initialized = true;
        aws_io_library_init(allocator);
        aws_register_error_info(&s_list);
        aws_register_log_subject_info_list(&s_event_stream_log_subject_list);
    }
}

void aws_event_stream_library_clean_up(void) {
    if (s_event_stream_library_initialized) {
        s_event_stream_library_initialized = false;
        aws_unregister_error_info(&s_list);
        aws_io_library_clean_up();
    }
}

#define TOTAL_LEN_OFFSET 0
#define PRELUDE_CRC_OFFSET (sizeof(uint32_t) + sizeof(uint32_t))
#define HEADER_LEN_OFFSET sizeof(uint32_t)

/* Computes the byte length necessary to store the headers represented in the headers list.
 * returns that length. */
uint32_t aws_event_stream_compute_headers_required_buffer_len(const struct aws_array_list *headers) {
    if (!headers || !aws_array_list_length(headers)) {
        return 0;
    }

    size_t headers_count = aws_array_list_length(headers);
    size_t headers_len = 0;

    for (size_t i = 0; i < headers_count; ++i) {
        struct aws_event_stream_header_value_pair *header = NULL;

        aws_array_list_get_at_ptr(headers, (void **)&header, i);

        headers_len += sizeof(header->header_name_len) + header->header_name_len + 1;

        if (header->header_value_type == AWS_EVENT_STREAM_HEADER_STRING ||
            header->header_value_type == AWS_EVENT_STREAM_HEADER_BYTE_BUF) {
            headers_len += sizeof(header->header_value_len);
        }

        if (header->header_value_type != AWS_EVENT_STREAM_HEADER_BOOL_FALSE &&
            header->header_value_type != AWS_EVENT_STREAM_HEADER_BOOL_TRUE) {
            headers_len += header->header_value_len;
        }
    }

    return (uint32_t)headers_len;
}

/* adds the headers represented in the headers list to the buffer.
 returns the new buffer offset for use elsewhere. Assumes buffer length is at least the length of the return value
 from compute_headers_length() */
size_t aws_event_stream_write_headers_to_buffer(const struct aws_array_list *headers, uint8_t *buffer) {
    if (!headers || !aws_array_list_length(headers)) {
        return 0;
    }

    size_t headers_count = aws_array_list_length(headers);
    uint8_t *buffer_alias = buffer;

    for (size_t i = 0; i < headers_count; ++i) {
        struct aws_event_stream_header_value_pair *header = NULL;

        aws_array_list_get_at_ptr(headers, (void **)&header, i);
        *buffer_alias = (uint8_t)header->header_name_len;
        buffer_alias++;
        memcpy(buffer_alias, header->header_name, (size_t)header->header_name_len);
        buffer_alias += header->header_name_len;
        *buffer_alias = (uint8_t)header->header_value_type;
        buffer_alias++;
        switch (header->header_value_type) {
            case AWS_EVENT_STREAM_HEADER_BOOL_FALSE:
            case AWS_EVENT_STREAM_HEADER_BOOL_TRUE:
                break;
            case AWS_EVENT_STREAM_HEADER_BYTE:
                *buffer_alias = header->header_value.static_val[0];
                buffer_alias++;
                break;
                /* additions of integers here assume the endianness conversion has already happened */
            case AWS_EVENT_STREAM_HEADER_INT16:
                memcpy(buffer_alias, header->header_value.static_val, sizeof(uint16_t));
                buffer_alias += sizeof(uint16_t);
                break;
            case AWS_EVENT_STREAM_HEADER_INT32:
                memcpy(buffer_alias, header->header_value.static_val, sizeof(uint32_t));
                buffer_alias += sizeof(uint32_t);
                break;
            case AWS_EVENT_STREAM_HEADER_INT64:
            case AWS_EVENT_STREAM_HEADER_TIMESTAMP:
                memcpy(buffer_alias, header->header_value.static_val, sizeof(uint64_t));
                buffer_alias += sizeof(uint64_t);
                break;
            case AWS_EVENT_STREAM_HEADER_BYTE_BUF:
            case AWS_EVENT_STREAM_HEADER_STRING:
                aws_write_u16(header->header_value_len, buffer_alias);
                buffer_alias += sizeof(uint16_t);
                memcpy(buffer_alias, header->header_value.variable_len_val, header->header_value_len);
                buffer_alias += header->header_value_len;
                break;
            case AWS_EVENT_STREAM_HEADER_UUID:
                memcpy(buffer_alias, header->header_value.static_val, 16);
                buffer_alias += header->header_value_len;
                break;
        }
    }

    return buffer_alias - buffer;
}

int aws_event_stream_read_headers_from_buffer(
    struct aws_array_list *headers,
    const uint8_t *buffer,
    size_t headers_len) {

    if (AWS_UNLIKELY(headers_len > AWS_EVENT_STREAM_MAX_HEADERS_SIZE)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED);
    }

    /* iterate the buffer per header. */
    const uint8_t *buffer_start = buffer;
    while ((size_t)(buffer - buffer_start) < headers_len) {
        struct aws_event_stream_header_value_pair header;
        AWS_ZERO_STRUCT(header);

        /* get the header info from the buffer, make sure to increment buffer offset. */
        header.header_name_len = *buffer;
        buffer += sizeof(header.header_name_len);
        memcpy((void *)header.header_name, buffer, (size_t)header.header_name_len);
        buffer += header.header_name_len;
        header.header_value_type = (enum aws_event_stream_header_value_type) * buffer;
        buffer++;

        switch (header.header_value_type) {
            case AWS_EVENT_STREAM_HEADER_BOOL_FALSE:
                header.header_value_len = 0;
                header.header_value.static_val[0] = 0;
                break;
            case AWS_EVENT_STREAM_HEADER_BOOL_TRUE:
                header.header_value_len = 0;
                header.header_value.static_val[0] = 1;
                break;
            case AWS_EVENT_STREAM_HEADER_BYTE:
                header.header_value_len = sizeof(uint8_t);
                header.header_value.static_val[0] = *buffer;
                buffer++;
                break;
            case AWS_EVENT_STREAM_HEADER_INT16:
                header.header_value_len = sizeof(uint16_t);
                memcpy(header.header_value.static_val, buffer, sizeof(uint16_t));
                buffer += sizeof(uint16_t);
                break;
            case AWS_EVENT_STREAM_HEADER_INT32:
                header.header_value_len = sizeof(uint32_t);
                memcpy(header.header_value.static_val, buffer, sizeof(uint32_t));
                buffer += sizeof(uint32_t);
                break;
            case AWS_EVENT_STREAM_HEADER_INT64:
            case AWS_EVENT_STREAM_HEADER_TIMESTAMP:
                header.header_value_len = sizeof(uint64_t);
                memcpy(header.header_value.static_val, buffer, sizeof(uint64_t));
                buffer += sizeof(uint64_t);
                break;
            case AWS_EVENT_STREAM_HEADER_BYTE_BUF:
            case AWS_EVENT_STREAM_HEADER_STRING:
                header.header_value_len = aws_read_u16(buffer);
                buffer += sizeof(header.header_value_len);
                header.header_value.variable_len_val = (uint8_t *)buffer;
                buffer += header.header_value_len;
                break;
            case AWS_EVENT_STREAM_HEADER_UUID:
                header.header_value_len = 16;
                memcpy(header.header_value.static_val, buffer, 16);
                buffer += header.header_value_len;
                break;
        }

        if (aws_array_list_push_back(headers, (const void *)&header)) {
            return AWS_OP_ERR;
        }
    }

    return AWS_OP_SUCCESS;
}

/* initialize message with the arguments
 * the underlying buffer will be allocated and payload will be copied.
 * see specification, this code should simply add these fields according to that.*/
int aws_event_stream_message_init(
    struct aws_event_stream_message *message,
    struct aws_allocator *alloc,
    struct aws_array_list *headers,
    struct aws_byte_buf *payload) {

    size_t payload_len = payload ? payload->len : 0;

    uint32_t headers_length = aws_event_stream_compute_headers_required_buffer_len(headers);

    if (AWS_UNLIKELY(headers_length > AWS_EVENT_STREAM_MAX_HEADERS_SIZE)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED);
    }

    uint32_t total_length =
        (uint32_t)(AWS_EVENT_STREAM_PRELUDE_LENGTH + headers_length + payload_len + AWS_EVENT_STREAM_TRAILER_LENGTH);

    if (AWS_UNLIKELY(total_length < headers_length || total_length < payload_len)) {
        return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
    }

    if (AWS_UNLIKELY(total_length > AWS_EVENT_STREAM_MAX_MESSAGE_SIZE)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED);
    }

    message->alloc = alloc;
    message->message_buffer = aws_mem_acquire(message->alloc, total_length);

    if (message->message_buffer) {
        message->owns_buffer = 1;
        aws_write_u32(total_length, message->message_buffer);
        uint8_t *buffer_offset = message->message_buffer + sizeof(total_length);
        aws_write_u32(headers_length, buffer_offset);
        buffer_offset += sizeof(headers_length);

        uint32_t running_crc =
            aws_checksums_crc32(message->message_buffer, (int)(buffer_offset - message->message_buffer), 0);

        const uint8_t *message_crc_boundary_start = buffer_offset;
        aws_write_u32(running_crc, buffer_offset);
        buffer_offset += sizeof(running_crc);

        if (headers_length) {
            buffer_offset += aws_event_stream_write_headers_to_buffer(headers, buffer_offset);
        }

        if (payload) {
            memcpy(buffer_offset, payload->buffer, payload->len);
            buffer_offset += payload->len;
        }

        running_crc = aws_checksums_crc32(
            message_crc_boundary_start, (int)(buffer_offset - message_crc_boundary_start), running_crc);
        aws_write_u32(running_crc, buffer_offset);

        return AWS_OP_SUCCESS;
    }

    return aws_raise_error(AWS_ERROR_OOM);
}

/* add buffer to the message (non-owning). Verify buffer crcs and that length fields are reasonable. */
int aws_event_stream_message_from_buffer(
    struct aws_event_stream_message *message,
    struct aws_allocator *alloc,
    struct aws_byte_buf *buffer) {
    AWS_ASSERT(buffer);

    message->alloc = alloc;
    message->owns_buffer = 0;

    if (AWS_UNLIKELY(buffer->len < AWS_EVENT_STREAM_PRELUDE_LENGTH + AWS_EVENT_STREAM_TRAILER_LENGTH)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_BUFFER_LENGTH_MISMATCH);
    }

    uint32_t message_length = aws_read_u32(buffer->buffer + TOTAL_LEN_OFFSET);

    if (AWS_UNLIKELY(message_length != buffer->len)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_BUFFER_LENGTH_MISMATCH);
    }

    if (AWS_UNLIKELY(message_length > AWS_EVENT_STREAM_MAX_MESSAGE_SIZE)) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED);
    }

    uint32_t running_crc = aws_checksums_crc32(buffer->buffer, (int)PRELUDE_CRC_OFFSET, 0);
    uint32_t prelude_crc = aws_read_u32(buffer->buffer + PRELUDE_CRC_OFFSET);

    if (running_crc != prelude_crc) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_PRELUDE_CHECKSUM_FAILURE);
    }

    running_crc = aws_checksums_crc32(
        buffer->buffer + PRELUDE_CRC_OFFSET,
        (int)(message_length - PRELUDE_CRC_OFFSET - AWS_EVENT_STREAM_TRAILER_LENGTH),
        running_crc);
    uint32_t message_crc = aws_read_u32(buffer->buffer + message_length - AWS_EVENT_STREAM_TRAILER_LENGTH);

    if (running_crc != message_crc) {
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_CHECKSUM_FAILURE);
    }

    message->message_buffer = buffer->buffer;

    if (aws_event_stream_message_headers_len(message) >
        message_length - AWS_EVENT_STREAM_PRELUDE_LENGTH - AWS_EVENT_STREAM_TRAILER_LENGTH) {
        message->message_buffer = 0;
        return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_INVALID_HEADERS_LEN);
    }

    return AWS_OP_SUCCESS;
}

/* Verify buffer crcs and that length fields are reasonable. Once that is done, the buffer is copied to the message. */
int aws_event_stream_message_from_buffer_copy(
    struct aws_event_stream_message *message,
    struct aws_allocator *alloc,
    const struct aws_byte_buf *buffer) {
    int parse_value = aws_event_stream_message_from_buffer(message, alloc, (struct aws_byte_buf *)buffer);

    if (!parse_value) {
        message->message_buffer = aws_mem_acquire(alloc, buffer->len);

        if (message->message_buffer) {
            memcpy(message->message_buffer, buffer->buffer, buffer->len);
            message->alloc = alloc;
            message->owns_buffer = 1;

            return AWS_OP_SUCCESS;
        }

        return aws_raise_error(AWS_ERROR_OOM);
    }

    return parse_value;
}

/* if buffer is owned, release the memory. */
void aws_event_stream_message_clean_up(struct aws_event_stream_message *message) {
    if (message->message_buffer && message->owns_buffer) {
        aws_mem_release(message->alloc, message->message_buffer);
    }
}

uint32_t aws_event_stream_message_total_length(const struct aws_event_stream_message *message) {
    return aws_read_u32(message->message_buffer + TOTAL_LEN_OFFSET);
}

uint32_t aws_event_stream_message_headers_len(const struct aws_event_stream_message *message) {
    return aws_read_u32(message->message_buffer + HEADER_LEN_OFFSET);
}

uint32_t aws_event_stream_message_prelude_crc(const struct aws_event_stream_message *message) {
    return aws_read_u32(message->message_buffer + PRELUDE_CRC_OFFSET);
}

int aws_event_stream_message_headers(const struct aws_event_stream_message *message, struct aws_array_list *headers) {
    return aws_event_stream_read_headers_from_buffer(
        headers,
        message->message_buffer + AWS_EVENT_STREAM_PRELUDE_LENGTH,
        aws_event_stream_message_headers_len(message));
}

const uint8_t *aws_event_stream_message_payload(const struct aws_event_stream_message *message) {
    return message->message_buffer + AWS_EVENT_STREAM_PRELUDE_LENGTH + aws_event_stream_message_headers_len(message);
}

uint32_t aws_event_stream_message_payload_len(const struct aws_event_stream_message *message) {
    return aws_event_stream_message_total_length(message) -
           (AWS_EVENT_STREAM_PRELUDE_LENGTH + aws_event_stream_message_headers_len(message) +
            AWS_EVENT_STREAM_TRAILER_LENGTH);
}

uint32_t aws_event_stream_message_message_crc(const struct aws_event_stream_message *message) {
    return aws_read_u32(
        message->message_buffer + (aws_event_stream_message_total_length(message) - AWS_EVENT_STREAM_TRAILER_LENGTH));
}

const uint8_t *aws_event_stream_message_buffer(const struct aws_event_stream_message *message) {
    return message->message_buffer;
}

#define DEBUG_STR_PRELUDE_TOTAL_LEN "\"total_length\": "
#define DEBUG_STR_PRELUDE_HDRS_LEN "\"headers_length\": "
#define DEBUG_STR_PRELUDE_CRC "\"prelude_crc\": "
#define DEBUG_STR_MESSAGE_CRC "\"message_crc\": "
#define DEBUG_STR_HEADER_NAME "\"name\": "
#define DEBUG_STR_HEADER_VALUE "\"value\": "
#define DEBUG_STR_HEADER_TYPE "\"type\": "

int aws_event_stream_message_to_debug_str(FILE *fd, const struct aws_event_stream_message *message) {
    struct aws_array_list headers;
    aws_event_stream_headers_list_init(&headers, message->alloc);
    aws_event_stream_message_headers(message, &headers);

    fprintf(
        fd,
        "{\n  " DEBUG_STR_PRELUDE_TOTAL_LEN "%d,\n  " DEBUG_STR_PRELUDE_HDRS_LEN "%d,\n  " DEBUG_STR_PRELUDE_CRC
        "%d,\n",
        aws_event_stream_message_total_length(message),
        aws_event_stream_message_headers_len(message),
        aws_event_stream_message_prelude_crc(message));

    int count = 0;

    uint16_t headers_count = (uint16_t)aws_array_list_length(&headers);

    fprintf(fd, "  \"headers\": [");

    for (uint16_t i = 0; i < headers_count; ++i) {
        struct aws_event_stream_header_value_pair *header = NULL;

        aws_array_list_get_at_ptr(&headers, (void **)&header, i);

        fprintf(fd, "    {\n");

        fprintf(fd, "      " DEBUG_STR_HEADER_NAME "\"");
        fwrite(header->header_name, sizeof(char), (size_t)header->header_name_len, fd);
        fprintf(fd, "\",\n");

        fprintf(fd, "      " DEBUG_STR_HEADER_TYPE "%d,\n", header->header_value_type);

        if (header->header_value_type == AWS_EVENT_STREAM_HEADER_BOOL_FALSE) {
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "false\n");
        } else if (header->header_value_type == AWS_EVENT_STREAM_HEADER_BOOL_TRUE) {
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "true\n");
        } else if (header->header_value_type == AWS_EVENT_STREAM_HEADER_BYTE) {
            int8_t int_value = (int8_t)header->header_value.static_val[0];
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "%d\n", (int)int_value);
        } else if (header->header_value_type == AWS_EVENT_STREAM_HEADER_INT16) {
            int16_t int_value = aws_read_u16(header->header_value.static_val);
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "%d\n", (int)int_value);
        } else if (header->header_value_type == AWS_EVENT_STREAM_HEADER_INT32) {
            int32_t int_value = (int32_t)aws_read_u32(header->header_value.static_val);
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "%d\n", (int)int_value);
        } else if (
            header->header_value_type == AWS_EVENT_STREAM_HEADER_INT64 ||
            header->header_value_type == AWS_EVENT_STREAM_HEADER_TIMESTAMP) {
            int64_t int_value = (int64_t)aws_read_u64(header->header_value.static_val);
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "%lld\n", (long long)int_value);
        } else {
            size_t buffer_len = 0;
            aws_base64_compute_encoded_len(header->header_value_len, &buffer_len);
            char *encoded_buffer = (char *)aws_mem_acquire(message->alloc, buffer_len);
            if (!encoded_buffer) {
                return aws_raise_error(AWS_ERROR_OOM);
            }

            struct aws_byte_buf encode_output = aws_byte_buf_from_array((uint8_t *)encoded_buffer, buffer_len);

            if (header->header_value_type == AWS_EVENT_STREAM_HEADER_UUID) {
                struct aws_byte_cursor to_encode =
                    aws_byte_cursor_from_array(header->header_value.static_val, header->header_value_len);

                aws_base64_encode(&to_encode, &encode_output);
            } else {
                struct aws_byte_cursor to_encode =
                    aws_byte_cursor_from_array(header->header_value.variable_len_val, header->header_value_len);
                aws_base64_encode(&to_encode, &encode_output);
            }
            fprintf(fd, "      " DEBUG_STR_HEADER_VALUE "\"%s\"\n", encoded_buffer);
            aws_mem_release(message->alloc, encoded_buffer);
        }

        fprintf(fd, "    }");

        if (count < headers_count - 1) {
            fprintf(fd, ",");
        }
        fprintf(fd, "\n");

        count++;
    }
    aws_event_stream_headers_list_cleanup(&headers);
    fprintf(fd, "  ],\n");

    size_t payload_len = aws_event_stream_message_payload_len(message);
    const uint8_t *payload = aws_event_stream_message_payload(message);
    size_t encoded_len = 0;
    aws_base64_compute_encoded_len(payload_len, &encoded_len);
    char *encoded_payload = (char *)aws_mem_acquire(message->alloc, encoded_len);

    if (!encoded_payload) {
        return aws_raise_error(AWS_ERROR_OOM);
    }

    struct aws_byte_cursor payload_buffer = aws_byte_cursor_from_array(payload, payload_len);
    struct aws_byte_buf encoded_payload_buffer = aws_byte_buf_from_array((uint8_t *)encoded_payload, encoded_len);

    aws_base64_encode(&payload_buffer, &encoded_payload_buffer);
    fprintf(fd, "  \"payload\": \"%s\",\n", encoded_payload);
    fprintf(fd, "  " DEBUG_STR_MESSAGE_CRC "%d\n}\n", aws_event_stream_message_message_crc(message));

    return AWS_OP_SUCCESS;
}

int aws_event_stream_headers_list_init(struct aws_array_list *headers, struct aws_allocator *allocator) {
    AWS_ASSERT(headers);
    AWS_ASSERT(allocator);

    return aws_array_list_init_dynamic(headers, allocator, 4, sizeof(struct aws_event_stream_header_value_pair));
}

void aws_event_stream_headers_list_cleanup(struct aws_array_list *headers) {
    if (AWS_UNLIKELY(!headers || !aws_array_list_is_valid(headers))) {
        return;
    }

    for (size_t i = 0; i < aws_array_list_length(headers); ++i) {
        struct aws_event_stream_header_value_pair *header = NULL;
        aws_array_list_get_at_ptr(headers, (void **)&header, i);

        if (header->value_owned) {
            aws_mem_release(headers->alloc, (void *)header->header_value.variable_len_val);
        }
    }

    aws_array_list_clean_up(headers);
}

static int s_add_variable_len_header(
    struct aws_array_list *headers,
    struct aws_event_stream_header_value_pair *header,
    const char *name,
    uint8_t name_len,
    uint8_t *value,
    uint16_t value_len,
    int8_t copy) {

    memcpy((void *)header->header_name, (void *)name, (size_t)name_len);

    if (copy) {
        header->header_value.variable_len_val = aws_mem_acquire(headers->alloc, value_len);
        if (!header->header_value.variable_len_val) {
            return aws_raise_error(AWS_ERROR_OOM);
        }

        header->value_owned = 1;
        memcpy((void *)header->header_value.variable_len_val, (void *)value, value_len);
    } else {
        header->value_owned = 0;
        header->header_value.variable_len_val = value;
    }

    if (aws_array_list_push_back(headers, (void *)header)) {
        if (header->value_owned) {
            aws_mem_release(headers->alloc, (void *)header->header_value.variable_len_val);
        }
        return AWS_OP_ERR;
    }

    return AWS_OP_SUCCESS;
}

int aws_event_stream_add_string_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    const char *value,
    uint16_t value_len,
    int8_t copy) {
    struct aws_event_stream_header_value_pair header = {.header_name_len = name_len,
                                                        .header_value_len = value_len,
                                                        .value_owned = copy,
                                                        .header_value_type = AWS_EVENT_STREAM_HEADER_STRING};

    return s_add_variable_len_header(headers, &header, name, name_len, (uint8_t *)value, value_len, copy);
}

struct aws_event_stream_header_value_pair aws_event_stream_create_string_header(
    struct aws_byte_cursor name,
    struct aws_byte_cursor value) {
    AWS_PRECONDITION(name.len < INT8_MAX);
    AWS_PRECONDITION(value.len < INT16_MAX);

    struct aws_event_stream_header_value_pair header = {
        .header_value_type = AWS_EVENT_STREAM_HEADER_STRING,
        .header_value.variable_len_val = value.ptr,
        .header_value_len = (uint16_t)value.len,
        .header_name_len = (uint8_t)name.len,
        .value_owned = 0,
    };

    memcpy(header.header_name, name.ptr, name.len);

    return header;
}

struct aws_event_stream_header_value_pair aws_event_stream_create_int32_header(
    struct aws_byte_cursor name,
    int32_t value) {
    AWS_PRECONDITION(name.len < INT8_MAX);

    struct aws_event_stream_header_value_pair header = {
        .header_value_type = AWS_EVENT_STREAM_HEADER_INT32,
        .header_value_len = (uint16_t)sizeof(int32_t),
        .header_name_len = (uint8_t)name.len,
        .value_owned = 0,
    };

    memcpy(header.header_name, name.ptr, name.len);
    aws_write_u32((uint32_t)value, header.header_value.static_val);

    return header;
}

int aws_event_stream_add_byte_header(struct aws_array_list *headers, const char *name, uint8_t name_len, int8_t value) {
    struct aws_event_stream_header_value_pair header = {.header_name_len = name_len,
                                                        .header_value_len = 1,
                                                        .value_owned = 0,
                                                        .header_value_type = AWS_EVENT_STREAM_HEADER_BYTE,
                                                        .header_value.static_val[0] = (uint8_t)value};

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_bool_header(struct aws_array_list *headers, const char *name, uint8_t name_len, int8_t value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = 0,
        .value_owned = 0,
        .header_value_type = value ? AWS_EVENT_STREAM_HEADER_BOOL_TRUE : AWS_EVENT_STREAM_HEADER_BOOL_FALSE,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_int16_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    int16_t value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = sizeof(value),
        .value_owned = 0,
        .header_value_type = AWS_EVENT_STREAM_HEADER_INT16,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);
    aws_write_u16((uint16_t)value, header.header_value.static_val);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_int32_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    int32_t value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = sizeof(value),
        .value_owned = 0,
        .header_value_type = AWS_EVENT_STREAM_HEADER_INT32,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);
    aws_write_u32((uint32_t)value, header.header_value.static_val);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_int64_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    int64_t value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = sizeof(value),
        .value_owned = 0,
        .header_value_type = AWS_EVENT_STREAM_HEADER_INT64,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);
    aws_write_u64((uint64_t)value, header.header_value.static_val);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_bytebuf_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    uint8_t *value,
    uint16_t value_len,
    int8_t copy) {
    struct aws_event_stream_header_value_pair header = {.header_name_len = name_len,
                                                        .header_value_len = value_len,
                                                        .value_owned = copy,
                                                        .header_value_type = AWS_EVENT_STREAM_HEADER_BYTE_BUF};

    return s_add_variable_len_header(headers, &header, name, name_len, value, value_len, copy);
}

int aws_event_stream_add_timestamp_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    int64_t value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = sizeof(uint64_t),
        .value_owned = 0,
        .header_value_type = AWS_EVENT_STREAM_HEADER_TIMESTAMP,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);
    aws_write_u64((uint64_t)value, header.header_value.static_val);

    return aws_array_list_push_back(headers, (void *)&header);
}

int aws_event_stream_add_uuid_header(
    struct aws_array_list *headers,
    const char *name,
    uint8_t name_len,
    const uint8_t *value) {
    struct aws_event_stream_header_value_pair header = {
        .header_name_len = name_len,
        .header_value_len = 16,
        .value_owned = 0,
        .header_value_type = AWS_EVENT_STREAM_HEADER_UUID,
    };

    memcpy((void *)header.header_name, (void *)name, (size_t)name_len);
    memcpy((void *)header.header_value.static_val, value, 16);

    return aws_array_list_push_back(headers, (void *)&header);
}

struct aws_byte_buf aws_event_stream_header_name(struct aws_event_stream_header_value_pair *header) {
    return aws_byte_buf_from_array((uint8_t *)header->header_name, header->header_name_len);
}

int8_t aws_event_stream_header_value_as_byte(struct aws_event_stream_header_value_pair *header) {
    return (int8_t)header->header_value.static_val[0];
}

struct aws_byte_buf aws_event_stream_header_value_as_string(struct aws_event_stream_header_value_pair *header) {
    return aws_event_stream_header_value_as_bytebuf(header);
}

int8_t aws_event_stream_header_value_as_bool(struct aws_event_stream_header_value_pair *header) {
    return header->header_value_type == AWS_EVENT_STREAM_HEADER_BOOL_TRUE ? (int8_t)1 : (int8_t)0;
}

int16_t aws_event_stream_header_value_as_int16(struct aws_event_stream_header_value_pair *header) {
    return (int16_t)aws_read_u16(header->header_value.static_val);
}

int32_t aws_event_stream_header_value_as_int32(struct aws_event_stream_header_value_pair *header) {
    return (int32_t)aws_read_u32(header->header_value.static_val);
}

int64_t aws_event_stream_header_value_as_int64(struct aws_event_stream_header_value_pair *header) {
    return (int64_t)aws_read_u64(header->header_value.static_val);
}

struct aws_byte_buf aws_event_stream_header_value_as_bytebuf(struct aws_event_stream_header_value_pair *header) {
    return aws_byte_buf_from_array(header->header_value.variable_len_val, header->header_value_len);
}

int64_t aws_event_stream_header_value_as_timestamp(struct aws_event_stream_header_value_pair *header) {
    return aws_event_stream_header_value_as_int64(header);
}

struct aws_byte_buf aws_event_stream_header_value_as_uuid(struct aws_event_stream_header_value_pair *header) {
    return aws_byte_buf_from_array(header->header_value.static_val, 16);
}

uint16_t aws_event_stream_header_value_length(struct aws_event_stream_header_value_pair *header) {
    return header->header_value_len;
}

static struct aws_event_stream_message_prelude s_empty_prelude = {.total_len = 0, .headers_len = 0, .prelude_crc = 0};

static void s_reset_header_state(struct aws_event_stream_streaming_decoder *decoder, uint8_t free_header_data) {

    if (free_header_data && decoder->current_header.value_owned) {
        aws_mem_release(decoder->alloc, (void *)decoder->current_header.header_value.variable_len_val);
    }

    memset((void *)&decoder->current_header, 0, sizeof(struct aws_event_stream_header_value_pair));
}

static void s_reset_state(struct aws_event_stream_streaming_decoder *decoder);

static int s_headers_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed);

static int s_read_header_value(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {

    size_t current_pos = decoder->message_pos;

    size_t length_read = current_pos - decoder->current_header_value_offset;
    struct aws_event_stream_header_value_pair *current_header = &decoder->current_header;

    if (!length_read) {
        /* save an allocation, this can only happen if the data we were handed is larger than the length of the header
         * value. we don't really need to handle offsets in this case. This expects the user is living by the contract
         * that they cannot act like they own this memory beyond the lifetime of their callback, and they should not
         * mutate it */
        if (len >= current_header->header_value_len) {
            /* this part works regardless of type since the layout of the union will line up. */
            current_header->header_value.variable_len_val = (uint8_t *)data;
            current_header->value_owned = 0;
            decoder->on_header(decoder, &decoder->prelude, &decoder->current_header, decoder->user_context);
            *processed += current_header->header_value_len;
            decoder->message_pos += current_header->header_value_len;
            decoder->running_crc =
                aws_checksums_crc32(data, (int)current_header->header_value_len, decoder->running_crc);

            s_reset_header_state(decoder, 1);
            decoder->state = s_headers_state;
            return AWS_OP_SUCCESS;
        }

        /* a possible optimization later would be to only allocate this once, and then keep reusing the same buffer. for
         * subsequent messages.*/
        if (current_header->header_value_type == AWS_EVENT_STREAM_HEADER_BYTE_BUF ||
            current_header->header_value_type == AWS_EVENT_STREAM_HEADER_STRING) {
            current_header->header_value.variable_len_val =
                aws_mem_acquire(decoder->alloc, decoder->current_header.header_value_len);

            if (!current_header->header_value.variable_len_val) {
                return aws_raise_error(AWS_ERROR_OOM);
            }

            current_header->value_owned = 1;
        }
    }

    size_t max_read =
        len >= current_header->header_value_len - length_read ? current_header->header_value_len - length_read : len;

    const uint8_t *header_value_alias = current_header->header_value_type == AWS_EVENT_STREAM_HEADER_BYTE_BUF ||
                                                current_header->header_value_type == AWS_EVENT_STREAM_HEADER_STRING
                                            ? current_header->header_value.variable_len_val
                                            : current_header->header_value.static_val;

    memcpy((void *)(header_value_alias + length_read), data, max_read);
    decoder->running_crc = aws_checksums_crc32(data, (int)max_read, decoder->running_crc);

    *processed += max_read;
    decoder->message_pos += max_read;
    length_read += max_read;

    if (length_read == current_header->header_value_len) {
        decoder->on_header(decoder, &decoder->prelude, current_header, decoder->user_context);
        s_reset_header_state(decoder, 1);
        decoder->state = s_headers_state;
    }

    return AWS_OP_SUCCESS;
}

static int s_read_header_value_len(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {
    size_t current_pos = decoder->message_pos;

    size_t length_portion_read = current_pos - decoder->current_header_value_offset;

    if (length_portion_read < sizeof(uint16_t)) {
        size_t max_to_read =
            len > sizeof(uint16_t) - length_portion_read ? sizeof(uint16_t) - length_portion_read : len;
        memcpy(decoder->working_buffer + length_portion_read, data, max_to_read);
        decoder->running_crc = aws_checksums_crc32(data, (int)max_to_read, decoder->running_crc);

        *processed += max_to_read;
        decoder->message_pos += max_to_read;

        length_portion_read = decoder->message_pos - decoder->current_header_value_offset;
    }

    if (length_portion_read == sizeof(uint16_t)) {
        decoder->current_header.header_value_len = aws_read_u16(decoder->working_buffer);
        decoder->current_header_value_offset = decoder->message_pos;
        decoder->state = s_read_header_value;
    }

    return AWS_OP_SUCCESS;
}

static int s_read_header_type(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {
    (void)len;
    uint8_t type = *data;
    decoder->running_crc = aws_checksums_crc32(data, 1, decoder->running_crc);
    *processed += 1;
    decoder->message_pos++;
    decoder->current_header_value_offset++;
    struct aws_event_stream_header_value_pair *current_header = &decoder->current_header;

    if (type >= AWS_EVENT_STREAM_HEADER_BOOL_FALSE && type <= AWS_EVENT_STREAM_HEADER_UUID) {
        current_header->header_value_type = (enum aws_event_stream_header_value_type)type;

        switch (type) {
            case AWS_EVENT_STREAM_HEADER_STRING:
            case AWS_EVENT_STREAM_HEADER_BYTE_BUF:
                decoder->state = s_read_header_value_len;
                break;
            case AWS_EVENT_STREAM_HEADER_BOOL_FALSE:
                current_header->header_value_len = 0;
                current_header->header_value.static_val[0] = 0;
                decoder->on_header(decoder, &decoder->prelude, current_header, decoder->user_context);
                s_reset_header_state(decoder, 1);
                break;
            case AWS_EVENT_STREAM_HEADER_BOOL_TRUE:
                current_header->header_value_len = 0;
                current_header->header_value.static_val[0] = 1;
                decoder->on_header(decoder, &decoder->prelude, current_header, decoder->user_context);
                s_reset_header_state(decoder, 1);
                break;
            case AWS_EVENT_STREAM_HEADER_BYTE:
                current_header->header_value_len = 1;
                decoder->state = s_read_header_value;
                break;
            case AWS_EVENT_STREAM_HEADER_INT16:
                current_header->header_value_len = sizeof(uint16_t);
                decoder->state = s_read_header_value;
                break;
            case AWS_EVENT_STREAM_HEADER_INT32:
                current_header->header_value_len = sizeof(uint32_t);
                decoder->state = s_read_header_value;
                break;
            case AWS_EVENT_STREAM_HEADER_INT64:
            case AWS_EVENT_STREAM_HEADER_TIMESTAMP:
                current_header->header_value_len = sizeof(uint64_t);
                decoder->state = s_read_header_value;
                break;
            case AWS_EVENT_STREAM_HEADER_UUID:
                current_header->header_value_len = 16;
                decoder->state = s_read_header_value;
                break;
            default:
                return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_UNKNOWN_HEADER_TYPE);
        }

        return AWS_OP_SUCCESS;
    }

    return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_UNKNOWN_HEADER_TYPE);
}

static int s_read_header_name(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {
    size_t current_pos = decoder->message_pos;

    size_t length_read = current_pos - decoder->current_header_name_offset;

    size_t max_read = len >= decoder->current_header.header_name_len - length_read
                          ? decoder->current_header.header_name_len - length_read
                          : len;
    memcpy((void *)(decoder->current_header.header_name + length_read), data, max_read);
    decoder->running_crc = aws_checksums_crc32(data, (int)max_read, decoder->running_crc);

    *processed += max_read;
    decoder->message_pos += max_read;
    length_read += max_read;

    if (length_read == decoder->current_header.header_name_len) {
        decoder->state = s_read_header_type;
        decoder->current_header_value_offset = decoder->message_pos;
    }

    return AWS_OP_SUCCESS;
}

static int s_read_header_name_len(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {
    (void)len;
    decoder->current_header.header_name_len = *data;
    decoder->message_pos++;
    decoder->current_header_name_offset++;
    *processed += 1;
    decoder->state = s_read_header_name;
    decoder->running_crc = aws_checksums_crc32(data, 1, decoder->running_crc);

    return AWS_OP_SUCCESS;
}

static int s_start_header(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) /* NOLINT */ {
    (void)data;
    (void)len;
    (void)processed;
    decoder->state = s_read_header_name_len;
    decoder->current_header_name_offset = decoder->message_pos;

    return AWS_OP_SUCCESS;
}

static int s_payload_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed);

/*Handles the initial state for header parsing.
  will oscillate between multiple other states as well.
  after all headers have been handled, payload will be set as the next state. */
static int s_headers_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) /* NOLINT */ {
    (void)data;
    (void)len;
    (void)processed;

    size_t current_pos = decoder->message_pos;

    size_t headers_boundary = decoder->prelude.headers_len + AWS_EVENT_STREAM_PRELUDE_LENGTH;

    if (current_pos < headers_boundary) {
        decoder->state = s_start_header;
        return AWS_OP_SUCCESS;
    }

    if (current_pos == headers_boundary) {
        decoder->state = s_payload_state;
        return AWS_OP_SUCCESS;
    }

    return aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_PARSER_ILLEGAL_STATE);
}

/* handles reading the trailer. Once it has been read, it will be compared to the running checksum. If successful,
 * the state will be reset. */
static int s_read_trailer_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {

    size_t remaining_amount = decoder->prelude.total_len - decoder->message_pos;
    size_t segment_length = len > remaining_amount ? remaining_amount : len;
    size_t offset = sizeof(uint32_t) - remaining_amount;
    memcpy(decoder->working_buffer + offset, data, segment_length);
    decoder->message_pos += segment_length;
    *processed += segment_length;

    if (decoder->message_pos == decoder->prelude.total_len) {
        uint32_t message_crc = aws_read_u32(decoder->working_buffer);

        if (message_crc == decoder->running_crc) {
            s_reset_state(decoder);
        } else {
            char error_message[70];
            snprintf(
                error_message,
                sizeof(error_message),
                "CRC Mismatch. message_crc was 0x08%" PRIX32 ", but computed 0x08%" PRIX32,
                message_crc,
                decoder->running_crc);
            aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_CHECKSUM_FAILURE);
            decoder->on_error(
                decoder,
                &decoder->prelude,
                AWS_ERROR_EVENT_STREAM_MESSAGE_CHECKSUM_FAILURE,
                error_message,
                decoder->user_context);
            return AWS_OP_ERR;
        }
    }

    return AWS_OP_SUCCESS;
}

/* handles the reading of the payload up to the final checksum. Sets read_trailer_state as the new state once
 * the payload has been processed. */
static int s_payload_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {

    if (decoder->message_pos < decoder->prelude.total_len - AWS_EVENT_STREAM_TRAILER_LENGTH) {
        size_t remaining_amount = decoder->prelude.total_len - decoder->message_pos - AWS_EVENT_STREAM_TRAILER_LENGTH;
        size_t segment_length = len > remaining_amount ? remaining_amount : len;
        int8_t final_segment =
            (segment_length + decoder->message_pos) == (decoder->prelude.total_len - AWS_EVENT_STREAM_TRAILER_LENGTH);
        struct aws_byte_buf payload_buf = aws_byte_buf_from_array(data, segment_length);
        decoder->on_payload(decoder, &payload_buf, final_segment, decoder->user_context);
        decoder->message_pos += segment_length;
        decoder->running_crc = aws_checksums_crc32(data, (int)segment_length, decoder->running_crc);
        *processed += segment_length;
    }

    if (decoder->message_pos == decoder->prelude.total_len - AWS_EVENT_STREAM_TRAILER_LENGTH) {
        decoder->state = s_read_trailer_state;
    }

    return AWS_OP_SUCCESS;
}

/* Parses the payload and verifies checksums. Sets the next state if successful. */
static int s_verify_prelude_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) /* NOLINT */ {
    (void)data;
    (void)len;
    (void)processed;

    decoder->prelude.headers_len = aws_read_u32(decoder->working_buffer + HEADER_LEN_OFFSET);
    decoder->prelude.prelude_crc = aws_read_u32(decoder->working_buffer + PRELUDE_CRC_OFFSET);
    decoder->prelude.total_len = aws_read_u32(decoder->working_buffer + TOTAL_LEN_OFFSET);

    decoder->running_crc = aws_checksums_crc32(decoder->working_buffer, PRELUDE_CRC_OFFSET, 0);

    if (AWS_LIKELY(decoder->running_crc == decoder->prelude.prelude_crc)) {

        if (AWS_UNLIKELY(
                decoder->prelude.headers_len > AWS_EVENT_STREAM_MAX_HEADERS_SIZE ||
                decoder->prelude.total_len > AWS_EVENT_STREAM_MAX_MESSAGE_SIZE)) {
            aws_raise_error(AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED);
            char error_message[] = "Maximum message field size exceeded";

            decoder->on_error(
                decoder,
                &decoder->prelude,
                AWS_ERROR_EVENT_STREAM_MESSAGE_FIELD_SIZE_EXCEEDED,
                error_message,
                decoder->user_context);
            return AWS_OP_ERR;
        }

        /* Should only call on_prelude() after passing crc check and limitation check, otherwise call on_prelude() with
         * incorrect prelude is error prune. */
        decoder->on_prelude(decoder, &decoder->prelude, decoder->user_context);

        decoder->running_crc = aws_checksums_crc32(
            decoder->working_buffer + PRELUDE_CRC_OFFSET,
            (int)sizeof(decoder->prelude.prelude_crc),
            decoder->running_crc);
        memset(decoder->working_buffer, 0, sizeof(decoder->working_buffer));
        decoder->state = decoder->prelude.headers_len > 0 ? s_headers_state : s_payload_state;
    } else {
        char error_message[70];
        snprintf(
            error_message,
            sizeof(error_message),
            "CRC Mismatch. prelude_crc was 0x08%" PRIX32 ", but computed 0x08%" PRIX32,
            decoder->prelude.prelude_crc,
            decoder->running_crc);

        aws_raise_error(AWS_ERROR_EVENT_STREAM_PRELUDE_CHECKSUM_FAILURE);
        decoder->on_error(
            decoder,
            &decoder->prelude,
            AWS_ERROR_EVENT_STREAM_PRELUDE_CHECKSUM_FAILURE,
            error_message,
            decoder->user_context);
        return AWS_OP_ERR;
    }

    return AWS_OP_SUCCESS;
}

/* initial state handles up to the reading of the prelude */
static int s_start_state(
    struct aws_event_stream_streaming_decoder *decoder,
    const uint8_t *data,
    size_t len,
    size_t *processed) {

    size_t previous_position = decoder->message_pos;
    if (decoder->message_pos < AWS_EVENT_STREAM_PRELUDE_LENGTH) {
        if (len >= AWS_EVENT_STREAM_PRELUDE_LENGTH - decoder->message_pos) {
            memcpy(
                decoder->working_buffer + decoder->message_pos,
                data,
                AWS_EVENT_STREAM_PRELUDE_LENGTH - decoder->message_pos);
            decoder->message_pos += AWS_EVENT_STREAM_PRELUDE_LENGTH - decoder->message_pos;
        } else {
            memcpy(decoder->working_buffer + decoder->message_pos, data, len);
            decoder->message_pos += len;
        }

        *processed += decoder->message_pos - previous_position;
    }

    if (decoder->message_pos == AWS_EVENT_STREAM_PRELUDE_LENGTH) {
        decoder->state = s_verify_prelude_state;
    }

    return AWS_OP_SUCCESS;
}

static void s_reset_state(struct aws_event_stream_streaming_decoder *decoder) {
    decoder->message_pos = 0;
    decoder->prelude = s_empty_prelude;
    decoder->running_crc = 0;
    memset(decoder->working_buffer, 0, sizeof(decoder->working_buffer));
    decoder->state = s_start_state;
}

void aws_event_stream_streaming_decoder_init(
    struct aws_event_stream_streaming_decoder *decoder,
    struct aws_allocator *alloc,
    aws_event_stream_process_on_payload_segment_fn *on_payload_segment,
    aws_event_stream_prelude_received_fn *on_prelude,
    aws_event_stream_header_received_fn *on_header,
    aws_event_stream_on_error_fn *on_error,
    void *user_data) {

    s_reset_state(decoder);
    decoder->alloc = alloc;
    decoder->on_error = on_error;
    decoder->on_header = on_header;
    decoder->on_payload = on_payload_segment;
    decoder->on_prelude = on_prelude;
    decoder->user_context = user_data;
}

void aws_event_stream_streaming_decoder_clean_up(struct aws_event_stream_streaming_decoder *decoder) {
    s_reset_state(decoder);
    decoder->on_error = 0;
    decoder->on_header = 0;
    decoder->on_payload = 0;
    decoder->on_prelude = 0;
    decoder->user_context = 0;
}

/* Simply sends the data to the state machine until all has been processed or an error is returned. */
int aws_event_stream_streaming_decoder_pump(
    struct aws_event_stream_streaming_decoder *decoder,
    const struct aws_byte_buf *data) {

    size_t processed = 0;
    int err_val = 0;
    while (!err_val && data->buffer && data->len && processed < data->len) {
        err_val = decoder->state(decoder, data->buffer + processed, data->len - processed, &processed);
    }

    return err_val;
}
#if _MSC_VER
#    pragma warning(pop)
#endif