Debian Codegraph @

crt/aws-c-io/source/socket_channel_handler.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 <aws/io/socket_channel_handler.h>
6
7 #include <aws/common/error.h>
8 #include <aws/common/task_scheduler.h>
9
10 #include <aws/io/event_loop.h>
11 #include <aws/io/logging.h>
12 #include <aws/io/socket.h>
13 #include <aws/io/statistics.h>
14
15 #ifdef _MSC_VER
16 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
17 #endif
18
19 struct socket_handler {
20 struct aws_socket *socket;
21 struct aws_channel_slot *slot;
22 size_t max_rw_size;
23 struct aws_channel_task read_task_storage;
24 struct aws_channel_task shutdown_task_storage;
25 struct aws_crt_statistics_socket stats;
26 int shutdown_err_code;
27 bool shutdown_in_progress;
28 };
29
30 static int s_socket_process_read_message(
31 struct aws_channel_handler *handler,
32 struct aws_channel_slot *slot,
33 struct aws_io_message *message) {
34 (void)handler;
35 (void)slot;
36 (void)message;
37
38 AWS_LOGF_FATAL(
39 AWS_LS_IO_SOCKET_HANDLER,
40 "id=%p: process_read_message called on "
41 "socket handler. This should never happen",
42 (void *)handler);
43
44 /*since a socket handler will ALWAYS be the first handler in a channel,
45 * this should NEVER happen, if it does it's a programmer error.*/
46 AWS_ASSERT(0);
47 return aws_raise_error(AWS_IO_CHANNEL_ERROR_ERROR_CANT_ACCEPT_INPUT);
48 }
49
50 /* invoked by the socket when a write has completed or failed. */
51 static void s_on_socket_write_complete(
52 struct aws_socket *socket,
53 int error_code,
54 size_t amount_written,
55 void *user_data) {
56
57 if (user_data) {
58 struct aws_io_message *message = user_data;
59 struct aws_channel *channel = message->owning_channel;
60 AWS_LOGF_TRACE(
61 AWS_LS_IO_SOCKET_HANDLER,
62 "static: write of size %llu, completed on channel %p",
63 (unsigned long long)amount_written,
64 (void *)channel);
65
66 if (message->on_completion) {
67 message->on_completion(channel, message, error_code, message->user_data);
68 }
69
70 if (socket && socket->handler) {
71 struct socket_handler *socket_handler = socket->handler->impl;
72 socket_handler->stats.bytes_written += amount_written;
73 }
74
75 aws_mem_release(message->allocator, message);
76
77 if (error_code) {
78 aws_channel_shutdown(channel, error_code);
79 }
80 }
81 }
82
83 static int s_socket_process_write_message(
84 struct aws_channel_handler *handler,
85 struct aws_channel_slot *slot,
86 struct aws_io_message *message) {
87 (void)slot;
88 struct socket_handler *socket_handler = handler->impl;
89
90 AWS_LOGF_TRACE(
91 AWS_LS_IO_SOCKET_HANDLER,
92 "id=%p: writing message of size %llu",
93 (void *)handler,
94 (unsigned long long)message->message_data.len);
95
96 if (!aws_socket_is_open(socket_handler->socket)) {
97 return aws_raise_error(AWS_IO_SOCKET_CLOSED);
98 }
99
100 struct aws_byte_cursor cursor = aws_byte_cursor_from_buf(&message->message_data);
101 if (aws_socket_write(socket_handler->socket, &cursor, s_on_socket_write_complete, message)) {
102 return AWS_OP_ERR;
103 }
104
105 return AWS_OP_SUCCESS;
106 }
107
108 static void s_read_task(struct aws_channel_task *task, void *arg, aws_task_status status);
109
110 static void s_on_readable_notification(struct aws_socket *socket, int error_code, void *user_data);
111
112 /* Ok this next function is VERY important for how back pressure works. Here's what it's supposed to be doing:
113 *
114 * See how much data downstream is willing to accept.
115 * See how much we're actually willing to read per event loop tick (usually 16 kb).
116 * Take the minimum of those two.
117 * Try and read as much as possible up to the calculated max read.
118 * If we didn't read up to the max_read, we go back to waiting on the event loop to tell us we can read more.
119 * If we did read up to the max_read, we stop reading immediately and wait for either for a window update,
120 * or schedule a task to enforce fairness for other sockets in the event loop if we read up to the max
121 * read per event loop tick.
122 */
123 static void s_do_read(struct socket_handler *socket_handler) {
124
125 if (socket_handler->shutdown_in_progress) {
126 return;
127 }
128
129 size_t downstream_window = aws_channel_slot_downstream_read_window(socket_handler->slot);
130 size_t max_to_read =
131 downstream_window > socket_handler->max_rw_size ? socket_handler->max_rw_size : downstream_window;
132
133 AWS_LOGF_TRACE(
134 AWS_LS_IO_SOCKET_HANDLER,
135 "id=%p: invoking read. Downstream window %llu, max_to_read %llu",
136 (void *)socket_handler->slot->handler,
137 (unsigned long long)downstream_window,
138 (unsigned long long)max_to_read);
139
140 if (max_to_read == 0) {
141 return;
142 }
143
144 size_t total_read = 0;
145 size_t read = 0;
146 int last_error = 0;
147 while (total_read < max_to_read) {
148 size_t iter_max_read = max_to_read - total_read;
149
150 struct aws_io_message *message = aws_channel_acquire_message_from_pool(
151 socket_handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, iter_max_read);
152
153 if (aws_socket_read(socket_handler->socket, &message->message_data, &read)) {
154 last_error = aws_last_error();
155 aws_mem_release(message->allocator, message);
156 break;
157 }
158
159 total_read += read;
160 AWS_LOGF_TRACE(
161 AWS_LS_IO_SOCKET_HANDLER,
162 "id=%p: read %llu from socket",
163 (void *)socket_handler->slot->handler,
164 (unsigned long long)read);
165
166 if (aws_channel_slot_send_message(socket_handler->slot, message, AWS_CHANNEL_DIR_READ)) {
167 last_error = aws_last_error();
168 aws_mem_release(message->allocator, message);
169 break;
170 }
171 }
172
173 AWS_LOGF_TRACE(
174 AWS_LS_IO_SOCKET_HANDLER,
175 "id=%p: total read on this tick %llu",
176 (void *)socket_handler->slot->handler,
177 (unsigned long long)total_read);
178
179 socket_handler->stats.bytes_read += total_read;
180
181 /* resubscribe as long as there's no error, just return if we're in a would block scenario. */
182 if (total_read < max_to_read) {
183 AWS_ASSERT(last_error != 0);
184
185 if (last_error != AWS_IO_READ_WOULD_BLOCK) {
186 aws_channel_shutdown(socket_handler->slot->channel, last_error);
187 } else {
188 AWS_LOGF_TRACE(
189 AWS_LS_IO_SOCKET_HANDLER,
190 "id=%p: out of data to read on socket. "
191 "Waiting on event-loop notification.",
192 (void *)socket_handler->slot->handler);
193 }
194 return;
195 }
196 /* in this case, everything was fine, but there's still pending reads. We need to schedule a task to do the read
197 * again. */
198 if (total_read == socket_handler->max_rw_size && !socket_handler->read_task_storage.task_fn) {
199
200 AWS_LOGF_TRACE(
201 AWS_LS_IO_SOCKET_HANDLER,
202 "id=%p: more data is pending read, but we've exceeded "
203 "the max read on this tick. Scheduling a task to read on next tick.",
204 (void *)socket_handler->slot->handler);
205 aws_channel_task_init(
206 &socket_handler->read_task_storage, s_read_task, socket_handler, "socket_handler_re_read");
207 aws_channel_schedule_task_now(socket_handler->slot->channel, &socket_handler->read_task_storage);
208 }
209 }
210
211 /* the socket is either readable or errored out. If it's readable, kick off s_do_read() to do its thing. */
212 static void s_on_readable_notification(struct aws_socket *socket, int error_code, void *user_data) {
213 (void)socket;
214
215 struct socket_handler *socket_handler = user_data;
216 AWS_LOGF_TRACE(
217 AWS_LS_IO_SOCKET_HANDLER,
218 "id=%p: socket on-readable with error code %d(%s)",
219 (void *)socket_handler->slot->handler,
220 error_code,
221 aws_error_name(error_code));
222
223 /* Regardless of error code call read() until it reports error or EOF,
224 * so we can pick up data that was sent prior to the close.
225 *
226 * For example, if peer closes the socket immediately after sending the last
227 * bytes of data, the READABLE and HANGUP events arrive simultaneously.
228 *
229 * Another example, peer sends a TLS ALERT then immediately closes the socket.
230 * On some platforms, we'll never see the readable flag. So we want to make
231 * sure we read the ALERT, otherwise, we'll end up telling the user that the channel shutdown because of a socket
232 * closure, when in reality it was a TLS error
233 *
234 * It may take more than one read() to get all remaining data.
235 * Also, if the downstream read-window reaches 0, we need to patiently
236 * wait until the window opens before we can call read() again. */
237 (void)error_code;
238 s_do_read(socket_handler);
239 }
240
241 /* Either the result of a context switch (for fairness in the event loop), or a window update. */
242 static void s_read_task(struct aws_channel_task *task, void *arg, aws_task_status status) {
243 task->task_fn = NULL;
244 task->arg = NULL;
245
246 if (status == AWS_TASK_STATUS_RUN_READY) {
247 struct socket_handler *socket_handler = arg;
248 s_do_read(socket_handler);
249 }
250 }
251
252 static int s_socket_increment_read_window(
253 struct aws_channel_handler *handler,
254 struct aws_channel_slot *slot,
255 size_t size) {
256 (void)size;
257
258 struct socket_handler *socket_handler = handler->impl;
259
260 if (!socket_handler->shutdown_in_progress && !socket_handler->read_task_storage.task_fn) {
261 AWS_LOGF_TRACE(
262 AWS_LS_IO_SOCKET_HANDLER,
263 "id=%p: increment read window message received, scheduling"
264 " task for another read operation.",
265 (void *)handler);
266
267 aws_channel_task_init(
268 &socket_handler->read_task_storage, s_read_task, socket_handler, "socket_handler_read_on_window_increment");
269 aws_channel_schedule_task_now(slot->channel, &socket_handler->read_task_storage);
270 }
271
272 return AWS_OP_SUCCESS;
273 }
274
275 static void s_close_task(struct aws_channel_task *task, void *arg, aws_task_status status) {
276 (void)task;
277 (void)status;
278
279 struct aws_channel_handler *handler = arg;
280 struct socket_handler *socket_handler = handler->impl;
281
282 /*
283 * Run this unconditionally regardless of status, otherwise channel will not
284 * finish shutting down properly
285 */
286
287 /* this only happens in write direction. */
288 /* we also don't care about the free_scarce_resource_immediately
289 * code since we're always the last one in the shutdown sequence. */
290 aws_channel_slot_on_handler_shutdown_complete(
291 socket_handler->slot, AWS_CHANNEL_DIR_WRITE, socket_handler->shutdown_err_code, false);
292 }
293
294 struct channel_shutdown_close_args {
295 struct aws_channel_handler *handler;
296 int error_code;
297 struct aws_channel *channel;
298 struct aws_channel_slot *slot;
299 enum aws_channel_direction dir;
300 bool free_scarce_resource_immediately;
301 int test_flag;
302 };
303
304 static void s_shutdown_complete_fn(void *user_data) {
305 struct channel_shutdown_close_args *close_args = user_data;
306
307 /* Schedule a task to complete the shutdown, in case a do_read task is currently pending.
308 * It's OK to delay the shutdown, even when free_scarce_resources_immediately is true,
309 * because the socket has been closed: mitigating the risk that the socket is still being abused by
310 * a hostile peer. */
311 struct socket_handler *socket_handler = close_args->handler->impl;
312 aws_channel_task_init(
313 &socket_handler->shutdown_task_storage, s_close_task, close_args->handler, "socket_handler_close");
314 socket_handler->shutdown_err_code = close_args->error_code;
315 aws_channel_schedule_task_now(close_args->channel, &socket_handler->shutdown_task_storage);
316 aws_mem_release(close_args->handler->alloc, close_args);
317 }
318
319 static void s_shutdown_read_dir_complete_fn(void *user_data) {
320 struct channel_shutdown_close_args *close_args = user_data;
321
322 aws_channel_slot_on_handler_shutdown_complete(
323 close_args->slot, close_args->dir, close_args->error_code, close_args->free_scarce_resource_immediately);
324 aws_mem_release(close_args->handler->alloc, close_args);
325 }
326
327 static int s_socket_shutdown(
328 struct aws_channel_handler *handler,
329 struct aws_channel_slot *slot,
330 enum aws_channel_direction dir,
331 int error_code,
332 bool free_scarce_resource_immediately) {
333 struct socket_handler *socket_handler = (struct socket_handler *)handler->impl;
334
335 socket_handler->shutdown_in_progress = true;
336 if (dir == AWS_CHANNEL_DIR_READ) {
337 AWS_LOGF_TRACE(
338 AWS_LS_IO_SOCKET_HANDLER,
339 "id=%p: shutting down read direction with error_code %d : %s",
340 (void *)handler,
341 error_code,
342 aws_error_name(error_code));
343 if (free_scarce_resource_immediately && aws_socket_is_open(socket_handler->socket)) {
344 struct channel_shutdown_close_args *close_args =
345 aws_mem_calloc(handler->alloc, 1, sizeof(struct channel_shutdown_close_args));
346
347 close_args->error_code = error_code;
348 close_args->handler = handler;
349 close_args->channel = slot->channel;
350 close_args->slot = slot;
351 close_args->free_scarce_resource_immediately = free_scarce_resource_immediately;
352 close_args->dir = dir;
353
354 aws_socket_set_close_complete_callback(socket_handler->socket, s_shutdown_read_dir_complete_fn, close_args);
355 if (aws_socket_close(socket_handler->socket)) {
356 return AWS_OP_ERR;
357 }
358 return AWS_OP_SUCCESS;
359 }
360
361 return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resource_immediately);
362 }
363
364 AWS_LOGF_TRACE(
365 AWS_LS_IO_SOCKET_HANDLER,
366 "id=%p: shutting down write direction with error_code %d",
367 (void *)handler,
368 error_code);
369 if (aws_socket_is_open(socket_handler->socket)) {
370 struct channel_shutdown_close_args *close_args =
371 aws_mem_calloc(handler->alloc, 1, sizeof(struct channel_shutdown_close_args));
372
373 close_args->error_code = error_code;
374 close_args->handler = handler;
375 close_args->channel = slot->channel;
376 close_args->slot = slot;
377 close_args->free_scarce_resource_immediately = free_scarce_resource_immediately;
378 close_args->dir = dir;
379
380 aws_socket_set_close_complete_callback(socket_handler->socket, s_shutdown_complete_fn, close_args);
381 aws_socket_close(socket_handler->socket);
382 } else { // If socket is already closed, fire the close task directly.
383 /* Schedule a task to complete the shutdown, in case a do_read task is currently pending.
384 * It's OK to delay the shutdown, even when free_scarce_resources_immediately is true,
385 * because the socket has been closed: mitigating the risk that the socket is still being abused by
386 * a hostile peer. */
387 aws_channel_task_init(&socket_handler->shutdown_task_storage, s_close_task, handler, "socket_handler_close");
388 socket_handler->shutdown_err_code = error_code;
389 aws_channel_schedule_task_now(slot->channel, &socket_handler->shutdown_task_storage);
390 }
391
392 return AWS_OP_SUCCESS;
393 }
394
395 static size_t s_message_overhead(struct aws_channel_handler *handler) {
396 (void)handler;
397 return 0;
398 }
399
400 static size_t s_socket_initial_window_size(struct aws_channel_handler *handler) {
401 (void)handler;
402 return SIZE_MAX;
403 }
404
405 static void s_socket_destroy(struct aws_channel_handler *handler) {
406 if (handler != NULL) {
407 struct socket_handler *socket_handler = (struct socket_handler *)handler->impl;
408 if (socket_handler != NULL) {
409 aws_crt_statistics_socket_cleanup(&socket_handler->stats);
410 }
411
412 aws_mem_release(handler->alloc, handler);
413 }
414 }
415
416 static void s_reset_statistics(struct aws_channel_handler *handler) {
417 struct socket_handler *socket_handler = (struct socket_handler *)handler->impl;
418
419 aws_crt_statistics_socket_reset(&socket_handler->stats);
420 }
421
422 static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats_list) {
423 struct socket_handler *socket_handler = (struct socket_handler *)handler->impl;
424
425 void *stats_base = &socket_handler->stats;
426 aws_array_list_push_back(stats_list, &stats_base);
427 }
428
429 static void s_trigger_read(struct aws_channel_handler *handler) {
430 struct socket_handler *socket_handler = (struct socket_handler *)handler->impl;
431
432 s_do_read(socket_handler);
433 }
434
435 static struct aws_channel_handler_vtable s_vtable = {
436 .process_read_message = s_socket_process_read_message,
437 .destroy = s_socket_destroy,
438 .process_write_message = s_socket_process_write_message,
439 .initial_window_size = s_socket_initial_window_size,
440 .increment_read_window = s_socket_increment_read_window,
441 .shutdown = s_socket_shutdown,
442 .message_overhead = s_message_overhead,
443 .reset_statistics = s_reset_statistics,
444 .gather_statistics = s_gather_statistics,
445 .trigger_read = s_trigger_read,
446 };
447
448 struct aws_channel_handler *aws_socket_handler_new(
449 struct aws_allocator *allocator,
450 struct aws_socket *socket,
451 struct aws_channel_slot *slot,
452 size_t max_read_size) {
453
454 /* make sure something has assigned this socket to an event loop, in client mode this will already have occurred.
455 In server mode, someone should have assigned it before calling us.*/
456 AWS_ASSERT(aws_socket_get_event_loop(socket));
457
458 struct aws_channel_handler *handler = NULL;
459
460 struct socket_handler *impl = NULL;
461
462 if (!aws_mem_acquire_many(
463 allocator, 2, &handler, sizeof(struct aws_channel_handler), &impl, sizeof(struct socket_handler))) {
464 return NULL;
465 }
466
467 impl->socket = socket;
468 impl->slot = slot;
469 impl->max_rw_size = max_read_size;
470 AWS_ZERO_STRUCT(impl->read_task_storage);
471 AWS_ZERO_STRUCT(impl->shutdown_task_storage);
472 impl->shutdown_in_progress = false;
473 if (aws_crt_statistics_socket_init(&impl->stats)) {
474 goto cleanup_handler;
475 }
476
477 AWS_LOGF_DEBUG(
478 AWS_LS_IO_SOCKET_HANDLER,
479 "id=%p: Socket handler created with max_read_size of %llu",
480 (void *)handler,
481 (unsigned long long)max_read_size);
482
483 handler->alloc = allocator;
484 handler->impl = impl;
485 handler->vtable = &s_vtable;
486 handler->slot = slot;
487 if (aws_socket_subscribe_to_readable_events(socket, s_on_readable_notification, impl)) {
488 goto cleanup_handler;
489 }
490
491 socket->handler = handler;
492
493 return handler;
494
495 cleanup_handler:
496 aws_mem_release(allocator, handler);
497
498 return NULL;
499 }
500
501 const struct aws_socket *aws_socket_handler_get_socket(const struct aws_channel_handler *handler) {
502 AWS_PRECONDITION(handler);
503 const struct socket_handler *socket_handler = handler->impl;
504 return socket_handler->socket;
505 }