Debian Codegraph @

source/module.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include "module.h"
6
7 #include "auth.h"
8 #include "cbor.h"
9 #include "checksums.h"
10 #include "common.h"
11 #include "crypto.h"
12 #include "event_stream.h"
13 #include "http.h"
14 #include "io.h"
15 #include "mqtt5_client.h"
16 #include "mqtt_client.h"
17 #include "mqtt_client_connection.h"
18 #include "mqtt_request_response.h"
19 #include "s3.h"
20 #include "websocket.h"
21
22 #include <aws/auth/auth.h>
23 #include <aws/common/byte_buf.h>
24 #include <aws/common/environment.h>
25 #include <aws/common/system_info.h>
26 #include <aws/event-stream/event_stream.h>
27 #include <aws/http/http.h>
28 #include <aws/io/io.h>
29 #include <aws/io/logging.h>
30 #include <aws/io/tls_channel_handler.h>
31 #include <aws/mqtt/mqtt.h>
32 #include <aws/s3/s3.h>
33
34 #include <aws/common/atomics.h>
35
36 #include <memoryobject.h>
37
38 static struct aws_logger s_logger;
39 static struct aws_atomic_var s_logger_init;
40
41 /* Python logging bridge: direct vtable override */
42 struct s_py_logger_impl {
43 PyObject *callback;
44 struct aws_atomic_var level;
45 };
46
47 static int s_py_logger_log(
48 struct aws_logger *logger,
49 enum aws_log_level log_level,
50 aws_log_subject_t subject,
51 const char *format,
52 ...) {
53
54 struct s_py_logger_impl *impl = logger->p_impl;
55
56 va_list args;
57 va_start(args, format);
58 /* Calculate how much room we'll need to build the full log line.
59 You cannot consume a va_list twice, so we have to copy it. */
60 va_list tmp;
61 va_copy(tmp, args);
62 int len = vsnprintf(NULL, 0, format, tmp);
63 va_end(tmp);
64 if (len < 0) {
65 va_end(args);
66 return AWS_OP_ERR;
67 }
68
69 char *buf = aws_mem_acquire(logger->allocator, (size_t)len + 1);
70 vsnprintf(buf, (size_t)len + 1, format, args);
71 va_end(args);
72
73 const char *subject_name = aws_log_subject_name(subject);
74 if (!subject_name) {
75 subject_name = "";
76 }
77
78 struct aws_string *thread_name_str = NULL;
79 aws_thread_current_name(logger->allocator, &thread_name_str);
80
81 PyGILState_STATE state;
82 if (aws_py_gilstate_ensure(&state)) {
83 aws_string_destroy(thread_name_str);
84 aws_mem_release(logger->allocator, buf);
85 return AWS_OP_ERR;
86 }
87
88 PyObject *py_thread_name;
89
90 if (thread_name_str) {
91 py_thread_name = PyUnicode_FromAwsString(thread_name_str);
92 } else {
93 py_thread_name = Py_None;
94 Py_INCREF(py_thread_name);
95 }
96
97 aws_string_destroy(thread_name_str);
98
99 PyObject *result = PyObject_CallFunction(
100 impl->callback, "(is#isO)", (int)log_level, buf, (Py_ssize_t)len, (int)subject, subject_name, py_thread_name);
101 Py_XDECREF(result);
102 Py_DECREF(py_thread_name);
103 if (PyErr_Occurred()) {
104 PyErr_WriteUnraisable(PyErr_Occurred());
105 PyGILState_Release(state);
106 aws_mem_release(logger->allocator, buf);
107 return aws_py_raise_error();
108 }
109
110 PyGILState_Release(state);
111 aws_mem_release(logger->allocator, buf);
112 return AWS_OP_SUCCESS;
113 }
114
115 static enum aws_log_level s_py_logger_get_log_level(struct aws_logger *logger, aws_log_subject_t subject) {
116 (void)subject;
117 struct s_py_logger_impl *impl = logger->p_impl;
118 return (enum aws_log_level)aws_atomic_load_int(&impl->level);
119 }
120
121 static int s_py_logger_set_log_level(struct aws_logger *logger, enum aws_log_level level) {
122 struct s_py_logger_impl *impl = logger->p_impl;
123 aws_atomic_store_int(&impl->level, (size_t)level);
124 return AWS_OP_SUCCESS;
125 }
126
127 static void s_py_logger_clean_up(struct aws_logger *logger) {
128 struct s_py_logger_impl *impl = logger->p_impl;
129 if (impl) {
130 PyGILState_STATE state;
131 if (!aws_py_gilstate_ensure(&state)) {
132 Py_XDECREF(impl->callback);
133 PyGILState_Release(state);
134 }
135 aws_mem_release(logger->allocator, impl);
136 }
137 }
138
139 static struct aws_logger_vtable s_py_logger_vtable = {
140 .log = s_py_logger_log,
141 .get_log_level = s_py_logger_get_log_level,
142 .set_log_level = s_py_logger_set_log_level,
143 .clean_up = s_py_logger_clean_up,
144 };
145
146 PyObject *aws_py_init_logging(PyObject *self, PyObject *args) {
147 (void)self;
148
149 /* NOTE: We are NOT using aws_py_get_allocator() for logging.
150 * This avoid deadlock during aws_mem_tracer_dump() */
151 struct aws_allocator *allocator = aws_default_allocator();
152
153 int log_level = 0;
154 const char *file_path = NULL;
155 Py_ssize_t file_path_len = 0;
156
157 if (!PyArg_ParseTuple(args, "bs#", &log_level, &file_path, &file_path_len)) {
158 PyErr_SetNone(PyExc_ValueError);
159 return NULL;
160 }
161
162 struct aws_logger_standard_options log_options = {
163 .level = log_level,
164 .file = NULL,
165 .filename = NULL,
166 };
167
168 Py_ssize_t stdout_len = (Py_ssize_t)strlen("stdout");
169
170 Py_ssize_t cmp_len = file_path_len > stdout_len ? stdout_len : file_path_len;
171
172 if (!memcmp("stdout", file_path, (size_t)cmp_len)) {
173 log_options.file = stdout;
174 } else if (!memcmp("stderr", file_path, (size_t)cmp_len)) {
175 log_options.file = stderr;
176 } else {
177 log_options.filename = file_path;
178 }
179
180 /* Atomically claim the init slot (0 → 1). Only one thread can win. */
181 size_t expected = 0;
182 if (!aws_atomic_compare_exchange_int(&s_logger_init, &expected, 1)) {
183 aws_raise_error(AWS_ERROR_INVALID_STATE);
184 return PyErr_Format(PyExc_RuntimeError, "Invalid state: logger cannot be initialized multiple times.");
185 }
186
187 if (aws_logger_init_standard(&s_logger, allocator, &log_options) != AWS_OP_SUCCESS) {
188 aws_atomic_store_int(&s_logger_init, 0); /* rollback on failure */
189 return PyErr_AwsLastError();
190 }
191 aws_logger_set(&s_logger);
192
193 Py_RETURN_NONE;
194 }
195
196 PyObject *aws_py_set_log_level(PyObject *self, PyObject *args) {
197 (void)self;
198
199 if (!aws_atomic_load_int(&s_logger_init)) {
200 aws_raise_error(AWS_ERROR_INVALID_STATE);
201 return PyErr_Format(PyExc_RuntimeError, "Invalid state: logger cannot be initialized multiple times.");
202 }
203
204 int log_level = 0;
205 if (!PyArg_ParseTuple(args, "b", &log_level)) {
206 PyErr_SetNone(PyExc_ValueError);
207 return NULL;
208 }
209
210 if (aws_logger_set_log_level(&s_logger, log_level) != AWS_OP_SUCCESS) {
211 return PyErr_AwsLastError();
212 }
213
214 Py_RETURN_NONE;
215 }
216
217 PyObject *aws_py_init_python_logging(PyObject *self, PyObject *args) {
218 (void)self;
219
220 int log_level;
221 PyObject *py_callback;
222 if (!PyArg_ParseTuple(args, "iO", &log_level, &py_callback)) {
223 return NULL;
224 }
225
226 /* Atomically claim the init slot (0 → 1). Only one thread can win. */
227 size_t expected = 0;
228 if (!aws_atomic_compare_exchange_int(&s_logger_init, &expected, 1)) {
229 aws_raise_error(AWS_ERROR_INVALID_STATE);
230 return PyErr_AwsLastError();
231 }
232
233 if (!PyCallable_Check(py_callback)) {
234 aws_atomic_store_int(&s_logger_init, 0); /* rollback */
235 PyErr_SetString(PyExc_TypeError, "callback must be callable");
236 return NULL;
237 }
238
239 struct aws_allocator *allocator = aws_default_allocator();
240
241 struct s_py_logger_impl *impl = aws_mem_calloc(allocator, 1, sizeof(struct s_py_logger_impl));
242
243 Py_INCREF(py_callback);
244 impl->callback = py_callback;
245 aws_atomic_store_int(&impl->level, (size_t)log_level);
246
247 s_logger.vtable = &s_py_logger_vtable;
248 s_logger.allocator = allocator;
249 s_logger.p_impl = impl;
250
251 aws_logger_set(&s_logger);
252
253 Py_RETURN_NONE;
254 }
255
256 PyObject *aws_py_logger_log(PyObject *self, PyObject *args) {
257 (void)self;
258
259 int log_level;
260 int subject;
261 const char *message;
262 if (!PyArg_ParseTuple(args, "iis", &log_level, &subject, &message)) {
263 return NULL;
264 }
265
266 AWS_LOGF((enum aws_log_level)log_level, subject, "%s", message);
267
268 Py_RETURN_NONE;
269 }
270
271 struct aws_byte_cursor aws_byte_cursor_from_pyunicode(PyObject *str) {
272 Py_ssize_t len;
273 const char *ptr = PyUnicode_AsUTF8AndSize(str, &len);
274 if (ptr) {
275 return aws_byte_cursor_from_array(ptr, (size_t)len);
276 }
277 return aws_byte_cursor_from_array(NULL, 0);
278 }
279
280 struct aws_byte_cursor aws_byte_cursor_from_pybytes(PyObject *py_bytes) {
281 char *ptr;
282 Py_ssize_t len;
283 if (PyBytes_AsStringAndSize(py_bytes, &ptr, &len) == -1) {
284 return aws_byte_cursor_from_array(NULL, 0);
285 }
286
287 return aws_byte_cursor_from_array(ptr, (size_t)len);
288 }
289
290 PyObject *PyUnicode_FromAwsByteCursor(const struct aws_byte_cursor *cursor) {
291 if (cursor->len > PY_SSIZE_T_MAX) {
292 PyErr_SetString(PyExc_OverflowError, "Cursor exceeds PY_SSIZE_T_MAX");
293 return NULL;
294 }
295 return PyUnicode_FromStringAndSize((const char *)cursor->ptr, (Py_ssize_t)cursor->len);
296 }
297
298 PyObject *PyUnicode_FromAwsString(const struct aws_string *aws_str) {
299 if (aws_str->len > PY_SSIZE_T_MAX) {
300 PyErr_SetString(PyExc_OverflowError, "String exceeds PY_SSIZE_T_MAX");
301 return NULL;
302 }
303 return PyUnicode_FromStringAndSize(aws_string_c_str(aws_str), aws_str->len);
304 }
305
306 PyObject *PyBytes_FromAwsByteCursor(const struct aws_byte_cursor *cursor) {
307 if (cursor->len > PY_SSIZE_T_MAX) {
308 PyErr_SetString(PyExc_OverflowError, "Cursor exceeds PY_SSIZE_T_MAX");
309 return NULL;
310 }
311 return PyBytes_FromStringAndSize((const char *)cursor->ptr, (Py_ssize_t)cursor->len);
312 }
313
314 uint32_t PyObject_GetAttrAsUint32(PyObject *o, const char *class_name, const char *attr_name) {
315 uint32_t result = UINT32_MAX;
316
317 PyObject *attr = PyObject_GetAttrString(o, attr_name); /* new reference */
318 if (!attr) {
319 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
320 return result;
321 }
322
323 if (attr == Py_None) {
324 PyErr_Format(PyExc_AttributeError, "'%s.%s' required integral attribute is None", class_name, attr_name);
325 goto done;
326 }
327
328 PyObject_GetAsOptionalUint32(attr, class_name, attr_name, &result);
329
330 done:
331
332 Py_DECREF(attr);
333 return result;
334 }
335
336 uint16_t PyObject_GetAttrAsUint16(PyObject *o, const char *class_name, const char *attr_name) {
337 uint16_t result = UINT16_MAX;
338
339 PyObject *attr = PyObject_GetAttrString(o, attr_name); /* new reference */
340 if (!attr) {
341 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
342 return result;
343 }
344
345 if (attr == Py_None) {
346 PyErr_Format(PyExc_AttributeError, "'%s.%s' required integral attribute is None", class_name, attr_name);
347 goto done;
348 }
349
350 PyObject_GetAsOptionalUint16(attr, class_name, attr_name, &result);
351
352 done:
353
354 Py_DECREF(attr);
355 return result;
356 }
357
358 uint8_t PyObject_GetAttrAsUint8(PyObject *o, const char *class_name, const char *attr_name) {
359 uint8_t result = UINT8_MAX;
360
361 PyObject *attr = PyObject_GetAttrString(o, attr_name); /* new reference */
362 if (!attr) {
363 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
364 return result;
365 }
366
367 if (attr == Py_None) {
368 PyErr_Format(PyExc_AttributeError, "'%s.%s' required integral attribute is None", class_name, attr_name);
369 goto done;
370 }
371
372 PyObject_GetAsOptionalUint8(attr, class_name, attr_name, &result);
373
374 done:
375
376 Py_DECREF(attr);
377 return result;
378 }
379
380 bool PyObject_GetAttrAsBool(PyObject *o, const char *class_name, const char *attr_name) {
381 bool result = false;
382
383 PyObject *attr = PyObject_GetAttrString(o, attr_name); /* new reference */
384 if (!attr) {
385 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
386 return result;
387 }
388
389 if (attr == Py_None) {
390 PyErr_Format(PyExc_AttributeError, "'%s.%s' required boolean attribute is None", class_name, attr_name);
391 goto done;
392 }
393
394 int val = PyObject_IsTrue(attr);
395 if (val == -1) {
396 PyErr_Format(PyExc_TypeError, "Cannot convert %s.%s to bool", class_name, attr_name);
397 goto done;
398 }
399
400 result = val != 0;
401 done:
402 Py_DECREF(attr);
403 return result;
404 }
405
406 int PyObject_GetAttrAsIntEnum(PyObject *o, const char *class_name, const char *attr_name) {
407 int result = -1;
408
409 PyObject *attr = PyObject_GetAttrString(o, attr_name); /* new reference */
410 if (!attr) {
411 PyErr_Format(PyExc_AttributeError, "'%s.%s' attribute not found", class_name, attr_name);
412 return result;
413 }
414
415 if (attr == Py_None) {
416 PyErr_Format(
417 PyExc_AttributeError, "'%s.%s' required integral enumeration attribute is None", class_name, attr_name);
418 goto done;
419 }
420
421 PyObject_GetAsOptionalIntEnum(attr, class_name, attr_name, &result);
422
423 done:
424
425 Py_DECREF(attr);
426 return result;
427 }
428
429 bool *PyObject_GetAsOptionalBool(PyObject *o, const char *class_name, const char *attr_name, bool *stored_bool) {
430 if (o == Py_None) {
431 goto done;
432 }
433
434 int val = PyObject_IsTrue(o);
435 if (val == -1) {
436 PyErr_Format(PyExc_TypeError, "Cannot convert %s.%s to bool", class_name, attr_name);
437 goto done;
438 }
439
440 *stored_bool = (bool)(val != 0);
441 return stored_bool;
442
443 done:
444 return NULL;
445 }
446
447 uint64_t *PyObject_GetAsOptionalUint64(
448 PyObject *o,
449 const char *class_name,
450 const char *attr_name,
451 uint64_t *stored_int) {
452 if (o == Py_None) {
453 goto done;
454 }
455
456 unsigned long long val = PyLong_AsUnsignedLongLong(o);
457 if (PyErr_Occurred()) {
458 PyErr_Format(PyErr_Occurred(), "Cannot convert %s.%s to a C uint64_t", class_name, attr_name);
459 goto done;
460 }
461
462 *stored_int = (uint64_t)val;
463 return stored_int;
464
465 done:
466 return NULL;
467 }
468
469 uint32_t *PyObject_GetAsOptionalUint32(
470 PyObject *o,
471 const char *class_name,
472 const char *attr_name,
473 uint32_t *stored_int) {
474
475 if (o == Py_None) {
476 goto done;
477 }
478
479 /* Using PyLong_AsLongLong() because it will convert floating point numbers (PyLong_AsUnsignedLong() will not).
480 * By using "long long" (not just "long") we can be sure to fit the whole range of 32bit numbers. */
481 long long val = PyLong_AsLongLong(o);
482 if (PyErr_Occurred()) {
483 PyErr_Format(PyErr_Occurred(), "Cannot convert %s.%s to a C uint32_t", class_name, attr_name);
484 goto done;
485 }
486
487 if (val < 0) {
488 PyErr_Format(PyExc_OverflowError, "%s.%s cannot be negative", class_name, attr_name);
489 goto done;
490 }
491
492 if (val > UINT32_MAX) {
493 PyErr_Format(PyExc_OverflowError, "%s.%s too large to convert to C uint32_t", class_name, attr_name);
494 goto done;
495 }
496
497 *stored_int = (uint32_t)val;
498 return stored_int;
499
500 done:
501 return NULL;
502 }
503
504 uint16_t *PyObject_GetAsOptionalUint16(
505 PyObject *o,
506 const char *class_name,
507 const char *attr_name,
508 uint16_t *stored_int) {
509
510 if (o == Py_None) {
511 goto done;
512 }
513
514 long val = PyLong_AsLong(o);
515 if (PyErr_Occurred()) {
516 PyErr_Format(PyErr_Occurred(), "Cannot convert %s.%s to a C uint16_t", class_name, attr_name);
517 goto done;
518 }
519
520 if (val < 0) {
521 PyErr_Format(PyExc_OverflowError, "%s.%s cannot be negative", class_name, attr_name);
522 goto done;
523 }
524
525 if (val > UINT16_MAX) {
526 PyErr_Format(PyExc_OverflowError, "%s.%s too large to convert to C uint16_t", class_name, attr_name);
527 goto done;
528 }
529
530 *stored_int = (uint16_t)val;
531
532 return stored_int;
533
534 done:
535 return NULL;
536 }
537
538 uint8_t *PyObject_GetAsOptionalUint8(PyObject *o, const char *class_name, const char *attr_name, uint8_t *stored_int) {
539
540 if (o == Py_None) {
541 goto done;
542 }
543
544 long val = PyLong_AsLong(o);
545 if (PyErr_Occurred()) {
546 PyErr_Format(PyErr_Occurred(), "Cannot convert %s.%s to a C uint8_t", class_name, attr_name);
547 goto done;
548 }
549
550 if (val < 0) {
551 PyErr_Format(PyExc_OverflowError, "%s.%s cannot be negative", class_name, attr_name);
552 goto done;
553 }
554
555 if (val > UINT8_MAX) {
556 PyErr_Format(PyExc_OverflowError, "%s.%s too large to convert to C uint8_t", class_name, attr_name);
557 goto done;
558 }
559
560 *stored_int = (uint8_t)val;
561
562 return stored_int;
563
564 done:
565 return NULL;
566 }
567
568 int *PyObject_GetAsOptionalIntEnum(PyObject *o, const char *class_name, const char *attr_name, int *stored_enum) {
569 if (o == Py_None) {
570 goto done;
571 }
572
573 if (!PyLong_Check(o)) {
574 PyErr_Format(PyExc_TypeError, "%s.%s is not a valid enum", class_name, attr_name);
575 goto done;
576 }
577
578 *stored_enum = PyLong_AsLong(o);
579 return stored_enum;
580 done:
581 return NULL;
582 }
583
584 void PyErr_SetAwsLastError(void) {
585 PyErr_AwsLastError();
586 }
587
588 PyObject *PyErr_AwsLastError(void) {
589 int err = aws_last_error();
590 const char *name = aws_error_name(err);
591 const char *msg = aws_error_str(err);
592 return PyErr_Format(PyExc_RuntimeError, "%d (%s): %s", err, name, msg);
593 }
594
595 #define AWS_DEFINE_ERROR_INFO_CRT(CODE, STR) \
596 [(CODE) - AWS_ERROR_ENUM_BEGIN_RANGE(AWS_CRT_PYTHON_PACKAGE_ID)] = \
597 AWS_DEFINE_ERROR_INFO(CODE, STR, "aws-crt-python")
598
599 /* clang-format off */
600 static struct aws_error_info s_errors[] = {
601 AWS_DEFINE_ERROR_INFO_CRT(
602 AWS_ERROR_CRT_CALLBACK_EXCEPTION,
603 "Callback raised an exception."),
604 };
605 /* clang-format on */
606
607 static struct aws_error_info_list s_error_list = {
608 .error_list = s_errors,
609 .count = AWS_ARRAY_SIZE(s_errors),
610 };
611
612 /* Mappings between Python built-in exception types and AWS_ERROR_ codes
613 * Stored in hashtables as `PyObject*` of Python exception type, and `int` of AWS_ERROR_ enum (cast to void*) */
614 static struct aws_hash_table s_py_to_aws_error_map;
615 static struct aws_hash_table s_aws_to_py_error_map;
616
617 static void s_error_map_init(void) {
618 struct error_pair {
619 PyObject *py_exception_type;
620 int aws_error_code;
621 };
622
623 /* If the same key is listed multiple times, later entries overwrite earlier entries
624 * Ex: Both TypeError and ValueError map to INVALID_ARG, but INVALID_ARG only maps to ValueError. */
625 struct error_pair s_error_array[] = {
626 {PyExc_IndexError, AWS_ERROR_INVALID_INDEX},
627 {PyExc_MemoryError, AWS_ERROR_OOM},
628 {PyExc_NotImplementedError, AWS_ERROR_UNIMPLEMENTED},
629 {PyExc_OverflowError, AWS_ERROR_OVERFLOW_DETECTED},
630 {PyExc_TypeError, AWS_ERROR_INVALID_ARGUMENT},
631 {PyExc_ValueError, AWS_ERROR_INVALID_ARGUMENT},
632 {PyExc_FileNotFoundError, AWS_ERROR_FILE_INVALID_PATH},
633 {PyExc_BlockingIOError, AWS_IO_READ_WOULD_BLOCK},
634 {PyExc_BrokenPipeError, AWS_IO_BROKEN_PIPE},
635 };
636
637 if (aws_hash_table_init(
638 &s_py_to_aws_error_map,
639 aws_default_allocator(), /* non-tracing allocator so this doesn't show up in leak dumps */
640 AWS_ARRAY_SIZE(s_error_array),
641 aws_hash_ptr,
642 aws_ptr_eq,
643 NULL /*destroy_key_fn*/,
644 NULL /*destroy_value_fn*/)) {
645 AWS_FATAL_ASSERT(0);
646 }
647
648 if (aws_hash_table_init(
649 &s_aws_to_py_error_map,
650 aws_default_allocator(), /* non-tracing allocator so this doesn't show up in leak dumps */
651 AWS_ARRAY_SIZE(s_error_array),
652 aws_hash_ptr,
653 aws_ptr_eq,
654 NULL /*destroy_key_fn*/,
655 NULL /*destroy_value_fn*/)) {
656 AWS_FATAL_ASSERT(0);
657 }
658
659 for (size_t i = 0; i < AWS_ARRAY_SIZE(s_error_array); ++i) {
660 void *py_exc = s_error_array[i].py_exception_type;
661 void *aws_err = (void *)(size_t)s_error_array[i].aws_error_code;
662 if (aws_hash_table_put(&s_py_to_aws_error_map, py_exc, aws_err, NULL)) {
663 AWS_FATAL_ASSERT(0);
664 }
665 if (aws_hash_table_put(&s_aws_to_py_error_map, aws_err, py_exc, NULL)) {
666 AWS_FATAL_ASSERT(0);
667 }
668 }
669 }
670
671 int aws_py_translate_py_error(void) {
672 AWS_ASSERT(PyErr_Occurred() != NULL);
673 AWS_ASSERT(PyGILState_Check() == 1);
674
675 int aws_error_code = AWS_ERROR_UNKNOWN;
676
677 struct aws_hash_element *found;
678 aws_hash_table_find(&s_py_to_aws_error_map, PyErr_Occurred(), &found);
679 if (found) {
680 aws_error_code = (int)(size_t)found->value;
681 }
682
683 /* Print standard traceback to sys.stderr and clear the error indicator. */
684 /* Handles the exception in C, do not set the last vars for python. */
685 PyErr_PrintEx(0 /*set_sys_last_vars*/);
686 fprintf(stderr, "Treating Python exception as error %d(%s)\n", aws_error_code, aws_error_name(aws_error_code));
687
688 return aws_error_code;
689 }
690
691 int aws_py_raise_error(void) {
692
693 int aws_error_code = aws_py_translate_py_error();
694 return aws_raise_error(aws_error_code);
695 }
696
697 PyObject *aws_py_get_corresponding_builtin_exception(PyObject *self, PyObject *args) {
698 (void)self;
699 int error_code;
700 if (!PyArg_ParseTuple(args, "i", &error_code)) {
701 return NULL;
702 }
703
704 struct aws_hash_element *found;
705 aws_hash_table_find(&s_aws_to_py_error_map, (void *)(size_t)error_code, &found);
706 if (!found) {
707 Py_RETURN_NONE;
708 }
709
710 PyObject *py_exception_type = found->value;
711 Py_INCREF(py_exception_type);
712 return py_exception_type;
713 }
714
715 PyObject *aws_py_get_error_name(PyObject *self, PyObject *args) {
716 (void)self;
717 int error_code;
718 if (!PyArg_ParseTuple(args, "i", &error_code)) {
719 return NULL;
720 }
721
722 const char *name = aws_error_name(error_code);
723 return PyUnicode_FromString(name);
724 }
725
726 PyObject *aws_py_get_error_message(PyObject *self, PyObject *args) {
727 (void)self;
728 int error_code;
729 if (!PyArg_ParseTuple(args, "i", &error_code)) {
730 return NULL;
731 }
732
733 const char *name = aws_error_str(error_code);
734 return PyUnicode_FromString(name);
735 }
736
737 PyObject *aws_py_memory_view_from_byte_buffer(struct aws_byte_buf *buf) {
738 size_t available = buf->capacity - buf->len;
739 if (available > PY_SSIZE_T_MAX) {
740 PyErr_SetString(PyExc_OverflowError, "Buffer exceeds PY_SSIZE_T_MAX");
741 return NULL;
742 }
743
744 Py_ssize_t mem_size = available;
745 char *mem_start = (char *)(buf->buffer + buf->len);
746 return PyMemoryView_FromMemory(mem_start, mem_size, PyBUF_WRITE);
747 }
748
749 PyObject *aws_py_weakref_get_ref(PyObject *ref) {
750 /* If Python >= 3.13 */
751 #if PY_VERSION_HEX >= 0x030D0000
752 /* Use PyWeakref_GetRef() (new in Python 3.13), which gets you:
753 * a new strong reference,
754 * or NULL because ref is dead,
755 * or -1 because you called it wrong */
756 PyObject *obj = NULL;
757 if (PyWeakref_GetRef(ref, &obj) == -1) {
758 PyErr_WriteUnraisable(PyErr_Occurred());
759 AWS_ASSERT(0 && "expected a weakref");
760 }
761 return obj;
762
763 #else
764 /* Use PyWeakref_GetObject() (deprecated as of Python 3.13), which gets you:
765 * a borrowed reference,
766 * or Py_None because ref is dead,
767 * or NULL because you called it wrong */
768 PyObject *obj = PyWeakref_GetObject(ref); /* borrowed reference */
769 if (obj == NULL) {
770 PyErr_WriteUnraisable(PyErr_Occurred());
771 AWS_ASSERT(0 && "expected a weakref");
772 } else if (obj == Py_None) {
773 obj = NULL;
774 } else {
775 /* Be like PyWeakref_GetRef() and make it new strong reference */
776 Py_INCREF(obj);
777 }
778 return obj;
779 #endif
780 }
781
782 int aws_py_gilstate_ensure(PyGILState_STATE *out_state) {
783 /* If Python >= 3.13 */
784 #if PY_VERSION_HEX >= 0x030D0000
785 // Py_IsFinalizing is part of the Stable ABI since version 3.13.
786 if (AWS_LIKELY(!Py_IsFinalizing())) {
787 #else
788 if (AWS_LIKELY(Py_IsInitialized())) {
789 #endif
790 *out_state = PyGILState_Ensure();
791 return AWS_OP_SUCCESS;
792 }
793
794 return aws_raise_error(AWS_ERROR_INVALID_STATE);
795 }
796
797 void *aws_py_get_binding(PyObject *obj, const char *capsule_name, const char *class_name) {
798 if (!obj || obj == Py_None) {
799 return PyErr_Format(PyExc_TypeError, "Expected '%s', received 'NoneType'", class_name);
800 }
801
802 PyObject *py_binding = PyObject_GetAttrString(obj, "_binding"); /* new reference */
803 if (!py_binding) {
804 return PyErr_Format(PyExc_TypeError, "Expected valid '%s' (no '_binding' attribute)", class_name);
805 }
806
807 void *binding = NULL;
808 if (!PyCapsule_CheckExact(py_binding)) {
809 PyErr_Format(PyExc_TypeError, "Expected valid '%s' ('_binding' attribute is not a capsule)", class_name);
810 goto done;
811 }
812
813 binding = PyCapsule_GetPointer(py_binding, capsule_name);
814 if (!binding) {
815 PyErr_Format(
816 PyExc_TypeError,
817 "Expected valid '%s' ('_binding' attribute does not contain '%s')",
818 class_name,
819 capsule_name);
820 goto done;
821 }
822
823 done:
824 Py_DECREF(py_binding);
825 return binding;
826 }
827
828 /*******************************************************************************
829 * Allocator
830 ******************************************************************************/
831 static struct aws_allocator *s_allocator = NULL;
832
833 struct aws_allocator *aws_py_get_allocator(void) {
834 return s_allocator;
835 }
836
837 AWS_STATIC_STRING_FROM_LITERAL(s_mem_tracing_env_var, "AWS_CRT_MEMORY_TRACING");
838
839 static void s_init_allocator(void) {
840 /* use non-tracing allocator by default */
841 s_allocator = aws_default_allocator();
842
843 /* read environment variable. must be number correlating to trace mode */
844 struct aws_string *value_str = NULL;
845 aws_get_environment_value(aws_default_allocator(), s_mem_tracing_env_var, &value_str);
846 if (value_str == NULL) {
847 return;
848 }
849
850 int level = atoi(aws_string_c_str(value_str));
851 aws_string_destroy(value_str);
852 value_str = NULL;
853
854 if (level <= AWS_MEMTRACE_NONE || level > AWS_MEMTRACE_STACKS) {
855 return;
856 }
857
858 s_allocator = aws_mem_tracer_new(aws_default_allocator(), NULL, level, 16);
859 }
860
861 PyObject *aws_py_native_memory_usage(PyObject *self, PyObject *args) {
862 (void)self;
863 (void)args;
864
865 size_t bytes = 0;
866 struct aws_allocator *alloc = aws_py_get_allocator();
867 if (alloc != aws_default_allocator()) {
868 bytes = aws_mem_tracer_bytes(alloc);
869 }
870
871 return PyLong_FromSize_t(bytes);
872 }
873
874 PyObject *aws_py_native_memory_dump(PyObject *self, PyObject *args) {
875 (void)self;
876 (void)args;
877
878 struct aws_allocator *alloc = aws_py_get_allocator();
879 if (alloc != aws_default_allocator()) {
880 aws_mem_tracer_dump(alloc);
881 }
882
883 Py_RETURN_NONE;
884 }
885
886 /*******************************************************************************
887 * Crash handler
888 ******************************************************************************/
889 #if defined(_WIN32)
890 # include <windows.h>
891 static LONG WINAPI s_print_stack_trace(struct _EXCEPTION_POINTERS *exception_pointers) {
892 aws_backtrace_print(stderr, exception_pointers);
893 return EXCEPTION_EXECUTE_HANDLER;
894 }
895 #elif defined(AWS_HAVE_EXECINFO)
896 # include <signal.h>
897 static void s_print_stack_trace(int sig, siginfo_t *sig_info, void *user_data) {
898 (void)sig;
899 (void)sig_info;
900 (void)user_data;
901 aws_backtrace_print(stderr, sig_info);
902 exit(-1);
903 }
904 #endif
905
906 static void s_install_crash_handler(void) {
907 #if defined(_WIN32)
908 SetUnhandledExceptionFilter(s_print_stack_trace);
909 #elif defined(AWS_HAVE_EXECINFO)
910 struct sigaction sa;
911 memset(&sa, 0, sizeof(struct sigaction));
912 sigemptyset(&sa.sa_mask);
913
914 sa.sa_flags = SA_NODEFER;
915 sa.sa_sigaction = s_print_stack_trace;
916
917 sigaction(SIGSEGV, &sa, NULL);
918 sigaction(SIGABRT, &sa, NULL);
919 sigaction(SIGILL, &sa, NULL);
920 sigaction(SIGBUS, &sa, NULL);
921 #endif
922 }
923
924 /*******************************************************************************
925 * Definitions
926 ******************************************************************************/
927
928 #define AWS_PY_METHOD_DEF(NAME, FLAGS) {#NAME, aws_py_##NAME, (FLAGS), NULL}
929
930 static PyMethodDef s_module_methods[] = {
931 /* Common */
932 AWS_PY_METHOD_DEF(get_error_name, METH_VARARGS),
933 AWS_PY_METHOD_DEF(get_error_message, METH_VARARGS),
934 AWS_PY_METHOD_DEF(get_corresponding_builtin_exception, METH_VARARGS),
935 AWS_PY_METHOD_DEF(get_cpu_group_count, METH_VARARGS),
936 AWS_PY_METHOD_DEF(get_cpu_count_for_group, METH_VARARGS),
937 AWS_PY_METHOD_DEF(native_memory_usage, METH_NOARGS),
938 AWS_PY_METHOD_DEF(native_memory_dump, METH_NOARGS),
939 AWS_PY_METHOD_DEF(thread_join_all_managed, METH_VARARGS),
940
941 /* IO */
942 AWS_PY_METHOD_DEF(is_alpn_available, METH_NOARGS),
943 AWS_PY_METHOD_DEF(is_tls_cipher_supported, METH_VARARGS),
944 AWS_PY_METHOD_DEF(event_loop_group_new, METH_VARARGS),
945 AWS_PY_METHOD_DEF(host_resolver_new_default, METH_VARARGS),
946 AWS_PY_METHOD_DEF(client_bootstrap_new, METH_VARARGS),
947 AWS_PY_METHOD_DEF(client_tls_ctx_new, METH_VARARGS),
948 AWS_PY_METHOD_DEF(tls_connections_options_new_from_ctx, METH_VARARGS),
949 AWS_PY_METHOD_DEF(tls_connection_options_set_alpn_list, METH_VARARGS),
950 AWS_PY_METHOD_DEF(tls_connection_options_set_server_name, METH_VARARGS),
951 AWS_PY_METHOD_DEF(init_logging, METH_VARARGS),
952 AWS_PY_METHOD_DEF(set_log_level, METH_VARARGS),
953 AWS_PY_METHOD_DEF(init_python_logging, METH_VARARGS),
954 AWS_PY_METHOD_DEF(logger_log, METH_VARARGS),
955 AWS_PY_METHOD_DEF(input_stream_new, METH_VARARGS),
956 AWS_PY_METHOD_DEF(pkcs11_lib_new, METH_VARARGS),
957
958 /* MQTT Client */
959 AWS_PY_METHOD_DEF(mqtt_client_new, METH_VARARGS),
960
961 /* MQTT Client Connection */
962 AWS_PY_METHOD_DEF(mqtt_client_connection_new, METH_VARARGS),
963 AWS_PY_METHOD_DEF(mqtt_client_connection_connect, METH_VARARGS),
964 AWS_PY_METHOD_DEF(mqtt_client_connection_reconnect, METH_VARARGS),
965 AWS_PY_METHOD_DEF(mqtt_client_connection_publish, METH_VARARGS),
966 AWS_PY_METHOD_DEF(mqtt_client_connection_subscribe, METH_VARARGS),
967 AWS_PY_METHOD_DEF(mqtt_client_connection_on_message, METH_VARARGS),
968 AWS_PY_METHOD_DEF(mqtt_client_connection_resubscribe_existing_topics, METH_VARARGS),
969 AWS_PY_METHOD_DEF(mqtt_client_connection_unsubscribe, METH_VARARGS),
970 AWS_PY_METHOD_DEF(mqtt_client_connection_disconnect, METH_VARARGS),
971 AWS_PY_METHOD_DEF(mqtt_ws_handshake_transform_complete, METH_VARARGS),
972 AWS_PY_METHOD_DEF(mqtt_client_connection_get_stats, METH_VARARGS),
973
974 /* MQTT5 Client */
975 AWS_PY_METHOD_DEF(mqtt5_client_new, METH_VARARGS),
976 AWS_PY_METHOD_DEF(mqtt5_client_start, METH_VARARGS),
977 AWS_PY_METHOD_DEF(mqtt5_client_stop, METH_VARARGS),
978 AWS_PY_METHOD_DEF(mqtt5_client_publish, METH_VARARGS),
979 AWS_PY_METHOD_DEF(mqtt5_client_subscribe, METH_VARARGS),
980 AWS_PY_METHOD_DEF(mqtt5_client_unsubscribe, METH_VARARGS),
981 AWS_PY_METHOD_DEF(mqtt5_client_get_stats, METH_VARARGS),
982 AWS_PY_METHOD_DEF(mqtt5_client_invoke_publish_acknowledgement, METH_VARARGS),
983 AWS_PY_METHOD_DEF(mqtt5_ws_handshake_transform_complete, METH_VARARGS),
984
985 /* MQTT Request Response Client */
986 AWS_PY_METHOD_DEF(mqtt_request_response_client_new_from_5, METH_VARARGS),
987 AWS_PY_METHOD_DEF(mqtt_request_response_client_new_from_311, METH_VARARGS),
988 AWS_PY_METHOD_DEF(mqtt_request_response_client_make_request, METH_VARARGS),
989 AWS_PY_METHOD_DEF(mqtt_request_response_client_create_stream, METH_VARARGS),
990 AWS_PY_METHOD_DEF(mqtt_streaming_operation_open, METH_VARARGS),
991
992 /* Cryptographic primitives */
993 AWS_PY_METHOD_DEF(md5_new, METH_NOARGS),
994 AWS_PY_METHOD_DEF(sha256_new, METH_NOARGS),
995 AWS_PY_METHOD_DEF(sha1_new, METH_NOARGS),
996 AWS_PY_METHOD_DEF(hash_update, METH_VARARGS),
997 AWS_PY_METHOD_DEF(hash_digest, METH_VARARGS),
998 AWS_PY_METHOD_DEF(sha256_hmac_new, METH_VARARGS),
999 AWS_PY_METHOD_DEF(hash_update, METH_VARARGS),
1000 AWS_PY_METHOD_DEF(hash_digest, METH_VARARGS),
1001
1002 /* RSA crypto primitives */
1003 AWS_PY_METHOD_DEF(rsa_private_key_from_pem_data, METH_VARARGS),
1004 AWS_PY_METHOD_DEF(rsa_public_key_from_pem_data, METH_VARARGS),
1005 AWS_PY_METHOD_DEF(rsa_private_key_from_der_data, METH_VARARGS),
1006 AWS_PY_METHOD_DEF(rsa_public_key_from_der_data, METH_VARARGS),
1007 AWS_PY_METHOD_DEF(rsa_encrypt, METH_VARARGS),
1008 AWS_PY_METHOD_DEF(rsa_decrypt, METH_VARARGS),
1009 AWS_PY_METHOD_DEF(rsa_sign, METH_VARARGS),
1010 AWS_PY_METHOD_DEF(rsa_verify, METH_VARARGS),
1011
1012 /* ED25519 crypto primitives */
1013 AWS_PY_METHOD_DEF(ed25519_new_generate, METH_NOARGS),
1014 AWS_PY_METHOD_DEF(ed25519_export_public_key, METH_VARARGS),
1015 AWS_PY_METHOD_DEF(ed25519_export_private_key, METH_VARARGS),
1016
1017 /* EC crypto primitives */
1018 AWS_PY_METHOD_DEF(ec_new_generate, METH_VARARGS),
1019 AWS_PY_METHOD_DEF(ec_key_from_der_data, METH_VARARGS),
1020 AWS_PY_METHOD_DEF(ec_export_key, METH_VARARGS),
1021 AWS_PY_METHOD_DEF(ec_sign, METH_VARARGS),
1022 AWS_PY_METHOD_DEF(ec_verify, METH_VARARGS),
1023 AWS_PY_METHOD_DEF(ec_encode_signature, METH_VARARGS),
1024 AWS_PY_METHOD_DEF(ec_decode_signature, METH_VARARGS),
1025 AWS_PY_METHOD_DEF(ec_decode_signature_to_padded_pair, METH_VARARGS),
1026 AWS_PY_METHOD_DEF(ec_get_public_coords, METH_VARARGS),
1027
1028 /* Checksum primitives */
1029 AWS_PY_METHOD_DEF(checksums_crc32, METH_VARARGS),
1030 AWS_PY_METHOD_DEF(checksums_crc32c, METH_VARARGS),
1031 AWS_PY_METHOD_DEF(checksums_crc64nvme, METH_VARARGS),
1032 AWS_PY_METHOD_DEF(checksums_crc32_combine, METH_VARARGS),
1033 AWS_PY_METHOD_DEF(checksums_crc32c_combine, METH_VARARGS),
1034 AWS_PY_METHOD_DEF(checksums_crc64nvme_combine, METH_VARARGS),
1035
1036 /* XXHash Checksum primitives */
1037 AWS_PY_METHOD_DEF(xxhash64_new, METH_VARARGS),
1038 AWS_PY_METHOD_DEF(xxhash3_64_new, METH_VARARGS),
1039 AWS_PY_METHOD_DEF(xxhash3_128_new, METH_VARARGS),
1040 AWS_PY_METHOD_DEF(xxhash64_compute, METH_VARARGS),
1041 AWS_PY_METHOD_DEF(xxhash3_64_compute, METH_VARARGS),
1042 AWS_PY_METHOD_DEF(xxhash3_128_compute, METH_VARARGS),
1043 AWS_PY_METHOD_DEF(xxhash_update, METH_VARARGS),
1044 AWS_PY_METHOD_DEF(xxhash_finalize, METH_VARARGS),
1045
1046 /* HTTP */
1047 AWS_PY_METHOD_DEF(http_connection_close, METH_VARARGS),
1048 AWS_PY_METHOD_DEF(http_connection_is_open, METH_VARARGS),
1049 AWS_PY_METHOD_DEF(http2_connection_update_window, METH_VARARGS),
1050 AWS_PY_METHOD_DEF(http_stream_update_window, METH_VARARGS),
1051 AWS_PY_METHOD_DEF(http_client_connection_new, METH_VARARGS),
1052 AWS_PY_METHOD_DEF(http_client_stream_new, METH_VARARGS),
1053 AWS_PY_METHOD_DEF(http_client_stream_activate, METH_VARARGS),
1054 AWS_PY_METHOD_DEF(http2_client_stream_write_data, METH_VARARGS),
1055 AWS_PY_METHOD_DEF(http_message_new_request, METH_VARARGS),
1056 AWS_PY_METHOD_DEF(http_message_get_request_method, METH_VARARGS),
1057 AWS_PY_METHOD_DEF(http_message_set_request_method, METH_VARARGS),
1058 AWS_PY_METHOD_DEF(http_message_get_request_path, METH_VARARGS),
1059 AWS_PY_METHOD_DEF(http_message_set_request_path, METH_VARARGS),
1060 AWS_PY_METHOD_DEF(http_message_set_body_stream, METH_VARARGS),
1061 AWS_PY_METHOD_DEF(http_headers_new, METH_VARARGS),
1062 AWS_PY_METHOD_DEF(http_headers_add, METH_VARARGS),
1063 AWS_PY_METHOD_DEF(http_headers_add_pairs, METH_VARARGS),
1064 AWS_PY_METHOD_DEF(http_headers_set, METH_VARARGS),
1065 AWS_PY_METHOD_DEF(http_headers_get, METH_VARARGS),
1066 AWS_PY_METHOD_DEF(http_headers_get_index, METH_VARARGS),
1067 AWS_PY_METHOD_DEF(http_headers_count, METH_VARARGS),
1068 AWS_PY_METHOD_DEF(http_headers_remove, METH_VARARGS),
1069 AWS_PY_METHOD_DEF(http_headers_remove_value, METH_VARARGS),
1070 AWS_PY_METHOD_DEF(http_headers_clear, METH_VARARGS),
1071
1072 /* Auth */
1073 AWS_PY_METHOD_DEF(credentials_new, METH_VARARGS),
1074 AWS_PY_METHOD_DEF(credentials_access_key_id, METH_VARARGS),
1075 AWS_PY_METHOD_DEF(credentials_secret_access_key, METH_VARARGS),
1076 AWS_PY_METHOD_DEF(credentials_session_token, METH_VARARGS),
1077 AWS_PY_METHOD_DEF(credentials_expiration_timestamp_seconds, METH_VARARGS),
1078 AWS_PY_METHOD_DEF(credentials_provider_get_credentials, METH_VARARGS),
1079 AWS_PY_METHOD_DEF(credentials_provider_new_chain_default, METH_VARARGS),
1080 AWS_PY_METHOD_DEF(credentials_provider_new_static, METH_VARARGS),
1081 AWS_PY_METHOD_DEF(credentials_provider_new_profile, METH_VARARGS),
1082 AWS_PY_METHOD_DEF(credentials_provider_new_process, METH_VARARGS),
1083 AWS_PY_METHOD_DEF(credentials_provider_new_environment, METH_VARARGS),
1084 AWS_PY_METHOD_DEF(credentials_provider_new_chain, METH_VARARGS),
1085 AWS_PY_METHOD_DEF(credentials_provider_new_delegate, METH_VARARGS),
1086 AWS_PY_METHOD_DEF(credentials_provider_new_cognito, METH_VARARGS),
1087 AWS_PY_METHOD_DEF(credentials_provider_new_x509, METH_VARARGS),
1088 AWS_PY_METHOD_DEF(signing_config_new, METH_VARARGS),
1089 AWS_PY_METHOD_DEF(signing_config_get_algorithm, METH_VARARGS),
1090 AWS_PY_METHOD_DEF(signing_config_get_signature_type, METH_VARARGS),
1091 AWS_PY_METHOD_DEF(signing_config_get_credentials_provider, METH_VARARGS),
1092 AWS_PY_METHOD_DEF(signing_config_get_region, METH_VARARGS),
1093 AWS_PY_METHOD_DEF(signing_config_get_service, METH_VARARGS),
1094 AWS_PY_METHOD_DEF(signing_config_get_date, METH_VARARGS),
1095 AWS_PY_METHOD_DEF(signing_config_get_use_double_uri_encode, METH_VARARGS),
1096 AWS_PY_METHOD_DEF(signing_config_get_should_normalize_uri_path, METH_VARARGS),
1097 AWS_PY_METHOD_DEF(signing_config_get_signed_body_value, METH_VARARGS),
1098 AWS_PY_METHOD_DEF(signing_config_get_signed_body_header_type, METH_VARARGS),
1099 AWS_PY_METHOD_DEF(signing_config_get_expiration_in_seconds, METH_VARARGS),
1100 AWS_PY_METHOD_DEF(signing_config_get_omit_session_token, METH_VARARGS),
1101 AWS_PY_METHOD_DEF(sign_request_aws, METH_VARARGS),
1102
1103 /* Event Stream */
1104 AWS_PY_METHOD_DEF(event_stream_rpc_client_connection_connect, METH_VARARGS),
1105 AWS_PY_METHOD_DEF(event_stream_rpc_client_connection_close, METH_VARARGS),
1106 AWS_PY_METHOD_DEF(event_stream_rpc_client_connection_is_open, METH_VARARGS),
1107 AWS_PY_METHOD_DEF(event_stream_rpc_client_connection_send_protocol_message, METH_VARARGS),
1108 AWS_PY_METHOD_DEF(event_stream_rpc_client_connection_new_stream, METH_VARARGS),
1109 AWS_PY_METHOD_DEF(event_stream_rpc_client_continuation_activate, METH_VARARGS),
1110 AWS_PY_METHOD_DEF(event_stream_rpc_client_continuation_send_message, METH_VARARGS),
1111 AWS_PY_METHOD_DEF(event_stream_rpc_client_continuation_is_closed, METH_VARARGS),
1112
1113 /* S3 */
1114 AWS_PY_METHOD_DEF(s3_client_new, METH_VARARGS),
1115 AWS_PY_METHOD_DEF(s3_client_make_meta_request, METH_VARARGS),
1116 AWS_PY_METHOD_DEF(s3_meta_request_cancel, METH_VARARGS),
1117 AWS_PY_METHOD_DEF(s3_get_ec2_instance_type, METH_NOARGS),
1118 AWS_PY_METHOD_DEF(s3_is_crt_s3_optimized_for_system, METH_NOARGS),
1119 AWS_PY_METHOD_DEF(s3_get_recommended_throughput_target_gbps, METH_NOARGS),
1120 AWS_PY_METHOD_DEF(s3_get_optimized_platforms, METH_NOARGS),
1121 AWS_PY_METHOD_DEF(s3_cross_process_lock_new, METH_VARARGS),
1122 AWS_PY_METHOD_DEF(s3_cross_process_lock_acquire, METH_VARARGS),
1123 AWS_PY_METHOD_DEF(s3_cross_process_lock_release, METH_VARARGS),
1124
1125 /* WebSocket */
1126 AWS_PY_METHOD_DEF(websocket_client_connect, METH_VARARGS),
1127 AWS_PY_METHOD_DEF(websocket_close, METH_VARARGS),
1128 AWS_PY_METHOD_DEF(websocket_send_frame, METH_VARARGS),
1129 AWS_PY_METHOD_DEF(websocket_increment_read_window, METH_VARARGS),
1130 AWS_PY_METHOD_DEF(websocket_create_handshake_request, METH_VARARGS),
1131
1132 /* CBOR Encode */
1133 AWS_PY_METHOD_DEF(cbor_encoder_new, METH_VARARGS),
1134 AWS_PY_METHOD_DEF(cbor_encoder_get_encoded_data, METH_VARARGS),
1135 AWS_PY_METHOD_DEF(cbor_encoder_write_uint, METH_VARARGS),
1136 AWS_PY_METHOD_DEF(cbor_encoder_write_negint, METH_VARARGS),
1137 AWS_PY_METHOD_DEF(cbor_encoder_write_float, METH_VARARGS),
1138 AWS_PY_METHOD_DEF(cbor_encoder_write_bytes, METH_VARARGS),
1139 AWS_PY_METHOD_DEF(cbor_encoder_write_text, METH_VARARGS),
1140 AWS_PY_METHOD_DEF(cbor_encoder_write_array_start, METH_VARARGS),
1141 AWS_PY_METHOD_DEF(cbor_encoder_write_map_start, METH_VARARGS),
1142 AWS_PY_METHOD_DEF(cbor_encoder_write_tag, METH_VARARGS),
1143 AWS_PY_METHOD_DEF(cbor_encoder_write_bool, METH_VARARGS),
1144 AWS_PY_METHOD_DEF(cbor_encoder_write_simple_types, METH_VARARGS),
1145 AWS_PY_METHOD_DEF(cbor_encoder_write_py_list, METH_VARARGS),
1146 AWS_PY_METHOD_DEF(cbor_encoder_write_py_dict, METH_VARARGS),
1147 AWS_PY_METHOD_DEF(cbor_encoder_write_data_item, METH_VARARGS),
1148
1149 /* CBOR Decode */
1150 AWS_PY_METHOD_DEF(cbor_decoder_new, METH_VARARGS),
1151 AWS_PY_METHOD_DEF(cbor_decoder_peek_type, METH_VARARGS),
1152 AWS_PY_METHOD_DEF(cbor_decoder_get_remaining_bytes_len, METH_VARARGS),
1153 AWS_PY_METHOD_DEF(cbor_decoder_consume_next_element, METH_VARARGS),
1154 AWS_PY_METHOD_DEF(cbor_decoder_consume_next_data_item, METH_VARARGS),
1155 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_unsigned_int, METH_VARARGS),
1156 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_negative_int, METH_VARARGS),
1157 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_float, METH_VARARGS),
1158 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_boolean, METH_VARARGS),
1159 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_bytes, METH_VARARGS),
1160 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_text, METH_VARARGS),
1161 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_array_start, METH_VARARGS),
1162 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_map_start, METH_VARARGS),
1163 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_tag, METH_VARARGS),
1164 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_py_list, METH_VARARGS),
1165 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_py_dict, METH_VARARGS),
1166 AWS_PY_METHOD_DEF(cbor_decoder_pop_next_data_item, METH_VARARGS),
1167 {NULL, NULL, 0, NULL},
1168 };
1169
1170 static const char s_module_name[] = "_awscrt";
1171 PyDoc_STRVAR(s_module_doc, "C extension for binding AWS implementations of MQTT, HTTP, and friends");
1172 AWS_STATIC_STRING_FROM_LITERAL(s_crash_handler_env_var, "AWS_CRT_CRASH_HANDLER");
1173
1174 /*******************************************************************************
1175 * Module Init
1176 ******************************************************************************/
1177
1178 PyMODINIT_FUNC PyInit__awscrt(void) {
1179 static struct PyModuleDef s_module_def = {
1180 PyModuleDef_HEAD_INIT,
1181 s_module_name,
1182 s_module_doc,
1183 -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
1184 s_module_methods,
1185 NULL, /* slots for multi-phase initialization */
1186 NULL, /* traversal fn to call during GC traversal */
1187 NULL, /* clear fn to call during GC clear */
1188 NULL, /* fn to call during deallocation of the module object */
1189 };
1190
1191 PyObject *m = PyModule_Create(&s_module_def);
1192 if (!m) {
1193 return NULL;
1194 }
1195
1196 #ifdef Py_GIL_DISABLED
1197 PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
1198 #endif
1199
1200 s_init_allocator();
1201
1202 /* Don't report this memory when dumping possible leaks. */
1203 struct aws_allocator *nontracing_allocator = aws_default_allocator();
1204
1205 struct aws_string *crash_handler_env = NULL;
1206 aws_get_environment_value(nontracing_allocator, s_crash_handler_env_var, &crash_handler_env);
1207 if (aws_string_eq_c_str(crash_handler_env, "1")) {
1208 s_install_crash_handler();
1209 }
1210 aws_string_destroy(crash_handler_env);
1211
1212 aws_http_library_init(nontracing_allocator);
1213 aws_auth_library_init(nontracing_allocator);
1214 aws_mqtt_library_init(nontracing_allocator);
1215 aws_event_stream_library_init(nontracing_allocator);
1216 aws_s3_library_init(nontracing_allocator);
1217
1218 #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9
1219 if (!PyEval_ThreadsInitialized()) {
1220 PyEval_InitThreads();
1221 }
1222 #endif
1223
1224 aws_register_error_info(&s_error_list);
1225 s_error_map_init();
1226
1227 return m;
1228 }
1229
1230 /**
1231 * align with the the vanilla C types Python tends to use.
1232 * This is important when passing arguments between C and Python
1233 * via things like PyArg_ParseTuple() and PyObject_CallFunction()
1234 * https://docs.python.org/3/c-api/arg.html
1235 */
1236 AWS_STATIC_ASSERT(sizeof(uint8_t) == sizeof(unsigned char)); /* we pass uint8_t as "B" (unsigned char) */
1237 AWS_STATIC_ASSERT(sizeof(uint16_t) == sizeof(unsigned short)); /* we pass uint16_t as "H" (unsigned short) */
1238 AWS_STATIC_ASSERT(sizeof(uint32_t) == sizeof(unsigned int)); /* we pass uint32_t as "I" (unsigned int) */
1239 AWS_STATIC_ASSERT(sizeof(uint64_t) == sizeof(unsigned long long)); /* we pass uint64_t as "K" (unsigned long long) */
1240 AWS_STATIC_ASSERT(sizeof(enum aws_log_level) == sizeof(int)); /* we pass enums as "i" (int) */