Debian Codegraph @

source/io.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 "io.h"
6
7 #include <aws/common/atomics.h>
8
9 #include <aws/io/channel_bootstrap.h>
10 #include <aws/io/event_loop.h>
11 #include <aws/io/socket.h>
12 #include <aws/io/stream.h>
13 #include <aws/io/tls_channel_handler.h>
14
15 #include <stdio.h>
16 #include <string.h>
17
18 static const char *s_capsule_name_client_bootstrap = "aws_client_bootstrap";
19 static const char *s_capsule_name_elg = "aws_event_loop_group";
20 static const char *s_capsule_name_host_resolver = "aws_host_resolver";
21 static const char *s_capsule_name_tls_ctx = "aws_client_tls_ctx";
22 static const char *s_capsule_name_tls_conn_options = "aws_tls_connection_options";
23 static const char *s_capsule_name_input_stream = "aws_input_stream";
24
25 bool aws_py_socket_options_init(struct aws_socket_options *socket_options, PyObject *py_socket_options) {
26 AWS_ZERO_STRUCT(*socket_options);
27
28 bool success = false;
29
30 socket_options->domain = PyObject_GetAttrAsIntEnum(py_socket_options, "SocketOptions", "domain");
31 if (PyErr_Occurred()) {
32 goto done;
33 }
34
35 socket_options->type = PyObject_GetAttrAsIntEnum(py_socket_options, "SocketOptions", "type");
36 if (PyErr_Occurred()) {
37 goto done;
38 }
39
40 socket_options->connect_timeout_ms =
41 PyObject_GetAttrAsUint32(py_socket_options, "SocketOptions", "connect_timeout_ms");
42 if (PyErr_Occurred()) {
43 goto done;
44 }
45
46 socket_options->keepalive = PyObject_GetAttrAsBool(py_socket_options, "SocketOptions", "keep_alive");
47 if (PyErr_Occurred()) {
48 goto done;
49 }
50
51 socket_options->keep_alive_interval_sec =
52 PyObject_GetAttrAsUint16(py_socket_options, "SocketOptions", "keep_alive_interval_secs");
53 if (PyErr_Occurred()) {
54 goto done;
55 }
56
57 socket_options->keep_alive_timeout_sec =
58 PyObject_GetAttrAsUint16(py_socket_options, "SocketOptions", "keep_alive_timeout_secs");
59 if (PyErr_Occurred()) {
60 goto done;
61 }
62
63 socket_options->keep_alive_max_failed_probes =
64 PyObject_GetAttrAsUint16(py_socket_options, "SocketOptions", "keep_alive_max_probes");
65 if (PyErr_Occurred()) {
66 goto done;
67 }
68
69 success = true;
70
71 done:
72 if (!success) {
73 AWS_ZERO_STRUCT(*socket_options);
74 }
75 return success;
76 }
77
78 PyObject *aws_py_is_alpn_available(PyObject *self, PyObject *args) {
79
80 (void)self;
81 (void)args;
82
83 return PyBool_FromLong(aws_tls_is_alpn_available());
84 }
85
86 PyObject *aws_py_is_tls_cipher_supported(PyObject *self, PyObject *args) {
87 (void)self;
88 (void)args;
89
90 int cipher_pref = 0;
91
92 if (!PyArg_ParseTuple(args, "i", &cipher_pref)) {
93 return NULL;
94 }
95
96 return PyBool_FromLong(aws_tls_is_cipher_pref_supported(cipher_pref));
97 }
98 /*******************************************************************************
99 * AWS_EVENT_LOOP_GROUP
100 ******************************************************************************/
101
102 struct event_loop_group_binding {
103 struct aws_event_loop_group *native;
104
105 /* Dependencies that must outlive this */
106 PyObject *shutdown_complete;
107 };
108
109 /* Callback when native event-loop-group finishes its async cleanup */
110 static void s_elg_native_cleanup_complete(void *user_data) {
111 struct event_loop_group_binding *elg_binding = user_data;
112 PyObject *shutdown_complete = elg_binding->shutdown_complete;
113
114 aws_mem_release(aws_py_get_allocator(), elg_binding);
115
116 /*************** GIL ACQUIRE ***************/
117 PyGILState_STATE state;
118 if (aws_py_gilstate_ensure(&state)) {
119 return; /* Python has shut down. Nothing matters anymore, but don't crash */
120 }
121
122 PyObject *result = PyObject_CallFunction(shutdown_complete, "()");
123 if (result) {
124 Py_DECREF(result);
125 } else {
126 PyErr_WriteUnraisable(PyErr_Occurred());
127 }
128 Py_DECREF(shutdown_complete);
129
130 PyGILState_Release(state);
131 /*************** GIL RELEASE ***************/
132 }
133
134 static void s_elg_capsule_destructor(PyObject *elg_capsule) {
135 struct event_loop_group_binding *elg_binding = PyCapsule_GetPointer(elg_capsule, s_capsule_name_elg);
136
137 /* Must use async cleanup.
138 * We could deadlock if we ran the synchronous cleanup from an event-loop thread. */
139 aws_event_loop_group_release(elg_binding->native);
140 }
141
142 PyObject *aws_py_event_loop_group_new(PyObject *self, PyObject *args) {
143 (void)self;
144
145 struct aws_allocator *allocator = aws_py_get_allocator();
146
147 uint16_t num_threads;
148 int is_pinned;
149 uint16_t cpu_group;
150 PyObject *shutdown_complete_py;
151 if (!PyArg_ParseTuple(args, "HpHO", &num_threads, &is_pinned, &cpu_group, &shutdown_complete_py)) {
152 return NULL;
153 }
154
155 struct event_loop_group_binding *binding = aws_mem_calloc(allocator, 1, sizeof(struct event_loop_group_binding));
156 if (!binding) {
157 return PyErr_AwsLastError();
158 }
159
160 struct aws_shutdown_callback_options shutdown_options = {
161 .shutdown_callback_fn = s_elg_native_cleanup_complete,
162 .shutdown_callback_user_data = binding,
163 };
164
165 if (is_pinned) {
166 binding->native =
167 aws_event_loop_group_new_default_pinned_to_cpu_group(allocator, num_threads, cpu_group, &shutdown_options);
168 } else {
169 binding->native = aws_event_loop_group_new_default(allocator, num_threads, &shutdown_options);
170 }
171 if (binding->native == NULL) {
172 PyErr_SetAwsLastError();
173 goto elg_init_failed;
174 }
175
176 PyObject *capsule = PyCapsule_New(binding, s_capsule_name_elg, s_elg_capsule_destructor);
177 if (!capsule) {
178 goto capsule_new_failed;
179 }
180
181 AWS_FATAL_ASSERT(shutdown_complete_py != Py_None);
182 binding->shutdown_complete = shutdown_complete_py;
183 Py_INCREF(binding->shutdown_complete);
184
185 return capsule;
186
187 capsule_new_failed:
188 aws_event_loop_group_release(binding->native);
189 elg_init_failed:
190 aws_mem_release(allocator, binding);
191 return NULL;
192 }
193
194 struct aws_event_loop_group *aws_py_get_event_loop_group(PyObject *event_loop_group) {
195 AWS_PY_RETURN_NATIVE_FROM_BINDING(event_loop_group, s_capsule_name_elg, "EventLoopGroup", event_loop_group_binding);
196 }
197
198 /*******************************************************************************
199 * AWS_HOST_RESOLVER
200 ******************************************************************************/
201
202 struct host_resolver_binding {
203 struct aws_host_resolver *native;
204
205 /* Dependencies that must outlive this */
206 PyObject *event_loop_group;
207 };
208
209 static void s_host_resolver_destructor(PyObject *host_resolver_capsule) {
210 struct host_resolver_binding *host_resolver =
211 PyCapsule_GetPointer(host_resolver_capsule, s_capsule_name_host_resolver);
212 assert(host_resolver);
213 aws_host_resolver_release(host_resolver->native);
214 Py_DECREF(host_resolver->event_loop_group);
215 aws_mem_release(aws_py_get_allocator(), host_resolver);
216 }
217
218 PyObject *aws_py_host_resolver_new_default(PyObject *self, PyObject *args) {
219 (void)self;
220
221 struct aws_allocator *allocator = aws_py_get_allocator();
222
223 Py_ssize_t max_hosts;
224 PyObject *elg_py;
225 if (!PyArg_ParseTuple(args, "nO", &max_hosts, &elg_py)) {
226 return NULL;
227 }
228
229 if (max_hosts < 1) {
230 PyErr_SetString(PyExc_ValueError, "max_hosts must be greater than 0");
231 return NULL;
232 }
233
234 struct aws_event_loop_group *elg = aws_py_get_event_loop_group(elg_py);
235 if (!elg) {
236 return NULL;
237 }
238
239 struct host_resolver_binding *host_resolver = aws_mem_calloc(allocator, 1, sizeof(struct host_resolver_binding));
240 if (!host_resolver) {
241 PyErr_SetAwsLastError();
242 return NULL;
243 }
244
245 /* From hereon, we need to clean up if errors occur */
246 struct aws_host_resolver_default_options resolver_options = {
247 .max_entries = max_hosts,
248 .el_group = elg,
249 };
250
251 host_resolver->native = aws_host_resolver_new_default(allocator, &resolver_options);
252 if (host_resolver->native == NULL) {
253 PyErr_SetAwsLastError();
254 goto resolver_init_failed;
255 }
256
257 PyObject *capsule = PyCapsule_New(host_resolver, s_capsule_name_host_resolver, s_host_resolver_destructor);
258 if (!capsule) {
259 goto capsule_new_failed;
260 }
261
262 /* From hereon, nothing will fail */
263
264 host_resolver->event_loop_group = elg_py;
265 Py_INCREF(elg_py);
266 return capsule;
267
268 capsule_new_failed:
269 aws_host_resolver_release(host_resolver->native);
270 resolver_init_failed:
271 aws_mem_release(allocator, host_resolver);
272 return NULL;
273 }
274
275 struct aws_host_resolver *aws_py_get_host_resolver(PyObject *host_resolver) {
276 AWS_PY_RETURN_NATIVE_FROM_BINDING(
277 host_resolver, s_capsule_name_host_resolver, "HostResolverBase", host_resolver_binding);
278 }
279
280 struct client_bootstrap_binding {
281 struct aws_client_bootstrap *native;
282
283 /* Dependencies that must outlive this */
284 PyObject *event_loop_group;
285 PyObject *host_resolver;
286 PyObject *shutdown_complete;
287 };
288
289 /* Fires after the native client bootstrap finishes shutting down. */
290 static void s_client_bootstrap_on_shutdown_complete(void *user_data) {
291 struct client_bootstrap_binding *bootstrap = user_data;
292 PyObject *shutdown_complete = bootstrap->shutdown_complete;
293
294 /*************** GIL ACQUIRE ***************/
295 PyGILState_STATE state;
296 if (aws_py_gilstate_ensure(&state)) {
297 return; /* Python has shut down. Nothing matters anymore, but don't crash */
298 }
299
300 Py_XDECREF(bootstrap->host_resolver);
301 Py_XDECREF(bootstrap->event_loop_group);
302
303 aws_mem_release(aws_py_get_allocator(), bootstrap);
304
305 if (shutdown_complete) {
306 PyObject *result = PyObject_CallFunction(shutdown_complete, "()");
307 if (result) {
308 Py_DECREF(result);
309 } else {
310 PyErr_WriteUnraisable(PyErr_Occurred());
311 }
312 Py_DECREF(shutdown_complete);
313 }
314
315 PyGILState_Release(state);
316 /*************** GIL RELEASE ***************/
317 }
318
319 /* Fires when python capsule is GC'd.
320 * Note that bootstrap shutdown is async, we can't release dependencies until it completes */
321 static void s_client_bootstrap_capsule_destructor(PyObject *bootstrap_capsule) {
322 struct client_bootstrap_binding *bootstrap =
323 PyCapsule_GetPointer(bootstrap_capsule, s_capsule_name_client_bootstrap);
324
325 aws_client_bootstrap_release(bootstrap->native);
326 }
327
328 PyObject *aws_py_client_bootstrap_new(PyObject *self, PyObject *args) {
329 (void)self;
330
331 struct aws_allocator *allocator = aws_py_get_allocator();
332
333 PyObject *elg_py;
334 PyObject *host_resolver_py;
335 PyObject *shutdown_complete_py;
336
337 if (!PyArg_ParseTuple(args, "OOO", &elg_py, &host_resolver_py, &shutdown_complete_py)) {
338 return NULL;
339 }
340
341 struct aws_event_loop_group *elg = aws_py_get_event_loop_group(elg_py);
342 if (!elg) {
343 return NULL;
344 }
345
346 struct aws_host_resolver *host_resolver = aws_py_get_host_resolver(host_resolver_py);
347 if (!host_resolver) {
348 return NULL;
349 }
350
351 struct client_bootstrap_binding *bootstrap = aws_mem_calloc(allocator, 1, sizeof(struct client_bootstrap_binding));
352 if (!bootstrap) {
353 PyErr_SetAwsLastError();
354 return NULL;
355 }
356
357 /* From hereon, we need to clean up if errors occur */
358
359 PyObject *capsule =
360 PyCapsule_New(bootstrap, s_capsule_name_client_bootstrap, s_client_bootstrap_capsule_destructor);
361 if (!capsule) {
362 goto error;
363 }
364
365 struct aws_client_bootstrap_options bootstrap_options = {
366 .event_loop_group = elg,
367 .host_resolver = host_resolver,
368 .on_shutdown_complete = s_client_bootstrap_on_shutdown_complete,
369 .user_data = bootstrap,
370 };
371 bootstrap->native = aws_client_bootstrap_new(allocator, &bootstrap_options);
372 if (!bootstrap->native) {
373 PyErr_SetAwsLastError();
374 goto error;
375 }
376
377 /* From hereon, nothing will fail */
378
379 bootstrap->event_loop_group = elg_py;
380 Py_INCREF(elg_py);
381
382 bootstrap->host_resolver = host_resolver_py;
383 Py_INCREF(host_resolver_py);
384
385 bootstrap->shutdown_complete = shutdown_complete_py;
386 Py_INCREF(bootstrap->shutdown_complete);
387
388 return capsule;
389
390 error:
391 if (capsule) {
392 Py_DECREF(capsule);
393 } else {
394 aws_mem_release(allocator, bootstrap);
395 }
396 return NULL;
397 }
398
399 struct aws_client_bootstrap *aws_py_get_client_bootstrap(PyObject *client_bootstrap) {
400 AWS_PY_RETURN_NATIVE_FROM_BINDING(
401 client_bootstrap, s_capsule_name_client_bootstrap, "ClientBootstrap", client_bootstrap_binding);
402 }
403
404 static void s_tls_ctx_destructor(PyObject *tls_ctx_capsule) {
405
406 struct aws_tls_ctx *tls_ctx = PyCapsule_GetPointer(tls_ctx_capsule, s_capsule_name_tls_ctx);
407 assert(tls_ctx);
408
409 aws_tls_ctx_release(tls_ctx);
410 }
411
412 PyObject *aws_py_client_tls_ctx_new(PyObject *self, PyObject *args) {
413 (void)self;
414
415 struct aws_allocator *allocator = aws_py_get_allocator();
416
417 int min_tls_version = 0;
418 int cipher_pref = 0;
419 const char *ca_dirpath;
420 const char *ca_buffer;
421 Py_ssize_t ca_buffer_len;
422 const char *alpn_list;
423 const char *certificate_buffer;
424 Py_ssize_t certificate_buffer_len;
425 const char *private_key_buffer;
426 Py_ssize_t private_key_buffer_len;
427 const char *pkcs12_filepath;
428 const char *pkcs12_password;
429 int verify_peer;
430 int no_certificate_revocation;
431 PyObject *py_pkcs11_lib;
432 const char *pkcs11_user_pin;
433 Py_ssize_t pkcs11_user_pin_len;
434 PyObject *py_pkcs11_slot_id;
435 const char *pkcs11_token_label;
436 Py_ssize_t pkcs11_token_label_len;
437 const char *pkcs11_priv_key_label;
438 Py_ssize_t pkcs11_priv_key_label_len;
439 const char *pkcs11_cert_file_path;
440 Py_ssize_t pkcs11_cert_file_path_len;
441 const char *pkcs11_cert_file_contents;
442 Py_ssize_t pkcs11_cert_file_contents_len;
443 const char *windows_cert_store_path;
444
445 if (!PyArg_ParseTuple(
446 args,
447 "iizz#zz#z#zzppOz#Oz#z#z#z#z",
448 /* i */ &min_tls_version,
449 /* i */ &cipher_pref,
450 /* z */ &ca_dirpath,
451 /* z */ &ca_buffer,
452 /* # */ &ca_buffer_len,
453 /* z */ &alpn_list,
454 /* z */ &certificate_buffer,
455 /* # */ &certificate_buffer_len,
456 /* z */ &private_key_buffer,
457 /* # */ &private_key_buffer_len,
458 /* z */ &pkcs12_filepath,
459 /* z */ &pkcs12_password,
460 /* p */ &verify_peer,
461 /* p */ &no_certificate_revocation,
462 /* O */ &py_pkcs11_lib,
463 /* z */ &pkcs11_user_pin,
464 /* # */ &pkcs11_user_pin_len,
465 /* O */ &py_pkcs11_slot_id,
466 /* z */ &pkcs11_token_label,
467 /* # */ &pkcs11_token_label_len,
468 /* z */ &pkcs11_priv_key_label,
469 /* # */ &pkcs11_priv_key_label_len,
470 /* z */ &pkcs11_cert_file_path,
471 /* # */ &pkcs11_cert_file_path_len,
472 /* z */ &pkcs11_cert_file_contents,
473 /* # */ &pkcs11_cert_file_contents_len,
474 /* z */ &windows_cert_store_path)) {
475 return NULL;
476 }
477
478 struct aws_tls_ctx_options ctx_options;
479 AWS_ZERO_STRUCT(ctx_options);
480 if (certificate_buffer != NULL) {
481 /* mTLS with certificate and private key*/
482 struct aws_byte_cursor cert = aws_byte_cursor_from_array(certificate_buffer, certificate_buffer_len);
483 struct aws_byte_cursor key = aws_byte_cursor_from_array(private_key_buffer, private_key_buffer_len);
484 if (aws_tls_ctx_options_init_client_mtls(&ctx_options, allocator, &cert, &key)) {
485 PyErr_SetAwsLastError();
486 return NULL;
487 }
488 } else if (py_pkcs11_lib != Py_None) {
489 /* mTLS with PKCS#11 */
490 struct aws_pkcs11_lib *pkcs11_lib = aws_py_get_pkcs11_lib(py_pkcs11_lib);
491 if (pkcs11_lib == NULL) {
492 return NULL;
493 }
494
495 bool has_slot_id = false;
496 uint64_t slot_id_value = 0;
497 if (py_pkcs11_slot_id != Py_None) {
498 has_slot_id = true;
499 slot_id_value = PyLong_AsUnsignedLongLong(py_pkcs11_slot_id);
500 if ((slot_id_value == (uint64_t)-1) && PyErr_Occurred()) {
501 PyErr_SetString(PyExc_ValueError, "PKCS#11 slot_id is not a valid int");
502 return NULL;
503 }
504 }
505
506 struct aws_tls_ctx_pkcs11_options pkcs11_options = {
507 .pkcs11_lib = pkcs11_lib,
508 .user_pin = aws_byte_cursor_from_array(pkcs11_user_pin, pkcs11_user_pin_len),
509 .slot_id = has_slot_id ? &slot_id_value : NULL,
510 .token_label = aws_byte_cursor_from_array(pkcs11_token_label, pkcs11_token_label_len),
511 .private_key_object_label = aws_byte_cursor_from_array(pkcs11_priv_key_label, pkcs11_priv_key_label_len),
512 .cert_file_path = aws_byte_cursor_from_array(pkcs11_cert_file_path, pkcs11_cert_file_path_len),
513 .cert_file_contents = aws_byte_cursor_from_array(pkcs11_cert_file_contents, pkcs11_cert_file_contents_len),
514 };
515
516 if (aws_tls_ctx_options_init_client_mtls_with_pkcs11(&ctx_options, allocator, &pkcs11_options)) {
517 return PyErr_AwsLastError();
518 }
519 } else if (pkcs12_filepath != NULL) {
520 /* mTLS with PKCS#12 */
521 struct aws_byte_cursor password = aws_byte_cursor_from_c_str(pkcs12_password);
522 if (aws_tls_ctx_options_init_client_mtls_pkcs12_from_path(
523 &ctx_options, allocator, pkcs12_filepath, &password)) {
524 return PyErr_AwsLastError();
525 }
526 } else if (windows_cert_store_path != NULL) {
527 /* mTLS with certificate from a Windows certificate store */
528 if (aws_tls_ctx_options_init_client_mtls_from_system_path(&ctx_options, allocator, windows_cert_store_path)) {
529 return PyErr_AwsLastError();
530 }
531 } else {
532 /* no mTLS */
533 aws_tls_ctx_options_init_default_client(&ctx_options, allocator);
534 }
535
536 /* From hereon, we need to clean up if errors occur */
537
538 ctx_options.minimum_tls_version = min_tls_version;
539 ctx_options.cipher_pref = cipher_pref;
540
541 if (ca_dirpath != NULL) {
542 if (aws_tls_ctx_options_override_default_trust_store_from_path(&ctx_options, ca_dirpath, NULL)) {
543 PyErr_SetAwsLastError();
544 goto ctx_options_failure;
545 }
546 }
547
548 if (ca_buffer != NULL) {
549 struct aws_byte_cursor ca = aws_byte_cursor_from_array(ca_buffer, ca_buffer_len);
550
551 if (aws_tls_ctx_options_override_default_trust_store(&ctx_options, &ca)) {
552 PyErr_SetAwsLastError();
553 goto ctx_options_failure;
554 }
555 }
556
557 if (alpn_list != NULL) {
558 if (aws_tls_ctx_options_set_alpn_list(&ctx_options, alpn_list)) {
559 PyErr_SetAwsLastError();
560 goto ctx_options_failure;
561 }
562 }
563
564 ctx_options.verify_peer = (bool)verify_peer;
565 ctx_options.no_certificate_revocation = (bool)no_certificate_revocation;
566
567 struct aws_tls_ctx *tls_ctx = aws_tls_client_ctx_new(allocator, &ctx_options);
568 if (!tls_ctx) {
569 PyErr_SetAwsLastError();
570 goto ctx_options_failure;
571 }
572
573 PyObject *capsule = PyCapsule_New(tls_ctx, s_capsule_name_tls_ctx, s_tls_ctx_destructor);
574 if (!capsule) {
575 goto capsule_new_failure;
576 }
577
578 /* From hereon, nothing will fail */
579
580 aws_tls_ctx_options_clean_up(&ctx_options);
581 return capsule;
582
583 capsule_new_failure:
584 aws_tls_ctx_release(tls_ctx);
585
586 ctx_options_failure:
587 aws_tls_ctx_options_clean_up(&ctx_options);
588 return NULL;
589 }
590
591 struct aws_tls_ctx *aws_py_get_tls_ctx(PyObject *tls_ctx) {
592 return aws_py_get_binding(tls_ctx, s_capsule_name_tls_ctx, "TlsContextBase");
593 }
594
595 struct tls_connection_options_binding {
596 struct aws_tls_connection_options native;
597
598 /* Dependencies that must outlive this */
599 PyObject *tls_ctx;
600 };
601
602 static void s_tls_connection_options_destructor(PyObject *tls_connection_options_capsule) {
603
604 struct aws_allocator *allocator = aws_py_get_allocator();
605
606 struct tls_connection_options_binding *tls_connection_options =
607 PyCapsule_GetPointer(tls_connection_options_capsule, s_capsule_name_tls_conn_options);
608 assert(tls_connection_options);
609
610 aws_tls_connection_options_clean_up(&tls_connection_options->native);
611 Py_DECREF(tls_connection_options->tls_ctx);
612 aws_mem_release(allocator, tls_connection_options);
613 }
614
615 PyObject *aws_py_tls_connections_options_new_from_ctx(PyObject *self, PyObject *args) {
616 (void)self;
617
618 struct aws_allocator *allocator = aws_py_get_allocator();
619
620 PyObject *tls_ctx_py;
621
622 if (!PyArg_ParseTuple(args, "O", &tls_ctx_py)) {
623 return NULL;
624 }
625
626 struct aws_tls_ctx *ctx = aws_py_get_tls_ctx(tls_ctx_py);
627 if (!ctx) {
628 return NULL;
629 }
630
631 struct tls_connection_options_binding *conn_options =
632 aws_mem_calloc(allocator, 1, sizeof(struct tls_connection_options_binding));
633 if (!conn_options) {
634 PyErr_SetAwsLastError();
635 return NULL;
636 }
637
638 /* From hereon, we need to clean up if errors occur */
639
640 PyObject *capsule =
641 PyCapsule_New(conn_options, s_capsule_name_tls_conn_options, s_tls_connection_options_destructor);
642 if (!capsule) {
643 goto capsule_new_failed;
644 }
645
646 /* From hereon, nothing will fail */
647
648 aws_tls_connection_options_init_from_ctx(&conn_options->native, ctx);
649
650 conn_options->tls_ctx = tls_ctx_py;
651 Py_INCREF(tls_ctx_py);
652
653 return capsule;
654
655 capsule_new_failed:
656 aws_mem_release(allocator, conn_options);
657 return NULL;
658 }
659
660 struct aws_tls_connection_options *aws_py_get_tls_connection_options(PyObject *tls_connection_options) {
661 AWS_PY_RETURN_NATIVE_REF_FROM_BINDING(
662 tls_connection_options,
663 s_capsule_name_tls_conn_options,
664 "TlsConnectionOptions",
665 tls_connection_options_binding);
666 }
667
668 PyObject *aws_py_tls_connection_options_set_alpn_list(PyObject *self, PyObject *args) {
669 (void)self;
670
671 struct aws_allocator *allocator = aws_py_get_allocator();
672
673 PyObject *tls_conn_options_py;
674 const char *alpn_list;
675 if (!PyArg_ParseTuple(args, "Os", &tls_conn_options_py, &alpn_list)) {
676 return NULL;
677 }
678
679 struct aws_tls_connection_options *connection_options = aws_py_get_tls_connection_options(tls_conn_options_py);
680 if (!connection_options) {
681 return NULL;
682 }
683
684 if (aws_tls_connection_options_set_alpn_list(connection_options, allocator, alpn_list)) {
685 PyErr_SetAwsLastError();
686 return NULL;
687 }
688
689 Py_RETURN_NONE;
690 }
691
692 PyObject *aws_py_tls_connection_options_set_server_name(PyObject *self, PyObject *args) {
693 (void)self;
694
695 struct aws_allocator *allocator = aws_py_get_allocator();
696
697 PyObject *tls_conn_options_py;
698 const char *server_name;
699 Py_ssize_t server_name_len;
700 if (!PyArg_ParseTuple(args, "Os#", &tls_conn_options_py, &server_name, &server_name_len)) {
701 return NULL;
702 }
703
704 struct aws_tls_connection_options *connection_options = aws_py_get_tls_connection_options(tls_conn_options_py);
705 if (!connection_options) {
706 return NULL;
707 }
708
709 struct aws_byte_cursor server_name_cur = aws_byte_cursor_from_array(server_name, (size_t)server_name_len);
710
711 if (aws_tls_connection_options_set_server_name(connection_options, allocator, &server_name_cur)) {
712 PyErr_SetAwsLastError();
713 return NULL;
714 }
715
716 Py_RETURN_NONE;
717 }
718
719 /* aws_input_stream implementation for accessing Python I/O classes */
720 struct aws_input_stream_py_impl {
721 struct aws_input_stream base;
722 struct aws_allocator *allocator;
723
724 bool is_end_of_stream;
725
726 /* Track the refcount from C land */
727 struct aws_atomic_var c_ref;
728
729 /* Pointer to python self. The stream will have a same lifetime as the python Object */
730 PyObject *py_self;
731 };
732
733 static int s_aws_input_stream_py_seek(
734 struct aws_input_stream *stream,
735 int64_t offset,
736 enum aws_stream_seek_basis basis) {
737
738 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
739
740 int aws_result = AWS_OP_SUCCESS;
741 PyObject *method_result = NULL;
742
743 /*************** GIL ACQUIRE ***************/
744 PyGILState_STATE state;
745 if (aws_py_gilstate_ensure(&state)) {
746 return AWS_OP_ERR; /* Python has shut down. Nothing matters anymore, but don't crash */
747 }
748
749 method_result = PyObject_CallMethod(impl->py_self, "_seek", "(Li)", offset, basis);
750 if (!method_result) {
751 aws_result = aws_py_raise_error();
752 goto done;
753 }
754
755 /* Clear EOF */
756 impl->is_end_of_stream = false;
757
758 done:
759 Py_XDECREF(method_result);
760 PyGILState_Release(state);
761 /*************** GIL RELEASE ***************/
762
763 return aws_result;
764 }
765
766 int s_aws_input_stream_py_read(struct aws_input_stream *stream, struct aws_byte_buf *dest) {
767 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
768
769 int aws_result = AWS_OP_SUCCESS;
770 PyObject *memory_view = NULL;
771 PyObject *method_result = NULL;
772
773 /*************** GIL ACQUIRE ***************/
774 PyGILState_STATE state;
775 if (aws_py_gilstate_ensure(&state)) {
776 return AWS_OP_ERR; /* Python has shut down. Nothing matters anymore, but don't crash */
777 }
778
779 memory_view = aws_py_memory_view_from_byte_buffer(dest);
780 if (!memory_view) {
781 aws_result = aws_py_raise_error();
782 goto done;
783 }
784
785 method_result = PyObject_CallMethod(impl->py_self, "_read_into_memoryview", "(O)", memory_view);
786 if (!method_result) {
787 aws_result = aws_py_raise_error();
788 goto done;
789 }
790
791 /* Return the number of bytes read. If the object is in non-blocking mode
792 * and no bytes are available, None is returned */
793 Py_ssize_t bytes_read = 0;
794 if (method_result != Py_None) {
795 bytes_read = PyLong_AsSsize_t(method_result);
796 if (bytes_read == -1 && PyErr_Occurred()) {
797 aws_result = aws_py_raise_error();
798 goto done;
799 }
800 AWS_FATAL_ASSERT(bytes_read >= 0);
801
802 if (bytes_read == 0) {
803 impl->is_end_of_stream = true;
804 } else {
805 dest->len += bytes_read;
806 }
807 }
808
809 done:
810 Py_XDECREF(memory_view);
811 Py_XDECREF(method_result);
812 PyGILState_Release(state);
813 /*************** GIL RELEASE ***************/
814
815 return aws_result;
816 }
817
818 int s_aws_input_stream_py_get_status(struct aws_input_stream *stream, struct aws_stream_status *status) {
819 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
820
821 status->is_valid = true;
822 status->is_end_of_stream = impl->is_end_of_stream;
823
824 return AWS_OP_SUCCESS;
825 }
826
827 int s_aws_input_stream_py_get_length(struct aws_input_stream *stream, int64_t *out_length) {
828 (void)stream;
829 (void)out_length;
830 return aws_raise_error(AWS_ERROR_UNIMPLEMENTED);
831 }
832
833 void s_aws_input_stream_py_acquire(struct aws_input_stream *stream) {
834 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
835 size_t pre_ref = aws_atomic_fetch_add(&impl->c_ref, 1);
836 if (pre_ref == 0) {
837 /* Only acquire the python ref when it's a new C ref */
838 /*************** GIL ACQUIRE ***************/
839 PyGILState_STATE state;
840 if (aws_py_gilstate_ensure(&state)) {
841 return; /* Python has shut down. Nothing matters anymore, but don't crash */
842 }
843 Py_INCREF(impl->py_self);
844 PyGILState_Release(state);
845 /*************** GIL RELEASE ***************/
846 }
847 }
848
849 void s_aws_input_stream_py_release(struct aws_input_stream *stream) {
850 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
851 size_t pre_ref = aws_atomic_fetch_sub(&impl->c_ref, 1);
852 if (pre_ref == 1) {
853 /* Only release the python ref when all the C refs gone */
854 /*************** GIL ACQUIRE ***************/
855 PyGILState_STATE state;
856 if (aws_py_gilstate_ensure(&state)) {
857 return; /* Python has shut down. Nothing matters anymore, but don't crash */
858 }
859 Py_DECREF(impl->py_self);
860 PyGILState_Release(state);
861 /*************** GIL RELEASE ***************/
862 }
863 }
864
865 static struct aws_input_stream_vtable s_aws_input_stream_py_vtable = {
866 .seek = s_aws_input_stream_py_seek,
867 .read = s_aws_input_stream_py_read,
868 .get_status = s_aws_input_stream_py_get_status,
869 .get_length = s_aws_input_stream_py_get_length,
870 .acquire = s_aws_input_stream_py_acquire,
871 .release = s_aws_input_stream_py_release,
872 };
873
874 /**
875 * Begin aws_input_stream <--> InputStream binding code.
876 * This is distinct from the aws_input_stream_from_pyobject() code because
877 * we might someday have an InputStream in python that is wrapping an
878 * aws_input_stream that was not initially created from python, and is not
879 * backed by a python I/O object.
880 */
881
882 static void s_input_stream_capsule_destructor(PyObject *py_capsule) {
883 struct aws_input_stream *stream = PyCapsule_GetPointer(py_capsule, s_capsule_name_input_stream);
884 struct aws_input_stream_py_impl *impl = AWS_CONTAINER_OF(stream, struct aws_input_stream_py_impl, base);
885 aws_mem_release(impl->allocator, impl);
886 }
887
888 PyObject *aws_py_input_stream_new(PyObject *self, PyObject *args) {
889 (void)self;
890
891 PyObject *py_self;
892 if (!PyArg_ParseTuple(args, "O", &py_self)) {
893 return NULL;
894 }
895
896 if (py_self == Py_None) {
897 PyErr_SetString(PyExc_TypeError, "InputStream cannot be None");
898 return NULL;
899 }
900
901 struct aws_allocator *alloc = aws_py_get_allocator();
902 struct aws_input_stream_py_impl *impl = aws_mem_calloc(alloc, 1, sizeof(struct aws_input_stream_py_impl));
903 impl->allocator = alloc;
904 impl->base.vtable = &s_aws_input_stream_py_vtable;
905 impl->py_self = py_self;
906 aws_atomic_init_int(&impl->c_ref, 0);
907 /* Lifetime of the impl will be the same as py_capsule and being handled by python */
908 PyObject *py_capsule = PyCapsule_New(&impl->base, s_capsule_name_input_stream, s_input_stream_capsule_destructor);
909
910 if (!py_capsule) {
911 aws_mem_release(impl->allocator, impl);
912 }
913
914 return py_capsule;
915 }
916
917 struct aws_input_stream *aws_py_get_input_stream(PyObject *input_stream) {
918 return aws_py_get_binding(input_stream, s_capsule_name_input_stream, "InputStream");
919 }