Debian Codegraph @

crt/aws-c-common/source/byte_buf.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/byte_buf.h>
7 #include <aws/common/private/byte_buf.h>
8
9 #include <stdarg.h>
10
11 #ifdef _MSC_VER
12 /* disables warning non const declared initializers for Microsoft compilers */
13 # pragma warning(disable : 4204)
14 # pragma warning(disable : 4706)
15 #endif
16
17 int aws_byte_buf_init(struct aws_byte_buf *buf, struct aws_allocator *allocator, size_t capacity) {
18 AWS_PRECONDITION(buf);
19 AWS_PRECONDITION(allocator);
20
21 buf->buffer = (capacity == 0) ? NULL : aws_mem_acquire(allocator, capacity);
22 if (capacity != 0 && buf->buffer == NULL) {
23 AWS_ZERO_STRUCT(*buf);
24 return AWS_OP_ERR;
25 }
26
27 buf->len = 0;
28 buf->capacity = capacity;
29 buf->allocator = allocator;
30 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
31 return AWS_OP_SUCCESS;
32 }
33
34 int aws_byte_buf_init_copy(struct aws_byte_buf *dest, struct aws_allocator *allocator, const struct aws_byte_buf *src) {
35 AWS_PRECONDITION(allocator);
36 AWS_PRECONDITION(dest);
37 AWS_ERROR_PRECONDITION(aws_byte_buf_is_valid(src));
38
39 if (!src->buffer) {
40 AWS_ZERO_STRUCT(*dest);
41 dest->allocator = allocator;
42 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
43 return AWS_OP_SUCCESS;
44 }
45
46 *dest = *src;
47 dest->allocator = allocator;
48 dest->buffer = (uint8_t *)aws_mem_acquire(allocator, src->capacity);
49 if (dest->buffer == NULL) {
50 AWS_ZERO_STRUCT(*dest);
51 return AWS_OP_ERR;
52 }
53 memcpy(dest->buffer, src->buffer, src->len);
54 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
55 return AWS_OP_SUCCESS;
56 }
57
58 bool aws_byte_buf_is_valid(const struct aws_byte_buf *const buf) {
59 return buf != NULL &&
60 ((buf->capacity == 0 && buf->len == 0 && buf->buffer == NULL) ||
61 (buf->capacity > 0 && buf->len <= buf->capacity && AWS_MEM_IS_WRITABLE(buf->buffer, buf->capacity)));
62 }
63
64 bool aws_byte_cursor_is_valid(const struct aws_byte_cursor *cursor) {
65 return cursor != NULL &&
66 ((cursor->len == 0) || (cursor->len > 0 && cursor->ptr && AWS_MEM_IS_READABLE(cursor->ptr, cursor->len)));
67 }
68
69 void aws_byte_buf_reset(struct aws_byte_buf *buf, bool zero_contents) {
70 if (zero_contents) {
71 aws_byte_buf_secure_zero(buf);
72 }
73 buf->len = 0;
74 }
75
76 void aws_byte_buf_clean_up(struct aws_byte_buf *buf) {
77 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
78 if (buf->allocator && buf->buffer) {
79 aws_mem_release(buf->allocator, (void *)buf->buffer);
80 }
81 buf->allocator = NULL;
82 buf->buffer = NULL;
83 buf->len = 0;
84 buf->capacity = 0;
85 }
86
87 void aws_byte_buf_secure_zero(struct aws_byte_buf *buf) {
88 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
89 if (buf->buffer) {
90 aws_secure_zero(buf->buffer, buf->capacity);
91 }
92 buf->len = 0;
93 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
94 }
95
96 void aws_byte_buf_clean_up_secure(struct aws_byte_buf *buf) {
97 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
98 aws_byte_buf_secure_zero(buf);
99 aws_byte_buf_clean_up(buf);
100 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
101 }
102
103 bool aws_byte_buf_eq(const struct aws_byte_buf *const a, const struct aws_byte_buf *const b) {
104 AWS_PRECONDITION(aws_byte_buf_is_valid(a));
105 AWS_PRECONDITION(aws_byte_buf_is_valid(b));
106 bool rval = aws_array_eq(a->buffer, a->len, b->buffer, b->len);
107 AWS_POSTCONDITION(aws_byte_buf_is_valid(a));
108 AWS_POSTCONDITION(aws_byte_buf_is_valid(b));
109 return rval;
110 }
111
112 bool aws_byte_buf_eq_ignore_case(const struct aws_byte_buf *const a, const struct aws_byte_buf *const b) {
113 AWS_PRECONDITION(aws_byte_buf_is_valid(a));
114 AWS_PRECONDITION(aws_byte_buf_is_valid(b));
115 bool rval = aws_array_eq_ignore_case(a->buffer, a->len, b->buffer, b->len);
116 AWS_POSTCONDITION(aws_byte_buf_is_valid(a));
117 AWS_POSTCONDITION(aws_byte_buf_is_valid(b));
118 return rval;
119 }
120
121 bool aws_byte_buf_eq_c_str(const struct aws_byte_buf *const buf, const char *const c_str) {
122 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
123 AWS_PRECONDITION(c_str != NULL);
124 bool rval = aws_array_eq_c_str(buf->buffer, buf->len, c_str);
125 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
126 return rval;
127 }
128
129 bool aws_byte_buf_eq_c_str_ignore_case(const struct aws_byte_buf *const buf, const char *const c_str) {
130 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
131 AWS_PRECONDITION(c_str != NULL);
132 bool rval = aws_array_eq_c_str_ignore_case(buf->buffer, buf->len, c_str);
133 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
134 return rval;
135 }
136
137 int aws_byte_buf_init_copy_from_cursor(
138 struct aws_byte_buf *dest,
139 struct aws_allocator *allocator,
140 struct aws_byte_cursor src) {
141 AWS_PRECONDITION(allocator);
142 AWS_PRECONDITION(dest);
143 AWS_ERROR_PRECONDITION(aws_byte_cursor_is_valid(&src));
144
145 AWS_ZERO_STRUCT(*dest);
146
147 dest->buffer = (src.len > 0) ? (uint8_t *)aws_mem_acquire(allocator, src.len) : NULL;
148 if (src.len != 0 && dest->buffer == NULL) {
149 return AWS_OP_ERR;
150 }
151
152 dest->len = src.len;
153 dest->capacity = src.len;
154 dest->allocator = allocator;
155 if (src.len > 0) {
156 memcpy(dest->buffer, src.ptr, src.len);
157 }
158 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
159 return AWS_OP_SUCCESS;
160 }
161
162 int aws_byte_buf_init_cache_and_update_cursors(struct aws_byte_buf *dest, struct aws_allocator *allocator, ...) {
163 AWS_PRECONDITION(allocator);
164 AWS_PRECONDITION(dest);
165
166 AWS_ZERO_STRUCT(*dest);
167
168 size_t total_len = 0;
169 va_list args;
170 va_start(args, allocator);
171
172 /* Loop until final NULL arg is encountered */
173 struct aws_byte_cursor *cursor_i;
174 while ((cursor_i = va_arg(args, struct aws_byte_cursor *)) != NULL) {
175 AWS_ASSERT(aws_byte_cursor_is_valid(cursor_i));
176 if (aws_add_size_checked(total_len, cursor_i->len, &total_len)) {
177 va_end(args);
178 return AWS_OP_ERR;
179 }
180 }
181 va_end(args);
182
183 if (aws_byte_buf_init(dest, allocator, total_len)) {
184 return AWS_OP_ERR;
185 }
186
187 va_start(args, allocator);
188 while ((cursor_i = va_arg(args, struct aws_byte_cursor *)) != NULL) {
189 /* Impossible for this call to fail, we pre-allocated sufficient space */
190 aws_byte_buf_append_and_update(dest, cursor_i);
191 }
192 va_end(args);
193
194 return AWS_OP_SUCCESS;
195 }
196
197 bool aws_byte_cursor_next_split(
198 const struct aws_byte_cursor *AWS_RESTRICT input_str,
199 char split_on,
200 struct aws_byte_cursor *AWS_RESTRICT substr) {
201
202 struct aws_byte_cursor cur = {.ptr = (uint8_t *)&split_on, .len = 1};
203 return aws_byte_cursor_next_split_on_cursor(input_str, cur, substr);
204 }
205
206 bool aws_byte_cursor_next_split_on_cursor(
207 const struct aws_byte_cursor *AWS_RESTRICT input_str,
208 struct aws_byte_cursor split_on,
209 struct aws_byte_cursor *AWS_RESTRICT substr) {
210
211 AWS_PRECONDITION(aws_byte_cursor_is_valid(input_str));
212
213 /* If substr is zeroed-out, then this is the first run. */
214 const bool first_run = substr->ptr == NULL;
215
216 /* It's legal for input_str to be zeroed out: {.ptr=NULL, .len=0}
217 * Deal with this case separately */
218 if (AWS_UNLIKELY(input_str->ptr == NULL)) {
219 if (first_run) {
220 /* Set substr->ptr to something non-NULL so that next split() call doesn't look like the first run */
221 substr->ptr = (void *)"";
222 substr->len = 0;
223 return true;
224 }
225
226 /* done */
227 AWS_ZERO_STRUCT(*substr);
228 return false;
229 }
230
231 /* Rest of function deals with non-NULL input_str->ptr */
232
233 if (first_run) {
234 *substr = *input_str;
235 } else {
236 /* This is not the first run.
237 * Advance substr past the previous split. */
238 const uint8_t *input_end = input_str->ptr + input_str->len;
239 substr->ptr += substr->len + split_on.len;
240
241 /* Note that it's ok if substr->ptr == input_end, this happens in the
242 * final valid split of an input_str that ends with the split_on character:
243 * Ex: "AB&" split on '&' produces "AB" and "" */
244 if (substr->ptr > input_end || substr->ptr < input_str->ptr) { /* 2nd check is overflow check */
245 /* done */
246 AWS_ZERO_STRUCT(*substr);
247 return false;
248 }
249
250 /* update len to be remainder of the string */
251 substr->len = input_str->len - (substr->ptr - input_str->ptr);
252 }
253
254 /* substr is now remainder of string, search for next split */
255 struct aws_byte_cursor found_cur = {0};
256 if (!aws_byte_cursor_find_exact(substr, &split_on, &found_cur)) {
257
258 /* Character found, update string length. */
259 substr->len = found_cur.ptr - substr->ptr;
260 }
261
262 AWS_POSTCONDITION(aws_byte_cursor_is_valid(substr));
263 return true;
264 }
265
266 int aws_byte_cursor_split_on_char_n(
267 const struct aws_byte_cursor *AWS_RESTRICT input_str,
268 char split_on,
269 size_t n,
270 struct aws_array_list *AWS_RESTRICT output) {
271 AWS_ASSERT(aws_byte_cursor_is_valid(input_str));
272 AWS_ASSERT(output);
273 AWS_ASSERT(output->item_size >= sizeof(struct aws_byte_cursor));
274
275 size_t max_splits = n > 0 ? n : SIZE_MAX;
276 size_t split_count = 0;
277
278 struct aws_byte_cursor substr;
279 AWS_ZERO_STRUCT(substr);
280
281 /* Until we run out of substrs or hit the max split count, keep iterating and pushing into the array list. */
282 while (split_count <= max_splits && aws_byte_cursor_next_split(input_str, split_on, &substr)) {
283
284 if (split_count == max_splits) {
285 /* If this is the last split, take the rest of the string. */
286 substr.len = input_str->len - (substr.ptr - input_str->ptr);
287 }
288
289 if (AWS_UNLIKELY(aws_array_list_push_back(output, (const void *)&substr))) {
290 return AWS_OP_ERR;
291 }
292 ++split_count;
293 }
294
295 return AWS_OP_SUCCESS;
296 }
297
298 int aws_byte_cursor_split_on_char(
299 const struct aws_byte_cursor *AWS_RESTRICT input_str,
300 char split_on,
301 struct aws_array_list *AWS_RESTRICT output) {
302
303 return aws_byte_cursor_split_on_char_n(input_str, split_on, 0, output);
304 }
305
306 int aws_byte_cursor_find_exact(
307 const struct aws_byte_cursor *AWS_RESTRICT input_str,
308 const struct aws_byte_cursor *AWS_RESTRICT to_find,
309 struct aws_byte_cursor *first_find) {
310 if (to_find->len > input_str->len) {
311 return aws_raise_error(AWS_ERROR_STRING_MATCH_NOT_FOUND);
312 }
313
314 if (to_find->len < 1) {
315 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
316 }
317
318 struct aws_byte_cursor working_cur = *input_str;
319
320 while (working_cur.len) {
321 uint8_t *first_char_location = memchr(working_cur.ptr, (char)*to_find->ptr, working_cur.len);
322
323 if (!first_char_location) {
324 return aws_raise_error(AWS_ERROR_STRING_MATCH_NOT_FOUND);
325 }
326
327 aws_byte_cursor_advance(&working_cur, first_char_location - working_cur.ptr);
328
329 if (working_cur.len < to_find->len) {
330 return aws_raise_error(AWS_ERROR_STRING_MATCH_NOT_FOUND);
331 }
332
333 if (!memcmp(working_cur.ptr, to_find->ptr, to_find->len)) {
334 *first_find = working_cur;
335 return AWS_OP_SUCCESS;
336 }
337
338 aws_byte_cursor_advance(&working_cur, 1);
339 }
340
341 return aws_raise_error(AWS_ERROR_STRING_MATCH_NOT_FOUND);
342 }
343
344 int aws_byte_buf_cat(struct aws_byte_buf *dest, size_t number_of_args, ...) {
345 AWS_PRECONDITION(aws_byte_buf_is_valid(dest));
346
347 va_list ap;
348 va_start(ap, number_of_args);
349
350 for (size_t i = 0; i < number_of_args; ++i) {
351 struct aws_byte_buf *buffer = va_arg(ap, struct aws_byte_buf *);
352 struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(buffer);
353
354 if (aws_byte_buf_append(dest, &cursor)) {
355 va_end(ap);
356 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
357 return AWS_OP_ERR;
358 }
359 }
360
361 va_end(ap);
362 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
363 return AWS_OP_SUCCESS;
364 }
365
366 bool aws_byte_cursor_eq(const struct aws_byte_cursor *a, const struct aws_byte_cursor *b) {
367 AWS_PRECONDITION(aws_byte_cursor_is_valid(a));
368 AWS_PRECONDITION(aws_byte_cursor_is_valid(b));
369 bool rv = aws_array_eq(a->ptr, a->len, b->ptr, b->len);
370 AWS_POSTCONDITION(aws_byte_cursor_is_valid(a));
371 AWS_POSTCONDITION(aws_byte_cursor_is_valid(b));
372 return rv;
373 }
374
375 bool aws_byte_cursor_eq_ignore_case(const struct aws_byte_cursor *a, const struct aws_byte_cursor *b) {
376 AWS_PRECONDITION(aws_byte_cursor_is_valid(a));
377 AWS_PRECONDITION(aws_byte_cursor_is_valid(b));
378 bool rv = aws_array_eq_ignore_case(a->ptr, a->len, b->ptr, b->len);
379 AWS_POSTCONDITION(aws_byte_cursor_is_valid(a));
380 AWS_POSTCONDITION(aws_byte_cursor_is_valid(b));
381 return rv;
382 }
383
384 /* Every possible uint8_t value, lowercased */
385 static const uint8_t s_tolower_table[] = {
386 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
387 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
388 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 'a',
389 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
390 'x', 'y', 'z', 91, 92, 93, 94, 95, 96, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
391 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 123, 124, 125, 126, 127, 128, 129, 130, 131,
392 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
393 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
394 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
395 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
396 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
397 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255};
398 AWS_STATIC_ASSERT(AWS_ARRAY_SIZE(s_tolower_table) == 256);
399
400 const uint8_t *aws_lookup_table_to_lower_get(void) {
401 return s_tolower_table;
402 }
403
404 bool aws_array_eq_ignore_case(
405 const void *const array_a,
406 const size_t len_a,
407 const void *const array_b,
408 const size_t len_b) {
409 AWS_PRECONDITION(
410 (len_a == 0) || AWS_MEM_IS_READABLE(array_a, len_a), "Input array [array_a] must be readable up to [len_a].");
411 AWS_PRECONDITION(
412 (len_b == 0) || AWS_MEM_IS_READABLE(array_b, len_b), "Input array [array_b] must be readable up to [len_b].");
413
414 if (len_a != len_b) {
415 return false;
416 }
417
418 const uint8_t *bytes_a = array_a;
419 const uint8_t *bytes_b = array_b;
420 for (size_t i = 0; i < len_a; ++i) {
421 if (s_tolower_table[bytes_a[i]] != s_tolower_table[bytes_b[i]]) {
422 return false;
423 }
424 }
425
426 return true;
427 }
428
429 bool aws_array_eq(const void *const array_a, const size_t len_a, const void *const array_b, const size_t len_b) {
430 AWS_PRECONDITION(
431 (len_a == 0) || AWS_MEM_IS_READABLE(array_a, len_a), "Input array [array_a] must be readable up to [len_a].");
432 AWS_PRECONDITION(
433 (len_b == 0) || AWS_MEM_IS_READABLE(array_b, len_b), "Input array [array_b] must be readable up to [len_b].");
434
435 if (len_a != len_b) {
436 return false;
437 }
438
439 if (len_a == 0) {
440 return true;
441 }
442
443 return !memcmp(array_a, array_b, len_a);
444 }
445
446 bool aws_array_eq_c_str_ignore_case(const void *const array, const size_t array_len, const char *const c_str) {
447 AWS_PRECONDITION(
448 array || (array_len == 0),
449 "Either input pointer [array_a] mustn't be NULL or input [array_len] mustn't be zero.");
450 AWS_PRECONDITION(c_str != NULL);
451
452 /* Simpler implementation could have been:
453 * return aws_array_eq_ignore_case(array, array_len, c_str, strlen(c_str));
454 * but that would have traversed c_str twice.
455 * This implementation traverses c_str just once. */
456
457 const uint8_t *array_bytes = array;
458 const uint8_t *str_bytes = (const uint8_t *)c_str;
459
460 for (size_t i = 0; i < array_len; ++i) {
461 uint8_t s = str_bytes[i];
462 if (s == '\0') {
463 return false;
464 }
465
466 if (s_tolower_table[array_bytes[i]] != s_tolower_table[s]) {
467 return false;
468 }
469 }
470
471 return str_bytes[array_len] == '\0';
472 }
473
474 bool aws_array_eq_c_str(const void *const array, const size_t array_len, const char *const c_str) {
475 AWS_PRECONDITION(
476 array || (array_len == 0),
477 "Either input pointer [array_a] mustn't be NULL or input [array_len] mustn't be zero.");
478 AWS_PRECONDITION(c_str != NULL);
479
480 /* Simpler implementation could have been:
481 * return aws_array_eq(array, array_len, c_str, strlen(c_str));
482 * but that would have traversed c_str twice.
483 * This implementation traverses c_str just once. */
484
485 const uint8_t *array_bytes = array;
486 const uint8_t *str_bytes = (const uint8_t *)c_str;
487
488 for (size_t i = 0; i < array_len; ++i) {
489 uint8_t s = str_bytes[i];
490 if (s == '\0') {
491 return false;
492 }
493
494 if (array_bytes[i] != s) {
495 return false;
496 }
497 }
498
499 return str_bytes[array_len] == '\0';
500 }
501
502 uint64_t aws_hash_array_ignore_case(const void *array, const size_t len) {
503 AWS_PRECONDITION(AWS_MEM_IS_READABLE(array, len));
504 /* FNV-1a: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function */
505 const uint64_t fnv_offset_basis = 0xcbf29ce484222325ULL;
506 const uint64_t fnv_prime = 0x100000001b3ULL;
507
508 const uint8_t *i = array;
509 const uint8_t *end = (i == NULL) ? NULL : (i + len);
510
511 uint64_t hash = fnv_offset_basis;
512 while (i != end) {
513 const uint8_t lower = s_tolower_table[*i++];
514 hash ^= lower;
515 #ifdef CBMC
516 # pragma CPROVER check push
517 # pragma CPROVER check disable "unsigned-overflow"
518 #endif
519 hash *= fnv_prime;
520 #ifdef CBMC
521 # pragma CPROVER check pop
522 #endif
523 }
524 return hash;
525 }
526
527 uint64_t aws_hash_byte_cursor_ptr_ignore_case(const void *item) {
528 AWS_PRECONDITION(aws_byte_cursor_is_valid(item));
529 const struct aws_byte_cursor *const cursor = item;
530 uint64_t rval = aws_hash_array_ignore_case(cursor->ptr, cursor->len);
531 AWS_POSTCONDITION(aws_byte_cursor_is_valid(item));
532 return rval;
533 }
534
535 bool aws_byte_cursor_eq_byte_buf(const struct aws_byte_cursor *const a, const struct aws_byte_buf *const b) {
536 AWS_PRECONDITION(aws_byte_cursor_is_valid(a));
537 AWS_PRECONDITION(aws_byte_buf_is_valid(b));
538 bool rv = aws_array_eq(a->ptr, a->len, b->buffer, b->len);
539 AWS_POSTCONDITION(aws_byte_cursor_is_valid(a));
540 AWS_POSTCONDITION(aws_byte_buf_is_valid(b));
541 return rv;
542 }
543
544 bool aws_byte_cursor_eq_byte_buf_ignore_case(
545 const struct aws_byte_cursor *const a,
546 const struct aws_byte_buf *const b) {
547 AWS_PRECONDITION(aws_byte_cursor_is_valid(a));
548 AWS_PRECONDITION(aws_byte_buf_is_valid(b));
549 bool rv = aws_array_eq_ignore_case(a->ptr, a->len, b->buffer, b->len);
550 AWS_POSTCONDITION(aws_byte_cursor_is_valid(a));
551 AWS_POSTCONDITION(aws_byte_buf_is_valid(b));
552 return rv;
553 }
554
555 bool aws_byte_cursor_eq_c_str(const struct aws_byte_cursor *const cursor, const char *const c_str) {
556 AWS_PRECONDITION(aws_byte_cursor_is_valid(cursor));
557 AWS_PRECONDITION(c_str != NULL);
558 bool rv = aws_array_eq_c_str(cursor->ptr, cursor->len, c_str);
559 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cursor));
560 return rv;
561 }
562
563 bool aws_byte_cursor_eq_c_str_ignore_case(const struct aws_byte_cursor *const cursor, const char *const c_str) {
564 AWS_PRECONDITION(aws_byte_cursor_is_valid(cursor));
565 AWS_PRECONDITION(c_str != NULL);
566 bool rv = aws_array_eq_c_str_ignore_case(cursor->ptr, cursor->len, c_str);
567 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cursor));
568 return rv;
569 }
570
571 bool aws_byte_cursor_starts_with(const struct aws_byte_cursor *input, const struct aws_byte_cursor *prefix) {
572
573 AWS_PRECONDITION(aws_byte_cursor_is_valid(input));
574 AWS_PRECONDITION(aws_byte_cursor_is_valid(prefix));
575
576 if (input->len < prefix->len) {
577 return false;
578 }
579
580 struct aws_byte_cursor start = {.ptr = input->ptr, .len = prefix->len};
581 bool rv = aws_byte_cursor_eq(&start, prefix);
582
583 AWS_POSTCONDITION(aws_byte_cursor_is_valid(input));
584 AWS_POSTCONDITION(aws_byte_cursor_is_valid(prefix));
585 return rv;
586 }
587
588 bool aws_byte_cursor_starts_with_ignore_case(
589 const struct aws_byte_cursor *input,
590 const struct aws_byte_cursor *prefix) {
591
592 AWS_PRECONDITION(aws_byte_cursor_is_valid(input));
593 AWS_PRECONDITION(aws_byte_cursor_is_valid(prefix));
594
595 if (input->len < prefix->len) {
596 return false;
597 }
598
599 struct aws_byte_cursor start = {.ptr = input->ptr, .len = prefix->len};
600 bool rv = aws_byte_cursor_eq_ignore_case(&start, prefix);
601
602 AWS_POSTCONDITION(aws_byte_cursor_is_valid(input));
603 AWS_POSTCONDITION(aws_byte_cursor_is_valid(prefix));
604 return rv;
605 }
606
607 int aws_byte_buf_append(struct aws_byte_buf *to, const struct aws_byte_cursor *from) {
608 AWS_PRECONDITION(aws_byte_buf_is_valid(to));
609 AWS_PRECONDITION(aws_byte_cursor_is_valid(from));
610
611 if (to->capacity - to->len < from->len) {
612 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
613 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
614 return aws_raise_error(AWS_ERROR_DEST_COPY_TOO_SMALL);
615 }
616
617 if (from->len > 0) {
618 /* This assert teaches clang-tidy that from->ptr and to->buffer cannot be null in a non-empty buffers */
619 AWS_ASSERT(from->ptr);
620 AWS_ASSERT(to->buffer);
621 memcpy(to->buffer + to->len, from->ptr, from->len);
622 to->len += from->len;
623 }
624
625 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
626 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
627 return AWS_OP_SUCCESS;
628 }
629
630 int aws_byte_buf_append_with_lookup(
631 struct aws_byte_buf *AWS_RESTRICT to,
632 const struct aws_byte_cursor *AWS_RESTRICT from,
633 const uint8_t *lookup_table) {
634 AWS_PRECONDITION(aws_byte_buf_is_valid(to));
635 AWS_PRECONDITION(aws_byte_cursor_is_valid(from));
636 AWS_PRECONDITION(
637 AWS_MEM_IS_READABLE(lookup_table, 256), "Input array [lookup_table] must be at least 256 bytes long.");
638
639 if (to->capacity - to->len < from->len) {
640 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
641 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
642 return aws_raise_error(AWS_ERROR_DEST_COPY_TOO_SMALL);
643 }
644
645 for (size_t i = 0; i < from->len; ++i) {
646 to->buffer[to->len + i] = lookup_table[from->ptr[i]];
647 }
648
649 if (aws_add_size_checked(to->len, from->len, &to->len)) {
650 return AWS_OP_ERR;
651 }
652
653 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
654 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
655 return AWS_OP_SUCCESS;
656 }
657
658 static int s_aws_byte_buf_append_dynamic(
659 struct aws_byte_buf *to,
660 const struct aws_byte_cursor *from,
661 bool clear_released_memory) {
662 AWS_PRECONDITION(aws_byte_buf_is_valid(to));
663 AWS_PRECONDITION(aws_byte_cursor_is_valid(from));
664 AWS_ERROR_PRECONDITION(to->allocator);
665
666 if (to->capacity - to->len < from->len) {
667 /*
668 * NewCapacity = Max(OldCapacity * 2, OldCapacity + MissingCapacity)
669 */
670 size_t missing_capacity = from->len - (to->capacity - to->len);
671
672 size_t required_capacity = 0;
673 if (aws_add_size_checked(to->capacity, missing_capacity, &required_capacity)) {
674 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
675 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
676 return AWS_OP_ERR;
677 }
678
679 /*
680 * It's ok if this overflows, just clamp to max possible.
681 * In theory this lets us still grow a buffer that's larger than 1/2 size_t space
682 * at least enough to accommodate the append.
683 */
684 size_t growth_capacity = aws_add_size_saturating(to->capacity, to->capacity);
685
686 size_t new_capacity = required_capacity;
687 if (new_capacity < growth_capacity) {
688 new_capacity = growth_capacity;
689 }
690
691 /*
692 * Attempt to resize - we intentionally do not use reserve() in order to preserve
693 * the (unlikely) use case of from and to being the same buffer range.
694 */
695
696 /*
697 * Try the max, but if that fails and the required is smaller, try it in fallback
698 */
699 uint8_t *new_buffer = aws_mem_acquire(to->allocator, new_capacity);
700 if (new_buffer == NULL) {
701 if (new_capacity > required_capacity) {
702 new_capacity = required_capacity;
703 new_buffer = aws_mem_acquire(to->allocator, new_capacity);
704 if (new_buffer == NULL) {
705 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
706 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
707 return AWS_OP_ERR;
708 }
709 } else {
710 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
711 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
712 return AWS_OP_ERR;
713 }
714 }
715
716 /*
717 * Copy old buffer -> new buffer
718 */
719 if (to->len > 0) {
720 memcpy(new_buffer, to->buffer, to->len);
721 }
722 /*
723 * Copy what we actually wanted to append in the first place
724 */
725 if (from->len > 0) {
726 memcpy(new_buffer + to->len, from->ptr, from->len);
727 }
728
729 if (clear_released_memory) {
730 aws_secure_zero(to->buffer, to->capacity);
731 }
732
733 /*
734 * Get rid of the old buffer
735 */
736 aws_mem_release(to->allocator, to->buffer);
737
738 /*
739 * Switch to the new buffer
740 */
741 to->buffer = new_buffer;
742 to->capacity = new_capacity;
743 } else {
744 if (from->len > 0) {
745 /* This assert teaches clang-tidy that from->ptr and to->buffer cannot be null in a non-empty buffers */
746 AWS_ASSERT(from->ptr);
747 AWS_ASSERT(to->buffer);
748 memcpy(to->buffer + to->len, from->ptr, from->len);
749 }
750 }
751
752 to->len += from->len;
753
754 AWS_POSTCONDITION(aws_byte_buf_is_valid(to));
755 AWS_POSTCONDITION(aws_byte_cursor_is_valid(from));
756 return AWS_OP_SUCCESS;
757 }
758
759 int aws_byte_buf_append_dynamic(struct aws_byte_buf *to, const struct aws_byte_cursor *from) {
760 return s_aws_byte_buf_append_dynamic(to, from, false);
761 }
762
763 int aws_byte_buf_append_auto(struct aws_byte_buf *to, const struct aws_byte_cursor *from) {
764 AWS_PRECONDITION(aws_byte_buf_is_valid(to));
765 AWS_PRECONDITION(aws_byte_cursor_is_valid(from));
766
767 /*
768 * Buffers without an allocator are externally-owned (e.g. by a
769 * buffer pool); they cannot grow, so use the static append path.
770 * Buffers with an allocator can grow, so use the dynamic path.
771 */
772 if (to->allocator != NULL) {
773 return aws_byte_buf_append_dynamic(to, from);
774 }
775 return aws_byte_buf_append(to, from);
776 }
777
778 int aws_byte_buf_append_dynamic_secure(struct aws_byte_buf *to, const struct aws_byte_cursor *from) {
779 return s_aws_byte_buf_append_dynamic(to, from, true);
780 }
781
782 static int s_aws_byte_buf_append_byte_dynamic(struct aws_byte_buf *buffer, uint8_t value, bool clear_released_memory) {
783 #if defined(_MSC_VER)
784 # pragma warning(push)
785 # pragma warning(disable : 4221)
786 #endif /* _MSC_VER */
787
788 /* msvc isn't a fan of this pointer-to-local assignment */
789 struct aws_byte_cursor eq_cursor = {.len = 1, .ptr = &value};
790
791 #if defined(_MSC_VER)
792 # pragma warning(pop)
793 #endif /* _MSC_VER */
794
795 return s_aws_byte_buf_append_dynamic(buffer, &eq_cursor, clear_released_memory);
796 }
797
798 int aws_byte_buf_append_byte_dynamic(struct aws_byte_buf *buffer, uint8_t value) {
799 return s_aws_byte_buf_append_byte_dynamic(buffer, value, false);
800 }
801
802 int aws_byte_buf_append_byte_dynamic_secure(struct aws_byte_buf *buffer, uint8_t value) {
803 return s_aws_byte_buf_append_byte_dynamic(buffer, value, true);
804 }
805
806 int aws_byte_buf_reserve(struct aws_byte_buf *buffer, size_t requested_capacity) {
807 AWS_ERROR_PRECONDITION(buffer->allocator);
808 AWS_ERROR_PRECONDITION(aws_byte_buf_is_valid(buffer));
809
810 if (requested_capacity <= buffer->capacity) {
811 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
812 return AWS_OP_SUCCESS;
813 }
814 if (!buffer->buffer && !buffer->capacity && requested_capacity > buffer->capacity) {
815 if (aws_byte_buf_init(buffer, buffer->allocator, requested_capacity)) {
816 return AWS_OP_ERR;
817 }
818 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
819 return AWS_OP_SUCCESS;
820 }
821 if (aws_mem_realloc(buffer->allocator, (void **)&buffer->buffer, buffer->capacity, requested_capacity)) {
822 return AWS_OP_ERR;
823 }
824
825 buffer->capacity = requested_capacity;
826
827 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
828 return AWS_OP_SUCCESS;
829 }
830
831 int aws_byte_buf_reserve_relative(struct aws_byte_buf *buffer, size_t additional_length) {
832 AWS_ERROR_PRECONDITION(buffer->allocator);
833 AWS_ERROR_PRECONDITION(aws_byte_buf_is_valid(buffer));
834
835 size_t requested_capacity = 0;
836 if (AWS_UNLIKELY(aws_add_size_checked(buffer->len, additional_length, &requested_capacity))) {
837 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
838 return AWS_OP_ERR;
839 }
840
841 return aws_byte_buf_reserve(buffer, requested_capacity);
842 }
843
844 int aws_byte_buf_reserve_smart(struct aws_byte_buf *buffer, size_t requested_capacity) {
845
846 if (requested_capacity <= buffer->capacity) {
847 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
848 return AWS_OP_SUCCESS;
849 }
850 size_t double_current_capacity = aws_add_size_saturating(buffer->capacity, buffer->capacity);
851 size_t new_capacity = aws_max_size(requested_capacity, double_current_capacity);
852 return aws_byte_buf_reserve(buffer, new_capacity);
853 }
854
855 int aws_byte_buf_reserve_smart_relative(struct aws_byte_buf *buffer, size_t additional_length) {
856 size_t requested_capacity = 0;
857 if (AWS_UNLIKELY(aws_add_size_checked(buffer->len, additional_length, &requested_capacity))) {
858 return AWS_OP_ERR;
859 }
860 return aws_byte_buf_reserve_smart(buffer, requested_capacity);
861 }
862
863 struct aws_byte_cursor aws_byte_cursor_right_trim_pred(
864 const struct aws_byte_cursor *source,
865 aws_byte_predicate_fn *predicate) {
866 AWS_PRECONDITION(aws_byte_cursor_is_valid(source));
867 AWS_PRECONDITION(predicate != NULL);
868 struct aws_byte_cursor trimmed = *source;
869
870 while (trimmed.len > 0 && predicate(*(trimmed.ptr + trimmed.len - 1))) {
871 --trimmed.len;
872 }
873 AWS_POSTCONDITION(aws_byte_cursor_is_valid(source));
874 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&trimmed));
875 return trimmed;
876 }
877
878 struct aws_byte_cursor aws_byte_cursor_left_trim_pred(
879 const struct aws_byte_cursor *source,
880 aws_byte_predicate_fn *predicate) {
881 AWS_PRECONDITION(aws_byte_cursor_is_valid(source));
882 AWS_PRECONDITION(predicate != NULL);
883 struct aws_byte_cursor trimmed = *source;
884
885 while (trimmed.len > 0 && predicate(*(trimmed.ptr))) {
886 --trimmed.len;
887 ++trimmed.ptr;
888 }
889 AWS_POSTCONDITION(aws_byte_cursor_is_valid(source));
890 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&trimmed));
891 return trimmed;
892 }
893
894 struct aws_byte_cursor aws_byte_cursor_trim_pred(
895 const struct aws_byte_cursor *source,
896 aws_byte_predicate_fn *predicate) {
897 AWS_PRECONDITION(aws_byte_cursor_is_valid(source));
898 AWS_PRECONDITION(predicate != NULL);
899 struct aws_byte_cursor left_trimmed = aws_byte_cursor_left_trim_pred(source, predicate);
900 struct aws_byte_cursor dest = aws_byte_cursor_right_trim_pred(&left_trimmed, predicate);
901 AWS_POSTCONDITION(aws_byte_cursor_is_valid(source));
902 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&dest));
903 return dest;
904 }
905
906 bool aws_byte_cursor_satisfies_pred(const struct aws_byte_cursor *source, aws_byte_predicate_fn *predicate) {
907 struct aws_byte_cursor trimmed = aws_byte_cursor_left_trim_pred(source, predicate);
908 bool rval = (trimmed.len == 0);
909 AWS_POSTCONDITION(aws_byte_cursor_is_valid(source));
910 return rval;
911 }
912
913 int aws_byte_cursor_compare_lexical(const struct aws_byte_cursor *lhs, const struct aws_byte_cursor *rhs) {
914 AWS_PRECONDITION(aws_byte_cursor_is_valid(lhs));
915 AWS_PRECONDITION(aws_byte_cursor_is_valid(rhs));
916 /* make sure we don't pass NULL pointers to memcmp */
917 AWS_PRECONDITION(lhs->ptr != NULL);
918 AWS_PRECONDITION(rhs->ptr != NULL);
919 size_t comparison_length = lhs->len;
920 if (comparison_length > rhs->len) {
921 comparison_length = rhs->len;
922 }
923
924 int result = memcmp(lhs->ptr, rhs->ptr, comparison_length);
925
926 AWS_POSTCONDITION(aws_byte_cursor_is_valid(lhs));
927 AWS_POSTCONDITION(aws_byte_cursor_is_valid(rhs));
928 if (result != 0) {
929 return result;
930 }
931
932 if (lhs->len != rhs->len) {
933 return comparison_length == lhs->len ? -1 : 1;
934 }
935
936 return 0;
937 }
938
939 int aws_byte_cursor_compare_lookup(
940 const struct aws_byte_cursor *lhs,
941 const struct aws_byte_cursor *rhs,
942 const uint8_t *lookup_table) {
943 AWS_PRECONDITION(aws_byte_cursor_is_valid(lhs));
944 AWS_PRECONDITION(aws_byte_cursor_is_valid(rhs));
945 AWS_PRECONDITION(AWS_MEM_IS_READABLE(lookup_table, 256));
946 if (lhs->len == 0 && rhs->len == 0) {
947 return 0;
948 } else if (lhs->len == 0) {
949 return -1;
950 } else if (rhs->len == 0) {
951 return 1;
952 }
953 const uint8_t *lhs_curr = lhs->ptr;
954 const uint8_t *lhs_end = lhs_curr + lhs->len;
955
956 const uint8_t *rhs_curr = rhs->ptr;
957 const uint8_t *rhs_end = rhs_curr + rhs->len;
958
959 while (lhs_curr < lhs_end && rhs_curr < rhs_end) {
960 uint8_t lhc = lookup_table[*lhs_curr];
961 uint8_t rhc = lookup_table[*rhs_curr];
962
963 AWS_POSTCONDITION(aws_byte_cursor_is_valid(lhs));
964 AWS_POSTCONDITION(aws_byte_cursor_is_valid(rhs));
965 if (lhc < rhc) {
966 return -1;
967 }
968
969 if (lhc > rhc) {
970 return 1;
971 }
972
973 lhs_curr++;
974 rhs_curr++;
975 }
976
977 AWS_POSTCONDITION(aws_byte_cursor_is_valid(lhs));
978 AWS_POSTCONDITION(aws_byte_cursor_is_valid(rhs));
979 if (lhs_curr < lhs_end) {
980 return 1;
981 }
982
983 if (rhs_curr < rhs_end) {
984 return -1;
985 }
986
987 return 0;
988 }
989
990 /**
991 * For creating a byte buffer from a null-terminated string literal.
992 */
993 struct aws_byte_buf aws_byte_buf_from_c_str(const char *c_str) {
994 struct aws_byte_buf buf;
995 buf.len = (!c_str) ? 0 : strlen(c_str);
996 buf.capacity = buf.len;
997 buf.buffer = (buf.capacity == 0) ? NULL : (uint8_t *)c_str;
998 buf.allocator = NULL;
999 AWS_POSTCONDITION(aws_byte_buf_is_valid(&buf));
1000 return buf;
1001 }
1002
1003 struct aws_byte_buf aws_byte_buf_from_array(const void *bytes, size_t len) {
1004 AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(bytes, len), "Input array [bytes] must be writable up to [len] bytes.");
1005 struct aws_byte_buf buf;
1006 buf.buffer = (len > 0) ? (uint8_t *)bytes : NULL;
1007 buf.len = len;
1008 buf.capacity = len;
1009 buf.allocator = NULL;
1010 AWS_POSTCONDITION(aws_byte_buf_is_valid(&buf));
1011 return buf;
1012 }
1013
1014 struct aws_byte_buf aws_byte_buf_from_empty_array(const void *bytes, size_t capacity) {
1015 AWS_PRECONDITION(
1016 AWS_MEM_IS_WRITABLE(bytes, capacity), "Input array [bytes] must be writable up to [capacity] bytes.");
1017 struct aws_byte_buf buf;
1018 buf.buffer = (capacity > 0) ? (uint8_t *)bytes : NULL;
1019 buf.len = 0;
1020 buf.capacity = capacity;
1021 buf.allocator = NULL;
1022 AWS_POSTCONDITION(aws_byte_buf_is_valid(&buf));
1023 return buf;
1024 }
1025
1026 struct aws_byte_cursor aws_byte_cursor_from_buf(const struct aws_byte_buf *const buf) {
1027 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1028 struct aws_byte_cursor cur;
1029 cur.ptr = buf->buffer;
1030 cur.len = buf->len;
1031 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&cur));
1032 return cur;
1033 }
1034
1035 struct aws_byte_cursor aws_byte_cursor_from_c_str(const char *c_str) {
1036 struct aws_byte_cursor cur;
1037 cur.ptr = (uint8_t *)c_str;
1038 cur.len = (cur.ptr) ? strlen(c_str) : 0;
1039 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&cur));
1040 return cur;
1041 }
1042
1043 struct aws_byte_cursor aws_byte_cursor_from_array(const void *const bytes, const size_t len) {
1044 AWS_PRECONDITION(len == 0 || AWS_MEM_IS_READABLE(bytes, len), "Input array [bytes] must be readable up to [len].");
1045 struct aws_byte_cursor cur;
1046 cur.ptr = (uint8_t *)bytes;
1047 cur.len = len;
1048 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&cur));
1049 return cur;
1050 }
1051
1052 #ifdef CBMC
1053 # pragma CPROVER check push
1054 # pragma CPROVER check disable "unsigned-overflow"
1055 #endif
1056 /**
1057 * If index >= bound, bound > (SIZE_MAX / 2), or index > (SIZE_MAX / 2), returns
1058 * 0. Otherwise, returns UINTPTR_MAX. This function is designed to return the correct
1059 * value even under CPU speculation conditions, and is intended to be used for
1060 * SPECTRE mitigation purposes.
1061 */
1062 size_t aws_nospec_mask(size_t index, size_t bound) {
1063 /*
1064 * SPECTRE mitigation - we compute a mask that will be zero if len < 0
1065 * or len >= buf->len, and all-ones otherwise, and AND it into the index.
1066 * It is critical that we avoid any branches in this logic.
1067 */
1068
1069 /*
1070 * Hide the index value from the optimizer. This helps ensure that all this
1071 * logic doesn't get eliminated.
1072 */
1073 #if defined(__GNUC__) || defined(__clang__)
1074 __asm__ __volatile__("" : "+r"(index));
1075 #endif
1076 #if defined(_MSVC_LANG)
1077 /*
1078 * MSVC doesn't have a good way for us to blind the optimizer, and doesn't
1079 * even have inline asm on x64. Some experimentation indicates that this
1080 * hack seems to confuse it sufficiently for our needs.
1081 */
1082 *((volatile uint8_t *)&index) += 0;
1083 #endif
1084
1085 /*
1086 * If len > (SIZE_MAX / 2), then we can end up with len - buf->len being
1087 * positive simply because the sign bit got inverted away. So we also check
1088 * that the sign bit isn't set from the start.
1089 *
1090 * We also check that bound <= (SIZE_MAX / 2) to catch cases where the
1091 * buffer is _already_ out of bounds.
1092 */
1093 size_t negative_mask = index | bound;
1094 size_t toobig_mask = bound - index - (uintptr_t)1;
1095 size_t combined_mask = negative_mask | toobig_mask;
1096
1097 /*
1098 * combined_mask needs to have its sign bit OFF for us to be in range.
1099 * We'd like to expand this to a mask we can AND into our index, so flip
1100 * that bit (and everything else), shift it over so it's the only bit in the
1101 * ones position, and multiply across the entire register.
1102 *
1103 * First, extract the (inverse) top bit and move it to the lowest bit.
1104 * Because there's no standard SIZE_BIT in C99, we'll divide by a mask with
1105 * just the top bit set instead.
1106 */
1107
1108 combined_mask = (~combined_mask) / (SIZE_MAX - (SIZE_MAX >> 1));
1109
1110 /*
1111 * Now multiply it to replicate it across all bits.
1112 *
1113 * Note that GCC is smart enough to optimize the divide-and-multiply into
1114 * an arithmetic right shift operation on x86.
1115 */
1116 combined_mask = combined_mask * UINTPTR_MAX;
1117
1118 return combined_mask;
1119 }
1120 #ifdef CBMC
1121 # pragma CPROVER check pop
1122 #endif
1123
1124 /**
1125 * Tests if the given aws_byte_cursor has at least len bytes remaining. If so,
1126 * *buf is advanced by len bytes (incrementing ->ptr and decrementing ->len),
1127 * and an aws_byte_cursor referring to the first len bytes of the original *buf
1128 * is returned. Otherwise, an aws_byte_cursor with ->ptr = NULL, ->len = 0 is
1129 * returned.
1130 *
1131 * Note that if len is above (SIZE_MAX / 2), this function will also treat it as
1132 * a buffer overflow, and return NULL without changing *buf.
1133 */
1134 struct aws_byte_cursor aws_byte_cursor_advance(struct aws_byte_cursor *const cursor, const size_t len) {
1135 AWS_PRECONDITION(aws_byte_cursor_is_valid(cursor));
1136 struct aws_byte_cursor rv;
1137 if (cursor->len > (SIZE_MAX >> 1) || len > (SIZE_MAX >> 1) || len > cursor->len) {
1138 rv.ptr = NULL;
1139 rv.len = 0;
1140 } else {
1141 rv.ptr = cursor->ptr;
1142 rv.len = len;
1143 cursor->ptr = (cursor->ptr == NULL) ? NULL : cursor->ptr + len;
1144 cursor->len -= len;
1145 }
1146 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cursor));
1147 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&rv));
1148 return rv;
1149 }
1150
1151 /**
1152 * Behaves identically to aws_byte_cursor_advance, but avoids speculative
1153 * execution potentially reading out-of-bounds pointers (by returning an
1154 * empty ptr in such speculated paths).
1155 *
1156 * This should generally be done when using an untrusted or
1157 * data-dependent value for 'len', to avoid speculating into a path where
1158 * cursor->ptr points outside the true ptr length.
1159 */
1160
1161 struct aws_byte_cursor aws_byte_cursor_advance_nospec(struct aws_byte_cursor *const cursor, size_t len) {
1162 AWS_PRECONDITION(aws_byte_cursor_is_valid(cursor));
1163
1164 struct aws_byte_cursor rv;
1165
1166 if (len <= cursor->len && len <= (SIZE_MAX >> 1) && cursor->len <= (SIZE_MAX >> 1)) {
1167 /*
1168 * If we're speculating past a failed bounds check, null out the pointer. This ensures
1169 * that we don't try to read past the end of the buffer and leak information about other
1170 * memory through timing side-channels.
1171 */
1172 uintptr_t mask = aws_nospec_mask(len, cursor->len + 1);
1173
1174 /* Make sure we don't speculate-underflow len either */
1175 len = len & mask;
1176 cursor->ptr = (uint8_t *)((uintptr_t)cursor->ptr & mask);
1177 /* Make sure subsequent nospec accesses don't advance ptr past NULL */
1178 cursor->len = cursor->len & mask;
1179
1180 rv.ptr = cursor->ptr;
1181 /* Make sure anything acting upon the returned cursor _also_ doesn't advance past NULL */
1182 rv.len = len & mask;
1183
1184 cursor->ptr = (cursor->ptr == NULL) ? NULL : cursor->ptr + len;
1185 cursor->len -= len;
1186 } else {
1187 rv.ptr = NULL;
1188 rv.len = 0;
1189 }
1190
1191 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cursor));
1192 AWS_POSTCONDITION(aws_byte_cursor_is_valid(&rv));
1193 return rv;
1194 }
1195
1196 /**
1197 * Reads specified length of data from byte cursor and copies it to the
1198 * destination array.
1199 *
1200 * On success, returns true and updates the cursor pointer/length accordingly.
1201 * If there is insufficient space in the cursor, returns false, leaving the
1202 * cursor unchanged.
1203 */
1204 bool aws_byte_cursor_read(struct aws_byte_cursor *AWS_RESTRICT cur, void *AWS_RESTRICT dest, const size_t len) {
1205 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1206 AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(dest, len));
1207 if (len == 0) {
1208 return true;
1209 }
1210
1211 struct aws_byte_cursor slice = aws_byte_cursor_advance_nospec(cur, len);
1212
1213 if (slice.ptr) {
1214 memcpy(dest, slice.ptr, len);
1215 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1216 AWS_POSTCONDITION(AWS_MEM_IS_READABLE(dest, len));
1217 return true;
1218 }
1219 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1220 return false;
1221 }
1222
1223 /**
1224 * Reads as many bytes from cursor as size of buffer, and copies them to buffer.
1225 *
1226 * On success, returns true and updates the cursor pointer/length accordingly.
1227 * If there is insufficient space in the cursor, returns false, leaving the
1228 * cursor unchanged.
1229 */
1230 bool aws_byte_cursor_read_and_fill_buffer(
1231 struct aws_byte_cursor *AWS_RESTRICT cur,
1232 struct aws_byte_buf *AWS_RESTRICT dest) {
1233 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1234 AWS_PRECONDITION(aws_byte_buf_is_valid(dest));
1235 if (aws_byte_cursor_read(cur, dest->buffer, dest->capacity)) {
1236 dest->len = dest->capacity;
1237 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1238 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
1239 return true;
1240 }
1241 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1242 AWS_POSTCONDITION(aws_byte_buf_is_valid(dest));
1243 return false;
1244 }
1245
1246 /**
1247 * Reads a single byte from cursor, placing it in *var.
1248 *
1249 * On success, returns true and updates the cursor pointer/length accordingly.
1250 * If there is insufficient space in the cursor, returns false, leaving the
1251 * cursor unchanged.
1252 */
1253 bool aws_byte_cursor_read_u8(struct aws_byte_cursor *AWS_RESTRICT cur, uint8_t *AWS_RESTRICT var) {
1254 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1255 AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(var, 1));
1256 bool rv = aws_byte_cursor_read(cur, var, 1);
1257 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1258 return rv;
1259 }
1260
1261 /**
1262 * Reads a 16-bit value in network byte order from cur, and places it in host
1263 * byte order into var.
1264 *
1265 * On success, returns true and updates the cursor pointer/length accordingly.
1266 * If there is insufficient space in the cursor, returns false, leaving the
1267 * cursor unchanged.
1268 */
1269 bool aws_byte_cursor_read_be16(struct aws_byte_cursor *cur, uint16_t *var) {
1270 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1271 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1272 bool rv = aws_byte_cursor_read(cur, var, 2);
1273
1274 if (AWS_LIKELY(rv)) {
1275 *var = aws_ntoh16(*var);
1276 }
1277
1278 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1279 return rv;
1280 }
1281
1282 /**
1283 * Reads a 16-bit value in little endian byte order from cur, and places it in host
1284 * byte order into var.
1285 *
1286 * On success, returns true and updates the cursor pointer/length accordingly.
1287 * If there is insufficient space in the cursor, returns false, leaving the
1288 * cursor unchanged.
1289 */
1290 bool aws_byte_cursor_read_le16(struct aws_byte_cursor *cur, uint16_t *var) {
1291 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1292 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1293 bool rv = aws_byte_cursor_read(cur, var, 2);
1294
1295 if (AWS_LIKELY(rv)) {
1296 *var = aws_letoh16(*var);
1297 }
1298
1299 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1300 return rv;
1301 }
1302
1303 /**
1304 * Reads an unsigned 24-bit value (3 bytes) in network byte order from cur,
1305 * and places it in host byte order into 32-bit var.
1306 * Ex: if cur's next 3 bytes are {0xAA, 0xBB, 0xCC}, then var becomes 0x00AABBCC.
1307 *
1308 * On success, returns true and updates the cursor pointer/length accordingly.
1309 * If there is insufficient space in the cursor, returns false, leaving the
1310 * cursor unchanged.
1311 */
1312 bool aws_byte_cursor_read_be24(struct aws_byte_cursor *cur, uint32_t *var) {
1313 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1314 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1315
1316 uint8_t *var_bytes = (void *)var;
1317
1318 /* read into "lower" 3 bytes */
1319 bool rv = aws_byte_cursor_read(cur, &var_bytes[1], 3);
1320
1321 if (AWS_LIKELY(rv)) {
1322 /* zero out "highest" 4th byte*/
1323 var_bytes[0] = 0;
1324
1325 *var = aws_ntoh32(*var);
1326 }
1327
1328 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1329 return rv;
1330 }
1331
1332 /**
1333 * Reads a 32-bit value in network byte order from cur, and places it in host
1334 * byte order into var.
1335 *
1336 * On success, returns true and updates the cursor pointer/length accordingly.
1337 * If there is insufficient space in the cursor, returns false, leaving the
1338 * cursor unchanged.
1339 */
1340 bool aws_byte_cursor_read_be32(struct aws_byte_cursor *cur, uint32_t *var) {
1341 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1342 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1343 bool rv = aws_byte_cursor_read(cur, var, 4);
1344
1345 if (AWS_LIKELY(rv)) {
1346 *var = aws_ntoh32(*var);
1347 }
1348
1349 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1350 return rv;
1351 }
1352
1353 /**
1354 * Reads a 32-bit value in little endian byte order from cur, and places it in host
1355 * byte order into var.
1356 *
1357 * On success, returns true and updates the cursor pointer/length accordingly.
1358 * If there is insufficient space in the cursor, returns false, leaving the
1359 * cursor unchanged.
1360 */
1361 bool aws_byte_cursor_read_le32(struct aws_byte_cursor *cur, uint32_t *var) {
1362 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1363 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1364 bool rv = aws_byte_cursor_read(cur, var, 4);
1365
1366 if (AWS_LIKELY(rv)) {
1367 *var = aws_letoh32(*var);
1368 }
1369
1370 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1371 return rv;
1372 }
1373
1374 bool aws_byte_cursor_read_be_i32(struct aws_byte_cursor *cur, int32_t *var) {
1375 uint32_t uval;
1376 bool rv = aws_byte_cursor_read_be32(cur, &uval);
1377 if (AWS_LIKELY(rv)) {
1378 memcpy(var, &uval, sizeof(uval));
1379 }
1380 return rv;
1381 }
1382
1383 bool aws_byte_cursor_read_le_i32(struct aws_byte_cursor *cur, int32_t *var) {
1384 uint32_t uval;
1385 bool rv = aws_byte_cursor_read_le32(cur, &uval);
1386 if (AWS_LIKELY(rv)) {
1387 memcpy(var, &uval, sizeof(uval));
1388 }
1389 return rv;
1390 }
1391
1392 /**
1393 * Reads a 32-bit value in network byte order from cur, and places it in host
1394 * byte order into var.
1395 *
1396 * On success, returns true and updates the cursor pointer/length accordingly.
1397 * If there is insufficient space in the cursor, returns false, leaving the
1398 * cursor unchanged.
1399 */
1400 bool aws_byte_cursor_read_float_be32(struct aws_byte_cursor *cur, float *var) {
1401 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1402 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1403 bool rv = aws_byte_cursor_read(cur, var, sizeof(float));
1404
1405 if (AWS_LIKELY(rv)) {
1406 *var = aws_ntohf32(*var);
1407 }
1408
1409 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1410 return rv;
1411 }
1412
1413 /**
1414 * Reads a 64-bit value in network byte order from cur, and places it in host
1415 * byte order into var.
1416 *
1417 * On success, returns true and updates the cursor pointer/length accordingly.
1418 * If there is insufficient space in the cursor, returns false, leaving the
1419 * cursor unchanged.
1420 */
1421 bool aws_byte_cursor_read_float_be64(struct aws_byte_cursor *cur, double *var) {
1422 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1423 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1424 bool rv = aws_byte_cursor_read(cur, var, sizeof(double));
1425
1426 if (AWS_LIKELY(rv)) {
1427 *var = aws_ntohf64(*var);
1428 }
1429
1430 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1431 return rv;
1432 }
1433
1434 /**
1435 * Reads a 64-bit value in network byte order from cur, and places it in host
1436 * byte order into var.
1437 *
1438 * On success, returns true and updates the cursor pointer/length accordingly.
1439 * If there is insufficient space in the cursor, returns false, leaving the
1440 * cursor unchanged.
1441 */
1442 bool aws_byte_cursor_read_be64(struct aws_byte_cursor *cur, uint64_t *var) {
1443 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1444 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1445 bool rv = aws_byte_cursor_read(cur, var, sizeof(*var));
1446
1447 if (AWS_LIKELY(rv)) {
1448 *var = aws_ntoh64(*var);
1449 }
1450
1451 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1452 return rv;
1453 }
1454
1455 /* Lookup from '0' -> 0, 'f' -> 0xf, 'F' -> 0xF, etc
1456 * invalid characters have value 255 */
1457 /* clang-format off */
1458 static const uint8_t s_hex_to_num_table[] = {
1459 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1460 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1461 255, 255,
1462 /* 0 - 9 */
1463 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1464 255, 255, 255, 255, 255, 255, 255,
1465 /* A - F */
1466 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
1467 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1468 255, 255, 255,
1469 /* a - f */
1470 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
1471 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1472 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1473 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1474 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1475 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1476 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1477 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
1478 };
1479 AWS_STATIC_ASSERT(AWS_ARRAY_SIZE(s_hex_to_num_table) == 256);
1480 /* clang-format on */
1481
1482 const uint8_t *aws_lookup_table_hex_to_num_get(void) {
1483 return s_hex_to_num_table;
1484 }
1485
1486 bool aws_byte_cursor_read_hex_u8(struct aws_byte_cursor *cur, uint8_t *var) {
1487 AWS_PRECONDITION(aws_byte_cursor_is_valid(cur));
1488 AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var));
1489
1490 bool success = false;
1491 if (AWS_LIKELY(cur->len >= 2)) {
1492 const uint8_t hi = s_hex_to_num_table[cur->ptr[0]];
1493 const uint8_t lo = s_hex_to_num_table[cur->ptr[1]];
1494
1495 /* table maps invalid characters to 255 */
1496 if (AWS_LIKELY(hi != 255 && lo != 255)) {
1497 *var = (hi << 4) | lo;
1498 cur->ptr += 2;
1499 cur->len -= 2;
1500 success = true;
1501 }
1502 }
1503
1504 AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur));
1505 return success;
1506 }
1507
1508 /**
1509 * Appends a sub-buffer to the specified buffer.
1510 *
1511 * If the buffer has at least `len' bytes remaining (buffer->capacity - buffer->len >= len),
1512 * then buffer->len is incremented by len, and an aws_byte_buf is assigned to *output corresponding
1513 * to the last len bytes of the input buffer. The aws_byte_buf at *output will have a null
1514 * allocator, a zero initial length, and a capacity of 'len'. The function then returns true.
1515 *
1516 * If there is insufficient space, then this function nulls all fields in *output and returns
1517 * false.
1518 */
1519 bool aws_byte_buf_advance(
1520 struct aws_byte_buf *const AWS_RESTRICT buffer,
1521 struct aws_byte_buf *const AWS_RESTRICT output,
1522 const size_t len) {
1523 AWS_PRECONDITION(aws_byte_buf_is_valid(buffer));
1524 AWS_PRECONDITION(aws_byte_buf_is_valid(output));
1525 if (buffer->capacity - buffer->len >= len) {
1526 *output = aws_byte_buf_from_array((buffer->buffer == NULL) ? NULL : buffer->buffer + buffer->len, len);
1527 buffer->len += len;
1528 output->len = 0;
1529 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
1530 AWS_POSTCONDITION(aws_byte_buf_is_valid(output));
1531 return true;
1532 } else {
1533 AWS_ZERO_STRUCT(*output);
1534 AWS_POSTCONDITION(aws_byte_buf_is_valid(buffer));
1535 AWS_POSTCONDITION(aws_byte_buf_is_valid(output));
1536 return false;
1537 }
1538 }
1539
1540 /**
1541 * Write specified number of bytes from array to byte buffer.
1542 *
1543 * On success, returns true and updates the buffer length accordingly.
1544 * If there is insufficient space in the buffer, returns false, leaving the
1545 * buffer unchanged.
1546 */
1547 bool aws_byte_buf_write(struct aws_byte_buf *AWS_RESTRICT buf, const uint8_t *AWS_RESTRICT src, size_t len) {
1548 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1549 AWS_PRECONDITION(AWS_MEM_IS_READABLE(src, len), "Input array [src] must be readable up to [len] bytes.");
1550
1551 if (len == 0) {
1552 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
1553 return true;
1554 }
1555
1556 if (buf->len > (SIZE_MAX >> 1) || len > (SIZE_MAX >> 1) || buf->len + len > buf->capacity) {
1557 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
1558 return false;
1559 }
1560
1561 memcpy(buf->buffer + buf->len, src, len);
1562 buf->len += len;
1563
1564 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
1565 return true;
1566 }
1567
1568 /**
1569 * Copies all bytes from buffer to buffer.
1570 *
1571 * On success, returns true and updates the buffer /length accordingly.
1572 * If there is insufficient space in the buffer, returns false, leaving the
1573 * buffer unchanged.
1574 */
1575 bool aws_byte_buf_write_from_whole_buffer(struct aws_byte_buf *AWS_RESTRICT buf, struct aws_byte_buf src) {
1576 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1577 AWS_PRECONDITION(aws_byte_buf_is_valid(&src));
1578 return aws_byte_buf_write(buf, src.buffer, src.len);
1579 }
1580
1581 /**
1582 * Copies all bytes from buffer to buffer.
1583 *
1584 * On success, returns true and updates the buffer /length accordingly.
1585 * If there is insufficient space in the buffer, returns false, leaving the
1586 * buffer unchanged.
1587 */
1588 bool aws_byte_buf_write_from_whole_cursor(struct aws_byte_buf *AWS_RESTRICT buf, struct aws_byte_cursor src) {
1589 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1590 AWS_PRECONDITION(aws_byte_cursor_is_valid(&src));
1591 return aws_byte_buf_write(buf, src.ptr, src.len);
1592 }
1593
1594 struct aws_byte_cursor aws_byte_buf_write_to_capacity(
1595 struct aws_byte_buf *buf,
1596 struct aws_byte_cursor *advancing_cursor) {
1597
1598 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1599 AWS_PRECONDITION(aws_byte_cursor_is_valid(advancing_cursor));
1600
1601 size_t available = buf->capacity - buf->len;
1602 size_t write_size = aws_min_size(available, advancing_cursor->len);
1603 struct aws_byte_cursor write_cursor = aws_byte_cursor_advance(advancing_cursor, write_size);
1604 aws_byte_buf_write_from_whole_cursor(buf, write_cursor);
1605 return write_cursor;
1606 }
1607
1608 /**
1609 * Copies one byte to buffer.
1610 *
1611 * On success, returns true and updates the cursor /length
1612 accordingly.
1613
1614 * If there is insufficient space in the cursor, returns false, leaving the
1615 cursor unchanged.
1616 */
1617 bool aws_byte_buf_write_u8(struct aws_byte_buf *AWS_RESTRICT buf, uint8_t c) {
1618 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1619 return aws_byte_buf_write(buf, &c, 1);
1620 }
1621
1622 /**
1623 * Writes one byte repeatedly to buffer (like memset)
1624 *
1625 * If there is insufficient space in the buffer, returns false, leaving the
1626 * buffer unchanged.
1627 */
1628 bool aws_byte_buf_write_u8_n(struct aws_byte_buf *buf, uint8_t c, size_t count) {
1629 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1630
1631 if (buf->len > (SIZE_MAX >> 1) || count > (SIZE_MAX >> 1) || buf->len + count > buf->capacity) {
1632 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
1633 return false;
1634 }
1635
1636 memset(buf->buffer + buf->len, c, count);
1637 buf->len += count;
1638
1639 AWS_POSTCONDITION(aws_byte_buf_is_valid(buf));
1640 return true;
1641 }
1642
1643 /**
1644 * Writes a 16-bit integer in network byte order (big endian) to buffer.
1645 *
1646 * On success, returns true and updates the cursor /length accordingly.
1647 * If there is insufficient space in the cursor, returns false, leaving the
1648 * cursor unchanged.
1649 */
1650 bool aws_byte_buf_write_be16(struct aws_byte_buf *buf, uint16_t x) {
1651 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1652 x = aws_hton16(x);
1653 return aws_byte_buf_write(buf, (uint8_t *)&x, 2);
1654 }
1655
1656 /**
1657 * Writes low 24-bits (3 bytes) of an unsigned integer in network byte order (big endian) to buffer.
1658 * Ex: If x is 0x00AABBCC then {0xAA, 0xBB, 0xCC} is written to buffer.
1659 *
1660 * On success, returns true and updates the buffer /length accordingly.
1661 * If there is insufficient space in the buffer, or x's value cannot fit in 3 bytes,
1662 * returns false, leaving the buffer unchanged.
1663 */
1664 bool aws_byte_buf_write_be24(struct aws_byte_buf *buf, uint32_t x) {
1665 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1666
1667 if (x > 0x00FFFFFF) {
1668 return false;
1669 }
1670
1671 uint32_t be32 = aws_hton32(x);
1672 uint8_t *be32_bytes = (uint8_t *)&be32;
1673
1674 /* write "lower" 3 bytes */
1675 return aws_byte_buf_write(buf, &be32_bytes[1], 3);
1676 }
1677
1678 /**
1679 * Writes a 32-bit integer in network byte order (big endian) to buffer.
1680 *
1681 * On success, returns true and updates the cursor /length accordingly.
1682 * If there is insufficient space in the cursor, returns false, leaving the
1683 * cursor unchanged.
1684 */
1685 bool aws_byte_buf_write_be32(struct aws_byte_buf *buf, uint32_t x) {
1686 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1687 x = aws_hton32(x);
1688 return aws_byte_buf_write(buf, (uint8_t *)&x, 4);
1689 }
1690
1691 /**
1692 * Writes a 32-bit float in network byte order (big endian) to buffer.
1693 *
1694 * On success, returns true and updates the cursor /length accordingly.
1695 * If there is insufficient space in the cursor, returns false, leaving the
1696 * cursor unchanged.
1697 */
1698 bool aws_byte_buf_write_float_be32(struct aws_byte_buf *buf, float x) {
1699 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1700 x = aws_htonf32(x);
1701 return aws_byte_buf_write(buf, (uint8_t *)&x, 4);
1702 }
1703
1704 /**
1705 * Writes a 64-bit integer in network byte order (big endian) to buffer.
1706 *
1707 * On success, returns true and updates the cursor /length accordingly.
1708 * If there is insufficient space in the cursor, returns false, leaving the
1709 * cursor unchanged.
1710 */
1711 bool aws_byte_buf_write_be64(struct aws_byte_buf *buf, uint64_t x) {
1712 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1713 x = aws_hton64(x);
1714 return aws_byte_buf_write(buf, (uint8_t *)&x, 8);
1715 }
1716
1717 /**
1718 * Writes a 64-bit float in network byte order (big endian) to buffer.
1719 *
1720 * On success, returns true and updates the cursor /length accordingly.
1721 * If there is insufficient space in the cursor, returns false, leaving the
1722 * cursor unchanged.
1723 */
1724 bool aws_byte_buf_write_float_be64(struct aws_byte_buf *buf, double x) {
1725 AWS_PRECONDITION(aws_byte_buf_is_valid(buf));
1726 x = aws_htonf64(x);
1727 return aws_byte_buf_write(buf, (uint8_t *)&x, 8);
1728 }
1729
1730 int aws_byte_buf_append_and_update(struct aws_byte_buf *to, struct aws_byte_cursor *from_and_update) {
1731 AWS_PRECONDITION(aws_byte_buf_is_valid(to));
1732 AWS_PRECONDITION(aws_byte_cursor_is_valid(from_and_update));
1733
1734 if (aws_byte_buf_append(to, from_and_update)) {
1735 return AWS_OP_ERR;
1736 }
1737
1738 from_and_update->ptr = to->buffer == NULL ? NULL : to->buffer + (to->len - from_and_update->len);
1739 return AWS_OP_SUCCESS;
1740 }
1741
1742 static struct aws_byte_cursor s_null_terminator_cursor = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("\0");
1743 int aws_byte_buf_append_null_terminator(struct aws_byte_buf *buf) {
1744 return aws_byte_buf_append_dynamic(buf, &s_null_terminator_cursor);
1745 }
1746
1747 bool aws_isalnum(uint8_t ch) {
1748 return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9');
1749 }
1750
1751 bool aws_isalpha(uint8_t ch) {
1752 return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
1753 }
1754
1755 bool aws_isdigit(uint8_t ch) {
1756 return (ch >= '0' && ch <= '9');
1757 }
1758
1759 bool aws_isxdigit(uint8_t ch) {
1760 return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
1761 }
1762
1763 bool aws_isspace(uint8_t ch) {
1764 switch (ch) {
1765 case 0x20: /* ' ' - space */
1766 case 0x09: /* '\t' - horizontal tab */
1767 case 0x0A: /* '\n' - line feed */
1768 case 0x0B: /* '\v' - vertical tab */
1769 case 0x0C: /* '\f' - form feed */
1770 case 0x0D: /* '\r' - carriage return */
1771 return true;
1772 default:
1773 return false;
1774 }
1775 }
1776
1777 static int s_read_unsigned(struct aws_byte_cursor cursor, uint64_t *dst, uint8_t base) {
1778 uint64_t val = 0;
1779 *dst = 0;
1780
1781 if (cursor.len == 0) {
1782 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1783 }
1784
1785 const uint8_t *hex_to_num_table = aws_lookup_table_hex_to_num_get();
1786
1787 /* read from left to right */
1788 for (size_t i = 0; i < cursor.len; ++i) {
1789 const uint8_t c = cursor.ptr[i];
1790 const uint8_t cval = hex_to_num_table[c];
1791 if (cval >= base) {
1792 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1793 }
1794
1795 if (aws_mul_u64_checked(val, base, &val)) {
1796 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
1797 }
1798
1799 if (aws_add_u64_checked(val, cval, &val)) {
1800 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
1801 }
1802 }
1803
1804 *dst = val;
1805 return AWS_OP_SUCCESS;
1806 }
1807
1808 int aws_byte_cursor_utf8_parse_u64(struct aws_byte_cursor cursor, uint64_t *dst) {
1809 return s_read_unsigned(cursor, dst, 10 /*base*/);
1810 }
1811
1812 int aws_byte_cursor_utf8_parse_i64(struct aws_byte_cursor cursor, int64_t *dst) {
1813 bool is_neg = cursor.len > 0 && cursor.ptr[0] == '-';
1814 if (is_neg) {
1815 aws_byte_cursor_advance(&cursor, 1);
1816 }
1817
1818 uint64_t u64 = 0;
1819 if (aws_byte_cursor_utf8_parse_u64(cursor, &u64)) {
1820 return AWS_OP_ERR;
1821 }
1822
1823 /* Note: corner cases for negative value is one higher then positive */
1824 uint64_t max_allowed = is_neg ? (uint64_t)INT64_MAX + 1 : (uint64_t)INT64_MAX;
1825 if (u64 > max_allowed) {
1826 return aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
1827 }
1828
1829 *dst = is_neg ? -(int64_t)u64 : (int64_t)u64;
1830 return AWS_OP_SUCCESS;
1831 }
1832
1833 int aws_byte_cursor_utf8_parse_u64_hex(struct aws_byte_cursor cursor, uint64_t *dst) {
1834 return s_read_unsigned(cursor, dst, 16 /*base*/);
1835 }