Debian Codegraph @

crt/aws-c-io/source/posix/socket.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/io/socket.h>
7
8 #include <aws/common/clock.h>
9 #include <aws/common/condition_variable.h>
10 #include <aws/common/mutex.h>
11 #include <aws/common/string.h>
12 #include <aws/common/uuid.h>
13
14 #include <aws/io/event_loop.h>
15 #include <aws/io/logging.h>
16 #include <aws/io/private/event_loop_impl.h>
17 #include <aws/io/private/socket_impl.h>
18
19 #include <arpa/inet.h>
20 #include <aws/io/io.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h> /* Required when VSOCK is used */
24 #include <net/if.h>
25 #include <netinet/tcp.h>
26 #include <sys/socket.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29
30 /*
31 * On OsX, suppress NoPipe signals via flags to setsockopt()
32 * On Linux, suppress NoPipe signals via flags to send()
33 */
34 #if defined(__MACH__)
35 # define NO_SIGNAL_SOCK_OPT SO_NOSIGPIPE
36 # define NO_SIGNAL_SEND 0
37 # define TCP_KEEPIDLE TCP_KEEPALIVE
38 #else
39 # define NO_SIGNAL_SEND MSG_NOSIGNAL
40 #endif
41
42 /* This isn't defined on ancient linux distros (breaking the builds).
43 * However, if this is a prebuild, we purposely build on an ancient system, but
44 * we want the kernel calls to still be the same as a modern build since that's likely the target of the application
45 * calling this code. Just define this if it isn't there already. GlibC and the kernel don't really care how the flag
46 * gets passed as long as it does.
47 */
48 #ifndef O_CLOEXEC
49 # define O_CLOEXEC 02000000
50 #endif
51
52 #ifdef USE_VSOCK
53 # if defined(__linux__) && defined(AF_VSOCK)
54 # include <linux/vm_sockets.h>
55 # else
56 # error "USE_VSOCK not supported on current platform"
57 # endif
58 #endif
59
60 /* other than CONNECTED_READ | CONNECTED_WRITE
61 * a socket is only in one of these states at a time. */
62 enum socket_state {
63 INIT = 0x01,
64 CONNECTING = 0x02,
65 CONNECTED_READ = 0x04,
66 CONNECTED_WRITE = 0x08,
67 BOUND = 0x10,
68 LISTENING = 0x20,
69 TIMEDOUT = 0x40,
70 ERROR = 0x80,
71 CLOSED,
72 };
73
74 static int s_convert_domain(enum aws_socket_domain domain) {
75 switch (domain) {
76 case AWS_SOCKET_IPV4:
77 return AF_INET;
78 case AWS_SOCKET_IPV6:
79 return AF_INET6;
80 case AWS_SOCKET_LOCAL:
81 return AF_UNIX;
82 #ifdef USE_VSOCK
83 case AWS_SOCKET_VSOCK:
84 return AF_VSOCK;
85 #endif
86 default:
87 AWS_ASSERT(0);
88 return AF_INET;
89 }
90 }
91
92 static int s_convert_type(enum aws_socket_type type) {
93 switch (type) {
94 case AWS_SOCKET_STREAM:
95 return SOCK_STREAM;
96 case AWS_SOCKET_DGRAM:
97 return SOCK_DGRAM;
98 default:
99 AWS_ASSERT(0);
100 return SOCK_STREAM;
101 }
102 }
103
104 static int s_determine_socket_error(int error) {
105 switch (error) {
106 case ECONNREFUSED:
107 return AWS_IO_SOCKET_CONNECTION_REFUSED;
108 case ECONNRESET:
109 return AWS_IO_SOCKET_CLOSED;
110 case ETIMEDOUT:
111 return AWS_IO_SOCKET_TIMEOUT;
112 case EHOSTUNREACH:
113 case ENETUNREACH:
114 return AWS_IO_SOCKET_NO_ROUTE_TO_HOST;
115 case EADDRNOTAVAIL:
116 return AWS_IO_SOCKET_INVALID_ADDRESS;
117 case ENETDOWN:
118 return AWS_IO_SOCKET_NETWORK_DOWN;
119 case ECONNABORTED:
120 return AWS_IO_SOCKET_CONNECT_ABORTED;
121 case EADDRINUSE:
122 return AWS_IO_SOCKET_ADDRESS_IN_USE;
123 case ENOBUFS:
124 case ENOMEM:
125 return AWS_ERROR_OOM;
126 case EAGAIN:
127 return AWS_IO_READ_WOULD_BLOCK;
128 case EMFILE:
129 case ENFILE:
130 return AWS_ERROR_MAX_FDS_EXCEEDED;
131 case ENOENT:
132 case EINVAL:
133 return AWS_ERROR_FILE_INVALID_PATH;
134 case EAFNOSUPPORT:
135 return AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY;
136 case EACCES:
137 return AWS_ERROR_NO_PERMISSION;
138 default:
139 return AWS_IO_SOCKET_NOT_CONNECTED;
140 }
141 }
142
143 static int s_create_socket(struct aws_socket *sock, const struct aws_socket_options *options) {
144
145 int fd = socket(s_convert_domain(options->domain), s_convert_type(options->type), 0);
146 int errno_value = errno; /* Always cache errno before potential side-effect */
147
148 AWS_LOGF_DEBUG(
149 AWS_LS_IO_SOCKET,
150 "id=%p fd=%d: initializing with domain %d and type %d",
151 (void *)sock,
152 fd,
153 options->domain,
154 options->type);
155 if (fd != -1) {
156 int flags = fcntl(fd, F_GETFL, 0);
157 flags |= O_NONBLOCK | O_CLOEXEC;
158 int success = fcntl(fd, F_SETFL, flags);
159 (void)success;
160 sock->io_handle.data.fd = fd;
161 sock->io_handle.additional_data = NULL;
162 return aws_socket_set_options(sock, options);
163 }
164
165 int aws_error = s_determine_socket_error(errno_value);
166 return aws_raise_error(aws_error);
167 }
168
169 struct posix_socket_connect_args {
170 struct aws_task task;
171 struct aws_allocator *allocator;
172 struct aws_socket *socket;
173 };
174
175 struct posix_socket {
176 struct aws_linked_list write_queue;
177 struct aws_linked_list written_queue;
178 struct aws_task written_task;
179 struct posix_socket_connect_args *connect_args;
180 /* Note that only the posix_socket impl part is refcounted.
181 * The public aws_socket can be a stack variable and cleaned up synchronously
182 * (by blocking until the event-loop cleans up the impl part).
183 * In hindsight, aws_socket should have been heap-allocated and refcounted, but alas */
184 struct aws_ref_count internal_refcount;
185 struct aws_allocator *allocator;
186 bool written_task_scheduled;
187 bool currently_subscribed;
188 bool continue_accept;
189 bool *close_happened;
190
191 aws_socket_on_shutdown_complete_fn *on_close_complete;
192 void *close_user_data;
193
194 aws_socket_on_shutdown_complete_fn *on_cleanup_complete;
195 void *cleanup_user_data;
196 };
197
198 static void s_socket_clean_up(struct aws_socket *socket);
199 static int s_socket_connect(struct aws_socket *socket, struct aws_socket_connect_options *socket_connect_options);
200 static int s_socket_bind(struct aws_socket *socket, struct aws_socket_bind_options *socket_bind_options);
201 static int s_socket_listen(struct aws_socket *socket, int backlog_size);
202 static int s_socket_start_accept(
203 struct aws_socket *socket,
204 struct aws_event_loop *accept_loop,
205 struct aws_socket_listener_options options);
206 static int s_socket_stop_accept(struct aws_socket *socket);
207 static int s_socket_set_options(struct aws_socket *socket, const struct aws_socket_options *options);
208 static int s_socket_close(struct aws_socket *socket);
209 static int s_socket_shutdown_dir(struct aws_socket *socket, enum aws_channel_direction dir);
210 static int s_socket_assign_to_event_loop(struct aws_socket *socket, struct aws_event_loop *event_loop);
211 static int s_socket_subscribe_to_readable_events(
212 struct aws_socket *socket,
213 aws_socket_on_readable_fn *on_readable,
214 void *user_data);
215 static int s_socket_read(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read);
216 static int s_socket_write(
217 struct aws_socket *socket,
218 const struct aws_byte_cursor *cursor,
219 aws_socket_on_write_completed_fn *written_fn,
220 void *user_data);
221 static int s_socket_get_error(struct aws_socket *socket);
222 static bool s_socket_is_open(struct aws_socket *socket);
223 static int s_set_close_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
224 static int s_set_cleanup_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
225 static struct aws_byte_buf s_socket_get_protocol_fn(const struct aws_socket *socket);
226 static struct aws_string *s_socket_get_server_name_fn(const struct aws_socket *socket);
227
228 struct aws_socket_vtable s_posix_socket_vtable = {
229 .socket_cleanup_fn = s_socket_clean_up,
230 .socket_connect_fn = s_socket_connect,
231 .socket_bind_fn = s_socket_bind,
232 .socket_listen_fn = s_socket_listen,
233 .socket_start_accept_fn = s_socket_start_accept,
234 .socket_stop_accept_fn = s_socket_stop_accept,
235 .socket_set_options_fn = s_socket_set_options,
236 .socket_close_fn = s_socket_close,
237 .socket_shutdown_dir_fn = s_socket_shutdown_dir,
238 .socket_assign_to_event_loop_fn = s_socket_assign_to_event_loop,
239 .socket_subscribe_to_readable_events_fn = s_socket_subscribe_to_readable_events,
240 .socket_read_fn = s_socket_read,
241 .socket_write_fn = s_socket_write,
242 .socket_get_error_fn = s_socket_get_error,
243 .socket_is_open_fn = s_socket_is_open,
244 .socket_get_protocol_fn = s_socket_get_protocol_fn,
245 .socket_get_server_name_fn = s_socket_get_server_name_fn,
246 .socket_set_close_callback = s_set_close_callback,
247 .socket_set_cleanup_callback = s_set_cleanup_callback,
248 };
249
250 static int s_set_close_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data) {
251 struct posix_socket *socket_impl = socket->impl;
252 socket_impl->close_user_data = user_data;
253 socket_impl->on_close_complete = fn;
254 return 0;
255 }
256
257 static int s_set_cleanup_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data) {
258 struct posix_socket *socket_impl = socket->impl;
259 socket_impl->cleanup_user_data = user_data;
260 socket_impl->on_cleanup_complete = fn;
261 return 0;
262 }
263
264 static void s_socket_destroy_impl(void *user_data) {
265 struct posix_socket *socket_impl = user_data;
266 aws_mem_release(socket_impl->allocator, socket_impl);
267 }
268
269 static int s_socket_init(
270 struct aws_socket *socket,
271 struct aws_allocator *alloc,
272 const struct aws_socket_options *options,
273 int existing_socket_fd) {
274 AWS_ASSERT(options);
275
276 AWS_ZERO_STRUCT(*socket);
277
278 struct posix_socket *posix_socket = aws_mem_calloc(alloc, 1, sizeof(struct posix_socket));
279 if (!posix_socket) {
280 socket->impl = NULL;
281 return AWS_OP_ERR;
282 }
283
284 socket->allocator = alloc;
285 socket->io_handle.data.fd = -1;
286 socket->state = INIT;
287 socket->options = *options;
288 socket->impl = posix_socket;
289 socket->vtable = &s_posix_socket_vtable;
290
291 if (existing_socket_fd < 0) {
292 int err = s_create_socket(socket, options);
293 if (err) {
294 aws_mem_release(alloc, posix_socket);
295 socket->impl = NULL;
296 return AWS_OP_ERR;
297 }
298 } else {
299 socket->io_handle = (struct aws_io_handle){
300 .data = {.fd = existing_socket_fd},
301 .additional_data = NULL,
302 };
303 aws_socket_set_options(socket, options);
304 }
305
306 aws_linked_list_init(&posix_socket->write_queue);
307 aws_linked_list_init(&posix_socket->written_queue);
308 posix_socket->currently_subscribed = false;
309 posix_socket->continue_accept = false;
310 aws_ref_count_init(&posix_socket->internal_refcount, posix_socket, s_socket_destroy_impl);
311 posix_socket->allocator = alloc;
312 posix_socket->connect_args = NULL;
313 posix_socket->close_happened = NULL;
314
315 return AWS_OP_SUCCESS;
316 }
317 #if defined(AWS_ENABLE_KQUEUE) || defined(AWS_ENABLE_EPOLL)
318 int aws_socket_init_posix(
319 struct aws_socket *socket,
320 struct aws_allocator *alloc,
321 const struct aws_socket_options *options) {
322 AWS_ASSERT(options);
323 return s_socket_init(socket, alloc, options, -1);
324 }
325 #endif // AWS_ENABLE_KQUEUE || AWS_ENABLE_EPOLL
326
327 static void s_socket_clean_up(struct aws_socket *socket) {
328 if (!socket->impl) {
329 /* protect from double clean */
330 return;
331 }
332
333 int fd_for_logging = socket->io_handle.data.fd; /* socket's fd gets reset before final log */
334 (void)fd_for_logging;
335
336 if (aws_socket_is_open(socket)) {
337 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p fd=%d: is still open, closing...", (void *)socket, fd_for_logging);
338 aws_socket_close(socket);
339 }
340 struct posix_socket *socket_impl = socket->impl;
341 aws_socket_on_shutdown_complete_fn *on_cleanup_complete = socket_impl->on_cleanup_complete;
342 void *cleanup_user_data = socket_impl->cleanup_user_data;
343
344 if (aws_ref_count_release(&socket_impl->internal_refcount) != 0) {
345 AWS_LOGF_DEBUG(
346 AWS_LS_IO_SOCKET,
347 "id=%p fd=%d: is still pending io letting it dangle and cleaning up later.",
348 (void *)socket,
349 fd_for_logging);
350 }
351
352 AWS_ZERO_STRUCT(*socket);
353 socket->io_handle.data.fd = -1;
354
355 if (on_cleanup_complete) {
356 on_cleanup_complete(cleanup_user_data);
357 }
358 }
359
360 /* Update socket->local_endpoint based on the results of getsockname() */
361 static int s_update_local_endpoint(struct aws_socket *socket) {
362 struct aws_socket_endpoint tmp_endpoint;
363 AWS_ZERO_STRUCT(tmp_endpoint);
364
365 struct sockaddr_storage address;
366 AWS_ZERO_STRUCT(address);
367 socklen_t address_size = sizeof(address);
368
369 if (getsockname(socket->io_handle.data.fd, (struct sockaddr *)&address, &address_size) != 0) {
370 int errno_value = errno; /* Always cache errno before potential side-effect */
371 AWS_LOGF_ERROR(
372 AWS_LS_IO_SOCKET,
373 "id=%p fd=%d: getsockname() failed with error %d",
374 (void *)socket,
375 socket->io_handle.data.fd,
376 errno_value);
377 int aws_error = s_determine_socket_error(errno_value);
378 return aws_raise_error(aws_error);
379 }
380
381 if (address.ss_family == AF_INET) {
382 struct sockaddr_in *s = (struct sockaddr_in *)&address;
383 tmp_endpoint.port = ntohs(s->sin_port);
384 if (inet_ntop(AF_INET, &s->sin_addr, tmp_endpoint.address, sizeof(tmp_endpoint.address)) == NULL) {
385 int errno_value = errno; /* Always cache errno before potential side-effect */
386
387 AWS_LOGF_ERROR(
388 AWS_LS_IO_SOCKET,
389 "id=%p fd=%d: inet_ntop() failed with error %d",
390 (void *)socket,
391 socket->io_handle.data.fd,
392 errno_value);
393 int aws_error = s_determine_socket_error(errno_value);
394 return aws_raise_error(aws_error);
395 }
396 } else if (address.ss_family == AF_INET6) {
397 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&address;
398 tmp_endpoint.port = ntohs(s->sin6_port);
399 if (inet_ntop(AF_INET6, &s->sin6_addr, tmp_endpoint.address, sizeof(tmp_endpoint.address)) == NULL) {
400 int errno_value = errno; /* Always cache errno before potential side-effect */
401 AWS_LOGF_ERROR(
402 AWS_LS_IO_SOCKET,
403 "id=%p fd=%d: inet_ntop() failed with error %d",
404 (void *)socket,
405 socket->io_handle.data.fd,
406 errno_value);
407 int aws_error = s_determine_socket_error(errno_value);
408 return aws_raise_error(aws_error);
409 }
410 } else if (address.ss_family == AF_UNIX) {
411 struct sockaddr_un *s = (struct sockaddr_un *)&address;
412
413 /* Ensure there's a null-terminator.
414 * On some platforms it may be missing when the path gets very long. See:
415 * https://man7.org/linux/man-pages/man7/unix.7.html#BUGS
416 * But let's keep it simple, and not deal with that madness until someone demands it. */
417 size_t sun_len;
418 if (aws_secure_strlen(s->sun_path, sizeof(tmp_endpoint.address), &sun_len)) {
419 AWS_LOGF_ERROR(
420 AWS_LS_IO_SOCKET,
421 "id=%p fd=%d: UNIX domain socket name is too long",
422 (void *)socket,
423 socket->io_handle.data.fd);
424 return aws_raise_error(AWS_IO_SOCKET_INVALID_ADDRESS);
425 }
426 memcpy(tmp_endpoint.address, s->sun_path, sun_len);
427 #if USE_VSOCK
428 } else if (address.ss_family == AF_VSOCK) {
429 struct sockaddr_vm *s = (struct sockaddr_vm *)&address;
430
431 tmp_endpoint.port = s->svm_port;
432
433 snprintf(tmp_endpoint.address, sizeof(tmp_endpoint.address), "%" PRIu32, s->svm_cid);
434 return AWS_OP_SUCCESS;
435 #endif /* USE_VSOCK */
436 } else {
437 AWS_ASSERT(0);
438 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
439 }
440
441 socket->local_endpoint = tmp_endpoint;
442 return AWS_OP_SUCCESS;
443 }
444
445 static void s_on_connection_error(struct aws_socket *socket, int error);
446
447 static int s_on_connection_success(struct aws_socket *socket) {
448
449 struct aws_event_loop *event_loop = socket->event_loop;
450 struct posix_socket *socket_impl = socket->impl;
451
452 if (socket_impl->currently_subscribed) {
453 aws_event_loop_unsubscribe_from_io_events(socket->event_loop, &socket->io_handle);
454 socket_impl->currently_subscribed = false;
455 }
456
457 socket->event_loop = NULL;
458
459 int connect_result;
460 socklen_t result_length = sizeof(connect_result);
461
462 if (getsockopt(socket->io_handle.data.fd, SOL_SOCKET, SO_ERROR, &connect_result, &result_length) < 0) {
463 int errno_value = errno; /* Always cache errno before potential side-effect */
464 AWS_LOGF_DEBUG(
465 AWS_LS_IO_SOCKET,
466 "id=%p fd=%d: failed to determine connection error %d",
467 (void *)socket,
468 socket->io_handle.data.fd,
469 errno_value);
470 int aws_error = s_determine_socket_error(errno_value);
471 aws_raise_error(aws_error);
472 s_on_connection_error(socket, aws_error);
473 return AWS_OP_ERR;
474 }
475
476 if (connect_result) {
477 AWS_LOGF_DEBUG(
478 AWS_LS_IO_SOCKET,
479 "id=%p fd=%d: connection error %d",
480 (void *)socket,
481 socket->io_handle.data.fd,
482 connect_result);
483 int aws_error = s_determine_socket_error(connect_result);
484 aws_raise_error(aws_error);
485 s_on_connection_error(socket, aws_error);
486 return AWS_OP_ERR;
487 }
488
489 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "id=%p fd=%d: connection success", (void *)socket, socket->io_handle.data.fd);
490
491 if (s_update_local_endpoint(socket)) {
492 s_on_connection_error(socket, aws_last_error());
493 return AWS_OP_ERR;
494 }
495
496 socket->state = CONNECTED_WRITE | CONNECTED_READ;
497
498 if (aws_socket_assign_to_event_loop(socket, event_loop)) {
499 AWS_LOGF_ERROR(
500 AWS_LS_IO_SOCKET,
501 "id=%p fd=%d: assignment to event loop %p failed with error %d",
502 (void *)socket,
503 socket->io_handle.data.fd,
504 (void *)event_loop,
505 aws_last_error());
506 s_on_connection_error(socket, aws_last_error());
507 return AWS_OP_ERR;
508 }
509
510 socket->connection_result_fn(socket, AWS_ERROR_SUCCESS, socket->connect_accept_user_data);
511
512 return AWS_OP_SUCCESS;
513 }
514
515 static void s_on_connection_error(struct aws_socket *socket, int error) {
516 socket->state = ERROR;
517 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p fd=%d: connection failure", (void *)socket, socket->io_handle.data.fd);
518 if (socket->connection_result_fn) {
519 socket->connection_result_fn(socket, error, socket->connect_accept_user_data);
520 } else if (socket->accept_result_fn) {
521 socket->accept_result_fn(socket, error, NULL, socket->connect_accept_user_data);
522 }
523 }
524
525 /* the next two callbacks compete based on which one runs first. if s_socket_connect_event
526 * comes back first, then we set socket_args->socket = NULL and continue on with the connection.
527 * if s_handle_socket_timeout() runs first, is sees socket_args->socket is NULL and just cleans up its memory.
528 * s_handle_socket_timeout() will always run so the memory for socket_connect_args is always cleaned up there. */
529 static void s_socket_connect_event(
530 struct aws_event_loop *event_loop,
531 struct aws_io_handle *handle,
532 int events,
533 void *user_data) {
534
535 (void)event_loop;
536 (void)handle;
537
538 struct posix_socket_connect_args *socket_args = (struct posix_socket_connect_args *)user_data;
539 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "fd=%d: connection activity handler triggered ", handle->data.fd);
540
541 if (socket_args->socket) {
542 AWS_LOGF_TRACE(
543 AWS_LS_IO_SOCKET,
544 "id=%p fd=%d: has not timed out yet proceeding with connection.",
545 (void *)socket_args->socket,
546 handle->data.fd);
547
548 struct posix_socket *socket_impl = socket_args->socket->impl;
549 if (!(events & AWS_IO_EVENT_TYPE_ERROR || events & AWS_IO_EVENT_TYPE_CLOSED) &&
550 (events & AWS_IO_EVENT_TYPE_READABLE || events & AWS_IO_EVENT_TYPE_WRITABLE)) {
551 struct aws_socket *socket = socket_args->socket;
552 socket_args->socket = NULL;
553 socket_impl->connect_args = NULL;
554 s_on_connection_success(socket);
555 return;
556 }
557
558 int aws_error = aws_socket_get_error(socket_args->socket);
559 /* we'll get another notification. */
560 if (aws_error == AWS_IO_READ_WOULD_BLOCK) {
561 AWS_LOGF_TRACE(
562 AWS_LS_IO_SOCKET,
563 "id=%p fd=%d: spurious event, waiting for another notification.",
564 (void *)socket_args->socket,
565 handle->data.fd);
566 return;
567 }
568
569 struct aws_socket *socket = socket_args->socket;
570 socket_args->socket = NULL;
571 socket_impl->connect_args = NULL;
572 aws_raise_error(aws_error);
573 s_on_connection_error(socket, aws_error);
574 }
575 }
576
577 static void s_handle_socket_timeout(struct aws_task *task, void *args, aws_task_status status) {
578 (void)task;
579 (void)status;
580
581 struct posix_socket_connect_args *socket_args = args;
582
583 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "task_id=%p: timeout task triggered, evaluating timeouts.", (void *)task);
584 /* successful connection will have nulled out connect_args->socket */
585 if (socket_args->socket) {
586 AWS_LOGF_ERROR(
587 AWS_LS_IO_SOCKET,
588 "id=%p fd=%d: timed out, shutting down.",
589 (void *)socket_args->socket,
590 socket_args->socket->io_handle.data.fd);
591
592 socket_args->socket->state = TIMEDOUT;
593 int error_code = AWS_IO_SOCKET_TIMEOUT;
594
595 if (status == AWS_TASK_STATUS_RUN_READY) {
596 aws_event_loop_unsubscribe_from_io_events(socket_args->socket->event_loop, &socket_args->socket->io_handle);
597 } else {
598 error_code = AWS_IO_EVENT_LOOP_SHUTDOWN;
599 aws_event_loop_free_io_event_resources(socket_args->socket->event_loop, &socket_args->socket->io_handle);
600 }
601 socket_args->socket->event_loop = NULL;
602 struct posix_socket *socket_impl = socket_args->socket->impl;
603 socket_impl->currently_subscribed = false;
604 aws_raise_error(error_code);
605 struct aws_socket *socket = socket_args->socket;
606 /*socket close sets socket_args->socket to NULL and
607 * socket_impl->connect_args to NULL. */
608 aws_socket_close(socket);
609 s_on_connection_error(socket, error_code);
610 }
611
612 aws_mem_release(socket_args->allocator, socket_args);
613 }
614
615 /* this is used simply for moving a connect_success callback when the connect finished immediately
616 * (like for unix domain sockets) into the event loop's thread. Also note, in that case there was no
617 * timeout task scheduled, so in this case the socket_args are cleaned up. */
618 static void s_run_connect_success(struct aws_task *task, void *arg, enum aws_task_status status) {
619 (void)task;
620 struct posix_socket_connect_args *socket_args = arg;
621
622 if (socket_args->socket) {
623 struct posix_socket *socket_impl = socket_args->socket->impl;
624 if (status == AWS_TASK_STATUS_RUN_READY) {
625 s_on_connection_success(socket_args->socket);
626 } else {
627 aws_raise_error(AWS_IO_SOCKET_CONNECT_ABORTED);
628 socket_args->socket->event_loop = NULL;
629 s_on_connection_error(socket_args->socket, AWS_IO_SOCKET_CONNECT_ABORTED);
630 }
631 socket_impl->connect_args = NULL;
632 }
633
634 aws_mem_release(socket_args->allocator, socket_args);
635 }
636
637 static inline int s_convert_pton_error(int pton_code, int errno_value) {
638 if (pton_code == 0) {
639 return AWS_IO_SOCKET_INVALID_ADDRESS;
640 }
641
642 return s_determine_socket_error(errno_value);
643 }
644
645 #ifdef USE_VSOCK
646 /** Convert a string to a VSOCK CID. Respects the calling convetion of inet_pton:
647 * 0 on error, 1 on success. */
648 static int parse_cid(const char *cid_str, unsigned int *value) {
649 if (cid_str == NULL || value == NULL) {
650 errno = EINVAL;
651 return 0;
652 }
653 /* strtoll returns 0 as both error and correct value */
654 errno = 0;
655 /* unsigned long long to handle edge cases in convention explicitly */
656 long long cid = strtoll(cid_str, NULL, 10);
657 if (errno != 0) {
658 return 0;
659 }
660
661 /* -1U means any, so it's a valid value, but it needs to be converted to
662 * unsigned int. */
663 if (cid == -1) {
664 *value = VMADDR_CID_ANY;
665 return 1;
666 }
667
668 if (cid < 0 || cid > UINT_MAX) {
669 errno = ERANGE;
670 return 0;
671 }
672
673 /* cast is safe here, edge cases already checked */
674 *value = (unsigned int)cid;
675 return 1;
676 }
677 #endif
678
679 static int s_socket_connect(struct aws_socket *socket, struct aws_socket_connect_options *socket_connect_options) {
680
681 const struct aws_socket_endpoint *remote_endpoint = socket_connect_options->remote_endpoint;
682 struct aws_event_loop *event_loop = socket_connect_options->event_loop;
683 aws_socket_on_connection_result_fn *on_connection_result = socket_connect_options->on_connection_result;
684 void *user_data = socket_connect_options->user_data;
685
686 AWS_ASSERT(event_loop);
687 AWS_ASSERT(!socket->event_loop);
688
689 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p fd=%d: beginning connect.", (void *)socket, socket->io_handle.data.fd);
690
691 if (socket->event_loop) {
692 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
693 }
694
695 if (socket->options.type != AWS_SOCKET_DGRAM) {
696 AWS_ASSERT(on_connection_result);
697 if (socket->state != INIT) {
698 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
699 }
700 } else { /* UDP socket */
701 /* UDP sockets jump to CONNECT_READ if bind is called first */
702 if (socket->state != CONNECTED_READ && socket->state != INIT) {
703 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
704 }
705 }
706
707 size_t address_strlen;
708 if (aws_secure_strlen(remote_endpoint->address, AWS_ADDRESS_MAX_LEN, &address_strlen)) {
709 return AWS_OP_ERR;
710 }
711
712 if (aws_socket_validate_port_for_connect(remote_endpoint->port, socket->options.domain)) {
713 return AWS_OP_ERR;
714 }
715
716 struct socket_address address;
717 AWS_ZERO_STRUCT(address);
718 socklen_t sock_size = 0;
719 int pton_err = 1;
720 if (socket->options.domain == AWS_SOCKET_IPV4) {
721 pton_err = inet_pton(AF_INET, remote_endpoint->address, &address.sock_addr_types.addr_in.sin_addr);
722 address.sock_addr_types.addr_in.sin_port = htons((uint16_t)remote_endpoint->port);
723 address.sock_addr_types.addr_in.sin_family = AF_INET;
724 sock_size = sizeof(address.sock_addr_types.addr_in);
725 } else if (socket->options.domain == AWS_SOCKET_IPV6) {
726 pton_err = inet_pton(AF_INET6, remote_endpoint->address, &address.sock_addr_types.addr_in6.sin6_addr);
727 address.sock_addr_types.addr_in6.sin6_port = htons((uint16_t)remote_endpoint->port);
728 address.sock_addr_types.addr_in6.sin6_family = AF_INET6;
729 sock_size = sizeof(address.sock_addr_types.addr_in6);
730 } else if (socket->options.domain == AWS_SOCKET_LOCAL) {
731 address.sock_addr_types.un_addr.sun_family = AF_UNIX;
732 strncpy(address.sock_addr_types.un_addr.sun_path, remote_endpoint->address, AWS_ADDRESS_MAX_LEN);
733 sock_size = sizeof(address.sock_addr_types.un_addr);
734 #ifdef USE_VSOCK
735 } else if (socket->options.domain == AWS_SOCKET_VSOCK) {
736 pton_err = parse_cid(remote_endpoint->address, &address.sock_addr_types.vm_addr.svm_cid);
737 address.sock_addr_types.vm_addr.svm_family = AF_VSOCK;
738 address.sock_addr_types.vm_addr.svm_port = remote_endpoint->port;
739 sock_size = sizeof(address.sock_addr_types.vm_addr);
740 #endif
741 } else {
742 AWS_ASSERT(0);
743 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
744 }
745
746 if (pton_err != 1) {
747 int errno_value = errno; /* Always cache errno before potential side-effect */
748 AWS_LOGF_DEBUG(
749 AWS_LS_IO_SOCKET,
750 "id=%p fd=%d: failed to parse address %s:%u.",
751 (void *)socket,
752 socket->io_handle.data.fd,
753 remote_endpoint->address,
754 remote_endpoint->port);
755 return aws_raise_error(s_convert_pton_error(pton_err, errno_value));
756 }
757
758 AWS_LOGF_DEBUG(
759 AWS_LS_IO_SOCKET,
760 "id=%p fd=%d: connecting to endpoint %s:%u.",
761 (void *)socket,
762 socket->io_handle.data.fd,
763 remote_endpoint->address,
764 remote_endpoint->port);
765
766 socket->state = CONNECTING;
767 socket->remote_endpoint = *remote_endpoint;
768 socket->connect_accept_user_data = user_data;
769 socket->connection_result_fn = on_connection_result;
770
771 struct posix_socket *socket_impl = socket->impl;
772
773 socket_impl->connect_args = aws_mem_calloc(socket->allocator, 1, sizeof(struct posix_socket_connect_args));
774 if (!socket_impl->connect_args) {
775 return AWS_OP_ERR;
776 }
777
778 socket_impl->connect_args->socket = socket;
779 socket_impl->connect_args->allocator = socket->allocator;
780
781 socket_impl->connect_args->task.fn = s_handle_socket_timeout;
782 socket_impl->connect_args->task.arg = socket_impl->connect_args;
783
784 int error_code = connect(socket->io_handle.data.fd, (struct sockaddr *)&address.sock_addr_types, sock_size);
785 socket->event_loop = event_loop;
786
787 if (!error_code) {
788 AWS_LOGF_INFO(
789 AWS_LS_IO_SOCKET,
790 "id=%p fd=%d: connected immediately, not scheduling timeout.",
791 (void *)socket,
792 socket->io_handle.data.fd);
793 socket_impl->connect_args->task.fn = s_run_connect_success;
794 /* the subscription for IO will happen once we setup the connection in the task. Since we already
795 * know the connection succeeded, we don't need to register for events yet. */
796 aws_event_loop_schedule_task_now(event_loop, &socket_impl->connect_args->task);
797 }
798
799 if (error_code) {
800 int errno_value = errno; /* Always cache errno before potential side-effect */
801 if (errno_value == EINPROGRESS || errno_value == EALREADY) {
802 AWS_LOGF_TRACE(
803 AWS_LS_IO_SOCKET,
804 "id=%p fd=%d: connection pending waiting on event-loop notification or timeout.",
805 (void *)socket,
806 socket->io_handle.data.fd);
807 /* cache the timeout task; it is possible for the IO subscription to come back virtually immediately
808 * and null out the connect args */
809 struct aws_task *timeout_task = &socket_impl->connect_args->task;
810
811 socket_impl->currently_subscribed = true;
812 /* This event is for when the connection finishes. (the fd will flip writable). */
813 if (aws_event_loop_subscribe_to_io_events(
814 event_loop,
815 &socket->io_handle,
816 AWS_IO_EVENT_TYPE_WRITABLE,
817 s_socket_connect_event,
818 socket_impl->connect_args)) {
819 AWS_LOGF_ERROR(
820 AWS_LS_IO_SOCKET,
821 "id=%p fd=%d: failed to register with event-loop %p.",
822 (void *)socket,
823 socket->io_handle.data.fd,
824 (void *)event_loop);
825 socket_impl->currently_subscribed = false;
826 socket->event_loop = NULL;
827 goto err_clean_up;
828 }
829
830 /* schedule a task to run at the connect timeout interval, if this task runs before the connect
831 * happens, we consider that a timeout. */
832 uint64_t timeout = 0;
833 aws_event_loop_current_clock_time(event_loop, &timeout);
834 timeout += aws_timestamp_convert(
835 socket->options.connect_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
836 AWS_LOGF_TRACE(
837 AWS_LS_IO_SOCKET,
838 "id=%p fd=%d: scheduling timeout task for %llu.",
839 (void *)socket,
840 socket->io_handle.data.fd,
841 (unsigned long long)timeout);
842 aws_event_loop_schedule_task_future(event_loop, timeout_task, timeout);
843 } else {
844 AWS_LOGF_DEBUG(
845 AWS_LS_IO_SOCKET,
846 "id=%p fd=%d: connect failed with error code %d.",
847 (void *)socket,
848 socket->io_handle.data.fd,
849 errno_value);
850 int aws_error = s_determine_socket_error(errno_value);
851 aws_raise_error(aws_error);
852 socket->event_loop = NULL;
853 socket_impl->currently_subscribed = false;
854 goto err_clean_up;
855 }
856 }
857 return AWS_OP_SUCCESS;
858
859 err_clean_up:
860 aws_mem_release(socket->allocator, socket_impl->connect_args);
861 socket_impl->connect_args = NULL;
862 return AWS_OP_ERR;
863 }
864
865 static int s_socket_bind(struct aws_socket *socket, struct aws_socket_bind_options *socket_bind_options) {
866 const struct aws_socket_endpoint *local_endpoint = socket_bind_options->local_endpoint;
867 if (socket->state != INIT) {
868 AWS_LOGF_ERROR(
869 AWS_LS_IO_SOCKET,
870 "id=%p fd=%d: invalid state for bind operation.",
871 (void *)socket,
872 socket->io_handle.data.fd);
873 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
874 }
875
876 size_t address_strlen;
877 if (aws_secure_strlen(local_endpoint->address, AWS_ADDRESS_MAX_LEN, &address_strlen)) {
878 return AWS_OP_ERR;
879 }
880
881 if (aws_socket_validate_port_for_bind(local_endpoint->port, socket->options.domain)) {
882 return AWS_OP_ERR;
883 }
884
885 AWS_LOGF_INFO(
886 AWS_LS_IO_SOCKET,
887 "id=%p fd=%d: binding to %s:%u.",
888 (void *)socket,
889 socket->io_handle.data.fd,
890 local_endpoint->address,
891 local_endpoint->port);
892
893 struct socket_address address;
894 AWS_ZERO_STRUCT(address);
895 socklen_t sock_size = 0;
896 int pton_err = 1;
897 if (socket->options.domain == AWS_SOCKET_IPV4) {
898 pton_err = inet_pton(AF_INET, local_endpoint->address, &address.sock_addr_types.addr_in.sin_addr);
899 address.sock_addr_types.addr_in.sin_port = htons((uint16_t)local_endpoint->port);
900 address.sock_addr_types.addr_in.sin_family = AF_INET;
901 sock_size = sizeof(address.sock_addr_types.addr_in);
902 } else if (socket->options.domain == AWS_SOCKET_IPV6) {
903 pton_err = inet_pton(AF_INET6, local_endpoint->address, &address.sock_addr_types.addr_in6.sin6_addr);
904 address.sock_addr_types.addr_in6.sin6_port = htons((uint16_t)local_endpoint->port);
905 address.sock_addr_types.addr_in6.sin6_family = AF_INET6;
906 sock_size = sizeof(address.sock_addr_types.addr_in6);
907 } else if (socket->options.domain == AWS_SOCKET_LOCAL) {
908 address.sock_addr_types.un_addr.sun_family = AF_UNIX;
909 strncpy(address.sock_addr_types.un_addr.sun_path, local_endpoint->address, AWS_ADDRESS_MAX_LEN);
910 sock_size = sizeof(address.sock_addr_types.un_addr);
911 #ifdef USE_VSOCK
912 } else if (socket->options.domain == AWS_SOCKET_VSOCK) {
913 pton_err = parse_cid(local_endpoint->address, &address.sock_addr_types.vm_addr.svm_cid);
914 address.sock_addr_types.vm_addr.svm_family = AF_VSOCK;
915 address.sock_addr_types.vm_addr.svm_port = local_endpoint->port;
916 sock_size = sizeof(address.sock_addr_types.vm_addr);
917 #endif
918 } else {
919 AWS_ASSERT(0);
920 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
921 }
922
923 if (pton_err != 1) {
924 int errno_value = errno; /* Always cache errno before potential side-effect */
925 AWS_LOGF_ERROR(
926 AWS_LS_IO_SOCKET,
927 "id=%p fd=%d: failed to parse address %s:%u.",
928 (void *)socket,
929 socket->io_handle.data.fd,
930 local_endpoint->address,
931 local_endpoint->port);
932 return aws_raise_error(s_convert_pton_error(pton_err, errno_value));
933 }
934
935 if (bind(socket->io_handle.data.fd, (struct sockaddr *)&address.sock_addr_types, sock_size) != 0) {
936 int errno_value = errno; /* Always cache errno before potential side-effect */
937 AWS_LOGF_ERROR(
938 AWS_LS_IO_SOCKET,
939 "id=%p fd=%d: bind failed with error code %d",
940 (void *)socket,
941 socket->io_handle.data.fd,
942 errno_value);
943
944 aws_raise_error(s_determine_socket_error(errno_value));
945 goto error;
946 }
947
948 if (s_update_local_endpoint(socket)) {
949 goto error;
950 }
951
952 if (socket->options.type == AWS_SOCKET_STREAM) {
953 socket->state = BOUND;
954 } else {
955 /* e.g. UDP is now readable */
956 socket->state = CONNECTED_READ;
957 }
958
959 AWS_LOGF_DEBUG(
960 AWS_LS_IO_SOCKET,
961 "id=%p fd=%d: successfully bound to %s:%u",
962 (void *)socket,
963 socket->io_handle.data.fd,
964 socket->local_endpoint.address,
965 socket->local_endpoint.port);
966
967 return AWS_OP_SUCCESS;
968
969 error:
970 socket->state = ERROR;
971 return AWS_OP_ERR;
972 }
973
974 static int s_socket_listen(struct aws_socket *socket, int backlog_size) {
975 if (socket->state != BOUND) {
976 AWS_LOGF_ERROR(
977 AWS_LS_IO_SOCKET,
978 "id=%p fd=%d: invalid state for listen operation. You must call bind first.",
979 (void *)socket,
980 socket->io_handle.data.fd);
981 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
982 }
983
984 int error_code = listen(socket->io_handle.data.fd, backlog_size);
985
986 if (!error_code) {
987 AWS_LOGF_INFO(
988 AWS_LS_IO_SOCKET, "id=%p fd=%d: successfully listening", (void *)socket, socket->io_handle.data.fd);
989 socket->state = LISTENING;
990 return AWS_OP_SUCCESS;
991 }
992
993 int errno_value = errno; /* Always cache errno before potential side-effect */
994
995 AWS_LOGF_ERROR(
996 AWS_LS_IO_SOCKET,
997 "id=%p fd=%d: listen failed with error code %d",
998 (void *)socket,
999 socket->io_handle.data.fd,
1000 errno_value);
1001
1002 socket->state = ERROR;
1003
1004 return aws_raise_error(s_determine_socket_error(errno_value));
1005 }
1006
1007 /* this is called by the event loop handler that was installed in start_accept(). It runs once the FD goes readable,
1008 * accepts as many as it can and then returns control to the event loop. */
1009 static void s_socket_accept_event(
1010 struct aws_event_loop *event_loop,
1011 struct aws_io_handle *handle,
1012 int events,
1013 void *user_data) {
1014
1015 (void)event_loop;
1016
1017 struct aws_socket *socket = user_data;
1018 struct posix_socket *socket_impl = socket->impl;
1019
1020 AWS_LOGF_DEBUG(
1021 AWS_LS_IO_SOCKET, "id=%p fd=%d: listening event received", (void *)socket, socket->io_handle.data.fd);
1022
1023 if (socket_impl->continue_accept && events & AWS_IO_EVENT_TYPE_READABLE) {
1024 int in_fd = 0;
1025 while (socket_impl->continue_accept && in_fd != -1) {
1026 struct sockaddr_storage in_addr;
1027 socklen_t in_len = sizeof(struct sockaddr_storage);
1028
1029 in_fd = accept(handle->data.fd, (struct sockaddr *)&in_addr, &in_len);
1030 if (in_fd == -1) {
1031 int errno_value = errno; /* Always cache errno before potential side-effect */
1032
1033 if (errno_value == EAGAIN || errno_value == EWOULDBLOCK) {
1034 break;
1035 }
1036
1037 int aws_error = aws_socket_get_error(socket);
1038 aws_raise_error(aws_error);
1039 s_on_connection_error(socket, aws_error);
1040 break;
1041 }
1042
1043 AWS_LOGF_DEBUG(
1044 AWS_LS_IO_SOCKET, "id=%p fd=%d: incoming connection", (void *)socket, socket->io_handle.data.fd);
1045
1046 struct aws_socket *new_sock = aws_mem_calloc(socket->allocator, 1, sizeof(struct aws_socket));
1047
1048 if (!new_sock) {
1049 close(in_fd);
1050 s_on_connection_error(socket, aws_last_error());
1051 continue;
1052 }
1053
1054 if (s_socket_init(new_sock, socket->allocator, &socket->options, in_fd)) {
1055 aws_mem_release(socket->allocator, new_sock);
1056 s_on_connection_error(socket, aws_last_error());
1057 continue;
1058 }
1059
1060 new_sock->local_endpoint = socket->local_endpoint;
1061 new_sock->state = CONNECTED_READ | CONNECTED_WRITE;
1062 uint32_t port = 0;
1063
1064 /* get the info on the incoming socket's address */
1065 if (in_addr.ss_family == AF_INET) {
1066 struct sockaddr_in *s = (struct sockaddr_in *)&in_addr;
1067 port = ntohs(s->sin_port);
1068 /* this came from the kernel, a.) it won't fail. b.) even if it does
1069 * its not fatal. come back and add logging later. */
1070 if (!inet_ntop(
1071 AF_INET,
1072 &s->sin_addr,
1073 new_sock->remote_endpoint.address,
1074 sizeof(new_sock->remote_endpoint.address))) {
1075 AWS_LOGF_WARN(
1076 AWS_LS_IO_SOCKET,
1077 "id=%p fd=%d:. Failed to determine remote address.",
1078 (void *)socket,
1079 socket->io_handle.data.fd);
1080 }
1081 new_sock->options.domain = AWS_SOCKET_IPV4;
1082 } else if (in_addr.ss_family == AF_INET6) {
1083 /* this came from the kernel, a.) it won't fail. b.) even if it does
1084 * its not fatal. come back and add logging later. */
1085 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&in_addr;
1086 port = ntohs(s->sin6_port);
1087 if (!inet_ntop(
1088 AF_INET6,
1089 &s->sin6_addr,
1090 new_sock->remote_endpoint.address,
1091 sizeof(new_sock->remote_endpoint.address))) {
1092 AWS_LOGF_WARN(
1093 AWS_LS_IO_SOCKET,
1094 "id=%p fd=%d:. Failed to determine remote address.",
1095 (void *)socket,
1096 socket->io_handle.data.fd);
1097 }
1098 new_sock->options.domain = AWS_SOCKET_IPV6;
1099 } else if (in_addr.ss_family == AF_UNIX) {
1100 new_sock->remote_endpoint = socket->local_endpoint;
1101 new_sock->options.domain = AWS_SOCKET_LOCAL;
1102 }
1103
1104 new_sock->remote_endpoint.port = port;
1105
1106 AWS_LOGF_INFO(
1107 AWS_LS_IO_SOCKET,
1108 "id=%p fd=%d: connected to %s:%d, incoming fd %d",
1109 (void *)socket,
1110 socket->io_handle.data.fd,
1111 new_sock->remote_endpoint.address,
1112 new_sock->remote_endpoint.port,
1113 in_fd);
1114
1115 int flags = fcntl(in_fd, F_GETFL, 0);
1116
1117 flags |= O_NONBLOCK | O_CLOEXEC;
1118 fcntl(in_fd, F_SETFL, flags);
1119
1120 bool close_occurred = false;
1121 socket_impl->close_happened = &close_occurred;
1122 socket->accept_result_fn(socket, AWS_ERROR_SUCCESS, new_sock, socket->connect_accept_user_data);
1123
1124 if (close_occurred) {
1125 return;
1126 }
1127
1128 socket_impl->close_happened = NULL;
1129 }
1130 }
1131
1132 AWS_LOGF_TRACE(
1133 AWS_LS_IO_SOCKET,
1134 "id=%p fd=%d: finished processing incoming connections, "
1135 "waiting on event-loop notification",
1136 (void *)socket,
1137 socket->io_handle.data.fd);
1138 }
1139
1140 static void s_process_invoke_on_accept_start(struct aws_task *task, void *args, enum aws_task_status status) {
1141 (void)task;
1142 struct on_start_accept_result_args *on_accept_args = args;
1143 if (status == AWS_TASK_STATUS_RUN_READY) {
1144 struct aws_socket *socket = on_accept_args->socket;
1145
1146 if (on_accept_args->on_accept_start) {
1147 // socket should not be cleaned up until on_accept_result callback is invoked.
1148 AWS_FATAL_ASSERT(socket);
1149 on_accept_args->on_accept_start(socket, on_accept_args->error, on_accept_args->on_accept_start_user_data);
1150 }
1151 }
1152 aws_mem_release(on_accept_args->allocator, args);
1153 }
1154
1155 static void s_invoke_on_accept_start(
1156 struct aws_allocator *allocator,
1157 struct aws_event_loop *loop,
1158 struct aws_socket *socket,
1159 int error,
1160 aws_socket_on_accept_started_fn *on_accept_start,
1161 void *on_accept_start_user_data) {
1162 struct on_start_accept_result_args *args = aws_mem_calloc(allocator, 1, sizeof(struct on_start_accept_result_args));
1163
1164 args->allocator = allocator;
1165 args->socket = socket;
1166 args->error = error;
1167 args->on_accept_start = on_accept_start;
1168 args->on_accept_start_user_data = on_accept_start_user_data;
1169
1170 aws_task_init(&args->task, s_process_invoke_on_accept_start, args, "SocketOnAcceptStartResultTask");
1171 aws_event_loop_schedule_task_now(loop, &args->task);
1172 }
1173
1174 static int s_socket_start_accept(
1175 struct aws_socket *socket,
1176 struct aws_event_loop *accept_loop,
1177 struct aws_socket_listener_options options) {
1178 AWS_ASSERT(options.on_accept_result);
1179 AWS_ASSERT(accept_loop);
1180
1181 if (socket->event_loop) {
1182 AWS_LOGF_ERROR(
1183 AWS_LS_IO_SOCKET,
1184 "id=%p fd=%d: is already assigned to event-loop %p.",
1185 (void *)socket,
1186 socket->io_handle.data.fd,
1187 (void *)socket->event_loop);
1188 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
1189 }
1190
1191 if (socket->state != LISTENING) {
1192 AWS_LOGF_ERROR(
1193 AWS_LS_IO_SOCKET,
1194 "id=%p fd=%d: invalid state for start_accept operation. You must call listen first.",
1195 (void *)socket,
1196 socket->io_handle.data.fd);
1197 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
1198 }
1199
1200 socket->accept_result_fn = options.on_accept_result;
1201 socket->connect_accept_user_data = options.on_accept_result_user_data;
1202 socket->event_loop = accept_loop;
1203 struct posix_socket *socket_impl = socket->impl;
1204 socket_impl->continue_accept = true;
1205 socket_impl->currently_subscribed = true;
1206
1207 if (aws_event_loop_subscribe_to_io_events(
1208 socket->event_loop, &socket->io_handle, AWS_IO_EVENT_TYPE_READABLE, s_socket_accept_event, socket)) {
1209 AWS_LOGF_ERROR(
1210 AWS_LS_IO_SOCKET,
1211 "id=%p fd=%d: failed to subscribe to event-loop %p.",
1212 (void *)socket,
1213 socket->io_handle.data.fd,
1214 (void *)socket->event_loop);
1215 socket_impl->continue_accept = false;
1216 socket_impl->currently_subscribed = false;
1217 socket->event_loop = NULL;
1218
1219 return AWS_OP_ERR;
1220 }
1221
1222 s_invoke_on_accept_start(
1223 socket->allocator,
1224 accept_loop,
1225 socket,
1226 AWS_OP_SUCCESS,
1227 options.on_accept_start,
1228 options.on_accept_start_user_data);
1229 return AWS_OP_SUCCESS;
1230 }
1231
1232 struct stop_accept_args {
1233 struct aws_task task;
1234 struct aws_mutex mutex;
1235 struct aws_condition_variable condition_variable;
1236 struct aws_socket *socket;
1237 int ret_code;
1238 bool invoked;
1239 };
1240
1241 static bool s_stop_accept_pred(void *arg) {
1242 struct stop_accept_args *stop_accept_args = arg;
1243 return stop_accept_args->invoked;
1244 }
1245
1246 static void s_stop_accept_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1247 (void)task;
1248 (void)status;
1249
1250 struct stop_accept_args *stop_accept_args = arg;
1251 aws_mutex_lock(&stop_accept_args->mutex);
1252 stop_accept_args->ret_code = AWS_OP_SUCCESS;
1253 if (aws_socket_stop_accept(stop_accept_args->socket)) {
1254 stop_accept_args->ret_code = aws_last_error();
1255 }
1256 stop_accept_args->invoked = true;
1257 aws_condition_variable_notify_one(&stop_accept_args->condition_variable);
1258 aws_mutex_unlock(&stop_accept_args->mutex);
1259 }
1260
1261 static int s_socket_stop_accept(struct aws_socket *socket) {
1262 if (socket->state != LISTENING) {
1263 AWS_LOGF_ERROR(
1264 AWS_LS_IO_SOCKET,
1265 "id=%p fd=%d: is not in a listening state, can't stop_accept.",
1266 (void *)socket,
1267 socket->io_handle.data.fd);
1268 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
1269 }
1270
1271 AWS_LOGF_INFO(
1272 AWS_LS_IO_SOCKET, "id=%p fd=%d: stopping accepting new connections", (void *)socket, socket->io_handle.data.fd);
1273
1274 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
1275 struct stop_accept_args args = {
1276 .mutex = AWS_MUTEX_INIT,
1277 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
1278 .invoked = false,
1279 .socket = socket,
1280 .ret_code = AWS_OP_SUCCESS,
1281 .task = {.fn = s_stop_accept_task},
1282 };
1283 AWS_LOGF_INFO(
1284 AWS_LS_IO_SOCKET,
1285 "id=%p fd=%d: stopping accepting new connections from a different thread than "
1286 "the socket is running from. Blocking until it shuts down.",
1287 (void *)socket,
1288 socket->io_handle.data.fd);
1289 /* Look.... I know what I'm doing.... trust me, I'm an engineer.
1290 * We wait on the completion before 'args' goes out of scope.
1291 * NOLINTNEXTLINE */
1292 args.task.arg = &args;
1293 aws_mutex_lock(&args.mutex);
1294 aws_event_loop_schedule_task_now(socket->event_loop, &args.task);
1295 aws_condition_variable_wait_pred(&args.condition_variable, &args.mutex, s_stop_accept_pred, &args);
1296 aws_mutex_unlock(&args.mutex);
1297 AWS_LOGF_INFO(
1298 AWS_LS_IO_SOCKET,
1299 "id=%p fd=%d: stop accept task finished running.",
1300 (void *)socket,
1301 socket->io_handle.data.fd);
1302
1303 if (args.ret_code) {
1304 return aws_raise_error(args.ret_code);
1305 }
1306 return AWS_OP_SUCCESS;
1307 }
1308
1309 int ret_val = AWS_OP_SUCCESS;
1310 struct posix_socket *socket_impl = socket->impl;
1311 if (socket_impl->currently_subscribed) {
1312 ret_val = aws_event_loop_unsubscribe_from_io_events(socket->event_loop, &socket->io_handle);
1313 socket_impl->currently_subscribed = false;
1314 socket_impl->continue_accept = false;
1315 socket->event_loop = NULL;
1316 }
1317
1318 return ret_val;
1319 }
1320
1321 static int s_socket_set_options(struct aws_socket *socket, const struct aws_socket_options *options) {
1322 if (socket->options.domain != options->domain || socket->options.type != options->type) {
1323 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1324 }
1325
1326 AWS_LOGF_DEBUG(
1327 AWS_LS_IO_SOCKET,
1328 "id=%p fd=%d: setting socket options to: keep-alive %d, keep-alive timeout %d, keep-alive interval %d, "
1329 "keep-alive probe "
1330 "count %d.",
1331 (void *)socket,
1332 socket->io_handle.data.fd,
1333 (int)options->keepalive,
1334 (int)options->keep_alive_timeout_sec,
1335 (int)options->keep_alive_interval_sec,
1336 (int)options->keep_alive_max_failed_probes);
1337
1338 socket->options = *options;
1339
1340 #ifdef NO_SIGNAL_SOCK_OPT
1341 int option_value = 1;
1342 if (AWS_UNLIKELY(setsockopt(
1343 socket->io_handle.data.fd, SOL_SOCKET, NO_SIGNAL_SOCK_OPT, &option_value, sizeof(option_value)))) {
1344 int errno_value = errno; /* Always cache errno before potential side-effect */
1345 AWS_LOGF_WARN(
1346 AWS_LS_IO_SOCKET,
1347 "id=%p fd=%d: setsockopt() for NO_SIGNAL_SOCK_OPT failed with errno %d.",
1348 (void *)socket,
1349 socket->io_handle.data.fd,
1350 errno_value);
1351 }
1352 #endif /* NO_SIGNAL_SOCK_OPT */
1353
1354 int reuse = 1;
1355 if (AWS_UNLIKELY(setsockopt(socket->io_handle.data.fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)))) {
1356 int errno_value = errno; /* Always cache errno before potential side-effect */
1357 AWS_LOGF_WARN(
1358 AWS_LS_IO_SOCKET,
1359 "id=%p fd=%d: setsockopt() for SO_REUSEADDR failed with errno %d.",
1360 (void *)socket,
1361 socket->io_handle.data.fd,
1362 errno_value);
1363 }
1364 size_t network_interface_length = 0;
1365 if (aws_secure_strlen(options->network_interface_name, AWS_NETWORK_INTERFACE_NAME_MAX, &network_interface_length)) {
1366 AWS_LOGF_ERROR(
1367 AWS_LS_IO_SOCKET,
1368 "id=%p fd=%d: network_interface_name max length must be less or equal than %d bytes including NULL "
1369 "terminated",
1370 (void *)socket,
1371 socket->io_handle.data.fd,
1372 AWS_NETWORK_INTERFACE_NAME_MAX);
1373 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1374 }
1375 if (network_interface_length != 0) {
1376 #if defined(SO_BINDTODEVICE)
1377 if (setsockopt(
1378 socket->io_handle.data.fd,
1379 SOL_SOCKET,
1380 SO_BINDTODEVICE,
1381 options->network_interface_name,
1382 network_interface_length)) {
1383 int errno_value = errno; /* Always cache errno before potential side-effect */
1384 AWS_LOGF_ERROR(
1385 AWS_LS_IO_SOCKET,
1386 "id=%p fd=%d: setsockopt() with SO_BINDTODEVICE for \"%s\" failed with errno %d.",
1387 (void *)socket,
1388 socket->io_handle.data.fd,
1389 options->network_interface_name,
1390 errno_value);
1391 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1392 }
1393 #elif defined(IP_BOUND_IF)
1394 /*
1395 * If SO_BINDTODEVICE is not supported, the alternative is IP_BOUND_IF which requires an index instead
1396 * of a name. We are not using this everywhere because this requires 2 system calls instead of 1, and is
1397 * dependent upon the type of sockets, which doesn't support AWS_SOCKET_LOCAL. As a future optimization, we can
1398 * look into caching the result of if_nametoindex.
1399 */
1400 uint network_interface_index = if_nametoindex(options->network_interface_name);
1401 if (network_interface_index == 0) {
1402 int errno_value = errno; /* Always cache errno before potential side-effect */
1403 AWS_LOGF_ERROR(
1404 AWS_LS_IO_SOCKET,
1405 "id=%p fd=%d: network_interface_name \"%s\" not found. if_nametoindex() failed with errno %d.",
1406 (void *)socket,
1407 socket->io_handle.data.fd,
1408 options->network_interface_name,
1409 errno_value);
1410 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1411 }
1412 if (options->domain == AWS_SOCKET_IPV6) {
1413 if (setsockopt(
1414 socket->io_handle.data.fd,
1415 IPPROTO_IPV6,
1416 IPV6_BOUND_IF,
1417 &network_interface_index,
1418 sizeof(network_interface_index))) {
1419 int errno_value = errno; /* Always cache errno before potential side-effect */
1420 AWS_LOGF_ERROR(
1421 AWS_LS_IO_SOCKET,
1422 "id=%p fd=%d: setsockopt() with IPV6_BOUND_IF for \"%s\" failed with errno %d.",
1423 (void *)socket,
1424 socket->io_handle.data.fd,
1425 options->network_interface_name,
1426 errno_value);
1427 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1428 }
1429 } else if (setsockopt(
1430 socket->io_handle.data.fd,
1431 IPPROTO_IP,
1432 IP_BOUND_IF,
1433 &network_interface_index,
1434 sizeof(network_interface_index))) {
1435 int errno_value = errno; /* Always cache errno before potential side-effect */
1436 AWS_LOGF_ERROR(
1437 AWS_LS_IO_SOCKET,
1438 "id=%p fd=%d: setsockopt() with IP_BOUND_IF for \"%s\" failed with errno %d.",
1439 (void *)socket,
1440 socket->io_handle.data.fd,
1441 options->network_interface_name,
1442 errno_value);
1443 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
1444 }
1445 #else
1446 AWS_LOGF_ERROR(
1447 AWS_LS_IO_SOCKET,
1448 "id=%p fd=%d: network_interface_name is not supported on this platform.",
1449 (void *)socket,
1450 socket->io_handle.data.fd);
1451 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
1452 #endif
1453 }
1454 if (options->type == AWS_SOCKET_STREAM && options->domain != AWS_SOCKET_LOCAL) {
1455 if (socket->options.keepalive) {
1456 int keep_alive = 1;
1457 if (AWS_UNLIKELY(
1458 setsockopt(socket->io_handle.data.fd, SOL_SOCKET, SO_KEEPALIVE, &keep_alive, sizeof(int)))) {
1459 int errno_value = errno; /* Always cache errno before potential side-effect */
1460 AWS_LOGF_WARN(
1461 AWS_LS_IO_SOCKET,
1462 "id=%p fd=%d: setsockopt() for enabling SO_KEEPALIVE failed with errno %d.",
1463 (void *)socket,
1464 socket->io_handle.data.fd,
1465 errno_value);
1466 }
1467 }
1468
1469 #if !defined(__OpenBSD__)
1470 if (socket->options.keep_alive_interval_sec && socket->options.keep_alive_timeout_sec) {
1471 int ival_in_secs = socket->options.keep_alive_interval_sec;
1472 if (AWS_UNLIKELY(setsockopt(
1473 socket->io_handle.data.fd, IPPROTO_TCP, TCP_KEEPIDLE, &ival_in_secs, sizeof(ival_in_secs)))) {
1474 int errno_value = errno; /* Always cache errno before potential side-effect */
1475 AWS_LOGF_WARN(
1476 AWS_LS_IO_SOCKET,
1477 "id=%p fd=%d: setsockopt() for enabling TCP_KEEPIDLE for TCP failed with errno %d.",
1478 (void *)socket,
1479 socket->io_handle.data.fd,
1480 errno_value);
1481 }
1482
1483 ival_in_secs = socket->options.keep_alive_timeout_sec;
1484 if (AWS_UNLIKELY(setsockopt(
1485 socket->io_handle.data.fd, IPPROTO_TCP, TCP_KEEPINTVL, &ival_in_secs, sizeof(ival_in_secs)))) {
1486 int errno_value = errno; /* Always cache errno before potential side-effect */
1487 AWS_LOGF_WARN(
1488 AWS_LS_IO_SOCKET,
1489 "id=%p fd=%d: setsockopt() for enabling TCP_KEEPINTVL for TCP failed with errno %d.",
1490 (void *)socket,
1491 socket->io_handle.data.fd,
1492 errno_value);
1493 }
1494 }
1495
1496 if (socket->options.keep_alive_max_failed_probes) {
1497 int max_probes = socket->options.keep_alive_max_failed_probes;
1498 if (AWS_UNLIKELY(
1499 setsockopt(socket->io_handle.data.fd, IPPROTO_TCP, TCP_KEEPCNT, &max_probes, sizeof(max_probes)))) {
1500 int errno_value = errno; /* Always cache errno before potential side-effect */
1501 AWS_LOGF_WARN(
1502 AWS_LS_IO_SOCKET,
1503 "id=%p fd=%d: setsockopt() for enabling TCP_KEEPCNT for TCP failed with errno %d.",
1504 (void *)socket,
1505 socket->io_handle.data.fd,
1506 errno_value);
1507 }
1508 }
1509 #endif /* __OpenBSD__ */
1510 }
1511
1512 return AWS_OP_SUCCESS;
1513 }
1514
1515 struct socket_write_request {
1516 struct aws_byte_cursor cursor_cpy;
1517 aws_socket_on_write_completed_fn *written_fn;
1518 void *write_user_data;
1519 struct aws_linked_list_node node;
1520 size_t original_buffer_len;
1521 int error_code;
1522 };
1523
1524 struct posix_socket_close_args {
1525 struct aws_mutex mutex;
1526 struct aws_condition_variable condition_variable;
1527 struct aws_socket *socket;
1528 bool invoked;
1529 int ret_code;
1530 };
1531
1532 static bool s_close_predicate(void *arg) {
1533 struct posix_socket_close_args *close_args = arg;
1534 return close_args->invoked;
1535 }
1536
1537 static void s_close_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1538 (void)task;
1539 (void)status;
1540
1541 struct posix_socket_close_args *close_args = arg;
1542 aws_mutex_lock(&close_args->mutex);
1543 close_args->ret_code = AWS_OP_SUCCESS;
1544
1545 if (aws_socket_close(close_args->socket)) {
1546 close_args->ret_code = aws_last_error();
1547 }
1548
1549 close_args->invoked = true;
1550 aws_condition_variable_notify_one(&close_args->condition_variable);
1551 aws_mutex_unlock(&close_args->mutex);
1552 }
1553
1554 static int s_socket_close(struct aws_socket *socket) {
1555 struct posix_socket *socket_impl = socket->impl;
1556 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p fd=%d: closing", (void *)socket, socket->io_handle.data.fd);
1557 struct aws_event_loop *event_loop = socket->event_loop;
1558 if (socket->event_loop) {
1559 /* don't freak out on me, this almost never happens, and never occurs inside a channel
1560 * it only gets hit from a listening socket shutting down or from a unit test. */
1561 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
1562 AWS_LOGF_INFO(
1563 AWS_LS_IO_SOCKET,
1564 "id=%p fd=%d: closing from a different thread than "
1565 "the socket is running from. Blocking until it closes down.",
1566 (void *)socket,
1567 socket->io_handle.data.fd);
1568 /* the only time we allow this kind of thing is when you're a listener.*/
1569 if (socket->state != LISTENING) {
1570 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
1571 }
1572
1573 struct posix_socket_close_args args = {
1574 .mutex = AWS_MUTEX_INIT,
1575 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
1576 .socket = socket,
1577 .ret_code = AWS_OP_SUCCESS,
1578 .invoked = false,
1579 };
1580
1581 struct aws_task close_task = {
1582 .fn = s_close_task,
1583 .arg = &args,
1584 };
1585
1586 int fd_for_logging = socket->io_handle.data.fd; /* socket's fd gets reset before final log */
1587 (void)fd_for_logging;
1588
1589 aws_mutex_lock(&args.mutex);
1590 aws_event_loop_schedule_task_now(socket->event_loop, &close_task);
1591 aws_condition_variable_wait_pred(&args.condition_variable, &args.mutex, s_close_predicate, &args);
1592 aws_mutex_unlock(&args.mutex);
1593 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "id=%p fd=%d: close task completed.", (void *)socket, fd_for_logging);
1594 if (socket_impl->on_close_complete) {
1595 socket_impl->on_close_complete(socket_impl->close_user_data);
1596 }
1597 if (args.ret_code) {
1598 return aws_raise_error(args.ret_code);
1599 }
1600
1601 return AWS_OP_SUCCESS;
1602 }
1603
1604 if (socket_impl->currently_subscribed) {
1605 if (socket->state & LISTENING) {
1606 aws_socket_stop_accept(socket);
1607 } else {
1608 int err_code = aws_event_loop_unsubscribe_from_io_events(socket->event_loop, &socket->io_handle);
1609
1610 if (err_code) {
1611 return AWS_OP_ERR;
1612 }
1613 }
1614 socket_impl->currently_subscribed = false;
1615 socket->event_loop = NULL;
1616 }
1617 }
1618
1619 if (socket_impl->close_happened) {
1620 *socket_impl->close_happened = true;
1621 }
1622
1623 if (socket_impl->connect_args) {
1624 socket_impl->connect_args->socket = NULL;
1625 socket_impl->connect_args = NULL;
1626 }
1627
1628 if (aws_socket_is_open(socket)) {
1629 close(socket->io_handle.data.fd);
1630 socket->io_handle.data.fd = -1;
1631 socket->state = CLOSED;
1632
1633 /* ensure callbacks for pending writes fire (in order) before this close function returns */
1634
1635 if (socket_impl->written_task_scheduled) {
1636 aws_event_loop_cancel_task(event_loop, &socket_impl->written_task);
1637 }
1638
1639 while (!aws_linked_list_empty(&socket_impl->written_queue)) {
1640 struct aws_linked_list_node *node = aws_linked_list_pop_front(&socket_impl->written_queue);
1641 struct socket_write_request *write_request = AWS_CONTAINER_OF(node, struct socket_write_request, node);
1642 size_t bytes_written = write_request->original_buffer_len - write_request->cursor_cpy.len;
1643 write_request->written_fn(socket, write_request->error_code, bytes_written, write_request->write_user_data);
1644 aws_mem_release(socket->allocator, write_request);
1645 }
1646
1647 while (!aws_linked_list_empty(&socket_impl->write_queue)) {
1648 struct aws_linked_list_node *node = aws_linked_list_pop_front(&socket_impl->write_queue);
1649 struct socket_write_request *write_request = AWS_CONTAINER_OF(node, struct socket_write_request, node);
1650 size_t bytes_written = write_request->original_buffer_len - write_request->cursor_cpy.len;
1651 write_request->written_fn(socket, AWS_IO_SOCKET_CLOSED, bytes_written, write_request->write_user_data);
1652 aws_mem_release(socket->allocator, write_request);
1653 }
1654 }
1655
1656 if (socket_impl->on_close_complete) {
1657 socket_impl->on_close_complete(socket_impl->close_user_data);
1658 }
1659 return AWS_OP_SUCCESS;
1660 }
1661
1662 static int s_socket_shutdown_dir(struct aws_socket *socket, enum aws_channel_direction dir) {
1663 int how = dir == AWS_CHANNEL_DIR_READ ? 0 : 1;
1664 AWS_LOGF_DEBUG(
1665 AWS_LS_IO_SOCKET, "id=%p fd=%d: shutting down in direction %d", (void *)socket, socket->io_handle.data.fd, dir);
1666 if (shutdown(socket->io_handle.data.fd, how)) {
1667 int errno_value = errno; /* Always cache errno before potential side-effect */
1668 int aws_error = s_determine_socket_error(errno_value);
1669 return aws_raise_error(aws_error);
1670 }
1671
1672 if (dir == AWS_CHANNEL_DIR_READ) {
1673 socket->state &= ~CONNECTED_READ;
1674 } else {
1675 socket->state &= ~CONNECTED_WRITE;
1676 }
1677
1678 return AWS_OP_SUCCESS;
1679 }
1680
1681 static void s_written_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1682 (void)task;
1683 (void)status;
1684
1685 struct aws_socket *socket = arg;
1686 struct posix_socket *socket_impl = socket->impl;
1687
1688 socket_impl->written_task_scheduled = false;
1689
1690 /* this is to handle a race condition when a callback kicks off a cleanup, or the user decides
1691 * to close the socket based on something they read (SSL validation failed for example).
1692 * if clean_up happens when internal_refcount > 0, socket_impl is kept dangling */
1693 aws_ref_count_acquire(&socket_impl->internal_refcount);
1694
1695 /* Notes about weird loop:
1696 * 1) Only process the initial contents of queue when this task is run,
1697 * ignoring any writes queued during delivery.
1698 * If we simply looped until the queue was empty, we could get into a
1699 * synchronous loop of completing and writing and completing and writing...
1700 * and it would be tough for multiple sockets to share an event-loop fairly.
1701 * 2) Check if queue is empty with each iteration.
1702 * If user calls close() from the callback, close() will process all
1703 * nodes in the written_queue, and the queue will be empty when the
1704 * callstack gets back to here. */
1705 if (!aws_linked_list_empty(&socket_impl->written_queue)) {
1706 struct aws_linked_list_node *stop_after = aws_linked_list_back(&socket_impl->written_queue);
1707 do {
1708 struct aws_linked_list_node *node = aws_linked_list_pop_front(&socket_impl->written_queue);
1709 struct socket_write_request *write_request = AWS_CONTAINER_OF(node, struct socket_write_request, node);
1710 size_t bytes_written = write_request->original_buffer_len - write_request->cursor_cpy.len;
1711 write_request->written_fn(socket, write_request->error_code, bytes_written, write_request->write_user_data);
1712 aws_mem_release(socket_impl->allocator, write_request);
1713 if (node == stop_after) {
1714 break;
1715 }
1716 } while (!aws_linked_list_empty(&socket_impl->written_queue));
1717 }
1718
1719 aws_ref_count_release(&socket_impl->internal_refcount);
1720 }
1721
1722 /* this gets called in two scenarios.
1723 * 1st scenario, someone called aws_socket_write() and we want to try writing now, so an error can be returned
1724 * immediately if something bad has happened to the socket. In this case, `parent_request` is set.
1725 * 2nd scenario, the event loop notified us that the socket went writable. In this case `parent_request` is NULL */
1726 static int s_process_socket_write_requests(struct aws_socket *socket, struct socket_write_request *parent_request) {
1727 struct posix_socket *socket_impl = socket->impl;
1728
1729 if (parent_request) {
1730 AWS_LOGF_TRACE(
1731 AWS_LS_IO_SOCKET,
1732 "id=%p fd=%d: processing write requests, called from aws_socket_write",
1733 (void *)socket,
1734 socket->io_handle.data.fd);
1735 } else {
1736 AWS_LOGF_TRACE(
1737 AWS_LS_IO_SOCKET,
1738 "id=%p fd=%d: processing write requests, invoked by the event-loop",
1739 (void *)socket,
1740 socket->io_handle.data.fd);
1741 }
1742
1743 bool purge = false;
1744 int aws_error = AWS_OP_SUCCESS;
1745 bool parent_request_failed = false;
1746 bool pushed_to_written_queue = false;
1747
1748 /* if a close call happens in the middle, this queue will have been cleaned out from under us. */
1749 while (!aws_linked_list_empty(&socket_impl->write_queue)) {
1750 struct aws_linked_list_node *node = aws_linked_list_front(&socket_impl->write_queue);
1751 struct socket_write_request *write_request = AWS_CONTAINER_OF(node, struct socket_write_request, node);
1752
1753 AWS_LOGF_TRACE(
1754 AWS_LS_IO_SOCKET,
1755 "id=%p fd=%d: dequeued write request of size %llu, remaining to write %llu",
1756 (void *)socket,
1757 socket->io_handle.data.fd,
1758 (unsigned long long)write_request->original_buffer_len,
1759 (unsigned long long)write_request->cursor_cpy.len);
1760
1761 ssize_t written = send(
1762 socket->io_handle.data.fd, write_request->cursor_cpy.ptr, write_request->cursor_cpy.len, NO_SIGNAL_SEND);
1763 int errno_value = errno; /* Always cache errno before potential side-effect */
1764
1765 AWS_LOGF_TRACE(
1766 AWS_LS_IO_SOCKET,
1767 "id=%p fd=%d: send written size %d",
1768 (void *)socket,
1769 socket->io_handle.data.fd,
1770 (int)written);
1771
1772 if (written < 0) {
1773 if (errno_value == EAGAIN) {
1774 AWS_LOGF_TRACE(
1775 AWS_LS_IO_SOCKET, "id=%p fd=%d: returned would block", (void *)socket, socket->io_handle.data.fd);
1776 break;
1777 }
1778
1779 if (errno_value == EPIPE) {
1780 AWS_LOGF_DEBUG(
1781 AWS_LS_IO_SOCKET,
1782 "id=%p fd=%d: already closed before write",
1783 (void *)socket,
1784 socket->io_handle.data.fd);
1785 aws_error = AWS_IO_SOCKET_CLOSED;
1786 aws_raise_error(aws_error);
1787 purge = true;
1788 break;
1789 }
1790
1791 purge = true;
1792 AWS_LOGF_DEBUG(
1793 AWS_LS_IO_SOCKET,
1794 "id=%p fd=%d: write error with error code %d",
1795 (void *)socket,
1796 socket->io_handle.data.fd,
1797 errno_value);
1798 aws_error = s_determine_socket_error(errno_value);
1799 aws_raise_error(aws_error);
1800 break;
1801 }
1802
1803 size_t remaining_to_write = write_request->cursor_cpy.len;
1804
1805 aws_byte_cursor_advance(&write_request->cursor_cpy, (size_t)written);
1806 AWS_LOGF_TRACE(
1807 AWS_LS_IO_SOCKET,
1808 "id=%p fd=%d: remaining write request to write %llu",
1809 (void *)socket,
1810 socket->io_handle.data.fd,
1811 (unsigned long long)write_request->cursor_cpy.len);
1812
1813 if ((size_t)written == remaining_to_write) {
1814 AWS_LOGF_TRACE(
1815 AWS_LS_IO_SOCKET, "id=%p fd=%d: write request completed", (void *)socket, socket->io_handle.data.fd);
1816
1817 aws_linked_list_remove(node);
1818 write_request->error_code = AWS_ERROR_SUCCESS;
1819 aws_linked_list_push_back(&socket_impl->written_queue, node);
1820 pushed_to_written_queue = true;
1821 }
1822 }
1823
1824 if (purge) {
1825 while (!aws_linked_list_empty(&socket_impl->write_queue)) {
1826 struct aws_linked_list_node *node = aws_linked_list_pop_front(&socket_impl->write_queue);
1827 struct socket_write_request *write_request = AWS_CONTAINER_OF(node, struct socket_write_request, node);
1828
1829 /* If this fn was invoked directly from aws_socket_write(), don't invoke the error callback
1830 * as the user will be able to rely on the return value from aws_socket_write() */
1831 if (write_request == parent_request) {
1832 parent_request_failed = true;
1833 aws_mem_release(socket->allocator, write_request);
1834 } else {
1835 write_request->error_code = aws_error;
1836 aws_linked_list_push_back(&socket_impl->written_queue, node);
1837 pushed_to_written_queue = true;
1838 }
1839 }
1840 }
1841
1842 if (pushed_to_written_queue && !socket_impl->written_task_scheduled) {
1843 socket_impl->written_task_scheduled = true;
1844 aws_task_init(&socket_impl->written_task, s_written_task, socket, "socket_written_task");
1845 aws_event_loop_schedule_task_now(socket->event_loop, &socket_impl->written_task);
1846 }
1847
1848 /* Only report error if aws_socket_write() invoked this function and its write_request failed */
1849 if (!parent_request_failed) {
1850 return AWS_OP_SUCCESS;
1851 }
1852
1853 aws_raise_error(aws_error);
1854 return AWS_OP_ERR;
1855 }
1856
1857 static void s_on_socket_io_event(
1858 struct aws_event_loop *event_loop,
1859 struct aws_io_handle *handle,
1860 int events,
1861 void *user_data) {
1862 (void)event_loop;
1863 (void)handle;
1864 struct aws_socket *socket = user_data;
1865 struct posix_socket *socket_impl = socket->impl;
1866
1867 /* this is to handle a race condition when an error kicks off a cleanup, or the user decides
1868 * to close the socket based on something they read (SSL validation failed for example).
1869 * if clean_up happens when internal_refcount > 0, socket_impl is kept dangling but currently
1870 * subscribed is set to false. */
1871 aws_ref_count_acquire(&socket_impl->internal_refcount);
1872
1873 /* NOTE: READABLE|WRITABLE|HANG_UP events might arrive simultaneously
1874 * (e.g. peer sends last few bytes and immediately hangs up).
1875 * Notify user of READABLE|WRITABLE events first, so they try to read any remaining bytes. */
1876
1877 if (socket_impl->currently_subscribed && events & AWS_IO_EVENT_TYPE_READABLE) {
1878 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p fd=%d: is readable", (void *)socket, socket->io_handle.data.fd);
1879 if (socket->readable_fn) {
1880 socket->readable_fn(socket, AWS_OP_SUCCESS, socket->readable_user_data);
1881 }
1882 }
1883 /* if socket closed in between these branches, the currently_subscribed will be false and socket_impl will not
1884 * have been cleaned up, so this next branch is safe. */
1885 if (socket_impl->currently_subscribed && events & AWS_IO_EVENT_TYPE_WRITABLE) {
1886 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p fd=%d: is writable", (void *)socket, socket->io_handle.data.fd);
1887 s_process_socket_write_requests(socket, NULL);
1888 }
1889
1890 if (events & AWS_IO_EVENT_TYPE_REMOTE_HANG_UP || events & AWS_IO_EVENT_TYPE_CLOSED) {
1891 aws_raise_error(AWS_IO_SOCKET_CLOSED);
1892 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p fd=%d: closed remotely", (void *)socket, socket->io_handle.data.fd);
1893 if (socket->readable_fn) {
1894 socket->readable_fn(socket, AWS_IO_SOCKET_CLOSED, socket->readable_user_data);
1895 }
1896 goto end_check;
1897 }
1898
1899 if (socket_impl->currently_subscribed && events & AWS_IO_EVENT_TYPE_ERROR) {
1900 int aws_error = aws_socket_get_error(socket);
1901 aws_raise_error(aws_error);
1902 AWS_LOGF_TRACE(
1903 AWS_LS_IO_SOCKET, "id=%p fd=%d: error event occurred", (void *)socket, socket->io_handle.data.fd);
1904 if (socket->readable_fn) {
1905 socket->readable_fn(socket, aws_error, socket->readable_user_data);
1906 }
1907 goto end_check;
1908 }
1909
1910 end_check:
1911 aws_ref_count_release(&socket_impl->internal_refcount);
1912 }
1913
1914 static int s_socket_assign_to_event_loop(struct aws_socket *socket, struct aws_event_loop *event_loop) {
1915 if (!socket->event_loop) {
1916 AWS_LOGF_DEBUG(
1917 AWS_LS_IO_SOCKET,
1918 "id=%p fd=%d: assigning to event loop %p",
1919 (void *)socket,
1920 socket->io_handle.data.fd,
1921 (void *)event_loop);
1922 socket->event_loop = event_loop;
1923 struct posix_socket *socket_impl = socket->impl;
1924 socket_impl->currently_subscribed = true;
1925 if (aws_event_loop_subscribe_to_io_events(
1926 event_loop,
1927 &socket->io_handle,
1928 AWS_IO_EVENT_TYPE_WRITABLE | AWS_IO_EVENT_TYPE_READABLE,
1929 s_on_socket_io_event,
1930 socket)) {
1931 AWS_LOGF_ERROR(
1932 AWS_LS_IO_SOCKET,
1933 "id=%p fd=%d: assigning to event loop %p failed with error %d",
1934 (void *)socket,
1935 socket->io_handle.data.fd,
1936 (void *)event_loop,
1937 aws_last_error());
1938 socket_impl->currently_subscribed = false;
1939 socket->event_loop = NULL;
1940 return AWS_OP_ERR;
1941 }
1942
1943 return AWS_OP_SUCCESS;
1944 }
1945
1946 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
1947 }
1948
1949 static int s_socket_subscribe_to_readable_events(
1950 struct aws_socket *socket,
1951 aws_socket_on_readable_fn *on_readable,
1952 void *user_data) {
1953
1954 AWS_LOGF_TRACE(
1955 AWS_LS_IO_SOCKET, " id=%p fd=%d: subscribing to readable events", (void *)socket, socket->io_handle.data.fd);
1956 if (!(socket->state & CONNECTED_READ)) {
1957 AWS_LOGF_ERROR(
1958 AWS_LS_IO_SOCKET,
1959 "id=%p fd=%d: can't subscribe to readable events since the socket is not connected",
1960 (void *)socket,
1961 socket->io_handle.data.fd);
1962 return aws_raise_error(AWS_IO_SOCKET_NOT_CONNECTED);
1963 }
1964
1965 if (socket->readable_fn) {
1966 AWS_LOGF_ERROR(
1967 AWS_LS_IO_SOCKET,
1968 "id=%p fd=%d: can't subscribe to readable events since it is already subscribed",
1969 (void *)socket,
1970 socket->io_handle.data.fd);
1971 return aws_raise_error(AWS_ERROR_IO_ALREADY_SUBSCRIBED);
1972 }
1973
1974 AWS_ASSERT(on_readable);
1975 socket->readable_user_data = user_data;
1976 socket->readable_fn = on_readable;
1977
1978 return AWS_OP_SUCCESS;
1979 }
1980
1981 static int s_socket_read(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read) {
1982 AWS_ASSERT(amount_read);
1983
1984 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
1985 AWS_LOGF_ERROR(
1986 AWS_LS_IO_SOCKET,
1987 "id=%p fd=%d: cannot read from a different thread than event loop %p",
1988 (void *)socket,
1989 socket->io_handle.data.fd,
1990 (void *)socket->event_loop);
1991 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
1992 }
1993
1994 if (!(socket->state & CONNECTED_READ)) {
1995 AWS_LOGF_ERROR(
1996 AWS_LS_IO_SOCKET,
1997 "id=%p fd=%d: cannot read because it is not connected",
1998 (void *)socket,
1999 socket->io_handle.data.fd);
2000 return aws_raise_error(AWS_IO_SOCKET_NOT_CONNECTED);
2001 }
2002
2003 ssize_t read_val = read(socket->io_handle.data.fd, buffer->buffer + buffer->len, buffer->capacity - buffer->len);
2004 int errno_value = errno; /* Always cache errno before potential side-effect */
2005
2006 AWS_LOGF_TRACE(
2007 AWS_LS_IO_SOCKET, "id=%p fd=%d: read of %d", (void *)socket, socket->io_handle.data.fd, (int)read_val);
2008
2009 if (read_val > 0) {
2010 *amount_read = (size_t)read_val;
2011 buffer->len += *amount_read;
2012 return AWS_OP_SUCCESS;
2013 }
2014
2015 /* read_val of 0 means EOF which we'll treat as AWS_IO_SOCKET_CLOSED */
2016 if (read_val == 0) {
2017 AWS_LOGF_INFO(
2018 AWS_LS_IO_SOCKET, "id=%p fd=%d: zero read, socket is closed", (void *)socket, socket->io_handle.data.fd);
2019 *amount_read = 0;
2020
2021 if (buffer->capacity - buffer->len > 0) {
2022 return aws_raise_error(AWS_IO_SOCKET_CLOSED);
2023 }
2024
2025 return AWS_OP_SUCCESS;
2026 }
2027
2028 #if defined(EWOULDBLOCK)
2029 if (errno_value == EAGAIN || errno_value == EWOULDBLOCK) {
2030 #else
2031 if (errno_value == EAGAIN) {
2032 #endif
2033 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p fd=%d: read would block", (void *)socket, socket->io_handle.data.fd);
2034 return aws_raise_error(AWS_IO_READ_WOULD_BLOCK);
2035 }
2036
2037 if (errno_value == EPIPE || errno_value == ECONNRESET) {
2038 AWS_LOGF_INFO(AWS_LS_IO_SOCKET, "id=%p fd=%d: socket is closed.", (void *)socket, socket->io_handle.data.fd);
2039 return aws_raise_error(AWS_IO_SOCKET_CLOSED);
2040 }
2041
2042 if (errno_value == ETIMEDOUT) {
2043 AWS_LOGF_ERROR(AWS_LS_IO_SOCKET, "id=%p fd=%d: socket timed out.", (void *)socket, socket->io_handle.data.fd);
2044 return aws_raise_error(AWS_IO_SOCKET_TIMEOUT);
2045 }
2046
2047 AWS_LOGF_ERROR(
2048 AWS_LS_IO_SOCKET,
2049 "id=%p fd=%d: read failed with error: %s",
2050 (void *)socket,
2051 socket->io_handle.data.fd,
2052 strerror(errno_value));
2053 return aws_raise_error(s_determine_socket_error(errno_value));
2054 }
2055
2056 static int s_socket_write(
2057 struct aws_socket *socket,
2058 const struct aws_byte_cursor *cursor,
2059 aws_socket_on_write_completed_fn *written_fn,
2060 void *user_data) {
2061 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
2062 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
2063 }
2064
2065 if (!(socket->state & CONNECTED_WRITE)) {
2066 AWS_LOGF_ERROR(
2067 AWS_LS_IO_SOCKET,
2068 "id=%p fd=%d: cannot write to because it is not connected",
2069 (void *)socket,
2070 socket->io_handle.data.fd);
2071 return aws_raise_error(AWS_IO_SOCKET_NOT_CONNECTED);
2072 }
2073
2074 AWS_ASSERT(written_fn);
2075 struct posix_socket *socket_impl = socket->impl;
2076 struct socket_write_request *write_request =
2077 aws_mem_calloc(socket->allocator, 1, sizeof(struct socket_write_request));
2078
2079 if (!write_request) {
2080 return AWS_OP_ERR;
2081 }
2082
2083 write_request->original_buffer_len = cursor->len;
2084 write_request->written_fn = written_fn;
2085 write_request->write_user_data = user_data;
2086 write_request->cursor_cpy = *cursor;
2087 aws_linked_list_push_back(&socket_impl->write_queue, &write_request->node);
2088
2089 return s_process_socket_write_requests(socket, write_request);
2090 }
2091
2092 static int s_socket_get_error(struct aws_socket *socket) {
2093 int connect_result;
2094 socklen_t result_length = sizeof(connect_result);
2095
2096 if (getsockopt(socket->io_handle.data.fd, SOL_SOCKET, SO_ERROR, &connect_result, &result_length) < 0) {
2097 return s_determine_socket_error(errno);
2098 }
2099
2100 if (connect_result) {
2101 return s_determine_socket_error(connect_result);
2102 }
2103
2104 return AWS_OP_SUCCESS;
2105 }
2106
2107 static bool s_socket_is_open(struct aws_socket *socket) {
2108 return socket->io_handle.data.fd >= 0;
2109 }
2110
2111 static struct aws_byte_buf s_socket_get_protocol_fn(const struct aws_socket *socket) {
2112 struct aws_byte_buf empty;
2113 AWS_ZERO_STRUCT(empty);
2114 AWS_LOGF_ERROR(
2115 AWS_LS_IO_SOCKET,
2116 "id=%p socket_get_protocol_fn should only be called on a socket using secitem.",
2117 (void *)socket);
2118 return empty;
2119 }
2120
2121 static struct aws_string *s_socket_get_server_name_fn(const struct aws_socket *socket) {
2122 AWS_LOGF_ERROR(
2123 AWS_LS_IO_SOCKET,
2124 "id=%p socket_get_server_name_fn should only be called on a socket using secitem.",
2125 (void *)socket);
2126 return NULL;
2127 }
2128
2129 bool aws_is_network_interface_name_valid(const char *interface_name) {
2130 if (if_nametoindex(interface_name) == 0) {
2131 AWS_LOGF_ERROR(AWS_LS_IO_SOCKET, "network_interface_name(%s) is invalid with errno: %d", interface_name, errno);
2132 return false;
2133 }
2134 return true;
2135 }
2136
2137 int aws_parse_ipv4_address(const struct aws_string *src, uint32_t *dst) {
2138 int result = inet_pton(AF_INET, aws_string_c_str(src), dst);
2139 if (result != 1) {
2140 int errno_value = errno; /* Always cache errno before potential side-effect */
2141 return aws_raise_error(s_convert_pton_error(result, errno_value));
2142 }
2143 return AWS_OP_SUCCESS;
2144 }
2145 int aws_parse_ipv6_address(const struct aws_string *src, struct aws_byte_buf *dst) {
2146 /* IPV6 requires 16 bytes */
2147 size_t result_length = 16;
2148 if (dst->capacity - dst->len < result_length) {
2149 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
2150 }
2151 int result = inet_pton(AF_INET6, aws_string_c_str(src), dst->buffer + dst->len);
2152 if (result != 1) {
2153 int errno_value = errno; /* Always cache errno before potential side-effect */
2154 return aws_raise_error(s_convert_pton_error(result, errno_value));
2155 }
2156 dst->len += result_length;
2157 return AWS_OP_SUCCESS;
2158 }