Shenghong commited on
Commit
bfd87b5
·
verified ·
1 Parent(s): d617dd9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. include/aws/auth/auth.h +94 -0
  2. include/aws/auth/aws_imds_client.h +489 -0
  3. include/aws/auth/credentials.h +1277 -0
  4. include/aws/auth/exports.h +29 -0
  5. include/aws/auth/signable.h +237 -0
  6. include/aws/auth/signing.h +138 -0
  7. include/aws/auth/signing_config.h +314 -0
  8. include/aws/auth/signing_result.h +169 -0
  9. include/aws/cal/cal.h +61 -0
  10. include/aws/cal/ecc.h +185 -0
  11. include/aws/cal/ed25519.h +88 -0
  12. include/aws/cal/exports.h +28 -0
  13. include/aws/cal/hash.h +139 -0
  14. include/aws/cal/hmac.h +87 -0
  15. include/aws/cal/rsa.h +175 -0
  16. include/aws/cal/symmetric_cipher.h +259 -0
  17. include/aws/common/allocator.h +234 -0
  18. include/aws/common/array_list.h +241 -0
  19. include/aws/common/array_list.inl +410 -0
  20. include/aws/common/atomics.h +329 -0
  21. include/aws/common/atomics.inl +147 -0
  22. include/aws/common/atomics_gnu.inl +218 -0
  23. include/aws/common/byte_order.h +76 -0
  24. include/aws/common/cache.h +87 -0
  25. include/aws/common/cbor.h +460 -0
  26. include/aws/common/common.h +48 -0
  27. include/aws/common/condition_variable.h +118 -0
  28. include/aws/common/config.h +33 -0
  29. include/aws/common/cpuid.h +36 -0
  30. include/aws/common/cross_process_lock.h +35 -0
  31. include/aws/common/date_time.h +167 -0
  32. include/aws/common/device_random.h +50 -0
  33. include/aws/common/encoding.h +235 -0
  34. include/aws/common/encoding.inl +142 -0
  35. include/aws/common/environment.h +65 -0
  36. include/aws/common/error.h +225 -0
  37. include/aws/common/exports.h +40 -0
  38. include/aws/common/fifo_cache.h +31 -0
  39. include/aws/common/file.h +213 -0
  40. include/aws/common/hash_table.h +454 -0
  41. include/aws/common/host_utils.h +28 -0
  42. include/aws/common/json.h +489 -0
  43. include/aws/common/lifo_cache.h +31 -0
  44. include/aws/common/linked_hash_table.h +125 -0
  45. include/aws/common/linked_list.h +196 -0
  46. include/aws/common/linked_list.inl +440 -0
  47. include/aws/common/log_channel.h +75 -0
  48. include/aws/common/log_formatter.h +98 -0
  49. include/aws/common/log_writer.h +76 -0
  50. include/aws/common/logging.h +360 -0
include/aws/auth/auth.h ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_AUTH_H
2
+ #define AWS_AUTH_AUTH_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/auth/exports.h>
10
+
11
+ #include <aws/io/logging.h>
12
+ #include <aws/sdkutils/sdkutils.h>
13
+
14
+ AWS_PUSH_SANE_WARNING_LEVEL
15
+
16
+ #define AWS_C_AUTH_PACKAGE_ID 6
17
+
18
+ /**
19
+ * Auth-specific error codes
20
+ */
21
+ enum aws_auth_errors {
22
+ AWS_AUTH_PROFILE_PARSE_RECOVERABLE_ERROR = AWS_ERROR_SDKUTILS_PARSE_RECOVERABLE,
23
+ AWS_AUTH_PROFILE_PARSE_FATAL_ERROR = AWS_ERROR_SDKUTILS_PARSE_FATAL,
24
+ AWS_AUTH_SIGNING_UNSUPPORTED_ALGORITHM = AWS_ERROR_ENUM_BEGIN_RANGE(AWS_C_AUTH_PACKAGE_ID),
25
+ AWS_AUTH_SIGNING_MISMATCHED_CONFIGURATION,
26
+ AWS_AUTH_SIGNING_NO_CREDENTIALS,
27
+ AWS_AUTH_SIGNING_ILLEGAL_REQUEST_QUERY_PARAM,
28
+ AWS_AUTH_SIGNING_ILLEGAL_REQUEST_HEADER,
29
+ AWS_AUTH_SIGNING_INVALID_CONFIGURATION,
30
+ AWS_AUTH_CREDENTIALS_PROVIDER_INVALID_ENVIRONMENT,
31
+ AWS_AUTH_CREDENTIALS_PROVIDER_INVALID_DELEGATE,
32
+ AWS_AUTH_CREDENTIALS_PROVIDER_PROFILE_SOURCE_FAILURE,
33
+ AWS_AUTH_CREDENTIALS_PROVIDER_IMDS_SOURCE_FAILURE,
34
+ AWS_AUTH_CREDENTIALS_PROVIDER_STS_SOURCE_FAILURE,
35
+ AWS_AUTH_CREDENTIALS_PROVIDER_HTTP_STATUS_FAILURE,
36
+ AWS_AUTH_PROVIDER_PARSER_UNEXPECTED_RESPONSE,
37
+ AWS_AUTH_CREDENTIALS_PROVIDER_ECS_SOURCE_FAILURE,
38
+ AWS_AUTH_CREDENTIALS_PROVIDER_X509_SOURCE_FAILURE,
39
+ AWS_AUTH_CREDENTIALS_PROVIDER_PROCESS_SOURCE_FAILURE,
40
+ AWS_AUTH_CREDENTIALS_PROVIDER_STS_WEB_IDENTITY_SOURCE_FAILURE,
41
+ AWS_AUTH_SIGNING_UNSUPPORTED_SIGNATURE_TYPE,
42
+ AWS_AUTH_SIGNING_MISSING_PREVIOUS_SIGNATURE,
43
+ AWS_AUTH_SIGNING_INVALID_CREDENTIALS,
44
+ AWS_AUTH_CANONICAL_REQUEST_MISMATCH,
45
+ AWS_AUTH_SIGV4A_SIGNATURE_VALIDATION_FAILURE,
46
+ AWS_AUTH_CREDENTIALS_PROVIDER_COGNITO_SOURCE_FAILURE,
47
+ AWS_AUTH_CREDENTIALS_PROVIDER_DELEGATE_FAILURE,
48
+ AWS_AUTH_SSO_TOKEN_PROVIDER_SOURCE_FAILURE,
49
+ AWS_AUTH_SSO_TOKEN_INVALID,
50
+ AWS_AUTH_SSO_TOKEN_EXPIRED,
51
+ AWS_AUTH_CREDENTIALS_PROVIDER_SSO_SOURCE_FAILURE,
52
+ AWS_AUTH_IMDS_CLIENT_SOURCE_FAILURE,
53
+ AWS_AUTH_PROFILE_STS_CREDENTIALS_PROVIDER_CYCLE_FAILURE,
54
+ AWS_AUTH_CREDENTIALS_PROVIDER_ECS_INVALID_TOKEN_FILE_PATH,
55
+ AWS_AUTH_CREDENTIALS_PROVIDER_ECS_INVALID_HOST,
56
+
57
+ AWS_AUTH_ERROR_END_RANGE = AWS_ERROR_ENUM_END_RANGE(AWS_C_AUTH_PACKAGE_ID)
58
+ };
59
+
60
+ /**
61
+ * Auth-specific logging subjects
62
+ */
63
+ enum aws_auth_log_subject {
64
+ AWS_LS_AUTH_GENERAL = AWS_LOG_SUBJECT_BEGIN_RANGE(AWS_C_AUTH_PACKAGE_ID),
65
+ AWS_LS_AUTH_PROFILE,
66
+ AWS_LS_AUTH_CREDENTIALS_PROVIDER,
67
+ AWS_LS_AUTH_SIGNING,
68
+ AWS_LS_IMDS_CLIENT,
69
+
70
+ AWS_LS_AUTH_LAST = AWS_LOG_SUBJECT_END_RANGE(AWS_C_AUTH_PACKAGE_ID)
71
+ };
72
+
73
+ AWS_EXTERN_C_BEGIN
74
+
75
+ /**
76
+ * Initializes internal datastructures used by aws-c-auth.
77
+ * Must be called before using any functionality in aws-c-auth.
78
+ *
79
+ * @param allocator memory allocator to use for any module-level memory allocation
80
+ */
81
+ AWS_AUTH_API
82
+ void aws_auth_library_init(struct aws_allocator *allocator);
83
+
84
+ /**
85
+ * Clean up internal datastructures used by aws-c-auth.
86
+ * Must not be called until application is done using functionality in aws-c-auth.
87
+ */
88
+ AWS_AUTH_API
89
+ void aws_auth_library_clean_up(void);
90
+
91
+ AWS_EXTERN_C_END
92
+ AWS_POP_SANE_WARNING_LEVEL
93
+
94
+ #endif /* AWS_AUTH_AUTH_H */
include/aws/auth/aws_imds_client.h ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_IMDS_CLIENT_H
2
+ #define AWS_AUTH_IMDS_CLIENT_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+ #include <aws/auth/auth.h>
9
+ #include <aws/auth/credentials.h>
10
+ #include <aws/common/array_list.h>
11
+ #include <aws/common/date_time.h>
12
+ #include <aws/http/connection_manager.h>
13
+ #include <aws/io/retry_strategy.h>
14
+
15
+ AWS_PUSH_SANE_WARNING_LEVEL
16
+
17
+ typedef void(aws_imds_client_shutdown_completed_fn)(void *user_data);
18
+
19
+ /**
20
+ * Optional callback and user data to be invoked when an imds client has fully shut down
21
+ */
22
+ struct aws_imds_client_shutdown_options {
23
+ aws_imds_client_shutdown_completed_fn *shutdown_callback;
24
+ void *shutdown_user_data;
25
+ };
26
+
27
+ /**
28
+ * Configuration options when creating an imds client
29
+ */
30
+ struct aws_imds_client_options {
31
+ /*
32
+ * Completion callback to be invoked when the client has fully shut down
33
+ */
34
+ struct aws_imds_client_shutdown_options shutdown_options;
35
+
36
+ /*
37
+ * Client bootstrap to use when this client makes network connections
38
+ */
39
+ struct aws_client_bootstrap *bootstrap;
40
+
41
+ /*
42
+ * Retry strategy instance that governs how failed requests are retried
43
+ */
44
+ struct aws_retry_strategy *retry_strategy;
45
+
46
+ /*
47
+ * What version of the imds protocol to use
48
+ *
49
+ * Defaults to IMDS_PROTOCOL_V2
50
+ */
51
+ enum aws_imds_protocol_version imds_version;
52
+
53
+ /*
54
+ * If true, fallback from v2 to v1 will be disabled for all cases
55
+ */
56
+ bool ec2_metadata_v1_disabled;
57
+
58
+ /*
59
+ * Table holding all cross-system functional dependencies for an imds client.
60
+ *
61
+ * For mocking the http layer in tests, leave NULL otherwise
62
+ */
63
+ struct aws_auth_http_system_vtable *function_table;
64
+ };
65
+
66
+ /*
67
+ * Standard callback for instance metadata queries
68
+ */
69
+ typedef void(
70
+ aws_imds_client_on_get_resource_callback_fn)(const struct aws_byte_buf *resource, int error_code, void *user_data);
71
+
72
+ /**
73
+ * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html
74
+ */
75
+ struct aws_imds_iam_profile {
76
+ struct aws_date_time last_updated;
77
+ struct aws_byte_cursor instance_profile_arn;
78
+ struct aws_byte_cursor instance_profile_id;
79
+ };
80
+
81
+ /**
82
+ * Block of per-instance EC2-specific data
83
+ *
84
+ * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
85
+ */
86
+ struct aws_imds_instance_info {
87
+ /* an array of aws_byte_cursor */
88
+ struct aws_array_list marketplace_product_codes;
89
+ struct aws_byte_cursor availability_zone;
90
+ struct aws_byte_cursor private_ip;
91
+ struct aws_byte_cursor version;
92
+ struct aws_byte_cursor instance_id;
93
+ /* an array of aws_byte_cursor */
94
+ struct aws_array_list billing_products;
95
+ struct aws_byte_cursor instance_type;
96
+ struct aws_byte_cursor account_id;
97
+ struct aws_byte_cursor image_id;
98
+ struct aws_date_time pending_time;
99
+ struct aws_byte_cursor architecture;
100
+ struct aws_byte_cursor kernel_id;
101
+ struct aws_byte_cursor ramdisk_id;
102
+ struct aws_byte_cursor region;
103
+ };
104
+
105
+ /* the item typed stored in array is pointer to aws_byte_cursor */
106
+ typedef void(
107
+ aws_imds_client_on_get_array_callback_fn)(const struct aws_array_list *array, int error_code, void *user_data);
108
+
109
+ typedef void(aws_imds_client_on_get_credentials_callback_fn)(
110
+ const struct aws_credentials *credentials,
111
+ int error_code,
112
+ void *user_data);
113
+
114
+ typedef void(aws_imds_client_on_get_iam_profile_callback_fn)(
115
+ const struct aws_imds_iam_profile *iam_profile_info,
116
+ int error_code,
117
+ void *user_data);
118
+
119
+ typedef void(aws_imds_client_on_get_instance_info_callback_fn)(
120
+ const struct aws_imds_instance_info *instance_info,
121
+ int error_code,
122
+ void *user_data);
123
+
124
+ /**
125
+ * AWS EC2 Metadata Client is used to retrieve AWS EC2 Instance Metadata info.
126
+ */
127
+ struct aws_imds_client;
128
+
129
+ AWS_EXTERN_C_BEGIN
130
+
131
+ /**
132
+ * Creates a new imds client
133
+ *
134
+ * @param allocator memory allocator to use for creation and queries
135
+ * @param options configuration options for the imds client
136
+ *
137
+ * @return a newly-constructed imds client, or NULL on failure
138
+ */
139
+ AWS_AUTH_API
140
+ struct aws_imds_client *aws_imds_client_new(
141
+ struct aws_allocator *allocator,
142
+ const struct aws_imds_client_options *options);
143
+
144
+ /**
145
+ * Increments the ref count on the client
146
+ *
147
+ * @param client imds client to acquire a reference to
148
+ */
149
+ AWS_AUTH_API
150
+ void aws_imds_client_acquire(struct aws_imds_client *client);
151
+
152
+ /**
153
+ * Decrements the ref count on the client
154
+ *
155
+ * @param client imds client to release a reference to
156
+ */
157
+ AWS_AUTH_API
158
+ void aws_imds_client_release(struct aws_imds_client *client);
159
+
160
+ /**
161
+ * Queries a generic resource (string) from the ec2 instance metadata document
162
+ *
163
+ * @param client imds client to use for the query
164
+ * @param resource_path path of the resource to query
165
+ * @param callback callback function to invoke on query success or failure
166
+ * @param user_data opaque data to invoke the completion callback with
167
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
168
+ */
169
+ AWS_AUTH_API
170
+ int aws_imds_client_get_resource_async(
171
+ struct aws_imds_client *client,
172
+ struct aws_byte_cursor resource_path,
173
+ aws_imds_client_on_get_resource_callback_fn callback,
174
+ void *user_data);
175
+
176
+ /**
177
+ * Gets the ami id of the ec2 instance from the instance metadata document
178
+ *
179
+ * @param client imds client to use for the query
180
+ * @param callback callback function to invoke on query success or failure
181
+ * @param user_data opaque data to invoke the completion callback with
182
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
183
+ */
184
+ AWS_AUTH_API
185
+ int aws_imds_client_get_ami_id(
186
+ struct aws_imds_client *client,
187
+ aws_imds_client_on_get_resource_callback_fn callback,
188
+ void *user_data);
189
+
190
+ /**
191
+ * Gets the ami launch index of the ec2 instance from the instance metadata document
192
+ *
193
+ * @param client imds client to use for the query
194
+ * @param callback callback function to invoke on query success or failure
195
+ * @param user_data opaque data to invoke the completion callback with
196
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
197
+ */
198
+ AWS_AUTH_API
199
+ int aws_imds_client_get_ami_launch_index(
200
+ struct aws_imds_client *client,
201
+ aws_imds_client_on_get_resource_callback_fn callback,
202
+ void *user_data);
203
+
204
+ /**
205
+ * Gets the ami manifest path of the ec2 instance from the instance metadata document
206
+ *
207
+ * @param client imds client to use for the query
208
+ * @param callback callback function to invoke on query success or failure
209
+ * @param user_data opaque data to invoke the completion callback with
210
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
211
+ */
212
+ AWS_AUTH_API
213
+ int aws_imds_client_get_ami_manifest_path(
214
+ struct aws_imds_client *client,
215
+ aws_imds_client_on_get_resource_callback_fn callback,
216
+ void *user_data);
217
+
218
+ /**
219
+ * Gets the list of ancestor ami ids of the ec2 instance from the instance metadata document
220
+ *
221
+ * @param client imds client to use for the query
222
+ * @param callback callback function to invoke on query success or failure
223
+ * @param user_data opaque data to invoke the completion callback with
224
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
225
+ */
226
+ AWS_AUTH_API
227
+ int aws_imds_client_get_ancestor_ami_ids(
228
+ struct aws_imds_client *client,
229
+ aws_imds_client_on_get_array_callback_fn callback,
230
+ void *user_data);
231
+
232
+ /**
233
+ * Gets the instance-action of the ec2 instance from the instance metadata document
234
+ *
235
+ * @param client imds client to use for the query
236
+ * @param callback callback function to invoke on query success or failure
237
+ * @param user_data opaque data to invoke the completion callback with
238
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
239
+ */
240
+ AWS_AUTH_API
241
+ int aws_imds_client_get_instance_action(
242
+ struct aws_imds_client *client,
243
+ aws_imds_client_on_get_resource_callback_fn callback,
244
+ void *user_data);
245
+
246
+ /**
247
+ * Gets the instance id of the ec2 instance from the instance metadata document
248
+ *
249
+ * @param client imds client to use for the query
250
+ * @param callback callback function to invoke on query success or failure
251
+ * @param user_data opaque data to invoke the completion callback with
252
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
253
+ */
254
+ AWS_AUTH_API
255
+ int aws_imds_client_get_instance_id(
256
+ struct aws_imds_client *client,
257
+ aws_imds_client_on_get_resource_callback_fn callback,
258
+ void *user_data);
259
+
260
+ /**
261
+ * Gets the instance type of the ec2 instance from the instance metadata document
262
+ *
263
+ * @param client imds client to use for the query
264
+ * @param callback callback function to invoke on query success or failure
265
+ * @param user_data opaque data to invoke the completion callback with
266
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
267
+ */
268
+ AWS_AUTH_API
269
+ int aws_imds_client_get_instance_type(
270
+ struct aws_imds_client *client,
271
+ aws_imds_client_on_get_resource_callback_fn callback,
272
+ void *user_data);
273
+
274
+ /**
275
+ * Gets the mac address of the ec2 instance from the instance metadata document
276
+ *
277
+ * @param client imds client to use for the query
278
+ * @param callback callback function to invoke on query success or failure
279
+ * @param user_data opaque data to invoke the completion callback with
280
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
281
+ */
282
+ AWS_AUTH_API
283
+ int aws_imds_client_get_mac_address(
284
+ struct aws_imds_client *client,
285
+ aws_imds_client_on_get_resource_callback_fn callback,
286
+ void *user_data);
287
+
288
+ /**
289
+ * Gets the private ip address of the ec2 instance from the instance metadata document
290
+ *
291
+ * @param client imds client to use for the query
292
+ * @param callback callback function to invoke on query success or failure
293
+ * @param user_data opaque data to invoke the completion callback with
294
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
295
+ */
296
+ AWS_AUTH_API
297
+ int aws_imds_client_get_private_ip_address(
298
+ struct aws_imds_client *client,
299
+ aws_imds_client_on_get_resource_callback_fn callback,
300
+ void *user_data);
301
+
302
+ /**
303
+ * Gets the availability zone of the ec2 instance from the instance metadata document
304
+ *
305
+ * @param client imds client to use for the query
306
+ * @param callback callback function to invoke on query success or failure
307
+ * @param user_data opaque data to invoke the completion callback with
308
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
309
+ */
310
+ AWS_AUTH_API
311
+ int aws_imds_client_get_availability_zone(
312
+ struct aws_imds_client *client,
313
+ aws_imds_client_on_get_resource_callback_fn callback,
314
+ void *user_data);
315
+
316
+ /**
317
+ * Gets the product codes of the ec2 instance from the instance metadata document
318
+ *
319
+ * @param client imds client to use for the query
320
+ * @param callback callback function to invoke on query success or failure
321
+ * @param user_data opaque data to invoke the completion callback with
322
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
323
+ */
324
+ AWS_AUTH_API
325
+ int aws_imds_client_get_product_codes(
326
+ struct aws_imds_client *client,
327
+ aws_imds_client_on_get_resource_callback_fn callback,
328
+ void *user_data);
329
+
330
+ /**
331
+ * Gets the public key of the ec2 instance from the instance metadata document
332
+ *
333
+ * @param client imds client to use for the query
334
+ * @param callback callback function to invoke on query success or failure
335
+ * @param user_data opaque data to invoke the completion callback with
336
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
337
+ */
338
+ AWS_AUTH_API
339
+ int aws_imds_client_get_public_key(
340
+ struct aws_imds_client *client,
341
+ aws_imds_client_on_get_resource_callback_fn callback,
342
+ void *user_data);
343
+
344
+ /**
345
+ * Gets the ramdisk id of the ec2 instance from the instance metadata document
346
+ *
347
+ * @param client imds client to use for the query
348
+ * @param callback callback function to invoke on query success or failure
349
+ * @param user_data opaque data to invoke the completion callback with
350
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
351
+ */
352
+ AWS_AUTH_API
353
+ int aws_imds_client_get_ramdisk_id(
354
+ struct aws_imds_client *client,
355
+ aws_imds_client_on_get_resource_callback_fn callback,
356
+ void *user_data);
357
+
358
+ /**
359
+ * Gets the reservation id of the ec2 instance from the instance metadata document
360
+ *
361
+ * @param client imds client to use for the query
362
+ * @param callback callback function to invoke on query success or failure
363
+ * @param user_data opaque data to invoke the completion callback with
364
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
365
+ */
366
+ AWS_AUTH_API
367
+ int aws_imds_client_get_reservation_id(
368
+ struct aws_imds_client *client,
369
+ aws_imds_client_on_get_resource_callback_fn callback,
370
+ void *user_data);
371
+
372
+ /**
373
+ * Gets the list of the security groups of the ec2 instance from the instance metadata document
374
+ *
375
+ * @param client imds client to use for the query
376
+ * @param callback callback function to invoke on query success or failure
377
+ * @param user_data opaque data to invoke the completion callback with
378
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
379
+ */
380
+ AWS_AUTH_API
381
+ int aws_imds_client_get_security_groups(
382
+ struct aws_imds_client *client,
383
+ aws_imds_client_on_get_array_callback_fn callback,
384
+ void *user_data);
385
+
386
+ /**
387
+ * Gets the list of block device mappings of the ec2 instance from the instance metadata document
388
+ *
389
+ * @param client imds client to use for the query
390
+ * @param callback callback function to invoke on query success or failure
391
+ * @param user_data opaque data to invoke the completion callback with
392
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
393
+ */
394
+ AWS_AUTH_API
395
+ int aws_imds_client_get_block_device_mapping(
396
+ struct aws_imds_client *client,
397
+ aws_imds_client_on_get_array_callback_fn callback,
398
+ void *user_data);
399
+
400
+ /**
401
+ * Gets the attached iam role of the ec2 instance from the instance metadata document
402
+ *
403
+ * @param client imds client to use for the query
404
+ * @param callback callback function to invoke on query success or failure
405
+ * @param user_data opaque data to invoke the completion callback with
406
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
407
+ */
408
+ AWS_AUTH_API
409
+ int aws_imds_client_get_attached_iam_role(
410
+ struct aws_imds_client *client,
411
+ aws_imds_client_on_get_resource_callback_fn callback,
412
+ void *user_data);
413
+
414
+ /**
415
+ * Gets temporary credentials based on the attached iam role of the ec2 instance
416
+ *
417
+ * @param client imds client to use for the query
418
+ * @param iam_role_name iam role name to get temporary credentials through
419
+ * @param callback callback function to invoke on query success or failure
420
+ * @param user_data opaque data to invoke the completion callback with
421
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
422
+ */
423
+ AWS_AUTH_API
424
+ int aws_imds_client_get_credentials(
425
+ struct aws_imds_client *client,
426
+ struct aws_byte_cursor iam_role_name,
427
+ aws_imds_client_on_get_credentials_callback_fn callback,
428
+ void *user_data);
429
+
430
+ /**
431
+ * Gets the iam profile information of the ec2 instance from the instance metadata document
432
+ *
433
+ * @param client imds client to use for the query
434
+ * @param callback callback function to invoke on query success or failure
435
+ * @param user_data opaque data to invoke the completion callback with
436
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
437
+ */
438
+ AWS_AUTH_API
439
+ int aws_imds_client_get_iam_profile(
440
+ struct aws_imds_client *client,
441
+ aws_imds_client_on_get_iam_profile_callback_fn callback,
442
+ void *user_data);
443
+
444
+ /**
445
+ * Gets the user data of the ec2 instance from the instance metadata document
446
+ *
447
+ * @param client imds client to use for the query
448
+ * @param callback callback function to invoke on query success or failure
449
+ * @param user_data opaque data to invoke the completion callback with
450
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
451
+ */
452
+ AWS_AUTH_API
453
+ int aws_imds_client_get_user_data(
454
+ struct aws_imds_client *client,
455
+ aws_imds_client_on_get_resource_callback_fn callback,
456
+ void *user_data);
457
+
458
+ /**
459
+ * Gets the signature of the ec2 instance from the instance metadata document
460
+ *
461
+ * @param client imds client to use for the query
462
+ * @param callback callback function to invoke on query success or failure
463
+ * @param user_data opaque data to invoke the completion callback with
464
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
465
+ */
466
+ AWS_AUTH_API
467
+ int aws_imds_client_get_instance_signature(
468
+ struct aws_imds_client *client,
469
+ aws_imds_client_on_get_resource_callback_fn callback,
470
+ void *user_data);
471
+
472
+ /**
473
+ * Gets the instance information data block of the ec2 instance from the instance metadata document
474
+ *
475
+ * @param client imds client to use for the query
476
+ * @param callback callback function to invoke on query success or failure
477
+ * @param user_data opaque data to invoke the completion callback with
478
+ * @return AWS_OP_SUCCESS if the query was successfully started, AWS_OP_ERR otherwise
479
+ */
480
+ AWS_AUTH_API
481
+ int aws_imds_client_get_instance_info(
482
+ struct aws_imds_client *client,
483
+ aws_imds_client_on_get_instance_info_callback_fn callback,
484
+ void *user_data);
485
+
486
+ AWS_EXTERN_C_END
487
+ AWS_POP_SANE_WARNING_LEVEL
488
+
489
+ #endif /* AWS_AUTH_IMDS_CLIENT_H */
include/aws/auth/credentials.h ADDED
@@ -0,0 +1,1277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_CREDENTIALS_H
2
+ #define AWS_AUTH_CREDENTIALS_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/auth/auth.h>
10
+ #include <aws/common/array_list.h>
11
+ #include <aws/common/atomics.h>
12
+ #include <aws/common/linked_list.h>
13
+ #include <aws/io/io.h>
14
+
15
+ AWS_PUSH_SANE_WARNING_LEVEL
16
+
17
+ struct aws_client_bootstrap;
18
+ struct aws_auth_http_system_vtable;
19
+ struct aws_credentials;
20
+ struct aws_credentials_provider;
21
+ struct aws_ecc_key_pair;
22
+ struct aws_string;
23
+
24
+ extern const uint16_t aws_sts_assume_role_default_duration_secs;
25
+
26
+ /*
27
+ * Signature for the credentials sourcing callback
28
+ */
29
+ typedef void(aws_on_get_credentials_callback_fn)(struct aws_credentials *credentials, int error_code, void *user_data);
30
+
31
+ typedef int(aws_credentials_provider_get_credentials_fn)(
32
+ struct aws_credentials_provider *provider,
33
+ aws_on_get_credentials_callback_fn callback,
34
+ void *user_data);
35
+ typedef void(aws_credentials_provider_destroy_fn)(struct aws_credentials_provider *provider);
36
+
37
+ /*
38
+ * Common function table that all credentials provider implementations must support
39
+ */
40
+ struct aws_credentials_provider_vtable {
41
+ aws_credentials_provider_get_credentials_fn *get_credentials;
42
+ aws_credentials_provider_destroy_fn *destroy;
43
+ };
44
+
45
+ typedef void(aws_credentials_provider_shutdown_completed_fn)(void *user_data);
46
+
47
+ /*
48
+ * All credentials providers support an optional shutdown callback that
49
+ * gets invoked, with appropriate user data, when the resources used by the provider
50
+ * are no longer in use. For example, the imds provider uses this to
51
+ * signal when it is no longer using the client bootstrap used in its
52
+ * internal connection manager.
53
+ */
54
+ struct aws_credentials_provider_shutdown_options {
55
+ aws_credentials_provider_shutdown_completed_fn *shutdown_callback;
56
+ void *shutdown_user_data;
57
+ };
58
+
59
+ /**
60
+ * A baseclass for credentials providers. A credentials provider is an object that has an asynchronous
61
+ * query function for retrieving AWS credentials.
62
+ *
63
+ * Ref-counted. Thread-safe.
64
+ */
65
+ struct aws_credentials_provider {
66
+ struct aws_credentials_provider_vtable *vtable;
67
+ struct aws_allocator *allocator;
68
+ struct aws_credentials_provider_shutdown_options shutdown_options;
69
+ void *impl;
70
+ struct aws_atomic_var ref_count;
71
+ };
72
+
73
+ /*
74
+ * Config structs for creating all the different credentials providers
75
+ */
76
+
77
+ /**
78
+ * Configuration options for a provider that returns a fixed set of credentials
79
+ */
80
+ struct aws_credentials_provider_static_options {
81
+ struct aws_credentials_provider_shutdown_options shutdown_options;
82
+ struct aws_byte_cursor access_key_id;
83
+ struct aws_byte_cursor secret_access_key;
84
+ struct aws_byte_cursor session_token;
85
+ struct aws_byte_cursor account_id;
86
+ };
87
+
88
+ /**
89
+ * Configuration options for a provider that returns credentials based on environment variable values
90
+ */
91
+ struct aws_credentials_provider_environment_options {
92
+ struct aws_credentials_provider_shutdown_options shutdown_options;
93
+ };
94
+
95
+ /**
96
+ * Configuration options for a provider that sources credentials from the aws config and credentials files
97
+ * (by default ~/.aws/config and ~/.aws/credentials)
98
+ */
99
+ struct aws_credentials_provider_profile_options {
100
+ struct aws_credentials_provider_shutdown_options shutdown_options;
101
+
102
+ /*
103
+ * Override of what profile to use to source credentials from ('default' by default)
104
+ */
105
+ struct aws_byte_cursor profile_name_override;
106
+
107
+ /*
108
+ * Override path to the profile config file (~/.aws/config by default)
109
+ */
110
+ struct aws_byte_cursor config_file_name_override;
111
+
112
+ /*
113
+ * Override path to the profile credentials file (~/.aws/credentials by default)
114
+ */
115
+ struct aws_byte_cursor credentials_file_name_override;
116
+
117
+ /**
118
+ * (Optional)
119
+ * Use a cached merged profile collection. A merge collection has both config file
120
+ * (~/.aws/config) and credentials file based profile collection (~/.aws/credentials) using
121
+ * `aws_profile_collection_new_from_merge`.
122
+ * If this option is provided, `config_file_name_override` and `credentials_file_name_override` will be ignored.
123
+ */
124
+ struct aws_profile_collection *profile_collection_cached;
125
+
126
+ /*
127
+ * Bootstrap to use for any network connections made while sourcing credentials (for example,
128
+ * a profile that uses assume-role will need to hit STS)
129
+ */
130
+ struct aws_client_bootstrap *bootstrap;
131
+
132
+ /*
133
+ * Client TLS context to use for any secure network connections made while sourcing credentials
134
+ * (for example, a profile that uses assume-role will need to hit STS).
135
+ *
136
+ * If a TLS context is needed, and you did not pass one in, it will be created automatically.
137
+ * However, you are encouraged to pass in a shared one since these are expensive objects.
138
+ * If using BYO_CRYPTO, you must provide the TLS context since it cannot be created automatically.
139
+ */
140
+ struct aws_tls_ctx *tls_ctx;
141
+
142
+ /* For mocking the http layer in tests, leave NULL otherwise */
143
+ struct aws_auth_http_system_vtable *function_table;
144
+ };
145
+
146
+ /**
147
+ * Configuration options for a provider that functions as a caching decorator. Credentials sourced through this
148
+ * provider will be cached within it until their expiration time. When the cached credentials expire, new
149
+ * credentials will be fetched when next queried.
150
+ */
151
+ struct aws_credentials_provider_cached_options {
152
+ struct aws_credentials_provider_shutdown_options shutdown_options;
153
+
154
+ /*
155
+ * The provider to cache credentials query results from
156
+ */
157
+ struct aws_credentials_provider *source;
158
+
159
+ /*
160
+ * An optional expiration time period for sourced credentials. For a given set of cached credentials,
161
+ * the refresh time period will be the minimum of this time and any expiration timestamp on the credentials
162
+ * themselves.
163
+ */
164
+ uint64_t refresh_time_in_milliseconds;
165
+
166
+ /* For mocking, leave NULL otherwise */
167
+ aws_io_clock_fn *high_res_clock_fn;
168
+ aws_io_clock_fn *system_clock_fn;
169
+ };
170
+
171
+ /**
172
+ * Configuration options for a provider that queries, in order, a list of providers. This provider uses the
173
+ * first set of credentials successfully queried. Providers are queried one at a time; a provider is not queried
174
+ * until the preceding provider has failed to source credentials.
175
+ */
176
+ struct aws_credentials_provider_chain_options {
177
+ struct aws_credentials_provider_shutdown_options shutdown_options;
178
+
179
+ /*
180
+ * Pointer to an array of credentials providers to use
181
+ */
182
+ struct aws_credentials_provider **providers;
183
+
184
+ /*
185
+ * Number of elements in the array of credentials providers
186
+ */
187
+ size_t provider_count;
188
+ };
189
+
190
+ /*
191
+ * EC2 IMDS_V1 takes one http request to get resource, while IMDS_V2 takes one more token (Http PUT) request
192
+ * to get secure token used in following request.
193
+ */
194
+ enum aws_imds_protocol_version {
195
+ /**
196
+ * Defaults to IMDS_PROTOCOL_V2. It can be set to either one and IMDS Client
197
+ * will figure out (by looking at response code) which protocol an instance
198
+ * is using. But a more clear setting will reduce unnecessary network request.
199
+ */
200
+ IMDS_PROTOCOL_V2,
201
+ IMDS_PROTOCOL_V1,
202
+ };
203
+
204
+ /**
205
+ * Configuration options for the provider that sources credentials from ec2 instance metadata
206
+ */
207
+ struct aws_credentials_provider_imds_options {
208
+ struct aws_credentials_provider_shutdown_options shutdown_options;
209
+
210
+ /*
211
+ * Connection bootstrap to use for any network connections made while sourcing credentials
212
+ */
213
+ struct aws_client_bootstrap *bootstrap;
214
+
215
+ /*
216
+ * Which version of the imds query protocol to use.
217
+ */
218
+ enum aws_imds_protocol_version imds_version;
219
+
220
+ /*
221
+ * If true, fallback from v2 to v1 will be disabled for all cases
222
+ */
223
+ bool ec2_metadata_v1_disabled;
224
+
225
+ /* For mocking the http layer in tests, leave NULL otherwise */
226
+ struct aws_auth_http_system_vtable *function_table;
227
+ };
228
+
229
+ /*
230
+ * Configuration options for the provider that sources credentials from ECS container metadata.
231
+ * The ECS creds provider can be used to access creds via either a relative URI to a fixed endpoint
232
+ * (http://169.254.170.2) or via a full URI specified by environment variables (in order of priority):
233
+ * AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
234
+ * AWS_CONTAINER_CREDENTIALS_FULL_URI
235
+ *
236
+ *`AWS_CONTAINER_CREDENTIALS_FULL_URI` URL must satisfy one of the following:
237
+ * 1. The URL begins with `https`.
238
+ * 2. The resolved IP address is within the loopback CIDR (IPv4 127.0.0.0/8, IPv6 ::1/128), ECS container address
239
+ * (169.254.170.2), or EKS Pod Identity address (169.254.170.23 or fd00:ec2::23).
240
+ *
241
+ * For the Authorization token, there are two ways (in order of priority):
242
+ * 1. AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE (an env var which contains the absolute path to the token file. The file
243
+ * will be re-read for each call to get credentials.)
244
+ * 2. AWS_CONTAINER_AUTHORIZATION_TOKEN (an env var that contains a static auth token)
245
+ */
246
+ struct aws_credentials_provider_ecs_environment_options {
247
+ struct aws_credentials_provider_shutdown_options shutdown_options;
248
+
249
+ /*
250
+ * (Required)
251
+ * Connection bootstrap to use for any network connections made while sourcing credentials
252
+ */
253
+ struct aws_client_bootstrap *bootstrap;
254
+
255
+ /*
256
+ * (Required)
257
+ * Client TLS context to use when making a query. This will only be used if the AWS_CONTAINER_CREDENTIALS_FULL_URI
258
+ * is set and starts with https
259
+ */
260
+ struct aws_tls_ctx *tls_ctx;
261
+
262
+ /* For mocking the http layer in tests, leave NULL otherwise */
263
+ struct aws_auth_http_system_vtable *function_table;
264
+ };
265
+
266
+ /*
267
+ * Configuration options for the provider that sources credentials from ECS container metadata.
268
+ * This options struct doesn't read anything from the environment and requires everything to be explicitly passed in. If
269
+ * you need to read properties from the environment, use the `aws_credentials_provider_ecs_environment_options`.
270
+ *
271
+ *`host` must satisfy one of the following:
272
+ * 1. tls_context is set
273
+ * 2. The resolved IP address is within the loopback CIDR (IPv4 127.0.0.0/8, IPv6 ::1/128), ECS container address
274
+ * (169.254.170.2), or EKS Pod Identity address (169.254.170.23 or fd00:ec2::23).
275
+ */
276
+ struct aws_credentials_provider_ecs_options {
277
+ struct aws_credentials_provider_shutdown_options shutdown_options;
278
+
279
+ /*
280
+ * Connection bootstrap to use for any network connections made while sourcing credentials
281
+ */
282
+ struct aws_client_bootstrap *bootstrap;
283
+
284
+ /*
285
+ * Host to query credentials from
286
+ */
287
+ struct aws_byte_cursor host;
288
+
289
+ /*
290
+ * Http path and query string for the credentials query
291
+ */
292
+ struct aws_byte_cursor path_and_query;
293
+
294
+ /*
295
+ * Authorization token file path to include in the credentials query. The file will be re-read for each call to
296
+ * get_credentials.
297
+ * This has higher priority than `auth_token`.
298
+ */
299
+ struct aws_byte_cursor auth_token_file_path;
300
+
301
+ /*
302
+ * Authorization token to include in the credentials query.
303
+ * No effect if `auth_token_file_path` is set.
304
+ */
305
+ struct aws_byte_cursor auth_token;
306
+
307
+ /*
308
+ * Client TLS context to use when making query.
309
+ * If set, port 443 is used. If NULL, port 80 is used.
310
+ */
311
+ struct aws_tls_ctx *tls_ctx;
312
+
313
+ /* For mocking the http layer in tests, leave NULL otherwise */
314
+ struct aws_auth_http_system_vtable *function_table;
315
+
316
+ /*
317
+ * Port to query credentials from. If zero, 80/443 will be used based on whether or not tls is enabled.
318
+ */
319
+ uint32_t port;
320
+ };
321
+
322
+ /**
323
+ * Configuration options for the X509 credentials provider
324
+ *
325
+ * The x509 credentials provider sources temporary credentials from AWS IoT Core using TLS mutual authentication.
326
+ * See details: https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html
327
+ * An end to end demo with detailed steps can be found here:
328
+ * https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/
329
+ */
330
+ struct aws_credentials_provider_x509_options {
331
+ struct aws_credentials_provider_shutdown_options shutdown_options;
332
+
333
+ /*
334
+ * Connection bootstrap to use for any network connections made while sourcing credentials
335
+ */
336
+ struct aws_client_bootstrap *bootstrap;
337
+
338
+ /* TLS connection options that have been initialized with your x509 certificate and private key */
339
+ const struct aws_tls_connection_options *tls_connection_options;
340
+
341
+ /* IoT thing name you registered with AWS IOT for your device, it will be used in http request header */
342
+ struct aws_byte_cursor thing_name;
343
+
344
+ /* Iot role alias you created with AWS IoT for your IAM role, it will be used in http request path */
345
+ struct aws_byte_cursor role_alias;
346
+
347
+ /**
348
+ * Per-account X509 credentials sourcing endpoint.
349
+ */
350
+ struct aws_byte_cursor endpoint;
351
+
352
+ /**
353
+ * (Optional) Http proxy configuration for the http request that fetches credentials
354
+ */
355
+ const struct aws_http_proxy_options *proxy_options;
356
+
357
+ /* For mocking the http layer in tests, leave NULL otherwise */
358
+ struct aws_auth_http_system_vtable *function_table;
359
+ };
360
+
361
+ /**
362
+ * Configuration options for the STS web identity provider
363
+ *
364
+ * Sts with web identity credentials provider sources a set of temporary security credentials for users who have been
365
+ * authenticated in a mobile or web application with a web identity provider.
366
+ * Example providers include Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible
367
+ * identity provider like Elastic Kubernetes Service
368
+ * https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html
369
+ * The required parameters used in the request (region, roleArn, sessionName, tokenFilePath) are automatically resolved
370
+ * by SDK from envrionment variables or config file if not set.
371
+ ---------------------------------------------------------------------------------
372
+ | Parameter | Environment Variable Name | Config File Property Name |
373
+ ----------------------------------------------------------------------------------
374
+ | region | AWS_REGION/AWS_DEFAULT_REGION| region |
375
+ | role_arn | AWS_ROLE_ARN | role_arn |
376
+ | role_session_name | AWS_ROLE_SESSION_NAME | role_session_name |
377
+ | token_file_path | AWS_WEB_IDENTITY_TOKEN_FILE | web_identity_token_file |
378
+ |--------------------------------------------------------------------------------|
379
+ * The order of resolution is the following
380
+ * 1. Parameters
381
+ * 2. Environment Variables (in case of region, the AWS_REGION is preferred over the AWS_DEFAULT_REGION)
382
+ * 3. Config File
383
+ */
384
+ struct aws_credentials_provider_sts_web_identity_options {
385
+ struct aws_credentials_provider_shutdown_options shutdown_options;
386
+
387
+ /*
388
+ * Connection bootstrap to use for any network connections made while sourcing credentials
389
+ */
390
+ struct aws_client_bootstrap *bootstrap;
391
+
392
+ /**
393
+ * (Optional)
394
+ * Use a cached config profile collection. You can also pass a merged collection.
395
+ */
396
+ struct aws_profile_collection *config_profile_collection_cached;
397
+
398
+ /*
399
+ * Client TLS context to use when querying STS web identity provider.
400
+ * Required.
401
+ */
402
+ struct aws_tls_ctx *tls_ctx;
403
+
404
+ /* For mocking the http layer in tests, leave NULL otherwise */
405
+ struct aws_auth_http_system_vtable *function_table;
406
+
407
+ /*
408
+ * (Optional)
409
+ * Override of what profile to use, if not set, 'default' will be used.
410
+ */
411
+ struct aws_byte_cursor profile_name_override;
412
+
413
+ /*
414
+ * (Optional)
415
+ * Override of region, if not set, it will be resolved from env or profile.
416
+ */
417
+ struct aws_byte_cursor region;
418
+ /*
419
+ * (Optional)
420
+ * Override of role_arn, if not set, it will be resolved from env or profile.
421
+ */
422
+ struct aws_byte_cursor role_arn;
423
+ /*
424
+ * (Optional)
425
+ * Override of role_session_name, if not set, it will be resolved from env or profile.
426
+ */
427
+ struct aws_byte_cursor role_session_name;
428
+ /*
429
+ * (Optional)
430
+ * Override of token_file_path, if not set, it will be resolved from env or profile.
431
+ */
432
+ struct aws_byte_cursor token_file_path;
433
+ };
434
+
435
+ /*
436
+ * Configuration for the SSOCredentialsProvider that sends a GetRoleCredentialsRequest to the AWS Single
437
+ * Sign-On Service to maintain short-lived sessions to use for authentication.
438
+ *
439
+ * https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html
440
+ */
441
+ struct aws_credentials_provider_sso_options {
442
+ struct aws_credentials_provider_shutdown_options shutdown_options;
443
+
444
+ /*
445
+ * Override of what profile to use to source credentials from ('default' by default)
446
+ */
447
+ struct aws_byte_cursor profile_name_override;
448
+
449
+ /*
450
+ * Override path to the profile config file (~/.aws/config by default)
451
+ */
452
+ struct aws_byte_cursor config_file_name_override;
453
+
454
+ /**
455
+ * (Optional)
456
+ * Use a cached config profile collection. You can also pass a merged collection.
457
+ * config_file_name_override will be ignored if this option is provided.
458
+ */
459
+ struct aws_profile_collection *config_file_cached;
460
+
461
+ /*
462
+ * Connection bootstrap to use for any network connections made while sourcing credentials
463
+ * Required.
464
+ */
465
+ struct aws_client_bootstrap *bootstrap;
466
+
467
+ /*
468
+ * Client TLS context to use when querying SSO provider.
469
+ * Required.
470
+ */
471
+ struct aws_tls_ctx *tls_ctx;
472
+
473
+ /* For mocking, leave NULL otherwise */
474
+ struct aws_auth_http_system_vtable *function_table;
475
+ aws_io_clock_fn *system_clock_fn;
476
+ };
477
+
478
+ /**
479
+ * Configuration options for the STS credentials provider.
480
+ * STS Credentials Provider will try to automatically resolve the region and use a regional STS endpoint if successful.
481
+ * The region resolution order is the following:
482
+ * 1. AWS_REGION environment variable
483
+ * 2. AWS_DEFAULT_REGION environment variable
484
+ * 3. The region property in the config file.
485
+ */
486
+ struct aws_credentials_provider_sts_options {
487
+ /*
488
+ * Connection bootstrap to use for any network connections made while sourcing credentials
489
+ */
490
+ struct aws_client_bootstrap *bootstrap;
491
+
492
+ /*
493
+ * Client TLS context to use when querying STS.
494
+ * Required.
495
+ */
496
+ struct aws_tls_ctx *tls_ctx;
497
+
498
+ /*
499
+ * Credentials provider to be used to sign the requests made to STS to fetch credentials.
500
+ */
501
+ struct aws_credentials_provider *creds_provider;
502
+
503
+ /*
504
+ * Arn of the role to assume by fetching credentials for
505
+ */
506
+ struct aws_byte_cursor role_arn;
507
+
508
+ /*
509
+ * Assumed role session identifier to be associated with the sourced credentials
510
+ */
511
+ struct aws_byte_cursor session_name;
512
+
513
+ /*
514
+ * (Optional) Unique identifier for assuming a role in another account
515
+ */
516
+ struct aws_byte_cursor external_id;
517
+
518
+ /*
519
+ * How long sourced credentials should remain valid for, in seconds. 900 is the minimum allowed value.
520
+ */
521
+ uint16_t duration_seconds;
522
+
523
+ /**
524
+ * (Optional) Http proxy configuration for the AssumeRole http request that fetches credentials
525
+ */
526
+ const struct aws_http_proxy_options *http_proxy_options;
527
+
528
+ /**
529
+ * (Optional)
530
+ * Uses a cached config file profile collection (~/.aws/config). You can also pass a merged profile collection,
531
+ * which contains both a config file and a credentials file.
532
+ * If provided, config_file_name_override is ignored.
533
+ */
534
+ struct aws_profile_collection *profile_collection_cached;
535
+
536
+ /*
537
+ * (Optional)
538
+ * Override of what profile to use; if not set, 'default' will be used.
539
+ */
540
+ struct aws_byte_cursor profile_name_override;
541
+
542
+ /*
543
+ * (Optional)
544
+ * Override path to the profile config file (~/.aws/config by default).
545
+ */
546
+ struct aws_byte_cursor config_file_name_override;
547
+
548
+ struct aws_credentials_provider_shutdown_options shutdown_options;
549
+
550
+ /* For mocking, leave NULL otherwise */
551
+ struct aws_auth_http_system_vtable *function_table;
552
+ aws_io_clock_fn *system_clock_fn;
553
+ };
554
+
555
+ /**
556
+ *
557
+ * Configuration options for the process credentials provider
558
+ *
559
+ * The process credentials provider sources credentials from running a command or process.
560
+ * The command to run is sourced from a profile in the AWS config file, using the standard
561
+ * profile selection rules. The profile key the command is read from is "credential_process."
562
+ * E.g.:
563
+ * [default]
564
+ * credential_process=/opt/amazon/bin/my-credential-fetcher --argsA=abc
565
+ * On successfully running the command, the output should be a json data with the following
566
+ * format:
567
+ * {
568
+ "Version": 1,
569
+ "AccessKeyId": "accesskey",
570
+ "SecretAccessKey": "secretAccessKey"
571
+ "SessionToken": "....",
572
+ "Expiration": "2019-05-29T00:21:43Z"
573
+ }
574
+ * Version here identifies the command output format version.
575
+ */
576
+ struct aws_credentials_provider_process_options {
577
+ struct aws_credentials_provider_shutdown_options shutdown_options;
578
+ /**
579
+ * In which profile name to look for credential_process,
580
+ * if not provided, we will try environment variable: AWS_PROFILE.
581
+ */
582
+ struct aws_byte_cursor profile_to_use;
583
+
584
+ /**
585
+ * (Optional)
586
+ * Use a cached config profile collection. You can also pass a merged collection.
587
+ */
588
+ struct aws_profile_collection *config_profile_collection_cached;
589
+ };
590
+
591
+ /**
592
+ * Configuration options for the default credentials provider chain.
593
+ */
594
+ struct aws_credentials_provider_chain_default_options {
595
+ struct aws_credentials_provider_shutdown_options shutdown_options;
596
+
597
+ /*
598
+ * Connection bootstrap to use for any network connections made while sourcing credentials
599
+ */
600
+ struct aws_client_bootstrap *bootstrap;
601
+
602
+ /*
603
+ * Client TLS context to use for any secure network connections made while sourcing credentials.
604
+ *
605
+ * If not provided the default chain will construct a new one, but these
606
+ * are expensive objects so you are encouraged to pass in a shared one.
607
+ *
608
+ * Must be provided if using BYO_CRYPTO.
609
+ */
610
+ struct aws_tls_ctx *tls_ctx;
611
+
612
+ /**
613
+ * (Optional)
614
+ * Use a cached merged profile collection. A merge collection has both config file
615
+ * (~/.aws/config) and credentials file based profile collection (~/.aws/credentials) using
616
+ * `aws_profile_collection_new_from_merge`.
617
+ */
618
+ struct aws_profile_collection *profile_collection_cached;
619
+
620
+ /*
621
+ * (Optional)
622
+ * Override of what profile to use, if not set, 'default' will be used.
623
+ */
624
+ struct aws_byte_cursor profile_name_override;
625
+
626
+ /*
627
+ * (Optional)
628
+ * If enabled, the Environment Credentials Provider is not added to the chain.
629
+ */
630
+ bool skip_environment_credentials_provider;
631
+ };
632
+
633
+ typedef int(aws_credentials_provider_delegate_get_credentials_fn)(
634
+ void *delegate_user_data,
635
+ aws_on_get_credentials_callback_fn callback,
636
+ void *callback_user_data);
637
+
638
+ /**
639
+ * Configuration options for the delegate credentials provider.
640
+ */
641
+ struct aws_credentials_provider_delegate_options {
642
+ struct aws_credentials_provider_shutdown_options shutdown_options;
643
+
644
+ /**
645
+ * Delegated get_credentials() callback.
646
+ */
647
+ aws_credentials_provider_delegate_get_credentials_fn *get_credentials;
648
+
649
+ /**
650
+ * User data for delegated callbacks.
651
+ */
652
+ void *delegate_user_data;
653
+ };
654
+
655
+ /**
656
+ * A (string) pair defining an identity provider and a valid login token sourced from it.
657
+ */
658
+ struct aws_cognito_identity_provider_token_pair {
659
+
660
+ /**
661
+ * Name of an identity provider
662
+ */
663
+ struct aws_byte_cursor identity_provider_name;
664
+
665
+ /**
666
+ * Valid login token source from the identity provider
667
+ */
668
+ struct aws_byte_cursor identity_provider_token;
669
+ };
670
+
671
+ typedef void(aws_credentials_provider_cognito_get_token_pairs_completion_fn)(
672
+ struct aws_cognito_identity_provider_token_pair *logins,
673
+ size_t login_count,
674
+ int error_code,
675
+ void *completion_user_data);
676
+
677
+ typedef int(aws_credentials_provider_cognito_get_token_pairs_async_fn)(
678
+ void *get_token_pairs_user_data,
679
+ aws_credentials_provider_cognito_get_token_pairs_completion_fn *completion_callback,
680
+ void *completion_user_data);
681
+
682
+ /**
683
+ * Configuration options needed to create a Cognito-based Credentials Provider
684
+ */
685
+ struct aws_credentials_provider_cognito_options {
686
+ struct aws_credentials_provider_shutdown_options shutdown_options;
687
+
688
+ /**
689
+ * Cognito service regional endpoint to source credentials from.
690
+ */
691
+ struct aws_byte_cursor endpoint;
692
+
693
+ /**
694
+ * Cognito identity to fetch credentials relative to.
695
+ */
696
+ struct aws_byte_cursor identity;
697
+
698
+ /**
699
+ * Optional set of identity provider token pairs to allow for authenticated identity access.
700
+ */
701
+ struct aws_cognito_identity_provider_token_pair *logins;
702
+ size_t login_count;
703
+
704
+ /**
705
+ * Optional ARN of the role to be assumed when multiple roles were received in the token from the identity provider.
706
+ */
707
+ struct aws_byte_cursor *custom_role_arn;
708
+
709
+ /**
710
+ * Connection bootstrap to use for network connections made while sourcing credentials
711
+ */
712
+ struct aws_client_bootstrap *bootstrap;
713
+
714
+ /**
715
+ * Client TLS context to use when querying cognito credentials.
716
+ * Required.
717
+ */
718
+ struct aws_tls_ctx *tls_ctx;
719
+
720
+ /**
721
+ * (Optional) Http proxy configuration for the http request that fetches credentials
722
+ */
723
+ const struct aws_http_proxy_options *http_proxy_options;
724
+
725
+ /* For mocking the http layer in tests, leave NULL otherwise */
726
+ struct aws_auth_http_system_vtable *function_table;
727
+
728
+ /**
729
+ * Optional async function to allow for dynamic augmentation of the token pair set on a per-request basis.
730
+ */
731
+ aws_credentials_provider_cognito_get_token_pairs_async_fn *get_token_pairs;
732
+
733
+ /**
734
+ * User data that should be passed in to the get_token_pairs function as the first parameter. In practice, this
735
+ * will be a reference to a CRT binding object.
736
+ */
737
+ void *get_token_pairs_user_data;
738
+ };
739
+
740
+ /**
741
+ * Configuration options for `aws_credentials_new_with_options`
742
+ */
743
+ struct aws_credentials_options {
744
+
745
+ /* Value for the aws access key id field */
746
+ struct aws_byte_cursor access_key_id_cursor;
747
+ /* Value for the secret access key field */
748
+ struct aws_byte_cursor secret_access_key_cursor;
749
+ /* (Optional) security token associated with the credentials */
750
+ struct aws_byte_cursor session_token_cursor;
751
+ /* (Optional) account id associated with the credentials */
752
+ struct aws_byte_cursor account_id_cursor;
753
+ /* Time point, in seconds since epoch, that the credentials will no longer be valid.
754
+ * For credentials that do not expire, use UINT64_MAX. */
755
+ uint64_t expiration_timepoint_seconds;
756
+ };
757
+
758
+ AWS_EXTERN_C_BEGIN
759
+
760
+ /*
761
+ * Credentials APIs
762
+ *
763
+ * expiration_timepoint_seconds is the timepoint, in seconds since epoch, that the credentials will no longer
764
+ * be valid. For credentials that do not expire, use UINT64_MAX.
765
+ */
766
+
767
+ /**
768
+ * Creates a new set of aws credentials
769
+ *
770
+ * @param allocator memory allocator to use
771
+ * @param access_key_id_cursor value for the aws access key id field
772
+ * @param secret_access_key_cursor value for the secret access key field
773
+ * @param session_token_cursor (optional) security token associated with the credentials
774
+ * @param expiration_timepoint_seconds timepoint, in seconds since epoch, that the credentials will no longer
775
+ * be valid past. For credentials that do not expire, use UINT64_MAX
776
+ *
777
+ * @return a valid credentials object, or NULL
778
+ */
779
+ AWS_AUTH_API
780
+ struct aws_credentials *aws_credentials_new(
781
+ struct aws_allocator *allocator,
782
+ struct aws_byte_cursor access_key_id_cursor,
783
+ struct aws_byte_cursor secret_access_key_cursor,
784
+ struct aws_byte_cursor session_token_cursor,
785
+ uint64_t expiration_timepoint_seconds);
786
+
787
+ /**
788
+ * Creates a new set of aws credentials with account_id
789
+ *
790
+ * @param allocator memory allocator to use
791
+ * @param access_key_id_cursor value for the aws access key id field
792
+ * @param secret_access_key_cursor value for the secret access key field
793
+ * @param session_token_cursor (optional) security token associated with the credentials
794
+ * @param account_id (optional) value for the account_id field
795
+ * @param expiration_timepoint_seconds timepoint, in seconds since epoch, that the credentials will no longer
796
+ * be valid past. For credentials that do not expire, use UINT64_MAX
797
+ *
798
+ * @return a valid credentials object, or NULL
799
+ */
800
+ AWS_AUTH_API
801
+ struct aws_credentials *aws_credentials_new_with_options(
802
+ struct aws_allocator *allocator,
803
+ const struct aws_credentials_options *options);
804
+
805
+ /**
806
+ * Creates a new set of aws anonymous credentials.
807
+ * Use Anonymous credentials, when you want to skip the signing process.
808
+ *
809
+ * @param allocator memory allocator to use
810
+ *
811
+ * @return a valid credentials object, or NULL
812
+ */
813
+ AWS_AUTH_API
814
+ struct aws_credentials *aws_credentials_new_anonymous(struct aws_allocator *allocator);
815
+
816
+ /**
817
+ * Creates a new set of AWS credentials
818
+ *
819
+ * @param allocator memory allocator to use
820
+ * @param access_key_id value for the aws access key id field
821
+ * @param secret_access_key value for the secret access key field
822
+ * @param session_token (optional) security token associated with the credentials
823
+ * @param expiration_timepoint_seconds timepoint, in seconds since epoch, that the credentials will no longer
824
+ * be valid past. For credentials that do not expire, use UINT64_MAX
825
+ *
826
+ * @return a valid credentials object, or NULL
827
+ */
828
+ AWS_AUTH_API
829
+ struct aws_credentials *aws_credentials_new_from_string(
830
+ struct aws_allocator *allocator,
831
+ const struct aws_string *access_key_id,
832
+ const struct aws_string *secret_access_key,
833
+ const struct aws_string *session_token,
834
+ uint64_t expiration_timepoint_seconds);
835
+
836
+ /**
837
+ * Creates a set of AWS credentials that includes an ECC key pair. These credentials do not have a value for
838
+ * the secret access key; the ecc key takes over that field's role in sigv4a signing.
839
+ *
840
+ * @param allocator memory allocator to use for all memory allocation
841
+ * @param access_key_id access key id for the credential set
842
+ * @param ecc_key ecc key to use during signing when using these credentials
843
+ * @param session_token (optional) session token associated with the credentials
844
+ * @param expiration_timepoint_in_seconds (optional) if session-based, time at which these credentials expire
845
+ * @return a new pair of AWS credentials, or NULL
846
+ */
847
+ AWS_AUTH_API
848
+ struct aws_credentials *aws_credentials_new_ecc(
849
+ struct aws_allocator *allocator,
850
+ struct aws_byte_cursor access_key_id,
851
+ struct aws_ecc_key_pair *ecc_key,
852
+ struct aws_byte_cursor session_token,
853
+ uint64_t expiration_timepoint_in_seconds);
854
+
855
+ /*
856
+ * Takes a pair of AWS credentials and performs the sigv4a key expansion algorithm to generate a unique
857
+ * ecc P256 key pair based on the credentials. The ecc key is written to the buffer in DER format.
858
+ *
859
+ * Sigv4a signing takes the raw DER-encoded ecc key as an optional parameter in signing (if not present,
860
+ * key expansion will be done for the caller before signing).
861
+ */
862
+ AWS_AUTH_API
863
+ struct aws_credentials *aws_credentials_new_ecc_from_aws_credentials(
864
+ struct aws_allocator *allocator,
865
+ const struct aws_credentials *credentials);
866
+
867
+ /**
868
+ * Add a reference to some credentials
869
+ *
870
+ * @param credentials credentials to increment the ref count on
871
+ */
872
+ AWS_AUTH_API
873
+ void aws_credentials_acquire(const struct aws_credentials *credentials);
874
+
875
+ /**
876
+ * Remove a reference to some credentials
877
+ *
878
+ * @param credentials credentials to decrement the ref count on
879
+ */
880
+ AWS_AUTH_API
881
+ void aws_credentials_release(const struct aws_credentials *credentials);
882
+
883
+ /**
884
+ * Get the AWS access key id from a set of credentials
885
+ *
886
+ * @param credentials credentials to get the access key id from
887
+ * @return a byte cursor to the access key id
888
+ */
889
+ AWS_AUTH_API
890
+ struct aws_byte_cursor aws_credentials_get_access_key_id(const struct aws_credentials *credentials);
891
+
892
+ /**
893
+ * Get the AWS secret access key from a set of credentials
894
+ *
895
+ * @param credentials credentials to get the secret access key from
896
+ * @return a byte cursor to the secret access key
897
+ */
898
+ AWS_AUTH_API
899
+ struct aws_byte_cursor aws_credentials_get_secret_access_key(const struct aws_credentials *credentials);
900
+
901
+ /**
902
+ * Get the AWS session token from a set of credentials
903
+ *
904
+ * @param credentials credentials to get the session token from
905
+ * @return a byte cursor to the session token or an empty byte cursor if there is no session token
906
+ */
907
+ AWS_AUTH_API
908
+ struct aws_byte_cursor aws_credentials_get_session_token(const struct aws_credentials *credentials);
909
+
910
+ /**
911
+ * Get the AWS account id from a set of credentials
912
+ *
913
+ * @param credentials to get the account id from
914
+ * @return a byte cursor to the account id or an empty byte cursor if there is no account id
915
+ */
916
+ AWS_AUTH_API
917
+ struct aws_byte_cursor aws_credentials_get_account_id(const struct aws_credentials *credentials);
918
+
919
+ /**
920
+ * Get the expiration timepoint (in seconds since epoch) associated with a set of credentials
921
+ *
922
+ * @param credentials credentials to get the expiration timepoint for
923
+ * @return the time, in seconds since epoch, the credentials will expire; UINT64_MAX for credentials
924
+ * without a specific expiration time
925
+ */
926
+ AWS_AUTH_API
927
+ uint64_t aws_credentials_get_expiration_timepoint_seconds(const struct aws_credentials *credentials);
928
+
929
+ /**
930
+ * Get the elliptic curve key associated with this set of credentials
931
+ * @param credentials credentials to get the the elliptic curve key for
932
+ * @return the elliptic curve key associated with the credentials, or NULL if no key is associated with
933
+ * these credentials
934
+ */
935
+ AWS_AUTH_API
936
+ struct aws_ecc_key_pair *aws_credentials_get_ecc_key_pair(const struct aws_credentials *credentials);
937
+
938
+ /**
939
+ * If credentials are anonymous, then the signing process is skipped.
940
+ *
941
+ * @param credentials credentials to check
942
+ *
943
+ * @return true if the credentials are anonymous; false otherwise.
944
+ */
945
+ AWS_AUTH_API
946
+ bool aws_credentials_is_anonymous(const struct aws_credentials *credentials);
947
+
948
+ /**
949
+ * Derives an ecc key pair (based on the nist P256 curve) from the access key id and secret access key components
950
+ * of a set of AWS credentials using an internal key derivation specification. Used to perform sigv4a signing in
951
+ * the hybrid mode based on AWS credentials.
952
+ *
953
+ * @param allocator memory allocator to use for all memory allocation
954
+ * @param credentials AWS credentials to derive the ECC key from using the AWS sigv4a key derivation specification
955
+ * @return a new ecc key pair or NULL on failure
956
+ */
957
+ AWS_AUTH_API
958
+ struct aws_ecc_key_pair *aws_ecc_key_pair_new_ecdsa_p256_key_from_aws_credentials(
959
+ struct aws_allocator *allocator,
960
+ const struct aws_credentials *credentials);
961
+
962
+ /*
963
+ * Credentials provider APIs
964
+ */
965
+
966
+ /**
967
+ * Release a reference to a credentials provider
968
+ *
969
+ * @param provider provider to decrement the ref count on
970
+ */
971
+ AWS_AUTH_API
972
+ struct aws_credentials_provider *aws_credentials_provider_release(struct aws_credentials_provider *provider);
973
+
974
+ /*
975
+ * Add a reference to a credentials provider
976
+ *
977
+ * @param provider provider to increment the ref count on
978
+ */
979
+ AWS_AUTH_API
980
+ struct aws_credentials_provider *aws_credentials_provider_acquire(struct aws_credentials_provider *provider);
981
+
982
+ /*
983
+ * Async function for retrieving credentials from a provider
984
+ *
985
+ * @param provider credentials provider to source from
986
+ * @param callback completion callback to invoke when the fetch has completed or failed
987
+ * @param user_data user data to pass to the completion callback
988
+ *
989
+ * @return AWS_OP_SUCCESS if the fetch was successfully started, AWS_OP_ERR otherwise. The completion
990
+ * callback will only be invoked if-and-only-if the return value was AWS_OP_SUCCESS.
991
+ *
992
+ */
993
+ AWS_AUTH_API
994
+ int aws_credentials_provider_get_credentials(
995
+ struct aws_credentials_provider *provider,
996
+ aws_on_get_credentials_callback_fn callback,
997
+ void *user_data);
998
+
999
+ /*
1000
+ * Credentials provider variant creation
1001
+ */
1002
+
1003
+ /**
1004
+ * Creates a simple provider that just returns a fixed set of credentials
1005
+ *
1006
+ * @param allocator memory allocator to use for all memory allocation
1007
+ * @param options provider-specific configuration options
1008
+ *
1009
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1010
+ */
1011
+ AWS_AUTH_API
1012
+ struct aws_credentials_provider *aws_credentials_provider_new_static(
1013
+ struct aws_allocator *allocator,
1014
+ const struct aws_credentials_provider_static_options *options);
1015
+
1016
+ /**
1017
+ * Creates a simple anonymous credentials provider
1018
+ *
1019
+ * @param allocator memory allocator to use for all memory allocation
1020
+ * @param shutdown_options an optional shutdown callback that gets
1021
+ * invoked when the resources used by the provider are no longer in use.
1022
+ *
1023
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1024
+ */
1025
+ AWS_AUTH_API
1026
+ struct aws_credentials_provider *aws_credentials_provider_new_anonymous(
1027
+ struct aws_allocator *allocator,
1028
+ const struct aws_credentials_provider_shutdown_options *shutdown_options);
1029
+
1030
+ /**
1031
+ * Creates a provider that returns credentials sourced from the environment variables:
1032
+ *
1033
+ * AWS_ACCESS_KEY_ID
1034
+ * AWS_SECRET_ACCESS_KEY
1035
+ * AWS_SESSION_TOKEN
1036
+ *
1037
+ * @param allocator memory allocator to use for all memory allocation
1038
+ * @param options provider-specific configuration options
1039
+ *
1040
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1041
+ */
1042
+ AWS_AUTH_API
1043
+ struct aws_credentials_provider *aws_credentials_provider_new_environment(
1044
+ struct aws_allocator *allocator,
1045
+ const struct aws_credentials_provider_environment_options *options);
1046
+
1047
+ /**
1048
+ * Creates a provider that functions as a caching decorating of another provider.
1049
+ *
1050
+ * For example, the default chain is implemented as:
1051
+ *
1052
+ * CachedProvider -> ProviderChain(EnvironmentProvider -> ProfileProvider -> ECS/EC2IMD etc...)
1053
+ *
1054
+ * A reference is taken on the target provider
1055
+ *
1056
+ * @param allocator memory allocator to use for all memory allocation
1057
+ * @param options provider-specific configuration options
1058
+ *
1059
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1060
+ */
1061
+ AWS_AUTH_API
1062
+ struct aws_credentials_provider *aws_credentials_provider_new_cached(
1063
+ struct aws_allocator *allocator,
1064
+ const struct aws_credentials_provider_cached_options *options);
1065
+
1066
+ /**
1067
+ * Creates a provider that sources credentials from key-value profiles loaded from the aws credentials
1068
+ * file ("~/.aws/credentials" by default) and the aws config file ("~/.aws/config" by
1069
+ * default)
1070
+ *
1071
+ * @param allocator memory allocator to use for all memory allocation
1072
+ * @param options provider-specific configuration options
1073
+ *
1074
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1075
+ */
1076
+ AWS_AUTH_API
1077
+ struct aws_credentials_provider *aws_credentials_provider_new_profile(
1078
+ struct aws_allocator *allocator,
1079
+ const struct aws_credentials_provider_profile_options *options);
1080
+
1081
+ /**
1082
+ * Creates a provider that assumes an IAM role via. STS AssumeRole() API. This provider will fetch new credentials
1083
+ * upon each call to aws_credentials_provider_get_credentials().
1084
+ *
1085
+ * @param allocator memory allocator to use for all memory allocation
1086
+ * @param options provider-specific configuration options
1087
+ *
1088
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1089
+ */
1090
+ AWS_AUTH_API
1091
+ struct aws_credentials_provider *aws_credentials_provider_new_sts(
1092
+ struct aws_allocator *allocator,
1093
+ const struct aws_credentials_provider_sts_options *options);
1094
+
1095
+ /**
1096
+ * Creates a provider that sources credentials from an ordered sequence of providers, with the overall result
1097
+ * being from the first provider to return a valid set of credentials
1098
+ *
1099
+ * References are taken on all supplied providers
1100
+ *
1101
+ * @param allocator memory allocator to use for all memory allocation
1102
+ * @param options provider-specific configuration options
1103
+ *
1104
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1105
+ */
1106
+ AWS_AUTH_API
1107
+ struct aws_credentials_provider *aws_credentials_provider_new_chain(
1108
+ struct aws_allocator *allocator,
1109
+ const struct aws_credentials_provider_chain_options *options);
1110
+
1111
+ /**
1112
+ * Creates a provider that sources credentials from the ec2 instance metadata service
1113
+ *
1114
+ * @param allocator memory allocator to use for all memory allocation
1115
+ * @param options provider-specific configuration options
1116
+ *
1117
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1118
+ */
1119
+ AWS_AUTH_API
1120
+ struct aws_credentials_provider *aws_credentials_provider_new_imds(
1121
+ struct aws_allocator *allocator,
1122
+ const struct aws_credentials_provider_imds_options *options);
1123
+
1124
+ /**
1125
+ * Creates a provider that sources credentials from the ecs role credentials service and reads the required params from
1126
+ * environment variables
1127
+ *
1128
+ * @param allocator memory allocator to use for all memory allocation
1129
+ * @param options provider-specific configuration options
1130
+ *
1131
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1132
+ */
1133
+ AWS_AUTH_API
1134
+ struct aws_credentials_provider *aws_credentials_provider_new_ecs_from_environment(
1135
+ struct aws_allocator *allocator,
1136
+ const struct aws_credentials_provider_ecs_environment_options *options);
1137
+
1138
+ /**
1139
+ * Creates a provider that sources credentials from the ecs role credentials service
1140
+ * This function doesn't read anything from the environment and requires everything to be explicitly passed in.
1141
+ * If you need to read properties from the environment, use the `aws_credentials_provider_new_ecs_from_environment`.
1142
+ *
1143
+ * @param allocator memory allocator to use for all memory allocation
1144
+ * @param options provider-specific configuration options
1145
+ *
1146
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1147
+ */
1148
+ AWS_AUTH_API
1149
+ struct aws_credentials_provider *aws_credentials_provider_new_ecs(
1150
+ struct aws_allocator *allocator,
1151
+ const struct aws_credentials_provider_ecs_options *options);
1152
+
1153
+ /**
1154
+ * Creates a provider that sources credentials from IoT Core
1155
+ *
1156
+ * @param allocator memory allocator to use for all memory allocation
1157
+ * @param options provider-specific configuration options
1158
+ *
1159
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1160
+ */
1161
+ AWS_AUTH_API
1162
+ struct aws_credentials_provider *aws_credentials_provider_new_x509(
1163
+ struct aws_allocator *allocator,
1164
+ const struct aws_credentials_provider_x509_options *options);
1165
+
1166
+ /**
1167
+ * Creates a provider that sources credentials from STS using AssumeRoleWithWebIdentity
1168
+ *
1169
+ * @param allocator memory allocator to use for all memory allocation
1170
+ * @param options provider-specific configuration options
1171
+ *
1172
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1173
+ */
1174
+ AWS_AUTH_API
1175
+ struct aws_credentials_provider *aws_credentials_provider_new_sts_web_identity(
1176
+ struct aws_allocator *allocator,
1177
+ const struct aws_credentials_provider_sts_web_identity_options *options);
1178
+
1179
+ /**
1180
+ * Creates a provider that sources credentials from SSO using a SSOToken.
1181
+ *
1182
+ * @param allocator memory allocator to use for all memory allocation
1183
+ * @param options provider-specific configuration options
1184
+ *
1185
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1186
+ */
1187
+ AWS_AUTH_API
1188
+ struct aws_credentials_provider *aws_credentials_provider_new_sso(
1189
+ struct aws_allocator *allocator,
1190
+ const struct aws_credentials_provider_sso_options *options);
1191
+
1192
+ /*
1193
+ * Creates a provider that sources credentials from running an external command or process
1194
+ *
1195
+ * @param allocator memory allocator to use for all memory allocation
1196
+ * @param options provider-specific configuration options
1197
+ *
1198
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1199
+ */
1200
+ AWS_AUTH_API
1201
+ struct aws_credentials_provider *aws_credentials_provider_new_process(
1202
+ struct aws_allocator *allocator,
1203
+ const struct aws_credentials_provider_process_options *options);
1204
+
1205
+ /**
1206
+ * Create a credentials provider depends on provided vtable to fetch the credentials.
1207
+ *
1208
+ * @param allocator memory allocator to use for all memory allocation
1209
+ * @param options provider-specific configuration options
1210
+ *
1211
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1212
+ */
1213
+ AWS_AUTH_API
1214
+ struct aws_credentials_provider *aws_credentials_provider_new_delegate(
1215
+ struct aws_allocator *allocator,
1216
+ const struct aws_credentials_provider_delegate_options *options);
1217
+
1218
+ /**
1219
+ * Creates a provider that sources credentials from the Cognito-Identity service via an
1220
+ * invocation of the GetCredentialsForIdentity API call.
1221
+ *
1222
+ * @param allocator memory allocator to use for all memory allocation
1223
+ * @param options provider-specific configuration options
1224
+ *
1225
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1226
+ */
1227
+ AWS_AUTH_API
1228
+ struct aws_credentials_provider *aws_credentials_provider_new_cognito(
1229
+ struct aws_allocator *allocator,
1230
+ const struct aws_credentials_provider_cognito_options *options);
1231
+
1232
+ /**
1233
+ * Creates a cognito-based provider that has a caching layer wrapped around it
1234
+ *
1235
+ * @param allocator memory allocator to use for all memory allocation
1236
+ * @param options cognito-specific configuration options
1237
+ *
1238
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1239
+ */
1240
+ AWS_AUTH_API
1241
+ struct aws_credentials_provider *aws_credentials_provider_new_cognito_caching(
1242
+ struct aws_allocator *allocator,
1243
+ const struct aws_credentials_provider_cognito_options *options);
1244
+
1245
+ /**
1246
+ * Creates the default provider chain used by most AWS SDKs.
1247
+ *
1248
+ * Generally:
1249
+ *
1250
+ * (1) Environment
1251
+ * (2) Profile
1252
+ * - STSCredentialsProvider
1253
+ * - ProcessCredentialsProvider
1254
+ * - ProfileCredentialsProvider
1255
+ * (3) STS web identity
1256
+ * (4) (conditional, off by default) ECS
1257
+ * (5) (conditional, on by default) EC2 Instance Metadata
1258
+ *
1259
+ * Support for environmental control of the default provider chain is not yet
1260
+ * implemented.
1261
+ *
1262
+ * @param allocator memory allocator to use for all memory allocation
1263
+ * @param options provider-specific configuration options
1264
+ *
1265
+ * @return the newly-constructed credentials provider, or NULL if an error occurred.
1266
+ */
1267
+ AWS_AUTH_API
1268
+ struct aws_credentials_provider *aws_credentials_provider_new_chain_default(
1269
+ struct aws_allocator *allocator,
1270
+ const struct aws_credentials_provider_chain_default_options *options);
1271
+
1272
+ AWS_AUTH_API extern const struct aws_auth_http_system_vtable *g_aws_credentials_provider_http_function_table;
1273
+
1274
+ AWS_EXTERN_C_END
1275
+ AWS_POP_SANE_WARNING_LEVEL
1276
+
1277
+ #endif /* AWS_AUTH_CREDENTIALS_H */
include/aws/auth/exports.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_EXPORTS_H
2
+ #define AWS_AUTH_EXPORTS_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #if defined(USE_WINDOWS_DLL_SEMANTICS) || defined(WIN32)
10
+ # ifdef AWS_AUTH_USE_IMPORT_EXPORT
11
+ # ifdef AWS_AUTH_EXPORTS
12
+ # define AWS_AUTH_API __declspec(dllexport)
13
+ # else
14
+ # define AWS_AUTH_API __declspec(dllimport)
15
+ # endif /* AWS_AUTH_EXPORTS */
16
+ # else
17
+ # define AWS_AUTH_API
18
+ # endif /*USE_IMPORT_EXPORT */
19
+
20
+ #else
21
+ # if ((__GNUC__ >= 4) || defined(__clang__)) && defined(AWS_AUTH_USE_IMPORT_EXPORT) && defined(AWS_AUTH_EXPORTS)
22
+ # define AWS_AUTH_API __attribute__((visibility("default")))
23
+ # else
24
+ # define AWS_AUTH_API
25
+ # endif /* __GNUC__ >= 4 || defined(__clang__) */
26
+
27
+ #endif /* defined(USE_WINDOWS_DLL_SEMANTICS) || defined(WIN32) */
28
+
29
+ #endif /* AWS_AUTH_EXPORTS_H */
include/aws/auth/signable.h ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_SIGNABLE_H
2
+ #define AWS_AUTH_SIGNABLE_H
3
+
4
+ #include <aws/auth/auth.h>
5
+
6
+ AWS_PUSH_SANE_WARNING_LEVEL
7
+
8
+ struct aws_http_message;
9
+ struct aws_http_headers;
10
+ struct aws_input_stream;
11
+ struct aws_signable;
12
+ struct aws_string;
13
+
14
+ /*
15
+ * While not referenced directly in this file, this is the structure expected to be in the property lists
16
+ */
17
+ struct aws_signable_property_list_pair {
18
+ struct aws_byte_cursor name;
19
+ struct aws_byte_cursor value;
20
+ };
21
+
22
+ typedef int(aws_signable_get_property_fn)(
23
+ const struct aws_signable *signable,
24
+ const struct aws_string *name,
25
+ struct aws_byte_cursor *out_value);
26
+
27
+ typedef int(aws_signable_get_property_list_fn)(
28
+ const struct aws_signable *signable,
29
+ const struct aws_string *name,
30
+ struct aws_array_list **out_list);
31
+
32
+ typedef int(aws_signable_get_payload_stream_fn)(
33
+ const struct aws_signable *signable,
34
+ struct aws_input_stream **out_input_stream);
35
+
36
+ typedef void(aws_signable_destroy_fn)(struct aws_signable *signable);
37
+
38
+ struct aws_signable_vtable {
39
+ aws_signable_get_property_fn *get_property;
40
+ aws_signable_get_property_list_fn *get_property_list;
41
+ aws_signable_get_payload_stream_fn *get_payload_stream;
42
+ aws_signable_destroy_fn *destroy;
43
+ };
44
+
45
+ /**
46
+ * Signable is a generic interface for any kind of object that can be cryptographically signed.
47
+ *
48
+ * Like signing_result, the signable interface presents
49
+ *
50
+ * (1) Properties - A set of key-value pairs
51
+ * (2) Property Lists - A set of named key-value pair lists
52
+ *
53
+ * as well as
54
+ *
55
+ * (3) A message payload modeled as a stream
56
+ *
57
+ * When creating a signable "subclass" the query interface should map to retrieving
58
+ * the properties of the underlying object needed by signing algorithms that can operate on it.
59
+ *
60
+ * As an example, if a signable implementation wrapped an http request, you would query
61
+ * request elements like method and uri from the property interface, headers would be queried
62
+ * via the property list interface, and the request body would map to the payload stream.
63
+ *
64
+ * String constants that map to agreed on keys for particular signable types
65
+ * ("METHOD", "URI", "HEADERS", etc...) are exposed in appropriate header files.
66
+ */
67
+ struct aws_signable {
68
+ struct aws_allocator *allocator;
69
+ void *impl;
70
+ struct aws_signable_vtable *vtable;
71
+ };
72
+
73
+ AWS_EXTERN_C_BEGIN
74
+
75
+ /**
76
+ * Cleans up and frees all resources associated with a signable instance
77
+ *
78
+ * @param signable signable object to destroy
79
+ */
80
+ AWS_AUTH_API
81
+ void aws_signable_destroy(struct aws_signable *signable);
82
+
83
+ /**
84
+ * Retrieves a property (key-value pair) from a signable. Global property name constants are
85
+ * included below.
86
+ *
87
+ * @param signable signable object to retrieve a property from
88
+ * @param name name of the property to query
89
+ * @param out_value output parameter for the property's value
90
+ *
91
+ * @return AWS_OP_SUCCESS if the property was successfully fetched, AWS_OP_ERR otherwise
92
+ */
93
+ AWS_AUTH_API
94
+ int aws_signable_get_property(
95
+ const struct aws_signable *signable,
96
+ const struct aws_string *name,
97
+ struct aws_byte_cursor *out_value);
98
+
99
+ /**
100
+ * Retrieves a named property list (list of key-value pairs) from a signable. Global property list name
101
+ * constants are included below.
102
+ *
103
+ * @param signable signable object to retrieve a property list from
104
+ * @param name name of the property list to fetch
105
+ * @param out_property_list output parameter for the fetched property list
106
+ *
107
+ * @return AWS_OP_SUCCESS if the property list was successfully fetched, AWS_OP_ERR otherwise
108
+ */
109
+ AWS_AUTH_API
110
+ int aws_signable_get_property_list(
111
+ const struct aws_signable *signable,
112
+ const struct aws_string *name,
113
+ struct aws_array_list **out_property_list);
114
+
115
+ /**
116
+ * Retrieves the signable's message payload as a stream.
117
+ *
118
+ * @param signable signable to get the payload of
119
+ * @param out_input_stream output parameter for the payload stream
120
+ *
121
+ * @return AWS_OP_SUCCESS if successful, AWS_OP_ERR otherwise
122
+ */
123
+ AWS_AUTH_API
124
+ int aws_signable_get_payload_stream(const struct aws_signable *signable, struct aws_input_stream **out_input_stream);
125
+
126
+ /*
127
+ * Some global property and property-list name constants
128
+ */
129
+
130
+ /**
131
+ * Name of the property list that wraps the headers of an http request
132
+ */
133
+ AWS_AUTH_API extern const struct aws_string *g_aws_http_headers_property_list_name;
134
+
135
+ /**
136
+ * Name of the property list that wraps the query params of an http request. Only used by signing_result.
137
+ * For input to a http signing algorithm, query params are assumed to be part of the uri.
138
+ */
139
+ AWS_AUTH_API extern const struct aws_string *g_aws_http_query_params_property_list_name;
140
+
141
+ /**
142
+ * Name of the property that holds the method of an http request
143
+ */
144
+ AWS_AUTH_API extern const struct aws_string *g_aws_http_method_property_name;
145
+
146
+ /**
147
+ * Name of the property that holds the URI of an http request
148
+ */
149
+ AWS_AUTH_API extern const struct aws_string *g_aws_http_uri_property_name;
150
+
151
+ /**
152
+ * Name of the property that holds the signature value. This is always added to signing results.
153
+ * Depending on the requested signature type, the signature may be padded or encoded differently:
154
+ * (1) Header - hex encoding of the binary signature value
155
+ * (2) QueryParam - hex encoding of the binary signature value
156
+ * (3) Chunk/Sigv4 - hex encoding of the binary signature value
157
+ * (4) Chunk/Sigv4a - fixed-size-rhs-padded (with AWS_SIGV4A_SIGNATURE_PADDING_BYTE) hex encoding of the
158
+ * binary signature value
159
+ * (5) Event - binary signature value (NYI)
160
+ */
161
+ AWS_AUTH_API extern const struct aws_string *g_aws_signature_property_name;
162
+
163
+ /**
164
+ * Name of the property that holds the (hex-encoded) signature value of the signing event that preceded this one.
165
+ * This property must appear on signables that represent chunks or events.
166
+ */
167
+ AWS_AUTH_API extern const struct aws_string *g_aws_previous_signature_property_name;
168
+
169
+ /**
170
+ * Name of the property that holds the canonical request associated with this signable.
171
+ * This property must appear on signables that represent an http request's canonical request.
172
+ */
173
+ AWS_AUTH_API extern const struct aws_string *g_aws_canonical_request_property_name;
174
+
175
+ /*
176
+ * Common signable constructors
177
+ */
178
+
179
+ /**
180
+ * Creates a signable wrapper around an http request.
181
+ *
182
+ * @param allocator memory allocator to use to create the signable
183
+ * @param request http request to create a signable for
184
+ *
185
+ * @return the new signable object, or NULL if failure
186
+ */
187
+ AWS_AUTH_API
188
+ struct aws_signable *aws_signable_new_http_request(struct aws_allocator *allocator, struct aws_http_message *request);
189
+
190
+ /**
191
+ * Creates a signable that represents a unit of chunked encoding within an http request.
192
+ * This can also be used for Transcribe event signing with encoded payload as chunk_data.
193
+ *
194
+ * @param allocator memory allocator use to create the signable
195
+ * @param chunk_data stream representing the data in the chunk; it should be in its final, encoded form
196
+ * @param previous_signature the signature computed in the most recent signing that preceded this one. It can be
197
+ * found by copying the "signature" property from the signing_result of that most recent signing.
198
+ *
199
+ * @return the new signable object, or NULL if failure
200
+ */
201
+ AWS_AUTH_API
202
+ struct aws_signable *aws_signable_new_chunk(
203
+ struct aws_allocator *allocator,
204
+ struct aws_input_stream *chunk_data,
205
+ struct aws_byte_cursor previous_signature);
206
+
207
+ /**
208
+ * Creates a signable wrapper around a set of headers.
209
+ *
210
+ * @param allocator memory allocator use to create the signable
211
+ * @param trailing_headers http headers to create a signable for
212
+ * @param previous_signature the signature computed in the most recent signing that preceded this one. It can be
213
+ * found by copying the "signature" property from the signing_result of that most recent signing.
214
+ *
215
+ * @return the new signable object, or NULL if failure
216
+ */
217
+ AWS_AUTH_API
218
+ struct aws_signable *aws_signable_new_trailing_headers(
219
+ struct aws_allocator *allocator,
220
+ struct aws_http_headers *trailing_headers,
221
+ struct aws_byte_cursor previous_signature);
222
+
223
+ /**
224
+ * Creates a signable that represents a pre-computed canonical request from an http request
225
+ * @param allocator memory allocator use to create the signable
226
+ * @param canonical_request text of the canonical request
227
+ * @return the new signable object, or NULL if failure
228
+ */
229
+ AWS_AUTH_API
230
+ struct aws_signable *aws_signable_new_canonical_request(
231
+ struct aws_allocator *allocator,
232
+ struct aws_byte_cursor canonical_request);
233
+
234
+ AWS_EXTERN_C_END
235
+ AWS_POP_SANE_WARNING_LEVEL
236
+
237
+ #endif /* AWS_AUTH_SIGNABLE_H */
include/aws/auth/signing.h ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_SIGNER_H
2
+ #define AWS_AUTH_SIGNER_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/auth/auth.h>
10
+
11
+ #include <aws/auth/signing_config.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ struct aws_ecc_key_pair;
16
+ struct aws_signable;
17
+ struct aws_signing_result;
18
+
19
+ /**
20
+ * Gets called by the signing function when the signing is complete.
21
+ *
22
+ * Note that result will be destroyed after this function returns, so either copy it,
23
+ * or do all necessary adjustments inside the callback.
24
+ *
25
+ * When performing event or chunk signing, you will need to copy out the signature value in order
26
+ * to correctly configure the signable that wraps the event or chunk you want signed next. The signature is
27
+ * found in the "signature" property on the signing result. This value must be added as the
28
+ * "previous-signature" property on the next signable.
29
+ */
30
+ typedef void(aws_signing_complete_fn)(struct aws_signing_result *result, int error_code, void *userdata);
31
+
32
+ AWS_EXTERN_C_BEGIN
33
+
34
+ /*
35
+ * Takes a signable object and a configuration struct and computes the changes to the signable necessary
36
+ * for compliance with the signer's signing algorithm.
37
+ *
38
+ * This signing function currently supports only the sigv4 algorithm.
39
+ *
40
+ * When using this signing function to sign AWS http requests:
41
+ *
42
+ * (1) Do not add the following headers to requests before signing:
43
+ * x-amz-content-sha256,
44
+ * X-Amz-Date,
45
+ * Authorization
46
+ *
47
+ * (2) Do not add the following query params to requests before signing:
48
+ * X-Amz-Signature,
49
+ * X-Amz-Date,
50
+ * X-Amz-Credential,
51
+ * X-Amz-Algorithm,
52
+ * X-Amz-SignedHeaders
53
+ *
54
+ * The signing result will tell exactly what header and/or query params to add to the request
55
+ * to become a fully-signed AWS http request.
56
+ *
57
+ *
58
+ * When using this signing function to sign chunks:
59
+ *
60
+ * (1) Use aws_signable_new_chunk() to create the signable object representing the chunk
61
+ *
62
+ * The signing result will include the chunk's signature as the "signature" property.
63
+ *
64
+ *
65
+ */
66
+
67
+ /**
68
+ * (Asynchronous) entry point to sign something (a request, a chunk, an event) with an AWS signing process.
69
+ * Depending on the configuration, the signing process may or may not complete synchronously.
70
+ *
71
+ * @param allocator memory allocator to use throughout the signing process
72
+ * @param signable the thing to be signed. See signable.h for common constructors for signables that
73
+ * wrap different types.
74
+ * @param base_config pointer to a signing configuration, currently this must be of type aws_signing_config_aws
75
+ * @param on_complete completion callback to be invoked when signing has finished
76
+ * @param user_data opaque user data that will be passed to the completion callback
77
+ *
78
+ * @return AWS_OP_SUCCESS if the signing attempt was *initiated* successfully, AWS_OP_ERR otherwise
79
+ */
80
+ AWS_AUTH_API
81
+ int aws_sign_request_aws(
82
+ struct aws_allocator *allocator,
83
+ const struct aws_signable *signable,
84
+ const struct aws_signing_config_base *base_config,
85
+ aws_signing_complete_fn *on_complete,
86
+ void *userdata);
87
+
88
+ /**
89
+ * Test-only API used for cross-library signing verification tests
90
+ *
91
+ * Verifies:
92
+ * (1) The canonical request generated during sigv4a signing of the request matches what is passed in
93
+ * (2) The signature passed in is a valid ECDSA signature of the hashed string-to-sign derived from the
94
+ * canonical request
95
+ *
96
+ * @param allocator memory allocator to use throughout the signing verification process
97
+ * @param signable the thing to be signed. See signable.h for common constructors for signables that
98
+ * wrap different types.
99
+ * @param base_config pointer to a signing configuration, currently this must be of type aws_signing_config_aws
100
+ * @param expected_canonical_request_cursor expected result when building the canonical request
101
+ * @param signature_cursor the actual signature computed from a previous signing of the signable
102
+ * @param ecc_key_pub_x the x coordinate of the public part of the ecc key to verify the signature
103
+ * @param ecc_key_pub_y the y coordinate of the public part of the ecc key to verify the signature
104
+ *
105
+ * @return AWS_OP_SUCCESS if the signing attempt was *initiated* successfully, AWS_OP_ERR otherwise
106
+ */
107
+ AWS_AUTH_API
108
+ int aws_verify_sigv4a_signing(
109
+ struct aws_allocator *allocator,
110
+ const struct aws_signable *signable,
111
+ const struct aws_signing_config_base *base_config,
112
+ struct aws_byte_cursor expected_canonical_request_cursor,
113
+ struct aws_byte_cursor signature_cursor,
114
+ struct aws_byte_cursor ecc_key_pub_x,
115
+ struct aws_byte_cursor ecc_key_pub_y);
116
+
117
+ /**
118
+ * Another helper function to check a computed sigv4a signature.
119
+ */
120
+ AWS_AUTH_API
121
+ int aws_validate_v4a_authorization_value(
122
+ struct aws_allocator *allocator,
123
+ struct aws_ecc_key_pair *ecc_key,
124
+ struct aws_byte_cursor string_to_sign_cursor,
125
+ struct aws_byte_cursor signature_value_cursor);
126
+
127
+ /**
128
+ * Removes any padding added to the end of a sigv4a signature. Signature must be hex-encoded.
129
+ * @param signature signature to remove padding from
130
+ * @return cursor that ranges over only the valid hex encoding of the sigv4a signature
131
+ */
132
+ AWS_AUTH_API
133
+ struct aws_byte_cursor aws_trim_padded_sigv4a_signature(struct aws_byte_cursor signature);
134
+
135
+ AWS_EXTERN_C_END
136
+ AWS_POP_SANE_WARNING_LEVEL
137
+
138
+ #endif /* AWS_AUTH_SIGNER_H */
include/aws/auth/signing_config.h ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_SIGNING_CONFIG_H
2
+ #define AWS_AUTH_SIGNING_CONFIG_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/auth/auth.h>
10
+
11
+ #include <aws/common/byte_buf.h>
12
+ #include <aws/common/date_time.h>
13
+
14
+ AWS_PUSH_SANE_WARNING_LEVEL
15
+
16
+ struct aws_credentials;
17
+
18
+ typedef bool(aws_should_sign_header_fn)(const struct aws_byte_cursor *name, void *userdata);
19
+
20
+ /**
21
+ * A primitive RTTI indicator for signing configuration structs
22
+ *
23
+ * There must be one entry per config structure type and it's a fatal error
24
+ * to put the wrong value in the "config_type" member of your config structure.
25
+ */
26
+ enum aws_signing_config_type { AWS_SIGNING_CONFIG_AWS = 1 };
27
+
28
+ /**
29
+ * All signing configuration structs must match this by having
30
+ * the config_type member as the first member.
31
+ */
32
+ struct aws_signing_config_base {
33
+ enum aws_signing_config_type config_type;
34
+ };
35
+
36
+ /**
37
+ * What version of the AWS signing process should we use.
38
+ */
39
+ enum aws_signing_algorithm {
40
+ AWS_SIGNING_ALGORITHM_V4,
41
+ AWS_SIGNING_ALGORITHM_V4_ASYMMETRIC,
42
+ AWS_SIGNING_ALGORITHM_V4_S3EXPRESS,
43
+ };
44
+
45
+ /**
46
+ * What sort of signature should be computed from the signable?
47
+ */
48
+ enum aws_signature_type {
49
+ /**
50
+ * A signature for a full http request should be computed, with header updates applied to the signing result.
51
+ */
52
+ AWS_ST_HTTP_REQUEST_HEADERS,
53
+
54
+ /**
55
+ * A signature for a full http request should be computed, with query param updates applied to the signing result.
56
+ */
57
+ AWS_ST_HTTP_REQUEST_QUERY_PARAMS,
58
+
59
+ /**
60
+ * Compute a signature for a payload chunk. The signable's input stream should be the chunk data and the
61
+ * signable should contain the most recent signature value (either the original http request or the most recent
62
+ * chunk) in the "previous-signature" property.
63
+ */
64
+ AWS_ST_HTTP_REQUEST_CHUNK,
65
+
66
+ /**
67
+ * Compute a signature for an event stream event. The signable's input stream should be the encoded event-stream
68
+ * message (headers + payload), the signable should contain the most recent signature value (either the original
69
+ * http request or the most recent event) in the "previous-signature" property.
70
+ *
71
+ * This option is only supported for Sigv4 for now.
72
+ */
73
+ AWS_ST_HTTP_REQUEST_EVENT,
74
+
75
+ /**
76
+ * Compute a signature for an http request via it's already-computed canonical request. Only the authorization
77
+ * signature header is added to the signing result.
78
+ */
79
+ AWS_ST_CANONICAL_REQUEST_HEADERS,
80
+
81
+ /**
82
+ * Compute a signature for an http request via it's already-computed canonical request. Only the authorization
83
+ * signature query param is added to the signing result.
84
+ */
85
+ AWS_ST_CANONICAL_REQUEST_QUERY_PARAMS,
86
+
87
+ /**
88
+ * Compute a signature for the trailing headers.
89
+ * the signable should contain the most recent signature value (either the original http request or the most recent
90
+ * chunk) in the "previous-signature" property.
91
+ */
92
+ AWS_ST_HTTP_REQUEST_TRAILING_HEADERS
93
+ };
94
+
95
+ /**
96
+ * The SHA-256 of an empty string:
97
+ * 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
98
+ * For use with `aws_signing_config_aws.signed_body_value`.
99
+ */
100
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_empty_sha256;
101
+
102
+ /**
103
+ * 'UNSIGNED-PAYLOAD'
104
+ * For use with `aws_signing_config_aws.signed_body_value`.
105
+ */
106
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_unsigned_payload;
107
+
108
+ /**
109
+ * 'STREAMING-UNSIGNED-PAYLOAD-TRAILER'
110
+ * For use with `aws_signing_config_aws.signed_body_value`.
111
+ */
112
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_streaming_unsigned_payload_trailer;
113
+
114
+ /**
115
+ * 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD'
116
+ * For use with `aws_signing_config_aws.signed_body_value`.
117
+ */
118
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_streaming_aws4_hmac_sha256_payload;
119
+
120
+ /**
121
+ * 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER'
122
+ * For use with `aws_signing_config_aws.signed_body_value`.
123
+ */
124
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_streaming_aws4_hmac_sha256_payload_trailer;
125
+
126
+ /**
127
+ * 'STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD'
128
+ * For use with `aws_signing_config_aws.signed_body_value`.
129
+ */
130
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_streaming_aws4_ecdsa_p256_sha256_payload;
131
+
132
+ /**
133
+ * 'STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER'
134
+ * For use with `aws_signing_config_aws.signed_body_value`.
135
+ */
136
+ AWS_AUTH_API extern const struct aws_byte_cursor
137
+ g_aws_signed_body_value_streaming_aws4_ecdsa_p256_sha256_payload_trailer;
138
+
139
+ /**
140
+ * 'STREAMING-AWS4-HMAC-SHA256-EVENTS'
141
+ * For use with `aws_signing_config_aws.signed_body_value`.
142
+ *
143
+ * Event signing is only supported for Sigv4 for now.
144
+ */
145
+ AWS_AUTH_API extern const struct aws_byte_cursor g_aws_signed_body_value_streaming_aws4_hmac_sha256_events;
146
+
147
+ /**
148
+ * Controls if signing adds a header containing the canonical request's body value
149
+ */
150
+ enum aws_signed_body_header_type {
151
+ /**
152
+ * Do not add a header
153
+ */
154
+ AWS_SBHT_NONE,
155
+
156
+ /**
157
+ * Add the "x-amz-content-sha256" header with the canonical request's body value
158
+ */
159
+ AWS_SBHT_X_AMZ_CONTENT_SHA256,
160
+ };
161
+
162
+ /**
163
+ * A configuration structure for use in AWS-related signing. Currently covers sigv4 only, but is not required to.
164
+ */
165
+ struct aws_signing_config_aws {
166
+
167
+ /**
168
+ * What kind of config structure is this?
169
+ */
170
+ enum aws_signing_config_type config_type;
171
+
172
+ /**
173
+ * What signing algorithm to use.
174
+ */
175
+ enum aws_signing_algorithm algorithm;
176
+
177
+ /**
178
+ * What sort of signature should be computed?
179
+ */
180
+ enum aws_signature_type signature_type;
181
+
182
+ /*
183
+ * Region-related configuration
184
+ * (1) If Sigv4, the region to sign against
185
+ * (2) If Sigv4a, the value of the X-amzn-region-set header (added in signing)
186
+ */
187
+ struct aws_byte_cursor region;
188
+
189
+ /**
190
+ * name of service to sign a request for
191
+ */
192
+ struct aws_byte_cursor service;
193
+
194
+ /**
195
+ * Raw date to use during the signing process.
196
+ */
197
+ struct aws_date_time date;
198
+
199
+ /**
200
+ * Optional function to control which headers are a part of the canonical request.
201
+ * Skipping auth-required headers will result in an unusable signature. Headers injected by the signing process
202
+ * are not skippable.
203
+ *
204
+ * This function does not override the internal check function (x-amzn-trace-id, user-agent), but rather
205
+ * supplements it. In particular, a header will get signed if and only if it returns true to both
206
+ * the internal check (skips x-amzn-trace-id, user-agent) and this function (if defined).
207
+ */
208
+ aws_should_sign_header_fn *should_sign_header;
209
+ void *should_sign_header_ud;
210
+
211
+ /*
212
+ * Put all flags in here at the end. If this grows, stay aware of bit-space overflow and ABI compatibility.
213
+ */
214
+ struct {
215
+ /**
216
+ * We assume the uri will be encoded once in preparation for transmission. Certain services
217
+ * do not decode before checking signature, requiring us to actually double-encode the uri in the canonical
218
+ * request in order to pass a signature check.
219
+ */
220
+ uint32_t use_double_uri_encode : 1;
221
+
222
+ /**
223
+ * Controls whether or not the uri paths should be normalized when building the canonical request
224
+ */
225
+ uint32_t should_normalize_uri_path : 1;
226
+
227
+ /**
228
+ * Controls whether "X-Amz-Security-Token" is omitted from the canonical request.
229
+ * "X-Amz-Security-Token" is added during signing, as a header or
230
+ * query param, when credentials have a session token.
231
+ * If false (the default), this parameter is included in the canonical request.
232
+ * If true, this parameter is still added, but omitted from the canonical request.
233
+ */
234
+ uint32_t omit_session_token : 1;
235
+ } flags;
236
+
237
+ /**
238
+ * Optional string to use as the canonical request's body value.
239
+ * If string is empty, a value will be calculated from the payload during signing.
240
+ * Typically, this is the SHA-256 of the (request/chunk/event) payload, written as lowercase hex.
241
+ * If this has been precalculated, it can be set here. Special values used by certain services can also be set
242
+ * (e.g. "UNSIGNED-PAYLOAD" "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" "STREAMING-AWS4-HMAC-SHA256-EVENTS").
243
+ */
244
+ struct aws_byte_cursor signed_body_value;
245
+
246
+ /**
247
+ * Controls what body "hash" header, if any, should be added to the canonical request and the signed request:
248
+ * AWS_SBHT_NONE - no header should be added
249
+ * AWS_SBHT_X_AMZ_CONTENT_SHA256 - the body "hash" should be added in the X-Amz-Content-Sha256 header
250
+ */
251
+ enum aws_signed_body_header_type signed_body_header;
252
+
253
+ /*
254
+ * Signing key control:
255
+ *
256
+ * If "credentials" is valid:
257
+ * use it
258
+ * Else if "credentials_provider" is valid
259
+ * query credentials from the provider
260
+ * If sigv4a is being used
261
+ * use the ecc-based credentials derived from the query result
262
+ * Else
263
+ * use the query result
264
+ * Else
265
+ * fail
266
+ *
267
+ */
268
+
269
+ /*
270
+ * AWS Credentials to sign with. If Sigv4a is the algorithm and the credentials supplied are not ecc-based,
271
+ * a temporary ecc-based credentials object will be built and used instead.
272
+ */
273
+ const struct aws_credentials *credentials;
274
+
275
+ /*
276
+ * AWS credentials provider to fetch credentials from. If the signing algorithm is asymmetric sigv4, then the
277
+ * ecc-based credentials will be derived from the fetched credentials.
278
+ */
279
+ struct aws_credentials_provider *credentials_provider;
280
+
281
+ /**
282
+ * If non-zero and the signing transform is query param, then signing will add X-Amz-Expires to the query
283
+ * string, equal to the value specified here. If this value is zero or if header signing is being used then
284
+ * this parameter has no effect.
285
+ */
286
+ uint64_t expiration_in_seconds;
287
+ };
288
+
289
+ AWS_EXTERN_C_BEGIN
290
+
291
+ /**
292
+ * Returns a c-string that describes the supplied signing algorithm
293
+ *
294
+ * @param algorithm signing algorithm to get a friendly string name for
295
+ *
296
+ * @return friendly string name of the supplied algorithm, or "Unknown" if the algorithm is not recognized
297
+ */
298
+ AWS_AUTH_API
299
+ const char *aws_signing_algorithm_to_string(enum aws_signing_algorithm algorithm);
300
+
301
+ /**
302
+ * Checks a signing configuration for invalid settings combinations.
303
+ *
304
+ * @param config signing configuration to validate
305
+ *
306
+ * @return - AWS_OP_SUCCESS if the configuration is valid, AWS_OP_ERR otherwise
307
+ */
308
+ AWS_AUTH_API
309
+ int aws_validate_aws_signing_config_aws(const struct aws_signing_config_aws *config);
310
+
311
+ AWS_EXTERN_C_END
312
+ AWS_POP_SANE_WARNING_LEVEL
313
+
314
+ #endif /* AWS_AUTH_SIGNING_CONFIG_H */
include/aws/auth/signing_result.h ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_AUTH_SIGNING_RESULT_H
2
+ #define AWS_AUTH_SIGNING_RESULT_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/auth/auth.h>
10
+
11
+ #include <aws/common/hash_table.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ struct aws_array_list;
16
+ struct aws_byte_cursor;
17
+ struct aws_http_message;
18
+ struct aws_string;
19
+
20
+ struct aws_signing_result_property {
21
+ struct aws_string *name;
22
+ struct aws_string *value;
23
+ };
24
+
25
+ /**
26
+ * A structure for tracking all the signer-requested changes to a signable. Interpreting
27
+ * these changes is signing-algorithm specific.
28
+ *
29
+ * A signing result consists of
30
+ *
31
+ * (1) Properties - A set of key-value pairs
32
+ * (2) Property Lists - A set of named key-value pair lists
33
+ *
34
+ * The hope is that these two generic structures are enough to model the changes required
35
+ * by any generic message-signing algorithm.
36
+ *
37
+ * Note that the key-value pairs of a signing_result are different types (but same intent) as
38
+ * the key-value pairs in the signable interface. This is because the signing result stands alone
39
+ * and owns its own copies of all values, whereas a signable can wrap an existing object and thus
40
+ * use non-owning references (like byte cursors) if appropriate to its implementation.
41
+ */
42
+ struct aws_signing_result {
43
+ struct aws_allocator *allocator;
44
+ struct aws_hash_table properties;
45
+ struct aws_hash_table property_lists;
46
+ };
47
+
48
+ AWS_EXTERN_C_BEGIN
49
+
50
+ /**
51
+ * Initialize a signing result to its starting state
52
+ *
53
+ * @param result signing result to initialize
54
+ * @param allocator allocator to use for all memory allocation
55
+ *
56
+ * @return AWS_OP_SUCCESS if initialization was successful, AWS_OP_ERR otherwise
57
+ */
58
+ AWS_AUTH_API
59
+ int aws_signing_result_init(struct aws_signing_result *result, struct aws_allocator *allocator);
60
+
61
+ /**
62
+ * Clean up all resources held by the signing result
63
+ *
64
+ * @param result signing result to clean up resources for
65
+ */
66
+ AWS_AUTH_API
67
+ void aws_signing_result_clean_up(struct aws_signing_result *result);
68
+
69
+ /**
70
+ * Sets the value of a property on a signing result
71
+ *
72
+ * @param result signing result to modify
73
+ * @param property_name name of the property to set
74
+ * @param property_value value that the property should assume
75
+ *
76
+ * @return AWS_OP_SUCCESS if the set was successful, AWS_OP_ERR otherwise
77
+ */
78
+ AWS_AUTH_API
79
+ int aws_signing_result_set_property(
80
+ struct aws_signing_result *result,
81
+ const struct aws_string *property_name,
82
+ const struct aws_byte_cursor *property_value);
83
+
84
+ /**
85
+ * Gets the value of a property on a signing result
86
+ *
87
+ * @param result signing result to query from
88
+ * @param property_name name of the property to query the value of
89
+ * @param out_property_value output parameter for the property value
90
+ *
91
+ * @return AWS_OP_SUCCESS if the get was successful, AWS_OP_ERR otherwise
92
+ */
93
+ AWS_AUTH_API
94
+ int aws_signing_result_get_property(
95
+ const struct aws_signing_result *result,
96
+ const struct aws_string *property_name,
97
+ struct aws_string **out_property_value);
98
+
99
+ /**
100
+ * Adds a key-value pair to a named property list. If the named list does not yet exist, it will be created as
101
+ * an empty list before the pair is added. No uniqueness checks are made against existing pairs.
102
+ *
103
+ * @param result signing result to modify
104
+ * @param list_name name of the list to add the property key-value pair to
105
+ * @param property_name key value of the key-value pair to append
106
+ * @param property_value property value of the key-value pair to append
107
+ *
108
+ * @return AWS_OP_SUCCESS if the operation was successful, AWS_OP_ERR otherwise
109
+ */
110
+ AWS_AUTH_API
111
+ int aws_signing_result_append_property_list(
112
+ struct aws_signing_result *result,
113
+ const struct aws_string *list_name,
114
+ const struct aws_byte_cursor *property_name,
115
+ const struct aws_byte_cursor *property_value);
116
+
117
+ /**
118
+ * Gets a named property list on the signing result. If the list does not exist, *out_list will be set to null
119
+ *
120
+ * @param result signing result to query
121
+ * @param list_name name of the list of key-value pairs to get
122
+ * @param out_list output parameter for the list of key-value pairs
123
+ *
124
+ */
125
+ AWS_AUTH_API
126
+ void aws_signing_result_get_property_list(
127
+ const struct aws_signing_result *result,
128
+ const struct aws_string *list_name,
129
+ struct aws_array_list **out_list);
130
+
131
+ /**
132
+ * Looks for a property within a named property list on the signing result. If the list does not exist, or the property
133
+ * does not exist within the list, *out_value will be set to NULL.
134
+ *
135
+ * @param result signing result to query
136
+ * @param list_name name of the list of key-value pairs to search through for the property
137
+ * @param property_name name of the property to search for within the list
138
+ * @param out_value output parameter for the property value, if found
139
+ *
140
+ */
141
+ AWS_AUTH_API
142
+ void aws_signing_result_get_property_value_in_property_list(
143
+ const struct aws_signing_result *result,
144
+ const struct aws_string *list_name,
145
+ const struct aws_string *property_name,
146
+ struct aws_string **out_value);
147
+
148
+ /*
149
+ * Specific implementation that applies a signing result to a mutable http request
150
+ *
151
+ * @param request http request to apply the signing result to
152
+ * @param allocator memory allocator to use for all memory allocation
153
+ * @param result signing result to apply to the request
154
+ *
155
+ * @return AWS_OP_SUCCESS if the application operation was successful, AWS_OP_ERR otherwise
156
+ */
157
+ AWS_AUTH_API
158
+ int aws_apply_signing_result_to_http_request(
159
+ struct aws_http_message *request,
160
+ struct aws_allocator *allocator,
161
+ const struct aws_signing_result *result);
162
+
163
+ AWS_AUTH_API extern const struct aws_string *g_aws_signing_authorization_header_name;
164
+ AWS_AUTH_API extern const struct aws_string *g_aws_signing_authorization_query_param_name;
165
+
166
+ AWS_EXTERN_C_END
167
+ AWS_POP_SANE_WARNING_LEVEL
168
+
169
+ #endif /* AWS_AUTH_SIGNING_RESULT_H */
include/aws/cal/cal.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_CAL_H
2
+ #define AWS_CAL_CAL_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/common.h>
9
+ #include <aws/common/logging.h>
10
+
11
+ #include <aws/cal/exports.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ struct aws_allocator;
16
+
17
+ #define AWS_C_CAL_PACKAGE_ID 7
18
+
19
+ enum aws_cal_errors {
20
+ AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED = AWS_ERROR_ENUM_BEGIN_RANGE(AWS_C_CAL_PACKAGE_ID),
21
+ AWS_ERROR_CAL_MISSING_REQUIRED_KEY_COMPONENT,
22
+ AWS_ERROR_CAL_INVALID_KEY_LENGTH_FOR_ALGORITHM,
23
+ AWS_ERROR_CAL_UNKNOWN_OBJECT_IDENTIFIER,
24
+ AWS_ERROR_CAL_MALFORMED_ASN1_ENCOUNTERED,
25
+ AWS_ERROR_CAL_MISMATCHED_DER_TYPE,
26
+ AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM,
27
+ AWS_ERROR_CAL_BUFFER_TOO_LARGE_FOR_ALGORITHM,
28
+ AWS_ERROR_CAL_INVALID_CIPHER_MATERIAL_SIZE_FOR_ALGORITHM,
29
+ AWS_ERROR_CAL_DER_UNSUPPORTED_NEGATIVE_INT,
30
+ AWS_ERROR_CAL_UNSUPPORTED_KEY_FORMAT,
31
+ AWS_ERROR_CAL_CRYPTO_OPERATION_FAILED,
32
+ AWS_ERROR_CAL_END_RANGE = AWS_ERROR_ENUM_END_RANGE(AWS_C_CAL_PACKAGE_ID)
33
+ };
34
+
35
+ enum aws_cal_log_subject {
36
+ AWS_LS_CAL_GENERAL = AWS_LOG_SUBJECT_BEGIN_RANGE(AWS_C_CAL_PACKAGE_ID),
37
+ AWS_LS_CAL_ECC,
38
+ AWS_LS_CAL_HASH,
39
+ AWS_LS_CAL_HMAC,
40
+ AWS_LS_CAL_DER,
41
+ AWS_LS_CAL_LIBCRYPTO_RESOLVE,
42
+ AWS_LS_CAL_RSA,
43
+ AWS_LS_CAL_ED25519,
44
+
45
+ AWS_LS_CAL_LAST = AWS_LOG_SUBJECT_END_RANGE(AWS_C_CAL_PACKAGE_ID)
46
+ };
47
+
48
+ AWS_EXTERN_C_BEGIN
49
+
50
+ AWS_CAL_API void aws_cal_library_init(struct aws_allocator *allocator);
51
+ AWS_CAL_API void aws_cal_library_clean_up(void);
52
+
53
+ /*
54
+ * Every CRT thread that might invoke aws-lc functionality should call this as part of the thread at_exit process
55
+ */
56
+ AWS_CAL_API void aws_cal_thread_clean_up(void);
57
+
58
+ AWS_EXTERN_C_END
59
+ AWS_POP_SANE_WARNING_LEVEL
60
+
61
+ #endif /* AWS_CAL_CAL_H */
include/aws/cal/ecc.h ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_ECC_H
2
+ #define AWS_CAL_ECC_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/exports.h>
8
+
9
+ #include <aws/common/atomics.h>
10
+ #include <aws/common/byte_buf.h>
11
+ #include <aws/common/common.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ enum aws_ecc_curve_name {
16
+ AWS_CAL_ECDSA_P256,
17
+ AWS_CAL_ECDSA_P384,
18
+ };
19
+
20
+ struct aws_ecc_key_pair;
21
+
22
+ typedef void aws_ecc_key_pair_destroy_fn(struct aws_ecc_key_pair *key_pair);
23
+ typedef int aws_ecc_key_pair_sign_message_fn(
24
+ const struct aws_ecc_key_pair *key_pair,
25
+ const struct aws_byte_cursor *message,
26
+ struct aws_byte_buf *signature_output);
27
+ typedef int aws_ecc_key_pair_derive_public_key_fn(struct aws_ecc_key_pair *key_pair);
28
+ typedef int aws_ecc_key_pair_verify_signature_fn(
29
+ const struct aws_ecc_key_pair *signer,
30
+ const struct aws_byte_cursor *message,
31
+ const struct aws_byte_cursor *signature);
32
+ typedef size_t aws_ecc_key_pair_signature_length_fn(const struct aws_ecc_key_pair *signer);
33
+
34
+ struct aws_ecc_key_pair_vtable {
35
+ aws_ecc_key_pair_destroy_fn *destroy;
36
+ aws_ecc_key_pair_derive_public_key_fn *derive_pub_key;
37
+ aws_ecc_key_pair_sign_message_fn *sign_message;
38
+ aws_ecc_key_pair_verify_signature_fn *verify_signature;
39
+ aws_ecc_key_pair_signature_length_fn *signature_length;
40
+ };
41
+
42
+ struct aws_ecc_key_pair {
43
+ struct aws_allocator *allocator;
44
+ struct aws_atomic_var ref_count;
45
+ enum aws_ecc_curve_name curve_name;
46
+ struct aws_byte_buf key_buf;
47
+ struct aws_byte_buf pub_x;
48
+ struct aws_byte_buf pub_y;
49
+ struct aws_byte_buf priv_d;
50
+ struct aws_ecc_key_pair_vtable *vtable;
51
+ void *impl;
52
+ };
53
+
54
+ AWS_EXTERN_C_BEGIN
55
+
56
+ /**
57
+ * Adds one to an ecc key pair's ref count.
58
+ */
59
+ AWS_CAL_API void aws_ecc_key_pair_acquire(struct aws_ecc_key_pair *key_pair);
60
+
61
+ /**
62
+ * Subtracts one from an ecc key pair's ref count. If ref count reaches zero, the key pair is destroyed.
63
+ */
64
+ AWS_CAL_API void aws_ecc_key_pair_release(struct aws_ecc_key_pair *key_pair);
65
+
66
+ /**
67
+ * Creates an Elliptic Curve private key that can be used for signing.
68
+ * Returns a new instance of aws_ecc_key_pair if the key was successfully built.
69
+ * Otherwise returns NULL. Note: priv_key::len must match the appropriate length
70
+ * for the selected curve_name.
71
+ */
72
+ AWS_CAL_API struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_private_key(
73
+ struct aws_allocator *allocator,
74
+ enum aws_ecc_curve_name curve_name,
75
+ const struct aws_byte_cursor *priv_key);
76
+
77
+ #if !defined(AWS_OS_IOS)
78
+ /**
79
+ * Creates an Elliptic Curve public/private key pair that can be used for signing and verifying.
80
+ * Returns a new instance of aws_ecc_key_pair if the key was successfully built.
81
+ * Otherwise returns NULL.
82
+ * Note: On Apple platforms this function is only supported on MacOS. This is
83
+ * due to usage of SecItemExport, which is only available on MacOS 10.7+
84
+ * (yes, MacOS only and no other Apple platforms). There are alternatives for
85
+ * ios and other platforms, but they are ugly to use. Hence for now it only
86
+ * supports this call on MacOS.
87
+ */
88
+ AWS_CAL_API struct aws_ecc_key_pair *aws_ecc_key_pair_new_generate_random(
89
+ struct aws_allocator *allocator,
90
+ enum aws_ecc_curve_name curve_name);
91
+ #endif /* !AWS_OS_IOS */
92
+
93
+ /**
94
+ * Creates an Elliptic Curve public key that can be used for verifying.
95
+ * Returns a new instance of aws_ecc_key_pair if the key was successfully built.
96
+ * Otherwise returns NULL. Note: public_key_x::len and public_key_y::len must
97
+ * match the appropriate length for the selected curve_name.
98
+ */
99
+ AWS_CAL_API struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_public_key(
100
+ struct aws_allocator *allocator,
101
+ enum aws_ecc_curve_name curve_name,
102
+ const struct aws_byte_cursor *public_key_x,
103
+ const struct aws_byte_cursor *public_key_y);
104
+
105
+ /**
106
+ * Creates an Elliptic Curve public/private key pair from a DER encoded key pair.
107
+ * Returns a new instance of aws_ecc_key_pair if the key was successfully built.
108
+ * Otherwise returns NULL. Whether or not signing or verification can be perform depends
109
+ * on if encoded_keys is a public/private pair or a public key.
110
+ */
111
+ AWS_CAL_API struct aws_ecc_key_pair *aws_ecc_key_pair_new_from_asn1(
112
+ struct aws_allocator *allocator,
113
+ const struct aws_byte_cursor *encoded_keys);
114
+
115
+ /**
116
+ * Creates an Elliptic curve public key from x and y coordinates encoded as hex strings
117
+ * Returns a new instance of aws_ecc_key_pair if the key was successfully built.
118
+ * Otherwise returns NULL.
119
+ */
120
+ AWS_CAL_API struct aws_ecc_key_pair *aws_ecc_key_new_from_hex_coordinates(
121
+ struct aws_allocator *allocator,
122
+ enum aws_ecc_curve_name curve_name,
123
+ struct aws_byte_cursor pub_x_hex_cursor,
124
+ struct aws_byte_cursor pub_y_hex_cursor);
125
+
126
+ /**
127
+ * Derives a public key from the private key if supported by this operating system (not supported on OSX).
128
+ * key_pair::pub_x and key_pair::pub_y will be set with the raw key buffers.
129
+ */
130
+ AWS_CAL_API int aws_ecc_key_pair_derive_public_key(struct aws_ecc_key_pair *key_pair);
131
+
132
+ /**
133
+ * Get the curve name from the oid. OID here is the payload of the DER encoded ASN.1 part (doesn't include
134
+ * type specifier or length. On success, the value of curve_name will be set.
135
+ */
136
+ AWS_CAL_API int aws_ecc_curve_name_from_oid(struct aws_byte_cursor *oid, enum aws_ecc_curve_name *curve_name);
137
+
138
+ /**
139
+ * Get the DER encoded OID from the curve_name. The OID in this case will not contain the type or the length specifier.
140
+ */
141
+ AWS_CAL_API int aws_ecc_oid_from_curve_name(enum aws_ecc_curve_name curve_name, struct aws_byte_cursor *oid);
142
+
143
+ /**
144
+ * Uses the key_pair's private key to sign message. The output will be in signature. Signature must be large enough
145
+ * to hold the signature. Check aws_ecc_key_pair_signature_length() for the appropriate size. Signature will be DER
146
+ * encoded.
147
+ *
148
+ * It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually
149
+ * something like a SHA256.
150
+ */
151
+ AWS_CAL_API int aws_ecc_key_pair_sign_message(
152
+ const struct aws_ecc_key_pair *key_pair,
153
+ const struct aws_byte_cursor *message,
154
+ struct aws_byte_buf *signature);
155
+
156
+ /**
157
+ * Uses the key_pair's public key to verify signature of message. Signature should be DER
158
+ * encoded.
159
+ *
160
+ * It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually
161
+ * something like a SHA256.
162
+ *
163
+ * returns AWS_OP_SUCCESS if the signature is valid.
164
+ */
165
+ AWS_CAL_API int aws_ecc_key_pair_verify_signature(
166
+ const struct aws_ecc_key_pair *key_pair,
167
+ const struct aws_byte_cursor *message,
168
+ const struct aws_byte_cursor *signature);
169
+ AWS_CAL_API size_t aws_ecc_key_pair_signature_length(const struct aws_ecc_key_pair *key_pair);
170
+
171
+ AWS_CAL_API void aws_ecc_key_pair_get_public_key(
172
+ const struct aws_ecc_key_pair *key_pair,
173
+ struct aws_byte_cursor *pub_x,
174
+ struct aws_byte_cursor *pub_y);
175
+
176
+ AWS_CAL_API void aws_ecc_key_pair_get_private_key(
177
+ const struct aws_ecc_key_pair *key_pair,
178
+ struct aws_byte_cursor *private_d);
179
+
180
+ AWS_CAL_API size_t aws_ecc_key_coordinate_byte_size_from_curve_name(enum aws_ecc_curve_name curve_name);
181
+
182
+ AWS_EXTERN_C_END
183
+ AWS_POP_SANE_WARNING_LEVEL
184
+
185
+ #endif /* AWS_CAL_ECC_H */
include/aws/cal/ed25519.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_ED25519_H
2
+ #define AWS_CAL_ED25519_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/cal.h>
8
+ #include <aws/common/byte_buf.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ struct aws_ed25519_key_pair;
13
+
14
+ AWS_EXTERN_C_BEGIN
15
+
16
+ /**
17
+ * Generate new Ed25519 key.
18
+ * Returns a new instance of aws_ed25519_key_pair if the key was successfully generated.
19
+ * Otherwise returns NULL.
20
+ * Note: keygen is not supported on all platforms and will return NULL for the key
21
+ * and raise AWS_ERROR_CAL_UNSUPPORTED_ALGORITHM.
22
+ * Examples of unsupported cases:
23
+ * - openssl pre 1.1.1 (Note: aws-lc and boringssl both expose the needed functions)
24
+ * - win/mac builds without special flag that forces linking to libcrypto to support this
25
+ */
26
+ AWS_CAL_API struct aws_ed25519_key_pair *aws_ed25519_key_pair_new_generate(struct aws_allocator *allocator);
27
+
28
+ /**
29
+ * Adds one to an Ed25519 key pair's ref count.
30
+ * Returns key_pair pointer.
31
+ */
32
+ AWS_CAL_API struct aws_ed25519_key_pair *aws_ed25519_key_pair_acquire(struct aws_ed25519_key_pair *key_pair);
33
+
34
+ /**
35
+ * Subtracts one from an Ed25519 key pair's ref count. If ref count reaches zero, the key pair is destroyed.
36
+ * Always returns NULL.
37
+ */
38
+ AWS_CAL_API struct aws_ed25519_key_pair *aws_ed25519_key_pair_release(struct aws_ed25519_key_pair *key_pair);
39
+
40
+ enum aws_ed25519_key_export_format {
41
+ /* Export the key as raw bytes */
42
+ AWS_CAL_ED25519_KEY_EXPORT_RAW,
43
+
44
+ /**
45
+ * Export the key to openssh format.
46
+ * This will only export the key block, framing (i.e. pem) is left as exercise for the caller.
47
+ * b64 encoding is done as convenience since common framing formats require it.
48
+ */
49
+ AWS_CAL_ED25519_KEY_EXPORT_OPENSSH_B64,
50
+ };
51
+
52
+ /*
53
+ * Get public key for the key pair.
54
+ * Key in specified format is appended to the buffer.
55
+ * The buffer must be initialized before this call, with sufficient capacity to hold the result.
56
+ * Use aws_ed25519_key_pair_get_public_key_size to figure out how much capacity buffer needs for a given format.
57
+ */
58
+ AWS_CAL_API int aws_ed25519_key_pair_get_public_key(
59
+ const struct aws_ed25519_key_pair *key_pair,
60
+ enum aws_ed25519_key_export_format format,
61
+ struct aws_byte_buf *out);
62
+
63
+ /**
64
+ * Gets the size of the exported public key.
65
+ */
66
+ AWS_CAL_API size_t aws_ed25519_key_pair_get_public_key_size(enum aws_ed25519_key_export_format format);
67
+
68
+ /*
69
+ * Get private key for the key pair.
70
+ * Key in specified format is appended to the buffer.
71
+ * The buffer must be initialized before this call, with sufficient capacity to hold the result.
72
+ * Use aws_ed25519_key_pair_get_private_key_size to figure out how much capacity buffer needs for a given format.
73
+ */
74
+ AWS_CAL_API int aws_ed25519_key_pair_get_private_key(
75
+ const struct aws_ed25519_key_pair *key_pair,
76
+ enum aws_ed25519_key_export_format format,
77
+ struct aws_byte_buf *out);
78
+
79
+ /**
80
+ * Gets the size of the exported private key.
81
+ */
82
+ AWS_CAL_API size_t aws_ed25519_key_pair_get_private_key_size(enum aws_ed25519_key_export_format format);
83
+
84
+ AWS_EXTERN_C_END
85
+
86
+ AWS_POP_SANE_WARNING_LEVEL
87
+
88
+ #endif /* AWS_CAL_ED25519_H */
include/aws/cal/exports.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_EXPORTS_H
2
+ #define AWS_CAL_EXPORTS_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #if defined(AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined(_WIN32)
8
+ # ifdef AWS_CAL_USE_IMPORT_EXPORT
9
+ # ifdef AWS_CAL_EXPORTS
10
+ # define AWS_CAL_API __declspec(dllexport)
11
+ # else
12
+ # define AWS_CAL_API __declspec(dllimport)
13
+ # endif /* AWS_CAL_EXPORTS */
14
+ # else
15
+ # define AWS_CAL_API
16
+ # endif /* AWS_CAL_USE_IMPORT_EXPORT */
17
+
18
+ #else /* defined (AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined (_WIN32) */
19
+
20
+ # if defined(AWS_CAL_USE_IMPORT_EXPORT) && defined(AWS_CAL_EXPORTS)
21
+ # define AWS_CAL_API __attribute__((visibility("default")))
22
+ # else
23
+ # define AWS_CAL_API
24
+ # endif
25
+
26
+ #endif /* defined (AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined (_WIN32) */
27
+
28
+ #endif /* AWS_CAL_EXPORTS_H */
include/aws/cal/hash.h ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_HASH_H_
2
+ #define AWS_CAL_HASH_H_
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/exports.h>
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+
14
+ #define AWS_SHA256_LEN 32
15
+ #define AWS_SHA1_LEN 20
16
+ #define AWS_MD5_LEN 16
17
+
18
+ struct aws_hash;
19
+
20
+ struct aws_hash_vtable {
21
+ const char *alg_name;
22
+ const char *provider;
23
+ void (*destroy)(struct aws_hash *hash);
24
+ int (*update)(struct aws_hash *hash, const struct aws_byte_cursor *buf);
25
+ int (*finalize)(struct aws_hash *hash, struct aws_byte_buf *out);
26
+ };
27
+
28
+ struct aws_hash {
29
+ struct aws_allocator *allocator;
30
+ struct aws_hash_vtable *vtable;
31
+ size_t digest_size;
32
+ bool good;
33
+ void *impl;
34
+ };
35
+
36
+ typedef struct aws_hash *(aws_hash_new_fn)(struct aws_allocator *allocator);
37
+
38
+ AWS_EXTERN_C_BEGIN
39
+ /**
40
+ * Allocates and initializes a sha256 hash instance.
41
+ */
42
+ AWS_CAL_API struct aws_hash *aws_sha256_new(struct aws_allocator *allocator);
43
+ /**
44
+ * Allocates and initializes a sha1 hash instance.
45
+ */
46
+ AWS_CAL_API struct aws_hash *aws_sha1_new(struct aws_allocator *allocator);
47
+ /**
48
+ * Allocates and initializes an md5 hash instance.
49
+ */
50
+ AWS_CAL_API struct aws_hash *aws_md5_new(struct aws_allocator *allocator);
51
+
52
+ /**
53
+ * Cleans up and deallocates hash.
54
+ */
55
+ AWS_CAL_API void aws_hash_destroy(struct aws_hash *hash);
56
+ /**
57
+ * Updates the running hash with to_hash. this can be called multiple times.
58
+ */
59
+ AWS_CAL_API int aws_hash_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash);
60
+ /**
61
+ * Completes the hash computation and writes the final digest to output.
62
+ * Allocation of output is the caller's responsibility. If you specify
63
+ * truncate_to to something other than 0, the output will be truncated to that
64
+ * number of bytes. For example, if you want a SHA256 digest as the first 16
65
+ * bytes, set truncate_to to 16. If you want the full digest size, just set this
66
+ * to 0.
67
+ */
68
+ AWS_CAL_API int aws_hash_finalize(struct aws_hash *hash, struct aws_byte_buf *output, size_t truncate_to);
69
+
70
+ /**
71
+ * Computes the md5 hash over input and writes the digest output to 'output'.
72
+ * Use this if you don't need to stream the data you're hashing and you can load
73
+ * the entire input to hash into memory.
74
+ */
75
+ AWS_CAL_API int aws_md5_compute(
76
+ struct aws_allocator *allocator,
77
+ const struct aws_byte_cursor *input,
78
+ struct aws_byte_buf *output,
79
+ size_t truncate_to);
80
+
81
+ /**
82
+ * Computes the sha256 hash over input and writes the digest output to 'output'.
83
+ * Use this if you don't need to stream the data you're hashing and you can load
84
+ * the entire input to hash into memory. If you specify truncate_to to something
85
+ * other than 0, the output will be truncated to that number of bytes. For
86
+ * example, if you want a SHA256 digest as the first 16 bytes, set truncate_to
87
+ * to 16. If you want the full digest size, just set this to 0.
88
+ */
89
+ AWS_CAL_API int aws_sha256_compute(
90
+ struct aws_allocator *allocator,
91
+ const struct aws_byte_cursor *input,
92
+ struct aws_byte_buf *output,
93
+ size_t truncate_to);
94
+
95
+ /**
96
+ * Computes the sha1 hash over input and writes the digest output to 'output'.
97
+ * Use this if you don't need to stream the data you're hashing and you can load
98
+ * the entire input to hash into memory. If you specify truncate_to to something
99
+ * other than 0, the output will be truncated to that number of bytes. For
100
+ * example, if you want a SHA1 digest as the first 16 bytes, set truncate_to
101
+ * to 16. If you want the full digest size, just set this to 0.
102
+ */
103
+ AWS_CAL_API int aws_sha1_compute(
104
+ struct aws_allocator *allocator,
105
+ const struct aws_byte_cursor *input,
106
+ struct aws_byte_buf *output,
107
+ size_t truncate_to);
108
+
109
+ /**
110
+ * Set the implementation of md5 to use. If you compiled without BYO_CRYPTO,
111
+ * you do not need to call this. However, if use this, we will honor it,
112
+ * regardless of compile options. This may be useful for testing purposes. If
113
+ * you did set BYO_CRYPTO, and you do not call this function you will
114
+ * segfault.
115
+ */
116
+ AWS_CAL_API void aws_set_md5_new_fn(aws_hash_new_fn *fn);
117
+
118
+ /**
119
+ * Set the implementation of sha256 to use. If you compiled without
120
+ * BYO_CRYPTO, you do not need to call this. However, if use this, we will
121
+ * honor it, regardless of compile options. This may be useful for testing
122
+ * purposes. If you did set BYO_CRYPTO, and you do not call this function
123
+ * you will segfault.
124
+ */
125
+ AWS_CAL_API void aws_set_sha256_new_fn(aws_hash_new_fn *fn);
126
+
127
+ /**
128
+ * Set the implementation of sha1 to use. If you compiled without
129
+ * BYO_CRYPTO, you do not need to call this. However, if use this, we will
130
+ * honor it, regardless of compile options. This may be useful for testing
131
+ * purposes. If you did set BYO_CRYPTO, and you do not call this function
132
+ * you will segfault.
133
+ */
134
+ AWS_CAL_API void aws_set_sha1_new_fn(aws_hash_new_fn *fn);
135
+
136
+ AWS_EXTERN_C_END
137
+ AWS_POP_SANE_WARNING_LEVEL
138
+
139
+ #endif /* AWS_CAL_HASH_H_ */
include/aws/cal/hmac.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_HMAC_H_
2
+ #define AWS_CAL_HMAC_H_
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/exports.h>
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+
14
+ #define AWS_SHA256_HMAC_LEN 32
15
+
16
+ struct aws_hmac;
17
+
18
+ struct aws_hmac_vtable {
19
+ const char *alg_name;
20
+ const char *provider;
21
+ void (*destroy)(struct aws_hmac *hmac);
22
+ int (*update)(struct aws_hmac *hmac, const struct aws_byte_cursor *buf);
23
+ int (*finalize)(struct aws_hmac *hmac, struct aws_byte_buf *out);
24
+ };
25
+
26
+ struct aws_hmac {
27
+ struct aws_allocator *allocator;
28
+ struct aws_hmac_vtable *vtable;
29
+ size_t digest_size;
30
+ bool good;
31
+ void *impl;
32
+ };
33
+
34
+ typedef struct aws_hmac *(aws_hmac_new_fn)(struct aws_allocator *allocator, const struct aws_byte_cursor *secret);
35
+
36
+ AWS_EXTERN_C_BEGIN
37
+ /**
38
+ * Allocates and initializes a sha256 hmac instance. Secret is the key to be
39
+ * used for the hmac process.
40
+ */
41
+ AWS_CAL_API struct aws_hmac *aws_sha256_hmac_new(struct aws_allocator *allocator, const struct aws_byte_cursor *secret);
42
+
43
+ /**
44
+ * Cleans up and deallocates hmac.
45
+ */
46
+ AWS_CAL_API void aws_hmac_destroy(struct aws_hmac *hmac);
47
+
48
+ /**
49
+ * Updates the running hmac with to_hash. this can be called multiple times.
50
+ */
51
+ AWS_CAL_API int aws_hmac_update(struct aws_hmac *hmac, const struct aws_byte_cursor *to_hmac);
52
+ /**
53
+ * Completes the hmac computation and writes the final digest to output.
54
+ * Allocation of output is the caller's responsibility. If you specify
55
+ * truncate_to to something other than 0, the output will be truncated to that
56
+ * number of bytes. For example if you want a SHA256 digest as the first 16
57
+ * bytes, set truncate_to to 16. If you want the full digest size, just set this
58
+ * to 0.
59
+ */
60
+ AWS_CAL_API int aws_hmac_finalize(struct aws_hmac *hmac, struct aws_byte_buf *output, size_t truncate_to);
61
+ /**
62
+ * Computes the sha256 hmac over input and writes the digest output to 'output'.
63
+ * Use this if you don't need to stream the data you're hashing and you can load
64
+ * the entire input to hash into memory. If you specify truncate_to to something
65
+ * other than 0, the output will be truncated to that number of bytes. For
66
+ * example if you want a SHA256 HMAC digest as the first 16 bytes, set
67
+ * truncate_to to 16. If you want the full digest size, just set this to 0.
68
+ */
69
+ AWS_CAL_API int aws_sha256_hmac_compute(
70
+ struct aws_allocator *allocator,
71
+ const struct aws_byte_cursor *secret,
72
+ const struct aws_byte_cursor *to_hmac,
73
+ struct aws_byte_buf *output,
74
+ size_t truncate_to);
75
+ /**
76
+ * Set the implementation of sha256 hmac to use. If you compiled without
77
+ * BYO_CRYPTO, you do not need to call this. However, if use this, we will
78
+ * honor it, regardless of compile options. This may be useful for testing
79
+ * purposes. If you did set BYO_CRYPTO, and you do not call this function
80
+ * you will segfault.
81
+ */
82
+ AWS_CAL_API void aws_set_sha256_hmac_new_fn(aws_hmac_new_fn *fn);
83
+
84
+ AWS_EXTERN_C_END
85
+ AWS_POP_SANE_WARNING_LEVEL
86
+
87
+ #endif /* AWS_CAL_HASH_H_ */
include/aws/cal/rsa.h ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_RSA_H
2
+ #define AWS_CAL_RSA_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/cal.h>
8
+ #include <aws/common/byte_buf.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ struct aws_rsa_key_pair;
13
+
14
+ enum aws_rsa_encryption_algorithm {
15
+ AWS_CAL_RSA_ENCRYPTION_PKCS1_5,
16
+ AWS_CAL_RSA_ENCRYPTION_OAEP_SHA256,
17
+ AWS_CAL_RSA_ENCRYPTION_OAEP_SHA512,
18
+ };
19
+
20
+ enum aws_rsa_signature_algorithm {
21
+ AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA256,
22
+ AWS_CAL_RSA_SIGNATURE_PKCS1_5_SHA1,
23
+ AWS_CAL_RSA_SIGNATURE_PSS_SHA256,
24
+ };
25
+
26
+ /*
27
+ * Note: prefer using standard key sizes - 1024, 2048, 4096.
28
+ * Other key sizes will work, but which key sizes are supported may vary by
29
+ * platform. Typically, multiples of 64 should work on all platforms.
30
+ */
31
+ enum {
32
+ AWS_CAL_RSA_MIN_SUPPORTED_KEY_SIZE_IN_BITS = 1024,
33
+ AWS_CAL_RSA_MAX_SUPPORTED_KEY_SIZE_IN_BITS = 4096,
34
+ };
35
+
36
+ AWS_EXTERN_C_BEGIN
37
+
38
+ /**
39
+ * Creates an RSA public key from RSAPublicKey as defined in rfc 8017 (aka PKCS1).
40
+ * Returns a new instance of aws_rsa_key_pair if the key was successfully built.
41
+ * Otherwise returns NULL.
42
+ */
43
+ AWS_CAL_API struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_public_key_pkcs1(
44
+ struct aws_allocator *allocator,
45
+ struct aws_byte_cursor key);
46
+
47
+ /**
48
+ * Creates an RSA private key from RSAPrivateKey as defined in rfc 8017 (aka PKCS1).
49
+ * Returns a new instance of aws_rsa_key_pair if the key was successfully built.
50
+ * Otherwise returns NULL.
51
+ */
52
+ AWS_CAL_API struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_private_key_pkcs1(
53
+ struct aws_allocator *allocator,
54
+ struct aws_byte_cursor key);
55
+
56
+ /**
57
+ * Creates an RSA private key from PrivateKeyInfo as defined in rfc 5208 (aka PKCS8).
58
+ * Returns a new instance of aws_rsa_key_pair if the key was successfully built.
59
+ * Otherwise returns NULL.
60
+ */
61
+ AWS_CAL_API struct aws_rsa_key_pair *aws_rsa_key_pair_new_from_private_key_pkcs8(
62
+ struct aws_allocator *allocator,
63
+ struct aws_byte_cursor key);
64
+
65
+ /**
66
+ * Adds one to an RSA key pair's ref count.
67
+ * Returns key_pair pointer.
68
+ */
69
+ AWS_CAL_API struct aws_rsa_key_pair *aws_rsa_key_pair_acquire(struct aws_rsa_key_pair *key_pair);
70
+
71
+ /**
72
+ * Subtracts one from an RSA key pair's ref count. If ref count reaches zero, the key pair is destroyed.
73
+ * Always returns NULL.
74
+ */
75
+ AWS_CAL_API struct aws_rsa_key_pair *aws_rsa_key_pair_release(struct aws_rsa_key_pair *key_pair);
76
+
77
+ /**
78
+ * Max plaintext size that can be encrypted by the key (i.e. max data size
79
+ * supported by the key - bytes needed for padding).
80
+ */
81
+ AWS_CAL_API size_t aws_rsa_key_pair_max_encrypt_plaintext_size(
82
+ const struct aws_rsa_key_pair *key_pair,
83
+ enum aws_rsa_encryption_algorithm algorithm);
84
+
85
+ /*
86
+ * Uses the key_pair's private key to encrypt the plaintext. The output will be
87
+ * in out. out must be large enough to to hold the ciphertext. Check
88
+ * aws_rsa_key_pair_block_length() for output upper bound.
89
+ */
90
+ AWS_CAL_API int aws_rsa_key_pair_encrypt(
91
+ const struct aws_rsa_key_pair *key_pair,
92
+ enum aws_rsa_encryption_algorithm algorithm,
93
+ struct aws_byte_cursor plaintext,
94
+ struct aws_byte_buf *out);
95
+
96
+ /*
97
+ * Uses the key_pair's private key to decrypt the ciphertext. The output will be
98
+ * in out. out must be large enough to to hold the ciphertext. Check
99
+ * aws_rsa_key_pair_block_length() for output upper bound.
100
+ */
101
+ AWS_CAL_API int aws_rsa_key_pair_decrypt(
102
+ const struct aws_rsa_key_pair *key_pair,
103
+ enum aws_rsa_encryption_algorithm algorithm,
104
+ struct aws_byte_cursor ciphertext,
105
+ struct aws_byte_buf *out);
106
+
107
+ /*
108
+ * Max size for a block supported by a given key pair.
109
+ */
110
+ AWS_CAL_API size_t aws_rsa_key_pair_block_length(const struct aws_rsa_key_pair *key_pair);
111
+
112
+ /**
113
+ * Uses the key_pair's private key to sign message. The output will be in out. out must be large enough
114
+ * to hold the signature. Check aws_rsa_key_pair_signature_length() for the appropriate size.
115
+ *
116
+ * It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually
117
+ * something like a SHA256.
118
+ */
119
+ AWS_CAL_API int aws_rsa_key_pair_sign_message(
120
+ const struct aws_rsa_key_pair *key_pair,
121
+ enum aws_rsa_signature_algorithm algorithm,
122
+ struct aws_byte_cursor digest,
123
+ struct aws_byte_buf *out);
124
+
125
+ /**
126
+ * Uses the key_pair's public key to verify signature of message.
127
+ *
128
+ * It is the callers job to make sure message is the appropriate cryptographic digest for this operation. It's usually
129
+ * something like a SHA256.
130
+ *
131
+ * returns AWS_OP_SUCCESS if the signature is valid.
132
+ * raises AWS_ERROR_CAL_SIGNATURE_VALIDATION_FAILED if signature validation failed
133
+ */
134
+ AWS_CAL_API int aws_rsa_key_pair_verify_signature(
135
+ const struct aws_rsa_key_pair *key_pair,
136
+ enum aws_rsa_signature_algorithm algorithm,
137
+ struct aws_byte_cursor digest,
138
+ struct aws_byte_cursor signature);
139
+
140
+ /*
141
+ * Max size for a signature supported by a given key pair.
142
+ */
143
+ AWS_CAL_API size_t aws_rsa_key_pair_signature_length(const struct aws_rsa_key_pair *key_pair);
144
+
145
+ enum aws_rsa_key_export_format {
146
+ AWS_CAL_RSA_KEY_EXPORT_PKCS1,
147
+ };
148
+
149
+ /*
150
+ * Get public key for the key pair.
151
+ * Inits out to a copy of key.
152
+ * Any encoding on top of that (ex. b64) is left up to user.
153
+ * Note: this function is currently not supported on windows for generated keys.
154
+ */
155
+ AWS_CAL_API int aws_rsa_key_pair_get_public_key(
156
+ const struct aws_rsa_key_pair *key_pair,
157
+ enum aws_rsa_key_export_format format,
158
+ struct aws_byte_buf *out);
159
+
160
+ /*
161
+ * Get private key for the key pair.
162
+ * Inits out to a copy of key.
163
+ * Any encoding on top of that (ex. b64) is left up to user.
164
+ * Note: this function is currently not supported on Windows for generated keys.
165
+ */
166
+ AWS_CAL_API int aws_rsa_key_pair_get_private_key(
167
+ const struct aws_rsa_key_pair *key_pair,
168
+ enum aws_rsa_key_export_format format,
169
+ struct aws_byte_buf *out);
170
+
171
+ AWS_EXTERN_C_END
172
+
173
+ AWS_POP_SANE_WARNING_LEVEL
174
+
175
+ #endif /* AWS_CAL_RSA_H */
include/aws/cal/symmetric_cipher.h ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_CAL_SYMMETRIC_CIPHER_H
2
+ #define AWS_CAL_SYMMETRIC_CIPHER_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/cal/cal.h>
8
+ #include <aws/common/byte_buf.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ #define AWS_AES_256_CIPHER_BLOCK_SIZE 16
13
+ #define AWS_AES_256_KEY_BIT_LEN 256
14
+ #define AWS_AES_256_KEY_BYTE_LEN (AWS_AES_256_KEY_BIT_LEN / 8)
15
+
16
+ struct aws_symmetric_cipher;
17
+
18
+ typedef struct aws_symmetric_cipher *(aws_aes_cbc_256_new_fn)(struct aws_allocator *allocator,
19
+ const struct aws_byte_cursor *key,
20
+ const struct aws_byte_cursor *iv);
21
+
22
+ typedef struct aws_symmetric_cipher *(aws_aes_ctr_256_new_fn)(struct aws_allocator *allocator,
23
+ const struct aws_byte_cursor *key,
24
+ const struct aws_byte_cursor *iv);
25
+
26
+ typedef struct aws_symmetric_cipher *(aws_aes_gcm_256_new_fn)(struct aws_allocator *allocator,
27
+ const struct aws_byte_cursor *key,
28
+ const struct aws_byte_cursor *iv,
29
+ const struct aws_byte_cursor *aad);
30
+
31
+ typedef struct aws_symmetric_cipher *(aws_aes_keywrap_256_new_fn)(struct aws_allocator *allocator,
32
+ const struct aws_byte_cursor *key);
33
+
34
+ enum aws_symmetric_cipher_state {
35
+ AWS_SYMMETRIC_CIPHER_READY,
36
+ AWS_SYMMETRIC_CIPHER_FINALIZED,
37
+ AWS_SYMMETRIC_CIPHER_ERROR,
38
+ };
39
+
40
+ AWS_EXTERN_C_BEGIN
41
+
42
+ /**
43
+ * Creates an instance of AES CBC with 256-bit key.
44
+ * If key and iv are NULL, they will be generated internally.
45
+ * You can get the generated key and iv back by calling:
46
+ *
47
+ * aws_symmetric_cipher_get_key() and
48
+ * aws_symmetric_cipher_get_initialization_vector()
49
+ *
50
+ * respectively.
51
+ *
52
+ * If they are set, that key and iv will be copied internally and used by the cipher.
53
+ *
54
+ * Returns NULL on failure. You can check aws_last_error() to get the error code indicating the failure cause.
55
+ */
56
+ AWS_CAL_API struct aws_symmetric_cipher *aws_aes_cbc_256_new(
57
+ struct aws_allocator *allocator,
58
+ const struct aws_byte_cursor *key,
59
+ const struct aws_byte_cursor *iv);
60
+
61
+ /**
62
+ * Creates an instance of AES CTR with 256-bit key.
63
+ * If key and iv are NULL, they will be generated internally.
64
+ * You can get the generated key and iv back by calling:
65
+ *
66
+ * aws_symmetric_cipher_get_key() and
67
+ * aws_symmetric_cipher_get_initialization_vector()
68
+ *
69
+ * respectively.
70
+ *
71
+ * If they are set, that key and iv will be copied internally and used by the cipher.
72
+ *
73
+ * Returns NULL on failure. You can check aws_last_error() to get the error code indicating the failure cause.
74
+ */
75
+ AWS_CAL_API struct aws_symmetric_cipher *aws_aes_ctr_256_new(
76
+ struct aws_allocator *allocator,
77
+ const struct aws_byte_cursor *key,
78
+ const struct aws_byte_cursor *iv);
79
+
80
+ /**
81
+ * Creates an instance of AES GCM with 256-bit key.
82
+ * If key, iv are NULL, they will be generated internally.
83
+ * You can get the generated key and iv back by calling:
84
+ *
85
+ * aws_symmetric_cipher_get_key() and
86
+ * aws_symmetric_cipher_get_initialization_vector()
87
+ *
88
+ * respectively.
89
+ *
90
+ * If aad is set it will be copied and applied to the cipher.
91
+ *
92
+ * If they are set, that key and iv will be copied internally and used by the cipher.
93
+ *
94
+ * For decryption purposes tag can be provided via aws_symmetric_cipher_set_tag method.
95
+ * Note: for decrypt operations, tag must be provided before first decrypt is called.
96
+ * (this is a windows bcrypt limitations, but for consistency sake same limitation is extended to other platforms)
97
+ * Tag generated during encryption can be retrieved using aws_symmetric_cipher_get_tag method
98
+ * after finalize is called.
99
+ *
100
+ * Returns NULL on failure. You can check aws_last_error() to get the error code indicating the failure cause.
101
+ */
102
+ AWS_CAL_API struct aws_symmetric_cipher *aws_aes_gcm_256_new(
103
+ struct aws_allocator *allocator,
104
+ const struct aws_byte_cursor *key,
105
+ const struct aws_byte_cursor *iv,
106
+ const struct aws_byte_cursor *aad);
107
+
108
+ /**
109
+ * Creates an instance of AES Keywrap with 256-bit key.
110
+ * If key is NULL, it will be generated internally.
111
+ * You can get the generated key back by calling:
112
+ *
113
+ * aws_symmetric_cipher_get_key()
114
+ *
115
+ * If key is set, that key will be copied internally and used by the cipher.
116
+ *
117
+ * Returns NULL on failure. You can check aws_last_error() to get the error code indicating the failure cause.
118
+ */
119
+ AWS_CAL_API struct aws_symmetric_cipher *aws_aes_keywrap_256_new(
120
+ struct aws_allocator *allocator,
121
+ const struct aws_byte_cursor *key);
122
+
123
+ /**
124
+ * Cleans up internal resources and state for cipher and then deallocates it.
125
+ */
126
+ AWS_CAL_API void aws_symmetric_cipher_destroy(struct aws_symmetric_cipher *cipher);
127
+
128
+ /**
129
+ * Encrypts the value in to_encrypt and writes the encrypted data into out.
130
+ * If out is dynamic it will be expanded. If it is not, and out is not large enough to handle
131
+ * the encrypted output, the call will fail. If you're trying to optimize to use a stack based array
132
+ * or something, make sure it's at least as large as the size of to_encrypt + an extra BLOCK to account for
133
+ * padding etc...
134
+ *
135
+ * returns AWS_OP_SUCCESS on success. Call aws_last_error() to determine the failure cause if it returns
136
+ * AWS_OP_ERR;
137
+ */
138
+ AWS_CAL_API int aws_symmetric_cipher_encrypt(
139
+ struct aws_symmetric_cipher *cipher,
140
+ struct aws_byte_cursor to_encrypt,
141
+ struct aws_byte_buf *out);
142
+
143
+ /**
144
+ * Decrypts the value in to_decrypt and writes the decrypted data into out.
145
+ * If out is dynamic it will be expanded. If it is not, and out is not large enough to handle
146
+ * the decrypted output, the call will fail. If you're trying to optimize to use a stack based array
147
+ * or something, make sure it's at least as large as the size of to_decrypt + an extra BLOCK to account for
148
+ * padding etc...
149
+ *
150
+ * returns AWS_OP_SUCCESS on success. Call aws_last_error() to determine the failure cause if it returns
151
+ * AWS_OP_ERR;
152
+ */
153
+ AWS_CAL_API int aws_symmetric_cipher_decrypt(
154
+ struct aws_symmetric_cipher *cipher,
155
+ struct aws_byte_cursor to_decrypt,
156
+ struct aws_byte_buf *out);
157
+
158
+ /**
159
+ * Encrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any
160
+ * writes any remaining encrypted data to out. If out is dynamic it will be expanded. If it is not, and
161
+ * out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize
162
+ * to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for
163
+ * padding etc...
164
+ *
165
+ * After invoking this function, you MUST call aws_symmetric_cipher_reset() before invoking any encrypt/decrypt
166
+ * operations on this cipher again.
167
+ *
168
+ * returns AWS_OP_SUCCESS on success. Call aws_last_error() to determine the failure cause if it returns
169
+ * AWS_OP_ERR;
170
+ */
171
+ AWS_CAL_API int aws_symmetric_cipher_finalize_encryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out);
172
+
173
+ /**
174
+ * Decrypts any remaining data that was reserved for final padding, loads GMACs etc... and if there is any
175
+ * writes any remaining decrypted data to out. If out is dynamic it will be expanded. If it is not, and
176
+ * out is not large enough to handle the decrypted output, the call will fail. If you're trying to optimize
177
+ * to use a stack based array or something, make sure it's at least as large as the size of 2 BLOCKs to account for
178
+ * padding etc...
179
+ *
180
+ * After invoking this function, you MUST call aws_symmetric_cipher_reset() before invoking any encrypt/decrypt
181
+ * operations on this cipher again.
182
+ *
183
+ * returns AWS_OP_SUCCESS on success. Call aws_last_error() to determine the failure cause if it returns
184
+ * AWS_OP_ERR;
185
+ */
186
+ AWS_CAL_API int aws_symmetric_cipher_finalize_decryption(struct aws_symmetric_cipher *cipher, struct aws_byte_buf *out);
187
+
188
+ /**
189
+ * Resets the cipher state for starting a new encrypt or decrypt operation. Note encrypt/decrypt cannot be mixed on the
190
+ * same cipher without a call to reset in between them. However, this leaves the key, iv etc... materials setup for
191
+ * immediate reuse.
192
+ * Note: GCM tag is not preserved between operations. If you intend to do encrypt followed directly by decrypt, make
193
+ * sure to make a copy of tag before reseting the cipher and pass that copy for decryption.
194
+ *
195
+ * Warning: In most cases it's a really bad idea to reset a cipher and perform another operation using that cipher.
196
+ * Key and IV should not be reused for different operations. Instead of reseting the cipher, destroy the cipher
197
+ * and create new one with a new key/iv pair. Use reset at your own risk, and only after careful consideration.
198
+ *
199
+ * returns AWS_OP_SUCCESS on success. Call aws_last_error() to determine the failure cause if it returns
200
+ * AWS_OP_ERR;
201
+ */
202
+ AWS_CAL_API int aws_symmetric_cipher_reset(struct aws_symmetric_cipher *cipher);
203
+
204
+ /**
205
+ * Gets the current GMAC tag. If not AES GCM, this function will just return an empty cursor.
206
+ * The memory in this cursor is unsafe as it refers to the internal buffer.
207
+ * This was done because the use case doesn't require fetching these during an
208
+ * encryption or decryption operation and it dramatically simplifies the API.
209
+ * Only use this function between other calls to this API as any function call can alter the value of this tag.
210
+ *
211
+ * If you need to access it in a different pattern, copy the values to your own buffer first.
212
+ */
213
+ AWS_CAL_API struct aws_byte_cursor aws_symmetric_cipher_get_tag(const struct aws_symmetric_cipher *cipher);
214
+
215
+ /**
216
+ * Sets the GMAC tag on the cipher. Does nothing for ciphers that do not support tag.
217
+ */
218
+ AWS_CAL_API void aws_symmetric_cipher_set_tag(struct aws_symmetric_cipher *cipher, struct aws_byte_cursor tag);
219
+
220
+ /**
221
+ * Gets the original initialization vector as a cursor.
222
+ * The memory in this cursor is unsafe as it refers to the internal buffer.
223
+ * This was done because the use case doesn't require fetching these during an
224
+ * encryption or decryption operation and it dramatically simplifies the API.
225
+ *
226
+ * Unlike some other fields, this value does not change after the inital construction of the cipher.
227
+ *
228
+ * For some algorithms, such as AES Keywrap, this will return an empty cursor.
229
+ */
230
+ AWS_CAL_API struct aws_byte_cursor aws_symmetric_cipher_get_initialization_vector(
231
+ const struct aws_symmetric_cipher *cipher);
232
+
233
+ /**
234
+ * Gets the original key.
235
+ *
236
+ * The memory in this cursor is unsafe as it refers to the internal buffer.
237
+ * This was done because the use case doesn't require fetching these during an
238
+ * encryption or decryption operation and it dramatically simplifies the API.
239
+ *
240
+ * Unlike some other fields, this value does not change after the inital construction of the cipher.
241
+ */
242
+ AWS_CAL_API struct aws_byte_cursor aws_symmetric_cipher_get_key(const struct aws_symmetric_cipher *cipher);
243
+
244
+ /**
245
+ * Returns true if the state of the cipher is good, and otherwise returns false.
246
+ * Most operations, other than aws_symmetric_cipher_reset() will fail if this function is returning false.
247
+ * aws_symmetric_cipher_reset() will reset the state to a good state if possible.
248
+ */
249
+ AWS_CAL_API bool aws_symmetric_cipher_is_good(const struct aws_symmetric_cipher *cipher);
250
+
251
+ /**
252
+ * Retuns the current state of the cipher. Ther state of the cipher can be ready for use, finalized, or has encountered
253
+ * an error. if the cipher is in a finished or error state, it must be reset before further use.
254
+ */
255
+ AWS_CAL_API enum aws_symmetric_cipher_state aws_symmetric_cipher_get_state(const struct aws_symmetric_cipher *cipher);
256
+
257
+ AWS_EXTERN_C_END
258
+ AWS_POP_SANE_WARNING_LEVEL
259
+ #endif /* AWS_CAL_SYMMETRIC_CIPHER_H */
include/aws/common/allocator.h ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ALLOCATOR_H
2
+ #define AWS_COMMON_ALLOCATOR_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/macros.h>
9
+ #include <aws/common/stdbool.h>
10
+ #include <aws/common/stdint.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+ AWS_EXTERN_C_BEGIN
14
+
15
+ /*
16
+ * Quick guide to allocators:
17
+ * CRT offers several flavours of allocators:
18
+ * - default: basic allocator that invokes system one directly.
19
+ * - aligned: basic allocator that aligns small allocations on 8 byte
20
+ * boundary and big buffers on 32/64 byte (system dependent) boundary.
21
+ * Aligned mem can improve perf on some operations, like memcpy or hashes.
22
+ * Depending on a system, can result in higher peak memory count in heavy
23
+ * acquire/free scenarios (ex. s3), due to memory fragmentation related to how
24
+ * aligned allocators work (over allocate, find aligned offset, release extra memory)
25
+ * - wrapped_cf: wraps MacOS's Security Framework allocator.
26
+ * - mem_tracer: wraps any allocator and provides tracing functionality to allocations
27
+ * - small_block_allocator: pools smaller allocations into preallocated buckets.
28
+ * Not actively maintained. Avoid if possible.
29
+ */
30
+
31
+ /* Allocator structure. An instance of this will be passed around for anything needing memory allocation */
32
+ struct aws_allocator {
33
+ void *(*mem_acquire)(struct aws_allocator *allocator, size_t size);
34
+ void (*mem_release)(struct aws_allocator *allocator, void *ptr);
35
+ /* Optional method; if not supported, this pointer must be NULL */
36
+ void *(*mem_realloc)(struct aws_allocator *allocator, void *oldptr, size_t oldsize, size_t newsize);
37
+ /* Optional method; if not supported, this pointer must be NULL */
38
+ void *(*mem_calloc)(struct aws_allocator *allocator, size_t num, size_t size);
39
+ void *impl;
40
+ };
41
+
42
+ /**
43
+ * Inexpensive (constant time) check of data-structure invariants.
44
+ */
45
+ AWS_COMMON_API
46
+ bool aws_allocator_is_valid(const struct aws_allocator *alloc);
47
+
48
+ AWS_COMMON_API
49
+ struct aws_allocator *aws_default_allocator(void);
50
+
51
+ /*
52
+ * Allocator that align small allocations on 8 byte boundary and big allocations
53
+ * on 32/64 byte boundary.
54
+ */
55
+ AWS_COMMON_API
56
+ struct aws_allocator *aws_aligned_allocator(void);
57
+
58
+ #ifdef __MACH__
59
+ /* Avoid pulling in CoreFoundation headers in a header file. */
60
+ struct __CFAllocator; /* NOLINT(bugprone-reserved-identifier) */
61
+ typedef const struct __CFAllocator *CFAllocatorRef;
62
+
63
+ /**
64
+ * Wraps a CFAllocator around aws_allocator. For Mac only. Use this anytime you need a CFAllocatorRef for interacting
65
+ * with Apple Frameworks. Unfortunately, it allocates memory so we can't make it static file scope, be sure to call
66
+ * aws_wrapped_cf_allocator_destroy when finished.
67
+ */
68
+ AWS_COMMON_API
69
+ CFAllocatorRef aws_wrapped_cf_allocator_new(struct aws_allocator *allocator);
70
+
71
+ /**
72
+ * Cleans up any resources alloced in aws_wrapped_cf_allocator_new.
73
+ */
74
+ AWS_COMMON_API
75
+ void aws_wrapped_cf_allocator_destroy(CFAllocatorRef allocator);
76
+ #endif
77
+
78
+ /**
79
+ * Returns at least `size` of memory ready for usage. In versions v0.6.8 and prior, this function was allowed to return
80
+ * NULL. In later versions, if allocator->mem_acquire() returns NULL, this function will assert and exit. To handle
81
+ * conditions where OOM is not a fatal error, allocator->mem_acquire() is responsible for finding/reclaiming/running a
82
+ * GC etc...before returning.
83
+ */
84
+ AWS_COMMON_API
85
+ void *aws_mem_acquire(struct aws_allocator *allocator, size_t size);
86
+
87
+ /**
88
+ * Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits
89
+ * to zero. In versions v0.6.8 and prior, this function was allowed to return NULL.
90
+ * In later versions, if allocator->mem_calloc() returns NULL, this function will assert and exit. To handle
91
+ * conditions where OOM is not a fatal error, allocator->mem_calloc() is responsible for finding/reclaiming/running a
92
+ * GC etc...before returning.
93
+ */
94
+ AWS_COMMON_API
95
+ void *aws_mem_calloc(struct aws_allocator *allocator, size_t num, size_t size);
96
+
97
+ /**
98
+ * Allocates many chunks of bytes into a single block. Expects to be called with alternating void ** (dest), size_t
99
+ * (size). The first void ** will be set to the root of the allocation. Alignment is assumed to be sizeof(intmax_t).
100
+ *
101
+ * This is useful for allocating structs using the pimpl pattern, as you may allocate the public object and impl object
102
+ * in the same contiguous block of memory.
103
+ *
104
+ * Returns a pointer to the allocation.
105
+ *
106
+ * In versions v0.6.8 and prior, this function was allowed to return
107
+ * NULL. In later versions, if allocator->mem_acquire() returns NULL, this function will assert and exit. To handle
108
+ * conditions where OOM is not a fatal error, allocator->mem_acquire() is responsible for finding/reclaiming/running a
109
+ * GC etc...before returning.
110
+ */
111
+ AWS_COMMON_API
112
+ void *aws_mem_acquire_many(struct aws_allocator *allocator, size_t count, ...);
113
+
114
+ /**
115
+ * Releases ptr back to whatever allocated it.
116
+ * Nothing happens if ptr is NULL.
117
+ */
118
+ AWS_COMMON_API
119
+ void aws_mem_release(struct aws_allocator *allocator, void *ptr);
120
+
121
+ /**
122
+ * Attempts to adjust the size of the pointed-to memory buffer from oldsize to
123
+ * newsize. The pointer (*ptr) may be changed if the memory needs to be
124
+ * reallocated.
125
+ *
126
+ * In versions v0.6.8 and prior, this function was allowed to return
127
+ * NULL. In later versions, if allocator->mem_realloc() returns NULL, this function will assert and exit. To handle
128
+ * conditions where OOM is not a fatal error, allocator->mem_realloc() is responsible for finding/reclaiming/running a
129
+ * GC etc...before returning.
130
+ */
131
+ AWS_COMMON_API
132
+ int aws_mem_realloc(struct aws_allocator *allocator, void **ptr, size_t oldsize, size_t newsize);
133
+ /*
134
+ * Maintainer note: The above function doesn't return the pointer (as with
135
+ * standard C realloc) as this pattern becomes error-prone when OOMs occur.
136
+ * In particular, we want to avoid losing the old pointer when an OOM condition
137
+ * occurs, so we prefer to take the old pointer as an in/out reference argument
138
+ * that we can leave unchanged on failure.
139
+ */
140
+
141
+ enum aws_mem_trace_level {
142
+ AWS_MEMTRACE_NONE = 0, /* no tracing */
143
+ AWS_MEMTRACE_BYTES = 1, /* just track allocation sizes and total allocated */
144
+ AWS_MEMTRACE_STACKS = 2, /* capture callstacks for each allocation */
145
+ };
146
+
147
+ /*
148
+ * Wraps an allocator and tracks all external allocations. If aws_mem_trace_dump() is called
149
+ * and there are still allocations active, they will be reported to the aws_logger at TRACE level.
150
+ * allocator - The allocator to wrap
151
+ * deprecated - Deprecated arg, ignored.
152
+ * level - The level to track allocations at
153
+ * frames_per_stack is how many frames to store per callstack if AWS_MEMTRACE_STACKS is in use,
154
+ * otherwise it is ignored. 8 tends to be a pretty good number balancing storage space vs useful stacks.
155
+ * Returns the tracer allocator, which should be used for all allocations that should be tracked.
156
+ */
157
+ AWS_COMMON_API
158
+ struct aws_allocator *aws_mem_tracer_new(
159
+ struct aws_allocator *allocator,
160
+ struct aws_allocator *deprecated,
161
+ enum aws_mem_trace_level level,
162
+ size_t frames_per_stack);
163
+
164
+ /*
165
+ * Unwraps the traced allocator and cleans up the tracer.
166
+ * Returns the original allocator
167
+ */
168
+ AWS_COMMON_API
169
+ struct aws_allocator *aws_mem_tracer_destroy(struct aws_allocator *trace_allocator);
170
+
171
+ /*
172
+ * If there are outstanding allocations, dumps them to log, along with any information gathered
173
+ * based on the trace level set when aws_mem_trace() was called.
174
+ * Should be passed the tracer allocator returned from aws_mem_trace().
175
+ */
176
+ AWS_COMMON_API
177
+ void aws_mem_tracer_dump(struct aws_allocator *trace_allocator);
178
+
179
+ /*
180
+ * Returns the current number of bytes in outstanding allocations
181
+ */
182
+ AWS_COMMON_API
183
+ size_t aws_mem_tracer_bytes(struct aws_allocator *trace_allocator);
184
+
185
+ /*
186
+ * Returns the current number of outstanding allocations
187
+ */
188
+ AWS_COMMON_API
189
+ size_t aws_mem_tracer_count(struct aws_allocator *trace_allocator);
190
+
191
+ /*
192
+ * Creates a new Small Block Allocator which fronts the supplied parent allocator. The SBA will intercept
193
+ * and handle small allocs, and will forward anything larger to the parent allocator.
194
+ * If multi_threaded is true, the internal allocator will protect its internal data structures with a mutex
195
+ */
196
+ AWS_COMMON_API
197
+ struct aws_allocator *aws_small_block_allocator_new(struct aws_allocator *allocator, bool multi_threaded);
198
+
199
+ /*
200
+ * Destroys a Small Block Allocator instance and frees its memory to the parent allocator. The parent
201
+ * allocator will otherwise be unaffected.
202
+ */
203
+ AWS_COMMON_API
204
+ void aws_small_block_allocator_destroy(struct aws_allocator *sba_allocator);
205
+
206
+ /*
207
+ * Returns the number of bytes currently active in the SBA
208
+ */
209
+ AWS_COMMON_API
210
+ size_t aws_small_block_allocator_bytes_active(struct aws_allocator *sba_allocator);
211
+
212
+ /*
213
+ * Returns the number of bytes reserved in pages/bins inside the SBA, e.g. the
214
+ * current system memory used by the SBA
215
+ */
216
+ AWS_COMMON_API
217
+ size_t aws_small_block_allocator_bytes_reserved(struct aws_allocator *sba_allocator);
218
+
219
+ /*
220
+ * Returns the page size that the SBA is using
221
+ */
222
+ AWS_COMMON_API
223
+ size_t aws_small_block_allocator_page_size(struct aws_allocator *sba_allocator);
224
+
225
+ /*
226
+ * Returns the amount of memory in each page available to user allocations
227
+ */
228
+ AWS_COMMON_API
229
+ size_t aws_small_block_allocator_page_size_available(struct aws_allocator *sba_allocator);
230
+
231
+ AWS_EXTERN_C_END
232
+ AWS_POP_SANE_WARNING_LEVEL
233
+
234
+ #endif /* AWS_COMMON_ALLOCATOR_H */
include/aws/common/array_list.h ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ARRAY_LIST_H
2
+ #define AWS_COMMON_ARRAY_LIST_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+ #include <aws/common/common.h>
9
+ #include <aws/common/math.h>
10
+
11
+ #include <stdlib.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ enum { AWS_ARRAY_LIST_DEBUG_FILL = 0xDD };
16
+
17
+ struct aws_array_list {
18
+ struct aws_allocator *alloc;
19
+ size_t current_size;
20
+ size_t length;
21
+ size_t item_size;
22
+ void *data;
23
+ };
24
+
25
+ /**
26
+ * Prototype for a comparator function for sorting elements.
27
+ *
28
+ * a and b should be cast to pointers to the element type held in the list
29
+ * before being dereferenced. The function should compare the elements and
30
+ * return a positive number if a > b, zero if a = b, and a negative number
31
+ * if a < b.
32
+ */
33
+ typedef int(aws_array_list_comparator_fn)(const void *a, const void *b);
34
+
35
+ AWS_EXTERN_C_BEGIN
36
+
37
+ /**
38
+ * Initializes an array list with an array of size initial_item_allocation * item_size. In this mode, the array size
39
+ * will grow by a factor of 2 upon insertion if space is not available. initial_item_allocation is the number of
40
+ * elements you want space allocated for. item_size is the size of each element in bytes. Mixing items types is not
41
+ * supported by this API.
42
+ */
43
+ AWS_STATIC_IMPL
44
+ int aws_array_list_init_dynamic(
45
+ struct aws_array_list *AWS_RESTRICT list,
46
+ struct aws_allocator *alloc,
47
+ size_t initial_item_allocation,
48
+ size_t item_size);
49
+
50
+ /**
51
+ * Initializes an array list with a preallocated array of void *. item_count is the number of elements in the array,
52
+ * and item_size is the size in bytes of each element. Mixing items types is not supported
53
+ * by this API. Once this list is full, new items will be rejected.
54
+ */
55
+ AWS_STATIC_IMPL
56
+ void aws_array_list_init_static(
57
+ struct aws_array_list *AWS_RESTRICT list,
58
+ void *raw_array,
59
+ size_t item_count,
60
+ size_t item_size);
61
+
62
+ /**
63
+ * Initializes an array list with a preallocated array of *already-initialized* elements. item_count is the number of
64
+ * elements in the array, and item_size is the size in bytes of each element.
65
+ *
66
+ * Once initialized, nothing further can be added to the list, since it will be full and cannot resize.
67
+ *
68
+ * Primary use case is to treat an already-initialized C array as an array list.
69
+ */
70
+ AWS_STATIC_IMPL
71
+ void aws_array_list_init_static_from_initialized(
72
+ struct aws_array_list *AWS_RESTRICT list,
73
+ void *raw_array,
74
+ size_t item_count,
75
+ size_t item_size);
76
+
77
+ /**
78
+ * Set of properties of a valid aws_array_list.
79
+ */
80
+ AWS_STATIC_IMPL
81
+ bool aws_array_list_is_valid(const struct aws_array_list *AWS_RESTRICT list);
82
+
83
+ /**
84
+ * Deallocates any memory that was allocated for this list, and resets list for reuse or deletion.
85
+ */
86
+ AWS_STATIC_IMPL
87
+ void aws_array_list_clean_up(struct aws_array_list *AWS_RESTRICT list);
88
+
89
+ /**
90
+ * Erases and then deallocates any memory that was allocated for this list, and resets list for reuse or deletion.
91
+ */
92
+ AWS_STATIC_IMPL
93
+ void aws_array_list_clean_up_secure(struct aws_array_list *AWS_RESTRICT list);
94
+
95
+ /**
96
+ * Pushes the memory pointed to by val onto the end of internal list
97
+ */
98
+ AWS_STATIC_IMPL
99
+ int aws_array_list_push_back(struct aws_array_list *AWS_RESTRICT list, const void *val);
100
+
101
+ /**
102
+ * Copies the element at the front of the list if it exists. If list is empty, AWS_ERROR_LIST_EMPTY will be raised
103
+ */
104
+ AWS_STATIC_IMPL
105
+ int aws_array_list_front(const struct aws_array_list *AWS_RESTRICT list, void *val);
106
+
107
+ /**
108
+ * Pushes the memory pointed to by val onto the front of internal list.
109
+ * This call results in shifting all of the elements in the list. Avoid this call unless that
110
+ * is intended behavior.
111
+ */
112
+ AWS_STATIC_IMPL
113
+ int aws_array_list_push_front(struct aws_array_list *AWS_RESTRICT list, const void *val);
114
+
115
+ /**
116
+ * Deletes the element at the front of the list if it exists. If list is empty, AWS_ERROR_LIST_EMPTY will be raised.
117
+ * This call results in shifting all of the elements at the end of the array to the front. Avoid this call unless that
118
+ * is intended behavior.
119
+ */
120
+ AWS_STATIC_IMPL
121
+ int aws_array_list_pop_front(struct aws_array_list *AWS_RESTRICT list);
122
+
123
+ /**
124
+ * Delete N elements from the front of the list.
125
+ * Remaining elements are shifted to the front of the list.
126
+ * If the list has less than N elements, the list is cleared.
127
+ * This call is more efficient than calling aws_array_list_pop_front() N times.
128
+ */
129
+ AWS_STATIC_IMPL
130
+ void aws_array_list_pop_front_n(struct aws_array_list *AWS_RESTRICT list, size_t n);
131
+
132
+ /**
133
+ * Deletes the element this index in the list if it exists.
134
+ * If element does not exist, AWS_ERROR_INVALID_INDEX will be raised.
135
+ * This call results in shifting all remaining elements towards the front.
136
+ * Avoid this call unless that is intended behavior.
137
+ */
138
+ AWS_STATIC_IMPL
139
+ int aws_array_list_erase(struct aws_array_list *AWS_RESTRICT list, size_t index);
140
+
141
+ /**
142
+ * Copies the element at the end of the list if it exists. If list is empty, AWS_ERROR_LIST_EMPTY will be raised.
143
+ */
144
+ AWS_STATIC_IMPL
145
+ int aws_array_list_back(const struct aws_array_list *AWS_RESTRICT list, void *val);
146
+
147
+ /**
148
+ * Deletes the element at the end of the list if it exists. If list is empty, AWS_ERROR_LIST_EMPTY will be raised.
149
+ */
150
+ AWS_STATIC_IMPL
151
+ int aws_array_list_pop_back(struct aws_array_list *AWS_RESTRICT list);
152
+
153
+ /**
154
+ * Clears all elements in the array and resets length to zero. Size does not change in this operation.
155
+ */
156
+ AWS_STATIC_IMPL
157
+ void aws_array_list_clear(struct aws_array_list *AWS_RESTRICT list);
158
+
159
+ /**
160
+ * If in dynamic mode, shrinks the allocated array size to the minimum amount necessary to store its elements.
161
+ */
162
+ AWS_COMMON_API
163
+ int aws_array_list_shrink_to_fit(struct aws_array_list *AWS_RESTRICT list);
164
+
165
+ /**
166
+ * Copies the elements from from to to. If to is in static mode, it must at least be the same length as from. Any data
167
+ * in to will be overwritten in this copy.
168
+ */
169
+ AWS_COMMON_API
170
+ int aws_array_list_copy(const struct aws_array_list *AWS_RESTRICT from, struct aws_array_list *AWS_RESTRICT to);
171
+
172
+ /**
173
+ * Swap contents between two dynamic lists. Both lists must use the same allocator.
174
+ */
175
+ AWS_STATIC_IMPL
176
+ void aws_array_list_swap_contents(
177
+ struct aws_array_list *AWS_RESTRICT list_a,
178
+ struct aws_array_list *AWS_RESTRICT list_b);
179
+
180
+ /**
181
+ * Returns the number of elements that can fit in the internal array. If list is initialized in dynamic mode,
182
+ * the capacity changes over time.
183
+ */
184
+ AWS_STATIC_IMPL
185
+ size_t aws_array_list_capacity(const struct aws_array_list *AWS_RESTRICT list);
186
+
187
+ /**
188
+ * Returns the number of elements in the internal array.
189
+ */
190
+ AWS_STATIC_IMPL
191
+ size_t aws_array_list_length(const struct aws_array_list *AWS_RESTRICT list);
192
+
193
+ /**
194
+ * Copies the memory at index to val. If element does not exist, AWS_ERROR_INVALID_INDEX will be raised.
195
+ */
196
+ AWS_STATIC_IMPL
197
+ int aws_array_list_get_at(const struct aws_array_list *AWS_RESTRICT list, void *val, size_t index);
198
+
199
+ /**
200
+ * Copies the memory address of the element at index to *val. If element does not exist, AWS_ERROR_INVALID_INDEX will be
201
+ * raised.
202
+ */
203
+ AWS_STATIC_IMPL
204
+ int aws_array_list_get_at_ptr(const struct aws_array_list *AWS_RESTRICT list, void **val, size_t index);
205
+
206
+ /**
207
+ * Ensures that the array list has enough capacity to store a value at the specified index. If there is not already
208
+ * enough capacity, and the list is in dynamic mode, this function will attempt to allocate more memory, expanding the
209
+ * list. In static mode, if 'index' is beyond the maximum index, AWS_ERROR_INVALID_INDEX will be raised.
210
+ */
211
+ AWS_COMMON_API
212
+ int aws_array_list_ensure_capacity(struct aws_array_list *AWS_RESTRICT list, size_t index);
213
+
214
+ /**
215
+ * Copies the the memory pointed to by val into the array at index. If in dynamic mode, the size will grow by a factor
216
+ * of two when the array is full. In static mode, AWS_ERROR_INVALID_INDEX will be raised if the index is past the bounds
217
+ * of the array.
218
+ */
219
+ AWS_STATIC_IMPL
220
+ int aws_array_list_set_at(struct aws_array_list *AWS_RESTRICT list, const void *val, size_t index);
221
+
222
+ /**
223
+ * Swap elements at the specified indices, which must be within the bounds of the array.
224
+ */
225
+ AWS_COMMON_API
226
+ void aws_array_list_swap(struct aws_array_list *AWS_RESTRICT list, size_t a, size_t b);
227
+
228
+ /**
229
+ * Sort elements in the list in-place according to the comparator function.
230
+ */
231
+ AWS_COMMON_API
232
+ void aws_array_list_sort(struct aws_array_list *AWS_RESTRICT list, aws_array_list_comparator_fn *compare_fn);
233
+
234
+ AWS_EXTERN_C_END
235
+ #ifndef AWS_NO_STATIC_IMPL
236
+ # include <aws/common/array_list.inl>
237
+ #endif /* AWS_NO_STATIC_IMPL */
238
+
239
+ AWS_POP_SANE_WARNING_LEVEL
240
+
241
+ #endif /* AWS_COMMON_ARRAY_LIST_H */
include/aws/common/array_list.inl ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ARRAY_LIST_INL
2
+ #define AWS_COMMON_ARRAY_LIST_INL
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ /* This is implicitly included, but helps with editor highlighting */
10
+ #include <aws/common/array_list.h>
11
+ /*
12
+ * Do not add system headers here; add them to array_list.h. This file is included under extern "C" guards,
13
+ * which might break system headers.
14
+ */
15
+ AWS_EXTERN_C_BEGIN
16
+
17
+ AWS_STATIC_IMPL
18
+ int aws_array_list_init_dynamic(
19
+ struct aws_array_list *AWS_RESTRICT list,
20
+ struct aws_allocator *alloc,
21
+ size_t initial_item_allocation,
22
+ size_t item_size) {
23
+
24
+ AWS_FATAL_PRECONDITION(list != NULL);
25
+ AWS_FATAL_PRECONDITION(alloc != NULL);
26
+ AWS_FATAL_PRECONDITION(item_size > 0);
27
+
28
+ AWS_ZERO_STRUCT(*list);
29
+
30
+ size_t allocation_size = 0;
31
+ if (aws_mul_size_checked(initial_item_allocation, item_size, &allocation_size)) {
32
+ goto error;
33
+ }
34
+
35
+ if (allocation_size > 0) {
36
+ list->data = aws_mem_acquire(alloc, allocation_size);
37
+ if (!list->data) {
38
+ goto error;
39
+ }
40
+ #ifdef DEBUG_BUILD
41
+ memset(list->data, AWS_ARRAY_LIST_DEBUG_FILL, allocation_size);
42
+
43
+ #endif
44
+ list->current_size = allocation_size;
45
+ }
46
+ list->item_size = item_size;
47
+ list->alloc = alloc;
48
+
49
+ AWS_FATAL_POSTCONDITION(list->current_size == 0 || list->data);
50
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
51
+ return AWS_OP_SUCCESS;
52
+
53
+ error:
54
+ AWS_POSTCONDITION(AWS_IS_ZEROED(*list));
55
+ return AWS_OP_ERR;
56
+ }
57
+
58
+ AWS_STATIC_IMPL
59
+ void aws_array_list_init_static(
60
+ struct aws_array_list *AWS_RESTRICT list,
61
+ void *raw_array,
62
+ size_t item_count,
63
+ size_t item_size) {
64
+
65
+ AWS_FATAL_PRECONDITION(list != NULL);
66
+ AWS_FATAL_PRECONDITION(raw_array != NULL);
67
+ AWS_FATAL_PRECONDITION(item_count > 0);
68
+ AWS_FATAL_PRECONDITION(item_size > 0);
69
+
70
+ AWS_ZERO_STRUCT(*list);
71
+ list->alloc = NULL;
72
+
73
+ size_t current_size = 0;
74
+ int no_overflow = !aws_mul_size_checked(item_count, item_size, &current_size);
75
+ AWS_FATAL_PRECONDITION(no_overflow);
76
+ list->current_size = current_size;
77
+
78
+ list->item_size = item_size;
79
+ list->length = 0;
80
+ list->data = raw_array;
81
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
82
+ }
83
+
84
+ AWS_STATIC_IMPL
85
+ void aws_array_list_init_static_from_initialized(
86
+ struct aws_array_list *AWS_RESTRICT list,
87
+ void *raw_array,
88
+ size_t item_count,
89
+ size_t item_size) {
90
+
91
+ aws_array_list_init_static(list, raw_array, item_count, item_size);
92
+ list->length = item_count;
93
+
94
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
95
+ }
96
+
97
+ AWS_STATIC_IMPL
98
+ bool aws_array_list_is_valid(const struct aws_array_list *AWS_RESTRICT list) {
99
+ if (!list) {
100
+ return false;
101
+ }
102
+ size_t required_size = 0;
103
+ bool required_size_is_valid =
104
+ (aws_mul_size_checked(list->length, list->item_size, &required_size) == AWS_OP_SUCCESS);
105
+ bool current_size_is_valid = (list->current_size >= required_size);
106
+ bool data_is_valid = AWS_IMPLIES(list->current_size == 0, list->data == NULL) &&
107
+ AWS_IMPLIES(list->current_size != 0, AWS_MEM_IS_WRITABLE(list->data, list->current_size));
108
+ bool item_size_is_valid = (list->item_size != 0);
109
+ return required_size_is_valid && current_size_is_valid && data_is_valid && item_size_is_valid;
110
+ }
111
+
112
+ AWS_STATIC_IMPL
113
+ void aws_array_list_clean_up(struct aws_array_list *AWS_RESTRICT list) {
114
+ AWS_PRECONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
115
+ if (list->alloc && list->data) {
116
+ aws_mem_release(list->alloc, list->data);
117
+ }
118
+
119
+ AWS_ZERO_STRUCT(*list);
120
+ }
121
+
122
+ AWS_STATIC_IMPL
123
+ void aws_array_list_clean_up_secure(struct aws_array_list *AWS_RESTRICT list) {
124
+ AWS_PRECONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
125
+ if (list->alloc && list->data) {
126
+ aws_secure_zero(list->data, list->current_size);
127
+ aws_mem_release(list->alloc, list->data);
128
+ }
129
+
130
+ AWS_ZERO_STRUCT(*list);
131
+ }
132
+
133
+ AWS_STATIC_IMPL
134
+ int aws_array_list_push_back(struct aws_array_list *AWS_RESTRICT list, const void *val) {
135
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
136
+ AWS_PRECONDITION(
137
+ val && AWS_MEM_IS_READABLE(val, list->item_size),
138
+ "Input pointer [val] must point writable memory of [list->item_size] bytes.");
139
+
140
+ int err_code = aws_array_list_set_at(list, val, aws_array_list_length(list));
141
+
142
+ if (err_code && aws_last_error() == AWS_ERROR_INVALID_INDEX && !list->alloc) {
143
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
144
+ return aws_raise_error(AWS_ERROR_LIST_EXCEEDS_MAX_SIZE);
145
+ }
146
+
147
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
148
+ return err_code;
149
+ }
150
+
151
+ AWS_STATIC_IMPL
152
+ int aws_array_list_front(const struct aws_array_list *AWS_RESTRICT list, void *val) {
153
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
154
+ AWS_PRECONDITION(
155
+ val && AWS_MEM_IS_WRITABLE(val, list->item_size),
156
+ "Input pointer [val] must point writable memory of [list->item_size] bytes.");
157
+ if (aws_array_list_length(list) > 0) {
158
+ memcpy(val, list->data, list->item_size);
159
+ AWS_POSTCONDITION(AWS_BYTES_EQ(val, list->data, list->item_size));
160
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
161
+ return AWS_OP_SUCCESS;
162
+ }
163
+
164
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
165
+ return aws_raise_error(AWS_ERROR_LIST_EMPTY);
166
+ }
167
+
168
+ AWS_STATIC_IMPL
169
+ int aws_array_list_push_front(struct aws_array_list *AWS_RESTRICT list, const void *val) {
170
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
171
+ AWS_PRECONDITION(
172
+ val && AWS_MEM_IS_READABLE(val, list->item_size),
173
+ "Input pointer [val] must point writable memory of [list->item_size] bytes.");
174
+ size_t orig_len = aws_array_list_length(list);
175
+ int err_code = aws_array_list_ensure_capacity(list, orig_len);
176
+
177
+ if (err_code && aws_last_error() == AWS_ERROR_INVALID_INDEX && !list->alloc) {
178
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
179
+ return aws_raise_error(AWS_ERROR_LIST_EXCEEDS_MAX_SIZE);
180
+ } else if (err_code) {
181
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
182
+ return err_code;
183
+ }
184
+ if (orig_len) {
185
+ memmove((uint8_t *)list->data + list->item_size, list->data, orig_len * list->item_size);
186
+ }
187
+ ++list->length;
188
+ memcpy(list->data, val, list->item_size);
189
+
190
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
191
+ return err_code;
192
+ }
193
+
194
+ AWS_STATIC_IMPL
195
+ int aws_array_list_pop_front(struct aws_array_list *AWS_RESTRICT list) {
196
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
197
+ if (aws_array_list_length(list) > 0) {
198
+ aws_array_list_pop_front_n(list, 1);
199
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
200
+ return AWS_OP_SUCCESS;
201
+ }
202
+
203
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
204
+ return aws_raise_error(AWS_ERROR_LIST_EMPTY);
205
+ }
206
+
207
+ AWS_STATIC_IMPL
208
+ void aws_array_list_pop_front_n(struct aws_array_list *AWS_RESTRICT list, size_t n) {
209
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
210
+ if (n >= aws_array_list_length(list)) {
211
+ aws_array_list_clear(list);
212
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
213
+ return;
214
+ }
215
+
216
+ if (n > 0) {
217
+ size_t popping_bytes = list->item_size * n;
218
+ size_t remaining_items = aws_array_list_length(list) - n;
219
+ size_t remaining_bytes = remaining_items * list->item_size;
220
+ memmove(list->data, (uint8_t *)list->data + popping_bytes, remaining_bytes);
221
+ list->length = remaining_items;
222
+ #ifdef DEBUG_BUILD
223
+ memset((uint8_t *)list->data + remaining_bytes, AWS_ARRAY_LIST_DEBUG_FILL, popping_bytes);
224
+ #endif
225
+ }
226
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
227
+ }
228
+
229
+ int aws_array_list_erase(struct aws_array_list *AWS_RESTRICT list, size_t index) {
230
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
231
+
232
+ const size_t length = aws_array_list_length(list);
233
+
234
+ if (index >= length) {
235
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
236
+ return aws_raise_error(AWS_ERROR_INVALID_INDEX);
237
+ }
238
+
239
+ if (index == 0) {
240
+ /* Removing front element */
241
+ aws_array_list_pop_front(list);
242
+ } else if (index == (length - 1)) {
243
+ /* Removing back element */
244
+ aws_array_list_pop_back(list);
245
+ } else {
246
+ /* Removing middle element */
247
+ uint8_t *item_ptr = (uint8_t *)list->data + (index * list->item_size);
248
+ uint8_t *next_item_ptr = item_ptr + list->item_size;
249
+ size_t trailing_items = (length - index) - 1;
250
+ size_t trailing_bytes = trailing_items * list->item_size;
251
+ memmove(item_ptr, next_item_ptr, trailing_bytes);
252
+
253
+ aws_array_list_pop_back(list);
254
+ }
255
+
256
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
257
+ return AWS_OP_SUCCESS;
258
+ }
259
+
260
+ AWS_STATIC_IMPL
261
+ int aws_array_list_back(const struct aws_array_list *AWS_RESTRICT list, void *val) {
262
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
263
+ AWS_PRECONDITION(
264
+ val && AWS_MEM_IS_WRITABLE(val, list->item_size),
265
+ "Input pointer [val] must point writable memory of [list->item_size] bytes.");
266
+ if (aws_array_list_length(list) > 0) {
267
+ size_t last_item_offset = list->item_size * (aws_array_list_length(list) - 1);
268
+
269
+ memcpy(val, (void *)((uint8_t *)list->data + last_item_offset), list->item_size);
270
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
271
+ return AWS_OP_SUCCESS;
272
+ }
273
+
274
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
275
+ return aws_raise_error(AWS_ERROR_LIST_EMPTY);
276
+ }
277
+
278
+ AWS_STATIC_IMPL
279
+ int aws_array_list_pop_back(struct aws_array_list *AWS_RESTRICT list) {
280
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
281
+ if (aws_array_list_length(list) > 0) {
282
+
283
+ AWS_FATAL_PRECONDITION(list->data);
284
+
285
+ size_t last_item_offset = list->item_size * (aws_array_list_length(list) - 1);
286
+
287
+ memset((void *)((uint8_t *)list->data + last_item_offset), 0, list->item_size);
288
+ list->length--;
289
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
290
+ return AWS_OP_SUCCESS;
291
+ }
292
+
293
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
294
+ return aws_raise_error(AWS_ERROR_LIST_EMPTY);
295
+ }
296
+
297
+ AWS_STATIC_IMPL
298
+ void aws_array_list_clear(struct aws_array_list *AWS_RESTRICT list) {
299
+ AWS_PRECONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
300
+ if (list->data) {
301
+ #ifdef DEBUG_BUILD
302
+ memset(list->data, AWS_ARRAY_LIST_DEBUG_FILL, list->current_size);
303
+ #endif
304
+ list->length = 0;
305
+ }
306
+ AWS_POSTCONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
307
+ }
308
+
309
+ AWS_STATIC_IMPL
310
+ void aws_array_list_swap_contents(
311
+ struct aws_array_list *AWS_RESTRICT list_a,
312
+ struct aws_array_list *AWS_RESTRICT list_b) {
313
+ AWS_FATAL_PRECONDITION(list_a->alloc);
314
+ AWS_FATAL_PRECONDITION(list_a->alloc == list_b->alloc);
315
+ AWS_FATAL_PRECONDITION(list_a->item_size == list_b->item_size);
316
+ AWS_FATAL_PRECONDITION(list_a != list_b);
317
+ AWS_PRECONDITION(aws_array_list_is_valid(list_a));
318
+ AWS_PRECONDITION(aws_array_list_is_valid(list_b));
319
+
320
+ struct aws_array_list tmp = *list_a;
321
+ *list_a = *list_b;
322
+ *list_b = tmp;
323
+ AWS_POSTCONDITION(aws_array_list_is_valid(list_a));
324
+ AWS_POSTCONDITION(aws_array_list_is_valid(list_b));
325
+ }
326
+
327
+ AWS_STATIC_IMPL
328
+ size_t aws_array_list_capacity(const struct aws_array_list *AWS_RESTRICT list) {
329
+ AWS_FATAL_PRECONDITION(list->item_size);
330
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
331
+ size_t capacity = list->current_size / list->item_size;
332
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
333
+ return capacity;
334
+ }
335
+
336
+ AWS_STATIC_IMPL
337
+ size_t aws_array_list_length(const struct aws_array_list *AWS_RESTRICT list) {
338
+ /*
339
+ * This assert teaches clang-tidy and friends that list->data cannot be null in a non-empty
340
+ * list.
341
+ */
342
+ AWS_FATAL_PRECONDITION(!list->length || list->data);
343
+ AWS_PRECONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
344
+ size_t len = list->length;
345
+ AWS_POSTCONDITION(AWS_IS_ZEROED(*list) || aws_array_list_is_valid(list));
346
+ return len;
347
+ }
348
+
349
+ AWS_STATIC_IMPL
350
+ int aws_array_list_get_at(const struct aws_array_list *AWS_RESTRICT list, void *val, size_t index) {
351
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
352
+ AWS_PRECONDITION(
353
+ val && AWS_MEM_IS_WRITABLE(val, list->item_size),
354
+ "Input pointer [val] must point writable memory of [list->item_size] bytes.");
355
+ if (aws_array_list_length(list) > index) {
356
+ memcpy(val, (void *)((uint8_t *)list->data + (list->item_size * index)), list->item_size);
357
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
358
+ return AWS_OP_SUCCESS;
359
+ }
360
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
361
+ return aws_raise_error(AWS_ERROR_INVALID_INDEX);
362
+ }
363
+
364
+ AWS_STATIC_IMPL
365
+ int aws_array_list_get_at_ptr(const struct aws_array_list *AWS_RESTRICT list, void **val, size_t index) {
366
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
367
+ AWS_PRECONDITION(val != NULL);
368
+ if (aws_array_list_length(list) > index) {
369
+ *val = (void *)((uint8_t *)list->data + (list->item_size * index));
370
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
371
+ return AWS_OP_SUCCESS;
372
+ }
373
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
374
+ return aws_raise_error(AWS_ERROR_INVALID_INDEX);
375
+ }
376
+
377
+ AWS_STATIC_IMPL
378
+ int aws_array_list_set_at(struct aws_array_list *AWS_RESTRICT list, const void *val, size_t index) {
379
+ AWS_PRECONDITION(aws_array_list_is_valid(list));
380
+ AWS_PRECONDITION(
381
+ val && AWS_MEM_IS_READABLE(val, list->item_size),
382
+ "Input pointer [val] must point readable memory of [list->item_size] bytes.");
383
+
384
+ if (aws_array_list_ensure_capacity(list, index)) {
385
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
386
+ return AWS_OP_ERR;
387
+ }
388
+
389
+ AWS_FATAL_PRECONDITION(list->data);
390
+
391
+ memcpy((void *)((uint8_t *)list->data + (list->item_size * index)), val, list->item_size);
392
+
393
+ /*
394
+ * This isn't perfect, but its the best I can come up with for detecting
395
+ * length changes.
396
+ */
397
+ if (index >= aws_array_list_length(list)) {
398
+ if (aws_add_size_checked(index, 1, &list->length)) {
399
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
400
+ return AWS_OP_ERR;
401
+ }
402
+ }
403
+
404
+ AWS_POSTCONDITION(aws_array_list_is_valid(list));
405
+ return AWS_OP_SUCCESS;
406
+ }
407
+
408
+ AWS_EXTERN_C_END
409
+
410
+ #endif /* AWS_COMMON_ARRAY_LIST_INL */
include/aws/common/atomics.h ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ATOMICS_H
2
+ #define AWS_COMMON_ATOMICS_H
3
+
4
+ #include <aws/common/common.h>
5
+
6
+ /**
7
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8
+ * SPDX-License-Identifier: Apache-2.0.
9
+ */
10
+
11
+ AWS_PUSH_SANE_WARNING_LEVEL
12
+
13
+ /**
14
+ * struct aws_atomic_var represents an atomic variable - a value which can hold an integer or pointer
15
+ * that can be manipulated atomically. struct aws_atomic_vars should normally only be manipulated
16
+ * with atomics methods defined in this header.
17
+ */
18
+ struct aws_atomic_var {
19
+ void *value;
20
+ };
21
+ /* Helpers for extracting the integer and pointer values from aws_atomic_var. */
22
+ #define AWS_ATOMIC_VAR_PTRVAL(var) ((var)->value)
23
+ #define AWS_ATOMIC_VAR_INTVAL(var) (*(aws_atomic_impl_int_t *)(var))
24
+
25
+ /*
26
+ * This enumeration specifies the memory ordering properties requested for a particular
27
+ * atomic operation. The atomic operation may provide stricter ordering than requested.
28
+ * Note that, within a single thread, all operations are still sequenced (that is, a thread
29
+ * sees its own atomic writes and reads happening in program order, but other threads may
30
+ * disagree on this ordering).
31
+ *
32
+ * The behavior of these memory orderings are the same as in the C11 atomics API; however,
33
+ * we only implement a subset that can be portably implemented on the compilers we target.
34
+ */
35
+
36
+ enum aws_memory_order {
37
+ /**
38
+ * No particular ordering constraints are guaranteed relative to other
39
+ * operations at all; we merely ensure that the operation itself is atomic.
40
+ */
41
+ aws_memory_order_relaxed = 0,
42
+ /* aws_memory_order_consume - not currently implemented */
43
+
44
+ /**
45
+ * Specifies acquire ordering. No reads or writes on the current thread can be
46
+ * reordered to happen before this operation. This is typically paired with a release
47
+ * ordering; any writes that happened on the releasing operation will be visible
48
+ * after the paired acquire operation.
49
+ *
50
+ * Acquire ordering is only meaningful on load or load-store operations.
51
+ */
52
+ aws_memory_order_acquire = 2, /* leave a spot for consume if we ever add it */
53
+
54
+ /**
55
+ * Specifies release order. No reads or writes can be reordered to come after this
56
+ * operation. Typically paired with an acquire operation.
57
+ *
58
+ * Release ordering is only meaningful on store or load-store operations.
59
+ */
60
+ aws_memory_order_release,
61
+
62
+ /**
63
+ * Specifies acquire-release order; if this operation acts as a load, it acts as an
64
+ * acquire operation; if it acts as a store, it acts as a release operation; if it's
65
+ * a load-store, it does both.
66
+ */
67
+ aws_memory_order_acq_rel,
68
+
69
+ /*
70
+ * Specifies sequentially consistent order. This behaves as acq_rel, but in addition,
71
+ * all seq_cst operations appear to occur in some globally consistent order.
72
+ *
73
+ * TODO: Figure out how to correctly implement this in MSVC. It appears that interlocked
74
+ * functions provide only acq_rel ordering.
75
+ */
76
+ aws_memory_order_seq_cst
77
+ };
78
+
79
+ /**
80
+ * Statically initializes an aws_atomic_var to a given size_t value.
81
+ */
82
+ #define AWS_ATOMIC_INIT_INT(x) {.value = (void *)(uintptr_t)(x)}
83
+
84
+ /**
85
+ * Statically initializes an aws_atomic_var to a given void * value.
86
+ */
87
+ #define AWS_ATOMIC_INIT_PTR(x) {.value = (void *)(x)}
88
+
89
+ AWS_EXTERN_C_BEGIN
90
+
91
+ /*
92
+ * Note: We do not use the C11 atomics API; this is because we want to make sure the representation
93
+ * (and behavior) of atomic values is consistent, regardless of what --std= flag you pass to your compiler.
94
+ * Since C11 atomics can silently introduce locks, we run the risk of creating such ABI inconsistencies
95
+ * if we decide based on compiler features which atomics API to use, and in practice we expect to have
96
+ * either the GNU or MSVC atomics anyway.
97
+ *
98
+ * As future work, we could test to see if the C11 atomics API on this platform behaves consistently
99
+ * with the other APIs and use it if it does.
100
+ */
101
+
102
+ /**
103
+ * Initializes an atomic variable with an integer value. This operation should be done before any
104
+ * other operations on this atomic variable, and must be done before attempting any parallel operations.
105
+ *
106
+ * This operation does not imply a barrier. Ensure that you use an acquire-release barrier (or stronger)
107
+ * when communicating the fact that initialization is complete to the other thread. Launching the thread
108
+ * implies a sufficiently strong barrier.
109
+ */
110
+ AWS_STATIC_IMPL
111
+ void aws_atomic_init_int(volatile struct aws_atomic_var *var, size_t n);
112
+
113
+ /**
114
+ * Initializes an atomic variable with a pointer value. This operation should be done before any
115
+ * other operations on this atomic variable, and must be done before attempting any parallel operations.
116
+ *
117
+ * This operation does not imply a barrier. Ensure that you use an acquire-release barrier (or stronger)
118
+ * when communicating the fact that initialization is complete to the other thread. Launching the thread
119
+ * implies a sufficiently strong barrier.
120
+ */
121
+ AWS_STATIC_IMPL
122
+ void aws_atomic_init_ptr(volatile struct aws_atomic_var *var, void *p);
123
+
124
+ /**
125
+ * Reads an atomic var as an integer, using the specified ordering, and returns the result.
126
+ */
127
+ AWS_STATIC_IMPL
128
+ size_t aws_atomic_load_int_explicit(volatile const struct aws_atomic_var *var, enum aws_memory_order memory_order);
129
+
130
+ /**
131
+ * Reads an atomic var as an integer, using sequentially consistent ordering, and returns the result.
132
+ */
133
+ AWS_STATIC_IMPL
134
+ size_t aws_atomic_load_int(volatile const struct aws_atomic_var *var);
135
+ /**
136
+ * Reads an atomic var as a pointer, using the specified ordering, and returns the result.
137
+ */
138
+ AWS_STATIC_IMPL
139
+ void *aws_atomic_load_ptr_explicit(volatile const struct aws_atomic_var *var, enum aws_memory_order memory_order);
140
+
141
+ /**
142
+ * Reads an atomic var as a pointer, using sequentially consistent ordering, and returns the result.
143
+ */
144
+ AWS_STATIC_IMPL
145
+ void *aws_atomic_load_ptr(volatile const struct aws_atomic_var *var);
146
+
147
+ /**
148
+ * Stores an integer into an atomic var, using the specified ordering.
149
+ */
150
+ AWS_STATIC_IMPL
151
+ void aws_atomic_store_int_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order memory_order);
152
+
153
+ /**
154
+ * Stores an integer into an atomic var, using sequentially consistent ordering.
155
+ */
156
+ AWS_STATIC_IMPL
157
+ void aws_atomic_store_int(volatile struct aws_atomic_var *var, size_t n);
158
+
159
+ /**
160
+ * Stores a pointer into an atomic var, using the specified ordering.
161
+ */
162
+ AWS_STATIC_IMPL
163
+ void aws_atomic_store_ptr_explicit(volatile struct aws_atomic_var *var, void *p, enum aws_memory_order memory_order);
164
+
165
+ /**
166
+ * Stores a pointer into an atomic var, using sequentially consistent ordering.
167
+ */
168
+ AWS_STATIC_IMPL
169
+ void aws_atomic_store_ptr(volatile struct aws_atomic_var *var, void *p);
170
+
171
+ /**
172
+ * Exchanges an integer with the value in an atomic_var, using the specified ordering.
173
+ * Returns the value that was previously in the atomic_var.
174
+ */
175
+ AWS_STATIC_IMPL
176
+ size_t aws_atomic_exchange_int_explicit(
177
+ volatile struct aws_atomic_var *var,
178
+ size_t n,
179
+ enum aws_memory_order memory_order);
180
+
181
+ /**
182
+ * Exchanges an integer with the value in an atomic_var, using sequentially consistent ordering.
183
+ * Returns the value that was previously in the atomic_var.
184
+ */
185
+ AWS_STATIC_IMPL
186
+ size_t aws_atomic_exchange_int(volatile struct aws_atomic_var *var, size_t n);
187
+
188
+ /**
189
+ * Exchanges a pointer with the value in an atomic_var, using the specified ordering.
190
+ * Returns the value that was previously in the atomic_var.
191
+ */
192
+ AWS_STATIC_IMPL
193
+ void *aws_atomic_exchange_ptr_explicit(
194
+ volatile struct aws_atomic_var *var,
195
+ void *p,
196
+ enum aws_memory_order memory_order);
197
+
198
+ /**
199
+ * Exchanges an integer with the value in an atomic_var, using sequentially consistent ordering.
200
+ * Returns the value that was previously in the atomic_var.
201
+ */
202
+ AWS_STATIC_IMPL
203
+ void *aws_atomic_exchange_ptr(volatile struct aws_atomic_var *var, void *p);
204
+
205
+ /**
206
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
207
+ * to the value in *var. On success, the memory ordering used was order_success; otherwise, it was order_failure.
208
+ * order_failure must be no stronger than order_success, and must not be release or acq_rel.
209
+ * Returns true if the compare was successful and the variable updated to desired.
210
+ */
211
+ AWS_STATIC_IMPL
212
+ bool aws_atomic_compare_exchange_int_explicit(
213
+ volatile struct aws_atomic_var *var,
214
+ size_t *expected,
215
+ size_t desired,
216
+ enum aws_memory_order order_success,
217
+ enum aws_memory_order order_failure);
218
+
219
+ /**
220
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
221
+ * to the value in *var. Uses sequentially consistent memory ordering, regardless of success or failure.
222
+ * Returns true if the compare was successful and the variable updated to desired.
223
+ */
224
+ AWS_STATIC_IMPL
225
+ bool aws_atomic_compare_exchange_int(volatile struct aws_atomic_var *var, size_t *expected, size_t desired);
226
+
227
+ /**
228
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
229
+ * to the value in *var. On success, the memory ordering used was order_success; otherwise, it was order_failure.
230
+ * order_failure must be no stronger than order_success, and must not be release or acq_rel.
231
+ * Returns true if the compare was successful and the variable updated to desired.
232
+ */
233
+ AWS_STATIC_IMPL
234
+ bool aws_atomic_compare_exchange_ptr_explicit(
235
+ volatile struct aws_atomic_var *var,
236
+ void **expected,
237
+ void *desired,
238
+ enum aws_memory_order order_success,
239
+ enum aws_memory_order order_failure);
240
+
241
+ /**
242
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
243
+ * to the value in *var. Uses sequentially consistent memory ordering, regardless of success or failure.
244
+ * Returns true if the compare was successful and the variable updated to desired.
245
+ */
246
+ AWS_STATIC_IMPL
247
+ bool aws_atomic_compare_exchange_ptr(volatile struct aws_atomic_var *var, void **expected, void *desired);
248
+
249
+ /**
250
+ * Atomically adds n to *var, and returns the previous value of *var.
251
+ */
252
+ AWS_STATIC_IMPL
253
+ size_t aws_atomic_fetch_add_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order);
254
+
255
+ /**
256
+ * Atomically subtracts n from *var, and returns the previous value of *var.
257
+ */
258
+ AWS_STATIC_IMPL
259
+ size_t aws_atomic_fetch_sub_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order);
260
+
261
+ /**
262
+ * Atomically ORs n with *var, and returns the previous value of *var.
263
+ */
264
+ AWS_STATIC_IMPL
265
+ size_t aws_atomic_fetch_or_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order);
266
+
267
+ /**
268
+ * Atomically ANDs n with *var, and returns the previous value of *var.
269
+ */
270
+ AWS_STATIC_IMPL
271
+ size_t aws_atomic_fetch_and_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order);
272
+
273
+ /**
274
+ * Atomically XORs n with *var, and returns the previous value of *var.
275
+ */
276
+ AWS_STATIC_IMPL
277
+ size_t aws_atomic_fetch_xor_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order);
278
+
279
+ /**
280
+ * Atomically adds n to *var, and returns the previous value of *var.
281
+ * Uses sequentially consistent ordering.
282
+ */
283
+ AWS_STATIC_IMPL
284
+ size_t aws_atomic_fetch_add(volatile struct aws_atomic_var *var, size_t n);
285
+
286
+ /**
287
+ * Atomically subtracts n from *var, and returns the previous value of *var.
288
+ * Uses sequentially consistent ordering.
289
+ */
290
+ AWS_STATIC_IMPL
291
+ size_t aws_atomic_fetch_sub(volatile struct aws_atomic_var *var, size_t n);
292
+
293
+ /**
294
+ * Atomically ands n into *var, and returns the previous value of *var.
295
+ * Uses sequentially consistent ordering.
296
+ */
297
+ AWS_STATIC_IMPL
298
+ size_t aws_atomic_fetch_and(volatile struct aws_atomic_var *var, size_t n);
299
+
300
+ /**
301
+ * Atomically ors n into *var, and returns the previous value of *var.
302
+ * Uses sequentially consistent ordering.
303
+ */
304
+ AWS_STATIC_IMPL
305
+ size_t aws_atomic_fetch_or(volatile struct aws_atomic_var *var, size_t n);
306
+
307
+ /**
308
+ * Atomically xors n into *var, and returns the previous value of *var.
309
+ * Uses sequentially consistent ordering.
310
+ */
311
+ AWS_STATIC_IMPL
312
+ size_t aws_atomic_fetch_xor(volatile struct aws_atomic_var *var, size_t n);
313
+
314
+ /**
315
+ * Provides the same reordering guarantees as an atomic operation with the specified memory order, without
316
+ * needing to actually perform an atomic operation.
317
+ */
318
+ AWS_STATIC_IMPL
319
+ void aws_atomic_thread_fence(enum aws_memory_order order);
320
+
321
+ AWS_EXTERN_C_END
322
+
323
+ #ifndef AWS_NO_STATIC_IMPL
324
+ # include <aws/common/atomics.inl>
325
+ #endif /* AWS_NO_STATIC_IMPL */
326
+
327
+ AWS_POP_SANE_WARNING_LEVEL
328
+
329
+ #endif
include/aws/common/atomics.inl ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ATOMICS_INL
2
+ #define AWS_COMMON_ATOMICS_INL
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/atomics.h>
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_EXTERN_C_BEGIN
13
+
14
+ /**
15
+ * Reads an atomic var as an integer, using sequentially consistent ordering, and returns the result.
16
+ */
17
+ AWS_STATIC_IMPL
18
+ size_t aws_atomic_load_int(volatile const struct aws_atomic_var *var) {
19
+ return aws_atomic_load_int_explicit(var, aws_memory_order_seq_cst);
20
+ }
21
+
22
+ /**
23
+ * Reads an atomic var as a pointer, using sequentially consistent ordering, and returns the result.
24
+ */
25
+ AWS_STATIC_IMPL
26
+ void *aws_atomic_load_ptr(volatile const struct aws_atomic_var *var) {
27
+ return aws_atomic_load_ptr_explicit(var, aws_memory_order_seq_cst);
28
+ }
29
+
30
+ /**
31
+ * Stores an integer into an atomic var, using sequentially consistent ordering.
32
+ */
33
+ AWS_STATIC_IMPL
34
+ void aws_atomic_store_int(volatile struct aws_atomic_var *var, size_t n) {
35
+ aws_atomic_store_int_explicit(var, n, aws_memory_order_seq_cst);
36
+ }
37
+
38
+ /**
39
+ * Stores a pointer into an atomic var, using sequentially consistent ordering.
40
+ */
41
+ AWS_STATIC_IMPL
42
+ void aws_atomic_store_ptr(volatile struct aws_atomic_var *var, void *p) {
43
+ aws_atomic_store_ptr_explicit(var, p, aws_memory_order_seq_cst);
44
+ }
45
+
46
+ /**
47
+ * Exchanges an integer with the value in an atomic_var, using sequentially consistent ordering.
48
+ * Returns the value that was previously in the atomic_var.
49
+ */
50
+ AWS_STATIC_IMPL
51
+ size_t aws_atomic_exchange_int(volatile struct aws_atomic_var *var, size_t n) {
52
+ return aws_atomic_exchange_int_explicit(var, n, aws_memory_order_seq_cst);
53
+ }
54
+
55
+ /**
56
+ * Exchanges an integer with the value in an atomic_var, using sequentially consistent ordering.
57
+ * Returns the value that was previously in the atomic_var.
58
+ */
59
+ AWS_STATIC_IMPL
60
+ void *aws_atomic_exchange_ptr(volatile struct aws_atomic_var *var, void *p) {
61
+ return aws_atomic_exchange_ptr_explicit(var, p, aws_memory_order_seq_cst);
62
+ }
63
+
64
+ /**
65
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
66
+ * to the value in *var. Uses sequentially consistent memory ordering, regardless of success or failure.
67
+ * Returns true if the compare was successful and the variable updated to desired.
68
+ */
69
+ AWS_STATIC_IMPL
70
+ bool aws_atomic_compare_exchange_int(volatile struct aws_atomic_var *var, size_t *expected, size_t desired) {
71
+ return aws_atomic_compare_exchange_int_explicit(
72
+ var, expected, desired, aws_memory_order_seq_cst, aws_memory_order_seq_cst);
73
+ }
74
+
75
+ /**
76
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
77
+ * to the value in *var. Uses sequentially consistent memory ordering, regardless of success or failure.
78
+ * Returns true if the compare was successful and the variable updated to desired.
79
+ */
80
+ AWS_STATIC_IMPL
81
+ bool aws_atomic_compare_exchange_ptr(volatile struct aws_atomic_var *var, void **expected, void *desired) {
82
+ return aws_atomic_compare_exchange_ptr_explicit(
83
+ var, expected, desired, aws_memory_order_seq_cst, aws_memory_order_seq_cst);
84
+ }
85
+
86
+ /**
87
+ * Atomically adds n to *var, and returns the previous value of *var.
88
+ * Uses sequentially consistent ordering.
89
+ */
90
+ AWS_STATIC_IMPL
91
+ size_t aws_atomic_fetch_add(volatile struct aws_atomic_var *var, size_t n) {
92
+ return aws_atomic_fetch_add_explicit(var, n, aws_memory_order_seq_cst);
93
+ }
94
+
95
+ /**
96
+ * Atomically subtracts n from *var, and returns the previous value of *var.
97
+ * Uses sequentially consistent ordering.
98
+ */
99
+ AWS_STATIC_IMPL
100
+ size_t aws_atomic_fetch_sub(volatile struct aws_atomic_var *var, size_t n) {
101
+ return aws_atomic_fetch_sub_explicit(var, n, aws_memory_order_seq_cst);
102
+ }
103
+
104
+ /**
105
+ * Atomically ands n into *var, and returns the previous value of *var.
106
+ * Uses sequentially consistent ordering.
107
+ */
108
+ AWS_STATIC_IMPL
109
+ size_t aws_atomic_fetch_and(volatile struct aws_atomic_var *var, size_t n) {
110
+ return aws_atomic_fetch_and_explicit(var, n, aws_memory_order_seq_cst);
111
+ }
112
+
113
+ /**
114
+ * Atomically ors n into *var, and returns the previous value of *var.
115
+ * Uses sequentially consistent ordering.
116
+ */
117
+ AWS_STATIC_IMPL
118
+ size_t aws_atomic_fetch_or(volatile struct aws_atomic_var *var, size_t n) {
119
+ return aws_atomic_fetch_or_explicit(var, n, aws_memory_order_seq_cst);
120
+ }
121
+
122
+ /**
123
+ * Atomically xors n into *var, and returns the previous value of *var.
124
+ * Uses sequentially consistent ordering.
125
+ */
126
+ AWS_STATIC_IMPL
127
+ size_t aws_atomic_fetch_xor(volatile struct aws_atomic_var *var, size_t n) {
128
+ return aws_atomic_fetch_xor_explicit(var, n, aws_memory_order_seq_cst);
129
+ }
130
+ AWS_EXTERN_C_END
131
+
132
+ /* Include the backend implementation now, because we'll use its typedefs and #defines below */
133
+ #if defined(__GNUC__) || defined(__clang__)
134
+ # if defined(__ATOMIC_RELAXED)
135
+ # include <aws/common/atomics_gnu.inl>
136
+ # else
137
+ # include <aws/common/atomics_gnu_old.inl>
138
+ # endif /* __ATOMIC_RELAXED */
139
+ #elif defined(_MSC_VER)
140
+ # include <aws/common/atomics_msvc.inl>
141
+ #else
142
+ # error No atomics implementation for your compiler is available
143
+ #endif
144
+
145
+ #include <aws/common/atomics_fallback.inl>
146
+
147
+ #endif /* AWS_COMMON_ATOMICS_INL */
include/aws/common/atomics_gnu.inl ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ATOMICS_GNU_INL
2
+ #define AWS_COMMON_ATOMICS_GNU_INL
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ /* These are implicitly included, but help with editor highlighting */
10
+ #include <aws/common/atomics.h>
11
+ #include <aws/common/common.h>
12
+
13
+ #include <stdint.h>
14
+ #include <stdlib.h>
15
+
16
+ AWS_EXTERN_C_BEGIN
17
+
18
+ #ifdef __clang__
19
+ # pragma clang diagnostic push
20
+ # pragma clang diagnostic ignored "-Wc11-extensions"
21
+ #else
22
+ # pragma GCC diagnostic push
23
+ # pragma GCC diagnostic ignored "-Wpedantic"
24
+ #endif
25
+
26
+ typedef size_t aws_atomic_impl_int_t;
27
+
28
+ static inline int aws_atomic_priv_xlate_order(enum aws_memory_order order) {
29
+ switch (order) {
30
+ case aws_memory_order_relaxed:
31
+ return __ATOMIC_RELAXED;
32
+ case aws_memory_order_acquire:
33
+ return __ATOMIC_ACQUIRE;
34
+ case aws_memory_order_release:
35
+ return __ATOMIC_RELEASE;
36
+ case aws_memory_order_acq_rel:
37
+ return __ATOMIC_ACQ_REL;
38
+ case aws_memory_order_seq_cst:
39
+ return __ATOMIC_SEQ_CST;
40
+ default: /* Unknown memory order */
41
+ abort();
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Initializes an atomic variable with an integer value. This operation should be done before any
47
+ * other operations on this atomic variable, and must be done before attempting any parallel operations.
48
+ */
49
+ AWS_STATIC_IMPL
50
+ void aws_atomic_init_int(volatile struct aws_atomic_var *var, size_t n) {
51
+ AWS_ATOMIC_VAR_INTVAL(var) = n;
52
+ }
53
+
54
+ /**
55
+ * Initializes an atomic variable with a pointer value. This operation should be done before any
56
+ * other operations on this atomic variable, and must be done before attempting any parallel operations.
57
+ */
58
+ AWS_STATIC_IMPL
59
+ void aws_atomic_init_ptr(volatile struct aws_atomic_var *var, void *p) {
60
+ AWS_ATOMIC_VAR_PTRVAL(var) = p;
61
+ }
62
+
63
+ /**
64
+ * Reads an atomic var as an integer, using the specified ordering, and returns the result.
65
+ */
66
+ AWS_STATIC_IMPL
67
+ size_t aws_atomic_load_int_explicit(volatile const struct aws_atomic_var *var, enum aws_memory_order memory_order) {
68
+ return __atomic_load_n(&AWS_ATOMIC_VAR_INTVAL(var), aws_atomic_priv_xlate_order(memory_order));
69
+ }
70
+
71
+ /**
72
+ * Reads an atomic var as a pointer, using the specified ordering, and returns the result.
73
+ */
74
+ AWS_STATIC_IMPL
75
+ void *aws_atomic_load_ptr_explicit(volatile const struct aws_atomic_var *var, enum aws_memory_order memory_order) {
76
+ return __atomic_load_n(&AWS_ATOMIC_VAR_PTRVAL(var), aws_atomic_priv_xlate_order(memory_order));
77
+ }
78
+
79
+ /**
80
+ * Stores an integer into an atomic var, using the specified ordering.
81
+ */
82
+ AWS_STATIC_IMPL
83
+ void aws_atomic_store_int_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order memory_order) {
84
+ __atomic_store_n(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(memory_order));
85
+ }
86
+
87
+ /**
88
+ * Stores an pointer into an atomic var, using the specified ordering.
89
+ */
90
+ AWS_STATIC_IMPL
91
+ void aws_atomic_store_ptr_explicit(volatile struct aws_atomic_var *var, void *p, enum aws_memory_order memory_order) {
92
+ __atomic_store_n(&AWS_ATOMIC_VAR_PTRVAL(var), p, aws_atomic_priv_xlate_order(memory_order));
93
+ }
94
+
95
+ /**
96
+ * Exchanges an integer with the value in an atomic_var, using the specified ordering.
97
+ * Returns the value that was previously in the atomic_var.
98
+ */
99
+ AWS_STATIC_IMPL
100
+ size_t aws_atomic_exchange_int_explicit(
101
+ volatile struct aws_atomic_var *var,
102
+ size_t n,
103
+ enum aws_memory_order memory_order) {
104
+ return __atomic_exchange_n(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(memory_order));
105
+ }
106
+
107
+ /**
108
+ * Exchanges a pointer with the value in an atomic_var, using the specified ordering.
109
+ * Returns the value that was previously in the atomic_var.
110
+ */
111
+ AWS_STATIC_IMPL
112
+ void *aws_atomic_exchange_ptr_explicit(
113
+ volatile struct aws_atomic_var *var,
114
+ void *p,
115
+ enum aws_memory_order memory_order) {
116
+ return __atomic_exchange_n(&AWS_ATOMIC_VAR_PTRVAL(var), p, aws_atomic_priv_xlate_order(memory_order));
117
+ }
118
+
119
+ /**
120
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
121
+ * to the value in *var. On success, the memory ordering used was order_success; otherwise, it was order_failure.
122
+ * order_failure must be no stronger than order_success, and must not be release or acq_rel.
123
+ */
124
+ AWS_STATIC_IMPL
125
+ bool aws_atomic_compare_exchange_int_explicit(
126
+ volatile struct aws_atomic_var *var,
127
+ size_t *expected,
128
+ size_t desired,
129
+ enum aws_memory_order order_success,
130
+ enum aws_memory_order order_failure) {
131
+ return __atomic_compare_exchange_n(
132
+ &AWS_ATOMIC_VAR_INTVAL(var),
133
+ expected,
134
+ desired,
135
+ false,
136
+ aws_atomic_priv_xlate_order(order_success),
137
+ aws_atomic_priv_xlate_order(order_failure));
138
+ }
139
+
140
+ /**
141
+ * Atomically compares *var to *expected; if they are equal, atomically sets *var = desired. Otherwise, *expected is set
142
+ * to the value in *var. On success, the memory ordering used was order_success; otherwise, it was order_failure.
143
+ * order_failure must be no stronger than order_success, and must not be release or acq_rel.
144
+ */
145
+ AWS_STATIC_IMPL
146
+ bool aws_atomic_compare_exchange_ptr_explicit(
147
+ volatile struct aws_atomic_var *var,
148
+ void **expected,
149
+ void *desired,
150
+ enum aws_memory_order order_success,
151
+ enum aws_memory_order order_failure) {
152
+ return __atomic_compare_exchange_n(
153
+ &AWS_ATOMIC_VAR_PTRVAL(var),
154
+ expected,
155
+ desired,
156
+ false,
157
+ aws_atomic_priv_xlate_order(order_success),
158
+ aws_atomic_priv_xlate_order(order_failure));
159
+ }
160
+
161
+ /**
162
+ * Atomically adds n to *var, and returns the previous value of *var.
163
+ */
164
+ AWS_STATIC_IMPL
165
+ size_t aws_atomic_fetch_add_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order) {
166
+ return __atomic_fetch_add(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(order));
167
+ }
168
+
169
+ /**
170
+ * Atomically subtracts n from *var, and returns the previous value of *var.
171
+ */
172
+ AWS_STATIC_IMPL
173
+ size_t aws_atomic_fetch_sub_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order) {
174
+ return __atomic_fetch_sub(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(order));
175
+ }
176
+
177
+ /**
178
+ * Atomically ORs n with *var, and returns the previous value of *var.
179
+ */
180
+ AWS_STATIC_IMPL
181
+ size_t aws_atomic_fetch_or_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order) {
182
+ return __atomic_fetch_or(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(order));
183
+ }
184
+
185
+ /**
186
+ * Atomically ANDs n with *var, and returns the previous value of *var.
187
+ */
188
+ AWS_STATIC_IMPL
189
+ size_t aws_atomic_fetch_and_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order) {
190
+ return __atomic_fetch_and(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(order));
191
+ }
192
+
193
+ /**
194
+ * Atomically XORs n with *var, and returns the previous value of *var.
195
+ */
196
+ AWS_STATIC_IMPL
197
+ size_t aws_atomic_fetch_xor_explicit(volatile struct aws_atomic_var *var, size_t n, enum aws_memory_order order) {
198
+ return __atomic_fetch_xor(&AWS_ATOMIC_VAR_INTVAL(var), n, aws_atomic_priv_xlate_order(order));
199
+ }
200
+
201
+ /**
202
+ * Provides the same reordering guarantees as an atomic operation with the specified memory order, without
203
+ * needing to actually perform an atomic operation.
204
+ */
205
+ AWS_STATIC_IMPL
206
+ void aws_atomic_thread_fence(enum aws_memory_order order) {
207
+ __atomic_thread_fence(order);
208
+ }
209
+
210
+ #ifdef __clang__
211
+ # pragma clang diagnostic pop
212
+ #else
213
+ # pragma GCC diagnostic pop
214
+ #endif
215
+
216
+ #define AWS_ATOMICS_HAVE_THREAD_FENCE
217
+ AWS_EXTERN_C_END
218
+ #endif /* AWS_COMMON_ATOMICS_GNU_INL */
include/aws/common/byte_order.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_BYTE_ORDER_H
2
+ #define AWS_COMMON_BYTE_ORDER_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+
11
+ AWS_PUSH_SANE_WARNING_LEVEL
12
+ AWS_EXTERN_C_BEGIN
13
+
14
+ /**
15
+ * Returns 1 if machine is big endian, 0 if little endian.
16
+ * If you compile with even -O1 optimization, this check is completely optimized
17
+ * out at compile time and code which calls "if (aws_is_big_endian())" will do
18
+ * the right thing without branching.
19
+ */
20
+ AWS_STATIC_IMPL int aws_is_big_endian(void);
21
+ /**
22
+ * Convert 64 bit integer from host to network byte order.
23
+ */
24
+ AWS_STATIC_IMPL uint64_t aws_hton64(uint64_t x);
25
+ /**
26
+ * Convert 64 bit integer from network to host byte order.
27
+ */
28
+ AWS_STATIC_IMPL uint64_t aws_ntoh64(uint64_t x);
29
+
30
+ /**
31
+ * Convert 32 bit integer from host to network byte order.
32
+ */
33
+ AWS_STATIC_IMPL uint32_t aws_hton32(uint32_t x);
34
+
35
+ /**
36
+ * Convert 32 bit float from host to network byte order.
37
+ */
38
+ AWS_STATIC_IMPL float aws_htonf32(float x);
39
+
40
+ /**
41
+ * Convert 64 bit double from host to network byte order.
42
+ */
43
+ AWS_STATIC_IMPL double aws_htonf64(double x);
44
+
45
+ /**
46
+ * Convert 32 bit integer from network to host byte order.
47
+ */
48
+ AWS_STATIC_IMPL uint32_t aws_ntoh32(uint32_t x);
49
+
50
+ /**
51
+ * Convert 32 bit float from network to host byte order.
52
+ */
53
+ AWS_STATIC_IMPL float aws_ntohf32(float x);
54
+ /**
55
+ * Convert 32 bit float from network to host byte order.
56
+ */
57
+ AWS_STATIC_IMPL double aws_ntohf64(double x);
58
+
59
+ /**
60
+ * Convert 16 bit integer from host to network byte order.
61
+ */
62
+ AWS_STATIC_IMPL uint16_t aws_hton16(uint16_t x);
63
+
64
+ /**
65
+ * Convert 16 bit integer from network to host byte order.
66
+ */
67
+ AWS_STATIC_IMPL uint16_t aws_ntoh16(uint16_t x);
68
+
69
+ AWS_EXTERN_C_END
70
+ #ifndef AWS_NO_STATIC_IMPL
71
+ # include <aws/common/byte_order.inl>
72
+ #endif /* AWS_NO_STATIC_IMPL */
73
+
74
+ AWS_POP_SANE_WARNING_LEVEL
75
+
76
+ #endif /* AWS_COMMON_BYTE_ORDER_H */
include/aws/common/cache.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CACHE_H
2
+ #define AWS_COMMON_CACHE_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/linked_hash_table.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ struct aws_cache;
13
+
14
+ struct aws_cache_vtable {
15
+ void (*destroy)(struct aws_cache *cache);
16
+ int (*find)(struct aws_cache *cache, const void *key, void **p_value);
17
+ int (*put)(struct aws_cache *cache, const void *key, void *p_value);
18
+ int (*remove)(struct aws_cache *cache, const void *key);
19
+ void (*clear)(struct aws_cache *cache);
20
+ size_t (*get_element_count)(const struct aws_cache *cache);
21
+ };
22
+
23
+ /**
24
+ * Base stucture for caches, used the linked hash table implementation.
25
+ */
26
+ struct aws_cache {
27
+ struct aws_allocator *allocator;
28
+ const struct aws_cache_vtable *vtable;
29
+ struct aws_linked_hash_table table;
30
+ size_t max_items;
31
+
32
+ void *impl;
33
+ };
34
+
35
+ /* Default implementations */
36
+ void aws_cache_base_default_destroy(struct aws_cache *cache);
37
+ int aws_cache_base_default_find(struct aws_cache *cache, const void *key, void **p_value);
38
+ int aws_cache_base_default_remove(struct aws_cache *cache, const void *key);
39
+ void aws_cache_base_default_clear(struct aws_cache *cache);
40
+ size_t aws_cache_base_default_get_element_count(const struct aws_cache *cache);
41
+
42
+ AWS_EXTERN_C_BEGIN
43
+ /**
44
+ * Cleans up the cache. Elements in the cache will be evicted and cleanup
45
+ * callbacks will be invoked.
46
+ */
47
+ AWS_COMMON_API
48
+ void aws_cache_destroy(struct aws_cache *cache);
49
+
50
+ /**
51
+ * Finds element in the cache by key. If found, *p_value will hold the stored value, and AWS_OP_SUCCESS will be
52
+ * returned. If not found, AWS_OP_SUCCESS will be returned and *p_value will be NULL.
53
+ *
54
+ * If any errors occur AWS_OP_ERR will be returned.
55
+ */
56
+ AWS_COMMON_API
57
+ int aws_cache_find(struct aws_cache *cache, const void *key, void **p_value);
58
+
59
+ /**
60
+ * Puts `p_value` at `key`. If an element is already stored at `key` it will be replaced. If the cache is already full,
61
+ * an item will be removed based on the cache policy.
62
+ */
63
+ AWS_COMMON_API
64
+ int aws_cache_put(struct aws_cache *cache, const void *key, void *p_value);
65
+
66
+ /**
67
+ * Removes item at `key` from the cache.
68
+ */
69
+ AWS_COMMON_API
70
+ int aws_cache_remove(struct aws_cache *cache, const void *key);
71
+
72
+ /**
73
+ * Clears all items from the cache.
74
+ */
75
+ AWS_COMMON_API
76
+ void aws_cache_clear(struct aws_cache *cache);
77
+
78
+ /**
79
+ * Returns the number of elements in the cache.
80
+ */
81
+ AWS_COMMON_API
82
+ size_t aws_cache_get_element_count(const struct aws_cache *cache);
83
+
84
+ AWS_EXTERN_C_END
85
+ AWS_POP_SANE_WARNING_LEVEL
86
+
87
+ #endif /* AWS_COMMON_CACHE_H */
include/aws/common/cbor.h ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CBOR_H
2
+ #define AWS_COMMON_CBOR_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+ AWS_EXTERN_C_BEGIN
14
+
15
+ /**
16
+ * The types use by APIs, not 1:1 with major type.
17
+ * It's an extension for cbor major type in RFC8949 section 3.1
18
+ * Major type 0 - AWS_CBOR_TYPE_UINT
19
+ * Major type 1 - AWS_CBOR_TYPE_NEGINT
20
+ * Major type 2 - AWS_CBOR_TYPE_BYTES/AWS_CBOR_TYPE_INDEF_BYTES_START
21
+ * Major type 3 - AWS_CBOR_TYPE_TEXT/AWS_CBOR_TYPE_INDEF_TEXT_START
22
+ * Major type 4 - AWS_CBOR_TYPE_ARRAY_START/AWS_CBOR_TYPE_INDEF_ARRAY_START
23
+ * Major type 5 - AWS_CBOR_TYPE_MAP_START/AWS_CBOR_TYPE_INDEF_MAP_START
24
+ * Major type 6 - AWS_CBOR_TYPE_TAG
25
+ * Major type 7
26
+ * - 20/21 - AWS_CBOR_TYPE_BOOL
27
+ * - 22 - AWS_CBOR_TYPE_NULL
28
+ * - 23 - AWS_CBOR_TYPE_UNDEFINED
29
+ * - 25/26/27 - AWS_CBOR_TYPE_FLOAT
30
+ * - 31 - AWS_CBOR_TYPE_BREAK
31
+ * - rest of value are not supported.
32
+ */
33
+ enum aws_cbor_type {
34
+ AWS_CBOR_TYPE_UNKNOWN = 0,
35
+
36
+ AWS_CBOR_TYPE_UINT,
37
+ AWS_CBOR_TYPE_NEGINT,
38
+ AWS_CBOR_TYPE_FLOAT,
39
+ AWS_CBOR_TYPE_BYTES,
40
+ AWS_CBOR_TYPE_TEXT,
41
+
42
+ AWS_CBOR_TYPE_ARRAY_START,
43
+ AWS_CBOR_TYPE_MAP_START,
44
+
45
+ AWS_CBOR_TYPE_TAG,
46
+
47
+ AWS_CBOR_TYPE_BOOL,
48
+ AWS_CBOR_TYPE_NULL,
49
+ AWS_CBOR_TYPE_UNDEFINED,
50
+ AWS_CBOR_TYPE_BREAK,
51
+
52
+ AWS_CBOR_TYPE_INDEF_BYTES_START,
53
+ AWS_CBOR_TYPE_INDEF_TEXT_START,
54
+ AWS_CBOR_TYPE_INDEF_ARRAY_START,
55
+ AWS_CBOR_TYPE_INDEF_MAP_START,
56
+ };
57
+
58
+ /**
59
+ * The common tags, refer to RFC8949 section 3.4
60
+ * Expected value type followed by the tag:
61
+ * AWS_CBOR_TAG_STANDARD_TIME - AWS_CBOR_TYPE_TEXT
62
+ * AWS_CBOR_TAG_EPOCH_TIME - AWS_CBOR_TYPE_UINT/AWS_CBOR_TYPE_NEGINT/AWS_CBOR_TYPE_FLOAT
63
+ * AWS_CBOR_TAG_UNSIGNED_BIGNUM - AWS_CBOR_TYPE_BYTES
64
+ * AWS_CBOR_TAG_NEGATIVE_BIGNUM - AWS_CBOR_TYPE_BYTES
65
+ * AWS_CBOR_TAG_DECIMAL_FRACTION - AWS_CBOR_TYPE_ARRAY_START/AWS_CBOR_TYPE_INDEF_ARRAY_START
66
+ **/
67
+ #define AWS_CBOR_TAG_STANDARD_TIME 0
68
+ #define AWS_CBOR_TAG_EPOCH_TIME 1
69
+ #define AWS_CBOR_TAG_UNSIGNED_BIGNUM 2
70
+ #define AWS_CBOR_TAG_NEGATIVE_BIGNUM 3
71
+ #define AWS_CBOR_TAG_DECIMAL_FRACTION 4
72
+
73
+ struct aws_cbor_encoder;
74
+ struct aws_cbor_decoder;
75
+
76
+ /*******************************************************************************
77
+ * ENCODE
78
+ ******************************************************************************/
79
+
80
+ /* Return c-string for aws_cbor_type */
81
+ AWS_COMMON_API
82
+ const char *aws_cbor_type_cstr(enum aws_cbor_type type);
83
+
84
+ /**
85
+ * @brief Create a new cbor encoder. Creating a encoder with a temporay buffer.
86
+ * Every aws_cbor_encoder_write_* will encode directly into the buffer to follow the encoded data.
87
+ *
88
+ * @param allocator
89
+ * @return aws_cbor_encoder
90
+ */
91
+ AWS_COMMON_API
92
+ struct aws_cbor_encoder *aws_cbor_encoder_new(struct aws_allocator *allocator);
93
+
94
+ AWS_COMMON_API
95
+ struct aws_cbor_encoder *aws_cbor_encoder_destroy(struct aws_cbor_encoder *encoder);
96
+
97
+ /**
98
+ * @brief Get the current encoded data from encoder. The encoded data has the same lifetime as the encoder, and once
99
+ * any other function call invoked for the encoder, the encoded data is no longer valid.
100
+ *
101
+ * @param encoder
102
+ * @return struct aws_byte_cursor from the encoder buffer.
103
+ */
104
+ AWS_COMMON_API
105
+ struct aws_byte_cursor aws_cbor_encoder_get_encoded_data(const struct aws_cbor_encoder *encoder);
106
+
107
+ /**
108
+ * @brief Clear the current encoded buffer from encoder.
109
+ *
110
+ * @param encoder
111
+ */
112
+ AWS_COMMON_API
113
+ void aws_cbor_encoder_reset(struct aws_cbor_encoder *encoder);
114
+
115
+ /**
116
+ * @brief Encode a AWS_CBOR_TYPE_UINT value to "smallest possible" in encoder's buffer.
117
+ * Referring to RFC8949 section 4.2.1
118
+ *
119
+ * TODO: maybe add a width of the encoded value.
120
+ *
121
+ * @param encoder
122
+ * @param value value to encode.
123
+ */
124
+ AWS_COMMON_API
125
+ void aws_cbor_encoder_write_uint(struct aws_cbor_encoder *encoder, uint64_t value);
126
+
127
+ /**
128
+ * @brief Encode a AWS_CBOR_TYPE_NEGINT value to "smallest possible" in encoder's buffer.
129
+ * It represents (-1 - value).
130
+ * Referring to RFC8949 section 4.2.1
131
+ *
132
+ *
133
+ * @param encoder
134
+ * @param value The argument to encode to negative integer, which is (-1 - expected_val)
135
+ */
136
+ AWS_COMMON_API
137
+ void aws_cbor_encoder_write_negint(struct aws_cbor_encoder *encoder, uint64_t value);
138
+
139
+ /**
140
+ * @brief Encode a AWS_CBOR_TYPE_FLOAT value to "smallest possible", but will not be encoded into half-precision float,
141
+ * as it's not well supported cross languages.
142
+ *
143
+ * To be more specific, it will be encoded into integer/negative/float
144
+ * (Order with priority) when the conversation will not cause precision loss.
145
+ *
146
+ * @param encoder
147
+ * @param value value to encode.
148
+ */
149
+ AWS_COMMON_API
150
+ void aws_cbor_encoder_write_float(struct aws_cbor_encoder *encoder, double value);
151
+
152
+ /**
153
+ * @brief Encode a AWS_CBOR_TYPE_BYTES value to "smallest possible" in encoder's buffer.
154
+ * Referring to RFC8949 section 4.2.1, the length of "from" will be encoded first and then the value of "from" will
155
+ * be followed.
156
+ *
157
+ * @param encoder
158
+ * @param from value to encode.
159
+ */
160
+ AWS_COMMON_API
161
+ void aws_cbor_encoder_write_bytes(struct aws_cbor_encoder *encoder, struct aws_byte_cursor from);
162
+
163
+ /**
164
+ * @brief Encode a AWS_CBOR_TYPE_TEXT value to "smallest possible" in encoder's buffer.
165
+ * Referring to RFC8949 section 4.2.1, the length of "from" will be encoded first and then the value of "from" will
166
+ * be followed.
167
+ *
168
+ * @param encoder
169
+ * @param from value to encode.
170
+ */
171
+ AWS_COMMON_API
172
+ void aws_cbor_encoder_write_text(struct aws_cbor_encoder *encoder, struct aws_byte_cursor from);
173
+
174
+ /**
175
+ * @brief Encode a AWS_CBOR_TYPE_ARRAY_START value to "smallest possible" in encoder's buffer.
176
+ * Referring to RFC8949 section 4.2.1
177
+ * The "number_entries" is the cbor data items should be followed as the content of the array.
178
+ * Notes: it's user's responsibility to keep the integrity of the array to be encoded.
179
+ *
180
+ * @param encoder
181
+ * @param number_entries The number of data item in array.
182
+ */
183
+ AWS_COMMON_API
184
+ void aws_cbor_encoder_write_array_start(struct aws_cbor_encoder *encoder, size_t number_entries);
185
+
186
+ /**
187
+ * @brief Encode a AWS_CBOR_TYPE_MAP_START value to "smallest possible" in encoder's buffer.
188
+ * Referring to RFC8949 section 4.2.1
189
+ * The "number_entries" is the number of pair of cbor data items as key and value should be followed as the content of
190
+ * the map.
191
+ *
192
+ * Notes: it's user's responsibility to keep the integrity of the map to be encoded.
193
+ *
194
+ * @param encoder
195
+ * @param number_entries The number of data item in map.
196
+ */
197
+ AWS_COMMON_API
198
+ void aws_cbor_encoder_write_map_start(struct aws_cbor_encoder *encoder, size_t number_entries);
199
+
200
+ /**
201
+ * @brief Encode a AWS_CBOR_TYPE_TAG value to "smallest possible" in encoder's buffer.
202
+ * Referring to RFC8949 section 4.2.1
203
+ * The following cbor data item will be the content of the tagged value.
204
+ * Notes: it's user's responsibility to keep the integrity of the tagged value to follow the RFC8949 section 3.4
205
+ *
206
+ * @param encoder
207
+ * @param tag_number The tag value to encode.
208
+ */
209
+ AWS_COMMON_API
210
+ void aws_cbor_encoder_write_tag(struct aws_cbor_encoder *encoder, uint64_t tag_number);
211
+
212
+ /**
213
+ * @brief Encode a simple value AWS_CBOR_TYPE_NULL
214
+ *
215
+ * @param encoder
216
+ */
217
+ AWS_COMMON_API
218
+ void aws_cbor_encoder_write_null(struct aws_cbor_encoder *encoder);
219
+
220
+ /**
221
+ * @brief Encode a simple value AWS_CBOR_TYPE_UNDEFINED
222
+ *
223
+ * @param encoder
224
+ */
225
+ AWS_COMMON_API
226
+ void aws_cbor_encoder_write_undefined(struct aws_cbor_encoder *encoder);
227
+
228
+ /**
229
+ * @brief Encode a simple value AWS_CBOR_TYPE_BOOL
230
+ *
231
+ * @param encoder
232
+ */
233
+ AWS_COMMON_API
234
+ void aws_cbor_encoder_write_bool(struct aws_cbor_encoder *encoder, bool value);
235
+
236
+ /**
237
+ * @brief Encode a simple value AWS_CBOR_TYPE_BREAK
238
+ *
239
+ * Notes: no error checking, it's user's responsibility to track the break
240
+ * to close the corresponding indef_start
241
+ */
242
+ AWS_COMMON_API
243
+ void aws_cbor_encoder_write_break(struct aws_cbor_encoder *encoder);
244
+
245
+ /**
246
+ * @brief Encode a AWS_CBOR_TYPE_INDEF_BYTES_START
247
+ *
248
+ * Notes: no error checking, it's user's responsibility to add corresponding data and the break
249
+ * to close the indef_start
250
+ */
251
+ AWS_COMMON_API
252
+ void aws_cbor_encoder_write_indef_bytes_start(struct aws_cbor_encoder *encoder);
253
+ /**
254
+ * @brief Encode a AWS_CBOR_TYPE_INDEF_TEXT_START
255
+ *
256
+ * Notes: no error checking, it's user's responsibility to add corresponding data
257
+ * and the break to close the indef_start
258
+ */
259
+ AWS_COMMON_API
260
+ void aws_cbor_encoder_write_indef_text_start(struct aws_cbor_encoder *encoder);
261
+ /**
262
+ * @brief Encode a AWS_CBOR_TYPE_INDEF_ARRAY_START
263
+ *
264
+ * Notes: no error checking, it's user's responsibility to add corresponding data
265
+ * and the break to close the indef_start
266
+ */
267
+ AWS_COMMON_API
268
+ void aws_cbor_encoder_write_indef_array_start(struct aws_cbor_encoder *encoder);
269
+ /**
270
+ * @brief Encode a AWS_CBOR_TYPE_INDEF_MAP_START
271
+ *
272
+ * Notes: no error checking, it's user's responsibility to add corresponding data
273
+ * and the break to close the indef_start
274
+ */
275
+ AWS_COMMON_API
276
+ void aws_cbor_encoder_write_indef_map_start(struct aws_cbor_encoder *encoder);
277
+
278
+ /*******************************************************************************
279
+ * DECODE
280
+ ******************************************************************************/
281
+
282
+ /**
283
+ * @brief Create a cbor decoder to take src to decode.
284
+ * The typical usage of decoder will be:
285
+ * - If the next element type only accept what expected, `aws_cbor_decoder_pop_next_*`
286
+ * - If the next element type accept different type, invoke `aws_cbor_decoder_peek_type` first, then based on the type
287
+ * to invoke corresponding `aws_cbor_decoder_pop_next_*`
288
+ * - If the next element type doesn't have corrsponding value, specifically: AWS_CBOR_TYPE_NULL,
289
+ * AWS_CBOR_TYPE_UNDEFINED, AWS_CBOR_TYPE_INF_*_START, AWS_CBOR_TYPE_BREAK, call
290
+ * `aws_cbor_decoder_consume_next_single_element` to consume it and continues for further decoding.
291
+ * - To ignore the next data item (the element and the content of it), `aws_cbor_decoder_consume_next_whole_data_item`
292
+ *
293
+ * Note: it's caller's responsibilty to keep the src outlive the decoder.
294
+ *
295
+ * @param allocator
296
+ * @param src The src data to decode from.
297
+ * @return decoder
298
+ */
299
+ AWS_COMMON_API
300
+ struct aws_cbor_decoder *aws_cbor_decoder_new(struct aws_allocator *allocator, struct aws_byte_cursor src);
301
+
302
+ AWS_COMMON_API
303
+ struct aws_cbor_decoder *aws_cbor_decoder_destroy(struct aws_cbor_decoder *decoder);
304
+
305
+ /**
306
+ * @brief Get the length of the remaining bytes of the source. Once the source was decoded, it will be consumed,
307
+ * and result in decrease of the remaining length of bytes.
308
+ *
309
+ * @param decoder
310
+ * @return The length of bytes remaining of the decoder source.
311
+ */
312
+ AWS_COMMON_API
313
+ size_t aws_cbor_decoder_get_remaining_length(const struct aws_cbor_decoder *decoder);
314
+
315
+ /**
316
+ * @brief Reset the decoder source to a new src.
317
+ * The previous src will be discarded regardless of the unconsumed bytes.
318
+ * The decoder will clear its cache if any.
319
+ *
320
+ * @param decoder
321
+ * @param src The src data to decode from..
322
+ */
323
+ AWS_COMMON_API
324
+ void aws_cbor_decoder_reset_src(struct aws_cbor_decoder *decoder, struct aws_byte_cursor src);
325
+
326
+ /**
327
+ * @brief Decode the next element and store it in the decoder cache if there was no element cached.
328
+ * If there was element cached, just return the type of the cached element.
329
+ *
330
+ * @param decoder
331
+ * @param out_type
332
+ * @return AWS_OP_SUCCESS if succeed, AWS_OP_ERR for any decoding error and corresponding error code will be raised.
333
+ */
334
+ AWS_COMMON_API
335
+ int aws_cbor_decoder_peek_type(struct aws_cbor_decoder *decoder, enum aws_cbor_type *out_type);
336
+
337
+ /**
338
+ * @brief Consume the next data item, includes all the content within the data item.
339
+ *
340
+ * As an example for the following cbor, this function will consume all the data
341
+ * as it's only one cbor data item, an indefinite map with 2 <key, value> pair:
342
+ * 0xbf6346756ef563416d7421ff
343
+ * BF -- Start indefinite-length map
344
+ * 63 -- First key, UTF-8 string length 3
345
+ * 46756e -- "Fun"
346
+ * F5 -- First value, true
347
+ * 63 -- Second key, UTF-8 string length 3
348
+ * 416d74 -- "Amt"
349
+ * 21 -- Second value, -2
350
+ * FF -- "break"
351
+ *
352
+ * Notes: this function will not ensure the data item is well-formed.
353
+ *
354
+ * @param src The src to parse data from
355
+ * @return AWS_OP_SUCCESS successfully consumed the next data item, otherwise AWS_OP_ERR.
356
+ */
357
+ AWS_COMMON_API
358
+ int aws_cbor_decoder_consume_next_whole_data_item(struct aws_cbor_decoder *decoder);
359
+
360
+ /**
361
+ * @brief Consume the next single element, without the content followed by the element.
362
+ *
363
+ * As an example for the following cbor, this function will only consume the
364
+ * 0xBF, "Start indefinite-length map", not any content of the map represented.
365
+ * The next element to decode will start from 0x63
366
+ * 0xbf6346756ef563416d7421ff
367
+ * BF -- Start indefinite-length map
368
+ * 63 -- First key, UTF-8 string length 3
369
+ * 46756e -- "Fun"
370
+ * F5 -- First value, true
371
+ * 63 -- Second key, UTF-8 string length 3
372
+ * 416d74 -- "Amt"
373
+ * 21 -- Second value, -2
374
+ * FF -- "break"
375
+ *
376
+ * @param decoder The decoder to parse data from
377
+ * @return AWS_OP_SUCCESS successfully consumed the next element, otherwise AWS_OP_ERR.
378
+ */
379
+ AWS_COMMON_API
380
+ int aws_cbor_decoder_consume_next_single_element(struct aws_cbor_decoder *decoder);
381
+
382
+ /**
383
+ * @brief Get the next element based on the type. If the next element doesn't match the expected type. Error will be
384
+ * raised. If the next element already been cached, it will consume the cached item when no error was returned.
385
+ * Specifically:
386
+ * AWS_CBOR_TYPE_UINT - aws_cbor_decoder_pop_next_unsigned_int_val
387
+ * AWS_CBOR_TYPE_NEGINT - aws_cbor_decoder_pop_next_negative_int_val, it represents (-1 - *out)
388
+ * AWS_CBOR_TYPE_FLOAT - aws_cbor_decoder_pop_next_float_val
389
+ * AWS_CBOR_TYPE_BYTES - aws_cbor_decoder_pop_next_bytes_val
390
+ * AWS_CBOR_TYPE_TEXT - aws_cbor_decoder_pop_next_text_val
391
+ *
392
+ * @param decoder
393
+ * @param out
394
+ * @return AWS_OP_SUCCESS successfully consumed the next element and get the result, otherwise AWS_OP_ERR.
395
+ */
396
+ AWS_COMMON_API
397
+ int aws_cbor_decoder_pop_next_unsigned_int_val(struct aws_cbor_decoder *decoder, uint64_t *out);
398
+ AWS_COMMON_API
399
+ int aws_cbor_decoder_pop_next_negative_int_val(struct aws_cbor_decoder *decoder, uint64_t *out);
400
+ AWS_COMMON_API
401
+ int aws_cbor_decoder_pop_next_float_val(struct aws_cbor_decoder *decoder, double *out);
402
+ AWS_COMMON_API
403
+ int aws_cbor_decoder_pop_next_boolean_val(struct aws_cbor_decoder *decoder, bool *out);
404
+ AWS_COMMON_API
405
+ int aws_cbor_decoder_pop_next_bytes_val(struct aws_cbor_decoder *decoder, struct aws_byte_cursor *out);
406
+ AWS_COMMON_API
407
+ int aws_cbor_decoder_pop_next_text_val(struct aws_cbor_decoder *decoder, struct aws_byte_cursor *out);
408
+
409
+ /**
410
+ * @brief Get the next AWS_CBOR_TYPE_ARRAY_START element. Only consume the AWS_CBOR_TYPE_ARRAY_START element and set the
411
+ * size of array to *out_size, not the content of the array. The next *out_size cbor data items will be the content of
412
+ * the array for a valid cbor data,
413
+ *
414
+ * Notes: For indefinite-length, this function will fail with "AWS_ERROR_CBOR_UNEXPECTED_TYPE". The designed way to
415
+ * handle indefinite-length is:
416
+ * - Get AWS_CBOR_TYPE_INDEF_ARRAY_START from _peek_type
417
+ * - call `aws_cbor_decoder_consume_next_single_element` to pop the indefinite-length start.
418
+ * - Decode the next data item until AWS_CBOR_TYPE_BREAK read.
419
+ *
420
+ * @param decoder
421
+ * @param out_size store the size of array if succeed.
422
+ * @return AWS_OP_SUCCESS successfully consumed the next element and get the result, otherwise AWS_OP_ERR.
423
+ */
424
+ AWS_COMMON_API
425
+ int aws_cbor_decoder_pop_next_array_start(struct aws_cbor_decoder *decoder, uint64_t *out_size);
426
+
427
+ /**
428
+ * @brief Get the next AWS_CBOR_TYPE_MAP_START element.
429
+ * Only consume the AWS_CBOR_TYPE_MAP_START element and set the size of array to *out_size, not the content of the map.
430
+ * The next *out_size pair of cbor data items as key and value will be the content of the array for a valid cbor data,
431
+ *
432
+ * Notes: For indefinite-length, this function will fail with "AWS_ERROR_CBOR_UNEXPECTED_TYPE". The designed way to
433
+ * handle indefinite-length is:
434
+ * - Get AWS_CBOR_TYPE_INDEF_MAP_START from _peek_type
435
+ * - call `aws_cbor_decoder_consume_next_single_element` to pop the indefinite-length start.
436
+ * - Decode the next data item until AWS_CBOR_TYPE_BREAK read.
437
+ *
438
+ * @param decoder
439
+ * @param out_size store the size of map if succeed.
440
+ * @return AWS_OP_SUCCESS successfully consumed the next element and get the result, otherwise AWS_OP_ERR.
441
+ */
442
+ AWS_COMMON_API
443
+ int aws_cbor_decoder_pop_next_map_start(struct aws_cbor_decoder *decoder, uint64_t *out_size);
444
+
445
+ /**
446
+ * @brief Get the next AWS_CBOR_TYPE_TAG element.
447
+ * Only consume the AWS_CBOR_TYPE_TAG element and set the tag ID value to *out_tag_val, not the content of the tagged.
448
+ * The next cbor data item will be the content of the tagged value for a valid cbor data.
449
+ *
450
+ * @param decoder
451
+ * @param out_tag_val store the value of tag ID.
452
+ * @return AWS_OP_SUCCESS successfully consumed the next element and get the result, otherwise AWS_OP_ERR.
453
+ */
454
+ AWS_COMMON_API
455
+ int aws_cbor_decoder_pop_next_tag_val(struct aws_cbor_decoder *decoder, uint64_t *out_tag_val);
456
+
457
+ AWS_EXTERN_C_END
458
+ AWS_POP_SANE_WARNING_LEVEL
459
+
460
+ #endif // AWS_COMMON_CBOR_H
include/aws/common/common.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_COMMON_H
2
+ #define AWS_COMMON_COMMON_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/config.h>
10
+ #include <aws/common/exports.h>
11
+
12
+ #include <aws/common/allocator.h>
13
+ #include <aws/common/assert.h>
14
+ #include <aws/common/error.h>
15
+ #include <aws/common/macros.h>
16
+ #include <aws/common/platform.h>
17
+ #include <aws/common/predicates.h>
18
+ #include <aws/common/stdbool.h>
19
+ #include <aws/common/stdint.h>
20
+ #include <aws/common/zero.h>
21
+ #include <stddef.h>
22
+ #include <stdio.h>
23
+ #include <stdlib.h> /* for abort() */
24
+ #include <string.h>
25
+
26
+ AWS_PUSH_SANE_WARNING_LEVEL
27
+ AWS_EXTERN_C_BEGIN
28
+
29
+ /**
30
+ * Initializes internal data structures used by aws-c-common.
31
+ * Must be called before using any functionality in aws-c-common.
32
+ */
33
+ AWS_COMMON_API
34
+ void aws_common_library_init(struct aws_allocator *allocator);
35
+
36
+ /**
37
+ * Shuts down the internal data structures used by aws-c-common.
38
+ */
39
+ AWS_COMMON_API
40
+ void aws_common_library_clean_up(void);
41
+
42
+ AWS_COMMON_API
43
+ void aws_common_fatal_assert_library_initialized(void);
44
+
45
+ AWS_EXTERN_C_END
46
+ AWS_POP_SANE_WARNING_LEVEL
47
+
48
+ #endif /* AWS_COMMON_COMMON_H */
include/aws/common/condition_variable.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CONDITION_VARIABLE_H
2
+ #define AWS_COMMON_CONDITION_VARIABLE_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+ #ifndef _WIN32
11
+ # include <pthread.h>
12
+ #endif
13
+
14
+ AWS_PUSH_SANE_WARNING_LEVEL
15
+
16
+ struct aws_mutex;
17
+
18
+ struct aws_condition_variable;
19
+
20
+ typedef bool(aws_condition_predicate_fn)(void *);
21
+
22
+ struct aws_condition_variable {
23
+ #ifdef _WIN32
24
+ void *condition_handle;
25
+ #else
26
+ pthread_cond_t condition_handle;
27
+ #endif
28
+ bool initialized;
29
+ };
30
+
31
+ /**
32
+ * Static initializer for condition variable.
33
+ * You can do something like struct aws_condition_variable var =
34
+ * AWS_CONDITION_VARIABLE_INIT;
35
+ *
36
+ * If on Windows and you get an error about AWS_CONDITION_VARIABLE_INIT being undefined, please include windows.h to get
37
+ * CONDITION_VARIABLE_INIT.
38
+ */
39
+ #ifdef _WIN32
40
+ # define AWS_CONDITION_VARIABLE_INIT {.condition_handle = NULL, .initialized = true}
41
+ #else
42
+ # define AWS_CONDITION_VARIABLE_INIT {.condition_handle = PTHREAD_COND_INITIALIZER, .initialized = true}
43
+ #endif
44
+
45
+ AWS_EXTERN_C_BEGIN
46
+
47
+ /**
48
+ * Initializes a condition variable.
49
+ */
50
+ AWS_COMMON_API
51
+ int aws_condition_variable_init(struct aws_condition_variable *condition_variable);
52
+
53
+ /**
54
+ * Cleans up a condition variable.
55
+ */
56
+ AWS_COMMON_API
57
+ void aws_condition_variable_clean_up(struct aws_condition_variable *condition_variable);
58
+
59
+ /**
60
+ * Notifies/Wakes one waiting thread
61
+ */
62
+ AWS_COMMON_API
63
+ int aws_condition_variable_notify_one(struct aws_condition_variable *condition_variable);
64
+
65
+ /**
66
+ * Notifies/Wakes all waiting threads.
67
+ */
68
+ AWS_COMMON_API
69
+ int aws_condition_variable_notify_all(struct aws_condition_variable *condition_variable);
70
+
71
+ /**
72
+ * Waits the calling thread on a notification from another thread. This function must be called with the mutex locked
73
+ * by the calling thread otherwise the behavior is undefined. Spurious wakeups can occur and to avoid this causing
74
+ * any problems use the _pred version of this function.
75
+ */
76
+ AWS_COMMON_API
77
+ int aws_condition_variable_wait(struct aws_condition_variable *condition_variable, struct aws_mutex *mutex);
78
+
79
+ /**
80
+ * Waits the calling thread on a notification from another thread. If predicate returns false, the wait is reentered,
81
+ * otherwise control returns to the caller. This function must be called with the mutex locked by the calling thread
82
+ * otherwise the behavior is undefined.
83
+ */
84
+ AWS_COMMON_API
85
+ int aws_condition_variable_wait_pred(
86
+ struct aws_condition_variable *condition_variable,
87
+ struct aws_mutex *mutex,
88
+ aws_condition_predicate_fn *pred,
89
+ void *pred_ctx);
90
+
91
+ /**
92
+ * Waits the calling thread on a notification from another thread. Times out after time_to_wait. time_to_wait is in
93
+ * nanoseconds. This function must be called with the mutex locked by the calling thread otherwise the behavior is
94
+ * undefined. Spurious wakeups can occur and to avoid this causing any problems use the _pred version of this function.
95
+ */
96
+ AWS_COMMON_API
97
+ int aws_condition_variable_wait_for(
98
+ struct aws_condition_variable *condition_variable,
99
+ struct aws_mutex *mutex,
100
+ int64_t time_to_wait);
101
+
102
+ /**
103
+ * Waits the calling thread on a notification from another thread. Times out after time_to_wait. time_to_wait is in
104
+ * nanoseconds. If predicate returns false, the wait is reentered, otherwise control returns to the caller. This
105
+ * function must be called with the mutex locked by the calling thread otherwise the behavior is undefined.
106
+ */
107
+ AWS_COMMON_API
108
+ int aws_condition_variable_wait_for_pred(
109
+ struct aws_condition_variable *condition_variable,
110
+ struct aws_mutex *mutex,
111
+ int64_t time_to_wait,
112
+ aws_condition_predicate_fn *pred,
113
+ void *pred_ctx);
114
+
115
+ AWS_EXTERN_C_END
116
+ AWS_POP_SANE_WARNING_LEVEL
117
+
118
+ #endif /* AWS_COMMON_CONDITION_VARIABLE_H */
include/aws/common/config.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CONFIG_H
2
+ #define AWS_COMMON_CONFIG_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ /*
10
+ * This header exposes compiler feature test results determined during cmake
11
+ * configure time to inline function implementations. The macros defined here
12
+ * should be considered to be an implementation detail, and can change at any
13
+ * time.
14
+ */
15
+ #define AWS_HAVE_GCC_OVERFLOW_MATH_EXTENSIONS
16
+ #define AWS_HAVE_GCC_INLINE_ASM
17
+ /* #undef AWS_HAVE_MSVC_INTRINSICS_X64 */
18
+ #define AWS_HAVE_POSIX_LARGE_FILE_SUPPORT
19
+ #define AWS_HAVE_EXECINFO
20
+ /* #undef AWS_HAVE_WINAPI_DESKTOP */
21
+ #define AWS_HAVE_LINUX_IF_LINK_H
22
+ #define AWS_HAVE_AVX2_INTRINSICS
23
+ #define AWS_HAVE_AVX512_INTRINSICS
24
+ #define AWS_HAVE_MM256_EXTRACT_EPI64
25
+ #define AWS_HAVE_CLMUL
26
+ /* #undef AWS_HAVE_ARM32_CRC */
27
+ /* #undef AWS_HAVE_ARMv8_1 */
28
+ /* #undef AWS_ARCH_ARM64 */
29
+ #define AWS_ARCH_INTEL
30
+ #define AWS_ARCH_INTEL_X64
31
+ #define AWS_USE_CPU_EXTENSIONS
32
+
33
+ #endif
include/aws/common/cpuid.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CPUID_H
2
+ #define AWS_COMMON_CPUID_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/common.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ enum aws_cpu_feature_name {
13
+ AWS_CPU_FEATURE_CLMUL,
14
+ AWS_CPU_FEATURE_SSE_4_1,
15
+ AWS_CPU_FEATURE_SSE_4_2,
16
+ AWS_CPU_FEATURE_AVX2,
17
+ AWS_CPU_FEATURE_AVX512,
18
+ AWS_CPU_FEATURE_ARM_CRC,
19
+ AWS_CPU_FEATURE_BMI2,
20
+ AWS_CPU_FEATURE_VPCLMULQDQ,
21
+ AWS_CPU_FEATURE_ARM_PMULL,
22
+ AWS_CPU_FEATURE_ARM_CRYPTO,
23
+ AWS_CPU_FEATURE_COUNT,
24
+ };
25
+
26
+ AWS_EXTERN_C_BEGIN
27
+
28
+ /**
29
+ * Returns true if a cpu feature is supported, false otherwise.
30
+ */
31
+ AWS_COMMON_API bool aws_cpu_has_feature(enum aws_cpu_feature_name feature_name);
32
+
33
+ AWS_EXTERN_C_END
34
+ AWS_POP_SANE_WARNING_LEVEL
35
+
36
+ #endif /* AWS_COMMON_CPUID_H */
include/aws/common/cross_process_lock.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_CROSS_PROCESS_LOCK_H
2
+ #define AWS_COMMON_CROSS_PROCESS_LOCK_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/byte_buf.h>
8
+ #include <aws/common/common.h>
9
+
10
+ struct aws_cross_process_lock;
11
+ AWS_EXTERN_C_BEGIN
12
+
13
+ /**
14
+ * Attempts to acquire a system-wide (not per process or per user) lock scoped by instance_nonce.
15
+ * For any given unique nonce, a lock will be returned by the first caller. Subsequent calls will
16
+ * return NULL and raise AWS_ERROR_MUTEX_CALLER_NOT_OWNER
17
+ * until the either the process owning the lock exits or the program owning the lock
18
+ * calls aws_cross_process_lock_release() explicitly.
19
+ *
20
+ * If the process exits before the lock is released, the kernel will unlock it for the next consumer.
21
+ */
22
+ AWS_COMMON_API
23
+ struct aws_cross_process_lock *aws_cross_process_lock_try_acquire(
24
+ struct aws_allocator *allocator,
25
+ struct aws_byte_cursor instance_nonce);
26
+
27
+ /**
28
+ * Releases the lock so the next caller (may be another process) can get an instance of the lock.
29
+ */
30
+ AWS_COMMON_API
31
+ void aws_cross_process_lock_release(struct aws_cross_process_lock *instance_lock);
32
+
33
+ AWS_EXTERN_C_END
34
+
35
+ #endif /* AWS_COMMON_CROSS_PROCESS_LOCK_H */
include/aws/common/date_time.h ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_DATE_TIME_H
2
+ #define AWS_COMMON_DATE_TIME_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/common.h>
8
+
9
+ #include <time.h>
10
+
11
+ AWS_PUSH_SANE_WARNING_LEVEL
12
+
13
+ enum {
14
+ AWS_DATE_TIME_STR_MAX_LEN = 100,
15
+ AWS_DATE_TIME_STR_MAX_BASIC_LEN = 20,
16
+ };
17
+
18
+ struct aws_byte_buf;
19
+ struct aws_byte_cursor;
20
+
21
+ enum aws_date_format {
22
+ AWS_DATE_FORMAT_RFC822,
23
+ AWS_DATE_FORMAT_ISO_8601,
24
+ AWS_DATE_FORMAT_ISO_8601_BASIC,
25
+ AWS_DATE_FORMAT_AUTO_DETECT,
26
+ };
27
+
28
+ enum aws_date_month {
29
+ AWS_DATE_MONTH_JANUARY = 0,
30
+ AWS_DATE_MONTH_FEBRUARY,
31
+ AWS_DATE_MONTH_MARCH,
32
+ AWS_DATE_MONTH_APRIL,
33
+ AWS_DATE_MONTH_MAY,
34
+ AWS_DATE_MONTH_JUNE,
35
+ AWS_DATE_MONTH_JULY,
36
+ AWS_DATE_MONTH_AUGUST,
37
+ AWS_DATE_MONTH_SEPTEMBER,
38
+ AWS_DATE_MONTH_OCTOBER,
39
+ AWS_DATE_MONTH_NOVEMBER,
40
+ AWS_DATE_MONTH_DECEMBER,
41
+ };
42
+
43
+ enum aws_date_day_of_week {
44
+ AWS_DATE_DAY_OF_WEEK_SUNDAY = 0,
45
+ AWS_DATE_DAY_OF_WEEK_MONDAY,
46
+ AWS_DATE_DAY_OF_WEEK_TUESDAY,
47
+ AWS_DATE_DAY_OF_WEEK_WEDNESDAY,
48
+ AWS_DATE_DAY_OF_WEEK_THURSDAY,
49
+ AWS_DATE_DAY_OF_WEEK_FRIDAY,
50
+ AWS_DATE_DAY_OF_WEEK_SATURDAY,
51
+ };
52
+
53
+ struct aws_date_time {
54
+ time_t timestamp;
55
+ uint16_t milliseconds;
56
+ char tz[6];
57
+ struct tm gmt_time;
58
+ struct tm local_time;
59
+ bool utc_assumed;
60
+ };
61
+
62
+ AWS_EXTERN_C_BEGIN
63
+
64
+ /**
65
+ * Initializes dt to be the current system time.
66
+ */
67
+ AWS_COMMON_API void aws_date_time_init_now(struct aws_date_time *dt);
68
+
69
+ /**
70
+ * Initializes dt to be the time represented in milliseconds since unix epoch.
71
+ */
72
+ AWS_COMMON_API void aws_date_time_init_epoch_millis(struct aws_date_time *dt, uint64_t ms_since_epoch);
73
+
74
+ /**
75
+ * Initializes dt to be the time represented in seconds.millis since unix epoch.
76
+ */
77
+ AWS_COMMON_API void aws_date_time_init_epoch_secs(struct aws_date_time *dt, double sec_ms);
78
+
79
+ /**
80
+ * Initializes dt to be the time represented by date_str in format 'fmt'. Returns AWS_OP_SUCCESS if the
81
+ * string was successfully parsed, returns AWS_OP_ERR if parsing failed.
82
+ *
83
+ * The parser is lenient regarding AWS_DATE_FORMAT_ISO_8601 vs AWS_DATE_FORMAT_ISO_8601_BASIC.
84
+ * Regardless of which you pass in, both "2002-10-02T08:05:09Z" and "20021002T080509Z" would be accepted.
85
+ *
86
+ * Notes for AWS_DATE_FORMAT_RFC822:
87
+ * If no time zone information is provided, it is assumed to be local time (please don't do this).
88
+ *
89
+ * Only time zones indicating Universal Time (e.g. Z, UT, UTC, or GMT),
90
+ * or offsets from UTC (e.g. +0100, -0700), are accepted.
91
+ *
92
+ * Really, it's just better if you always use Universal Time.
93
+ */
94
+ AWS_COMMON_API int aws_date_time_init_from_str(
95
+ struct aws_date_time *dt,
96
+ const struct aws_byte_buf *date_str,
97
+ enum aws_date_format fmt);
98
+
99
+ /**
100
+ * aws_date_time_init variant that takes a byte_cursor rather than a byte_buf
101
+ */
102
+ AWS_COMMON_API int aws_date_time_init_from_str_cursor(
103
+ struct aws_date_time *dt,
104
+ const struct aws_byte_cursor *date_str_cursor,
105
+ enum aws_date_format fmt);
106
+
107
+ /**
108
+ * Copies the current time as a formatted date string in local time into output_buf. If buffer is too small, it will
109
+ * return AWS_OP_ERR. A good size suggestion is AWS_DATE_TIME_STR_MAX_LEN bytes. AWS_DATE_FORMAT_AUTO_DETECT is not
110
+ * allowed.
111
+ */
112
+ AWS_COMMON_API int aws_date_time_to_local_time_str(
113
+ const struct aws_date_time *dt,
114
+ enum aws_date_format fmt,
115
+ struct aws_byte_buf *output_buf);
116
+
117
+ /**
118
+ * Copies the current time as a formatted date string in utc time into output_buf. If buffer is too small, it will
119
+ * return AWS_OP_ERR. A good size suggestion is AWS_DATE_TIME_STR_MAX_LEN bytes. AWS_DATE_FORMAT_AUTO_DETECT is not
120
+ * allowed.
121
+ */
122
+ AWS_COMMON_API int aws_date_time_to_utc_time_str(
123
+ const struct aws_date_time *dt,
124
+ enum aws_date_format fmt,
125
+ struct aws_byte_buf *output_buf);
126
+
127
+ /**
128
+ * Copies the current time as a formatted short date string in local time into output_buf. If buffer is too small, it
129
+ * will return AWS_OP_ERR. A good size suggestion is AWS_DATE_TIME_STR_MAX_LEN bytes. AWS_DATE_FORMAT_AUTO_DETECT is not
130
+ * allowed.
131
+ */
132
+ AWS_COMMON_API int aws_date_time_to_local_time_short_str(
133
+ const struct aws_date_time *dt,
134
+ enum aws_date_format fmt,
135
+ struct aws_byte_buf *output_buf);
136
+
137
+ /**
138
+ * Copies the current time as a formatted short date string in utc time into output_buf. If buffer is too small, it will
139
+ * return AWS_OP_ERR. A good size suggestion is AWS_DATE_TIME_STR_MAX_LEN bytes. AWS_DATE_FORMAT_AUTO_DETECT is not
140
+ * allowed.
141
+ */
142
+ AWS_COMMON_API int aws_date_time_to_utc_time_short_str(
143
+ const struct aws_date_time *dt,
144
+ enum aws_date_format fmt,
145
+ struct aws_byte_buf *output_buf);
146
+
147
+ AWS_COMMON_API double aws_date_time_as_epoch_secs(const struct aws_date_time *dt);
148
+ AWS_COMMON_API uint64_t aws_date_time_as_nanos(const struct aws_date_time *dt);
149
+ AWS_COMMON_API uint64_t aws_date_time_as_millis(const struct aws_date_time *dt);
150
+ AWS_COMMON_API uint16_t aws_date_time_year(const struct aws_date_time *dt, bool local_time);
151
+ AWS_COMMON_API enum aws_date_month aws_date_time_month(const struct aws_date_time *dt, bool local_time);
152
+ AWS_COMMON_API uint8_t aws_date_time_month_day(const struct aws_date_time *dt, bool local_time);
153
+ AWS_COMMON_API enum aws_date_day_of_week aws_date_time_day_of_week(const struct aws_date_time *dt, bool local_time);
154
+ AWS_COMMON_API uint8_t aws_date_time_hour(const struct aws_date_time *dt, bool local_time);
155
+ AWS_COMMON_API uint8_t aws_date_time_minute(const struct aws_date_time *dt, bool local_time);
156
+ AWS_COMMON_API uint8_t aws_date_time_second(const struct aws_date_time *dt, bool local_time);
157
+ AWS_COMMON_API bool aws_date_time_dst(const struct aws_date_time *dt, bool local_time);
158
+
159
+ /**
160
+ * returns the difference of a and b (a - b) in seconds.
161
+ */
162
+ AWS_COMMON_API time_t aws_date_time_diff(const struct aws_date_time *a, const struct aws_date_time *b);
163
+
164
+ AWS_EXTERN_C_END
165
+ AWS_POP_SANE_WARNING_LEVEL
166
+
167
+ #endif /* AWS_COMMON_DATE_TIME_H */
include/aws/common/device_random.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_DEVICE_RANDOM_H
2
+ #define AWS_COMMON_DEVICE_RANDOM_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/common.h>
8
+
9
+ AWS_PUSH_SANE_WARNING_LEVEL
10
+
11
+ struct aws_byte_buf;
12
+
13
+ AWS_EXTERN_C_BEGIN
14
+
15
+ /**
16
+ * Get an unpredictably random 64bit number, suitable for cryptographic use.
17
+ */
18
+ AWS_COMMON_API int aws_device_random_u64(uint64_t *output);
19
+
20
+ /**
21
+ * Get an unpredictably random 32bit number, suitable for cryptographic use.
22
+ */
23
+ AWS_COMMON_API int aws_device_random_u32(uint32_t *output);
24
+
25
+ /**
26
+ * Get an unpredictably random 16bit number, suitable for cryptographic use.
27
+ */
28
+ AWS_COMMON_API int aws_device_random_u16(uint16_t *output);
29
+
30
+ /**
31
+ * Get an unpredictably random 8bit number, suitable for cryptographic use.
32
+ */
33
+ AWS_COMMON_API int aws_device_random_u8(uint8_t *output);
34
+
35
+ /**
36
+ * Fill the rest of a buffer with unpredictably random bytes, suitable for cryptographic use.
37
+ */
38
+ AWS_COMMON_API int aws_device_random_buffer(struct aws_byte_buf *output);
39
+
40
+ /**
41
+ * Write N unpredictably random bytes to a buffer, suitable for cryptographic use.
42
+ * If there is insufficient space in the buffer, AWS_ERROR_SHORT_BUFFER is raised
43
+ * and the buffer will be unchanged.
44
+ */
45
+ AWS_COMMON_API int aws_device_random_buffer_append(struct aws_byte_buf *output, size_t n);
46
+
47
+ AWS_EXTERN_C_END
48
+ AWS_POP_SANE_WARNING_LEVEL
49
+
50
+ #endif /* AWS_COMMON_DEVICE_RANDOM_H */
include/aws/common/encoding.h ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ENCODING_H
2
+ #define AWS_COMMON_ENCODING_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/byte_order.h>
11
+ #include <aws/common/common.h>
12
+
13
+ #include <memory.h>
14
+
15
+ AWS_PUSH_SANE_WARNING_LEVEL
16
+ AWS_EXTERN_C_BEGIN
17
+
18
+ /*
19
+ * computes the length necessary to store the result of aws_hex_encode().
20
+ * returns -1 on failure, and 0 on success. encoded_length will be set on
21
+ * success.
22
+ */
23
+ AWS_COMMON_API
24
+ int aws_hex_compute_encoded_len(size_t to_encode_len, size_t *encoded_length);
25
+
26
+ /*
27
+ * Base 16 (hex) encodes the contents of to_encode and stores the result in
28
+ * output. Assumes the buffer is empty and does not resize on
29
+ * insufficient capacity.
30
+ */
31
+ AWS_COMMON_API
32
+ int aws_hex_encode(const struct aws_byte_cursor *AWS_RESTRICT to_encode, struct aws_byte_buf *AWS_RESTRICT output);
33
+
34
+ /*
35
+ * Base 16 (hex) encodes the contents of to_encode and appends the result in
36
+ * output. Grows the destination buffer dynamically if necessary.
37
+ */
38
+ AWS_COMMON_API
39
+ int aws_hex_encode_append_dynamic(
40
+ const struct aws_byte_cursor *AWS_RESTRICT to_encode,
41
+ struct aws_byte_buf *AWS_RESTRICT output);
42
+
43
+ /*
44
+ * computes the length necessary to store the result of aws_hex_decode().
45
+ * returns -1 on failure, and 0 on success. decoded_len will be set on success.
46
+ */
47
+ AWS_COMMON_API
48
+ int aws_hex_compute_decoded_len(size_t to_decode_len, size_t *decoded_len);
49
+
50
+ /*
51
+ * Base 16 (hex) decodes the contents of to_decode and stores the result in
52
+ * output. If output is NULL, output_size will be set to what the output_size
53
+ * should be.
54
+ */
55
+ AWS_COMMON_API
56
+ int aws_hex_decode(const struct aws_byte_cursor *AWS_RESTRICT to_decode, struct aws_byte_buf *AWS_RESTRICT output);
57
+
58
+ /*
59
+ * Computes the length necessary to store the output of aws_base64_encode call.
60
+ * returns -1 on failure, and 0 on success. encoded_length will be set on
61
+ * success.
62
+ */
63
+ AWS_COMMON_API
64
+ int aws_base64_compute_encoded_len(size_t to_encode_len, size_t *encoded_len);
65
+
66
+ /*
67
+ * Base 64 encodes the contents of to_encode and stores the result in output.
68
+ */
69
+ AWS_COMMON_API
70
+ int aws_base64_encode(const struct aws_byte_cursor *AWS_RESTRICT to_encode, struct aws_byte_buf *AWS_RESTRICT output);
71
+
72
+ /*
73
+ * Computes the length necessary to store the output of aws_base64_decode call.
74
+ * returns -1 on failure, and 0 on success. decoded_len will be set on success.
75
+ */
76
+ AWS_COMMON_API
77
+ int aws_base64_compute_decoded_len(const struct aws_byte_cursor *AWS_RESTRICT to_decode, size_t *decoded_len);
78
+
79
+ /*
80
+ * Base 64 decodes the contents of to_decode and stores the result in output.
81
+ */
82
+ AWS_COMMON_API
83
+ int aws_base64_decode(const struct aws_byte_cursor *AWS_RESTRICT to_decode, struct aws_byte_buf *AWS_RESTRICT output);
84
+
85
+ /* Add a 64 bit unsigned integer to the buffer, ensuring network - byte order
86
+ * Assumes the buffer size is at least 8 bytes.
87
+ */
88
+ AWS_STATIC_IMPL void aws_write_u64(uint64_t value, uint8_t *buffer);
89
+
90
+ /*
91
+ * Extracts a 64 bit unsigned integer from buffer. Ensures conversion from
92
+ * network byte order to host byte order. Assumes buffer size is at least 8
93
+ * bytes.
94
+ */
95
+ AWS_STATIC_IMPL uint64_t aws_read_u64(const uint8_t *buffer);
96
+
97
+ /* Add a 32 bit unsigned integer to the buffer, ensuring network - byte order
98
+ * Assumes the buffer size is at least 4 bytes.
99
+ */
100
+ AWS_STATIC_IMPL void aws_write_u32(uint32_t value, uint8_t *buffer);
101
+
102
+ /*
103
+ * Extracts a 32 bit unsigned integer from buffer. Ensures conversion from
104
+ * network byte order to host byte order. Assumes the buffer size is at least 4
105
+ * bytes.
106
+ */
107
+ AWS_STATIC_IMPL uint32_t aws_read_u32(const uint8_t *buffer);
108
+
109
+ /* Add a 24 bit unsigned integer to the buffer, ensuring network - byte order
110
+ * return the new position in the buffer for the next operation.
111
+ * Note, since this uses uint32_t for storage, the 3 least significant bytes
112
+ * will be used. Assumes buffer is at least 3 bytes long.
113
+ */
114
+ AWS_STATIC_IMPL void aws_write_u24(uint32_t value, uint8_t *buffer);
115
+ /*
116
+ * Extracts a 24 bit unsigned integer from buffer. Ensures conversion from
117
+ * network byte order to host byte order. Assumes buffer is at least 3 bytes
118
+ * long.
119
+ */
120
+ AWS_STATIC_IMPL uint32_t aws_read_u24(const uint8_t *buffer);
121
+
122
+ /* Add a 16 bit unsigned integer to the buffer, ensuring network-byte order
123
+ * return the new position in the buffer for the next operation.
124
+ * Assumes buffer is at least 2 bytes long.
125
+ */
126
+ AWS_STATIC_IMPL void aws_write_u16(uint16_t value, uint8_t *buffer);
127
+ /*
128
+ * Extracts a 16 bit unsigned integer from buffer. Ensures conversion from
129
+ * network byte order to host byte order. Assumes buffer is at least 2 bytes
130
+ * long.
131
+ */
132
+ AWS_STATIC_IMPL uint16_t aws_read_u16(const uint8_t *buffer);
133
+
134
+ enum aws_text_encoding {
135
+ AWS_TEXT_UNKNOWN,
136
+ AWS_TEXT_UTF8,
137
+ AWS_TEXT_UTF16,
138
+ AWS_TEXT_UTF32,
139
+ AWS_TEXT_ASCII,
140
+ };
141
+
142
+ /* Checks the BOM in the buffer to see if encoding can be determined. If there is no BOM or
143
+ * it is unrecognizable, then AWS_TEXT_UNKNOWN will be returned.
144
+ */
145
+ AWS_STATIC_IMPL enum aws_text_encoding aws_text_detect_encoding(const uint8_t *bytes, size_t size);
146
+
147
+ /*
148
+ * Returns true if aws_text_detect_encoding() determines the text is UTF8 or ASCII.
149
+ * Note that this immediately returns true if the UTF8 BOM is seen.
150
+ * To fully validate every byte, use aws_decode_utf8().
151
+ */
152
+ AWS_STATIC_IMPL bool aws_text_is_utf8(const uint8_t *bytes, size_t size);
153
+
154
+ struct aws_utf8_decoder_options {
155
+ /**
156
+ * Optional.
157
+ * Callback invoked for each Unicode codepoint.
158
+ * Use this callback to store codepoints as they're decoded,
159
+ * or to perform additional validation. RFC-3629 is already enforced,
160
+ * which forbids codepoints between U+D800 and U+DFFF,
161
+ * but you may whish to forbid codepoints like U+0000.
162
+ *
163
+ * @return AWS_OP_SUCCESS to continue processing the string, otherwise
164
+ * return AWS_OP_ERROR and raise an error (i.e. AWS_ERROR_INVALID_UTF8)
165
+ * to stop processing the string and report failure.
166
+ */
167
+ int (*on_codepoint)(uint32_t codepoint, void *user_data);
168
+
169
+ /* Optional. Pointer passed to on_codepoint callback. */
170
+ void *user_data;
171
+ };
172
+
173
+ /**
174
+ * Decode a complete string of UTF8/ASCII text.
175
+ * Text is always validated according to RFC-3629 (you may perform additional
176
+ * validation in the on_codepoint callback).
177
+ * The text does not need to begin with a UTF8 BOM.
178
+ * If you need to decode text incrementally as you receive it, use aws_utf8_decoder_new() instead.
179
+ *
180
+ * @param bytes Text to decode.
181
+ * @param options Options for decoding. If NULL is passed, the text is simply validated.
182
+ *
183
+ * @return AWS_OP_SUCCESS if successful.
184
+ * An error is raised if the text is not valid, or the on_codepoint callback raises an error.
185
+ */
186
+ AWS_COMMON_API int aws_decode_utf8(struct aws_byte_cursor bytes, const struct aws_utf8_decoder_options *options);
187
+
188
+ struct aws_utf8_decoder;
189
+
190
+ /**
191
+ * Create a UTF8/ASCII decoder, which can process text incrementally as you receive it.
192
+ * Text is always validated according to RFC-3629 (you may perform additional
193
+ * validation in the on_codepoint callback).
194
+ * The text does not need to begin with a UTF8 BOM.
195
+ * To decode text all at once, simply use aws_decode_utf8().
196
+ *
197
+ * Feed bytes into the decoder with aws_utf8_decoder_update(),
198
+ * and call aws_utf8_decoder_finalize() when the text is complete.
199
+ *
200
+ * @param allocator Allocator
201
+ * @param options Options for decoder. If NULL is passed, the text is simply validated.
202
+ */
203
+ AWS_COMMON_API struct aws_utf8_decoder *aws_utf8_decoder_new(
204
+ struct aws_allocator *allocator,
205
+ const struct aws_utf8_decoder_options *options);
206
+
207
+ AWS_COMMON_API void aws_utf8_decoder_destroy(struct aws_utf8_decoder *decoder);
208
+ AWS_COMMON_API void aws_utf8_decoder_reset(struct aws_utf8_decoder *decoder);
209
+
210
+ /**
211
+ * Update the decoder with more bytes of text.
212
+ * The on_codepoint callback will be invoked for each codepoint encountered.
213
+ * Raises an error if invalid UTF8 is encountered or the on_codepoint callback reports an error.
214
+ *
215
+ * Note: You must call aws_utf8_decoder_finalize() when the text is 100% complete,
216
+ * to ensure the input was completely valid.
217
+ */
218
+ AWS_COMMON_API int aws_utf8_decoder_update(struct aws_utf8_decoder *decoder, struct aws_byte_cursor bytes);
219
+
220
+ /**
221
+ * Tell the decoder that you've reached the end of your text.
222
+ * Raises AWS_ERROR_INVALID_UTF8 if the text did not end with a complete UTF8 codepoint.
223
+ * This also resets the decoder.
224
+ */
225
+ AWS_COMMON_API int aws_utf8_decoder_finalize(struct aws_utf8_decoder *decoder);
226
+
227
+ AWS_EXTERN_C_END
228
+
229
+ #ifndef AWS_NO_STATIC_IMPL
230
+ # include <aws/common/encoding.inl>
231
+ #endif /* AWS_NO_STATIC_IMPL */
232
+
233
+ AWS_POP_SANE_WARNING_LEVEL
234
+
235
+ #endif /* AWS_COMMON_ENCODING_H */
include/aws/common/encoding.inl ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ENCODING_INL
2
+ #define AWS_COMMON_ENCODING_INL
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/byte_order.h>
11
+ #include <aws/common/common.h>
12
+ #include <aws/common/encoding.h>
13
+
14
+ AWS_EXTERN_C_BEGIN
15
+
16
+ /* Add a 64 bit unsigned integer to the buffer, ensuring network - byte order
17
+ * Assumes the buffer size is at least 8 bytes.
18
+ */
19
+ AWS_STATIC_IMPL void aws_write_u64(uint64_t value, uint8_t *buffer) {
20
+ value = aws_hton64(value);
21
+
22
+ memcpy((void *)buffer, &value, sizeof(value));
23
+ }
24
+
25
+ /*
26
+ * Extracts a 64 bit unsigned integer from buffer. Ensures conversion from
27
+ * network byte order to host byte order. Assumes buffer size is at least 8
28
+ * bytes.
29
+ */
30
+ AWS_STATIC_IMPL uint64_t aws_read_u64(const uint8_t *buffer) {
31
+ uint64_t value = 0;
32
+ memcpy((void *)&value, (void *)buffer, sizeof(value));
33
+
34
+ return aws_ntoh64(value);
35
+ }
36
+
37
+ /* Add a 32 bit unsigned integer to the buffer, ensuring network - byte order
38
+ * Assumes the buffer size is at least 4 bytes.
39
+ */
40
+ AWS_STATIC_IMPL void aws_write_u32(uint32_t value, uint8_t *buffer) {
41
+ value = aws_hton32(value);
42
+
43
+ memcpy((void *)buffer, (void *)&value, sizeof(value));
44
+ }
45
+
46
+ /*
47
+ * Extracts a 32 bit unsigned integer from buffer. Ensures conversion from
48
+ * network byte order to host byte order. Assumes the buffer size is at least 4
49
+ * bytes.
50
+ */
51
+ AWS_STATIC_IMPL uint32_t aws_read_u32(const uint8_t *buffer) {
52
+ uint32_t value = 0;
53
+ memcpy((void *)&value, (void *)buffer, sizeof(value));
54
+
55
+ return aws_ntoh32(value);
56
+ }
57
+
58
+ /* Add a 24 bit unsigned integer to the buffer, ensuring network - byte order
59
+ * return the new position in the buffer for the next operation.
60
+ * Note, since this uses uint32_t for storage, the 3 least significant bytes
61
+ * will be used. Assumes buffer is at least 3 bytes long.
62
+ */
63
+ AWS_STATIC_IMPL void aws_write_u24(uint32_t value, uint8_t *buffer) {
64
+ value = aws_hton32(value);
65
+ memcpy((void *)buffer, (void *)((uint8_t *)&value + 1), sizeof(value) - 1);
66
+ }
67
+
68
+ /*
69
+ * Extracts a 24 bit unsigned integer from buffer. Ensures conversion from
70
+ * network byte order to host byte order. Assumes buffer is at least 3 bytes
71
+ * long.
72
+ */
73
+ AWS_STATIC_IMPL uint32_t aws_read_u24(const uint8_t *buffer) {
74
+ uint32_t value = 0;
75
+ memcpy((void *)((uint8_t *)&value + 1), (void *)buffer, sizeof(value) - 1);
76
+
77
+ return aws_ntoh32(value);
78
+ }
79
+
80
+ /* Add a 16 bit unsigned integer to the buffer, ensuring network-byte order
81
+ * return the new position in the buffer for the next operation.
82
+ * Assumes buffer is at least 2 bytes long.
83
+ */
84
+ AWS_STATIC_IMPL void aws_write_u16(uint16_t value, uint8_t *buffer) {
85
+ value = aws_hton16(value);
86
+
87
+ memcpy((void *)buffer, (void *)&value, sizeof(value));
88
+ }
89
+
90
+ /*
91
+ * Extracts a 16 bit unsigned integer from buffer. Ensures conversion from
92
+ * network byte order to host byte order. Assumes buffer is at least 2 bytes
93
+ * long.
94
+ */
95
+ AWS_STATIC_IMPL uint16_t aws_read_u16(const uint8_t *buffer) {
96
+ uint16_t value = 0;
97
+ memcpy((void *)&value, (void *)buffer, sizeof(value));
98
+
99
+ return aws_ntoh16(value);
100
+ }
101
+
102
+ /* Reference: https://unicodebook.readthedocs.io/guess_encoding.html */
103
+ AWS_STATIC_IMPL enum aws_text_encoding aws_text_detect_encoding(const uint8_t *bytes, size_t size) {
104
+ static const char *UTF_8_BOM = "\xEF\xBB\xBF";
105
+ static const char *UTF_16_BE_BOM = "\xFE\xFF";
106
+ static const char *UTF_16_LE_BOM = "\xFF\xFE";
107
+ static const char *UTF_32_BE_BOM = "\x00\x00\xFE\xFF";
108
+ static const char *UTF_32_LE_BOM = "\xFF\xFE\x00\x00";
109
+
110
+ if (size >= 3) {
111
+ if (memcmp(bytes, UTF_8_BOM, 3) == 0)
112
+ return AWS_TEXT_UTF8;
113
+ }
114
+ if (size >= 4) {
115
+ if (memcmp(bytes, UTF_32_LE_BOM, 4) == 0)
116
+ return AWS_TEXT_UTF32;
117
+ if (memcmp(bytes, UTF_32_BE_BOM, 4) == 0)
118
+ return AWS_TEXT_UTF32;
119
+ }
120
+ if (size >= 2) {
121
+ if (memcmp(bytes, UTF_16_LE_BOM, 2) == 0)
122
+ return AWS_TEXT_UTF16;
123
+ if (memcmp(bytes, UTF_16_BE_BOM, 2) == 0)
124
+ return AWS_TEXT_UTF16;
125
+ }
126
+ size_t idx = 0;
127
+ for (; idx < size; ++idx) {
128
+ if (bytes[idx] & 0x80) {
129
+ return AWS_TEXT_UNKNOWN;
130
+ }
131
+ }
132
+ return AWS_TEXT_ASCII;
133
+ }
134
+
135
+ AWS_STATIC_IMPL bool aws_text_is_utf8(const uint8_t *bytes, size_t size) {
136
+ enum aws_text_encoding encoding = aws_text_detect_encoding(bytes, size);
137
+ return encoding == AWS_TEXT_UTF8 || encoding == AWS_TEXT_ASCII;
138
+ }
139
+
140
+ AWS_EXTERN_C_END
141
+
142
+ #endif /* AWS_COMMON_ENCODING_INL */
include/aws/common/environment.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ENVIRONMENT_H
2
+ #define AWS_COMMON_ENVIRONMENT_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+
11
+ AWS_PUSH_SANE_WARNING_LEVEL
12
+
13
+ struct aws_string;
14
+
15
+ /*
16
+ * Simple shims to the appropriate platform calls for environment variable manipulation.
17
+ *
18
+ * Not thread safe to use set/unset unsynced with get. Set/unset only used in unit tests.
19
+ */
20
+ AWS_EXTERN_C_BEGIN
21
+
22
+ /*
23
+ * Get the value of an environment variable. If the variable is not set, the output string will be set to NULL.
24
+ * Not thread-safe
25
+ */
26
+ AWS_COMMON_API
27
+ struct aws_string *aws_get_env(struct aws_allocator *allocator, const char *name);
28
+
29
+ /*
30
+ * Get the value of an environment variable. If the variable is not set or is empty, the output string will be set to
31
+ * NULL. Not thread-safe
32
+ */
33
+ AWS_COMMON_API
34
+ struct aws_string *aws_get_env_nonempty(struct aws_allocator *allocator, const char *name);
35
+
36
+ /*
37
+ * *DEPRECATED*
38
+ * Please use the `aws_get_env` or `aws_get_env_nonempty` instead.
39
+ * Get the value of an environment variable. If the variable is not set, the output string will be set to NULL.
40
+ * Not thread-safe
41
+ */
42
+ AWS_COMMON_API
43
+ int aws_get_environment_value(
44
+ struct aws_allocator *allocator,
45
+ const struct aws_string *variable_name,
46
+ struct aws_string **value_out);
47
+
48
+ /*
49
+ * Set the value of an environment variable. On Windows, setting a variable to the empty string will actually unset it.
50
+ * Not thread-safe
51
+ */
52
+ AWS_COMMON_API
53
+ int aws_set_environment_value(const struct aws_string *variable_name, const struct aws_string *value);
54
+
55
+ /*
56
+ * Unset an environment variable.
57
+ * Not thread-safe
58
+ */
59
+ AWS_COMMON_API
60
+ int aws_unset_environment_value(const struct aws_string *variable_name);
61
+
62
+ AWS_EXTERN_C_END
63
+ AWS_POP_SANE_WARNING_LEVEL
64
+
65
+ #endif /* AWS_COMMON_ENVIRONMENT_H */
include/aws/common/error.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_ERROR_H
2
+ #define AWS_COMMON_ERROR_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/assert.h>
10
+ #include <aws/common/exports.h>
11
+ #include <aws/common/macros.h>
12
+ #include <aws/common/package.h>
13
+ #include <aws/common/stdint.h>
14
+
15
+ AWS_PUSH_SANE_WARNING_LEVEL
16
+
17
+ #define AWS_OP_SUCCESS (0)
18
+ #define AWS_OP_ERR (-1)
19
+
20
+ /* Each library gets space for 2^^10 error entries */
21
+ #define AWS_ERROR_ENUM_STRIDE_BITS 10
22
+ #define AWS_ERROR_ENUM_STRIDE (1U << AWS_ERROR_ENUM_STRIDE_BITS)
23
+ #define AWS_ERROR_ENUM_BEGIN_RANGE(x) ((x) * AWS_ERROR_ENUM_STRIDE)
24
+ #define AWS_ERROR_ENUM_END_RANGE(x) (((x) + 1) * AWS_ERROR_ENUM_STRIDE - 1)
25
+
26
+ struct aws_error_info {
27
+ int error_code;
28
+ const char *literal_name;
29
+ const char *error_str;
30
+ const char *lib_name;
31
+ const char *formatted_name;
32
+ };
33
+
34
+ struct aws_error_info_list {
35
+ const struct aws_error_info *error_list;
36
+ uint16_t count;
37
+ };
38
+
39
+ #define AWS_DEFINE_ERROR_INFO(C, ES, LN) \
40
+ { \
41
+ .literal_name = #C, \
42
+ .error_code = (C), \
43
+ .error_str = (ES), \
44
+ .lib_name = (LN), \
45
+ .formatted_name = LN ": " #C ", " ES, \
46
+ }
47
+
48
+ typedef void(aws_error_handler_fn)(int err, void *ctx);
49
+
50
+ AWS_EXTERN_C_BEGIN
51
+
52
+ /*
53
+ * Returns the latest error code on the current thread, or 0 if none have
54
+ * occurred.
55
+ */
56
+ AWS_COMMON_API
57
+ int aws_last_error(void);
58
+
59
+ /*
60
+ * Returns the error str corresponding to `err`.
61
+ */
62
+ AWS_COMMON_API
63
+ const char *aws_error_str(int err);
64
+
65
+ /*
66
+ * Returns the enum name corresponding to `err`.
67
+ */
68
+ AWS_COMMON_API
69
+ const char *aws_error_name(int err);
70
+
71
+ /*
72
+ * Returns the error lib name corresponding to `err`.
73
+ */
74
+ AWS_COMMON_API
75
+ const char *aws_error_lib_name(int err);
76
+
77
+ /*
78
+ * Returns libname concatenated with error string.
79
+ */
80
+ AWS_COMMON_API
81
+ const char *aws_error_debug_str(int err);
82
+
83
+ /*
84
+ * Internal implementation detail.
85
+ */
86
+ AWS_COMMON_API
87
+ void aws_raise_error_private(int err);
88
+
89
+ /*
90
+ * Raises `err` to the installed callbacks, and sets the thread's error.
91
+ */
92
+ AWS_STATIC_IMPL
93
+ int aws_raise_error(int err);
94
+
95
+ /*
96
+ * Resets the `err` back to defaults
97
+ */
98
+ AWS_COMMON_API
99
+ void aws_reset_error(void);
100
+ /*
101
+ * Sets `err` to the latest error. Does not invoke callbacks.
102
+ */
103
+ AWS_COMMON_API
104
+ void aws_restore_error(int err);
105
+
106
+ /*
107
+ * Sets an application wide error handler function. This will be overridden by
108
+ * the thread local handler. The previous handler is returned, this can be used
109
+ * for restoring an error handler if it needs to be overridden temporarily.
110
+ * Setting this to NULL will turn off this error callback after it has been
111
+ * enabled.
112
+ */
113
+ AWS_COMMON_API
114
+ aws_error_handler_fn *aws_set_global_error_handler_fn(aws_error_handler_fn *handler, void *ctx);
115
+
116
+ /*
117
+ * Sets a thread-local error handler function. This will override the global
118
+ * handler. The previous handler is returned, this can be used for restoring an
119
+ * error handler if it needs to be overridden temporarily. Setting this to NULL
120
+ * will turn off this error callback after it has been enabled.
121
+ */
122
+ AWS_COMMON_API
123
+ aws_error_handler_fn *aws_set_thread_local_error_handler_fn(aws_error_handler_fn *handler, void *ctx);
124
+
125
+ /** TODO: this needs to be a private function (wait till we have the cmake story
126
+ * better before moving it though). It should be external for the purpose of
127
+ * other libs we own, but customers should not be able to hit it without going
128
+ * out of their way to do so.
129
+ */
130
+ AWS_COMMON_API
131
+ void aws_register_error_info(const struct aws_error_info_list *error_info);
132
+
133
+ AWS_COMMON_API
134
+ void aws_unregister_error_info(const struct aws_error_info_list *error_info);
135
+
136
+ /**
137
+ * Convert a c library io error into an aws error, and raise it.
138
+ * If no conversion is found, fallback_aws_error_code is raised.
139
+ * Always returns AWS_OP_ERR.
140
+ */
141
+ AWS_COMMON_API
142
+ int aws_translate_and_raise_io_error_or(int error_no, int fallback_aws_error_code);
143
+
144
+ /**
145
+ * Convert a c library io error into an aws error, and raise it.
146
+ * If no conversion is found, AWS_ERROR_SYS_CALL_FAILURE is raised.
147
+ * Always returns AWS_OP_ERR.
148
+ */
149
+ AWS_COMMON_API
150
+ int aws_translate_and_raise_io_error(int error_no);
151
+
152
+ AWS_EXTERN_C_END
153
+ #ifndef AWS_NO_STATIC_IMPL
154
+ # include <aws/common/error.inl>
155
+ #endif /* AWS_NO_STATIC_IMPL */
156
+
157
+ enum aws_common_error {
158
+ AWS_ERROR_SUCCESS = AWS_ERROR_ENUM_BEGIN_RANGE(AWS_C_COMMON_PACKAGE_ID),
159
+ AWS_ERROR_OOM,
160
+ AWS_ERROR_NO_SPACE,
161
+ AWS_ERROR_UNKNOWN,
162
+ AWS_ERROR_SHORT_BUFFER,
163
+ AWS_ERROR_OVERFLOW_DETECTED,
164
+ AWS_ERROR_UNSUPPORTED_OPERATION,
165
+ AWS_ERROR_INVALID_BUFFER_SIZE,
166
+ AWS_ERROR_INVALID_HEX_STR,
167
+ AWS_ERROR_INVALID_BASE64_STR,
168
+ AWS_ERROR_INVALID_INDEX,
169
+ AWS_ERROR_THREAD_INVALID_SETTINGS,
170
+ AWS_ERROR_THREAD_INSUFFICIENT_RESOURCE,
171
+ AWS_ERROR_THREAD_NO_PERMISSIONS,
172
+ AWS_ERROR_THREAD_NOT_JOINABLE,
173
+ AWS_ERROR_THREAD_NO_SUCH_THREAD_ID,
174
+ AWS_ERROR_THREAD_DEADLOCK_DETECTED,
175
+ AWS_ERROR_MUTEX_NOT_INIT,
176
+ AWS_ERROR_MUTEX_TIMEOUT,
177
+ AWS_ERROR_MUTEX_CALLER_NOT_OWNER,
178
+ AWS_ERROR_MUTEX_FAILED,
179
+ AWS_ERROR_COND_VARIABLE_INIT_FAILED,
180
+ AWS_ERROR_COND_VARIABLE_TIMED_OUT,
181
+ AWS_ERROR_COND_VARIABLE_ERROR_UNKNOWN,
182
+ AWS_ERROR_CLOCK_FAILURE,
183
+ AWS_ERROR_LIST_EMPTY,
184
+ AWS_ERROR_DEST_COPY_TOO_SMALL,
185
+ AWS_ERROR_LIST_EXCEEDS_MAX_SIZE,
186
+ AWS_ERROR_LIST_STATIC_MODE_CANT_SHRINK,
187
+ AWS_ERROR_PRIORITY_QUEUE_FULL,
188
+ AWS_ERROR_PRIORITY_QUEUE_EMPTY,
189
+ AWS_ERROR_PRIORITY_QUEUE_BAD_NODE,
190
+ AWS_ERROR_HASHTBL_ITEM_NOT_FOUND,
191
+ AWS_ERROR_INVALID_DATE_STR,
192
+ AWS_ERROR_INVALID_ARGUMENT,
193
+ AWS_ERROR_RANDOM_GEN_FAILED,
194
+ AWS_ERROR_MALFORMED_INPUT_STRING,
195
+ AWS_ERROR_UNIMPLEMENTED,
196
+ AWS_ERROR_INVALID_STATE,
197
+ AWS_ERROR_ENVIRONMENT_GET,
198
+ AWS_ERROR_ENVIRONMENT_SET,
199
+ AWS_ERROR_ENVIRONMENT_UNSET,
200
+ AWS_ERROR_STREAM_UNSEEKABLE,
201
+ AWS_ERROR_NO_PERMISSION,
202
+ AWS_ERROR_FILE_INVALID_PATH,
203
+ AWS_ERROR_MAX_FDS_EXCEEDED,
204
+ AWS_ERROR_SYS_CALL_FAILURE,
205
+ AWS_ERROR_C_STRING_BUFFER_NOT_NULL_TERMINATED,
206
+ AWS_ERROR_STRING_MATCH_NOT_FOUND,
207
+ AWS_ERROR_DIVIDE_BY_ZERO,
208
+ AWS_ERROR_INVALID_FILE_HANDLE,
209
+ AWS_ERROR_OPERATION_INTERUPTED,
210
+ AWS_ERROR_DIRECTORY_NOT_EMPTY,
211
+ AWS_ERROR_PLATFORM_NOT_SUPPORTED,
212
+ AWS_ERROR_INVALID_UTF8,
213
+ AWS_ERROR_GET_HOME_DIRECTORY_FAILED,
214
+ AWS_ERROR_INVALID_XML,
215
+ AWS_ERROR_FILE_OPEN_FAILURE,
216
+ AWS_ERROR_FILE_READ_FAILURE,
217
+ AWS_ERROR_FILE_WRITE_FAILURE,
218
+ AWS_ERROR_INVALID_CBOR,
219
+ AWS_ERROR_CBOR_UNEXPECTED_TYPE,
220
+ AWS_ERROR_END_COMMON_RANGE = AWS_ERROR_ENUM_END_RANGE(AWS_C_COMMON_PACKAGE_ID)
221
+ };
222
+
223
+ AWS_POP_SANE_WARNING_LEVEL
224
+
225
+ #endif /* AWS_COMMON_ERROR_H */
include/aws/common/exports.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_EXPORTS_H
2
+ #define AWS_COMMON_EXPORTS_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #if defined(AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined(_WIN32)
8
+ # ifdef AWS_COMMON_USE_IMPORT_EXPORT
9
+ # ifdef AWS_COMMON_EXPORTS
10
+ # define AWS_COMMON_API __declspec(dllexport)
11
+ # else
12
+ # define AWS_COMMON_API __declspec(dllimport)
13
+ # endif /* AWS_COMMON_EXPORTS */
14
+ # else
15
+ # define AWS_COMMON_API
16
+ # endif /* AWS_COMMON_USE_IMPORT_EXPORT */
17
+
18
+ #else /* defined (AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined (_WIN32) */
19
+
20
+ # if defined(AWS_COMMON_USE_IMPORT_EXPORT) && defined(AWS_COMMON_EXPORTS)
21
+ # define AWS_COMMON_API __attribute__((visibility("default")))
22
+ # else
23
+ # define AWS_COMMON_API
24
+ # endif
25
+
26
+ #endif /* defined (AWS_CRT_USE_WINDOWS_DLL_SEMANTICS) || defined (_WIN32) */
27
+
28
+ #ifdef AWS_NO_STATIC_IMPL
29
+ # define AWS_STATIC_IMPL AWS_COMMON_API
30
+ #endif
31
+
32
+ #ifndef AWS_STATIC_IMPL
33
+ /*
34
+ * In order to allow us to export our inlinable methods in a DLL/.so, we have a designated .c
35
+ * file where this AWS_STATIC_IMPL macro will be redefined to be non-static.
36
+ */
37
+ # define AWS_STATIC_IMPL static inline
38
+ #endif
39
+
40
+ #endif /* AWS_COMMON_EXPORTS_H */
include/aws/common/fifo_cache.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_FIFO_CACHE_H
2
+ #define AWS_COMMON_FIFO_CACHE_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/cache.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+ AWS_EXTERN_C_BEGIN
12
+
13
+ /**
14
+ * Initializes the first-in-first-out cache. Sets up the underlying linked hash table.
15
+ * Once `max_items` elements have been added, the oldest(first-in) item will
16
+ * be removed. For the other parameters, see aws/common/hash_table.h. Hash table
17
+ * semantics of these arguments are preserved.
18
+ */
19
+ AWS_COMMON_API
20
+ struct aws_cache *aws_cache_new_fifo(
21
+ struct aws_allocator *allocator,
22
+ aws_hash_fn *hash_fn,
23
+ aws_hash_callback_eq_fn *equals_fn,
24
+ aws_hash_callback_destroy_fn *destroy_key_fn,
25
+ aws_hash_callback_destroy_fn *destroy_value_fn,
26
+ size_t max_items);
27
+
28
+ AWS_EXTERN_C_END
29
+ AWS_POP_SANE_WARNING_LEVEL
30
+
31
+ #endif /* AWS_COMMON_FIFO_CACHE_H */
include/aws/common/file.h ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_FILE_H
2
+ #define AWS_COMMON_FILE_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/byte_buf.h>
8
+ #include <aws/common/common.h>
9
+ #include <aws/common/platform.h>
10
+ #include <stdio.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+
14
+ #ifdef AWS_OS_WINDOWS
15
+ # define AWS_PATH_DELIM '\\'
16
+ # define AWS_PATH_DELIM_STR "\\"
17
+ #else
18
+ # define AWS_PATH_DELIM '/'
19
+ # define AWS_PATH_DELIM_STR "/"
20
+ #endif
21
+
22
+ struct aws_string;
23
+ struct aws_directory_iterator;
24
+
25
+ enum aws_file_type {
26
+ AWS_FILE_TYPE_FILE = 1,
27
+ AWS_FILE_TYPE_SYM_LINK = 2,
28
+ AWS_FILE_TYPE_DIRECTORY = 4,
29
+ };
30
+
31
+ struct aws_directory_entry {
32
+ /**
33
+ * Absolute path to the entry from the current process root.
34
+ */
35
+ struct aws_byte_cursor path;
36
+ /**
37
+ * Path to the entry relative to the current working directory.
38
+ */
39
+ struct aws_byte_cursor relative_path;
40
+ /**
41
+ * Bit-field of enum aws_file_type
42
+ */
43
+ int file_type;
44
+ /**
45
+ * Size of the file on disk.
46
+ */
47
+ int64_t file_size;
48
+ };
49
+
50
+ /**
51
+ * Invoked during calls to aws_directory_traverse() as an entry is encountered. entry will contain
52
+ * the parsed directory entry info.
53
+ *
54
+ * Return true to continue the traversal, or alternatively, if you have a reason to abort the traversal, return false.
55
+ */
56
+ typedef bool(aws_on_directory_entry)(const struct aws_directory_entry *entry, void *user_data);
57
+
58
+ AWS_EXTERN_C_BEGIN
59
+
60
+ /**
61
+ * Deprecated - Use aws_fopen_safe() instead, avoid const char * in public APIs.
62
+ * Opens file at file_path using mode. Returns the FILE pointer if successful.
63
+ * Otherwise, aws_last_error() will contain the error that occurred
64
+ */
65
+ AWS_COMMON_API FILE *aws_fopen(const char *file_path, const char *mode);
66
+
67
+ /**
68
+ * Opens file at file_path using mode. Returns the FILE pointer if successful.
69
+ * Otherwise, aws_last_error() will contain the error that occurred
70
+ */
71
+ AWS_COMMON_API FILE *aws_fopen_safe(const struct aws_string *file_path, const struct aws_string *mode);
72
+
73
+ /**
74
+ * Creates a directory if it doesn't currently exist. If the directory already exists, it's ignored and assumed
75
+ * successful.
76
+ *
77
+ * Returns AWS_OP_SUCCESS on success. Otherwise, check aws_last_error().
78
+ */
79
+ AWS_COMMON_API int aws_directory_create(const struct aws_string *dir_path);
80
+ /**
81
+ * Returns true if the directory currently exists. Otherwise, it returns false.
82
+ */
83
+ AWS_COMMON_API bool aws_directory_exists(const struct aws_string *dir_path);
84
+ /**
85
+ * Deletes a directory. If the directory is not empty, this will fail unless the recursive parameter is set to true.
86
+ * If recursive is true then the entire directory and all of its contents will be deleted. If it is set to false,
87
+ * the directory will be deleted only if it is empty. Returns AWS_OP_SUCCESS if the operation was successful. Otherwise,
88
+ * aws_last_error() will contain the error that occurred. If the directory doesn't exist, AWS_OP_SUCCESS is still
89
+ * returned.
90
+ */
91
+ AWS_COMMON_API int aws_directory_delete(const struct aws_string *dir_path, bool recursive);
92
+ /**
93
+ * Deletes a file. Returns AWS_OP_SUCCESS if the operation was successful. Otherwise,
94
+ * aws_last_error() will contain the error that occurred. If the file doesn't exist, AWS_OP_SUCCESS is still returned.
95
+ */
96
+ AWS_COMMON_API int aws_file_delete(const struct aws_string *file_path);
97
+
98
+ /**
99
+ * Moves directory at from to to.
100
+ * Returns AWS_OP_SUCCESS if the operation was successful. Otherwise,
101
+ * aws_last_error() will contain the error that occurred.
102
+ */
103
+ AWS_COMMON_API int aws_directory_or_file_move(const struct aws_string *from, const struct aws_string *to);
104
+
105
+ /**
106
+ * Traverse a directory starting at path.
107
+ *
108
+ * If you want the traversal to recurse the entire directory, pass recursive as true. Passing false for this parameter
109
+ * will only iterate the contents of the directory, but will not descend into any directories it encounters.
110
+ *
111
+ * If recursive is set to true, the traversal is performed post-order, depth-first
112
+ * (for practical reasons such as deleting a directory that contains subdirectories or files).
113
+ *
114
+ * returns AWS_OP_SUCCESS(0) on success.
115
+ */
116
+ AWS_COMMON_API int aws_directory_traverse(
117
+ struct aws_allocator *allocator,
118
+ const struct aws_string *path,
119
+ bool recursive,
120
+ aws_on_directory_entry *on_entry,
121
+ void *user_data);
122
+
123
+ /**
124
+ * Creates a read-only iterator of a directory starting at path. If path is invalid or there's any other error
125
+ * condition, NULL will be returned. Call aws_last_error() for the exact error in that case.
126
+ */
127
+ AWS_COMMON_API struct aws_directory_iterator *aws_directory_entry_iterator_new(
128
+ struct aws_allocator *allocator,
129
+ const struct aws_string *path);
130
+
131
+ /**
132
+ * Moves the iterator to the next entry. Returns AWS_OP_SUCCESS if another entry is available, or AWS_OP_ERR with
133
+ * AWS_ERROR_LIST_EMPTY as the value for aws_last_error() if no more entries are available.
134
+ */
135
+ AWS_COMMON_API int aws_directory_entry_iterator_next(struct aws_directory_iterator *iterator);
136
+
137
+ /**
138
+ * Moves the iterator to the previous entry. Returns AWS_OP_SUCCESS if another entry is available, or AWS_OP_ERR with
139
+ * AWS_ERROR_LIST_EMPTY as the value for aws_last_error() if no more entries are available.
140
+ */
141
+ AWS_COMMON_API int aws_directory_entry_iterator_previous(struct aws_directory_iterator *iterator);
142
+
143
+ /**
144
+ * Cleanup and deallocate iterator
145
+ */
146
+ AWS_COMMON_API void aws_directory_entry_iterator_destroy(struct aws_directory_iterator *iterator);
147
+
148
+ /**
149
+ * Gets the aws_directory_entry value for iterator at the current position. Returns NULL if the iterator contains no
150
+ * entries.
151
+ */
152
+ AWS_COMMON_API const struct aws_directory_entry *aws_directory_entry_iterator_get_value(
153
+ const struct aws_directory_iterator *iterator);
154
+
155
+ /**
156
+ * Returns true iff the character is a directory separator on ANY supported platform.
157
+ */
158
+ AWS_COMMON_API
159
+ bool aws_is_any_directory_separator(char value);
160
+
161
+ /**
162
+ * Returns the directory separator used by the local platform
163
+ */
164
+ AWS_COMMON_API
165
+ char aws_get_platform_directory_separator(void);
166
+
167
+ /**
168
+ * Normalizes the path by replacing any directory separator with the local platform's directory separator.
169
+ * @param path path to normalize. Must be writeable.
170
+ */
171
+ AWS_COMMON_API
172
+ void aws_normalize_directory_separator(struct aws_byte_buf *path);
173
+
174
+ /**
175
+ * Returns the current user's home directory.
176
+ */
177
+ AWS_COMMON_API
178
+ struct aws_string *aws_get_home_directory(struct aws_allocator *allocator);
179
+
180
+ /**
181
+ * Returns true if a file or path exists, otherwise, false.
182
+ */
183
+ AWS_COMMON_API
184
+ bool aws_path_exists(const struct aws_string *path);
185
+
186
+ /*
187
+ * Wrapper for highest-resolution platform-dependent seek implementation.
188
+ * Maps to:
189
+ *
190
+ * _fseeki64() on windows
191
+ * fseeko() on linux
192
+ *
193
+ * whence can either be SEEK_SET or SEEK_END
194
+ *
195
+ * Returns AWS_OP_SUCCESS, or AWS_OP_ERR (after an error has been raised).
196
+ */
197
+ AWS_COMMON_API
198
+ int aws_fseek(FILE *file, int64_t offset, int whence);
199
+
200
+ /*
201
+ * Wrapper for os-specific file length query. We can't use fseek(END, 0)
202
+ * because support for it is not technically required.
203
+ *
204
+ * Unix flavors call fstat, while Windows variants use GetFileSize on a
205
+ * HANDLE queried from the libc FILE pointer.
206
+ */
207
+ AWS_COMMON_API
208
+ int aws_file_get_length(FILE *file, int64_t *length);
209
+
210
+ AWS_EXTERN_C_END
211
+ AWS_POP_SANE_WARNING_LEVEL
212
+
213
+ #endif /* AWS_COMMON_FILE_H */
include/aws/common/hash_table.h ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_HASH_TABLE_H
2
+ #define AWS_COMMON_HASH_TABLE_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+
11
+ #include <stddef.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ enum {
16
+ AWS_COMMON_HASH_TABLE_ITER_CONTINUE = (1 << 0),
17
+ AWS_COMMON_HASH_TABLE_ITER_DELETE = (1 << 1),
18
+ AWS_COMMON_HASH_TABLE_ITER_ERROR = (1 << 2),
19
+ };
20
+
21
+ /**
22
+ * Hash table data structure. This module provides an automatically resizing
23
+ * hash table implementation for general purpose use. The hash table stores a
24
+ * mapping between void * keys and values; it is expected that in most cases,
25
+ * these will point to a structure elsewhere in the heap, instead of inlining a
26
+ * key or value into the hash table element itself.
27
+ *
28
+ * Currently, this hash table implements a variant of robin hood hashing, but
29
+ * we do not guarantee that this won't change in the future.
30
+ *
31
+ * Associated with each hash function are four callbacks:
32
+ *
33
+ * hash_fn - A hash function from the keys to a uint64_t. It is critical that
34
+ * the hash function for a key does not change while the key is in the hash
35
+ * table; violating this results in undefined behavior. Collisions are
36
+ * tolerated, though naturally with reduced performance.
37
+ *
38
+ * equals_fn - An equality comparison function. This function must be
39
+ * reflexive and consistent with hash_fn.
40
+ *
41
+ * destroy_key_fn, destroy_value_fn - Optional callbacks invoked when the
42
+ * table is cleared or cleaned up and at the caller's option when an element
43
+ * is removed from the table. Either or both may be set to NULL, which
44
+ * has the same effect as a no-op destroy function.
45
+ *
46
+ * This datastructure can be safely moved between threads, subject to the
47
+ * requirements of the underlying allocator. It is also safe to invoke
48
+ * non-mutating operations on the hash table from multiple threads. A suitable
49
+ * memory barrier must be used when transitioning from single-threaded mutating
50
+ * usage to multithreaded usage.
51
+ */
52
+ struct hash_table_state; /* Opaque pointer */
53
+ struct aws_hash_table {
54
+ struct hash_table_state *p_impl;
55
+ };
56
+
57
+ /**
58
+ * Represents an element in the hash table. Various operations on the hash
59
+ * table may provide pointers to elements stored within the hash table;
60
+ * generally, calling code may alter value, but must not alter key (or any
61
+ * information used to compute key's hash code).
62
+ *
63
+ * Pointers to elements within the hash are invalidated whenever an operation
64
+ * which may change the number of elements in the hash is invoked (i.e. put,
65
+ * delete, clear, and clean_up), regardless of whether the number of elements
66
+ * actually changes.
67
+ */
68
+ struct aws_hash_element {
69
+ const void *key;
70
+ void *value;
71
+ };
72
+
73
+ enum aws_hash_iter_status {
74
+ AWS_HASH_ITER_STATUS_DONE,
75
+ AWS_HASH_ITER_STATUS_DELETE_CALLED,
76
+ AWS_HASH_ITER_STATUS_READY_FOR_USE,
77
+ };
78
+
79
+ struct aws_hash_iter {
80
+ const struct aws_hash_table *map;
81
+ struct aws_hash_element element;
82
+ size_t slot;
83
+ size_t limit;
84
+ enum aws_hash_iter_status status;
85
+ /*
86
+ * Reserving extra fields for binary compatibility with future expansion of
87
+ * iterator in case hash table implementation changes.
88
+ */
89
+ int unused_0;
90
+ void *unused_1;
91
+ void *unused_2;
92
+ };
93
+
94
+ /**
95
+ * Prototype for a key hashing function pointer.
96
+ */
97
+ typedef uint64_t(aws_hash_fn)(const void *key);
98
+
99
+ /**
100
+ * Prototype for a hash table equality check function pointer.
101
+ *
102
+ * This type is usually used for a function that compares two hash table
103
+ * keys, but note that the same type is used for a function that compares
104
+ * two hash table values in aws_hash_table_eq.
105
+ *
106
+ * Equality functions used in a hash table must be be reflexive (a == a),
107
+ * symmetric (a == b => b == a), transitive (a == b, b == c => a == c)
108
+ * and consistent (result does not change with time).
109
+ */
110
+ typedef bool(aws_hash_callback_eq_fn)(const void *a, const void *b);
111
+
112
+ /**
113
+ * Prototype for a hash table key or value destructor function pointer.
114
+ *
115
+ * This function is used to destroy elements in the hash table when the
116
+ * table is cleared or cleaned up.
117
+ *
118
+ * Note that functions which remove individual elements from the hash
119
+ * table provide options of whether or not to invoke the destructors
120
+ * on the key and value of a removed element.
121
+ */
122
+ typedef void(aws_hash_callback_destroy_fn)(void *key_or_value);
123
+
124
+ AWS_EXTERN_C_BEGIN
125
+
126
+ /**
127
+ * Initializes a hash map with initial capacity for 'size' elements
128
+ * without resizing. Uses hash_fn to compute the hash of each element.
129
+ * equals_fn to compute equality of two keys. Whenever an element is
130
+ * removed without being returned, destroy_key_fn is run on the pointer
131
+ * to the key and destroy_value_fn is run on the pointer to the value.
132
+ * Either or both may be NULL if a callback is not desired in this case.
133
+ */
134
+ AWS_COMMON_API
135
+ int aws_hash_table_init(
136
+ struct aws_hash_table *map,
137
+ struct aws_allocator *alloc,
138
+ size_t size,
139
+ aws_hash_fn *hash_fn,
140
+ aws_hash_callback_eq_fn *equals_fn,
141
+ aws_hash_callback_destroy_fn *destroy_key_fn,
142
+ aws_hash_callback_destroy_fn *destroy_value_fn);
143
+
144
+ /**
145
+ * Deletes every element from map and frees all associated memory.
146
+ * destroy_fn will be called for each element. aws_hash_table_init
147
+ * must be called before reusing the hash table.
148
+ *
149
+ * This method is idempotent.
150
+ */
151
+ AWS_COMMON_API
152
+ void aws_hash_table_clean_up(struct aws_hash_table *map);
153
+
154
+ /**
155
+ * Safely swaps two hash tables. Note that we swap the entirety of the hash
156
+ * table, including which allocator is associated.
157
+ *
158
+ * Neither hash table is required to be initialized; if one or both is
159
+ * uninitialized, then the uninitialized state is also swapped.
160
+ */
161
+ AWS_COMMON_API
162
+ void aws_hash_table_swap(struct aws_hash_table *AWS_RESTRICT a, struct aws_hash_table *AWS_RESTRICT b);
163
+
164
+ /**
165
+ * Moves the hash table in 'from' to 'to'. After this move, 'from' will
166
+ * be identical to the state of the original 'to' hash table, and 'to'
167
+ * will be in the same state as if it had been passed to aws_hash_table_clean_up
168
+ * (that is, it will have no memory allocated, and it will be safe to
169
+ * either discard it or call aws_hash_table_clean_up again).
170
+ *
171
+ * Note that 'to' will not be cleaned up. You should make sure that 'to'
172
+ * is either uninitialized or cleaned up before moving a hashtable into
173
+ * it.
174
+ */
175
+ AWS_COMMON_API
176
+ void aws_hash_table_move(struct aws_hash_table *AWS_RESTRICT to, struct aws_hash_table *AWS_RESTRICT from);
177
+
178
+ /**
179
+ * Returns the current number of entries in the table.
180
+ */
181
+ AWS_COMMON_API
182
+ size_t aws_hash_table_get_entry_count(const struct aws_hash_table *map);
183
+
184
+ /**
185
+ * Returns an iterator to be used for iterating through a hash table.
186
+ * Iterator will already point to the first element of the table it finds,
187
+ * which can be accessed as iter.element.
188
+ *
189
+ * This function cannot fail, but if there are no elements in the table,
190
+ * the returned iterator will return true for aws_hash_iter_done(&iter).
191
+ */
192
+ AWS_COMMON_API
193
+ struct aws_hash_iter aws_hash_iter_begin(const struct aws_hash_table *map);
194
+
195
+ /**
196
+ * Returns true if iterator is done iterating through table, false otherwise.
197
+ * If this is true, the iterator will not include an element of the table.
198
+ */
199
+ AWS_COMMON_API
200
+ bool aws_hash_iter_done(const struct aws_hash_iter *iter);
201
+
202
+ /**
203
+ * Updates iterator so that it points to next element of hash table.
204
+ *
205
+ * This and the two previous functions are designed to be used together with
206
+ * the following idiom:
207
+ *
208
+ * for (struct aws_hash_iter iter = aws_hash_iter_begin(&map);
209
+ * !aws_hash_iter_done(&iter); aws_hash_iter_next(&iter)) {
210
+ * const key_type key = *(const key_type *)iter.element.key;
211
+ * value_type value = *(value_type *)iter.element.value;
212
+ * // etc.
213
+ * }
214
+ *
215
+ * Note that calling this on an iter which is "done" is idempotent:
216
+ * i.e. it will return another iter which is "done".
217
+ */
218
+ AWS_COMMON_API
219
+ void aws_hash_iter_next(struct aws_hash_iter *iter);
220
+
221
+ /**
222
+ * Deletes the element currently pointed-to by the hash iterator.
223
+ * After calling this method, the element member of the iterator
224
+ * should not be accessed until the next call to aws_hash_iter_next.
225
+ *
226
+ * @param destroy_contents If true, the destructors for the key and value
227
+ * will be called.
228
+ */
229
+ AWS_COMMON_API
230
+ void aws_hash_iter_delete(struct aws_hash_iter *iter, bool destroy_contents);
231
+
232
+ /**
233
+ * Attempts to locate an element at key. If the element is found, a
234
+ * pointer to the value is placed in *p_elem; if it is not found,
235
+ * *pElem is set to NULL. Either way, AWS_OP_SUCCESS is returned.
236
+ *
237
+ * This method does not change the state of the hash table. Therefore, it
238
+ * is safe to call _find from multiple threads on the same hash table,
239
+ * provided no mutating operations happen in parallel.
240
+ *
241
+ * Calling code may update the value in the hash table by modifying **pElem
242
+ * after a successful find. However, this pointer is not guaranteed to
243
+ * remain usable after a subsequent call to _put, _delete, _clear, or
244
+ * _clean_up.
245
+ */
246
+
247
+ AWS_COMMON_API
248
+ int aws_hash_table_find(const struct aws_hash_table *map, const void *key, struct aws_hash_element **p_elem);
249
+
250
+ /**
251
+ * Attempts to locate an element at key. If no such element was found,
252
+ * creates a new element, with value initialized to NULL. In either case, a
253
+ * pointer to the element is placed in *p_elem.
254
+ *
255
+ * If was_created is non-NULL, *was_created is set to 0 if an existing
256
+ * element was found, or 1 is a new element was created.
257
+ *
258
+ * Returns AWS_OP_SUCCESS if an item was found or created.
259
+ * Raises AWS_ERROR_OOM if hash table expansion was required and memory
260
+ * allocation failed.
261
+ */
262
+ AWS_COMMON_API
263
+ int aws_hash_table_create(
264
+ struct aws_hash_table *map,
265
+ const void *key,
266
+ struct aws_hash_element **p_elem,
267
+ int *was_created);
268
+
269
+ /**
270
+ * Inserts a new element at key, with the given value. If another element
271
+ * exists at that key, the old element will be overwritten; both old key and
272
+ * value objects will be destroyed.
273
+ *
274
+ * If was_created is non-NULL, *was_created is set to 0 if an existing
275
+ * element was found, or 1 is a new element was created.
276
+ *
277
+ * Returns AWS_OP_SUCCESS if an item was found or created.
278
+ * Raises AWS_ERROR_OOM if hash table expansion was required and memory
279
+ * allocation failed.
280
+ */
281
+ AWS_COMMON_API
282
+ int aws_hash_table_put(struct aws_hash_table *map, const void *key, void *value, int *was_created);
283
+
284
+ /**
285
+ * Removes element at key. Always returns AWS_OP_SUCCESS.
286
+ *
287
+ * If pValue is non-NULL, the existing value (if any) is moved into
288
+ * (*value) before removing from the table, and destroy_fn is _not_
289
+ * invoked. If pValue is NULL, then (if the element existed) destroy_fn
290
+ * will be invoked on the element being removed.
291
+ *
292
+ * If was_present is non-NULL, it is set to 0 if the element was
293
+ * not present, or 1 if it was present (and is now removed).
294
+ */
295
+ AWS_COMMON_API
296
+ int aws_hash_table_remove(
297
+ struct aws_hash_table *map,
298
+ const void *key,
299
+ struct aws_hash_element *p_value,
300
+ int *was_present);
301
+
302
+ /**
303
+ * Removes element already known (typically by find()).
304
+ *
305
+ * p_value should point to a valid element returned by create() or find().
306
+ *
307
+ * NOTE: DO NOT call this method from inside of a aws_hash_table_foreach callback, return
308
+ * AWS_COMMON_HASH_TABLE_ITER_DELETE instead.
309
+ */
310
+ AWS_COMMON_API
311
+ int aws_hash_table_remove_element(struct aws_hash_table *map, struct aws_hash_element *p_value);
312
+
313
+ /**
314
+ * Iterates through every element in the map and invokes the callback on
315
+ * that item. Iteration is performed in an arbitrary, implementation-defined
316
+ * order, and is not guaranteed to be consistent across invocations.
317
+ *
318
+ * The callback may change the value associated with the key by overwriting
319
+ * the value pointed-to by value. In this case, the on_element_removed
320
+ * callback will not be invoked, unless the callback invokes
321
+ * AWS_COMMON_HASH_TABLE_ITER_DELETE (in which case the on_element_removed
322
+ * is given the updated value).
323
+ *
324
+ * The callback must return a bitmask of zero or more of the following values
325
+ * ORed together:
326
+ *
327
+ * # AWS_COMMON_HASH_TABLE_ITER_CONTINUE - Continues iteration to the next
328
+ * element (if not set, iteration stops)
329
+ * # AWS_COMMON_HASH_TABLE_ITER_DELETE - Deletes the current value and
330
+ * continues iteration. destroy_fn will NOT be invoked.
331
+ * # AWS_COMMON_HASH_TABLE_ITER_ERROR - Stop iteration with error.
332
+ * No action will be taken for the current value and the value before this.
333
+ * No rolling back. The deleted value before will NOT be back.
334
+ * aws_hash_table_foreach returns AWS_OP_ERR after stropping the iteration.
335
+ *
336
+ * Invoking any method which may change the contents of the hashtable
337
+ * during iteration results in undefined behavior. However, you may safely
338
+ * invoke non-mutating operations during an iteration.
339
+ *
340
+ * This operation is mutating only if AWS_COMMON_HASH_TABLE_ITER_DELETE
341
+ * is returned at some point during iteration. Otherwise, it is non-mutating
342
+ * and is safe to invoke in parallel with other non-mutating operations.
343
+ */
344
+
345
+ AWS_COMMON_API
346
+ int aws_hash_table_foreach(
347
+ struct aws_hash_table *map,
348
+ int (*callback)(void *context, struct aws_hash_element *p_element),
349
+ void *context);
350
+
351
+ /**
352
+ * Compares two hash tables for equality. Both hash tables must have equivalent
353
+ * key comparators; values will be compared using the comparator passed into this
354
+ * function. The key hash function does not need to be equivalent between the
355
+ * two hash tables.
356
+ */
357
+ AWS_COMMON_API
358
+ bool aws_hash_table_eq(
359
+ const struct aws_hash_table *a,
360
+ const struct aws_hash_table *b,
361
+ aws_hash_callback_eq_fn *value_eq);
362
+
363
+ /**
364
+ * Removes every element from the hash map. destroy_fn will be called for
365
+ * each element.
366
+ */
367
+ AWS_COMMON_API
368
+ void aws_hash_table_clear(struct aws_hash_table *map);
369
+
370
+ /**
371
+ * Convenience hash function for NULL-terminated C-strings
372
+ */
373
+ AWS_COMMON_API
374
+ uint64_t aws_hash_c_string(const void *item);
375
+
376
+ /**
377
+ * Convenience hash function for struct aws_strings.
378
+ * Hash is same as used on the string bytes by aws_hash_c_string.
379
+ */
380
+ AWS_COMMON_API
381
+ uint64_t aws_hash_string(const void *item);
382
+
383
+ /**
384
+ * Convenience hash function for struct aws_byte_cursor.
385
+ * Hash is same as used on the string bytes by aws_hash_c_string.
386
+ */
387
+ AWS_COMMON_API
388
+ uint64_t aws_hash_byte_cursor_ptr(const void *item);
389
+
390
+ /**
391
+ * Convenience hash function which hashes the pointer value directly,
392
+ * without dereferencing. This can be used in cases where pointer identity
393
+ * is desired, or where a uintptr_t is encoded into a const void *.
394
+ */
395
+ AWS_COMMON_API
396
+ uint64_t aws_hash_ptr(const void *item);
397
+
398
+ AWS_COMMON_API
399
+ uint64_t aws_hash_combine(uint64_t item1, uint64_t item2);
400
+
401
+ /**
402
+ * Convenience eq callback for NULL-terminated C-strings
403
+ */
404
+ AWS_COMMON_API
405
+ bool aws_hash_callback_c_str_eq(const void *a, const void *b);
406
+
407
+ /**
408
+ * Convenience eq callback for AWS strings
409
+ */
410
+ AWS_COMMON_API
411
+ bool aws_hash_callback_string_eq(const void *a, const void *b);
412
+
413
+ /**
414
+ * Convenience destroy callback for AWS strings
415
+ */
416
+ AWS_COMMON_API
417
+ void aws_hash_callback_string_destroy(void *a);
418
+
419
+ /**
420
+ * Equality function which compares pointer equality.
421
+ */
422
+ AWS_COMMON_API
423
+ bool aws_ptr_eq(const void *a, const void *b);
424
+
425
+ /**
426
+ * Best-effort check of hash_table_state data-structure invariants
427
+ */
428
+ AWS_COMMON_API
429
+ bool aws_hash_table_is_valid(const struct aws_hash_table *map);
430
+
431
+ /**
432
+ * Given a pointer to a hash_iter, checks that it is well-formed, with all data-structure invariants.
433
+ */
434
+ AWS_COMMON_API
435
+ bool aws_hash_iter_is_valid(const struct aws_hash_iter *iter);
436
+
437
+ /**
438
+ * Helper function to hash keys that are uint64_t values.
439
+ *
440
+ * The function is not a strong hash function in any sense; it merely reflects
441
+ * the uint64 value back. Do not use this function as a hash if you need
442
+ * the properties of a strong hash function.
443
+ */
444
+ AWS_COMMON_API uint64_t aws_hash_uint64_t_by_identity(const void *item);
445
+
446
+ /**
447
+ * Helper function to compare hash keys that are uint64_t values.
448
+ */
449
+ AWS_COMMON_API bool aws_hash_compare_uint64_t_eq(const void *a, const void *b);
450
+
451
+ AWS_EXTERN_C_END
452
+ AWS_POP_SANE_WARNING_LEVEL
453
+
454
+ #endif /* AWS_COMMON_HASH_TABLE_H */
include/aws/common/host_utils.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_HOST_UTILS_H
2
+ #define AWS_COMMON_HOST_UTILS_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/common.h>
8
+
9
+ struct aws_byte_cursor;
10
+
11
+ AWS_PUSH_SANE_WARNING_LEVEL
12
+ AWS_EXTERN_C_BEGIN
13
+
14
+ /*
15
+ * Determine whether host cursor is IPv4 string.
16
+ */
17
+ AWS_COMMON_API bool aws_host_utils_is_ipv4(struct aws_byte_cursor host);
18
+
19
+ /*
20
+ * Determine whether host cursor is IPv6 string.
21
+ * Supports checking for uri encoded strings and scoped literals.
22
+ */
23
+ AWS_COMMON_API bool aws_host_utils_is_ipv6(struct aws_byte_cursor host, bool is_uri_encoded);
24
+
25
+ AWS_EXTERN_C_END
26
+ AWS_POP_SANE_WARNING_LEVEL
27
+
28
+ #endif /* AWS_COMMON_HOST_UTILS_H */
include/aws/common/json.h ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_JSON_H
2
+ #define AWS_COMMON_JSON_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/byte_buf.h>
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+
14
+ struct aws_json_value;
15
+
16
+ AWS_EXTERN_C_BEGIN
17
+
18
+ // ====================
19
+ // Create and pass type
20
+
21
+ /**
22
+ * Creates a new string aws_json_value with the given string and returns a pointer to it.
23
+ *
24
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
25
+ * on the object/array containing the aws_json_value.
26
+ * Note: might be slower than c_str version due to internal copy
27
+ * @param string A byte cursor you want to store in the aws_json_value
28
+ * @param allocator The allocator to use when creating the value
29
+ * @return A new string aws_json_value
30
+ */
31
+ AWS_COMMON_API
32
+ struct aws_json_value *aws_json_value_new_string(struct aws_allocator *allocator, struct aws_byte_cursor string);
33
+
34
+ /**
35
+ * Creates a new string aws_json_value with the given string and returns a pointer to it.
36
+ *
37
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
38
+ * on the object/array containing the aws_json_value.
39
+ * @param string c string pointer you want to store in the aws_json_value
40
+ * @param allocator The allocator to use when creating the value
41
+ * @return A new string aws_json_value
42
+ */
43
+ AWS_COMMON_API
44
+ struct aws_json_value *aws_json_value_new_string_from_c_str(struct aws_allocator *allocator, const char *string);
45
+
46
+ /**
47
+ * Creates a new number aws_json_value with the given number and returns a pointer to it.
48
+ *
49
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
50
+ * on the object/array containing the aws_json_value.
51
+ * @param number The number you want to store in the aws_json_value
52
+ * @param allocator The allocator to use when creating the value
53
+ * @return A new number aws_json_value
54
+ */
55
+ AWS_COMMON_API
56
+ struct aws_json_value *aws_json_value_new_number(struct aws_allocator *allocator, double number);
57
+
58
+ /**
59
+ * Creates a new array aws_json_value and returns a pointer to it.
60
+ *
61
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
62
+ * on the object/array containing the aws_json_value.
63
+ * Deleting this array will also destroy any aws_json_values it contains.
64
+ * @param allocator The allocator to use when creating the value
65
+ * @return A new array aws_json_value
66
+ */
67
+ AWS_COMMON_API
68
+ struct aws_json_value *aws_json_value_new_array(struct aws_allocator *allocator);
69
+
70
+ /**
71
+ * Creates a new boolean aws_json_value with the given boolean and returns a pointer to it.
72
+ *
73
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
74
+ * on the object/array containing the aws_json_value.
75
+ * @param boolean The boolean you want to store in the aws_json_value
76
+ * @param allocator The allocator to use when creating the value
77
+ * @return A new boolean aws_json_value
78
+ */
79
+ AWS_COMMON_API
80
+ struct aws_json_value *aws_json_value_new_boolean(struct aws_allocator *allocator, bool boolean);
81
+
82
+ /**
83
+ * Creates a new null aws_json_value and returns a pointer to it.
84
+ *
85
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
86
+ * on the object/array containing the aws_json_value.
87
+ * @param allocator The allocator to use when creating the value
88
+ * @return A new null aws_json_value
89
+ */
90
+ AWS_COMMON_API
91
+ struct aws_json_value *aws_json_value_new_null(struct aws_allocator *allocator);
92
+
93
+ /**
94
+ * Creates a new object aws_json_value and returns a pointer to it.
95
+ *
96
+ * Note: You will need to free the memory for the aws_json_value using aws_json_destroy on the aws_json_value or
97
+ * on the object/array containing the aws_json_value.
98
+ * Deleting this object will also destroy any aws_json_values it contains.
99
+ * @param allocator The allocator to use when creating the value
100
+ * @return A new object aws_json_value
101
+ */
102
+ AWS_COMMON_API
103
+ struct aws_json_value *aws_json_value_new_object(struct aws_allocator *allocator);
104
+ // ====================
105
+
106
+ // ====================
107
+ // Value getters
108
+
109
+ /**
110
+ * Gets the string of a string aws_json_value.
111
+ * @param value The string aws_json_value.
112
+ * @param output The string
113
+ * @return AWS_OP_SUCCESS if the value is a string, otherwise AWS_OP_ERR.
114
+ */
115
+ AWS_COMMON_API
116
+ int aws_json_value_get_string(const struct aws_json_value *value, struct aws_byte_cursor *output);
117
+
118
+ /**
119
+ * Gets the number of a number aws_json_value.
120
+ * @param value The number aws_json_value.
121
+ * @param output The number
122
+ * @return AWS_OP_SUCCESS if the value is a number, otherwise AWS_OP_ERR.
123
+ */
124
+ AWS_COMMON_API
125
+ int aws_json_value_get_number(const struct aws_json_value *value, double *output);
126
+
127
+ /**
128
+ * Gets the boolean of a boolean aws_json_value.
129
+ * @param value The boolean aws_json_value.
130
+ * @param output The boolean
131
+ * @return AWS_OP_SUCCESS if the value is a boolean, otherwise AWS_OP_ERR.
132
+ */
133
+ AWS_COMMON_API
134
+ int aws_json_value_get_boolean(const struct aws_json_value *value, bool *output);
135
+ // ====================
136
+
137
+ // ====================
138
+ // Object API
139
+
140
+ /**
141
+ * Adds a aws_json_value to a object aws_json_value.
142
+ *
143
+ * Note that the aws_json_value will be destroyed when the aws_json_value object is destroyed
144
+ * by calling "aws_json_destroy()"
145
+ * Note: might be slower than c_str version due to internal copy
146
+ * @param object The object aws_json_value you want to add a value to.
147
+ * @param key The key to add the aws_json_value at.
148
+ * @param value The aws_json_value you want to add.
149
+ * @return AWS_OP_SUCCESS if adding was successful.
150
+ * Will return AWS_OP_ERROR if the object passed is invalid or if the passed key
151
+ * is already in use in the object.
152
+ */
153
+ AWS_COMMON_API
154
+ int aws_json_value_add_to_object(
155
+ struct aws_json_value *object,
156
+ struct aws_byte_cursor key,
157
+ struct aws_json_value *value);
158
+
159
+ /**
160
+ * Adds a aws_json_value to a object aws_json_value.
161
+ *
162
+ * Note that the aws_json_value will be destroyed when the aws_json_value object is destroyed
163
+ * by calling "aws_json_destroy()"
164
+ * @param object The object aws_json_value you want to add a value to.
165
+ * @param key The key to add the aws_json_value at.
166
+ * @param value The aws_json_value you want to add.
167
+ * @return AWS_OP_SUCCESS if adding was successful.
168
+ * Will return AWS_OP_ERROR if the object passed is invalid or if the passed key
169
+ * is already in use in the object.
170
+ */
171
+ AWS_COMMON_API
172
+ int aws_json_value_add_to_object_c_str(struct aws_json_value *object, const char *key, struct aws_json_value *value);
173
+
174
+ /**
175
+ * Returns the aws_json_value at the given key.
176
+ * Note: might be slower than c_str version due to internal copy
177
+ * @param object The object aws_json_value you want to get the value from.
178
+ * @param key The key that the aws_json_value is at. Is case sensitive.
179
+ * @return The aws_json_value at the given key, otherwise NULL.
180
+ */
181
+ AWS_COMMON_API
182
+ struct aws_json_value *aws_json_value_get_from_object(const struct aws_json_value *object, struct aws_byte_cursor key);
183
+
184
+ /**
185
+ * Returns the aws_json_value at the given key.
186
+ * Note: same as aws_json_value_get_from_object but with key as const char *.
187
+ * Prefer this method is you have a key thats already a valid char * as it is likely to be faster.
188
+ * @param object The object aws_json_value you want to get the value from.
189
+ * @param key The key that the aws_json_value is at. Is case sensitive.
190
+ * @return The aws_json_value at the given key, otherwise NULL.
191
+ */
192
+ AWS_COMMON_API
193
+ struct aws_json_value *aws_json_value_get_from_object_c_str(const struct aws_json_value *object, const char *key);
194
+
195
+ /**
196
+ * Checks if there is a aws_json_value at the given key.
197
+ * Note: might be slower than c_str version due to internal copy
198
+ * @param object The value aws_json_value you want to check a key in.
199
+ * @param key The key that you want to check. Is case sensitive.
200
+ * @return True if a aws_json_value is found.
201
+ */
202
+ AWS_COMMON_API
203
+ bool aws_json_value_has_key(const struct aws_json_value *object, struct aws_byte_cursor key);
204
+
205
+ /**
206
+ * Checks if there is a aws_json_value at the given key.
207
+ * Note: same as aws_json_value_has_key but with key as const char *.
208
+ * Prefer this method is you have a key thats already a valid char * as it is likely to be faster.
209
+ * @param object The value aws_json_value you want to check a key in.
210
+ * @param key The key that you want to check. Is case sensitive.
211
+ * @return True if a aws_json_value is found.
212
+ */
213
+ AWS_COMMON_API
214
+ bool aws_json_value_has_key_c_str(const struct aws_json_value *object, const char *key);
215
+
216
+ /**
217
+ * Removes the aws_json_value at the given key.
218
+ * Note: might be slower than c_str version due to internal copy
219
+ * @param object The object aws_json_value you want to remove a aws_json_value in.
220
+ * @param key The key that the aws_json_value is at. Is case sensitive.
221
+ * @return AWS_OP_SUCCESS if the aws_json_value was removed.
222
+ * Will return AWS_OP_ERR if the object passed is invalid or if the value
223
+ * at the key cannot be found.
224
+ */
225
+ AWS_COMMON_API
226
+ int aws_json_value_remove_from_object(struct aws_json_value *object, struct aws_byte_cursor key);
227
+
228
+ /**
229
+ * Removes the aws_json_value at the given key.
230
+ * Note: same as aws_json_value_remove_from_object but with key as const char *.
231
+ * Prefer this method is you have a key thats already a valid char * as it is likely to be faster.
232
+ * @param object The object aws_json_value you want to remove a aws_json_value in.
233
+ * @param key The key that the aws_json_value is at. Is case sensitive.
234
+ * @return AWS_OP_SUCCESS if the aws_json_value was removed.
235
+ * Will return AWS_OP_ERR if the object passed is invalid or if the value
236
+ * at the key cannot be found.
237
+ */
238
+ AWS_COMMON_API
239
+ int aws_json_value_remove_from_object_c_str(struct aws_json_value *object, const char *key);
240
+
241
+ /**
242
+ * @brief callback for iterating members of an object
243
+ * Iteration can be controlled as follows:
244
+ * - return AWS_OP_SUCCESS and out_should_continue is set to true (default value) -
245
+ * continue iteration without error
246
+ * - return AWS_OP_SUCCESS and out_continue is set to false -
247
+ * stop iteration without error
248
+ * - return AWS_OP_ERR - stop iteration with error
249
+ */
250
+ typedef int(aws_json_on_member_encountered_const_fn)(
251
+ const struct aws_byte_cursor *key,
252
+ const struct aws_json_value *value,
253
+ bool *out_should_continue,
254
+ void *user_data);
255
+
256
+ /**
257
+ * @brief iterates through members of the object.
258
+ * iteration is sequential in order fields were initially parsed.
259
+ * @param object object to iterate over.
260
+ * @param on_member callback for when member is encountered.
261
+ * @param user_data user data to pass back in callback.
262
+ * @return AWS_OP_SUCCESS when iteration finishes completely or exits early,
263
+ * AWS_OP_ERR if value is not an object.
264
+ */
265
+ AWS_COMMON_API
266
+ int aws_json_const_iterate_object(
267
+ const struct aws_json_value *object,
268
+ aws_json_on_member_encountered_const_fn *on_member,
269
+ void *user_data);
270
+
271
+ // ====================
272
+
273
+ // ====================
274
+ // Array API
275
+
276
+ /**
277
+ * Adds a aws_json_value to the given array aws_json_value.
278
+ *
279
+ * Note that the aws_json_value will be destroyed when the aws_json_value array is destroyed
280
+ * by calling "aws_json_destroy()"
281
+ * @param array The array aws_json_value you want to add an aws_json_value to.
282
+ * @param value The aws_json_value you want to add.
283
+ * @return AWS_OP_SUCCESS if adding the aws_json_value was successful.
284
+ * Will return AWS_OP_ERR if the array passed is invalid.
285
+ */
286
+ AWS_COMMON_API
287
+ int aws_json_value_add_array_element(struct aws_json_value *array, const struct aws_json_value *value);
288
+
289
+ /**
290
+ * Returns the aws_json_value at the given index in the array aws_json_value.
291
+ * @param array The array aws_json_value.
292
+ * @param index The index of the aws_json_value you want to access.
293
+ * @return A pointer to the aws_json_value at the given index in the array, otherwise NULL.
294
+ */
295
+ AWS_COMMON_API
296
+ struct aws_json_value *aws_json_get_array_element(const struct aws_json_value *array, size_t index);
297
+
298
+ /**
299
+ * Returns the number of items in the array aws_json_value.
300
+ * @param array The array aws_json_value.
301
+ * @return The number of items in the array_json_value.
302
+ */
303
+ AWS_COMMON_API
304
+ size_t aws_json_get_array_size(const struct aws_json_value *array);
305
+
306
+ /**
307
+ * Removes the aws_json_value at the given index in the array aws_json_value.
308
+ * @param array The array aws_json_value.
309
+ * @param index The index containing the aws_json_value you want to remove.
310
+ * @return AWS_OP_SUCCESS if the aws_json_value at the index was removed.
311
+ * Will return AWS_OP_ERR if the array passed is invalid or if the index
312
+ * passed is out of range.
313
+ */
314
+ AWS_COMMON_API
315
+ int aws_json_value_remove_array_element(struct aws_json_value *array, size_t index);
316
+
317
+ /**
318
+ * @brief callback for iterating values of an array.
319
+ * Iteration can be controlled as follows:
320
+ * - return AWS_OP_SUCCESS and out_should_continue is set to true (default value) -
321
+ * continue iteration without error
322
+ * - return AWS_OP_SUCCESS and out_continue is set to false -
323
+ * stop iteration without error
324
+ * - return AWS_OP_ERR - stop iteration with error
325
+ */
326
+ typedef int(aws_json_on_value_encountered_const_fn)(
327
+ size_t index,
328
+ const struct aws_json_value *value,
329
+ bool *out_should_continue,
330
+ void *user_data);
331
+
332
+ /**
333
+ * @brief iterates through values of an array.
334
+ * iteration is sequential starting with 0th element.
335
+ * @param array array to iterate over.
336
+ * @param on_value callback for when value is encountered.
337
+ * @param user_data user data to pass back in callback.
338
+ * @return AWS_OP_SUCCESS when iteration finishes completely or exits early,
339
+ * AWS_OP_ERR if value is not an array.
340
+ */
341
+ AWS_COMMON_API
342
+ int aws_json_const_iterate_array(
343
+ const struct aws_json_value *array,
344
+ aws_json_on_value_encountered_const_fn *on_value,
345
+ void *user_data);
346
+
347
+ // ====================
348
+
349
+ // ====================
350
+ // Checks
351
+
352
+ /**
353
+ * Checks whether two json values are equivalent.
354
+ * @param a first value to compare.
355
+ * @param b second value to compare.
356
+ * @param is_case_sensitive case sensitive compare or not.
357
+ * @return True is values are equal, false otherwise
358
+ */
359
+ AWS_COMMON_API
360
+ bool aws_json_value_compare(const struct aws_json_value *a, const struct aws_json_value *b, bool is_case_sensitive);
361
+
362
+ /**
363
+ * Duplicates json value.
364
+ * @param value first value to compare.
365
+ * @return duplicated value. NULL and last error set if value cannot be duplicated.
366
+ */
367
+ AWS_COMMON_API
368
+ struct aws_json_value *aws_json_value_duplicate(const struct aws_json_value *value);
369
+
370
+ /**
371
+ * Checks if the aws_json_value is a string.
372
+ * @param value The aws_json_value to check.
373
+ * @return True if the aws_json_value is a string aws_json_value, otherwise false.
374
+ */
375
+ AWS_COMMON_API
376
+ bool aws_json_value_is_string(const struct aws_json_value *value);
377
+
378
+ /**
379
+ * Checks if the aws_json_value is a number.
380
+ * @param value The aws_json_value to check.
381
+ * @return True if the aws_json_value is a number aws_json_value, otherwise false.
382
+ */
383
+ AWS_COMMON_API
384
+ bool aws_json_value_is_number(const struct aws_json_value *value);
385
+
386
+ /**
387
+ * Checks if the aws_json_value is a array.
388
+ * @param value The aws_json_value to check.
389
+ * @return True if the aws_json_value is a array aws_json_value, otherwise false.
390
+ */
391
+ AWS_COMMON_API
392
+ bool aws_json_value_is_array(const struct aws_json_value *value);
393
+
394
+ /**
395
+ * Checks if the aws_json_value is a boolean.
396
+ * @param value The aws_json_value to check.
397
+ * @return True if the aws_json_value is a boolean aws_json_value, otherwise false.
398
+ */
399
+ AWS_COMMON_API
400
+ bool aws_json_value_is_boolean(const struct aws_json_value *value);
401
+
402
+ /**
403
+ * Checks if the aws_json_value is a null aws_json_value.
404
+ * @param value The aws_json_value to check.
405
+ * @return True if the aws_json_value is a null aws_json_value, otherwise false.
406
+ */
407
+ AWS_COMMON_API
408
+ bool aws_json_value_is_null(const struct aws_json_value *value);
409
+
410
+ /**
411
+ * Checks if the aws_json_value is a object aws_json_value.
412
+ * @param value The aws_json_value to check.
413
+ * @return True if the aws_json_value is a object aws_json_value, otherwise false.
414
+ */
415
+ AWS_COMMON_API
416
+ bool aws_json_value_is_object(const struct aws_json_value *value);
417
+ // ====================
418
+
419
+ // ====================
420
+ // Memory Management
421
+
422
+ /**
423
+ * Removes the aws_json_value from memory. If the aws_json_value is a object or array, it will also destroy
424
+ * attached aws_json_values as well.
425
+ *
426
+ * For example, if you called "aws_json_array_add(b, a)" to add an object "a" to an array "b", if you call
427
+ * "aws_json_destroy(b)" then it will also free "a" automatically. All children/attached aws_json_values are freed
428
+ * when the parent/root aws_json_value is destroyed.
429
+ * @param value The aws_json_value to destroy.
430
+ */
431
+ AWS_COMMON_API
432
+ void aws_json_value_destroy(struct aws_json_value *value);
433
+ // ====================
434
+
435
+ // ====================
436
+ // Utility
437
+
438
+ /**
439
+ * Appends a unformatted JSON string representation of the aws_json_value into the passed byte buffer.
440
+ * The byte buffer is expected to be already initialized so the function can append the JSON into it.
441
+ *
442
+ * Note: The byte buffer will automatically have its size extended if the JSON string is over the byte
443
+ * buffer capacity AND the byte buffer has an allocator associated with it. If the byte buffer does not
444
+ * have an allocator associated and the JSON string is over capacity, AWS_OP_ERR will be returned.
445
+ *
446
+ * Note: When you are finished with the aws_byte_buf, you must call "aws_byte_buf_clean_up_secure" to free
447
+ * the memory used, as it will NOT be called automatically.
448
+ * @param value The aws_json_value to format.
449
+ * @param output The destination for the JSON string
450
+ * @return AWS_OP_SUCCESS if the JSON string was allocated to output without any errors
451
+ * Will return AWS_OP_ERR if the value passed is not an aws_json_value or if there
452
+ * was an error appending the JSON into the byte buffer.
453
+ */
454
+ AWS_COMMON_API
455
+ int aws_byte_buf_append_json_string(const struct aws_json_value *value, struct aws_byte_buf *output);
456
+
457
+ /**
458
+ * Appends a formatted JSON string representation of the aws_json_value into the passed byte buffer.
459
+ * The byte buffer is expected to already be initialized so the function can append the JSON into it.
460
+ *
461
+ * Note: The byte buffer will automatically have its size extended if the JSON string is over the byte
462
+ * buffer capacity AND the byte buffer has an allocator associated with it. If the byte buffer does not
463
+ * have an allocator associated and the JSON string is over capacity, AWS_OP_ERR will be returned.
464
+ *
465
+ * Note: When you are finished with the aws_byte_buf, you must call "aws_byte_buf_clean_up_secure" to free
466
+ * the memory used, as it will NOT be called automatically.
467
+ * @param value The aws_json_value to format.
468
+ * @param output The destination for the JSON string
469
+ * @return AWS_OP_SUCCESS if the JSON string was allocated to output without any errors
470
+ * Will return AWS_OP_ERR if the value passed is not an aws_json_value or if there
471
+ * aws an error appending the JSON into the byte buffer.
472
+ */
473
+ AWS_COMMON_API
474
+ int aws_byte_buf_append_json_string_formatted(const struct aws_json_value *value, struct aws_byte_buf *output);
475
+
476
+ /**
477
+ * Parses the JSON string and returns a aws_json_value containing the root of the JSON.
478
+ * @param allocator The allocator used to create the value
479
+ * @param string The string containing the JSON.
480
+ * @return The root aws_json_value of the JSON.
481
+ */
482
+ AWS_COMMON_API
483
+ struct aws_json_value *aws_json_value_new_from_string(struct aws_allocator *allocator, struct aws_byte_cursor string);
484
+ // ====================
485
+
486
+ AWS_EXTERN_C_END
487
+ AWS_POP_SANE_WARNING_LEVEL
488
+
489
+ #endif // AWS_COMMON_JSON_H
include/aws/common/lifo_cache.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_LIFO_CACHE_H
2
+ #define AWS_COMMON_LIFO_CACHE_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+
8
+ #include <aws/common/cache.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+ AWS_EXTERN_C_BEGIN
12
+
13
+ /**
14
+ * Initializes the last-in-first-out cache. Sets up the underlying linked hash table.
15
+ * Once `max_items` elements have been added, the latest(last-in) item will
16
+ * be removed. For the other parameters, see aws/common/hash_table.h. Hash table
17
+ * semantics of these arguments are preserved.
18
+ */
19
+ AWS_COMMON_API
20
+ struct aws_cache *aws_cache_new_lifo(
21
+ struct aws_allocator *allocator,
22
+ aws_hash_fn *hash_fn,
23
+ aws_hash_callback_eq_fn *equals_fn,
24
+ aws_hash_callback_destroy_fn *destroy_key_fn,
25
+ aws_hash_callback_destroy_fn *destroy_value_fn,
26
+ size_t max_items);
27
+
28
+ AWS_EXTERN_C_END
29
+ AWS_POP_SANE_WARNING_LEVEL
30
+
31
+ #endif /* AWS_COMMON_LIFO_CACHE_H */
include/aws/common/linked_hash_table.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_LINKED_HASH_TABLE_H
2
+ #define AWS_COMMON_LINKED_HASH_TABLE_H
3
+ /**
4
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ * SPDX-License-Identifier: Apache-2.0.
6
+ */
7
+ #include <aws/common/hash_table.h>
8
+ #include <aws/common/linked_list.h>
9
+
10
+ AWS_PUSH_SANE_WARNING_LEVEL
11
+
12
+ /**
13
+ * Simple linked hash table. Preserves insertion order, and can be iterated in insertion order.
14
+ *
15
+ * You can also change the order safely without altering the shape of the underlying hash table.
16
+ */
17
+ struct aws_linked_hash_table {
18
+ struct aws_allocator *allocator;
19
+ struct aws_linked_list list;
20
+ struct aws_hash_table table;
21
+ aws_hash_callback_destroy_fn *user_on_value_destroy;
22
+ aws_hash_callback_destroy_fn *user_on_key_destroy;
23
+ };
24
+
25
+ /**
26
+ * Linked-List node stored in the table. This is the node type that will be returned in
27
+ * aws_linked_hash_table_get_iteration_list().
28
+ */
29
+ struct aws_linked_hash_table_node {
30
+ struct aws_linked_list_node node;
31
+ struct aws_linked_hash_table *table;
32
+ const void *key;
33
+ void *value;
34
+ };
35
+
36
+ AWS_EXTERN_C_BEGIN
37
+
38
+ /**
39
+ * Initializes the table. Sets up the underlying hash table and linked list.
40
+ * For the other parameters, see aws/common/hash_table.h. Hash table
41
+ * semantics of these arguments are preserved.
42
+ */
43
+ AWS_COMMON_API
44
+ int aws_linked_hash_table_init(
45
+ struct aws_linked_hash_table *table,
46
+ struct aws_allocator *allocator,
47
+ aws_hash_fn *hash_fn,
48
+ aws_hash_callback_eq_fn *equals_fn,
49
+ aws_hash_callback_destroy_fn *destroy_key_fn,
50
+ aws_hash_callback_destroy_fn *destroy_value_fn,
51
+ size_t initial_item_count);
52
+
53
+ /**
54
+ * Cleans up the table. Elements in the table will be evicted and cleanup
55
+ * callbacks will be invoked.
56
+ */
57
+ AWS_COMMON_API
58
+ void aws_linked_hash_table_clean_up(struct aws_linked_hash_table *table);
59
+
60
+ /**
61
+ * Finds element in the table by key. If found, AWS_OP_SUCCESS will be
62
+ * returned. If not found, AWS_OP_SUCCESS will be returned and *p_value will be
63
+ * NULL.
64
+ *
65
+ * If any errors occur AWS_OP_ERR will be returned.
66
+ */
67
+ AWS_COMMON_API
68
+ int aws_linked_hash_table_find(struct aws_linked_hash_table *table, const void *key, void **p_value);
69
+
70
+ /**
71
+ * Finds element in the table by key. If found, AWS_OP_SUCCESS will be returned and the item will be moved to the back
72
+ * of the list.
73
+ * If not found, AWS_OP_SUCCESS will be returned and *p_value will be NULL.
74
+ *
75
+ * Note: this will change the order of elements
76
+ */
77
+ AWS_COMMON_API
78
+ int aws_linked_hash_table_find_and_move_to_back(struct aws_linked_hash_table *table, const void *key, void **p_value);
79
+
80
+ /**
81
+ * Puts `p_value` at `key`. If an element is already stored at `key` it will be replaced.
82
+ */
83
+ AWS_COMMON_API
84
+ int aws_linked_hash_table_put(struct aws_linked_hash_table *table, const void *key, void *p_value);
85
+
86
+ /**
87
+ * Removes item at `key` from the table.
88
+ */
89
+ AWS_COMMON_API
90
+ int aws_linked_hash_table_remove(struct aws_linked_hash_table *table, const void *key);
91
+
92
+ /**
93
+ * Clears all items from the table.
94
+ */
95
+ AWS_COMMON_API
96
+ void aws_linked_hash_table_clear(struct aws_linked_hash_table *table);
97
+
98
+ /**
99
+ * returns number of elements in the table.
100
+ */
101
+ AWS_COMMON_API
102
+ size_t aws_linked_hash_table_get_element_count(const struct aws_linked_hash_table *table);
103
+
104
+ /**
105
+ * Move the aws_linked_hash_table_node to the end of the list.
106
+ *
107
+ * Note: this will change the order of elements
108
+ */
109
+ AWS_COMMON_API
110
+ void aws_linked_hash_table_move_node_to_end_of_list(
111
+ struct aws_linked_hash_table *table,
112
+ struct aws_linked_hash_table_node *node);
113
+
114
+ /**
115
+ * returns the underlying linked list for iteration.
116
+ *
117
+ * The returned list has nodes of the type: aws_linked_hash_table_node. Use AWS_CONTAINER_OF for access to the element.
118
+ */
119
+ AWS_COMMON_API
120
+ const struct aws_linked_list *aws_linked_hash_table_get_iteration_list(const struct aws_linked_hash_table *table);
121
+
122
+ AWS_EXTERN_C_END
123
+ AWS_POP_SANE_WARNING_LEVEL
124
+
125
+ #endif /* AWS_COMMON_LINKED_HASH_TABLE_H */
include/aws/common/linked_list.h ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_LINKED_LIST_H
2
+ #define AWS_COMMON_LINKED_LIST_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+
11
+ #include <stddef.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ struct aws_linked_list_node {
16
+ struct aws_linked_list_node *next;
17
+ struct aws_linked_list_node *prev;
18
+ };
19
+
20
+ struct aws_linked_list {
21
+ struct aws_linked_list_node head;
22
+ struct aws_linked_list_node tail;
23
+ };
24
+
25
+ AWS_EXTERN_C_BEGIN
26
+
27
+ /**
28
+ * Set node's next and prev pointers to NULL.
29
+ */
30
+ AWS_STATIC_IMPL void aws_linked_list_node_reset(struct aws_linked_list_node *node);
31
+
32
+ /**
33
+ * These functions need to be defined first as they are used in pre
34
+ * and post conditions.
35
+ */
36
+
37
+ /**
38
+ * Tests if the list is empty.
39
+ */
40
+ AWS_STATIC_IMPL bool aws_linked_list_empty(const struct aws_linked_list *list);
41
+
42
+ /**
43
+ * Checks that a linked list is valid.
44
+ */
45
+ AWS_STATIC_IMPL bool aws_linked_list_is_valid(const struct aws_linked_list *list);
46
+ /**
47
+ * Checks that the prev of the next pointer of a node points to the
48
+ * node. As this checks whether the [next] connection of a node is
49
+ * bidirectional, it returns false if used for the list tail.
50
+ */
51
+ AWS_STATIC_IMPL bool aws_linked_list_node_next_is_valid(const struct aws_linked_list_node *node);
52
+
53
+ /**
54
+ * Checks that the next of the prev pointer of a node points to the
55
+ * node. Similarly to the above, this returns false if used for the
56
+ * head of a list.
57
+ */
58
+ AWS_STATIC_IMPL bool aws_linked_list_node_prev_is_valid(const struct aws_linked_list_node *node);
59
+ /**
60
+ * Checks that a linked list satisfies double linked list connectivity
61
+ * constraints. This check is O(n) as it traverses the whole linked
62
+ * list to ensure that tail is reachable from head (and vice versa)
63
+ * and that every connection is bidirectional.
64
+ *
65
+ * Note: This check *cannot* go into an infinite loop, because we
66
+ * ensure that the connection to the next node is
67
+ * bidirectional. Therefore, if a node's [a] a.next is a previous node
68
+ * [b] in the list, b.prev != &a and so this check would fail, thus
69
+ * terminating the loop.
70
+ */
71
+ AWS_STATIC_IMPL bool aws_linked_list_is_valid_deep(const struct aws_linked_list *list);
72
+
73
+ /**
74
+ * Initializes the list. List will be empty after this call.
75
+ */
76
+ AWS_STATIC_IMPL void aws_linked_list_init(struct aws_linked_list *list);
77
+
78
+ /**
79
+ * Returns an iteration pointer for the first element in the list.
80
+ */
81
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_begin(const struct aws_linked_list *list);
82
+
83
+ /**
84
+ * Returns an iteration pointer for one past the last element in the list.
85
+ */
86
+ AWS_STATIC_IMPL const struct aws_linked_list_node *aws_linked_list_end(const struct aws_linked_list *list);
87
+
88
+ /**
89
+ * Returns a pointer for the last element in the list.
90
+ * Used to begin iterating the list in reverse. Ex:
91
+ * for (i = aws_linked_list_rbegin(list); i != aws_linked_list_rend(list); i = aws_linked_list_prev(i)) {...}
92
+ */
93
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_rbegin(const struct aws_linked_list *list);
94
+
95
+ /**
96
+ * Returns the pointer to one before the first element in the list.
97
+ * Used to end iterating the list in reverse.
98
+ */
99
+ AWS_STATIC_IMPL const struct aws_linked_list_node *aws_linked_list_rend(const struct aws_linked_list *list);
100
+
101
+ /**
102
+ * Returns the next element in the list.
103
+ */
104
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_next(const struct aws_linked_list_node *node);
105
+
106
+ /**
107
+ * Returns the previous element in the list.
108
+ */
109
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_prev(const struct aws_linked_list_node *node);
110
+
111
+ /**
112
+ * Inserts to_add immediately after after.
113
+ */
114
+ AWS_STATIC_IMPL void aws_linked_list_insert_after(
115
+ struct aws_linked_list_node *after,
116
+ struct aws_linked_list_node *to_add);
117
+ /**
118
+ * Swaps the order two nodes in the linked list.
119
+ */
120
+ AWS_STATIC_IMPL void aws_linked_list_swap_nodes(struct aws_linked_list_node *a, struct aws_linked_list_node *b);
121
+
122
+ /**
123
+ * Inserts to_add immediately before before.
124
+ */
125
+ AWS_STATIC_IMPL void aws_linked_list_insert_before(
126
+ struct aws_linked_list_node *before,
127
+ struct aws_linked_list_node *to_add);
128
+
129
+ /**
130
+ * Removes the specified node from the list (prev/next point to each other) and
131
+ * returns the next node in the list.
132
+ */
133
+ AWS_STATIC_IMPL void aws_linked_list_remove(struct aws_linked_list_node *node);
134
+
135
+ /**
136
+ * Append new_node.
137
+ */
138
+ AWS_STATIC_IMPL void aws_linked_list_push_back(struct aws_linked_list *list, struct aws_linked_list_node *node);
139
+
140
+ /**
141
+ * Returns the element in the back of the list.
142
+ */
143
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_back(const struct aws_linked_list *list);
144
+
145
+ /**
146
+ * Returns the element in the back of the list and removes it
147
+ */
148
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_pop_back(struct aws_linked_list *list);
149
+
150
+ /**
151
+ * Prepend new_node.
152
+ */
153
+ AWS_STATIC_IMPL void aws_linked_list_push_front(struct aws_linked_list *list, struct aws_linked_list_node *node);
154
+ /**
155
+ * Returns the element in the front of the list.
156
+ */
157
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_front(const struct aws_linked_list *list);
158
+ /**
159
+ * Returns the element in the front of the list and removes it
160
+ */
161
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_pop_front(struct aws_linked_list *list);
162
+
163
+ AWS_STATIC_IMPL void aws_linked_list_swap_contents(
164
+ struct aws_linked_list *AWS_RESTRICT a,
165
+ struct aws_linked_list *AWS_RESTRICT b);
166
+
167
+ /**
168
+ * Remove all nodes from one list, and add them to the back of another.
169
+ *
170
+ * Example: if dst={1,2} and src={3,4}, they become dst={1,2,3,4} and src={}
171
+ */
172
+ AWS_STATIC_IMPL void aws_linked_list_move_all_back(
173
+ struct aws_linked_list *AWS_RESTRICT dst,
174
+ struct aws_linked_list *AWS_RESTRICT src);
175
+
176
+ /**
177
+ * Remove all nodes from one list, and add them to the front of another.
178
+ *
179
+ * Example: if dst={2,1} and src={4,3}, they become dst={4,3,2,1} and src={}
180
+ */
181
+ AWS_STATIC_IMPL void aws_linked_list_move_all_front(
182
+ struct aws_linked_list *AWS_RESTRICT dst,
183
+ struct aws_linked_list *AWS_RESTRICT src);
184
+
185
+ /**
186
+ * Returns true if the node is currently in a list, false otherwise.
187
+ */
188
+ AWS_STATIC_IMPL bool aws_linked_list_node_is_in_list(struct aws_linked_list_node *node);
189
+ AWS_EXTERN_C_END
190
+
191
+ #ifndef AWS_NO_STATIC_IMPL
192
+ # include <aws/common/linked_list.inl>
193
+ #endif /* AWS_NO_STATIC_IMPL */
194
+ AWS_POP_SANE_WARNING_LEVEL
195
+
196
+ #endif /* AWS_COMMON_LINKED_LIST_H */
include/aws/common/linked_list.inl ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_LINKED_LIST_INL
2
+ #define AWS_COMMON_LINKED_LIST_INL
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/common.h>
10
+ #include <aws/common/linked_list.h>
11
+ #include <stddef.h>
12
+
13
+ AWS_EXTERN_C_BEGIN
14
+
15
+ /**
16
+ * Set node's next and prev pointers to NULL.
17
+ */
18
+ AWS_STATIC_IMPL void aws_linked_list_node_reset(struct aws_linked_list_node *node) {
19
+ AWS_PRECONDITION(node != NULL);
20
+ AWS_ZERO_STRUCT(*node);
21
+ AWS_POSTCONDITION(AWS_IS_ZEROED(*node));
22
+ }
23
+
24
+ /**
25
+ * These functions need to be defined first as they are used in pre
26
+ * and post conditions.
27
+ */
28
+
29
+ /**
30
+ * Tests if the list is empty.
31
+ */
32
+ AWS_STATIC_IMPL bool aws_linked_list_empty(const struct aws_linked_list *list) {
33
+ AWS_PRECONDITION(list);
34
+ return list->head.next == &list->tail;
35
+ }
36
+
37
+ /**
38
+ * Checks that a linked list is valid.
39
+ */
40
+ AWS_STATIC_IMPL bool aws_linked_list_is_valid(const struct aws_linked_list *list) {
41
+ if (list && list->head.next && list->head.prev == NULL && list->tail.prev && list->tail.next == NULL) {
42
+ #if defined(AWS_DEEP_CHECKS) && (AWS_DEEP_CHECKS == 1)
43
+ return aws_linked_list_is_valid_deep(list);
44
+ #else
45
+ return true;
46
+ #endif
47
+ }
48
+ return false;
49
+ }
50
+
51
+ /**
52
+ * Checks that the prev of the next pointer of a node points to the
53
+ * node. As this checks whether the [next] connection of a node is
54
+ * bidirectional, it returns false if used for the list tail.
55
+ */
56
+ AWS_STATIC_IMPL bool aws_linked_list_node_next_is_valid(const struct aws_linked_list_node *node) {
57
+ return node && node->next && node->next->prev == node;
58
+ }
59
+
60
+ /**
61
+ * Checks that the next of the prev pointer of a node points to the
62
+ * node. Similarly to the above, this returns false if used for the
63
+ * head of a list.
64
+ */
65
+ AWS_STATIC_IMPL bool aws_linked_list_node_prev_is_valid(const struct aws_linked_list_node *node) {
66
+ return node && node->prev && node->prev->next == node;
67
+ }
68
+
69
+ /**
70
+ * Checks that a linked list satisfies double linked list connectivity
71
+ * constraints. This check is O(n) as it traverses the whole linked
72
+ * list to ensure that tail is reachable from head (and vice versa)
73
+ * and that every connection is bidirectional.
74
+ *
75
+ * Note: This check *cannot* go into an infinite loop, because we
76
+ * ensure that the connection to the next node is
77
+ * bidirectional. Therefore, if a node's [a] a.next is a previous node
78
+ * [b] in the list, b.prev != &a and so this check would fail, thus
79
+ * terminating the loop.
80
+ */
81
+ AWS_STATIC_IMPL bool aws_linked_list_is_valid_deep(const struct aws_linked_list *list) {
82
+ if (!list) {
83
+ return false;
84
+ }
85
+ /* This could go into an infinite loop for a circular list */
86
+ const struct aws_linked_list_node *temp = &list->head;
87
+ /* Head must reach tail by following next pointers */
88
+ bool head_reaches_tail = false;
89
+ /* By satisfying the above and that edges are bidirectional, we
90
+ * also guarantee that tail reaches head by following prev
91
+ * pointers */
92
+ while (temp) {
93
+ if (temp == &list->tail) {
94
+ head_reaches_tail = true;
95
+ break;
96
+ } else if (!aws_linked_list_node_next_is_valid(temp)) {
97
+ /* Next and prev pointers should connect the same nodes */
98
+ return false;
99
+ }
100
+ temp = temp->next;
101
+ }
102
+ return head_reaches_tail;
103
+ }
104
+
105
+ /**
106
+ * Initializes the list. List will be empty after this call.
107
+ */
108
+ AWS_STATIC_IMPL void aws_linked_list_init(struct aws_linked_list *list) {
109
+ AWS_PRECONDITION(list);
110
+ list->head.next = &list->tail;
111
+ list->head.prev = NULL;
112
+ list->tail.prev = &list->head;
113
+ list->tail.next = NULL;
114
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
115
+ AWS_POSTCONDITION(aws_linked_list_empty(list));
116
+ }
117
+
118
+ /**
119
+ * Returns an iteration pointer for the first element in the list.
120
+ */
121
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_begin(const struct aws_linked_list *list) {
122
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
123
+ struct aws_linked_list_node *rval = list->head.next;
124
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
125
+ AWS_POSTCONDITION(rval == list->head.next);
126
+ return rval;
127
+ }
128
+
129
+ /**
130
+ * Returns an iteration pointer for one past the last element in the list.
131
+ */
132
+ AWS_STATIC_IMPL const struct aws_linked_list_node *aws_linked_list_end(const struct aws_linked_list *list) {
133
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
134
+ const struct aws_linked_list_node *rval = &list->tail;
135
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
136
+ AWS_POSTCONDITION(rval == &list->tail);
137
+ return rval;
138
+ }
139
+
140
+ /**
141
+ * Returns a pointer for the last element in the list.
142
+ * Used to begin iterating the list in reverse. Ex:
143
+ * for (i = aws_linked_list_rbegin(list); i != aws_linked_list_rend(list); i = aws_linked_list_prev(i)) {...}
144
+ */
145
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_rbegin(const struct aws_linked_list *list) {
146
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
147
+ struct aws_linked_list_node *rval = list->tail.prev;
148
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
149
+ AWS_POSTCONDITION(rval == list->tail.prev);
150
+ return rval;
151
+ }
152
+
153
+ /**
154
+ * Returns the pointer to one before the first element in the list.
155
+ * Used to end iterating the list in reverse.
156
+ */
157
+ AWS_STATIC_IMPL const struct aws_linked_list_node *aws_linked_list_rend(const struct aws_linked_list *list) {
158
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
159
+ const struct aws_linked_list_node *rval = &list->head;
160
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
161
+ AWS_POSTCONDITION(rval == &list->head);
162
+ return rval;
163
+ }
164
+
165
+ /**
166
+ * Returns the next element in the list.
167
+ */
168
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_next(const struct aws_linked_list_node *node) {
169
+ AWS_PRECONDITION(aws_linked_list_node_next_is_valid(node));
170
+ struct aws_linked_list_node *rval = node->next;
171
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(node));
172
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(rval));
173
+ AWS_POSTCONDITION(rval == node->next);
174
+ return rval;
175
+ }
176
+
177
+ /**
178
+ * Returns the previous element in the list.
179
+ */
180
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_prev(const struct aws_linked_list_node *node) {
181
+ AWS_PRECONDITION(aws_linked_list_node_prev_is_valid(node));
182
+ struct aws_linked_list_node *rval = node->prev;
183
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(node));
184
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(rval));
185
+ AWS_POSTCONDITION(rval == node->prev);
186
+ return rval;
187
+ }
188
+
189
+ /**
190
+ * Inserts to_add immediately after after.
191
+ */
192
+ AWS_STATIC_IMPL void aws_linked_list_insert_after(
193
+ struct aws_linked_list_node *after,
194
+ struct aws_linked_list_node *to_add) {
195
+ AWS_PRECONDITION(aws_linked_list_node_next_is_valid(after));
196
+ AWS_PRECONDITION(to_add != NULL);
197
+ to_add->prev = after;
198
+ to_add->next = after->next;
199
+ after->next->prev = to_add;
200
+ after->next = to_add;
201
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(after));
202
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(to_add));
203
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(to_add));
204
+ AWS_POSTCONDITION(after->next == to_add);
205
+ }
206
+
207
+ /**
208
+ * Swaps the order two nodes in the linked list.
209
+ */
210
+ AWS_STATIC_IMPL void aws_linked_list_swap_nodes(struct aws_linked_list_node *a, struct aws_linked_list_node *b) {
211
+ AWS_PRECONDITION(aws_linked_list_node_prev_is_valid(a));
212
+ AWS_PRECONDITION(aws_linked_list_node_next_is_valid(a));
213
+ AWS_PRECONDITION(aws_linked_list_node_prev_is_valid(b));
214
+ AWS_PRECONDITION(aws_linked_list_node_next_is_valid(b));
215
+
216
+ if (a == b) {
217
+ return;
218
+ }
219
+
220
+ /* snapshot b's value to avoid clobbering its next/prev pointers if a/b are adjacent */
221
+ struct aws_linked_list_node tmp = *b;
222
+ a->prev->next = b;
223
+ a->next->prev = b;
224
+
225
+ tmp.prev->next = a;
226
+ tmp.next->prev = a;
227
+
228
+ tmp = *a;
229
+ *a = *b;
230
+ *b = tmp;
231
+
232
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(a));
233
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(a));
234
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(b));
235
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(b));
236
+ }
237
+
238
+ /**
239
+ * Inserts to_add immediately before before.
240
+ */
241
+ AWS_STATIC_IMPL void aws_linked_list_insert_before(
242
+ struct aws_linked_list_node *before,
243
+ struct aws_linked_list_node *to_add) {
244
+ AWS_PRECONDITION(aws_linked_list_node_prev_is_valid(before));
245
+ AWS_PRECONDITION(to_add != NULL);
246
+ to_add->next = before;
247
+ to_add->prev = before->prev;
248
+ before->prev->next = to_add;
249
+ before->prev = to_add;
250
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(before));
251
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(to_add));
252
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(to_add));
253
+ AWS_POSTCONDITION(before->prev == to_add);
254
+ }
255
+
256
+ /**
257
+ * Removes the specified node from the list (prev/next point to each other) and
258
+ * returns the next node in the list.
259
+ */
260
+ AWS_STATIC_IMPL void aws_linked_list_remove(struct aws_linked_list_node *node) {
261
+ AWS_PRECONDITION(aws_linked_list_node_prev_is_valid(node));
262
+ AWS_PRECONDITION(aws_linked_list_node_next_is_valid(node));
263
+ node->prev->next = node->next;
264
+ node->next->prev = node->prev;
265
+ aws_linked_list_node_reset(node);
266
+ AWS_POSTCONDITION(node->next == NULL && node->prev == NULL);
267
+ }
268
+
269
+ /**
270
+ * Append new_node.
271
+ */
272
+ AWS_STATIC_IMPL void aws_linked_list_push_back(struct aws_linked_list *list, struct aws_linked_list_node *node) {
273
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
274
+ AWS_PRECONDITION(node != NULL);
275
+ aws_linked_list_insert_before(&list->tail, node);
276
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
277
+ AWS_POSTCONDITION(list->tail.prev == node, "[node] is the new last element of [list]");
278
+ }
279
+
280
+ /**
281
+ * Returns the element in the back of the list.
282
+ */
283
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_back(const struct aws_linked_list *list) {
284
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
285
+ AWS_PRECONDITION(!aws_linked_list_empty(list));
286
+ struct aws_linked_list_node *rval = list->tail.prev;
287
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
288
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(rval));
289
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(rval));
290
+ return rval;
291
+ }
292
+
293
+ /**
294
+ * Returns the element in the back of the list and removes it
295
+ */
296
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_pop_back(struct aws_linked_list *list) {
297
+ AWS_PRECONDITION(!aws_linked_list_empty(list));
298
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
299
+ struct aws_linked_list_node *back = aws_linked_list_back(list);
300
+ aws_linked_list_remove(back);
301
+ AWS_POSTCONDITION(back->next == NULL && back->prev == NULL);
302
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
303
+ return back;
304
+ }
305
+
306
+ /**
307
+ * Prepend new_node.
308
+ */
309
+ AWS_STATIC_IMPL void aws_linked_list_push_front(struct aws_linked_list *list, struct aws_linked_list_node *node) {
310
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
311
+ AWS_PRECONDITION(node != NULL);
312
+ aws_linked_list_insert_before(list->head.next, node);
313
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
314
+ AWS_POSTCONDITION(list->head.next == node, "[node] is the new first element of [list]");
315
+ }
316
+
317
+ /**
318
+ * Returns the element in the front of the list.
319
+ */
320
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_front(const struct aws_linked_list *list) {
321
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
322
+ AWS_PRECONDITION(!aws_linked_list_empty(list));
323
+ struct aws_linked_list_node *rval = list->head.next;
324
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
325
+ AWS_POSTCONDITION(aws_linked_list_node_prev_is_valid(rval));
326
+ AWS_POSTCONDITION(aws_linked_list_node_next_is_valid(rval));
327
+ return rval;
328
+ }
329
+
330
+ /**
331
+ * Returns the element in the front of the list and removes it
332
+ */
333
+ AWS_STATIC_IMPL struct aws_linked_list_node *aws_linked_list_pop_front(struct aws_linked_list *list) {
334
+ AWS_PRECONDITION(!aws_linked_list_empty(list));
335
+ AWS_PRECONDITION(aws_linked_list_is_valid(list));
336
+ struct aws_linked_list_node *front = aws_linked_list_front(list);
337
+ aws_linked_list_remove(front);
338
+ AWS_POSTCONDITION(front->next == NULL && front->prev == NULL);
339
+ AWS_POSTCONDITION(aws_linked_list_is_valid(list));
340
+ return front;
341
+ }
342
+
343
+ AWS_STATIC_IMPL void aws_linked_list_swap_contents(
344
+ struct aws_linked_list *AWS_RESTRICT a,
345
+ struct aws_linked_list *AWS_RESTRICT b) {
346
+
347
+ AWS_PRECONDITION(aws_linked_list_is_valid(a));
348
+ AWS_PRECONDITION(aws_linked_list_is_valid(b));
349
+ AWS_PRECONDITION(a != b);
350
+ struct aws_linked_list_node *a_first = a->head.next;
351
+ struct aws_linked_list_node *a_last = a->tail.prev;
352
+
353
+ /* Move B's contents into A */
354
+ if (aws_linked_list_empty(b)) {
355
+ aws_linked_list_init(a);
356
+ } else {
357
+ a->head.next = b->head.next;
358
+ a->head.next->prev = &a->head;
359
+ a->tail.prev = b->tail.prev;
360
+ a->tail.prev->next = &a->tail;
361
+ }
362
+
363
+ /* Move A's old contents into B */
364
+ if (a_first == &a->tail) {
365
+ aws_linked_list_init(b);
366
+ } else {
367
+ b->head.next = a_first;
368
+ b->head.next->prev = &b->head;
369
+ b->tail.prev = a_last;
370
+ b->tail.prev->next = &b->tail;
371
+ }
372
+ AWS_POSTCONDITION(aws_linked_list_is_valid(a));
373
+ AWS_POSTCONDITION(aws_linked_list_is_valid(b));
374
+ }
375
+
376
+ AWS_STATIC_IMPL void aws_linked_list_move_all_back(
377
+ struct aws_linked_list *AWS_RESTRICT dst,
378
+ struct aws_linked_list *AWS_RESTRICT src) {
379
+
380
+ AWS_PRECONDITION(aws_linked_list_is_valid(src));
381
+ AWS_PRECONDITION(aws_linked_list_is_valid(dst));
382
+ AWS_PRECONDITION(dst != src);
383
+
384
+ if (!aws_linked_list_empty(src)) {
385
+ /* splice src nodes into dst, between the back and tail nodes */
386
+ struct aws_linked_list_node *dst_back = dst->tail.prev;
387
+ struct aws_linked_list_node *src_front = src->head.next;
388
+ struct aws_linked_list_node *src_back = src->tail.prev;
389
+
390
+ dst_back->next = src_front;
391
+ src_front->prev = dst_back;
392
+
393
+ dst->tail.prev = src_back;
394
+ src_back->next = &dst->tail;
395
+
396
+ /* reset src */
397
+ src->head.next = &src->tail;
398
+ src->tail.prev = &src->head;
399
+ }
400
+
401
+ AWS_POSTCONDITION(aws_linked_list_is_valid(src));
402
+ AWS_POSTCONDITION(aws_linked_list_is_valid(dst));
403
+ }
404
+
405
+ AWS_STATIC_IMPL void aws_linked_list_move_all_front(
406
+ struct aws_linked_list *AWS_RESTRICT dst,
407
+ struct aws_linked_list *AWS_RESTRICT src) {
408
+
409
+ AWS_PRECONDITION(aws_linked_list_is_valid(src));
410
+ AWS_PRECONDITION(aws_linked_list_is_valid(dst));
411
+ AWS_PRECONDITION(dst != src);
412
+
413
+ if (!aws_linked_list_empty(src)) {
414
+ /* splice src nodes into dst, between the head and front nodes */
415
+ struct aws_linked_list_node *dst_front = dst->head.next;
416
+ struct aws_linked_list_node *src_front = src->head.next;
417
+ struct aws_linked_list_node *src_back = src->tail.prev;
418
+
419
+ dst->head.next = src_front;
420
+ src_front->prev = &dst->head;
421
+
422
+ src_back->next = dst_front;
423
+ dst_front->prev = src_back;
424
+
425
+ /* reset src */
426
+ src->head.next = &src->tail;
427
+ src->tail.prev = &src->head;
428
+ }
429
+
430
+ AWS_POSTCONDITION(aws_linked_list_is_valid(src));
431
+ AWS_POSTCONDITION(aws_linked_list_is_valid(dst));
432
+ }
433
+
434
+ AWS_STATIC_IMPL bool aws_linked_list_node_is_in_list(struct aws_linked_list_node *node) {
435
+ return aws_linked_list_node_prev_is_valid(node) && aws_linked_list_node_next_is_valid(node);
436
+ }
437
+
438
+ AWS_EXTERN_C_END
439
+
440
+ #endif /* AWS_COMMON_LINKED_LIST_INL */
include/aws/common/log_channel.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #ifndef AWS_COMMON_LOG_CHANNEL_H
3
+ #define AWS_COMMON_LOG_CHANNEL_H
4
+
5
+ /**
6
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7
+ * SPDX-License-Identifier: Apache-2.0.
8
+ */
9
+
10
+ #include <aws/common/common.h>
11
+
12
+ #include <aws/common/logging.h>
13
+
14
+ AWS_PUSH_SANE_WARNING_LEVEL
15
+
16
+ struct aws_string;
17
+ struct aws_log_writer;
18
+
19
+ /*
20
+ * Log channel interface and default implementations
21
+ *
22
+ * A log channel is an abstraction for the transfer of formatted log data between a source (formatter)
23
+ * and a sink (writer).
24
+ */
25
+ struct aws_log_channel;
26
+
27
+ typedef int(aws_log_channel_send_fn)(struct aws_log_channel *channel, struct aws_string *output);
28
+ typedef void(aws_log_channel_clean_up_fn)(struct aws_log_channel *channel);
29
+
30
+ struct aws_log_channel_vtable {
31
+ aws_log_channel_send_fn *send;
32
+ aws_log_channel_clean_up_fn *clean_up;
33
+ };
34
+
35
+ struct aws_log_channel {
36
+ struct aws_log_channel_vtable *vtable;
37
+ struct aws_allocator *allocator;
38
+ struct aws_log_writer *writer;
39
+ void *impl;
40
+ };
41
+
42
+ AWS_EXTERN_C_BEGIN
43
+
44
+ /*
45
+ * Simple channel that results in log lines being written in the same thread they were generated in.
46
+ *
47
+ * The passed in log writer is not an ownership transfer. The log channel does not clean up the writer.
48
+ */
49
+ AWS_COMMON_API
50
+ int aws_log_channel_init_foreground(
51
+ struct aws_log_channel *channel,
52
+ struct aws_allocator *allocator,
53
+ struct aws_log_writer *writer);
54
+
55
+ /*
56
+ * Simple channel that sends log lines to a background thread.
57
+ *
58
+ * The passed in log writer is not an ownership transfer. The log channel does not clean up the writer.
59
+ */
60
+ AWS_COMMON_API
61
+ int aws_log_channel_init_background(
62
+ struct aws_log_channel *channel,
63
+ struct aws_allocator *allocator,
64
+ struct aws_log_writer *writer);
65
+
66
+ /*
67
+ * Channel cleanup function
68
+ */
69
+ AWS_COMMON_API
70
+ void aws_log_channel_clean_up(struct aws_log_channel *channel);
71
+
72
+ AWS_EXTERN_C_END
73
+ AWS_POP_SANE_WARNING_LEVEL
74
+
75
+ #endif /* AWS_COMMON_LOG_CHANNEL_H */
include/aws/common/log_formatter.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #ifndef AWS_COMMON_LOG_FORMATTER_H
3
+ #define AWS_COMMON_LOG_FORMATTER_H
4
+
5
+ /**
6
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7
+ * SPDX-License-Identifier: Apache-2.0.
8
+ */
9
+
10
+ #include <aws/common/common.h>
11
+
12
+ #include <aws/common/date_time.h>
13
+ #include <aws/common/logging.h>
14
+
15
+ #include <stdarg.h>
16
+ #include <stdio.h>
17
+
18
+ AWS_PUSH_SANE_WARNING_LEVEL
19
+
20
+ struct aws_allocator;
21
+ struct aws_string;
22
+
23
+ /*
24
+ * Log formatter interface and default implementation
25
+ *
26
+ * Log formatters are invoked by the LOGF_* macros to transform a set of arguments into
27
+ * one or more lines of text to be output to a logging sink (writer).
28
+ */
29
+ struct aws_log_formatter;
30
+
31
+ typedef int(aws_log_formatter_format_fn)(
32
+ struct aws_log_formatter *formatter,
33
+ struct aws_string **formatted_output,
34
+ enum aws_log_level level,
35
+ aws_log_subject_t subject,
36
+ const char *format,
37
+ va_list args);
38
+
39
+ typedef void(aws_log_formatter_clean_up_fn)(struct aws_log_formatter *logger);
40
+
41
+ struct aws_log_formatter_vtable {
42
+ aws_log_formatter_format_fn *format;
43
+ aws_log_formatter_clean_up_fn *clean_up;
44
+ };
45
+
46
+ struct aws_log_formatter {
47
+ struct aws_log_formatter_vtable *vtable;
48
+ struct aws_allocator *allocator;
49
+ void *impl;
50
+ };
51
+
52
+ struct aws_log_formatter_standard_options {
53
+ enum aws_date_format date_format;
54
+ };
55
+
56
+ struct aws_logging_standard_formatting_data {
57
+ char *log_line_buffer;
58
+ size_t total_length;
59
+ enum aws_log_level level;
60
+ const char *subject_name;
61
+ const char *format;
62
+ enum aws_date_format date_format;
63
+ struct aws_allocator *allocator; /* not used, just there to make byte_bufs valid */
64
+
65
+ size_t amount_written;
66
+ };
67
+
68
+ AWS_EXTERN_C_BEGIN
69
+
70
+ /*
71
+ * Initializes the default log formatter which outputs lines in the format:
72
+ *
73
+ * [<LogLevel>] [<Timestamp>] [<ThreadId>] - <User content>\n
74
+ */
75
+ AWS_COMMON_API
76
+ int aws_log_formatter_init_default(
77
+ struct aws_log_formatter *formatter,
78
+ struct aws_allocator *allocator,
79
+ struct aws_log_formatter_standard_options *options);
80
+
81
+ /*
82
+ * Cleans up a log formatter (minus the base structure memory) by calling the formatter's clean_up function
83
+ * via the vtable.
84
+ */
85
+ AWS_COMMON_API
86
+ void aws_log_formatter_clean_up(struct aws_log_formatter *formatter);
87
+
88
+ /*
89
+ * Formats a single log line based on the input + the var args list. Output is written to a fixed-size
90
+ * buffer supplied in the data struct.
91
+ */
92
+ AWS_COMMON_API
93
+ int aws_format_standard_log_line(struct aws_logging_standard_formatting_data *formatting_data, va_list args);
94
+
95
+ AWS_EXTERN_C_END
96
+ AWS_POP_SANE_WARNING_LEVEL
97
+
98
+ #endif /* AWS_COMMON_LOG_FORMATTER_H */
include/aws/common/log_writer.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #ifndef AWS_COMMON_LOG_WRITER_H
3
+ #define AWS_COMMON_LOG_WRITER_H
4
+
5
+ /**
6
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7
+ * SPDX-License-Identifier: Apache-2.0.
8
+ */
9
+
10
+ #include <aws/common/common.h>
11
+
12
+ AWS_PUSH_SANE_WARNING_LEVEL
13
+
14
+ struct aws_allocator;
15
+ struct aws_string;
16
+
17
+ /*
18
+ * Log writer interface and default implementation(s)
19
+ *
20
+ * A log writer functions as a sink for formatted log lines. We provide
21
+ * default implementations that go to stdout, stderr, and a specified file.
22
+ */
23
+ struct aws_log_writer;
24
+
25
+ typedef int(aws_log_writer_write_fn)(struct aws_log_writer *writer, const struct aws_string *output);
26
+ typedef void(aws_log_writer_clean_up_fn)(struct aws_log_writer *writer);
27
+
28
+ struct aws_log_writer_vtable {
29
+ aws_log_writer_write_fn *write;
30
+ aws_log_writer_clean_up_fn *clean_up;
31
+ };
32
+
33
+ struct aws_log_writer {
34
+ struct aws_log_writer_vtable *vtable;
35
+ struct aws_allocator *allocator;
36
+ void *impl;
37
+ };
38
+
39
+ struct aws_log_writer_file_options {
40
+ const char *filename;
41
+ FILE *file;
42
+ };
43
+
44
+ AWS_EXTERN_C_BEGIN
45
+
46
+ /*
47
+ * Initialize a log writer that sends log lines to stdout. Uses C library IO.
48
+ */
49
+ AWS_COMMON_API
50
+ int aws_log_writer_init_stdout(struct aws_log_writer *writer, struct aws_allocator *allocator);
51
+
52
+ /*
53
+ * Initialize a log writer that sends log lines to stderr. Uses C library IO.
54
+ */
55
+ AWS_COMMON_API
56
+ int aws_log_writer_init_stderr(struct aws_log_writer *writer, struct aws_allocator *allocator);
57
+
58
+ /*
59
+ * Initialize a log writer that sends log lines to a file. Uses C library IO.
60
+ */
61
+ AWS_COMMON_API
62
+ int aws_log_writer_init_file(
63
+ struct aws_log_writer *writer,
64
+ struct aws_allocator *allocator,
65
+ struct aws_log_writer_file_options *options);
66
+
67
+ /*
68
+ * Frees all resources used by a log writer with the exception of the base structure memory
69
+ */
70
+ AWS_COMMON_API
71
+ void aws_log_writer_clean_up(struct aws_log_writer *writer);
72
+
73
+ AWS_EXTERN_C_END
74
+ AWS_POP_SANE_WARNING_LEVEL
75
+
76
+ #endif /* AWS_COMMON_LOG_WRITER_H */
include/aws/common/logging.h ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef AWS_COMMON_LOGGING_H
2
+ #define AWS_COMMON_LOGGING_H
3
+
4
+ /**
5
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
+ * SPDX-License-Identifier: Apache-2.0.
7
+ */
8
+
9
+ #include <aws/common/atomics.h>
10
+ #include <aws/common/common.h>
11
+ #include <aws/common/thread.h>
12
+
13
+ AWS_PUSH_SANE_WARNING_LEVEL
14
+
15
+ #define AWS_LOG_LEVEL_NONE 0
16
+ #define AWS_LOG_LEVEL_FATAL 1
17
+ #define AWS_LOG_LEVEL_ERROR 2
18
+ #define AWS_LOG_LEVEL_WARN 3
19
+ #define AWS_LOG_LEVEL_INFO 4
20
+ #define AWS_LOG_LEVEL_DEBUG 5
21
+ #define AWS_LOG_LEVEL_TRACE 6
22
+
23
+ /**
24
+ * Controls what log calls pass through the logger and what log calls get filtered out.
25
+ * If a log level has a value of X, then all log calls using a level <= X will appear, while
26
+ * those using a value > X will not occur.
27
+ *
28
+ * You can filter both dynamically (by setting the log level on the logger object) or statically
29
+ * (by defining AWS_STATIC_LOG_LEVEL to be an appropriate integer module-wide). Statically filtered
30
+ * log calls will be completely compiled out but require a rebuild if you want to get more detail
31
+ * about what's happening.
32
+ */
33
+ enum aws_log_level {
34
+ AWS_LL_NONE = AWS_LOG_LEVEL_NONE,
35
+ AWS_LL_FATAL = AWS_LOG_LEVEL_FATAL,
36
+ AWS_LL_ERROR = AWS_LOG_LEVEL_ERROR,
37
+ AWS_LL_WARN = AWS_LOG_LEVEL_WARN,
38
+ AWS_LL_INFO = AWS_LOG_LEVEL_INFO,
39
+ AWS_LL_DEBUG = AWS_LOG_LEVEL_DEBUG,
40
+ AWS_LL_TRACE = AWS_LOG_LEVEL_TRACE,
41
+
42
+ AWS_LL_COUNT
43
+ };
44
+
45
+ /**
46
+ * Log subject is a way of designating the topic of logging.
47
+ *
48
+ * The general idea is to support a finer-grained approach to log level control. The primary use case
49
+ * is for situations that require more detailed logging within a specific domain, where enabling that detail
50
+ * globally leads to an untenable flood of information.
51
+ *
52
+ * For example, enable TRACE logging for tls-related log statements (handshake binary payloads), but
53
+ * only WARN logging everywhere else (because http payloads would blow up the log files).
54
+ *
55
+ * Log subject is an enum similar to aws error: each library has its own value-space and someone is
56
+ * responsible for registering the value <-> string connections.
57
+ */
58
+ typedef uint32_t aws_log_subject_t;
59
+
60
+ /* Each library gets space for 2^^10 log subject entries */
61
+ enum {
62
+ AWS_LOG_SUBJECT_STRIDE_BITS = 10,
63
+ };
64
+ #define AWS_LOG_SUBJECT_STRIDE (1U << AWS_LOG_SUBJECT_STRIDE_BITS)
65
+ #define AWS_LOG_SUBJECT_BEGIN_RANGE(x) ((x) * AWS_LOG_SUBJECT_STRIDE)
66
+ #define AWS_LOG_SUBJECT_END_RANGE(x) (((x) + 1) * AWS_LOG_SUBJECT_STRIDE - 1)
67
+
68
+ struct aws_log_subject_info {
69
+ aws_log_subject_t subject_id;
70
+ const char *subject_name;
71
+ const char *subject_description;
72
+ };
73
+
74
+ #define DEFINE_LOG_SUBJECT_INFO(id, name, desc) \
75
+ {.subject_id = (id), .subject_name = (name), .subject_description = (desc)}
76
+
77
+ struct aws_log_subject_info_list {
78
+ struct aws_log_subject_info *subject_list;
79
+ size_t count;
80
+ };
81
+
82
+ enum aws_common_log_subject {
83
+ AWS_LS_COMMON_GENERAL = AWS_LOG_SUBJECT_BEGIN_RANGE(AWS_C_COMMON_PACKAGE_ID),
84
+ AWS_LS_COMMON_TASK_SCHEDULER,
85
+ AWS_LS_COMMON_THREAD,
86
+ AWS_LS_COMMON_MEMTRACE,
87
+ AWS_LS_COMMON_XML_PARSER,
88
+ AWS_LS_COMMON_IO,
89
+ AWS_LS_COMMON_BUS,
90
+ AWS_LS_COMMON_TEST,
91
+ AWS_LS_COMMON_JSON_PARSER,
92
+ AWS_LS_COMMON_CBOR,
93
+
94
+ AWS_LS_COMMON_LAST = AWS_LOG_SUBJECT_END_RANGE(AWS_C_COMMON_PACKAGE_ID)
95
+ };
96
+
97
+ struct aws_logger;
98
+ struct aws_log_formatter;
99
+ struct aws_log_channel;
100
+ struct aws_log_writer;
101
+
102
+ #ifdef _MSC_VER
103
+ # pragma warning(push)
104
+ # pragma warning(disable : 4623) /* default constructor was implicitly defined as deleted */
105
+ # pragma warning(disable : 4626) /* assignment operator was implicitly defined as deleted */
106
+ # pragma warning(disable : 5027) /* move assignment operator was implicitly defined as deleted */
107
+ #endif
108
+
109
+ /**
110
+ * We separate the log level function from the log call itself so that we can do the filter check in the macros (see
111
+ * below)
112
+ *
113
+ * By doing so, we make it so that the variadic format arguments are not even evaluated if the filter check does not
114
+ * succeed.
115
+ */
116
+ struct aws_logger_vtable {
117
+ int (*const log)(
118
+ struct aws_logger *logger,
119
+ enum aws_log_level log_level,
120
+ aws_log_subject_t subject,
121
+ const char *format,
122
+ ...)
123
+ #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
124
+ __attribute__((format(printf, 4, 5)))
125
+ #endif /* non-ms compilers: TODO - find out what versions format support was added in */
126
+ ;
127
+ enum aws_log_level (*const get_log_level)(struct aws_logger *logger, aws_log_subject_t subject);
128
+ void (*const clean_up)(struct aws_logger *logger);
129
+ int (*set_log_level)(struct aws_logger *logger, enum aws_log_level);
130
+ };
131
+
132
+ #ifdef _MSC_VER
133
+ # pragma warning(pop)
134
+ #endif
135
+
136
+ struct aws_logger {
137
+ struct aws_logger_vtable *vtable;
138
+ struct aws_allocator *allocator;
139
+ void *p_impl;
140
+ };
141
+
142
+ /**
143
+ * The base formatted logging macro that all other formatted logging macros resolve to.
144
+ * Checks for a logger and filters based on log level.
145
+ */
146
+ #define AWS_LOGF(log_level, subject, ...) \
147
+ do { \
148
+ AWS_ASSERT(log_level > 0); \
149
+ struct aws_logger *logger = aws_logger_get(); \
150
+ if (logger != NULL && logger->vtable->get_log_level(logger, (subject)) >= (log_level)) { \
151
+ logger->vtable->log(logger, log_level, subject, __VA_ARGS__); \
152
+ } \
153
+ } while (0)
154
+ /**
155
+ * Unconditional logging macro that takes a logger and does not do a level check or a null check. Intended for
156
+ * situations when you need to log many things and do a single manual level check before beginning.
157
+ */
158
+ #define AWS_LOGUF(logger, log_level, subject, ...) \
159
+ { logger->vtable->log(logger, log_level, subject, __VA_ARGS__); }
160
+
161
+ /**
162
+ * LOGF_<level> variants for each level. These are what should be used directly to do all logging.
163
+ *
164
+ * i.e.
165
+ *
166
+ * LOGF_FATAL("Device \"%s\" not found", device->name);
167
+ *
168
+ *
169
+ * Later we will likely expose Subject-aware variants
170
+ */
171
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_FATAL)
172
+ # define AWS_LOGF_FATAL(subject, ...) AWS_LOGF(AWS_LL_FATAL, subject, __VA_ARGS__)
173
+ #else
174
+ # define AWS_LOGF_FATAL(subject, ...)
175
+ #endif
176
+
177
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_ERROR)
178
+ # define AWS_LOGF_ERROR(subject, ...) AWS_LOGF(AWS_LL_ERROR, subject, __VA_ARGS__)
179
+ #else
180
+ # define AWS_LOGF_ERROR(subject, ...)
181
+ #endif
182
+
183
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_WARN)
184
+ # define AWS_LOGF_WARN(subject, ...) AWS_LOGF(AWS_LL_WARN, subject, __VA_ARGS__)
185
+ #else
186
+ # define AWS_LOGF_WARN(subject, ...)
187
+ #endif
188
+
189
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_INFO)
190
+ # define AWS_LOGF_INFO(subject, ...) AWS_LOGF(AWS_LL_INFO, subject, __VA_ARGS__)
191
+ #else
192
+ # define AWS_LOGF_INFO(subject, ...)
193
+ #endif
194
+
195
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_DEBUG)
196
+ # define AWS_LOGF_DEBUG(subject, ...) AWS_LOGF(AWS_LL_DEBUG, subject, __VA_ARGS__)
197
+ #else
198
+ # define AWS_LOGF_DEBUG(subject, ...)
199
+ #endif
200
+
201
+ #if !defined(AWS_STATIC_LOG_LEVEL) || (AWS_STATIC_LOG_LEVEL >= AWS_LOG_LEVEL_TRACE)
202
+ # define AWS_LOGF_TRACE(subject, ...) AWS_LOGF(AWS_LL_TRACE, subject, __VA_ARGS__)
203
+ #else
204
+ # define AWS_LOGF_TRACE(subject, ...)
205
+ #endif
206
+
207
+ /*
208
+ * Standard logger implementation composing three sub-components:
209
+ *
210
+ * The formatter takes var args input from the user and produces a formatted log line
211
+ * The writer takes a formatted log line and outputs it somewhere
212
+ * The channel is the transport between the two
213
+ */
214
+ struct aws_logger_pipeline {
215
+ struct aws_log_formatter *formatter;
216
+ struct aws_log_channel *channel;
217
+ struct aws_log_writer *writer;
218
+ struct aws_allocator *allocator;
219
+ struct aws_atomic_var level;
220
+ };
221
+
222
+ /**
223
+ * Options for aws_logger_init_standard().
224
+ * Set `filename` to open a file for logging and close it when the logger cleans up.
225
+ * Set `file` to use a file that is already open, such as `stderr` or `stdout`.
226
+ */
227
+ struct aws_logger_standard_options {
228
+ enum aws_log_level level;
229
+ const char *filename;
230
+ FILE *file;
231
+ };
232
+
233
+ AWS_EXTERN_C_BEGIN
234
+
235
+ /**
236
+ * Sets the aws logger used globally across the process. Not thread-safe. Must only be called once.
237
+ */
238
+ AWS_COMMON_API
239
+ void aws_logger_set(struct aws_logger *logger);
240
+
241
+ /**
242
+ * Gets the aws logger used globally across the process.
243
+ */
244
+ AWS_COMMON_API
245
+ struct aws_logger *aws_logger_get(void);
246
+
247
+ /**
248
+ * Gets the aws logger used globally across the process if the logging level is at least the inputted level.
249
+ *
250
+ * @param subject log subject to perform the level check versus, not currently used
251
+ * @param level logging level to check against in order to return the logger
252
+ * @return the current logger if the current logging level is at or more detailed then the supplied logging level
253
+ */
254
+ AWS_COMMON_API
255
+ struct aws_logger *aws_logger_get_conditional(aws_log_subject_t subject, enum aws_log_level level);
256
+
257
+ /**
258
+ * Cleans up all resources used by the logger; simply invokes the clean_up v-function
259
+ */
260
+ AWS_COMMON_API
261
+ void aws_logger_clean_up(struct aws_logger *logger);
262
+
263
+ /**
264
+ * Sets the current logging level for the logger. Loggers are not require to support this.
265
+ * @param logger logger to set the log level for
266
+ * @param level new log level for the logger
267
+ * @return AWS_OP_SUCCESS if the level was successfully set, AWS_OP_ERR otherwise
268
+ */
269
+ AWS_COMMON_API
270
+ int aws_logger_set_log_level(struct aws_logger *logger, enum aws_log_level level);
271
+
272
+ /**
273
+ * Converts a log level to a c-string constant. Intended primarily to support building log lines that
274
+ * include the level in them, i.e.
275
+ *
276
+ * [ERROR] 10:34:54.642 01-31-19 - Json parse error....
277
+ */
278
+ AWS_COMMON_API
279
+ int aws_log_level_to_string(enum aws_log_level log_level, const char **level_string);
280
+
281
+ /**
282
+ * Converts a c-string constant to a log level value. Uses case-insensitive comparison
283
+ * and simply iterates all possibilities until a match or nothing remains. If no match
284
+ * is found, AWS_OP_ERR is returned.
285
+ */
286
+ AWS_COMMON_API
287
+ int aws_string_to_log_level(const char *level_string, enum aws_log_level *log_level);
288
+
289
+ /**
290
+ * Converts an aws_thread_id_t to a c-string. For portability, aws_thread_id_t
291
+ * must not be printed directly. Intended primarily to support building log
292
+ * lines that include the thread id in them. The parameter `buffer` must
293
+ * point-to a char buffer of length `bufsz == AWS_THREAD_ID_T_REPR_BUFSZ`. The
294
+ * thread id representation is returned in `buffer`.
295
+ */
296
+ AWS_COMMON_API
297
+ int aws_thread_id_t_to_string(aws_thread_id_t thread_id, char *buffer, size_t bufsz);
298
+
299
+ /**
300
+ * Get subject name from log subject.
301
+ */
302
+ AWS_COMMON_API
303
+ const char *aws_log_subject_name(aws_log_subject_t subject);
304
+
305
+ /**
306
+ * Connects log subject strings with log subject integer values
307
+ */
308
+ AWS_COMMON_API
309
+ void aws_register_log_subject_info_list(struct aws_log_subject_info_list *log_subject_list);
310
+
311
+ /**
312
+ * Disconnects log subject strings with log subject integer values
313
+ */
314
+ AWS_COMMON_API
315
+ void aws_unregister_log_subject_info_list(struct aws_log_subject_info_list *log_subject_list);
316
+
317
+ /*
318
+ * Initializes a pipeline logger that is built from the default formatter, a background thread-based channel, and
319
+ * a file writer. The default logger in almost all circumstances.
320
+ */
321
+ AWS_COMMON_API
322
+ int aws_logger_init_standard(
323
+ struct aws_logger *logger,
324
+ struct aws_allocator *allocator,
325
+ struct aws_logger_standard_options *options);
326
+
327
+ /*
328
+ * Initializes a pipeline logger from components that have already been initialized. This is not an ownership transfer.
329
+ * After the pipeline logger is cleaned up, the components will have to manually be cleaned up by the user.
330
+ */
331
+ AWS_COMMON_API
332
+ int aws_logger_init_from_external(
333
+ struct aws_logger *logger,
334
+ struct aws_allocator *allocator,
335
+ struct aws_log_formatter *formatter,
336
+ struct aws_log_channel *channel,
337
+ struct aws_log_writer *writer,
338
+ enum aws_log_level level);
339
+
340
+ /*
341
+ * Pipeline logger vtable for custom configurations
342
+ */
343
+ AWS_COMMON_API
344
+ extern struct aws_logger_vtable g_pipeline_logger_owned_vtable;
345
+
346
+ /*
347
+ * Initializes a logger that does not perform any allocation during logging. Log lines larger than the internal
348
+ * constant are truncated. Formatting matches the standard logger. Used for memory tracing logging.
349
+ * If no file or filename is set in the aws_logger_standard_options, then it will use stderr.
350
+ */
351
+ AWS_COMMON_API
352
+ int aws_logger_init_noalloc(
353
+ struct aws_logger *logger,
354
+ struct aws_allocator *allocator,
355
+ struct aws_logger_standard_options *options);
356
+
357
+ AWS_EXTERN_C_END
358
+ AWS_POP_SANE_WARNING_LEVEL
359
+
360
+ #endif /* AWS_COMMON_LOGGING_H */