Debian Codegraph @

source/websocket.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include "websocket.h"
7
8 #include "http.h"
9 #include "io.h"
10
11 #include <aws/http/proxy.h>
12 #include <aws/http/request_response.h>
13 #include <aws/http/websocket.h>
14 #include <aws/io/socket.h>
15
16 static const char *s_websocket_capsule_name = "aws_websocket";
17
18 static void s_websocket_on_connection_setup(
19 const struct aws_websocket_on_connection_setup_data *setup,
20 void *user_data);
21
22 static void s_websocket_on_connection_shutdown(struct aws_websocket *websocket, int error_code, void *user_data);
23
24 static bool s_websocket_on_incoming_frame_begin(
25 struct aws_websocket *websocket,
26 const struct aws_websocket_incoming_frame *frame,
27 void *user_data);
28
29 static bool s_websocket_on_incoming_frame_payload(
30 struct aws_websocket *websocket,
31 const struct aws_websocket_incoming_frame *frame,
32 struct aws_byte_cursor data,
33 void *user_data);
34
35 static bool s_websocket_on_incoming_frame_complete(
36 struct aws_websocket *websocket,
37 const struct aws_websocket_incoming_frame *frame,
38 int error_code,
39 void *user_data);
40
41 /* When WebSocket._binding is GC'd, release the native websocket pointer.
42 * It will close (if necessary) on its way to the grave */
43 static void s_websocket_capsule_destructor(PyObject *capsule) {
44 struct aws_websocket *websocket = PyCapsule_GetPointer(capsule, s_websocket_capsule_name);
45 aws_websocket_release(websocket);
46 }
47
48 /* Kick off websocket connection.
49 * WebSocket._binding does not get returned from this function,
50 * it gets delivered later via the _WebSocketCore._on_connection_setup() callback */
51 PyObject *aws_py_websocket_client_connect(PyObject *self, PyObject *args) {
52 (void)self;
53
54 struct aws_byte_cursor host; /* s# */
55 uint32_t port; /* I */
56 PyObject *handshake_request_py; /* O */
57 PyObject *bootstrap_py; /* O */
58 PyObject *socket_options_py; /* O */
59 PyObject *tls_options_py; /* O */
60 PyObject *proxy_options_py; /* O */
61 int manage_read_window; /* p - boolean predicate */
62 Py_ssize_t initial_read_window; /* n */
63 PyObject *websocket_core_py; /* O */
64
65 if (!PyArg_ParseTuple(
66 args,
67 "s#IOOOOOpnO",
68 &host.ptr,
69 &host.len,
70 &port,
71 &handshake_request_py,
72 &bootstrap_py,
73 &socket_options_py,
74 &tls_options_py,
75 &proxy_options_py,
76 &manage_read_window,
77 &initial_read_window,
78 &websocket_core_py)) {
79 return NULL;
80 }
81
82 /* First, wrangle args that don't require any cleanup if things go wrong... */
83
84 /* required bootstrap */
85 struct aws_client_bootstrap *bootstrap = aws_py_get_client_bootstrap(bootstrap_py);
86 if (bootstrap == NULL) {
87 return NULL;
88 }
89
90 /* required socket_options */
91 struct aws_socket_options socket_options;
92 if (aws_py_socket_options_init(&socket_options, socket_options_py) == false) {
93 return NULL;
94 }
95
96 /* optional tls_options */
97 struct aws_tls_connection_options *tls_options = NULL;
98 if (tls_options_py != Py_None) {
99 tls_options = aws_py_get_tls_connection_options(tls_options_py);
100 if (tls_options == NULL) {
101 return NULL;
102 }
103 }
104
105 /* optional proxy_options */
106 bool has_proxy_options = proxy_options_py != Py_None;
107 struct aws_http_proxy_options proxy_options;
108 if (has_proxy_options) {
109 if (aws_py_http_proxy_options_init(&proxy_options, proxy_options_py) == false) {
110 return NULL;
111 }
112 }
113
114 /* required handshake_request */
115 struct aws_http_message *handshake_request = aws_py_get_http_message(handshake_request_py);
116 if (handshake_request == NULL) {
117 return NULL;
118 }
119
120 /* From hereon, we need to clean up if errors occur... */
121
122 /* keep _WebSocketCore alive for lifetime of aws_websocket */
123 Py_INCREF(websocket_core_py);
124
125 struct aws_websocket_client_connection_options options = {
126 .allocator = aws_py_get_allocator(),
127 .bootstrap = bootstrap,
128 .socket_options = &socket_options,
129 .tls_options = tls_options,
130 .proxy_options = has_proxy_options ? &proxy_options : NULL,
131 .host = host,
132 .port = port,
133 .handshake_request = handshake_request,
134 .initial_window_size = (size_t)initial_read_window, /* already checked it was non-negative out in python */
135 .user_data = websocket_core_py,
136 .on_connection_setup = s_websocket_on_connection_setup,
137 .on_connection_shutdown = s_websocket_on_connection_shutdown,
138 .on_incoming_frame_begin = s_websocket_on_incoming_frame_begin,
139 .on_incoming_frame_payload = s_websocket_on_incoming_frame_payload,
140 .on_incoming_frame_complete = s_websocket_on_incoming_frame_complete,
141 .manual_window_management = manage_read_window != 0,
142 };
143 if (aws_websocket_client_connect(&options) != AWS_OP_SUCCESS) {
144 PyErr_SetAwsLastError();
145 goto error;
146 }
147
148 /* Success! */
149 Py_RETURN_NONE;
150
151 error:
152 Py_DECREF(websocket_core_py);
153 return NULL;
154 }
155
156 /* Completion callback for websocket_client_connect().
157 * Wrangle args and fire _WebSocketCore._on_connection_setup().
158 *
159 * DIATRIBE ON ERROR HANDLING:
160 * Wrangling args from C->Python takes a lot of function calls that could THEORETICALLY fail.
161 * But we MUST fire the completion callback or the user's code would just hang.
162 *
163 * Attempting to handle all theoretical arg-wrangling errors would add a TON of complexity, such as:
164 * - switch callback to report failure instead of success
165 * - cleanup half-initialized resources (shut down websocket, cleanup half-initialized lists)
166 * - ability to report pure python exception, in addition to C error_code, in callback
167 * - suppress further callbacks from C as websocket shuts down,
168 * to maintain contract of "if init fails, then no further callbacks"
169 *
170 * I'm making a judgement call to just make these theoretical failures fatal.
171 * If there's a bug, it will be glaringly obvious, and simple to fix.
172 * This seems better than complicating things with tons of error-handling code
173 * that we can't actually check (and so may not actually work).
174 */
175 static void s_websocket_on_connection_setup(
176 const struct aws_websocket_on_connection_setup_data *setup,
177 void *user_data) {
178
179 /* sanity check: websocket XOR error_code is set. both cannot be set. both cannot be unset */
180 AWS_FATAL_ASSERT((setup->websocket != NULL) ^ (setup->error_code != 0));
181
182 /* userdata is _WebSocketCore */
183 PyObject *websocket_core_py = user_data;
184
185 /*************** GIL ACQUIRE ***************/
186 PyGILState_STATE state = PyGILState_Ensure();
187
188 PyObject *websocket_binding_py = NULL;
189 if (setup->websocket) {
190 websocket_binding_py =
191 PyCapsule_New(setup->websocket, s_websocket_capsule_name, s_websocket_capsule_destructor);
192 AWS_FATAL_ASSERT(websocket_binding_py && "capsule allocation failed");
193 }
194
195 /* Any of the handshake_response variables could be NULL */
196
197 PyObject *status_code_py = NULL;
198 if (setup->handshake_response_status != NULL) {
199 status_code_py = PyLong_FromLong(*setup->handshake_response_status);
200 AWS_FATAL_ASSERT(status_code_py && "status code allocation failed");
201 }
202
203 PyObject *headers_py = NULL;
204 if (setup->handshake_response_header_array != NULL) {
205 headers_py = PyList_New((Py_ssize_t)setup->num_handshake_response_headers);
206 AWS_FATAL_ASSERT(headers_py && "header list allocation failed");
207 for (size_t i = 0; i < setup->num_handshake_response_headers; ++i) {
208 const struct aws_http_header *header_i = &setup->handshake_response_header_array[i];
209 PyObject *tuple_py = PyTuple_New(2);
210 AWS_FATAL_ASSERT(tuple_py && "header tuple allocation failed");
211
212 /* Header names are tokens as per RFC 7230 Section 3.2 (strict ASCII),
213 * which means aws-c-http rejects on the wire if they contain non-ASCII bytes.
214 * So errors related to http header decoding will be caught at the protocol level.
215 * We should never fail wrangling the header name. */
216 PyObject *name_py = PyUnicode_FromAwsByteCursor(&header_i->name);
217 AWS_FATAL_ASSERT(name_py && "header name wrangling failed");
218 PyTuple_SetItem(tuple_py, 0, name_py); /* Steals a reference */
219
220 /* Header value can contain RFC 7230 obs-text (0x80-0xFF), which is
221 * not guaranteed valid UTF-8. On decode failure, log it and drop
222 * the whole header list rather than aborting the process. */
223 PyObject *value_py = PyUnicode_FromAwsByteCursor(&header_i->value);
224 if (!value_py) {
225 PyErr_WriteUnraisable(websocket_core_py);
226 Py_DECREF(tuple_py);
227 Py_CLEAR(headers_py);
228 break;
229 }
230 PyTuple_SetItem(tuple_py, 1, value_py); /* Steals a reference */
231
232 PyList_SetItem(headers_py, i, tuple_py); /* Steals a reference */
233 }
234 }
235
236 PyObject *body_py = NULL;
237 if (setup->handshake_response_body != NULL) {
238 /* AWS APIs are fine with NULL as the address of a 0-length array,
239 * but python APIs requires that it be non-NULL */
240 const char *ptr = setup->handshake_response_body->ptr ? (const char *)setup->handshake_response_body->ptr : "";
241 body_py = PyBytes_FromStringAndSize(ptr, (Py_ssize_t)setup->handshake_response_body->len);
242 AWS_FATAL_ASSERT(body_py && "response body allocation failed");
243 }
244
245 PyObject *result = PyObject_CallMethod(
246 websocket_core_py,
247 "_on_connection_setup",
248 "(iOOOO)",
249 /* i */ setup->error_code,
250 /* O */ websocket_binding_py ? websocket_binding_py : Py_None,
251 /* O */ status_code_py ? status_code_py : Py_None,
252 /* O */ headers_py ? headers_py : Py_None,
253 /* O */ body_py ? body_py : Py_None);
254
255 if (result) {
256 Py_DECREF(result);
257 } else {
258 /* _WebSocketCore._on_connection_setup() runs the user's callback in a try/except
259 * So any exception that leaks out is an unexpected bug in our code.
260 * Make it fatal, we have no graceful way to deal with this. */
261 PyErr_WriteUnraisable(websocket_core_py);
262 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket on_connection_setup callback");
263 }
264
265 Py_XDECREF(websocket_binding_py);
266 Py_XDECREF(status_code_py);
267 Py_XDECREF(headers_py);
268 Py_XDECREF(body_py);
269
270 /* If setup failed, there will be no further callbacks, so release _WebSocketCore */
271 if (setup->error_code != 0) {
272 Py_DECREF(websocket_core_py);
273 }
274
275 PyGILState_Release(state);
276 /*************** GIL RELEASE ***************/
277 }
278
279 static void s_websocket_on_connection_shutdown(struct aws_websocket *websocket, int error_code, void *user_data) {
280 (void)websocket;
281
282 /* userdata is _WebSocketCore */
283 PyObject *websocket_core_py = user_data;
284
285 /*************** GIL ACQUIRE ***************/
286 PyGILState_STATE state = PyGILState_Ensure();
287
288 PyObject *result = PyObject_CallMethod(websocket_core_py, "_on_connection_shutdown", "(i)", error_code);
289 if (result) {
290 Py_DECREF(result);
291 } else {
292 /* _WebSocketCore._on_connection_shutdown() runs the user's callback in a try/except.
293 * So any exception that leaks out is an unexpected bug in our code.
294 * Make it fatal, we have no graceful way to deal with this. */
295 PyErr_WriteUnraisable(websocket_core_py);
296 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket on_connection_shutdown callback");
297 }
298
299 /* Release _WebSocketCore, there will be no further callbacks */
300 Py_DECREF(websocket_core_py);
301
302 PyGILState_Release(state);
303 /*************** GIL RELEASE ***************/
304 }
305
306 static bool s_websocket_on_incoming_frame_begin(
307 struct aws_websocket *websocket,
308 const struct aws_websocket_incoming_frame *frame,
309 void *user_data) {
310
311 (void)websocket;
312
313 /* userdata is _WebSocketCore */
314 PyObject *websocket_core_py = user_data;
315
316 /*************** GIL ACQUIRE ***************/
317 PyGILState_STATE state = PyGILState_Ensure();
318
319 PyObject *result = PyObject_CallMethod(
320 websocket_core_py,
321 "_on_incoming_frame_begin",
322 "(iKO)",
323 frame->opcode,
324 frame->payload_length,
325 frame->fin ? Py_True : Py_False);
326
327 /* If the user's callback raises an exception, we catch it and return False to C... */
328 if (result == NULL) {
329 /* ... so any exception that leaks out is an unexpected bug in our code.
330 * Make it fatal, we have no graceful way to deal with this. */
331 PyErr_WriteUnraisable(websocket_core_py);
332 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket on_incoming_frame_begin callback");
333 }
334
335 bool success = PyObject_IsTrue(result);
336 Py_DECREF(result);
337
338 PyGILState_Release(state);
339 /*************** GIL RELEASE ***************/
340
341 return success;
342 }
343
344 static bool s_websocket_on_incoming_frame_payload(
345 struct aws_websocket *websocket,
346 const struct aws_websocket_incoming_frame *frame,
347 struct aws_byte_cursor data,
348 void *user_data) {
349
350 (void)websocket;
351 (void)frame;
352
353 /* userdata is _WebSocketCore */
354 PyObject *websocket_core_py = user_data;
355
356 /*************** GIL ACQUIRE ***************/
357 PyGILState_STATE state = PyGILState_Ensure();
358
359 PyObject *result = PyObject_CallMethod(websocket_core_py, "_on_incoming_frame_payload", "(y#)", data.ptr, data.len);
360
361 /* If the user's callback raises an exception, we catch it and return False to C... */
362 if (result == NULL) {
363 /* ... so any exception that leaks out is an unexpected bug in our code.
364 * Make it fatal, we have no graceful way to deal with this. */
365 PyErr_WriteUnraisable(websocket_core_py);
366 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket on_incoming_frame_payload callback");
367 }
368
369 bool success = PyObject_IsTrue(result);
370 Py_DECREF(result);
371
372 PyGILState_Release(state);
373 /*************** GIL RELEASE ***************/
374
375 return success;
376 }
377
378 static bool s_websocket_on_incoming_frame_complete(
379 struct aws_websocket *websocket,
380 const struct aws_websocket_incoming_frame *frame,
381 int error_code,
382 void *user_data) {
383
384 (void)websocket;
385 (void)frame;
386
387 /* userdata is _WebSocketCore */
388 PyObject *websocket_core_py = user_data;
389
390 /*************** GIL ACQUIRE ***************/
391 PyGILState_STATE state = PyGILState_Ensure();
392
393 PyObject *result = PyObject_CallMethod(websocket_core_py, "_on_incoming_frame_complete", "(i)", error_code);
394
395 /* If the user's callback raises an exception, we catch it and return False to C... */
396 if (result == NULL) {
397 /* ... so any exception that leaks out is an unexpected bug in our code.
398 * Make it fatal, we have no graceful way to deal with this. */
399 PyErr_WriteUnraisable(websocket_core_py);
400 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket on_incoming_frame_complete callback");
401 }
402
403 bool success = PyObject_IsTrue(result);
404 Py_DECREF(result);
405
406 PyGILState_Release(state);
407 /*************** GIL RELEASE ***************/
408
409 return success;
410 }
411
412 PyObject *aws_py_websocket_close(PyObject *self, PyObject *args) {
413 (void)self;
414
415 PyObject *binding_py; /* O */
416 if (!PyArg_ParseTuple(args, "O", &binding_py)) {
417 return NULL;
418 }
419
420 struct aws_websocket *websocket = PyCapsule_GetPointer(binding_py, s_websocket_capsule_name);
421 if (!websocket) {
422 return NULL;
423 }
424
425 aws_websocket_close(websocket, false /*free_scarce_resources_immediately*/);
426
427 Py_RETURN_NONE;
428 }
429
430 /**
431 * This stays alive for the duration of a send_frame operation.
432 * It streams the payload data, and fires the completion callback.
433 */
434 struct websocket_send_op {
435 /* Py_buffer lets us hold onto Python data and read it without holding the GIL */
436 Py_buffer payload_buffer;
437
438 /* this cursor tracks our progress streaming the payload */
439 struct aws_byte_cursor payload_cursor;
440
441 PyObject *on_complete_py;
442 };
443
444 static void s_websocket_send_op_destroy(struct websocket_send_op *send_op) {
445 if (send_op == NULL) {
446 return;
447 }
448
449 if (send_op->payload_buffer.buf != NULL) {
450 PyBuffer_Release(&send_op->payload_buffer);
451 }
452
453 Py_XDECREF(send_op->on_complete_py);
454
455 aws_mem_release(aws_py_get_allocator(), send_op);
456 }
457
458 static bool s_websocket_stream_outgoing_payload(
459 struct aws_websocket *websocket,
460 struct aws_byte_buf *out_buf,
461 void *user_data) {
462
463 (void)websocket;
464 struct websocket_send_op *send_op = user_data;
465
466 aws_byte_buf_write_to_capacity(out_buf, &send_op->payload_cursor);
467 return true;
468 }
469
470 static void s_websocket_on_send_frame_complete(struct aws_websocket *websocket, int error_code, void *user_data) {
471 (void)websocket;
472
473 struct websocket_send_op *send_op = user_data;
474
475 /*************** GIL ACQUIRE ***************/
476 PyGILState_STATE state = PyGILState_Ensure();
477
478 PyObject *result = PyObject_CallFunction(send_op->on_complete_py, "(i)", error_code);
479 if (result) {
480 Py_DECREF(result);
481 } else {
482 /* WebSocket.send_frame.on_complete() runs the user's callback in a try/except.
483 * So any exception that leaks out is an unexpected bug in our code.
484 * Make it fatal, we have no graceful way to deal with this. */
485 PyErr_WriteUnraisable(send_op->on_complete_py);
486 AWS_FATAL_ASSERT(0 && "Failed to invoke WebSocket.send_frame()'s on_complete callback");
487 }
488
489 s_websocket_send_op_destroy(send_op);
490
491 PyGILState_Release(state);
492 /*************** GIL RELEASE ***************/
493 }
494
495 PyObject *aws_py_websocket_send_frame(PyObject *self, PyObject *args) {
496 (void)self;
497
498 PyObject *binding_py; /* O */
499 uint8_t opcode; /* b */
500 Py_buffer payload_buffer; /* z* */
501 int fin; /* p - boolean predicate */
502 PyObject *on_complete_py; /* O */
503
504 if (!PyArg_ParseTuple(args, "Obz*pO", &binding_py, &opcode, &payload_buffer, &fin, &on_complete_py)) {
505 return NULL;
506 }
507
508 /* From hereon, we need to clean up if errors occur (Py_buffers must always be released) ... */
509
510 struct websocket_send_op *send_op = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct websocket_send_op));
511 send_op->payload_buffer = payload_buffer;
512 send_op->payload_cursor = aws_byte_cursor_from_array(payload_buffer.buf, payload_buffer.len);
513 Py_INCREF(on_complete_py);
514 send_op->on_complete_py = on_complete_py;
515
516 struct aws_websocket *websocket = PyCapsule_GetPointer(binding_py, s_websocket_capsule_name);
517 if (!websocket) {
518 goto error;
519 }
520
521 struct aws_websocket_send_frame_options options = {
522 .payload_length = (uint64_t)payload_buffer.len,
523 .user_data = send_op,
524 .stream_outgoing_payload = s_websocket_stream_outgoing_payload,
525 .on_complete = s_websocket_on_send_frame_complete,
526 .opcode = opcode,
527 .fin = fin,
528 };
529
530 if (aws_websocket_send_frame(websocket, &options)) {
531 PyErr_SetAwsLastError();
532 goto error;
533 }
534
535 /* Success! */
536 Py_RETURN_NONE;
537
538 error:
539 s_websocket_send_op_destroy(send_op);
540 return NULL;
541 }
542
543 PyObject *aws_py_websocket_increment_read_window(PyObject *self, PyObject *args) {
544 (void)self;
545
546 PyObject *binding_py; /* O */
547 Py_ssize_t size; /* n */
548
549 if (!PyArg_ParseTuple(args, "On", &binding_py, &size)) {
550 return NULL;
551 }
552
553 struct aws_websocket *websocket = PyCapsule_GetPointer(binding_py, s_websocket_capsule_name);
554 if (!websocket) {
555 return NULL;
556 }
557
558 /* already checked that size was non-negative out in python */
559 aws_websocket_increment_read_window(websocket, (size_t)size);
560 Py_RETURN_NONE;
561 }
562
563 PyObject *aws_py_websocket_create_handshake_request(PyObject *self, PyObject *args) {
564 (void)self;
565
566 struct aws_byte_cursor host; /* s# */
567 struct aws_byte_cursor path; /* s# */
568
569 if (!PyArg_ParseTuple(args, "s#s#", &host.ptr, &host.len, &path.ptr, &path.len)) {
570 return NULL;
571 }
572
573 /* This function will return a tuple containing:
574 * 1) the binding for an HttpRequest
575 * 2) the binding for an HttpHeaders */
576 bool success = false;
577 struct aws_http_message *request = NULL;
578 PyObject *tuple_py = NULL;
579
580 request = aws_http_message_new_websocket_handshake_request(aws_py_get_allocator(), path, host);
581 if (!request) {
582 PyErr_SetAwsLastError();
583 goto cleanup;
584 }
585
586 tuple_py = PyTuple_New(2);
587 if (!tuple_py) {
588 goto cleanup;
589 }
590
591 PyObject *request_binding_py = aws_py_http_message_new_request_from_native(request);
592 if (!request_binding_py) {
593 goto cleanup;
594 }
595 PyTuple_SetItem(tuple_py, 0, request_binding_py); /* steals reference to request_binding_py */
596
597 PyObject *headers_binding_py = aws_py_http_headers_new_from_native(aws_http_message_get_headers(request));
598 if (!headers_binding_py) {
599 goto cleanup;
600 }
601 PyTuple_SetItem(tuple_py, 1, headers_binding_py); /* steals reference to headers_binding_py */
602
603 /* Success! */
604 success = true;
605
606 cleanup:
607 aws_http_message_release(request);
608 if (success) {
609 return tuple_py;
610 } else {
611 Py_XDECREF(tuple_py);
612 return NULL;
613 }
614 }