Debian Codegraph @

crt/aws-c-http/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 <aws/http/private/websocket_impl.h>
7
8 #include <aws/common/atomics.h>
9 #include <aws/common/device_random.h>
10 #include <aws/common/encoding.h>
11 #include <aws/common/mutex.h>
12 #include <aws/common/ref_count.h>
13 #include <aws/http/private/websocket_decoder.h>
14 #include <aws/http/private/websocket_encoder.h>
15 #include <aws/http/request_response.h>
16 #include <aws/io/channel.h>
17 #include <aws/io/logging.h>
18
19 #include <inttypes.h>
20
21 #ifdef _MSC_VER
22 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
23 #endif
24
25 /* TODO: If something goes wrong during normal shutdown, do I change the error_code? */
26
27 struct outgoing_frame {
28 struct aws_websocket_send_frame_options def;
29 struct aws_linked_list_node node;
30 };
31
32 struct aws_websocket {
33 struct aws_allocator *alloc;
34 struct aws_ref_count ref_count;
35 struct aws_channel_handler channel_handler;
36 struct aws_channel_slot *channel_slot;
37 size_t initial_window_size;
38 bool manual_window_update;
39
40 void *user_data;
41 aws_websocket_on_incoming_frame_begin_fn *on_incoming_frame_begin;
42 aws_websocket_on_incoming_frame_payload_fn *on_incoming_frame_payload;
43 aws_websocket_on_incoming_frame_complete_fn *on_incoming_frame_complete;
44
45 struct aws_channel_task move_synced_data_to_thread_task;
46 struct aws_channel_task shutdown_channel_from_offthread_task;
47 struct aws_channel_task increment_read_window_task;
48 struct aws_channel_task waiting_on_payload_stream_task;
49 struct aws_channel_task close_timeout_task;
50 bool is_server;
51
52 /* Data that should only be accessed from the websocket's channel thread. */
53 struct {
54 struct aws_websocket_encoder encoder;
55
56 /* list of outbound frames that have yet to be encoded and sent to the socket */
57 struct aws_linked_list outgoing_frame_list;
58
59 /* current outbound frame being encoded and sent to the socket */
60 struct outgoing_frame *current_outgoing_frame;
61
62 /*
63 * list of outbound frames that have been completely written to the io message heading to the socket.
64 * When the socket write completes we can in turn invoke completion callbacks for all of these frames
65 */
66 struct aws_linked_list write_completion_frames;
67
68 struct aws_websocket_decoder decoder;
69 struct aws_websocket_incoming_frame *current_incoming_frame;
70 struct aws_websocket_incoming_frame incoming_frame_storage;
71
72 /* Payload of incoming PING frame.
73 * The PONG frame we send in response must have an identical payload */
74 struct aws_byte_buf incoming_ping_payload;
75
76 /* If current incoming frame is CONTINUATION, this is the data type it is a continuation of. */
77 enum aws_websocket_opcode continuation_of_opcode;
78
79 /* Amount to increment window after a channel message has been processed. */
80 size_t incoming_message_window_update;
81
82 /* Cached slot to right */
83 struct aws_channel_slot *last_known_right_slot;
84
85 /* True when no more frames will be read, due to:
86 * - a CLOSE frame was received
87 * - decoder error
88 * - channel shutdown in read-dir
89 * - user calling aws_websocket_close()
90 * - user dropping the last refcount
91 */
92 bool is_reading_stopped;
93
94 /* True when no more frames will be written, due to:
95 * - a CLOSE frame was sent
96 * - encoder error
97 * - channel shutdown in write-dir */
98 bool is_writing_stopped;
99
100 /* During normal shutdown websocket ensures that a CLOSE frame is sent */
101 bool is_shutting_down_and_waiting_for_close_frame_to_be_written;
102 int channel_shutdown_error_code;
103 bool channel_shutdown_free_scarce_resources_immediately;
104
105 /* Wait until each aws_io_message is completely written to
106 * the socket before sending the next aws_io_message */
107 bool is_waiting_for_write_completion;
108
109 /* If, while writing out data from a payload stream, we experience "read would block",
110 * schedule a task to try again in the near-future. */
111 bool is_waiting_on_payload_stream_task;
112
113 /* True if this websocket is being used as a dumb mid-channel handler.
114 * The websocket will no longer respond to its public API or invoke callbacks. */
115 bool is_midchannel_handler;
116 } thread_data;
117
118 /* Data that may be touched from any thread (lock must be held). */
119 struct {
120 struct aws_mutex lock;
121
122 struct aws_linked_list outgoing_frame_list;
123
124 /* If non-zero, then increment_read_window_task is scheduled */
125 size_t window_increment_size;
126
127 /* Error-code returned by aws_websocket_send_frame() when is_writing_stopped is true */
128 int send_frame_error_code;
129
130 /* Use a task to issue a channel shutdown from off-thread. */
131 int shutdown_channel_from_offthread_task_error_code;
132 bool is_shutdown_channel_from_offthread_task_scheduled;
133
134 bool is_move_synced_data_to_thread_task_scheduled;
135
136 /* Mirrors variable from thread_data */
137 bool is_midchannel_handler;
138 } synced_data;
139 };
140
141 static int s_handler_process_read_message(
142 struct aws_channel_handler *handler,
143 struct aws_channel_slot *slot,
144 struct aws_io_message *message);
145
146 static int s_handler_process_write_message(
147 struct aws_channel_handler *handler,
148 struct aws_channel_slot *slot,
149 struct aws_io_message *message);
150
151 static int s_handler_increment_read_window(
152 struct aws_channel_handler *handler,
153 struct aws_channel_slot *slot,
154 size_t size);
155
156 static int s_handler_shutdown(
157 struct aws_channel_handler *handler,
158 struct aws_channel_slot *slot,
159 enum aws_channel_direction dir,
160 int error_code,
161 bool free_scarce_resources_immediately);
162
163 static size_t s_handler_initial_window_size(struct aws_channel_handler *handler);
164 static size_t s_handler_message_overhead(struct aws_channel_handler *handler);
165 static void s_handler_destroy(struct aws_channel_handler *handler);
166 static void s_websocket_on_refcount_zero(void *user_data);
167
168 static int s_encoder_stream_outgoing_payload(struct aws_byte_buf *out_buf, void *user_data);
169
170 static int s_decoder_on_frame(const struct aws_websocket_frame *frame, void *user_data);
171 static int s_decoder_on_payload(struct aws_byte_cursor data, void *user_data);
172 static int s_decoder_on_user_payload(struct aws_websocket *websocket, struct aws_byte_cursor data);
173 static int s_decoder_on_midchannel_payload(struct aws_websocket *websocket, struct aws_byte_cursor data);
174
175 static void s_destroy_outgoing_frame(struct aws_websocket *websocket, struct outgoing_frame *frame, int error_code);
176 static void s_complete_frame_list(struct aws_websocket *websocket, struct aws_linked_list *frames, int error_code);
177 static void s_complete_incoming_frame(struct aws_websocket *websocket, int error_code, bool *out_callback_result);
178 static void s_finish_shutdown(struct aws_websocket *websocket);
179 static void s_io_message_write_completed(
180 struct aws_channel *channel,
181 struct aws_io_message *message,
182 int err_code,
183 void *user_data);
184 static int s_send_frame(
185 struct aws_websocket *websocket,
186 const struct aws_websocket_send_frame_options *options,
187 bool from_public_api);
188 static bool s_midchannel_send_payload(struct aws_websocket *websocket, struct aws_byte_buf *out_buf, void *user_data);
189 static void s_midchannel_send_complete(struct aws_websocket *websocket, int error_code, void *user_data);
190 static void s_move_synced_data_to_thread_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
191 static void s_increment_read_window_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
192 static void s_shutdown_channel_from_offthread_task(
193 struct aws_channel_task *task,
194 void *arg,
195 enum aws_task_status status);
196 static void s_waiting_on_payload_stream_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
197 static void s_close_timeout_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
198 static void s_schedule_channel_shutdown_from_offthread(struct aws_websocket *websocket, int error_code);
199 static void s_shutdown_due_to_write_err(struct aws_websocket *websocket, int error_code);
200 static void s_shutdown_due_to_read_err(struct aws_websocket *websocket, int error_code);
201 static void s_stop_writing(struct aws_websocket *websocket, int send_frame_error_code);
202 static void s_try_write_outgoing_frames(struct aws_websocket *websocket);
203
204 static struct aws_channel_handler_vtable s_channel_handler_vtable = {
205 .process_read_message = s_handler_process_read_message,
206 .process_write_message = s_handler_process_write_message,
207 .increment_read_window = s_handler_increment_read_window,
208 .shutdown = s_handler_shutdown,
209 .initial_window_size = s_handler_initial_window_size,
210 .message_overhead = s_handler_message_overhead,
211 .destroy = s_handler_destroy,
212 };
213
214 const char *aws_websocket_opcode_str(uint8_t opcode) {
215 switch (opcode) {
216 case AWS_WEBSOCKET_OPCODE_CONTINUATION:
217 return "continuation";
218 case AWS_WEBSOCKET_OPCODE_TEXT:
219 return "text";
220 case AWS_WEBSOCKET_OPCODE_BINARY:
221 return "binary";
222 case AWS_WEBSOCKET_OPCODE_CLOSE:
223 return "close";
224 case AWS_WEBSOCKET_OPCODE_PING:
225 return "ping";
226 case AWS_WEBSOCKET_OPCODE_PONG:
227 return "pong";
228 default:
229 return "";
230 }
231 }
232
233 bool aws_websocket_is_data_frame(uint8_t opcode) {
234 /* RFC-6455 Section 5.6: Most significant bit of (4 bit) data frame opcode is 0 */
235 return !(opcode & 0x08);
236 }
237
238 static void s_lock_synced_data(struct aws_websocket *websocket) {
239 int err = aws_mutex_lock(&websocket->synced_data.lock);
240 AWS_ASSERT(!err);
241 (void)err;
242 }
243
244 static void s_unlock_synced_data(struct aws_websocket *websocket) {
245 int err = aws_mutex_unlock(&websocket->synced_data.lock);
246 AWS_ASSERT(!err);
247 (void)err;
248 }
249
250 struct aws_websocket *aws_websocket_handler_new(const struct aws_websocket_handler_options *options) {
251 struct aws_channel_slot *slot = NULL;
252 struct aws_websocket *websocket = NULL;
253 int err;
254
255 slot = aws_channel_slot_new(options->channel);
256 if (!slot) {
257 goto error;
258 }
259
260 err = aws_channel_slot_insert_end(options->channel, slot);
261 if (err) {
262 goto error;
263 }
264
265 websocket = aws_mem_calloc(options->allocator, 1, sizeof(struct aws_websocket));
266 if (!websocket) {
267 goto error;
268 }
269
270 websocket->alloc = options->allocator;
271 aws_ref_count_init(&websocket->ref_count, websocket, s_websocket_on_refcount_zero);
272 websocket->channel_handler.vtable = &s_channel_handler_vtable;
273 websocket->channel_handler.alloc = options->allocator;
274 websocket->channel_handler.impl = websocket;
275
276 websocket->channel_slot = slot;
277
278 websocket->initial_window_size = options->initial_window_size;
279 websocket->manual_window_update = options->manual_window_update;
280
281 websocket->user_data = options->user_data;
282 websocket->on_incoming_frame_begin = options->on_incoming_frame_begin;
283 websocket->on_incoming_frame_payload = options->on_incoming_frame_payload;
284 websocket->on_incoming_frame_complete = options->on_incoming_frame_complete;
285
286 websocket->is_server = options->is_server;
287
288 aws_channel_task_init(
289 &websocket->move_synced_data_to_thread_task,
290 s_move_synced_data_to_thread_task,
291 websocket,
292 "websocket_move_synced_data_to_thread");
293 aws_channel_task_init(
294 &websocket->shutdown_channel_from_offthread_task,
295 s_shutdown_channel_from_offthread_task,
296 websocket,
297 "websocket_shutdown_channel");
298 aws_channel_task_init(
299 &websocket->increment_read_window_task,
300 s_increment_read_window_task,
301 websocket,
302 "websocket_increment_read_window");
303 aws_channel_task_init(
304 &websocket->waiting_on_payload_stream_task,
305 s_waiting_on_payload_stream_task,
306 websocket,
307 "websocket_waiting_on_payload_stream");
308 aws_channel_task_init(&websocket->close_timeout_task, s_close_timeout_task, websocket, "websocket_close_timeout");
309
310 aws_linked_list_init(&websocket->thread_data.outgoing_frame_list);
311 aws_linked_list_init(&websocket->thread_data.write_completion_frames);
312 aws_byte_buf_init(&websocket->thread_data.incoming_ping_payload, websocket->alloc, 0);
313
314 aws_websocket_encoder_init(&websocket->thread_data.encoder, s_encoder_stream_outgoing_payload, websocket);
315
316 aws_websocket_decoder_init(
317 &websocket->thread_data.decoder, options->allocator, s_decoder_on_frame, s_decoder_on_payload, websocket);
318
319 aws_linked_list_init(&websocket->synced_data.outgoing_frame_list);
320
321 err = aws_mutex_init(&websocket->synced_data.lock);
322 if (err) {
323 AWS_LOGF_ERROR(
324 AWS_LS_HTTP_WEBSOCKET,
325 "static: Failed to initialize mutex, error %d (%s).",
326 aws_last_error(),
327 aws_error_name(aws_last_error()));
328
329 goto error;
330 }
331
332 err = aws_channel_slot_set_handler(slot, &websocket->channel_handler);
333 if (err) {
334 goto error;
335 }
336
337 /* Ensure websocket (and the rest of the channel) can't be destroyed until aws_websocket_release() is called */
338 aws_channel_acquire_hold(options->channel);
339
340 return websocket;
341
342 error:
343 if (slot) {
344 if (websocket && !slot->handler) {
345 websocket->channel_handler.vtable->destroy(&websocket->channel_handler);
346 }
347 aws_channel_slot_remove(slot);
348 }
349 return NULL;
350 }
351
352 static void s_handler_destroy(struct aws_channel_handler *handler) {
353 struct aws_websocket *websocket = handler->impl;
354 AWS_ASSERT(!websocket->thread_data.current_outgoing_frame);
355 AWS_ASSERT(!websocket->thread_data.current_incoming_frame);
356
357 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Destroying websocket.", (void *)websocket);
358
359 aws_websocket_decoder_clean_up(&websocket->thread_data.decoder);
360 aws_byte_buf_clean_up(&websocket->thread_data.incoming_ping_payload);
361 aws_mutex_clean_up(&websocket->synced_data.lock);
362 aws_mem_release(websocket->alloc, websocket);
363 }
364
365 struct aws_websocket *aws_websocket_acquire(struct aws_websocket *websocket) {
366 AWS_PRECONDITION(websocket);
367 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Acquiring websocket ref-count.", (void *)websocket);
368 aws_ref_count_acquire(&websocket->ref_count);
369 return websocket;
370 }
371
372 void aws_websocket_release(struct aws_websocket *websocket) {
373 if (!websocket) {
374 return;
375 }
376
377 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Releasing websocket ref-count.", (void *)websocket);
378 aws_ref_count_release(&websocket->ref_count);
379 }
380
381 static void s_websocket_on_refcount_zero(void *user_data) {
382 struct aws_websocket *websocket = user_data;
383 AWS_ASSERT(websocket->channel_slot);
384
385 AWS_LOGF_TRACE(
386 AWS_LS_HTTP_WEBSOCKET, "id=%p: Websocket ref-count is zero, shut down if necessary.", (void *)websocket);
387
388 /* Channel might already be shut down, but make sure */
389 s_schedule_channel_shutdown_from_offthread(websocket, AWS_ERROR_SUCCESS);
390
391 /* Channel won't destroy its slots/handlers until its refcount reaches 0 */
392 aws_channel_release_hold(websocket->channel_slot->channel);
393 }
394
395 struct aws_channel *aws_websocket_get_channel(const struct aws_websocket *websocket) {
396 return websocket->channel_slot->channel;
397 }
398
399 int aws_websocket_convert_to_midchannel_handler(struct aws_websocket *websocket) {
400 if (!aws_channel_thread_is_callers_thread(websocket->channel_slot->channel)) {
401 AWS_LOGF_ERROR(
402 AWS_LS_HTTP_WEBSOCKET, "id=%p: Cannot convert to midchannel handler on this thread.", (void *)websocket);
403 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
404 }
405
406 if (websocket->thread_data.is_midchannel_handler) {
407 AWS_LOGF_ERROR(
408 AWS_LS_HTTP_WEBSOCKET, "id=%p: Websocket has already converted to midchannel handler.", (void *)websocket);
409 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_IS_MIDCHANNEL_HANDLER);
410 }
411
412 if (websocket->thread_data.is_reading_stopped || websocket->thread_data.is_writing_stopped) {
413 AWS_LOGF_ERROR(
414 AWS_LS_HTTP_WEBSOCKET,
415 "id=%p: Cannot convert websocket to midchannel handler because it is closed or closing.",
416 (void *)websocket);
417 return aws_raise_error(AWS_ERROR_HTTP_CONNECTION_CLOSED);
418 }
419
420 if (websocket->thread_data.current_incoming_frame) {
421 AWS_LOGF_ERROR(
422 AWS_LS_HTTP_WEBSOCKET,
423 "id=%p: Cannot convert to midchannel handler in the middle of an incoming frame.",
424 (void *)websocket);
425 return aws_raise_error(AWS_ERROR_INVALID_STATE);
426 }
427
428 websocket->thread_data.is_midchannel_handler = true;
429
430 return AWS_OP_SUCCESS;
431 }
432
433 static int s_send_frame(
434 struct aws_websocket *websocket,
435 const struct aws_websocket_send_frame_options *options,
436 bool from_public_api) {
437
438 AWS_ASSERT(websocket);
439 AWS_ASSERT(options);
440
441 /* Check for bad input. Log about non-obvious errors. */
442 if (options->payload_length > 0 && !options->stream_outgoing_payload) {
443 AWS_LOGF_ERROR(
444 AWS_LS_HTTP_WEBSOCKET,
445 "id=%p: Invalid frame options, payload streaming function required when payload length is non-zero.",
446 (void *)websocket);
447 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
448 }
449
450 struct outgoing_frame *frame = aws_mem_calloc(websocket->alloc, 1, sizeof(struct outgoing_frame));
451 if (!frame) {
452 return AWS_OP_ERR;
453 }
454
455 frame->def = *options;
456
457 /* Enqueue frame, unless no further sending is allowed. */
458 int send_error = 0;
459 bool should_schedule_task = false;
460
461 /* BEGIN CRITICAL SECTION */
462 s_lock_synced_data(websocket);
463
464 if (websocket->synced_data.is_midchannel_handler && from_public_api) {
465 send_error = AWS_ERROR_HTTP_WEBSOCKET_IS_MIDCHANNEL_HANDLER;
466 } else if (websocket->synced_data.send_frame_error_code) {
467 send_error = websocket->synced_data.send_frame_error_code;
468 } else {
469 aws_linked_list_push_back(&websocket->synced_data.outgoing_frame_list, &frame->node);
470 if (!websocket->synced_data.is_move_synced_data_to_thread_task_scheduled) {
471 websocket->synced_data.is_move_synced_data_to_thread_task_scheduled = true;
472 should_schedule_task = true;
473 }
474 }
475
476 s_unlock_synced_data(websocket);
477 /* END CRITICAL SECTION */
478
479 if (send_error) {
480 AWS_LOGF_ERROR(
481 AWS_LS_HTTP_WEBSOCKET,
482 "id=%p: Cannot send frame, error %d (%s).",
483 (void *)websocket,
484 send_error,
485 aws_error_name(send_error));
486
487 aws_mem_release(websocket->alloc, frame);
488 return aws_raise_error(send_error);
489 }
490
491 AWS_LOGF_DEBUG(
492 AWS_LS_HTTP_WEBSOCKET,
493 "id=%p: Enqueuing outgoing frame with opcode=%" PRIu8 "(%s) length=%" PRIu64 " fin=%s",
494 (void *)websocket,
495 options->opcode,
496 aws_websocket_opcode_str(options->opcode),
497 options->payload_length,
498 options->fin ? "T" : "F");
499
500 if (should_schedule_task) {
501 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Scheduling synced data task.", (void *)websocket);
502 aws_channel_schedule_task_now(websocket->channel_slot->channel, &websocket->move_synced_data_to_thread_task);
503 }
504
505 return AWS_OP_SUCCESS;
506 }
507
508 int aws_websocket_send_frame(struct aws_websocket *websocket, const struct aws_websocket_send_frame_options *options) {
509 return s_send_frame(websocket, options, true);
510 }
511
512 static void s_move_synced_data_to_thread_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
513 (void)task;
514 if (status != AWS_TASK_STATUS_RUN_READY) {
515 return;
516 }
517
518 struct aws_websocket *websocket = arg;
519 struct aws_linked_list tmp_list;
520 aws_linked_list_init(&tmp_list);
521
522 /* BEGIN CRITICAL SECTION */
523 s_lock_synced_data(websocket);
524
525 aws_linked_list_swap_contents(&websocket->synced_data.outgoing_frame_list, &tmp_list);
526
527 websocket->synced_data.is_move_synced_data_to_thread_task_scheduled = false;
528
529 s_unlock_synced_data(websocket);
530 /* END CRITICAL SECTION */
531
532 if (!aws_linked_list_empty(&tmp_list)) {
533 aws_linked_list_move_all_back(&websocket->thread_data.outgoing_frame_list, &tmp_list);
534 s_try_write_outgoing_frames(websocket);
535 }
536 }
537
538 static void s_try_write_outgoing_frames(struct aws_websocket *websocket) {
539 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
540 int err;
541
542 /* Check whether we should be writing data */
543 if (!websocket->thread_data.current_outgoing_frame &&
544 aws_linked_list_empty(&websocket->thread_data.outgoing_frame_list)) {
545
546 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: No data to write at this time.", (void *)websocket);
547 return;
548 }
549
550 if (websocket->thread_data.is_waiting_for_write_completion) {
551 AWS_LOGF_TRACE(
552 AWS_LS_HTTP_WEBSOCKET,
553 "id=%p: Waiting until outstanding aws_io_message is written to socket before sending more data.",
554 (void *)websocket);
555 return;
556 }
557
558 if (websocket->thread_data.is_writing_stopped) {
559 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Websocket is no longer sending data.", (void *)websocket);
560 return;
561 }
562
563 /* Acquire aws_io_message */
564 struct aws_io_message *io_msg = aws_channel_slot_acquire_max_message_for_write(websocket->channel_slot);
565 if (!io_msg) {
566 AWS_LOGF_ERROR(
567 AWS_LS_HTTP_WEBSOCKET,
568 "id=%p: Failed acquire message from pool, error %d (%s).",
569 (void *)websocket,
570 aws_last_error(),
571 aws_error_name(aws_last_error()));
572 goto error;
573 }
574
575 io_msg->user_data = websocket;
576 io_msg->on_completion = s_io_message_write_completed;
577
578 /* Loop through frames, writing their data into the io_msg */
579 bool wrote_close_frame = false;
580 while (!websocket->thread_data.is_writing_stopped) {
581 if (websocket->thread_data.current_outgoing_frame) {
582 AWS_LOGF_TRACE(
583 AWS_LS_HTTP_WEBSOCKET,
584 "id=%p: Resuming write of frame=%p opcode=%" PRIu8 "(%s) payload-length=%" PRIu64 ".",
585 (void *)websocket,
586 (void *)websocket->thread_data.current_outgoing_frame,
587 websocket->thread_data.current_outgoing_frame->def.opcode,
588 aws_websocket_opcode_str(websocket->thread_data.current_outgoing_frame->def.opcode),
589 websocket->thread_data.current_outgoing_frame->def.payload_length);
590
591 } else {
592 /* We're not in the middle of encoding a frame, so pop off the next one to encode. */
593 if (aws_linked_list_empty(&websocket->thread_data.outgoing_frame_list)) {
594 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: No more frames to write.", (void *)websocket);
595 break;
596 }
597
598 struct aws_linked_list_node *node = aws_linked_list_pop_front(&websocket->thread_data.outgoing_frame_list);
599 websocket->thread_data.current_outgoing_frame = AWS_CONTAINER_OF(node, struct outgoing_frame, node);
600
601 struct aws_websocket_frame frame = {
602 .fin = websocket->thread_data.current_outgoing_frame->def.fin,
603 .opcode = websocket->thread_data.current_outgoing_frame->def.opcode,
604 .payload_length = websocket->thread_data.current_outgoing_frame->def.payload_length,
605 };
606
607 /* RFC-6455 Section 5.3 Client-to-Server Masking
608 * Clients must mask payload with key derived from an unpredictable source of entropy. */
609 if (!websocket->is_server) {
610 frame.masked = true;
611 /* TODO: faster source of random (but still seeded by device_random) */
612 struct aws_byte_buf masking_key_buf = aws_byte_buf_from_empty_array(frame.masking_key, 4);
613 err = aws_device_random_buffer(&masking_key_buf);
614 if (err) {
615 AWS_LOGF_ERROR(
616 AWS_LS_HTTP_WEBSOCKET,
617 "id=%p: Failed to derive masking key, error %d (%s).",
618 (void *)websocket,
619 aws_last_error(),
620 aws_error_name(aws_last_error()));
621 goto error;
622 }
623 }
624
625 err = aws_websocket_encoder_start_frame(&websocket->thread_data.encoder, &frame);
626 if (err) {
627 AWS_LOGF_ERROR(
628 AWS_LS_HTTP_WEBSOCKET,
629 "id=%p: Failed to start frame encoding, error %d (%s).",
630 (void *)websocket,
631 aws_last_error(),
632 aws_error_name(aws_last_error()));
633 goto error;
634 }
635
636 AWS_LOGF_TRACE(
637 AWS_LS_HTTP_WEBSOCKET,
638 "id=%p: Start writing frame=%p opcode=%" PRIu8 "(%s) payload-length=%" PRIu64 ".",
639 (void *)websocket,
640 (void *)websocket->thread_data.current_outgoing_frame,
641 websocket->thread_data.current_outgoing_frame->def.opcode,
642 aws_websocket_opcode_str(websocket->thread_data.current_outgoing_frame->def.opcode),
643 websocket->thread_data.current_outgoing_frame->def.payload_length);
644 }
645
646 err = aws_websocket_encoder_process(&websocket->thread_data.encoder, &io_msg->message_data);
647 if (err) {
648 AWS_LOGF_ERROR(
649 AWS_LS_HTTP_WEBSOCKET,
650 "id=%p: Frame encoding failed with error %d (%s).",
651 (void *)websocket,
652 aws_last_error(),
653 aws_error_name(aws_last_error()));
654 goto error;
655 }
656
657 if (aws_websocket_encoder_is_frame_in_progress(&websocket->thread_data.encoder)) {
658 AWS_LOGF_TRACE(
659 AWS_LS_HTTP_WEBSOCKET,
660 "id=%p: Outgoing frame still in progress, but no more data can be written at this time.",
661 (void *)websocket);
662 break;
663 }
664
665 if (websocket->thread_data.current_outgoing_frame->def.opcode == AWS_WEBSOCKET_OPCODE_CLOSE) {
666 wrote_close_frame = true;
667 }
668
669 /*
670 * a completely-written frame gets added to the write completion list so that when the socket write completes
671 * we can complete all of the outbound frames that were finished as part of the io message
672 */
673 aws_linked_list_push_back(
674 &websocket->thread_data.write_completion_frames, &websocket->thread_data.current_outgoing_frame->node);
675
676 websocket->thread_data.current_outgoing_frame = NULL;
677
678 if (wrote_close_frame) {
679 break;
680 }
681 }
682
683 /* If payload stream didn't have any bytes available to read right now, then the aws_io_message might be empty.
684 * If this is the case schedule a task to try again in the future. */
685 if (io_msg->message_data.len == 0) {
686 AWS_LOGF_TRACE(
687 AWS_LS_HTTP_WEBSOCKET,
688 "id=%p: Reading from payload stream would block, will try again later.",
689 (void *)websocket);
690
691 if (!websocket->thread_data.is_waiting_on_payload_stream_task) {
692 websocket->thread_data.is_waiting_on_payload_stream_task = true;
693
694 /* Future Optimization Idea: Minimize work while we wait. Use some kind of backoff for the retry timing,
695 * or have some way for stream to notify when more data is available. */
696 aws_channel_schedule_task_now(websocket->channel_slot->channel, &websocket->waiting_on_payload_stream_task);
697 }
698
699 aws_mem_release(io_msg->allocator, io_msg);
700 return;
701 }
702
703 /* Prepare to send aws_io_message up the channel. */
704
705 /* If CLOSE frame was written, that's the last data we'll write */
706 if (wrote_close_frame) {
707 s_stop_writing(websocket, AWS_ERROR_HTTP_WEBSOCKET_CLOSE_FRAME_SENT);
708 }
709
710 AWS_LOGF_TRACE(
711 AWS_LS_HTTP_WEBSOCKET,
712 "id=%p: Sending aws_io_message of size %zu in write direction.",
713 (void *)websocket,
714 io_msg->message_data.len);
715
716 websocket->thread_data.is_waiting_for_write_completion = true;
717 err = aws_channel_slot_send_message(websocket->channel_slot, io_msg, AWS_CHANNEL_DIR_WRITE);
718 if (err) {
719 websocket->thread_data.is_waiting_for_write_completion = false;
720 AWS_LOGF_ERROR(
721 AWS_LS_HTTP_WEBSOCKET,
722 "id=%p: Failed to send message in write direction, error %d (%s).",
723 (void *)websocket,
724 aws_last_error(),
725 aws_error_name(aws_last_error()));
726 goto error;
727 }
728
729 /* Finish shutdown if we were waiting for the CLOSE frame to be written */
730 if (wrote_close_frame && websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written) {
731 AWS_LOGF_TRACE(
732 AWS_LS_HTTP_WEBSOCKET, "id=%p: CLOSE frame sent, finishing handler shutdown sequence.", (void *)websocket);
733
734 s_finish_shutdown(websocket);
735 }
736
737 return;
738
739 error:
740 if (io_msg) {
741 aws_mem_release(io_msg->allocator, io_msg);
742 }
743
744 s_shutdown_due_to_write_err(websocket, aws_last_error());
745 }
746
747 /* Encoder's outgoing_payload callback invokes current frame's callback */
748 static int s_encoder_stream_outgoing_payload(struct aws_byte_buf *out_buf, void *user_data) {
749 struct aws_websocket *websocket = user_data;
750 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
751 AWS_ASSERT(websocket->thread_data.current_outgoing_frame);
752
753 struct outgoing_frame *current_frame = websocket->thread_data.current_outgoing_frame;
754 AWS_ASSERT(current_frame->def.stream_outgoing_payload);
755
756 bool callback_result = current_frame->def.stream_outgoing_payload(websocket, out_buf, current_frame->def.user_data);
757 if (!callback_result) {
758 AWS_LOGF_ERROR(
759 AWS_LS_HTTP_WEBSOCKET, "id=%p: Outgoing payload callback has reported a failure.", (void *)websocket);
760 return aws_raise_error(AWS_ERROR_HTTP_CALLBACK_FAILURE);
761 }
762
763 return AWS_OP_SUCCESS;
764 }
765
766 static void s_waiting_on_payload_stream_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
767 (void)task;
768 if (status != AWS_TASK_STATUS_RUN_READY) {
769 /* If channel has shut down, don't need to resume sending payload */
770 return;
771 }
772
773 struct aws_websocket *websocket = arg;
774 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
775
776 AWS_LOGF_TRACE(
777 AWS_LS_HTTP_WEBSOCKET, "id=%p: Done waiting for payload stream, sending more data...", (void *)websocket);
778
779 websocket->thread_data.is_waiting_on_payload_stream_task = false;
780 s_try_write_outgoing_frames(websocket);
781 }
782
783 static void s_io_message_write_completed(
784 struct aws_channel *channel,
785 struct aws_io_message *message,
786 int err_code,
787 void *user_data) {
788
789 (void)channel;
790 (void)message;
791 struct aws_websocket *websocket = user_data;
792 AWS_ASSERT(aws_channel_thread_is_callers_thread(channel));
793
794 /*
795 * Invoke the completion callbacks (and then destroy) for all the frames that were completely written as
796 * part of this message completion at the socket layer
797 */
798 s_complete_frame_list(websocket, &websocket->thread_data.write_completion_frames, err_code);
799
800 if (err_code == AWS_ERROR_SUCCESS) {
801 AWS_LOGF_TRACE(
802 AWS_LS_HTTP_WEBSOCKET, "id=%p: aws_io_message written to socket, sending more data...", (void *)websocket);
803
804 websocket->thread_data.is_waiting_for_write_completion = false;
805 s_try_write_outgoing_frames(websocket);
806 } else {
807 AWS_LOGF_TRACE(
808 AWS_LS_HTTP_WEBSOCKET,
809 "id=%p: aws_io_message did not finish writing to socket, error %d (%s).",
810 (void *)websocket,
811 err_code,
812 aws_error_name(err_code));
813
814 s_shutdown_due_to_write_err(websocket, err_code);
815 }
816 }
817
818 static int s_handler_process_write_message(
819 struct aws_channel_handler *handler,
820 struct aws_channel_slot *slot,
821 struct aws_io_message *message) {
822
823 (void)slot;
824 struct aws_websocket *websocket = handler->impl;
825 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
826
827 /* For each aws_io_message headed in the write direction, send a BINARY frame,
828 * where the frame's payload is the data from this aws_io_message. */
829 struct aws_websocket_send_frame_options options = {
830 .payload_length = message->message_data.len,
831 .user_data = message,
832 .stream_outgoing_payload = s_midchannel_send_payload,
833 .on_complete = s_midchannel_send_complete,
834 .opcode = AWS_WEBSOCKET_OPCODE_BINARY,
835 .fin = true,
836 };
837
838 /* Use copy_mark to track progress as the data is streamed out */
839 message->copy_mark = 0;
840
841 int err = s_send_frame(websocket, &options, false);
842 if (err) {
843 return AWS_OP_ERR;
844 }
845
846 return AWS_OP_SUCCESS;
847 }
848
849 /* Callback for writing data from downstream aws_io_messages into payload of BINARY frames headed upstream */
850 static bool s_midchannel_send_payload(struct aws_websocket *websocket, struct aws_byte_buf *out_buf, void *user_data) {
851 (void)websocket;
852 struct aws_io_message *io_msg = user_data;
853
854 /* copy_mark is used to track progress */
855 size_t src_available = io_msg->message_data.len - io_msg->copy_mark;
856 size_t dst_available = out_buf->capacity - out_buf->len;
857 size_t sending = dst_available < src_available ? dst_available : src_available;
858
859 bool success = aws_byte_buf_write(out_buf, io_msg->message_data.buffer + io_msg->copy_mark, sending);
860
861 io_msg->copy_mark += sending;
862 return success;
863 }
864
865 /* Callback when data from downstream aws_io_messages, finishes being sent as a BINARY frame upstream. */
866 static void s_midchannel_send_complete(struct aws_websocket *websocket, int error_code, void *user_data) {
867 (void)websocket;
868 struct aws_io_message *io_msg = user_data;
869
870 if (io_msg->on_completion) {
871 io_msg->on_completion(io_msg->owning_channel, io_msg, error_code, io_msg->user_data);
872 }
873
874 aws_mem_release(io_msg->allocator, io_msg);
875 }
876
877 static void s_destroy_outgoing_frame(struct aws_websocket *websocket, struct outgoing_frame *frame, int error_code) {
878 AWS_LOGF_TRACE(
879 AWS_LS_HTTP_WEBSOCKET,
880 "id=%p: Completed outgoing frame=%p opcode=%" PRIu8 "(%s) payload-length=%" PRIu64 " with error_code %d (%s).",
881 (void *)websocket,
882 (void *)frame,
883 frame->def.opcode,
884 aws_websocket_opcode_str(frame->def.opcode),
885 frame->def.payload_length,
886 error_code,
887 aws_error_name(error_code));
888
889 if (frame->def.on_complete) {
890 frame->def.on_complete(websocket, error_code, frame->def.user_data);
891 }
892
893 aws_mem_release(websocket->alloc, frame);
894 }
895
896 static void s_complete_frame_list(struct aws_websocket *websocket, struct aws_linked_list *frames, int error_code) {
897 struct aws_linked_list_node *node = aws_linked_list_begin(frames);
898 while (node != aws_linked_list_end(frames)) {
899 struct outgoing_frame *frame = AWS_CONTAINER_OF(node, struct outgoing_frame, node);
900
901 node = aws_linked_list_next(node);
902 s_destroy_outgoing_frame(websocket, frame, error_code);
903 }
904
905 /* we've released everything, so reset the list to empty */
906 aws_linked_list_init(frames);
907 }
908
909 /* Set is_reading_stopped = true, all further read data will be ignored.
910 * But also increment the read window, so that channel shutdown won't deadlock
911 * due to pending read-data in an upstream handler or the underlying OS socket. */
912 static void s_stop_reading_and_dont_block_shutdown(struct aws_websocket *websocket) {
913 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
914 if (websocket->thread_data.is_reading_stopped) {
915 return;
916 }
917
918 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Websocket will ignore any further read data.", (void *)websocket);
919 websocket->thread_data.is_reading_stopped = true;
920
921 aws_channel_slot_increment_read_window(websocket->channel_slot, SIZE_MAX);
922 }
923
924 static void s_stop_writing(struct aws_websocket *websocket, int send_frame_error_code) {
925 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
926 AWS_ASSERT(send_frame_error_code != AWS_ERROR_SUCCESS);
927
928 if (websocket->thread_data.is_writing_stopped) {
929 return;
930 }
931
932 AWS_LOGF_TRACE(
933 AWS_LS_HTTP_WEBSOCKET,
934 "id=%p: Websocket will send no more data, future attempts to send will get error %d (%s).",
935 (void *)websocket,
936 send_frame_error_code,
937 aws_error_name(send_frame_error_code));
938
939 /* BEGIN CRITICAL SECTION */
940 s_lock_synced_data(websocket);
941
942 websocket->synced_data.send_frame_error_code = send_frame_error_code;
943
944 s_unlock_synced_data(websocket);
945 /* END CRITICAL SECTION */
946
947 websocket->thread_data.is_writing_stopped = true;
948 }
949
950 static void s_shutdown_due_to_write_err(struct aws_websocket *websocket, int error_code) {
951 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
952
953 /* No more writing allowed (it's ok to call this redundantly). */
954 s_stop_writing(websocket, AWS_ERROR_HTTP_CONNECTION_CLOSED);
955
956 /* If there's a current outgoing frame, complete it with the specific error code.
957 * Any other pending frames will complete with the generic CONNECTION_CLOSED error. */
958 if (websocket->thread_data.current_outgoing_frame) {
959 s_destroy_outgoing_frame(websocket, websocket->thread_data.current_outgoing_frame, error_code);
960 websocket->thread_data.current_outgoing_frame = NULL;
961 }
962
963 /* If we're in the final stages of shutdown, ensure shutdown completes.
964 * Otherwise tell the channel to shutdown (it's ok to shutdown the channel redundantly). */
965 if (websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written) {
966 s_finish_shutdown(websocket);
967 } else {
968 AWS_LOGF_ERROR(
969 AWS_LS_HTTP_WEBSOCKET,
970 "id=%p: Closing websocket due to failure during write, error %d (%s).",
971 (void *)websocket,
972 error_code,
973 aws_error_name(error_code));
974 aws_channel_shutdown(websocket->channel_slot->channel, error_code);
975 }
976 }
977
978 static void s_shutdown_due_to_read_err(struct aws_websocket *websocket, int error_code) {
979 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
980
981 AWS_LOGF_ERROR(
982 AWS_LS_HTTP_WEBSOCKET,
983 "id=%p: Closing websocket due to failure during read, error %d (%s).",
984 (void *)websocket,
985 error_code,
986 aws_error_name(error_code));
987
988 s_stop_reading_and_dont_block_shutdown(websocket);
989
990 /* If there's a current incoming frame, complete it with the specific error code. */
991 if (websocket->thread_data.current_incoming_frame) {
992 s_complete_incoming_frame(websocket, error_code, NULL);
993 }
994
995 /* Tell channel to shutdown (it's ok to call this redundantly) */
996 aws_channel_shutdown(websocket->channel_slot->channel, error_code);
997 }
998
999 static void s_shutdown_channel_from_offthread_task(
1000 struct aws_channel_task *task,
1001 void *arg,
1002 enum aws_task_status status) {
1003
1004 (void)task;
1005
1006 if (status != AWS_TASK_STATUS_RUN_READY) {
1007 return;
1008 }
1009
1010 struct aws_websocket *websocket = arg;
1011 int error_code;
1012
1013 /* BEGIN CRITICAL SECTION */
1014 s_lock_synced_data(websocket);
1015
1016 error_code = websocket->synced_data.shutdown_channel_from_offthread_task_error_code;
1017
1018 s_unlock_synced_data(websocket);
1019 /* END CRITICAL SECTION */
1020
1021 /* Stop reading, so that shutdown won't be blocked.
1022 * If something off-thread is causing shutdown (aws_websocket_close(), refcount 0, etc),
1023 * the user may never interact with the websocket again. We can't rely on them
1024 * to keep the window open and prevent deadlock during shutdown. */
1025 s_stop_reading_and_dont_block_shutdown(websocket);
1026
1027 aws_channel_shutdown(websocket->channel_slot->channel, error_code);
1028 }
1029
1030 /* Tell the channel to shut down, from off-thread. It is safe to call this multiple times. */
1031 static void s_schedule_channel_shutdown_from_offthread(struct aws_websocket *websocket, int error_code) {
1032 bool schedule_shutdown = false;
1033
1034 /* BEGIN CRITICAL SECTION */
1035 s_lock_synced_data(websocket);
1036
1037 if (!websocket->synced_data.is_shutdown_channel_from_offthread_task_scheduled) {
1038 schedule_shutdown = true;
1039 websocket->synced_data.is_shutdown_channel_from_offthread_task_scheduled = true;
1040 websocket->synced_data.shutdown_channel_from_offthread_task_error_code = error_code;
1041 }
1042
1043 s_unlock_synced_data(websocket);
1044 /* END CRITICAL SECTION */
1045
1046 if (schedule_shutdown) {
1047 aws_channel_schedule_task_now(
1048 websocket->channel_slot->channel, &websocket->shutdown_channel_from_offthread_task);
1049 }
1050 }
1051
1052 void aws_websocket_close(struct aws_websocket *websocket, bool free_scarce_resources_immediately) {
1053 bool is_midchannel_handler;
1054
1055 /* BEGIN CRITICAL SECTION */
1056 s_lock_synced_data(websocket);
1057 is_midchannel_handler = websocket->synced_data.is_midchannel_handler;
1058 s_unlock_synced_data(websocket);
1059 /* END CRITICAL SECTION */
1060
1061 if (is_midchannel_handler) {
1062 AWS_LOGF_ERROR(
1063 AWS_LS_HTTP_WEBSOCKET,
1064 "id=%p: Ignoring close call, websocket has converted to midchannel handler.",
1065 (void *)websocket);
1066 return;
1067 }
1068
1069 /* TODO: aws_channel_shutdown() should let users specify error_code and "immediate" as separate parameters. */
1070 int error_code = AWS_ERROR_SUCCESS;
1071 if (free_scarce_resources_immediately) {
1072 error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
1073 }
1074
1075 s_schedule_channel_shutdown_from_offthread(websocket, error_code);
1076 }
1077
1078 static int s_handler_shutdown(
1079 struct aws_channel_handler *handler,
1080 struct aws_channel_slot *slot,
1081 enum aws_channel_direction dir,
1082 int error_code,
1083 bool free_scarce_resources_immediately) {
1084
1085 AWS_ASSERT(aws_channel_thread_is_callers_thread(slot->channel));
1086 struct aws_websocket *websocket = handler->impl;
1087 int err;
1088
1089 AWS_LOGF_DEBUG(
1090 AWS_LS_HTTP_WEBSOCKET,
1091 "id=%p: Websocket handler shutting down dir=%s error_code=%d immediate=%d.",
1092 (void *)websocket,
1093 dir == AWS_CHANNEL_DIR_READ ? "READ" : "WRITE",
1094 error_code,
1095 free_scarce_resources_immediately);
1096
1097 if (dir == AWS_CHANNEL_DIR_READ) {
1098 /* Shutdown in the read direction is immediate and simple. */
1099 websocket->thread_data.is_reading_stopped = true;
1100 aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
1101
1102 } else {
1103 websocket->thread_data.channel_shutdown_error_code = error_code;
1104 websocket->thread_data.channel_shutdown_free_scarce_resources_immediately = free_scarce_resources_immediately;
1105 websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written = true;
1106
1107 if (websocket->thread_data.channel_shutdown_free_scarce_resources_immediately ||
1108 websocket->thread_data.is_writing_stopped) {
1109
1110 AWS_LOGF_TRACE(
1111 AWS_LS_HTTP_WEBSOCKET,
1112 "id=%p: Finishing handler shutdown immediately, without ensuring a CLOSE frame was sent.",
1113 (void *)websocket);
1114
1115 s_stop_writing(websocket, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1116 s_finish_shutdown(websocket);
1117 } else {
1118 /* Attempt to queue a CLOSE frame, then wait for it to send before finishing shutdown. */
1119 struct aws_websocket_send_frame_options close_frame = {
1120 .opcode = AWS_WEBSOCKET_OPCODE_CLOSE,
1121 .fin = true,
1122 };
1123 err = s_send_frame(websocket, &close_frame, false);
1124 if (err) {
1125 AWS_LOGF_WARN(
1126 AWS_LS_HTTP_WEBSOCKET,
1127 "id=%p: Failed to send CLOSE frame, error %d (%s).",
1128 (void *)websocket,
1129 aws_last_error(),
1130 aws_error_name(aws_last_error()));
1131
1132 s_stop_writing(websocket, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1133 s_finish_shutdown(websocket);
1134 } else {
1135 AWS_LOGF_TRACE(
1136 AWS_LS_HTTP_WEBSOCKET,
1137 "id=%p: Outgoing CLOSE frame queued, handler will finish shutdown once it's sent.",
1138 (void *)websocket);
1139 /* schedule a task to run after 1 sec. If the CLOSE still not sent at that time, we should just cancel
1140 * sending it and shutdown the channel. */
1141 uint64_t schedule_time = 0;
1142 aws_channel_current_clock_time(websocket->channel_slot->channel, &schedule_time);
1143 schedule_time += AWS_WEBSOCKET_CLOSE_TIMEOUT;
1144 AWS_LOGF_TRACE(
1145 AWS_LS_HTTP_WEBSOCKET,
1146 "id=%p: websocket_close_timeout task will be run at timestamp %" PRIu64,
1147 (void *)websocket,
1148 schedule_time);
1149 aws_channel_schedule_task_future(
1150 websocket->channel_slot->channel, &websocket->close_timeout_task, schedule_time);
1151 }
1152 }
1153 }
1154
1155 return AWS_OP_SUCCESS;
1156 }
1157
1158 static void s_close_timeout_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
1159 (void)task;
1160 if (status != AWS_TASK_STATUS_RUN_READY) {
1161 /* If channel has shut down, don't need to resume sending payload */
1162 return;
1163 }
1164
1165 struct aws_websocket *websocket = arg;
1166 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
1167
1168 if (!websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written) {
1169 /* Not waiting for write to complete, which means the CLOSE frame has sent, just do nothing */
1170 return;
1171 }
1172
1173 AWS_LOGF_WARN(
1174 AWS_LS_HTTP_WEBSOCKET,
1175 "id=%p: Failed to send CLOSE frame, timeout happened, shutdown the channel",
1176 (void *)websocket);
1177
1178 s_stop_writing(websocket, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1179 s_finish_shutdown(websocket);
1180 }
1181
1182 static void s_finish_shutdown(struct aws_websocket *websocket) {
1183 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
1184 AWS_ASSERT(websocket->thread_data.is_writing_stopped);
1185 AWS_ASSERT(websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written);
1186
1187 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Finishing websocket handler shutdown.", (void *)websocket);
1188
1189 websocket->thread_data.is_shutting_down_and_waiting_for_close_frame_to_be_written = false;
1190
1191 /* Cancel all incomplete frames */
1192 if (websocket->thread_data.current_incoming_frame) {
1193 s_complete_incoming_frame(websocket, AWS_ERROR_HTTP_CONNECTION_CLOSED, NULL);
1194 }
1195
1196 if (websocket->thread_data.current_outgoing_frame) {
1197 s_destroy_outgoing_frame(
1198 websocket, websocket->thread_data.current_outgoing_frame, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1199 websocket->thread_data.current_outgoing_frame = NULL;
1200 }
1201
1202 /* BEGIN CRITICAL SECTION */
1203 s_lock_synced_data(websocket);
1204
1205 while (!aws_linked_list_empty(&websocket->synced_data.outgoing_frame_list)) {
1206 /* Move frames from synced_data to thread_data, then cancel them together outside critical section */
1207 struct aws_linked_list_node *node = aws_linked_list_pop_front(&websocket->synced_data.outgoing_frame_list);
1208 aws_linked_list_push_back(&websocket->thread_data.outgoing_frame_list, node);
1209 }
1210
1211 s_unlock_synced_data(websocket);
1212 /* END CRITICAL SECTION */
1213
1214 s_complete_frame_list(websocket, &websocket->thread_data.write_completion_frames, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1215
1216 while (!aws_linked_list_empty(&websocket->thread_data.outgoing_frame_list)) {
1217 struct aws_linked_list_node *node = aws_linked_list_pop_front(&websocket->thread_data.outgoing_frame_list);
1218 struct outgoing_frame *frame = AWS_CONTAINER_OF(node, struct outgoing_frame, node);
1219 s_destroy_outgoing_frame(websocket, frame, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1220 }
1221
1222 aws_channel_slot_on_handler_shutdown_complete(
1223 websocket->channel_slot,
1224 AWS_CHANNEL_DIR_WRITE,
1225 websocket->thread_data.channel_shutdown_error_code,
1226 websocket->thread_data.channel_shutdown_free_scarce_resources_immediately);
1227 }
1228
1229 static int s_handler_process_read_message(
1230 struct aws_channel_handler *handler,
1231 struct aws_channel_slot *slot,
1232 struct aws_io_message *message) {
1233
1234 AWS_ASSERT(message);
1235 AWS_ASSERT(aws_channel_thread_is_callers_thread(slot->channel));
1236 struct aws_websocket *websocket = handler->impl;
1237 struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(&message->message_data);
1238 int err;
1239
1240 /* At the end of this function we'll bump the window back up by this amount.
1241 * We start off assuming we'll re-open the window by the whole amount,
1242 * but this number will go down if we process any payload data that ought to shrink the window */
1243 websocket->thread_data.incoming_message_window_update = message->message_data.len;
1244
1245 AWS_LOGF_TRACE(
1246 AWS_LS_HTTP_WEBSOCKET,
1247 "id=%p: Begin processing incoming message of size %zu.",
1248 (void *)websocket,
1249 message->message_data.len);
1250
1251 while (cursor.len) {
1252 if (websocket->thread_data.is_reading_stopped) {
1253 goto clean_up;
1254 }
1255
1256 bool frame_complete;
1257 err = aws_websocket_decoder_process(&websocket->thread_data.decoder, &cursor, &frame_complete);
1258 if (err) {
1259 AWS_LOGF_ERROR(
1260 AWS_LS_HTTP_WEBSOCKET,
1261 "id=%p: Failed processing incoming message, error %d (%s). Closing connection.",
1262 (void *)websocket,
1263 aws_last_error(),
1264 aws_error_name(aws_last_error()));
1265
1266 goto error;
1267 }
1268
1269 if (frame_complete) {
1270 bool callback_result;
1271 s_complete_incoming_frame(websocket, AWS_ERROR_SUCCESS, &callback_result);
1272 if (!callback_result) {
1273 AWS_LOGF_ERROR(
1274 AWS_LS_HTTP_WEBSOCKET,
1275 "id=%p: Incoming frame completion callback has reported a failure. Closing connection",
1276 (void *)websocket);
1277
1278 aws_raise_error(AWS_ERROR_HTTP_CALLBACK_FAILURE);
1279 goto error;
1280 }
1281 }
1282 }
1283
1284 if (websocket->thread_data.incoming_message_window_update > 0) {
1285 aws_channel_slot_increment_read_window(slot, websocket->thread_data.incoming_message_window_update);
1286 }
1287
1288 goto clean_up;
1289
1290 error:
1291 s_shutdown_due_to_read_err(websocket, aws_last_error());
1292
1293 clean_up:
1294 if (cursor.len > 0) {
1295 AWS_LOGF_TRACE(
1296 AWS_LS_HTTP_WEBSOCKET,
1297 "id=%p: Done processing incoming message, final %zu bytes ignored.",
1298 (void *)websocket,
1299 cursor.len);
1300 } else {
1301 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Done processing incoming message.", (void *)websocket);
1302 }
1303 aws_mem_release(message->allocator, message);
1304 return AWS_OP_SUCCESS;
1305 }
1306
1307 static int s_decoder_on_frame(const struct aws_websocket_frame *frame, void *user_data) {
1308 struct aws_websocket *websocket = user_data;
1309 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
1310 AWS_ASSERT(!websocket->thread_data.current_incoming_frame);
1311 AWS_ASSERT(!websocket->thread_data.is_reading_stopped);
1312
1313 websocket->thread_data.current_incoming_frame = &websocket->thread_data.incoming_frame_storage;
1314
1315 websocket->thread_data.current_incoming_frame->payload_length = frame->payload_length;
1316 websocket->thread_data.current_incoming_frame->opcode = frame->opcode;
1317 websocket->thread_data.current_incoming_frame->fin = frame->fin;
1318
1319 /* If CONTINUATION frames are expected, remember which type of data is being continued.
1320 * RFC-6455 Section 5.4 Fragmentation */
1321 if (aws_websocket_is_data_frame(frame->opcode)) {
1322 if (frame->opcode != AWS_WEBSOCKET_OPCODE_CONTINUATION) {
1323 if (frame->fin) {
1324 websocket->thread_data.continuation_of_opcode = 0;
1325 } else {
1326 websocket->thread_data.continuation_of_opcode = frame->opcode;
1327 }
1328 }
1329 } else if (frame->opcode == AWS_WEBSOCKET_OPCODE_PING) {
1330 /* Prepare to store payload of PING so we can echo it back in the PONG */
1331 aws_byte_buf_reset(&websocket->thread_data.incoming_ping_payload, false /*zero_contents*/);
1332 /* Note: we are NOT calling aws_byte_buf_reserve().
1333 * This works around an attack where a malicious peer CLAIMS they'll send a huge frame,
1334 * which would case OOM if we did the reserve immediately.
1335 * If a malicious peer wants to run us out of memory, they'll need to do
1336 * it the costly way and actually send a billion bytes.
1337 * Or we could impose our own internal limits, but for now this is simpler */
1338 }
1339
1340 /* Invoke user cb */
1341 bool callback_result = true;
1342 if (websocket->on_incoming_frame_begin && !websocket->thread_data.is_midchannel_handler) {
1343 callback_result = websocket->on_incoming_frame_begin(
1344 websocket, websocket->thread_data.current_incoming_frame, websocket->user_data);
1345 }
1346
1347 if (!callback_result) {
1348 AWS_LOGF_ERROR(
1349 AWS_LS_HTTP_WEBSOCKET, "id=%p: Incoming frame callback has reported a failure.", (void *)websocket);
1350 return aws_raise_error(AWS_ERROR_HTTP_CALLBACK_FAILURE);
1351 }
1352
1353 return AWS_OP_SUCCESS;
1354 }
1355
1356 static int s_decoder_on_payload(struct aws_byte_cursor data, void *user_data) {
1357 struct aws_websocket *websocket = user_data;
1358 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
1359 AWS_ASSERT(websocket->thread_data.current_incoming_frame);
1360 AWS_ASSERT(!websocket->thread_data.is_reading_stopped);
1361
1362 /* Store payload of PING so we can echo it back in the PONG */
1363 if (websocket->thread_data.current_incoming_frame->opcode == AWS_WEBSOCKET_OPCODE_PING) {
1364 aws_byte_buf_append_dynamic(&websocket->thread_data.incoming_ping_payload, &data);
1365 }
1366
1367 if (websocket->thread_data.is_midchannel_handler) {
1368 return s_decoder_on_midchannel_payload(websocket, data);
1369 }
1370
1371 return s_decoder_on_user_payload(websocket, data);
1372 }
1373
1374 /* Invoke user cb */
1375 static int s_decoder_on_user_payload(struct aws_websocket *websocket, struct aws_byte_cursor data) {
1376 if (websocket->on_incoming_frame_payload) {
1377 if (!websocket->on_incoming_frame_payload(
1378 websocket, websocket->thread_data.current_incoming_frame, data, websocket->user_data)) {
1379
1380 AWS_LOGF_ERROR(
1381 AWS_LS_HTTP_WEBSOCKET, "id=%p: Incoming payload callback has reported a failure.", (void *)websocket);
1382 return aws_raise_error(AWS_ERROR_HTTP_CALLBACK_FAILURE);
1383 }
1384 }
1385
1386 /* If this is a "data" frame's payload, let the window shrink */
1387 if (aws_websocket_is_data_frame(websocket->thread_data.current_incoming_frame->opcode) &&
1388 websocket->manual_window_update) {
1389
1390 websocket->thread_data.incoming_message_window_update -= data.len;
1391 AWS_LOGF_DEBUG(
1392 AWS_LS_HTTP_WEBSOCKET,
1393 "id=%p: The read window is shrinking by %zu due to incoming payload from 'data' frame.",
1394 (void *)websocket,
1395 data.len);
1396 }
1397
1398 return AWS_OP_SUCCESS;
1399 }
1400
1401 /* Pass data to channel handler on the right */
1402 static int s_decoder_on_midchannel_payload(struct aws_websocket *websocket, struct aws_byte_cursor data) {
1403 struct aws_io_message *io_msg = NULL;
1404
1405 /* Only pass data to next handler if it's from a BINARY frame (or the CONTINUATION of a BINARY frame) */
1406 bool is_binary_data = websocket->thread_data.current_incoming_frame->opcode == AWS_WEBSOCKET_OPCODE_BINARY ||
1407 (websocket->thread_data.current_incoming_frame->opcode == AWS_WEBSOCKET_OPCODE_CONTINUATION &&
1408 websocket->thread_data.continuation_of_opcode == AWS_WEBSOCKET_OPCODE_BINARY);
1409 if (!is_binary_data) {
1410 return AWS_OP_SUCCESS;
1411 }
1412
1413 AWS_ASSERT(websocket->channel_slot->adj_right); /* Expected another slot in the read direction */
1414
1415 /* Note that current implementation of websocket handler does not buffer data travelling in the "read" direction,
1416 * so the downstream read window needs to be large enough to immediately receive incoming data. */
1417 if (aws_channel_slot_downstream_read_window(websocket->channel_slot) < data.len) {
1418 AWS_LOGF_ERROR(
1419 AWS_LS_HTTP_WEBSOCKET,
1420 "id=%p: Cannot send entire message without exceeding read window.",
1421 (void *)websocket);
1422 aws_raise_error(AWS_IO_CHANNEL_READ_WOULD_EXCEED_WINDOW);
1423 goto error;
1424 }
1425
1426 io_msg = aws_channel_acquire_message_from_pool(
1427 websocket->channel_slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, data.len);
1428 if (!io_msg) {
1429 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET, "id=%p: Failed to acquire message.", (void *)websocket);
1430 goto error;
1431 }
1432
1433 if (io_msg->message_data.capacity < data.len) {
1434 /* Probably can't happen. Data is coming an aws_io_message, should be able to acquire another just as big */
1435 AWS_LOGF_ERROR(
1436 AWS_LS_HTTP_WEBSOCKET, "id=%p: Failed to acquire sufficiently large message.", (void *)websocket);
1437 aws_raise_error(AWS_ERROR_UNKNOWN);
1438 goto error;
1439 }
1440
1441 if (!aws_byte_buf_write_from_whole_cursor(&io_msg->message_data, data)) {
1442 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET, "id=%p: Unexpected error while copying data.", (void *)websocket);
1443 aws_raise_error(AWS_ERROR_UNKNOWN);
1444 goto error;
1445 }
1446
1447 int err = aws_channel_slot_send_message(websocket->channel_slot, io_msg, AWS_CHANNEL_DIR_READ);
1448 if (err) {
1449 AWS_LOGF_ERROR(
1450 AWS_LS_HTTP_WEBSOCKET,
1451 "id=%p: Failed to send read message, error %d (%s).",
1452 (void *)websocket,
1453 aws_last_error(),
1454 aws_error_name(aws_last_error()));
1455 goto error;
1456 }
1457
1458 /* Reduce amount by which websocket will update its read window */
1459 AWS_ASSERT(websocket->thread_data.incoming_message_window_update >= data.len);
1460 websocket->thread_data.incoming_message_window_update -= data.len;
1461
1462 return AWS_OP_SUCCESS;
1463
1464 error:
1465 if (io_msg) {
1466 aws_mem_release(io_msg->allocator, io_msg);
1467 }
1468 return AWS_OP_ERR;
1469 }
1470
1471 /* When the websocket sends a frame automatically (PONG, CLOSE),
1472 * this holds the payload. */
1473 struct aws_websocket_autopayload {
1474 struct aws_allocator *alloc;
1475 struct aws_byte_buf buf;
1476 struct aws_byte_cursor advancing_cursor;
1477 };
1478
1479 static struct aws_websocket_autopayload *s_autopayload_new(
1480 struct aws_allocator *alloc,
1481 const struct aws_byte_buf *src) {
1482
1483 struct aws_websocket_autopayload *autopayload = aws_mem_calloc(alloc, 1, sizeof(struct aws_websocket_autopayload));
1484 autopayload->alloc = alloc;
1485 if (src->len > 0) {
1486 aws_byte_buf_init_copy(&autopayload->buf, alloc, src);
1487 autopayload->advancing_cursor = aws_byte_cursor_from_buf(&autopayload->buf);
1488 }
1489
1490 return autopayload;
1491 }
1492
1493 static void s_autopayload_destroy(struct aws_websocket_autopayload *autopayload) {
1494 aws_byte_buf_clean_up(&autopayload->buf);
1495 aws_mem_release(autopayload->alloc, autopayload);
1496 }
1497
1498 static void s_autopayload_send_complete(struct aws_websocket *websocket, int error_code, void *user_data) {
1499 (void)websocket;
1500 (void)error_code;
1501
1502 struct aws_websocket_autopayload *autopayload = user_data;
1503 s_autopayload_destroy(autopayload);
1504 }
1505
1506 static bool s_autopayload_stream_outgoing_payload(
1507 struct aws_websocket *websocket,
1508 struct aws_byte_buf *out_buf,
1509 void *user_data) {
1510
1511 (void)websocket;
1512 struct aws_websocket_autopayload *autopayload = user_data;
1513 aws_byte_buf_write_to_capacity(out_buf, &autopayload->advancing_cursor);
1514 return true;
1515 }
1516
1517 static void s_complete_incoming_frame(struct aws_websocket *websocket, int error_code, bool *out_callback_result) {
1518 AWS_ASSERT(aws_channel_thread_is_callers_thread(websocket->channel_slot->channel));
1519 AWS_ASSERT(websocket->thread_data.current_incoming_frame);
1520
1521 if (error_code == 0) {
1522 /* If this was a CLOSE frame, don't read any more data. */
1523 if (websocket->thread_data.current_incoming_frame->opcode == AWS_WEBSOCKET_OPCODE_CLOSE) {
1524 AWS_LOGF_DEBUG(
1525 AWS_LS_HTTP_WEBSOCKET,
1526 "id=%p: Close frame received, any further data received will be ignored.",
1527 (void *)websocket);
1528 s_stop_reading_and_dont_block_shutdown(websocket);
1529
1530 /* TODO: auto-close if there's a channel-handler to the right */
1531
1532 } else if (websocket->thread_data.current_incoming_frame->opcode == AWS_WEBSOCKET_OPCODE_PING) {
1533 /* Automatically respond to a PING with a PONG */
1534 if (!websocket->thread_data.is_writing_stopped) {
1535 /* Optimization idea: avoid allocations/copies each time we send an auto-PONG.
1536 * Maybe have a small autopayload pool, instead of allocating one each time.
1537 * Maybe encode directly to aws_io_message, instead of copying to a buf, that's copied to a msg later.
1538 * Maybe "std::move()" the aws_byte_bufs around instead of copying them. */
1539 struct aws_websocket_autopayload *autopong =
1540 s_autopayload_new(websocket->alloc, &websocket->thread_data.incoming_ping_payload);
1541
1542 struct aws_websocket_send_frame_options pong_frame = {
1543 .opcode = AWS_WEBSOCKET_OPCODE_PONG,
1544 .fin = true,
1545 .payload_length = autopong->buf.len,
1546 .stream_outgoing_payload = s_autopayload_stream_outgoing_payload,
1547 .on_complete = s_autopayload_send_complete,
1548 .user_data = autopong,
1549 };
1550
1551 int send_err = s_send_frame(websocket, &pong_frame, false /*from_public_api*/);
1552 /* Failure should be impossible. We already checked that writing is not stopped */
1553 AWS_FATAL_ASSERT(!send_err && "Unexpected failure sending websocket PONG");
1554 }
1555 }
1556 }
1557
1558 /* Invoke user cb */
1559 bool callback_result = true;
1560 if (websocket->on_incoming_frame_complete && !websocket->thread_data.is_midchannel_handler) {
1561 callback_result = websocket->on_incoming_frame_complete(
1562 websocket, websocket->thread_data.current_incoming_frame, error_code, websocket->user_data);
1563 }
1564
1565 if (out_callback_result) {
1566 *out_callback_result = callback_result;
1567 }
1568
1569 websocket->thread_data.current_incoming_frame = NULL;
1570 }
1571
1572 static size_t s_handler_initial_window_size(struct aws_channel_handler *handler) {
1573 struct aws_websocket *websocket = handler->impl;
1574 return websocket->initial_window_size;
1575 }
1576
1577 static size_t s_handler_message_overhead(struct aws_channel_handler *handler) {
1578 (void)handler;
1579 return AWS_WEBSOCKET_MAX_FRAME_OVERHEAD;
1580 }
1581
1582 static int s_handler_increment_read_window(
1583 struct aws_channel_handler *handler,
1584 struct aws_channel_slot *slot,
1585 size_t size) {
1586
1587 struct aws_websocket *websocket = handler->impl;
1588 AWS_ASSERT(aws_channel_thread_is_callers_thread(slot->channel));
1589 AWS_ASSERT(websocket->thread_data.is_midchannel_handler);
1590
1591 /* NOTE: This is pretty hacky and should change if it ever causes issues.
1592 *
1593 * Currently, all read messages are processed the moment they're received.
1594 * If the downstream read window is open enough to accept this data, we can send it right along.
1595 * BUT if the downstream window were too small, we'd need to buffer the data and wait until
1596 * the downstream window opened again to finish sending.
1597 *
1598 * To avoid that complexity, we go to pains here to ensure that the websocket's window exactly
1599 * matches the window to the right, allowing us to avoid buffering in the read direction.
1600 */
1601 size_t increment = size;
1602 if (websocket->thread_data.last_known_right_slot != slot->adj_right) {
1603 if (size < slot->window_size) {
1604 AWS_LOGF_ERROR(
1605 AWS_LS_HTTP_WEBSOCKET,
1606 "id=%p: The websocket does not support downstream handlers with a smaller window.",
1607 (void *)websocket);
1608 aws_raise_error(AWS_IO_CHANNEL_READ_WOULD_EXCEED_WINDOW);
1609 goto error;
1610 }
1611
1612 /* New handler to the right, make sure websocket's window matches its window. */
1613 websocket->thread_data.last_known_right_slot = slot->adj_right;
1614 increment = size - slot->window_size;
1615 }
1616
1617 if (increment != 0) {
1618 aws_channel_slot_increment_read_window(slot, increment);
1619 }
1620
1621 return AWS_OP_SUCCESS;
1622
1623 error:
1624 /* Shutting down channel because I know that no one ever checks these errors */
1625 s_shutdown_due_to_read_err(websocket, aws_last_error());
1626 return AWS_OP_ERR;
1627 }
1628
1629 static void s_increment_read_window_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
1630 (void)task;
1631
1632 if (status != AWS_TASK_STATUS_RUN_READY) {
1633 return;
1634 }
1635
1636 struct aws_websocket *websocket = arg;
1637 size_t size;
1638
1639 /* BEGIN CRITICAL SECTION */
1640 s_lock_synced_data(websocket);
1641
1642 size = websocket->synced_data.window_increment_size;
1643 websocket->synced_data.window_increment_size = 0;
1644
1645 s_unlock_synced_data(websocket);
1646 /* END CRITICAL SECTION */
1647
1648 AWS_LOGF_TRACE(
1649 AWS_LS_HTTP_WEBSOCKET, "id=%p: Running task to increment read window by %zu.", (void *)websocket, size);
1650
1651 aws_channel_slot_increment_read_window(websocket->channel_slot, size);
1652 }
1653
1654 void aws_websocket_increment_read_window(struct aws_websocket *websocket, size_t size) {
1655 if (size == 0) {
1656 AWS_LOGF_TRACE(AWS_LS_HTTP_WEBSOCKET, "id=%p: Ignoring window increment of size 0.", (void *)websocket);
1657 return;
1658 }
1659
1660 if (!websocket->manual_window_update) {
1661 AWS_LOGF_DEBUG(
1662 AWS_LS_HTTP_WEBSOCKET,
1663 "id=%p: Ignoring window increment. Manual window management (aka read backpressure) is not enabled.",
1664 (void *)websocket);
1665 return;
1666 }
1667
1668 /* Schedule a task to do the increment.
1669 * If task is already scheduled, just increase size to be incremented */
1670 bool is_midchannel_handler = false;
1671 bool should_schedule_task = false;
1672
1673 /* BEGIN CRITICAL SECTION */
1674 s_lock_synced_data(websocket);
1675
1676 if (websocket->synced_data.is_midchannel_handler) {
1677 is_midchannel_handler = true;
1678 } else if (websocket->synced_data.window_increment_size == 0) {
1679 should_schedule_task = true;
1680 websocket->synced_data.window_increment_size = size;
1681 } else {
1682 websocket->synced_data.window_increment_size =
1683 aws_add_size_saturating(websocket->synced_data.window_increment_size, size);
1684 }
1685
1686 s_unlock_synced_data(websocket);
1687 /* END CRITICAL SECTION */
1688
1689 if (is_midchannel_handler) {
1690 AWS_LOGF_TRACE(
1691 AWS_LS_HTTP_WEBSOCKET,
1692 "id=%p: Ignoring window increment call, websocket has converted to midchannel handler.",
1693 (void *)websocket);
1694 } else if (should_schedule_task) {
1695 AWS_LOGF_TRACE(
1696 AWS_LS_HTTP_WEBSOCKET, "id=%p: Scheduling task to increment read window by %zu.", (void *)websocket, size);
1697 aws_channel_schedule_task_now(websocket->channel_slot->channel, &websocket->increment_read_window_task);
1698 } else {
1699 AWS_LOGF_TRACE(
1700 AWS_LS_HTTP_WEBSOCKET,
1701 "id=%p: Task to increment read window already scheduled, increasing scheduled size by %zu.",
1702 (void *)websocket,
1703 size);
1704 }
1705 }
1706
1707 int aws_websocket_random_handshake_key(struct aws_byte_buf *dst) {
1708 /* RFC-6455 Section 4.1.
1709 * Derive random 16-byte value, base64-encoded, for the Sec-WebSocket-Key header */
1710 uint8_t key_random_storage[16] = {0};
1711 struct aws_byte_buf key_random_buf = aws_byte_buf_from_empty_array(key_random_storage, sizeof(key_random_storage));
1712 int err = aws_device_random_buffer(&key_random_buf);
1713 if (err) {
1714 return AWS_OP_ERR;
1715 }
1716
1717 struct aws_byte_cursor key_random_cur = aws_byte_cursor_from_buf(&key_random_buf);
1718 err = aws_base64_encode(&key_random_cur, dst);
1719 if (err) {
1720 return AWS_OP_ERR;
1721 }
1722
1723 return AWS_OP_SUCCESS;
1724 }
1725
1726 struct aws_http_message *aws_http_message_new_websocket_handshake_request(
1727 struct aws_allocator *allocator,
1728 struct aws_byte_cursor path,
1729 struct aws_byte_cursor host) {
1730
1731 AWS_PRECONDITION(allocator);
1732 AWS_PRECONDITION(aws_byte_cursor_is_valid(&path));
1733 AWS_PRECONDITION(aws_byte_cursor_is_valid(&host));
1734
1735 struct aws_http_message *request = aws_http_message_new_request(allocator);
1736 if (!request) {
1737 goto error;
1738 }
1739
1740 int err = aws_http_message_set_request_method(request, aws_http_method_get);
1741 if (err) {
1742 goto error;
1743 }
1744
1745 err = aws_http_message_set_request_path(request, path);
1746 if (err) {
1747 goto error;
1748 }
1749
1750 uint8_t key_storage[AWS_WEBSOCKET_MAX_HANDSHAKE_KEY_LENGTH];
1751 struct aws_byte_buf key_buf = aws_byte_buf_from_empty_array(key_storage, sizeof(key_storage));
1752 err = aws_websocket_random_handshake_key(&key_buf);
1753 if (err) {
1754 goto error;
1755 }
1756
1757 struct aws_http_header required_headers[] = {
1758 {
1759 .name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Host"),
1760 .value = host,
1761 },
1762 {
1763 .name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Upgrade"),
1764 .value = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("websocket"),
1765 },
1766 {
1767 .name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Connection"),
1768 .value = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Upgrade"),
1769 },
1770 {
1771 .name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Sec-WebSocket-Key"),
1772 .value = aws_byte_cursor_from_buf(&key_buf),
1773 },
1774 {
1775 .name = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("Sec-WebSocket-Version"),
1776 .value = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("13"),
1777 },
1778 };
1779
1780 for (size_t i = 0; i < AWS_ARRAY_SIZE(required_headers); ++i) {
1781 err = aws_http_message_add_header(request, required_headers[i]);
1782 if (err) {
1783 goto error;
1784 }
1785 }
1786
1787 return request;
1788
1789 error:
1790 aws_http_message_destroy(request);
1791 return NULL;
1792 }