Debian Codegraph @

crt/aws-c-common/source/encoding.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/encoding.h>
7
8 #include <aws/common/logging.h>
9 #include <ctype.h>
10 #include <stdlib.h>
11
12 #ifdef USE_SIMD_ENCODING
13 size_t aws_common_private_base64_decode_sse41(const unsigned char *in, unsigned char *out, size_t len);
14 void aws_common_private_base64_encode_sse41(
15 const unsigned char *in,
16 unsigned char *out,
17 size_t len,
18 bool url_safe_encoding);
19 bool aws_common_private_has_avx2(void);
20 #else
21 /*
22 * When AVX2 compilation is unavailable, we use these stubs to fall back to the pure-C decoder.
23 * Since we force aws_common_private_has_avx2 to return false, the encode and decode functions should
24 * not be called - but we must provide them anyway to avoid link errors.
25 */
26 static inline size_t aws_common_private_base64_decode_sse41(const unsigned char *in, unsigned char *out, size_t len) {
27 (void)in;
28 (void)out;
29 (void)len;
30 AWS_ASSERT(false);
31 return SIZE_MAX; /* unreachable */
32 }
33 static inline void aws_common_private_base64_encode_sse41(
34 const unsigned char *in,
35 unsigned char *out,
36 size_t len,
37 bool url_safe_encoding) {
38 (void)in;
39 (void)out;
40 (void)len;
41 (void)url_safe_encoding;
42 AWS_ASSERT(false);
43 }
44 static inline bool aws_common_private_has_avx2(void) {
45 return false;
46 }
47 #endif
48
49 static const uint8_t *HEX_CHARS = (const uint8_t *)"0123456789abcdef";
50
51 static const uint8_t BASE64_SENTINEL_VALUE = 0xff;
52 static const uint8_t BASE64_ENCODING_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
53 static const uint8_t BASE64_URL_ENCODING_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
54
55 /* in this table, 0xDD is an invalid decoded value, if you have to do byte counting for any reason, there's 16 bytes
56 * per row. Reformatting is turned off to make sure this stays as 16 bytes per line. */
57 /* clang-format off */
58 static const uint8_t BASE64_DECODING_TABLE[256] = {
59 64, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
60 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
61 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 62, 0xDD, 62, 0xDD, 63,
62 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xDD, 0xDD, 0xDD, 255, 0xDD, 0xDD,
63 0xDD, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
64 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xDD, 0xDD, 0xDD, 0xDD, 63,
65 0xDD, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
66 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
67 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
68 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
69 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
70 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
71 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
72 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
73 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
74 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD};
75 /* clang-format on */
76
77 int aws_hex_compute_encoded_len(size_t to_encode_len, size_t *encoded_length) {
78 AWS_ASSERT(encoded_length);
79
80 /* For every byte of input, there will be 2 hex chars of encoded output */
81
82 size_t temp = to_encode_len << 1;
83
84 if (AWS_UNLIKELY(temp < to_encode_len)) {
85 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
86 }
87
88 *encoded_length = temp;
89
90 return AWS_OP_SUCCESS;
91 }
92
93 int aws_hex_encode(const struct aws_byte_cursor *AWS_RESTRICT to_encode, struct aws_byte_buf *AWS_RESTRICT output) {
94 AWS_PRECONDITION(aws_byte_cursor_is_valid(to_encode));
95 AWS_PRECONDITION(aws_byte_buf_is_valid(output));
96
97 size_t encoded_len = 0;
98
99 if (AWS_UNLIKELY(aws_hex_compute_encoded_len(to_encode->len, &encoded_len))) {
100 return AWS_OP_ERR;
101 }
102
103 if (AWS_UNLIKELY(output->capacity < encoded_len)) {
104 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
105 }
106
107 size_t written = 0;
108 for (size_t i = 0; i < to_encode->len; ++i) {
109
110 output->buffer[written++] = HEX_CHARS[to_encode->ptr[i] >> 4 & 0x0f];
111 output->buffer[written++] = HEX_CHARS[to_encode->ptr[i] & 0x0f];
112 }
113
114 AWS_ASSERT(written == encoded_len);
115 output->len = encoded_len;
116
117 return AWS_OP_SUCCESS;
118 }
119
120 int aws_hex_encode_append_dynamic(
121 const struct aws_byte_cursor *AWS_RESTRICT to_encode,
122 struct aws_byte_buf *AWS_RESTRICT output) {
123 AWS_ASSERT(to_encode->ptr);
124 AWS_ASSERT(aws_byte_buf_is_valid(output));
125
126 size_t encoded_len = 0;
127 if (AWS_UNLIKELY(aws_add_size_checked(to_encode->len, to_encode->len, &encoded_len))) {
128 return AWS_OP_ERR;
129 }
130
131 if (AWS_UNLIKELY(aws_byte_buf_reserve_relative(output, encoded_len))) {
132 return AWS_OP_ERR;
133 }
134
135 size_t written = output->len;
136 for (size_t i = 0; i < to_encode->len; ++i) {
137
138 output->buffer[written++] = HEX_CHARS[to_encode->ptr[i] >> 4 & 0x0f];
139 output->buffer[written++] = HEX_CHARS[to_encode->ptr[i] & 0x0f];
140 }
141
142 output->len += encoded_len;
143
144 return AWS_OP_SUCCESS;
145 }
146
147 static int s_hex_decode_char_to_int(char character, uint8_t *int_val) {
148 if (character >= 'a' && character <= 'f') {
149 *int_val = (uint8_t)(10 + (character - 'a'));
150 return 0;
151 }
152
153 if (character >= 'A' && character <= 'F') {
154 *int_val = (uint8_t)(10 + (character - 'A'));
155 return 0;
156 }
157
158 if (character >= '0' && character <= '9') {
159 *int_val = (uint8_t)(character - '0');
160 return 0;
161 }
162
163 return AWS_OP_ERR;
164 }
165
166 int aws_hex_compute_decoded_len(size_t to_decode_len, size_t *decoded_len) {
167 AWS_ASSERT(decoded_len);
168
169 /* For every 2 hex chars (rounded up) of encoded input, there will be 1 byte of decoded output.
170 * Rounding is because if buffer isn't even, we'll pretend there's an extra '0' at start of buffer */
171
172 /* adding 1 before dividing by 2 is a trick to round up during division */
173 size_t temp = (to_decode_len + 1);
174
175 if (AWS_UNLIKELY(temp < to_decode_len)) {
176 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
177 }
178
179 *decoded_len = temp >> 1;
180 return AWS_OP_SUCCESS;
181 }
182
183 int aws_hex_decode(const struct aws_byte_cursor *AWS_RESTRICT to_decode, struct aws_byte_buf *AWS_RESTRICT output) {
184 AWS_PRECONDITION(aws_byte_cursor_is_valid(to_decode));
185 AWS_PRECONDITION(aws_byte_buf_is_valid(output));
186
187 size_t decoded_length = 0;
188
189 if (AWS_UNLIKELY(aws_hex_compute_decoded_len(to_decode->len, &decoded_length))) {
190 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
191 }
192
193 if (AWS_UNLIKELY(output->capacity < decoded_length)) {
194 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
195 }
196
197 size_t written = 0;
198 size_t i = 0;
199 uint8_t high_value = 0;
200 uint8_t low_value = 0;
201
202 /* if the buffer isn't even, prepend a 0 to the buffer. */
203 if (AWS_UNLIKELY(to_decode->len & 0x01)) {
204 i = 1;
205 if (s_hex_decode_char_to_int((char)to_decode->ptr[0], &low_value)) {
206 return aws_raise_error(AWS_ERROR_INVALID_HEX_STR);
207 }
208
209 output->buffer[written++] = low_value;
210 }
211
212 for (; i < to_decode->len; i += 2) {
213 if (AWS_UNLIKELY(
214 s_hex_decode_char_to_int(to_decode->ptr[i], &high_value) ||
215 s_hex_decode_char_to_int(to_decode->ptr[i + 1], &low_value))) {
216 return aws_raise_error(AWS_ERROR_INVALID_HEX_STR);
217 }
218
219 uint8_t value = (uint8_t)(high_value << 4);
220 value |= low_value;
221 output->buffer[written++] = value;
222 }
223
224 output->len = decoded_length;
225
226 return AWS_OP_SUCCESS;
227 }
228
229 int aws_base64_compute_encoded_len(size_t to_encode_len, size_t *encoded_len) {
230 AWS_ERROR_PRECONDITION(encoded_len);
231
232 /* For every 3 bytes (rounded up) of unencoded input, there will be 4 ascii characters of encoded output.
233 * Rounding is because the output will be padded with '=' chars if necessary to make it divisible by 4. */
234
235 /* adding 2 before dividing by 3 is a trick to round up during division */
236 size_t tmp = 0;
237
238 if (AWS_UNLIKELY(aws_add_size_checked(to_encode_len, 2, &tmp))) {
239 return AWS_OP_ERR;
240 }
241
242 tmp /= 3;
243 if (AWS_UNLIKELY(aws_mul_size_checked(tmp, 4, &tmp))) {
244 return AWS_OP_ERR;
245 }
246
247 *encoded_len = tmp;
248
249 return AWS_OP_SUCCESS;
250 }
251
252 int aws_base64_url_compute_encoded_len(size_t to_encode_len, size_t *encoded_len) {
253 AWS_ERROR_PRECONDITION(encoded_len);
254
255 /* Just do direct math for each each 6 bits map to char. +5 is same trick to as before to round up. */
256
257 size_t tmp = 0;
258
259 if (AWS_UNLIKELY(aws_mul_size_checked(to_encode_len, 8, &tmp))) {
260 return AWS_OP_ERR;
261 }
262
263 if (AWS_UNLIKELY(aws_add_size_checked(tmp, 5, &tmp))) {
264 return AWS_OP_ERR;
265 }
266
267 tmp /= 6;
268
269 *encoded_len = tmp;
270
271 return AWS_OP_SUCCESS;
272 }
273
274 bool s_ispadding(uint8_t ch) {
275 return ch == '=';
276 }
277
278 int aws_base64_compute_decoded_len(const struct aws_byte_cursor *AWS_RESTRICT to_decode, size_t *decoded_len) {
279 AWS_ASSERT(to_decode);
280 AWS_ASSERT(decoded_len);
281
282 /* strip padding */
283 struct aws_byte_cursor trimmed = aws_byte_cursor_right_trim_pred(to_decode, s_ispadding);
284
285 const size_t len = trimmed.len;
286
287 if (len == 0) {
288 *decoded_len = 0;
289 return AWS_OP_SUCCESS;
290 }
291
292 /* impossible len */
293 if (AWS_UNLIKELY(len % 4 == 1)) {
294 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
295 }
296
297 /* For every 4 ascii characters of encoded input, there will be 3 bytes of decoded output. */
298 size_t decoded_len_tmp = 0;
299
300 if (aws_mul_size_checked(len, 3, &decoded_len_tmp)) {
301 return AWS_OP_ERR;
302 }
303
304 decoded_len_tmp >>= 2;
305
306 /* But last two ascii chars might be padding. */
307
308 *decoded_len = decoded_len_tmp;
309 return AWS_OP_SUCCESS;
310 }
311
312 static int s_base64_encode(
313 const struct aws_byte_cursor *AWS_RESTRICT to_encode,
314 struct aws_byte_buf *AWS_RESTRICT output,
315 bool do_url_safe_encoding) {
316
317 size_t encoded_length = 0;
318 if (do_url_safe_encoding) {
319 if (AWS_UNLIKELY(aws_base64_url_compute_encoded_len(to_encode->len, &encoded_length))) {
320 return AWS_OP_ERR;
321 }
322 } else {
323 if (AWS_UNLIKELY(aws_base64_compute_encoded_len(to_encode->len, &encoded_length))) {
324 return AWS_OP_ERR;
325 }
326 }
327
328 size_t needed_capacity = 0;
329 if (AWS_UNLIKELY(aws_add_size_checked(output->len, encoded_length, &needed_capacity))) {
330 return AWS_OP_ERR;
331 }
332
333 if (AWS_UNLIKELY(output->capacity < needed_capacity)) {
334 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
335 }
336
337 AWS_ASSERT(needed_capacity == 0 || output->buffer != NULL);
338
339 /*
340 * Note: avx2 impl currently does not support url base64 (no padding -> output not divisible by 4 -> it writes out
341 * of bounds). Just use software version for now (since need for base64 url is small) instead of hacking together
342 * half hearted avx2 impl.
343 */
344 if (!do_url_safe_encoding && aws_common_private_has_avx2()) {
345 aws_common_private_base64_encode_sse41(
346 to_encode->ptr, output->buffer + output->len, to_encode->len, do_url_safe_encoding);
347 output->len += encoded_length;
348 return AWS_OP_SUCCESS;
349 }
350
351 size_t buffer_length = to_encode->len;
352 size_t block_count = (buffer_length + 2) / 3;
353 size_t remainder_count = (buffer_length % 3);
354 size_t str_index = output->len;
355
356 const uint8_t *encoding_table = do_url_safe_encoding ? BASE64_URL_ENCODING_TABLE : BASE64_ENCODING_TABLE;
357
358 for (size_t i = 0; i < buffer_length; i += 3) {
359 uint32_t block = to_encode->ptr[i];
360
361 block <<= 8;
362 if (AWS_LIKELY(i + 1 < buffer_length)) {
363 block = block | to_encode->ptr[i + 1];
364 }
365
366 block <<= 8;
367 if (AWS_LIKELY(i + 2 < buffer_length)) {
368 block = block | to_encode->ptr[i + 2];
369 }
370
371 output->buffer[str_index++] = encoding_table[(block >> 18) & 0x3F];
372 output->buffer[str_index++] = encoding_table[(block >> 12) & 0x3F];
373 if (AWS_LIKELY(i + 1 < buffer_length)) {
374 output->buffer[str_index++] = encoding_table[(block >> 6) & 0x3F];
375 if (AWS_LIKELY(i + 2 < buffer_length)) {
376 output->buffer[str_index++] = encoding_table[block & 0x3F];
377 }
378 }
379 }
380
381 if (!do_url_safe_encoding && remainder_count > 0) {
382 output->buffer[output->len + block_count * 4 - 1] = '=';
383 if (remainder_count == 1) {
384 output->buffer[output->len + block_count * 4 - 2] = '=';
385 }
386 }
387
388 output->len += encoded_length;
389
390 return AWS_OP_SUCCESS;
391 }
392
393 int aws_base64_encode(const struct aws_byte_cursor *AWS_RESTRICT to_encode, struct aws_byte_buf *AWS_RESTRICT output) {
394 return s_base64_encode(to_encode, output, false);
395 }
396
397 int aws_base64_url_encode(
398 const struct aws_byte_cursor *AWS_RESTRICT to_encode,
399 struct aws_byte_buf *AWS_RESTRICT output) {
400 return s_base64_encode(to_encode, output, true);
401 }
402
403 static inline int s_base64_get_decoded_value(unsigned char to_decode, uint8_t *value, int8_t allow_sentinel) {
404
405 uint8_t decode_value = BASE64_DECODING_TABLE[(size_t)to_decode];
406 if (decode_value != 0xDD && (decode_value != BASE64_SENTINEL_VALUE || allow_sentinel)) {
407 *value = decode_value;
408 return AWS_OP_SUCCESS;
409 }
410
411 return AWS_OP_ERR;
412 }
413
414 int aws_base64_decode(const struct aws_byte_cursor *AWS_RESTRICT to_decode, struct aws_byte_buf *AWS_RESTRICT output) {
415 size_t decoded_length = 0;
416
417 if (AWS_UNLIKELY(aws_base64_compute_decoded_len(to_decode, &decoded_length))) {
418 return AWS_OP_ERR;
419 }
420
421 if (output->capacity < decoded_length) {
422 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
423 }
424
425 /*
426 * Note: avx2 version relies on input being padded to 4 byte boundary.
427 * Regular base64 is always padded to 4, but for url variant padding is skipped.
428 * Fall back to software version for inputs that are not divisible by 4 cleanly (aka base64 url),
429 * as those are a corner case and we dont need them as often.
430 * Reconsider, writing intrinsic version is usage becomes more widespread.
431 */
432 if ((to_decode->len % 4 == 0) && aws_common_private_has_avx2()) {
433 size_t result = aws_common_private_base64_decode_sse41(to_decode->ptr, output->buffer, to_decode->len);
434 if (result == SIZE_MAX) {
435 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
436 }
437
438 output->len = result;
439 return AWS_OP_SUCCESS;
440 }
441
442 int64_t block_count = (int64_t)(to_decode->len + 3) / 4;
443
444 size_t remainder = to_decode->len % 4;
445 size_t string_index = 0;
446 uint8_t value1 = 0, value2 = 0, value3 = 0, value4 = 0;
447 int64_t buffer_index = 0;
448
449 for (int64_t i = 0; i < block_count - 1; ++i) {
450 if (AWS_UNLIKELY(
451 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value1, 0) ||
452 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value2, 0) ||
453 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value3, 0) ||
454 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value4, 0))) {
455 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
456 }
457
458 buffer_index = i * 3;
459 output->buffer[buffer_index++] = (uint8_t)((value1 << 2) | ((value2 >> 4) & 0x03));
460 output->buffer[buffer_index++] = (uint8_t)(((value2 << 4) & 0xF0) | ((value3 >> 2) & 0x0F));
461 output->buffer[buffer_index] = (uint8_t)((value3 & 0x03) << 6 | value4);
462 }
463
464 buffer_index = (block_count - 1) * 3;
465
466 if (buffer_index >= 0) {
467 if (s_base64_get_decoded_value(to_decode->ptr[string_index++], &value1, 0) ||
468 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value2, 0)) {
469 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
470 }
471
472 value3 = BASE64_SENTINEL_VALUE;
473 value4 = BASE64_SENTINEL_VALUE;
474
475 if ((remainder == 3 || remainder == 0) &&
476 s_base64_get_decoded_value(to_decode->ptr[string_index++], &value3, 1)) {
477 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
478 }
479
480 if (remainder == 0 && s_base64_get_decoded_value(to_decode->ptr[string_index++], &value4, 1)) {
481 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
482 }
483
484 /* Reject interior '=' followed by non-'=' (e.g. "AB=D") per RFC 4648:
485 * '=' is only valid at the end of encoded data. */
486 if (value3 == BASE64_SENTINEL_VALUE && value4 != BASE64_SENTINEL_VALUE) {
487 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
488 }
489
490 output->buffer[buffer_index++] = (uint8_t)((value1 << 2) | ((value2 >> 4) & 0x03));
491
492 if (value3 != BASE64_SENTINEL_VALUE) {
493 output->buffer[buffer_index++] = (uint8_t)(((value2 << 4) & 0xF0) | ((value3 >> 2) & 0x0F));
494 if (value4 != BASE64_SENTINEL_VALUE) {
495 output->buffer[buffer_index++] = (uint8_t)((value3 & 0x03) << 6 | value4);
496 }
497 }
498 }
499 output->len = decoded_length;
500
501 /* Sanity check: bytes written must match the precomputed decoded length */
502 if (buffer_index >= 0 && (size_t)buffer_index != decoded_length) {
503 output->len = 0;
504 return aws_raise_error(AWS_ERROR_INVALID_BASE64_STR);
505 }
506
507 return AWS_OP_SUCCESS;
508 }
509
510 struct aws_utf8_decoder {
511 struct aws_allocator *alloc;
512 /* Value of current codepoint, updated as we read each byte */
513 uint32_t codepoint;
514 /* Minimum value that current codepoint is allowed to end up with
515 * (i.e. text cannot use 2 bytes to encode what would have fit in 1 byte) */
516 uint32_t min;
517 /* Number of bytes remaining the current codepoint */
518 uint8_t remaining;
519 /* Custom callback */
520 int (*on_codepoint)(uint32_t codepoint, void *user_data);
521 /* user_data for on_codepoint */
522 void *user_data;
523 };
524
525 struct aws_utf8_decoder *aws_utf8_decoder_new(
526 struct aws_allocator *allocator,
527 const struct aws_utf8_decoder_options *options) {
528
529 struct aws_utf8_decoder *decoder = aws_mem_calloc(allocator, 1, sizeof(struct aws_utf8_decoder));
530 decoder->alloc = allocator;
531 if (options) {
532 decoder->on_codepoint = options->on_codepoint;
533 decoder->user_data = options->user_data;
534 }
535 return decoder;
536 }
537
538 void aws_utf8_decoder_destroy(struct aws_utf8_decoder *decoder) {
539 if (decoder) {
540 aws_mem_release(decoder->alloc, decoder);
541 }
542 }
543
544 void aws_utf8_decoder_reset(struct aws_utf8_decoder *decoder) {
545 decoder->codepoint = 0;
546 decoder->min = 0;
547 decoder->remaining = 0;
548 }
549
550 /* Why yes, this could be optimized. */
551 int aws_utf8_decoder_update(struct aws_utf8_decoder *decoder, struct aws_byte_cursor bytes) {
552
553 /* We're respecting RFC-3629, which uses 1 to 4 byte sequences (never 5 or 6) */
554 for (size_t i = 0; i < bytes.len; ++i) {
555 uint8_t byte = bytes.ptr[i];
556
557 if (decoder->remaining == 0) {
558 /* Check first byte of the codepoint to determine how many more bytes remain */
559 if ((byte & 0x80) == 0x00) {
560 /* 1 byte codepoints start with 0xxxxxxx */
561 decoder->remaining = 0;
562 decoder->codepoint = byte;
563 decoder->min = 0;
564 } else if ((byte & 0xE0) == 0xC0) {
565 /* 2 byte codepoints start with 110xxxxx */
566 decoder->remaining = 1;
567 decoder->codepoint = byte & 0x1F;
568 decoder->min = 0x80;
569 } else if ((byte & 0xF0) == 0xE0) {
570 /* 3 byte codepoints start with 1110xxxx */
571 decoder->remaining = 2;
572 decoder->codepoint = byte & 0x0F;
573 decoder->min = 0x800;
574 } else if ((byte & 0xF8) == 0xF0) {
575 /* 4 byte codepoints start with 11110xxx */
576 decoder->remaining = 3;
577 decoder->codepoint = byte & 0x07;
578 decoder->min = 0x10000;
579 } else {
580 return aws_raise_error(AWS_ERROR_INVALID_UTF8);
581 }
582 } else {
583 /* This is not the first byte of a codepoint.
584 * Ensure it starts with 10xxxxxx*/
585 if ((byte & 0xC0) != 0x80) {
586 return aws_raise_error(AWS_ERROR_INVALID_UTF8);
587 }
588
589 /* Insert the 6 newly decoded bits:
590 * shifting left anything we've already decoded, and insert the new bits to the right */
591 decoder->codepoint = (decoder->codepoint << 6) | (byte & 0x3F);
592
593 /* If we've decoded the whole codepoint, check it for validity
594 * (don't need to do these particular checks on 1 byte codepoints) */
595 if (--decoder->remaining == 0) {
596 /* Check that it's not "overlong" (encoded using more bytes than necessary) */
597 if (decoder->codepoint < decoder->min) {
598 return aws_raise_error(AWS_ERROR_INVALID_UTF8);
599 }
600
601 /* UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF,
602 * which are reserved for use with the UTF-16 encoding form (as
603 * surrogate pairs) and do not directly represent characters */
604 if (decoder->codepoint >= 0xD800 && decoder->codepoint <= 0xDFFF) {
605 return aws_raise_error(AWS_ERROR_INVALID_UTF8);
606 }
607 }
608 }
609
610 /* Invoke user's on_codepoint callback */
611 if (decoder->on_codepoint && decoder->remaining == 0) {
612 if (decoder->on_codepoint(decoder->codepoint, decoder->user_data)) {
613 return AWS_OP_ERR;
614 }
615 }
616 }
617
618 return AWS_OP_SUCCESS;
619 }
620
621 int aws_utf8_decoder_finalize(struct aws_utf8_decoder *decoder) {
622 bool valid = decoder->remaining == 0;
623 aws_utf8_decoder_reset(decoder);
624 if (AWS_LIKELY(valid)) {
625 return AWS_OP_SUCCESS;
626 }
627 return aws_raise_error(AWS_ERROR_INVALID_UTF8);
628 }
629
630 int aws_decode_utf8(struct aws_byte_cursor bytes, const struct aws_utf8_decoder_options *options) {
631 struct aws_utf8_decoder decoder = {
632 .on_codepoint = options ? options->on_codepoint : NULL,
633 .user_data = options ? options->user_data : NULL,
634 };
635
636 if (aws_utf8_decoder_update(&decoder, bytes)) {
637 return AWS_OP_ERR;
638 }
639
640 if (aws_utf8_decoder_finalize(&decoder)) {
641 return AWS_OP_ERR;
642 }
643
644 return AWS_OP_SUCCESS;
645 }