Debian Codegraph @

crt/aws-c-s3/source/s3_util.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/s3/private/s3_util.h"
7 #include "aws/s3/private/s3_client_impl.h"
8 #include "aws/s3/private/s3_meta_request_impl.h"
9 #include "aws/s3/private/s3_platform_info.h"
10 #include "aws/s3/private/s3_request.h"
11 #include <aws/auth/credentials.h>
12 #include <aws/common/clock.h>
13 #include <aws/common/encoding.h>
14 #include <aws/common/string.h>
15 #include <aws/common/xml_parser.h>
16 #include <aws/http/request_response.h>
17 #include <aws/s3/s3_client.h>
18 #include <inttypes.h>
19
20 #ifdef _MSC_VER
21 /* sscanf warning (not currently scanning for strings) */
22 # pragma warning(disable : 4996)
23 #endif
24
25 const struct aws_byte_cursor g_s3_client_version = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL(AWS_S3_CLIENT_VERSION);
26 const struct aws_byte_cursor g_s3_service_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("s3");
27 const struct aws_byte_cursor g_s3express_service_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("s3express");
28 const struct aws_byte_cursor g_host_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Host");
29 const struct aws_byte_cursor g_range_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Range");
30 const struct aws_byte_cursor g_if_match_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("If-Match");
31 const struct aws_byte_cursor g_request_id_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-request-id");
32 const struct aws_byte_cursor g_amz_id_2_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-id-2");
33 const struct aws_byte_cursor g_etag_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("ETag");
34 const struct aws_byte_cursor g_content_range_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Content-Range");
35 const struct aws_byte_cursor g_content_type_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Content-Type");
36 const struct aws_byte_cursor g_content_encoding_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Content-Encoding");
37 const struct aws_byte_cursor g_content_encoding_header_aws_chunked =
38 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("aws-chunked");
39 const struct aws_byte_cursor g_content_length_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Content-Length");
40 const struct aws_byte_cursor g_decoded_content_length_header_name =
41 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-decoded-content-length");
42 const struct aws_byte_cursor g_content_md5_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Content-MD5");
43 const struct aws_byte_cursor g_trailer_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-trailer");
44 const struct aws_byte_cursor g_request_validation_mode = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-checksum-mode");
45 const struct aws_byte_cursor g_enabled = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("enabled");
46
47 const struct aws_byte_cursor g_checksum_algorithm_header_name =
48 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-checksum-algorithm");
49 const struct aws_byte_cursor g_sdk_checksum_algorithm_header_name =
50 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-sdk-checksum-algorithm");
51 const struct aws_byte_cursor g_accept_ranges_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("accept-ranges");
52 const struct aws_byte_cursor g_acl_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-acl");
53 const struct aws_byte_cursor g_mp_parts_count_header_name =
54 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-mp-parts-count");
55 const struct aws_byte_cursor g_post_method = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("POST");
56 const struct aws_byte_cursor g_head_method = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("HEAD");
57 const struct aws_byte_cursor g_delete_method = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("DELETE");
58
59 const struct aws_byte_cursor g_user_agent_header_name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("User-Agent");
60 const struct aws_byte_cursor g_user_agent_header_product_name =
61 AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("CRTS3NativeClient");
62 const struct aws_byte_cursor g_user_agent_header_platform = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("platform");
63 const struct aws_byte_cursor g_user_agent_header_unknown = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("unknown");
64
65 const uint32_t g_s3_max_num_upload_parts = 10000;
66 const size_t g_s3_min_upload_part_size = MB_TO_BYTES(5);
67
68 const double g_default_throughput_target_gbps = 10.0;
69
70 /**
71 * Streaming buffer size selection based on experimental results on EBS:
72 *
73 * - Too small buffer sizes (e.g., 16KiB) impact disk read performance,
74 * achieving only 6.73 Gbps throughput from EBS.
75 * - Too large buffer sizes cause network connections to starve more easily
76 * when disk reads cannot provide data fast enough.
77 * - 1MiB buffer size provides optimal balance: sufficient disk read throughput
78 * while maintaining reasonable retry rates due to connection starvation.
79 */
80 const size_t g_streaming_buffer_size = MB_TO_BYTES(1);
81
82 /**
83 * The streaming approach reduces memory consumption without introducing unexpected errors
84 * or performance degradation.
85 *
86 * We start streaming for objects larger than 1TiB, with plans to lower this threshold in future iterations.
87 *
88 * The 1TiB threshold was chosen to minimize the blast radius of this behavioral change
89 * while still providing meaningful memory usage improvements for large objects.
90 */
91 const uint64_t g_streaming_object_size_threshold = TB_TO_BYTES(1);
92
93 /**
94 * TODO: update this default part size 17/16 MiB based on S3 best practice.
95 * Default part size is 8 MiB to reach the best performance from the experiments we had.
96 * Default max part size is 5GiB as the current server limit.
97 **/
98 const uint64_t g_default_part_size_fallback = MB_TO_BYTES(8);
99 #define G_DEFAULT_MAX_PART_SIZE 5368709120ULL
100 const uint64_t g_default_max_part_size = G_DEFAULT_MAX_PART_SIZE;
101
102 /* TODO: Use a reasonable alignment with the update of the buffer pool */
103 const uint64_t g_s3_optimal_range_size_alignment = 1;
104 /**
105 * The most parts in memory will be:
106 * - All downloaded parts to deliver them in the right order (download)
107 * - All parts read into memory for preparing for the HTTP level (upload)
108 * - All transferring parts in HTTP
109 * So, it gives us at most 3 × (the max range size) × (concurrency) in memory.
110 */
111 static const uint32_t s_optimal_range_size_memory_divisor = 3;
112
113 /**
114 * TODO: THIS IS A TEMP WORKAROUND, not the long term solution.
115 * As in Nov 2025, S3Express recommended to have no more than 75 connections to one single part.
116 *
117 * However, client don't know the part boundaries unless with an extra call. Thus, these are the workarounds to avoid
118 * the issue.
119 * 1. If the Part Size we set is larger than the possible size to hit the limitation, we are safe to make as many
120 * connections as we want.
121 * 2. If the object size is less than the threshold, we keep our previous behavior, as it's less likely to hit the
122 * server side limitation.
123 */
124 #define G_S3EXPRESS_CONNECTION_LIMITATION 75
125 const uint32_t g_s3express_connection_limitation = G_S3EXPRESS_CONNECTION_LIMITATION;
126 const uint64_t g_s3express_connection_limitation_part_size_threshold =
127 G_DEFAULT_MAX_PART_SIZE / G_S3EXPRESS_CONNECTION_LIMITATION;
128 #undef G_S3EXPRESS_CONNECTION_LIMITATION
129 #undef G_DEFAULT_MAX_PART_SIZE
130 const uint64_t g_s3express_connection_limitation_object_size_threshold = TB_TO_BYTES(4);
131
132 void copy_http_headers(const struct aws_http_headers *src, struct aws_http_headers *dest) {
133 AWS_PRECONDITION(src);
134 AWS_PRECONDITION(dest);
135
136 size_t headers_count = aws_http_headers_count(src);
137
138 for (size_t header_index = 0; header_index < headers_count; ++header_index) {
139 struct aws_http_header header;
140
141 aws_http_headers_get_index(src, header_index, &header);
142 aws_http_headers_set(dest, header.name, header.value);
143 }
144 }
145 /* user_data for XML traversal */
146 struct xml_get_body_at_path_traversal {
147 struct aws_allocator *allocator;
148 const char **path_name_array;
149 size_t path_name_count;
150 size_t path_name_i;
151 struct aws_byte_cursor *out_body;
152 bool found_node;
153 };
154
155 static int s_xml_get_body_at_path_on_node(struct aws_xml_node *node, void *user_data) {
156 struct xml_get_body_at_path_traversal *traversal = user_data;
157
158 /* if we already found what we're looking for, just finish parsing */
159 if (traversal->found_node) {
160 return AWS_OP_SUCCESS;
161 }
162
163 /* check if this node is on the path */
164 struct aws_byte_cursor node_name = aws_xml_node_get_name(node);
165 const char *expected_name = traversal->path_name_array[traversal->path_name_i];
166 if (aws_byte_cursor_eq_c_str_ignore_case(&node_name, expected_name)) {
167
168 bool is_final_node_on_path = traversal->path_name_i + 1 == traversal->path_name_count;
169 if (is_final_node_on_path) {
170 /* retrieve the body */
171 if (aws_xml_node_as_body(node, traversal->out_body) != AWS_OP_SUCCESS) {
172 return AWS_OP_ERR;
173 }
174 traversal->found_node = true;
175 return AWS_OP_SUCCESS;
176 } else {
177 /* node is on path, but it's not the final node, so traverse its children */
178 traversal->path_name_i++;
179 if (aws_xml_node_traverse(node, s_xml_get_body_at_path_on_node, traversal) != AWS_OP_SUCCESS) {
180 return AWS_OP_ERR;
181 }
182 traversal->path_name_i--;
183 return AWS_OP_SUCCESS;
184 }
185 } else {
186 /* this node is not on the path, continue parsing siblings */
187 return AWS_OP_SUCCESS;
188 }
189 }
190
191 int aws_xml_get_body_at_path(
192 struct aws_allocator *allocator,
193 struct aws_byte_cursor xml_doc,
194 const char **path_name_array,
195 struct aws_byte_cursor *out_body) {
196
197 struct xml_get_body_at_path_traversal traversal = {
198 .allocator = allocator,
199 .path_name_array = path_name_array,
200 .path_name_count = 0,
201 .out_body = out_body,
202 };
203
204 /* find path_name_count */
205 while (path_name_array[traversal.path_name_count] != NULL) {
206 traversal.path_name_count++;
207 AWS_ASSERT(traversal.path_name_count < 4); /* sanity check, increase cap if necessary */
208 }
209 AWS_ASSERT(traversal.path_name_count > 0);
210
211 /* parse XML */
212 struct aws_xml_parser_options parse_options = {
213 .doc = xml_doc,
214 .on_root_encountered = s_xml_get_body_at_path_on_node,
215 .user_data = &traversal,
216 };
217 if (aws_xml_parse(allocator, &parse_options)) {
218 goto error;
219 }
220
221 if (!traversal.found_node) {
222 aws_raise_error(AWS_ERROR_STRING_MATCH_NOT_FOUND);
223 goto error;
224 }
225
226 return AWS_OP_SUCCESS;
227 error:
228 AWS_ZERO_STRUCT(*out_body);
229 return AWS_OP_ERR;
230 }
231
232 struct aws_cached_signing_config_aws *aws_cached_signing_config_new(
233 struct aws_s3_client *client,
234 const struct aws_signing_config_aws *signing_config) {
235 AWS_PRECONDITION(client);
236 AWS_PRECONDITION(signing_config);
237
238 struct aws_allocator *allocator = client->allocator;
239
240 struct aws_cached_signing_config_aws *cached_signing_config =
241 aws_mem_calloc(allocator, 1, sizeof(struct aws_cached_signing_config_aws));
242
243 cached_signing_config->allocator = allocator;
244
245 cached_signing_config->config.config_type =
246 signing_config->config_type ? signing_config->config_type : AWS_SIGNING_CONFIG_AWS;
247
248 AWS_ASSERT(aws_byte_cursor_is_valid(&signing_config->region));
249 if (signing_config->region.len > 0) {
250 cached_signing_config->region = aws_string_new_from_cursor(allocator, &signing_config->region);
251 } else {
252 /* Fall back to client region. */
253 cached_signing_config->region = aws_string_new_from_string(allocator, client->region);
254 }
255 cached_signing_config->config.region = aws_byte_cursor_from_string(cached_signing_config->region);
256
257 if (signing_config->service.len > 0) {
258 cached_signing_config->service = aws_string_new_from_cursor(allocator, &signing_config->service);
259 cached_signing_config->config.service = aws_byte_cursor_from_string(cached_signing_config->service);
260 } else {
261 cached_signing_config->config.service = g_s3_service_name;
262 }
263
264 cached_signing_config->config.date = signing_config->date;
265
266 AWS_ASSERT(aws_byte_cursor_is_valid(&signing_config->signed_body_value));
267
268 if (signing_config->signed_body_value.len > 0) {
269 cached_signing_config->signed_body_value =
270 aws_string_new_from_cursor(allocator, &signing_config->signed_body_value);
271 cached_signing_config->config.signed_body_value =
272 aws_byte_cursor_from_string(cached_signing_config->signed_body_value);
273 } else {
274 cached_signing_config->config.signed_body_value = g_aws_signed_body_value_unsigned_payload;
275 }
276
277 if (signing_config->credentials != NULL) {
278 aws_credentials_acquire(signing_config->credentials);
279 cached_signing_config->config.credentials = signing_config->credentials;
280 }
281
282 if (signing_config->credentials_provider != NULL) {
283 aws_credentials_provider_acquire(signing_config->credentials_provider);
284 cached_signing_config->config.credentials_provider = signing_config->credentials_provider;
285 }
286
287 /* Configs default to Zero. */
288 cached_signing_config->config.algorithm = signing_config->algorithm;
289 cached_signing_config->config.signature_type = signing_config->signature_type;
290 /* TODO: you don't have a way to override this config as the other option is zero. But, you cannot really use the
291 * other value, as it is always required. */
292 cached_signing_config->config.signed_body_header = AWS_SBHT_X_AMZ_CONTENT_SHA256;
293 cached_signing_config->config.should_sign_header = signing_config->should_sign_header;
294 /* It's the user's responsibility to keep the user data around */
295 cached_signing_config->config.should_sign_header_ud = signing_config->should_sign_header_ud;
296
297 cached_signing_config->config.flags = signing_config->flags;
298 cached_signing_config->config.expiration_in_seconds = signing_config->expiration_in_seconds;
299
300 return cached_signing_config;
301 }
302
303 void aws_cached_signing_config_destroy(struct aws_cached_signing_config_aws *cached_signing_config) {
304 if (cached_signing_config == NULL) {
305 return;
306 }
307
308 aws_credentials_release(cached_signing_config->config.credentials);
309 aws_credentials_provider_release(cached_signing_config->config.credentials_provider);
310
311 aws_string_destroy(cached_signing_config->service);
312 aws_string_destroy(cached_signing_config->region);
313 aws_string_destroy(cached_signing_config->signed_body_value);
314
315 aws_mem_release(cached_signing_config->allocator, cached_signing_config);
316 }
317
318 void aws_s3_init_default_signing_config(
319 struct aws_signing_config_aws *signing_config,
320 const struct aws_byte_cursor region,
321 struct aws_credentials_provider *credentials_provider) {
322 AWS_PRECONDITION(signing_config);
323 AWS_PRECONDITION(credentials_provider);
324
325 AWS_ZERO_STRUCT(*signing_config);
326
327 signing_config->config_type = AWS_SIGNING_CONFIG_AWS;
328 signing_config->algorithm = AWS_SIGNING_ALGORITHM_V4;
329 signing_config->credentials_provider = credentials_provider;
330 signing_config->region = region;
331 signing_config->service = g_s3_service_name;
332 signing_config->signed_body_header = AWS_SBHT_X_AMZ_CONTENT_SHA256;
333 signing_config->signed_body_value = g_aws_signed_body_value_unsigned_payload;
334 }
335
336 struct aws_string *aws_strip_quotes(struct aws_allocator *allocator, struct aws_byte_cursor in_cur) {
337
338 if (in_cur.len >= 2 && in_cur.ptr[0] == '"' && in_cur.ptr[in_cur.len - 1] == '"') {
339 aws_byte_cursor_advance(&in_cur, 1);
340 --in_cur.len;
341 }
342
343 return aws_string_new_from_cursor(allocator, &in_cur);
344 }
345
346 int aws_last_error_or_unknown(void) {
347 int error = aws_last_error();
348 AWS_ASSERT(error != AWS_ERROR_SUCCESS); /* Someone forgot to call aws_raise_error() */
349 if (error == AWS_ERROR_SUCCESS) {
350 return AWS_ERROR_UNKNOWN;
351 }
352
353 return error;
354 }
355
356 void aws_s3_add_user_agent_header(struct aws_allocator *allocator, struct aws_http_message *message) {
357 AWS_PRECONDITION(allocator);
358 AWS_PRECONDITION(message);
359
360 const struct aws_byte_cursor space_delimiter = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL(" ");
361 const struct aws_byte_cursor forward_slash = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("/");
362 struct aws_byte_cursor platform_cursor = aws_s3_get_current_platform_ec2_intance_type(true /* cached_only */);
363 if (!platform_cursor.len) {
364 platform_cursor = g_user_agent_header_unknown;
365 }
366 const size_t user_agent_length = g_user_agent_header_product_name.len + forward_slash.len +
367 g_s3_client_version.len + space_delimiter.len + g_user_agent_header_platform.len +
368 forward_slash.len + platform_cursor.len;
369
370 struct aws_http_headers *headers = aws_http_message_get_headers(message);
371 AWS_ASSERT(headers != NULL);
372
373 struct aws_byte_cursor current_user_agent_header;
374 AWS_ZERO_STRUCT(current_user_agent_header);
375
376 struct aws_byte_buf user_agent_buffer;
377 AWS_ZERO_STRUCT(user_agent_buffer);
378
379 if (aws_http_headers_get(headers, g_user_agent_header_name, &current_user_agent_header) == AWS_OP_SUCCESS) {
380 /* If the header was found, then create a buffer with the total size we'll need, and append the current user
381 * agent header with a trailing space. */
382 aws_byte_buf_init(
383 &user_agent_buffer, allocator, current_user_agent_header.len + space_delimiter.len + user_agent_length);
384
385 aws_byte_buf_append_dynamic(&user_agent_buffer, &current_user_agent_header);
386
387 aws_byte_buf_append_dynamic(&user_agent_buffer, &space_delimiter);
388
389 } else {
390 AWS_ASSERT(aws_last_error() == AWS_ERROR_HTTP_HEADER_NOT_FOUND);
391
392 /* If the header was not found, then create a buffer with just the size of the user agent string that is about
393 * to be appended to the buffer. */
394 aws_byte_buf_init(&user_agent_buffer, allocator, user_agent_length);
395 }
396
397 /* Append the client's user-agent string. */
398 {
399 aws_byte_buf_append_dynamic(&user_agent_buffer, &g_user_agent_header_product_name);
400 aws_byte_buf_append_dynamic(&user_agent_buffer, &forward_slash);
401 aws_byte_buf_append_dynamic(&user_agent_buffer, &g_s3_client_version);
402 aws_byte_buf_append_dynamic(&user_agent_buffer, &space_delimiter);
403 aws_byte_buf_append_dynamic(&user_agent_buffer, &g_user_agent_header_platform);
404 aws_byte_buf_append_dynamic(&user_agent_buffer, &forward_slash);
405 aws_byte_buf_append_dynamic(&user_agent_buffer, &platform_cursor);
406 }
407
408 /* Apply the updated header. */
409 aws_http_headers_set(headers, g_user_agent_header_name, aws_byte_cursor_from_buf(&user_agent_buffer));
410
411 /* Clean up the scratch buffer. */
412 aws_byte_buf_clean_up(&user_agent_buffer);
413 }
414
415 int aws_s3_parse_content_range_cursor(
416 struct aws_byte_cursor content_range_cursor,
417 uint64_t *out_range_start,
418 uint64_t *out_range_end,
419 uint64_t *out_object_size) {
420
421 /* Expected Format of header is: "bytes StartByte-EndByte/TotalObjectSize" */
422
423 /* Check if it starts with "bytes " */
424 struct aws_byte_cursor bytes_prefix = aws_byte_cursor_from_c_str("bytes ");
425 if (!aws_byte_cursor_starts_with(&content_range_cursor, &bytes_prefix)) {
426 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
427 }
428
429 /* Skip past "bytes " */
430 aws_byte_cursor_advance(&content_range_cursor, bytes_prefix.len);
431
432 /* Parse range start */
433 struct aws_byte_cursor range_start_cursor;
434 AWS_ZERO_STRUCT(range_start_cursor);
435 if (!aws_byte_cursor_next_split(&content_range_cursor, '-', &range_start_cursor)) {
436 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
437 }
438
439 uint64_t range_start = 0;
440 if (aws_byte_cursor_utf8_parse_u64(range_start_cursor, &range_start)) {
441 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
442 }
443 /* Move the cursor to pass the `-` */
444 aws_byte_cursor_advance(&content_range_cursor, range_start_cursor.len + 1);
445 /* Parse range end */
446 struct aws_byte_cursor range_end_cursor;
447 AWS_ZERO_STRUCT(range_end_cursor);
448 if (!aws_byte_cursor_next_split(&content_range_cursor, '/', &range_end_cursor)) {
449 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
450 }
451
452 uint64_t range_end = 0;
453 if (aws_byte_cursor_utf8_parse_u64(range_end_cursor, &range_end)) {
454 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
455 }
456
457 /* Move the cursor to pass the `/` */
458 aws_byte_cursor_advance(&content_range_cursor, range_end_cursor.len + 1);
459 /* Parse object size (remaining part) */
460 uint64_t object_size = 0;
461 if (aws_byte_cursor_utf8_parse_u64(content_range_cursor, &object_size)) {
462 return aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_RANGE_HEADER);
463 }
464
465 /* Set output values */
466 if (out_range_start != NULL) {
467 *out_range_start = range_start;
468 }
469
470 if (out_range_end != NULL) {
471 *out_range_end = range_end;
472 }
473
474 if (out_object_size != NULL) {
475 *out_object_size = object_size;
476 }
477
478 return AWS_OP_SUCCESS;
479 }
480
481 int aws_s3_parse_content_range_response_header(
482 struct aws_http_headers *response_headers,
483 uint64_t *out_range_start,
484 uint64_t *out_range_end,
485 uint64_t *out_object_size) {
486 AWS_ERROR_PRECONDITION(response_headers);
487 struct aws_byte_cursor content_range_header_value;
488
489 if (aws_http_headers_get(response_headers, g_content_range_header_name, &content_range_header_value)) {
490 aws_raise_error(AWS_ERROR_S3_MISSING_CONTENT_RANGE_HEADER);
491 return AWS_OP_ERR;
492 }
493 return aws_s3_parse_content_range_cursor(
494 content_range_header_value, out_range_start, out_range_end, out_object_size);
495 }
496
497 int aws_s3_parse_content_length_response_header(
498 struct aws_allocator *allocator,
499 struct aws_http_headers *response_headers,
500 uint64_t *out_content_length) {
501 AWS_PRECONDITION(allocator);
502 AWS_PRECONDITION(response_headers);
503 AWS_PRECONDITION(out_content_length);
504
505 struct aws_byte_cursor content_length_header_value;
506
507 if (aws_http_headers_get(response_headers, g_content_length_header_name, &content_length_header_value)) {
508 aws_raise_error(AWS_ERROR_S3_MISSING_CONTENT_LENGTH_HEADER);
509 return AWS_OP_ERR;
510 }
511
512 struct aws_string *content_length_header_value_str =
513 aws_string_new_from_cursor(allocator, &content_length_header_value);
514
515 int result = AWS_OP_ERR;
516
517 if (sscanf((const char *)content_length_header_value_str->bytes, "%" PRIu64, out_content_length) == 1) {
518 result = AWS_OP_SUCCESS;
519 } else {
520 aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_LENGTH_HEADER);
521 }
522
523 aws_string_destroy(content_length_header_value_str);
524 return result;
525 }
526
527 int aws_s3_parse_request_range_header(
528 struct aws_http_headers *request_headers,
529 bool *out_has_start_range,
530 bool *out_has_end_range,
531 uint64_t *out_start_range,
532 uint64_t *out_end_range) {
533
534 AWS_PRECONDITION(request_headers);
535 AWS_PRECONDITION(out_has_start_range);
536 AWS_PRECONDITION(out_has_end_range);
537 AWS_PRECONDITION(out_start_range);
538 AWS_PRECONDITION(out_end_range);
539
540 bool has_start_range = false;
541 bool has_end_range = false;
542 uint64_t start_range = 0;
543 uint64_t end_range = 0;
544
545 struct aws_byte_cursor range_header_value;
546
547 if (aws_http_headers_get(request_headers, g_range_header_name, &range_header_value)) {
548 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
549 }
550
551 struct aws_byte_cursor range_header_start = aws_byte_cursor_from_c_str("bytes=");
552
553 /* verify bytes= */
554 if (!aws_byte_cursor_starts_with(&range_header_value, &range_header_start)) {
555 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
556 }
557
558 aws_byte_cursor_advance(&range_header_value, range_header_start.len);
559 struct aws_byte_cursor substr = {0};
560 /* parse start range */
561 if (!aws_byte_cursor_next_split(&range_header_value, '-', &substr)) {
562 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
563 }
564 if (substr.len > 0) {
565 if (aws_byte_cursor_utf8_parse_u64(substr, &start_range)) {
566 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
567 }
568 has_start_range = true;
569 }
570
571 /* parse end range */
572 if (!aws_byte_cursor_next_split(&range_header_value, '-', &substr)) {
573 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
574 }
575 if (substr.len > 0) {
576 if (aws_byte_cursor_utf8_parse_u64(substr, &end_range)) {
577 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
578 }
579 has_end_range = true;
580 }
581
582 /* verify that there is nothing extra */
583 if (aws_byte_cursor_next_split(&range_header_value, '-', &substr)) {
584 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
585 }
586
587 /* verify that start-range <= end-range */
588 if (has_end_range && start_range > end_range) {
589 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
590 }
591
592 /* verify that start-range or end-range is present */
593 if (!has_start_range && !has_end_range) {
594 return aws_raise_error(AWS_ERROR_S3_INVALID_RANGE_HEADER);
595 }
596
597 *out_has_start_range = has_start_range;
598 *out_has_end_range = has_end_range;
599 *out_start_range = start_range;
600 *out_end_range = end_range;
601 return AWS_OP_SUCCESS;
602 }
603
604 uint32_t aws_s3_calculate_auto_ranged_get_num_parts(
605 size_t part_size,
606 uint64_t first_part_size,
607 uint64_t object_range_start,
608 uint64_t object_range_end) {
609 uint32_t num_parts = 1;
610
611 if (first_part_size == 0) {
612 return num_parts;
613 }
614 uint64_t second_part_start = object_range_start + first_part_size;
615
616 /* If the range has room for a second part, calculate the additional amount of parts. */
617 if (second_part_start <= object_range_end) {
618 uint64_t aligned_range_remainder = object_range_end + 1 - second_part_start; /* range-end is inclusive */
619 num_parts += (uint32_t)(aligned_range_remainder / (uint64_t)part_size);
620
621 if ((aligned_range_remainder % part_size) > 0) {
622 ++num_parts;
623 }
624 }
625
626 return num_parts;
627 }
628
629 void aws_s3_calculate_auto_ranged_get_part_range(
630 uint64_t object_range_start,
631 uint64_t object_range_end,
632 size_t part_size,
633 uint64_t first_part_size,
634 uint32_t part_number,
635 uint64_t *out_part_range_start,
636 uint64_t *out_part_range_end) {
637 AWS_PRECONDITION(out_part_range_start);
638 AWS_PRECONDITION(out_part_range_end);
639
640 AWS_ASSERT(part_number > 0);
641
642 const uint32_t part_index = part_number - 1;
643
644 /* Part index is assumed to be in a valid range. */
645 AWS_ASSERT(
646 part_index <
647 aws_s3_calculate_auto_ranged_get_num_parts(part_size, first_part_size, object_range_start, object_range_end));
648
649 uint64_t part_size_uint64 = (uint64_t)part_size;
650
651 if (part_index == 0) {
652 /* If this is the first part, then use the first part size. */
653 *out_part_range_start = object_range_start;
654 *out_part_range_end = *out_part_range_start + first_part_size - 1;
655 } else {
656 /* Else, find the next part by adding the object range + total number of whole parts before this one + initial
657 * part size*/
658 *out_part_range_start = object_range_start + ((uint64_t)(part_index - 1)) * part_size_uint64 + first_part_size;
659 *out_part_range_end = *out_part_range_start + part_size_uint64 - 1; /* range-end is inclusive */
660 }
661
662 /* Cap the part's range end using the object's range end. */
663 if (*out_part_range_end > object_range_end) {
664 *out_part_range_end = object_range_end;
665 }
666 }
667
668 int aws_s3_calculate_optimal_mpu_part_size_and_num_parts(
669 uint64_t content_length,
670 size_t client_part_size,
671 uint64_t client_max_part_size,
672 size_t *out_part_size,
673 uint32_t *out_num_parts) {
674
675 AWS_FATAL_ASSERT(out_part_size);
676 AWS_FATAL_ASSERT(out_num_parts);
677
678 if (content_length == 0) {
679 *out_part_size = 0;
680 *out_num_parts = 0;
681 return AWS_OP_SUCCESS;
682 }
683
684 uint64_t part_size_uint64 = content_length / (uint64_t)g_s3_max_num_upload_parts;
685
686 if ((content_length % g_s3_max_num_upload_parts) > 0) {
687 ++part_size_uint64;
688 }
689
690 if (part_size_uint64 > SIZE_MAX) {
691 AWS_LOGF_ERROR(
692 AWS_LS_S3_META_REQUEST,
693 "Could not create meta request; required part size of %" PRIu64 " bytes is too large for platform.",
694 part_size_uint64);
695
696 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
697 }
698
699 size_t part_size = (size_t)part_size_uint64;
700
701 if (part_size > client_max_part_size) {
702 AWS_LOGF_ERROR(
703 AWS_LS_S3_META_REQUEST,
704 "Could not create meta request; required part size for request is %" PRIu64
705 ", but current maximum part size is %" PRIu64,
706 (uint64_t)part_size,
707 (uint64_t)client_max_part_size);
708 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
709 }
710
711 if (part_size < client_part_size) {
712 part_size = client_part_size;
713 }
714
715 if (content_length < part_size) {
716 /* When the content length is smaller than part size and larger than the threshold, we set one part
717 * with the whole length */
718 part_size = (size_t)content_length;
719 }
720
721 uint32_t num_parts = (uint32_t)(content_length / part_size);
722 if ((content_length % part_size) > 0) {
723 ++num_parts;
724 }
725 AWS_ASSERT(num_parts <= g_s3_max_num_upload_parts);
726
727 *out_part_size = part_size;
728 *out_num_parts = num_parts;
729 return AWS_OP_SUCCESS;
730 }
731
732 int aws_s3_crt_error_code_from_recoverable_server_error_code_string(struct aws_byte_cursor error_code_string) {
733 if (aws_byte_cursor_eq_c_str_ignore_case(&error_code_string, "SlowDown")) {
734 return AWS_ERROR_S3_SLOW_DOWN;
735 }
736 if (aws_byte_cursor_eq_c_str_ignore_case(&error_code_string, "InternalError") ||
737 aws_byte_cursor_eq_c_str_ignore_case(&error_code_string, "InternalErrors")) {
738 return AWS_ERROR_S3_INTERNAL_ERROR;
739 }
740 if (aws_byte_cursor_eq_c_str_ignore_case(&error_code_string, "RequestTimeTooSkewed")) {
741 return AWS_ERROR_S3_REQUEST_TIME_TOO_SKEWED;
742 }
743
744 if (aws_byte_cursor_eq_c_str_ignore_case(&error_code_string, "RequestTimeout")) {
745 return AWS_ERROR_S3_REQUEST_TIMEOUT;
746 }
747
748 return AWS_ERROR_UNKNOWN;
749 }
750
751 void aws_s3_request_finish_up_metrics_synced(struct aws_s3_request *request, struct aws_s3_meta_request *meta_request) {
752 AWS_PRECONDITION(meta_request);
753 AWS_PRECONDITION(request);
754 ASSERT_SYNCED_DATA_LOCK_HELD(meta_request);
755
756 if (request->send_data.metrics != NULL) {
757 /* Request is done, complete the metrics for the request now. */
758 struct aws_s3_request_metrics *metrics = request->send_data.metrics;
759 aws_high_res_clock_get_ticks((uint64_t *)&metrics->time_metrics.end_timestamp_ns);
760 metrics->time_metrics.total_duration_ns =
761 metrics->time_metrics.end_timestamp_ns - metrics->time_metrics.start_timestamp_ns;
762
763 if (meta_request->telemetry_callback != NULL) {
764 struct aws_s3_meta_request_event event = {.type = AWS_S3_META_REQUEST_EVENT_TELEMETRY};
765 event.u.telemetry.metrics = aws_s3_request_metrics_acquire(metrics);
766 aws_s3_meta_request_add_event_for_delivery_synced(meta_request, &event);
767 }
768 request->send_data.metrics = aws_s3_request_metrics_release(metrics);
769 }
770 }
771
772 int aws_s3_check_headers_for_checksum(
773 struct aws_s3_meta_request *meta_request,
774 const struct aws_http_headers *headers,
775 struct aws_s3_checksum **out_checksum,
776 struct aws_byte_buf *out_checksum_buffer,
777 bool meta_request_level) {
778 AWS_PRECONDITION(meta_request);
779 AWS_PRECONDITION(out_checksum);
780 AWS_PRECONDITION(out_checksum_buffer);
781
782 if (!headers || aws_http_headers_count(headers) == 0) {
783 *out_checksum = NULL;
784 return AWS_OP_SUCCESS;
785 }
786 if (meta_request_level && aws_http_headers_has(headers, g_mp_parts_count_header_name)) {
787 /* g_mp_parts_count_header_name indicates it's a object was uploaded as a
788 * multipart upload. So, the checksum should not be applied to the meta request level.
789 * But we we want to check it for the request level. */
790 *out_checksum = NULL;
791 return AWS_OP_SUCCESS;
792 }
793
794 for (size_t i = 0; i < AWS_ARRAY_SIZE(s_checksum_algo_priority_list); i++) {
795 enum aws_s3_checksum_algorithm algorithm = s_checksum_algo_priority_list[i];
796 if (!aws_s3_meta_request_checksum_config_has_algorithm(meta_request, algorithm)) {
797 /* If user doesn't select this algorithm, skip */
798 continue;
799 }
800 const struct aws_byte_cursor algorithm_header_name =
801 aws_get_http_header_name_from_checksum_algorithm(algorithm);
802 struct aws_byte_cursor checksum_value;
803 if (aws_http_headers_get(headers, algorithm_header_name, &checksum_value) == AWS_OP_SUCCESS) {
804 /* Found the checksum header, keep the header value and initialize the running checksum */
805 size_t encoded_len = 0;
806 aws_base64_compute_encoded_len(aws_get_digest_size_from_checksum_algorithm(algorithm), &encoded_len);
807 if (checksum_value.len == encoded_len) {
808 aws_byte_buf_init_copy_from_cursor(out_checksum_buffer, meta_request->allocator, checksum_value);
809 *out_checksum = aws_checksum_new(meta_request->allocator, algorithm);
810 if (!*out_checksum) {
811 AWS_LOGF_ERROR(
812 AWS_LS_S3_META_REQUEST,
813 "Could not create checksum for algorithm: %d, due to error code %d (%s)",
814 algorithm,
815 aws_last_error_or_unknown(),
816 aws_error_str(aws_last_error_or_unknown()));
817 return AWS_OP_ERR;
818 }
819 return AWS_OP_SUCCESS;
820 }
821 break;
822 }
823 }
824 *out_checksum = NULL;
825 return AWS_OP_SUCCESS;
826 }
827
828 int aws_s3_calculate_client_optimal_range_size(
829 uint64_t memory_limit_in_bytes,
830 uint32_t max_connections,
831 uint64_t *out_client_optimal_range_size) {
832
833 AWS_ERROR_PRECONDITION(out_client_optimal_range_size);
834
835 /* Validate input parameters */
836 if (memory_limit_in_bytes == 0 || max_connections == 0) {
837 AWS_LOGF_ERROR(
838 AWS_LS_S3_GENERAL,
839 "Invalid parameters for client optimal range size calculation: memory_limit=%" PRIu64
840 ", max_connections=%" PRIu32,
841 memory_limit_in_bytes,
842 max_connections);
843 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
844 }
845
846 /* Calculate memory-constrained range size using the formula:
847 * MemoryLimit / concurrency / s_optimal_range_size_memory_divisor
848 *
849 * The division by s_optimal_range_size_memory_divisor accounts for:
850 * - All downloaded parts to deliver them in the right order (download)
851 * - All parts read into memory for preparing for the HTTP level (upload)
852 * - All transferring parts in HTTP
853 */
854 uint64_t memory_constrained_size = memory_limit_in_bytes / max_connections / s_optimal_range_size_memory_divisor;
855
856 /* Apply minimum constraint first */
857 uint64_t optimal_size = memory_constrained_size;
858 if (optimal_size < g_default_part_size_fallback) {
859 optimal_size = g_default_part_size_fallback;
860 }
861 /* Apply maximum constraint */
862 if (optimal_size > g_default_max_part_size) {
863 optimal_size = g_default_max_part_size;
864 }
865
866 *out_client_optimal_range_size = optimal_size;
867
868 AWS_LOGF_DEBUG(
869 AWS_LS_S3_GENERAL,
870 "Calculated client optimal range size: memory_limit=%" PRIu64 ", max_connections=%" PRIu32
871 ", client_optimal_range_size=%" PRIu64,
872 memory_limit_in_bytes,
873 max_connections,
874 optimal_size);
875
876 return AWS_OP_SUCCESS;
877 }
878
879 int aws_s3_calculate_request_optimal_range_size(
880 uint64_t client_optimal_range_size,
881 uint64_t estimated_object_stored_part_size,
882 bool is_express,
883 uint64_t *out_request_optimal_range_size) {
884
885 AWS_ERROR_PRECONDITION(out_request_optimal_range_size);
886
887 /* Validate input parameters */
888 if (client_optimal_range_size == 0) {
889 AWS_LOGF_ERROR(
890 AWS_LS_S3_GENERAL,
891 "Invalid client_optimal_range_size for request optimal range size calculation: %" PRIu64,
892 client_optimal_range_size);
893 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
894 }
895
896 /* Apply the minimum constraint from the formula:
897 * min(client_optimal_range_size, estimated_object_stored_part_size)
898 * If estimated_object_stored_part_size is 0 (unknown), use client_optimal_range_size
899 */
900 uint64_t optimal_size = client_optimal_range_size;
901 if (estimated_object_stored_part_size > 0 && estimated_object_stored_part_size < client_optimal_range_size) {
902 optimal_size = estimated_object_stored_part_size;
903 }
904 /* Apply minimum constraint first to avoid excessive alignment */
905 if (optimal_size < g_default_part_size_fallback) {
906 optimal_size = g_default_part_size_fallback;
907 }
908 /* Apply a reasonable upper bound to this. The goal to increase the part size is to have less connection to hit one
909 * single part from server so that we are not bottleneck by the server throughput on one part */
910 if (is_express) {
911 /* As in 2025, each part in S3 express can provide over 100 Gbps throughput.
912 *
913 * Each S3express part can provide a much high throughput than we currently asking for (More than 100Gbps per
914 * part throughput, which means it in theory can handle 100 concurrent connections to 1 part). So, 128MiB
915 * with 5GiB max part size gives 40 connections to hit one part. Have larger range(less connections to hit one
916 * part from server) won't help the goal mentioned above. */
917 optimal_size = aws_min_u64(optimal_size, MB_TO_BYTES(128));
918 } else {
919 /* As in 2025, each part in S3 general bucket can provide around 10 Gbps throughput.
920 * Use 2GiB to below the INT32_MAX. Given the 5GiB max part size */
921 optimal_size = aws_min_u64(optimal_size, GB_TO_BYTES(2));
922 }
923
924 *out_request_optimal_range_size = optimal_size;
925
926 AWS_LOGF_TRACE(
927 AWS_LS_S3_GENERAL,
928 "Calculated request optimal range size: client_optimal_range_size=%" PRIu64 ", estimated_part_size=%" PRIu64
929 ", request_optimal_range_size=%" PRIu64,
930 client_optimal_range_size,
931 estimated_object_stored_part_size,
932 optimal_size);
933
934 return AWS_OP_SUCCESS;
935 }
936
937 static bool s_is_quote_or_space_char(uint8_t c) {
938 return c == '"' || c == ' ';
939 }
940
941 int aws_s3_extract_parts_from_etag(struct aws_byte_cursor etag_header_value, uint32_t *out_num_parts) {
942
943 AWS_ERROR_PRECONDITION(out_num_parts);
944 /* Strip quotes if present (ETags often come wrapped in quotes) */
945 struct aws_byte_cursor etag_cursor = aws_byte_cursor_trim_pred(&etag_header_value, s_is_quote_or_space_char);
946
947 /* Handle empty or invalid ETag */
948 if (etag_cursor.len == 0) {
949 AWS_LOGF_ERROR(AWS_LS_S3_GENERAL, "Empty ETag header value");
950 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
951 }
952
953 /* Use aws_byte_cursor_next_split to iterate through dash-separated parts */
954 struct aws_byte_cursor substr = {0};
955 struct aws_byte_cursor remaining_cursor = etag_cursor;
956 int split_count = 0;
957 struct aws_byte_cursor parts_count = {0};
958
959 /* Count splits and extract parts */
960 while (aws_byte_cursor_next_split(&remaining_cursor, '-', &substr)) {
961 split_count++;
962 if (split_count == 2) {
963 /**
964 * The ETag should follow the pattern <hash>-<parts_count>, so the second part is the parts count.
965 * The S3 ETag will not have `-` in the hash value, as it's a HEX string.
966 **/
967 parts_count = substr;
968 }
969 if (split_count > 2) {
970 /* More than 2 parts - invalid format */
971 AWS_LOGF_ERROR(
972 AWS_LS_S3_GENERAL,
973 "Invalid ETag format - multiple dashes found: " PRInSTR,
974 AWS_BYTE_CURSOR_PRI(etag_header_value));
975 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
976 }
977 }
978
979 if (split_count == 1) {
980 /* No dash found - this is a single-part upload */
981 *out_num_parts = 1;
982 AWS_LOGF_TRACE(
983 AWS_LS_S3_GENERAL, "Single-part ETag detected (no dash): " PRInSTR, AWS_BYTE_CURSOR_PRI(etag_cursor));
984 return AWS_OP_SUCCESS;
985 } else if (split_count == 2) {
986 /* Exactly one dash - multipart upload format */
987 /* Parse the number after the dash */
988 uint64_t num_parts_u64;
989 if (aws_byte_cursor_utf8_parse_u64(parts_count, &num_parts_u64)) {
990 AWS_LOGF_ERROR(
991 AWS_LS_S3_GENERAL,
992 "Invalid ETag format - could not parse number of parts: " PRInSTR,
993 AWS_BYTE_CURSOR_PRI(parts_count));
994 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
995 }
996
997 /* Validate the number is within reasonable bounds */
998 if (num_parts_u64 == 0 || num_parts_u64 > g_s3_max_num_upload_parts) {
999 AWS_LOGF_ERROR(
1000 AWS_LS_S3_GENERAL,
1001 "Invalid number of parts in ETag: %" PRIu64 " (must be 1-%" PRIu32 ")",
1002 num_parts_u64,
1003 g_s3_max_num_upload_parts);
1004 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1005 }
1006
1007 *out_num_parts = (uint32_t)num_parts_u64;
1008 } else {
1009 /* Should not reach here due to early exit above, but handle just in case */
1010 AWS_LOGF_ERROR(AWS_LS_S3_GENERAL, "Unexpected split count: %d", split_count);
1011 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1012 }
1013
1014 AWS_LOGF_TRACE(
1015 AWS_LS_S3_GENERAL,
1016 "Extracted %" PRIu32 " parts from ETag: " PRInSTR,
1017 *out_num_parts,
1018 AWS_BYTE_CURSOR_PRI(etag_header_value));
1019
1020 return AWS_OP_SUCCESS;
1021 }
1022
1023 static const struct aws_byte_cursor s_checksum_prefix = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("x-amz-checksum-");
1024
1025 bool aws_s3_is_checksum_value_header_name(struct aws_byte_cursor header_name) {
1026 return aws_byte_cursor_starts_with_ignore_case(&header_name, &s_checksum_prefix) &&
1027 !aws_byte_cursor_eq_c_str_ignore_case(&header_name, "x-amz-checksum-type") &&
1028 !aws_byte_cursor_eq_c_str_ignore_case(&header_name, "x-amz-checksum-mode") &&
1029 !aws_byte_cursor_eq_c_str_ignore_case(&header_name, "x-amz-checksum-algorithm");
1030 }