Debian Codegraph @

crt/aws-c-io/source/darwin/nw_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/private/socket_impl.h>
7 #include <aws/io/socket.h>
8
9 #include <aws/common/clock.h>
10 #include <aws/common/mutex.h>
11 #include <aws/common/string.h>
12 #include <aws/common/uuid.h>
13 #include <aws/io/logging.h>
14
15 #include "./dispatch_queue_event_loop_private.h" // private header
16 #include <Network/Network.h>
17 #include <aws/io/private/event_loop_impl.h>
18 #include <aws/io/private/tls_channel_handler_shared.h>
19
20 #include <arpa/inet.h>
21 #include <sys/socket.h>
22
23 static const char *s_aws_sec_trust_result_type_to_string(SecTrustResultType trust_result) {
24 switch (trust_result) {
25 case kSecTrustResultInvalid:
26 return "kSecTrustResultInvalid";
27 case kSecTrustResultProceed:
28 return "kSecTrustResultProceed";
29 case kSecTrustResultDeny:
30 return "kSecTrustResultDeny";
31 case kSecTrustResultUnspecified:
32 return "kSecTrustResultUnspecified";
33 case kSecTrustResultRecoverableTrustFailure:
34 return "kSecTrustResultRecoverableTrustFailure";
35 case kSecTrustResultFatalTrustFailure:
36 return "kSecTrustResultFatalTrustFailure";
37 case kSecTrustResultOtherError:
38 return "kSecTrustResultOtherError";
39 default:
40 return "Unknown SecTrustResultType";
41 }
42 }
43
44 static int s_determine_socket_error(int error) {
45 switch (error) {
46 /* SSL/TLS Errors */
47 case errSSLUnknownRootCert:
48 return AWS_IO_TLS_UNKNOWN_ROOT_CERTIFICATE;
49 case errSSLNoRootCert:
50 return AWS_IO_TLS_NO_ROOT_CERTIFICATE_FOUND;
51 case errSSLCertExpired:
52 return AWS_IO_TLS_CERTIFICATE_EXPIRED;
53 case errSSLCertNotYetValid:
54 return AWS_IO_TLS_CERTIFICATE_NOT_YET_VALID;
55 case errSSLPeerHandshakeFail:
56 return AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE;
57 case errSSLBadCert:
58 return AWS_IO_TLS_BAD_CERTIFICATE;
59 case errSSLPeerCertExpired:
60 return AWS_IO_TLS_PEER_CERTIFICATE_EXPIRED;
61 case errSSLPeerBadCert:
62 return AWS_IO_TLS_BAD_PEER_CERTIFICATE;
63 case errSSLPeerCertRevoked:
64 return AWS_IO_TLS_PEER_CERTIFICATE_REVOKED;
65 case errSSLPeerCertUnknown:
66 return AWS_IO_TLS_PEER_CERTIFICATE_UNKNOWN;
67 case errSSLInternal:
68 return AWS_IO_TLS_INTERNAL_ERROR;
69 case errSSLClosedGraceful:
70 return AWS_IO_TLS_CLOSED_GRACEFUL;
71 case errSSLClosedAbort:
72 return AWS_IO_TLS_CLOSED_ABORT;
73 case errSSLXCertChainInvalid:
74 return AWS_IO_TLS_INVALID_CERTIFICATE_CHAIN;
75 case errSSLHostNameMismatch:
76 return AWS_IO_TLS_HOST_NAME_MISMATCH;
77 case errSecNotTrusted:
78 case errSSLPeerProtocolVersion:
79 return AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE;
80
81 /* POSIX Errors */
82 case ECONNREFUSED:
83 return AWS_IO_SOCKET_CONNECTION_REFUSED;
84 case ETIMEDOUT:
85 return AWS_IO_SOCKET_TIMEOUT;
86 case EHOSTUNREACH:
87 case ENETUNREACH:
88 return AWS_IO_SOCKET_NO_ROUTE_TO_HOST;
89 case EADDRNOTAVAIL:
90 return AWS_IO_SOCKET_INVALID_ADDRESS;
91 case ENETDOWN:
92 return AWS_IO_SOCKET_NETWORK_DOWN;
93 case ECONNABORTED:
94 return AWS_IO_SOCKET_CONNECT_ABORTED;
95 case EADDRINUSE:
96 return AWS_IO_SOCKET_ADDRESS_IN_USE;
97 case ENOBUFS:
98 case ENOMEM:
99 return AWS_ERROR_OOM;
100 case EAGAIN:
101 return AWS_IO_READ_WOULD_BLOCK;
102 case EMFILE:
103 case ENFILE:
104 return AWS_ERROR_MAX_FDS_EXCEEDED;
105 case ENOENT:
106 case EINVAL:
107 return AWS_ERROR_FILE_INVALID_PATH;
108 case EAFNOSUPPORT:
109 return AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY;
110 case EACCES:
111 return AWS_ERROR_NO_PERMISSION;
112 default:
113 return AWS_IO_SOCKET_NOT_CONNECTED;
114 }
115 }
116
117 static int s_convert_nw_error(nw_error_t nw_error) {
118 int nw_error_code = nw_error ? nw_error_get_error_code(nw_error) : 0;
119 int crt_error_code = nw_error_code ? s_determine_socket_error(nw_error_code) : AWS_OP_SUCCESS;
120 return crt_error_code;
121 }
122
123 static inline int s_convert_pton_error(int pton_code) {
124 if (pton_code == 0) {
125 return AWS_IO_SOCKET_INVALID_ADDRESS;
126 }
127
128 return s_determine_socket_error(errno);
129 }
130
131 /*
132 * Helper function that gets the available human readable error description from Core Foundation.
133 */
134 static void s_get_error_description(CFErrorRef error, char *description_buffer, size_t buffer_size) {
135 if (error == NULL) {
136 snprintf(description_buffer, buffer_size, "No error provided");
137 return;
138 }
139
140 CFStringRef error_description = CFErrorCopyDescription(error);
141 if (error_description) {
142 CFStringGetCString(error_description, description_buffer, buffer_size, kCFStringEncodingUTF8);
143 CFRelease(error_description);
144 } else {
145 snprintf(description_buffer, buffer_size, "Unable to retrieve error description");
146 }
147 }
148
149 /*
150 * A socket is only in one of these states at a time, except for CONNECTED_READ | CONNECTED_WRITE.
151 *
152 * The state can only go increasing, except for the following cases
153 * 1. LISTENING and STOPPED: They can switch between each other.
154 * 2. CLOSING -> ERROR: It is a valid case where socket state tries to transfer from CLOSING to ERROR, but we never
155 * actually set it to ERROR if we are already in CLOSING state. This happened in the following scenario: After we
156 * called aws_socket_close(), the socket state is set to CLOSING. And if a read callback invoked at this time, it
157 * is possible that the socket reads an ERROR and tries to set the socket state to ERROR, which makes the socket
158 * state goes backwards. Though this is a valid case, we don't actually set it back to ERROR as we are shutting down the
159 * socket.
160 * 3. CONNECT_WRITE and CONNECT_READ: you are allow to flip the flags for these two state, while not going
161 * backwards to `CONNECTING` and `INIT` state.
162 */
163 enum aws_nw_socket_state {
164 AWS_NW_SOCKET_STATE_INVALID = 0x000,
165 AWS_NW_SOCKET_STATE_INIT = 0x001,
166 AWS_NW_SOCKET_STATE_CONNECTING = 0x002,
167 AWS_NW_SOCKET_STATE_CONNECTED_READ = 0x004,
168 AWS_NW_SOCKET_STATE_CONNECTED_WRITE = 0x008,
169 AWS_NW_SOCKET_STATE_BOUND = 0x010,
170 AWS_NW_SOCKET_STATE_LISTENING = 0x020,
171 AWS_NW_SOCKET_STATE_STOPPED = 0x040, // Stop the io events, while we could restart it later
172 AWS_NW_SOCKET_STATE_ERROR = 0x080,
173 AWS_NW_SOCKET_STATE_CLOSING = 0X100, // Only set when aws_socket_close() is called.
174 AWS_NW_SOCKET_STATE_CLOSED = 0x200,
175 };
176
177 static const char *aws_socket_state_to_c_string(enum aws_nw_socket_state state) {
178 switch ((int)state) {
179 case AWS_NW_SOCKET_STATE_INIT:
180 return "INIT";
181 case AWS_NW_SOCKET_STATE_INVALID:
182 return "INVALID";
183 case AWS_NW_SOCKET_STATE_CONNECTING:
184 return "CONNECTING";
185 case AWS_NW_SOCKET_STATE_CONNECTED_READ:
186 return "CONNECTED_READ";
187 case AWS_NW_SOCKET_STATE_CONNECTED_WRITE:
188 return "CONNECTED_WRITE";
189 case AWS_NW_SOCKET_STATE_BOUND:
190 return "BOUND";
191 case AWS_NW_SOCKET_STATE_LISTENING:
192 return "LISTENING";
193 case AWS_NW_SOCKET_STATE_STOPPED:
194 return "STOPPED";
195 case AWS_NW_SOCKET_STATE_ERROR:
196 return "ERROR";
197 case AWS_NW_SOCKET_STATE_CLOSING:
198 return "CLOSING";
199 case AWS_NW_SOCKET_STATE_CLOSED:
200 return "CLOSED";
201 case AWS_NW_SOCKET_STATE_CONNECTED_WRITE | AWS_NW_SOCKET_STATE_CONNECTED_READ:
202 return "CONNECTED_WRITE | CONNECTED_READ";
203 case AWS_NW_SOCKET_STATE_CLOSING | AWS_NW_SOCKET_STATE_CONNECTED_READ:
204 return "CLOSING | CONNECTED_READ";
205 case ~AWS_NW_SOCKET_STATE_CONNECTED_READ:
206 return "~CONNECTED_READ";
207 default:
208 return "UNKNOWN";
209 }
210 }
211
212 enum aws_nw_socket_mode {
213 NWSM_CONNECTION,
214 NWSM_LISTENER,
215 };
216
217 struct nw_listener_connection_args {
218 struct aws_task task;
219 int error_code;
220 struct aws_allocator *allocator;
221 struct nw_socket *nw_socket;
222 nw_connection_t new_connection;
223 void *user_data;
224 };
225
226 struct nw_socket_timeout_args {
227 struct aws_task task;
228 struct aws_allocator *allocator;
229 struct nw_socket *nw_socket;
230 };
231
232 struct nw_socket_scheduled_task_args {
233 struct aws_task task;
234 int error_code;
235 struct aws_allocator *allocator;
236 struct nw_socket *nw_socket;
237 dispatch_data_t data;
238 bool is_complete;
239 };
240
241 struct nw_socket_written_args {
242 struct aws_task task;
243 int error_code;
244 struct aws_allocator *allocator;
245 struct nw_socket *nw_socket;
246 aws_socket_on_write_completed_fn *written_fn;
247 void *user_data;
248 size_t bytes_written;
249 };
250
251 struct nw_socket_cancel_task_args {
252 struct aws_allocator *allocator;
253 struct nw_socket *nw_socket;
254 struct aws_task task;
255 };
256
257 struct nw_socket {
258 struct aws_allocator *allocator;
259
260 /* The `nw_socket_ref_count` that keeps the nw_socket alive. The `nw_socket_ref_count` initalized on
261 * aws_socket_init() and decreased on aws_socket_clean_up() called. The `internal_ref_count` will also keep a
262 * reference of the `nw_socket_ref_count` so that the nw_socket would alive until all system callbacks and tasks are
263 * handled. On `nw_socket_ref_count` drops to 0, it invokes s_socket_impl_destroy, which cleanup the nw_socket
264 * memory and invoke on_socket_cleanup_complete_fn.
265 */
266 struct aws_ref_count nw_socket_ref_count;
267
268 /* The `internal_ref_count` is used to track any in-flight socket operations. It would be init on socket init, and
269 * acquired on aws_socket_connect()/aws_socket_listen() called. The reference will be decreased on
270 * nw_connection/listener_state_changed_handler is invoked with a "nw_connection/listener_state_cancelled" state.
271 * Besides this, each network framework system call or each scheduled task in event loop would also acquire an
272 * internal reference, and release when the callback invoked or the task executed.
273 */
274 struct aws_ref_count internal_ref_count;
275
276 /* The `write_ref_count` is used to track any in-flight write operations. It would be init on aws_socket_init() and
277 * dropped on aws_socket_close() call. Each aws_socket_write() function call will acquire a ref-count, and released
278 * the ref-count on nw_connection_send handler is invoked.
279 * When the reference is dropped to 0, it invoked the destroy function `s_nw_socket_canceled()`, and start to cancel
280 * and close the Apple nw_connection/nw_listener.
281 */
282 struct aws_ref_count write_ref_count;
283
284 int last_error;
285
286 /* Apple's native structs for connection and listener. */
287 union {
288 nw_connection_t nw_connection;
289 nw_listener_t nw_listener;
290 } os_handle;
291 nw_parameters_t nw_parameters;
292 /* The socket would be either setup as nw_connection or nw_listener. */
293 enum aws_nw_socket_mode mode;
294
295 /* The linked list of `read_queue_node`. The read queue to store read data from io events. aws_socket_read()
296 * function would read data from the queue.
297
298 * WARNING: The read_queue is not lock protected so far, as we always access it on event loop thread. */
299 struct aws_linked_list read_queue;
300
301 /*
302 * nw_socket is ref counted. It is possible that the aws_socket object is released while nw_socket is still alive
303 * and processing events. We keep the callbacks and parameters on nw_socket to avoid bad access after the aws_socket
304 * is released.
305 */
306 aws_socket_on_readable_fn *on_readable;
307 void *on_readable_user_data;
308 aws_socket_on_connection_result_fn *on_connection_result_fn;
309 void *connect_result_user_data;
310 aws_socket_on_accept_started_fn *on_accept_started_fn;
311 void *listen_accept_started_user_data;
312 aws_socket_on_shutdown_complete_fn *on_socket_close_complete_fn;
313 void *close_user_data;
314 aws_socket_on_shutdown_complete_fn *on_socket_cleanup_complete_fn;
315 void *cleanup_user_data;
316
317 /* nw_socket had to be assigned to an event loop to process events. The nw_socket will acquire a reference of the
318 * event_loop's base event group to kept the event loop alive.
319 *
320 * For client socket (nw_connection): setup on aws_socket_connect()
321 * For listener (nw_listener) : setup on aws_socket_start_accept()
322 * For incoming socket / server socket (nw_connection accepted on a listener): setup by calling
323 * aws_socket_assign_event_loop()
324 */
325 struct aws_event_loop *event_loop;
326
327 /* Indicate the connection result is updated. This argument is used to cancel the timeout task. The argument should
328 * be only set on socket event loop. The value will be set to true if:
329 * 1. nw_connection returned with state=`nw_connection_state_ready`, indicating the connection succeed
330 * 2. nw_connection returned with state=`nw_connection_state_failed`, indicating the connection failed
331 * 3. directly set to true for the incoming socket, as the incoming socket is already connected
332 */
333 bool connection_setup;
334
335 /* Timeout task that is created on aws_socket_connect(). The task will be flagged to be canceled if the connection
336 * succeed or failed. */
337 struct nw_socket_timeout_args *timeout_args;
338
339 struct aws_string *host_name;
340 struct aws_string *alpn_list;
341 struct aws_tls_ctx *tls_ctx;
342 struct aws_byte_buf protocol_buf;
343
344 /* synced_data and the lock to protect the synced data. */
345 struct {
346 /* Used to avoid scheduling a duplicate read call. We would like to wait for the read call complete back before
347 * we schedule another one. */
348 bool read_scheduled;
349 /* The aws_nw_socket_state. aws_socket also has a field `state` which should be represent the same parameter,
350 * however, as it is possible that the aws_socket object is released while nw_socket is still alive, we will use
351 * nw_socket->state instead of socket->state to verify the socket_state.
352 */
353 enum aws_nw_socket_state state;
354 struct aws_mutex lock;
355 } synced_data;
356
357 /*
358 * The synced data to protect base_socket access. As aws_socket is not ref-counted. It is possible that the user
359 * called aws_socket_cleanup() to release the aws_socket(base_socket), while the nw_socket is still alive and the
360 * underlying system calls are still processing the data. Therefore, here nw_socket kept a point to base_socket to
361 * avoid bad access after aws_socket is cleaned up. The lock is acquired before we do any callback that might access
362 * the base_socket.
363 * We put aws_socket in a different base_socket_synced_data struct to avoid the lock contention between other
364 * cross-thread data, especially when we do a socket operation in a callback when the socket lock is acquired.
365 *
366 * As all the callbacks will hold the lock to make sure the base_socket is alive, we should avoid to use the lock in
367 * user API calls. So far we used it only in aws_socket_cleanup. And handle it in this way to avoid deadlock: if we
368 * are on the assigned event loop, we assume we are fired on the event loop thread, and we don't need to acquire the
369 * lock, otherwise, we acquire the lock.
370 */
371 struct {
372 struct aws_mutex lock;
373 struct aws_socket *base_socket;
374 } base_socket_synced_data;
375 };
376
377 static size_t KB_16 = 16 * 1024;
378
379 static void *s_socket_acquire_internal_ref(struct nw_socket *nw_socket) {
380 return aws_ref_count_acquire(&nw_socket->internal_ref_count);
381 }
382
383 static size_t s_socket_release_internal_ref(struct nw_socket *nw_socket) {
384 return aws_ref_count_release(&nw_socket->internal_ref_count);
385 }
386
387 static void *s_socket_acquire_write_ref(struct nw_socket *nw_socket) {
388 return aws_ref_count_acquire(&nw_socket->write_ref_count);
389 }
390
391 static size_t s_socket_release_write_ref(struct nw_socket *nw_socket) {
392 return aws_ref_count_release(&nw_socket->write_ref_count);
393 }
394
395 static int s_lock_base_socket(struct nw_socket *nw_socket) {
396 return aws_mutex_lock(&nw_socket->base_socket_synced_data.lock);
397 }
398
399 static int s_unlock_base_socket(struct nw_socket *nw_socket) {
400 return aws_mutex_unlock(&nw_socket->base_socket_synced_data.lock);
401 }
402
403 static int s_lock_socket_synced_data(struct nw_socket *nw_socket) {
404 return aws_mutex_lock(&nw_socket->synced_data.lock);
405 }
406
407 static int s_unlock_socket_synced_data(struct nw_socket *nw_socket) {
408 return aws_mutex_unlock(&nw_socket->synced_data.lock);
409 }
410
411 static bool s_validate_event_loop(struct aws_event_loop *event_loop) {
412 return event_loop && event_loop->vtable && event_loop->impl_data;
413 }
414
415 static int s_set_event_loop(struct aws_socket *aws_socket, struct aws_event_loop *event_loop) {
416 aws_socket->event_loop = event_loop;
417 struct nw_socket *nw_socket = aws_socket->impl;
418 // Never re-assign an event loop
419 AWS_FATAL_ASSERT(nw_socket->event_loop == NULL);
420
421 // Acquire the event loop group from the event loop. The event loop group will be released when the socket is
422 // destroyed.
423 if (!aws_event_loop_group_acquire_from_event_loop(event_loop)) {
424 AWS_LOGF_ERROR(
425 AWS_LS_IO_SOCKET,
426 "id=%p nw_socket=%p: failed to acquire event loop group.",
427 (void *)aws_socket,
428 (void *)nw_socket);
429 return AWS_OP_ERR;
430 }
431
432 nw_socket->event_loop = event_loop;
433 AWS_LOGF_DEBUG(
434 AWS_LS_IO_SOCKET, "id=%p nw_socket=%p: nw_socket set event loop.", (void *)aws_socket, (void *)nw_socket);
435
436 return AWS_OP_SUCCESS;
437 }
438
439 static void s_release_event_loop(struct nw_socket *nw_socket) {
440 if (nw_socket->event_loop == NULL) {
441 AWS_LOGF_DEBUG(
442 AWS_LS_IO_SOCKET, "nw_socket=%p: s_release_event_loop: socket has not event loop.", (void *)nw_socket);
443 return;
444 }
445 aws_event_loop_group_release_from_event_loop(nw_socket->event_loop);
446 AWS_LOGF_DEBUG(
447 AWS_LS_IO_SOCKET, "nw_socket=%p: s_release_event_loop: socket release event loop group.", (void *)nw_socket);
448 nw_socket->event_loop = NULL;
449 }
450
451 /* The help function to update the socket state. The function must be called with synced_data locked (use
452 * s_lock_socket_synced_data() / s_unlock_socket_synced_data()), as the function touches the synced_data.state. */
453 static void s_set_socket_state(struct nw_socket *nw_socket, enum aws_nw_socket_state state) {
454
455 AWS_LOGF_DEBUG(
456 AWS_LS_IO_SOCKET,
457 "nw_socket=%p: s_set_socket_state: socket state set from %s to %s.",
458 (void *)nw_socket,
459 aws_socket_state_to_c_string(nw_socket->synced_data.state),
460 aws_socket_state_to_c_string(state));
461 enum aws_nw_socket_state result_state = nw_socket->synced_data.state;
462
463 // clip the read/write bits
464 enum aws_nw_socket_state read_write_bits =
465 state & (AWS_NW_SOCKET_STATE_CONNECTED_WRITE | AWS_NW_SOCKET_STATE_CONNECTED_READ);
466 result_state = result_state & ~AWS_NW_SOCKET_STATE_CONNECTED_WRITE & ~AWS_NW_SOCKET_STATE_CONNECTED_READ;
467
468 // If the caller would like simply flip the read/write bits, set the state to invalid, as we dont have further
469 // information there.
470 if (~AWS_NW_SOCKET_STATE_CONNECTED_WRITE == (int)state || ~AWS_NW_SOCKET_STATE_CONNECTED_READ == (int)state) {
471 state = AWS_NW_SOCKET_STATE_INVALID;
472 }
473
474 // The state can only go increasing, except for the following cases
475 // 1. LISTENING and STOPPED: They can switch between each other.
476 // 2. CLOSING -> ERROR: It is a valid case where socket state tries to transfer from CLOSING to ERROR. This
477 // happened in the following scenario: After we called aws_socket_close(), the socket state is set to CLOSING. And
478 // if a read callback invoked at this time, it is possible that the socket reads an ERROR and tries to set the
479 // socket state to ERROR, which makes the socket state goes backwards. Though this is a valid case, we don't
480 // actually set it back to ERROR as we are shutting down the socket.
481 // 3. CONNECT_WRITE and CONNECT_READ: you are allow to flip the flags for these two state, while not going
482 // backwards to `CONNECTING` and `INIT` state.
483 if (result_state < state ||
484 (state == AWS_NW_SOCKET_STATE_LISTENING && result_state == AWS_NW_SOCKET_STATE_STOPPED)) {
485 result_state = state;
486 }
487
488 // Set CONNECTED_WRITE and CONNECTED_READ
489 result_state = result_state | read_write_bits;
490
491 nw_socket->synced_data.state = result_state;
492
493 AWS_LOGF_DEBUG(
494 AWS_LS_IO_SOCKET,
495 "nw_socket=%p: s_set_socket_state: socket state set to %s.",
496 (void *)nw_socket,
497 aws_socket_state_to_c_string(nw_socket->synced_data.state));
498 }
499
500 /* setup the TCP options Block for use in socket parameters */
501 static void s_setup_tcp_options(nw_protocol_options_t tcp_options, const struct aws_socket_options *options) {
502 if (options->domain == AWS_SOCKET_LOCAL) {
503 /*
504 * TCP options for a local connection should use system defaults and not be modified. We have this function in
505 * case we need to support the setting of local connection options in the future during the creation of
506 * nw_parameters.
507 */
508 return;
509 }
510
511 if (options->connect_timeout_ms) {
512 /* this value gets set in seconds. */
513 nw_tcp_options_set_connection_timeout(tcp_options, options->connect_timeout_ms / AWS_TIMESTAMP_MILLIS);
514 }
515
516 /* Only change default keepalive values if keepalive is true and both interval and timeout
517 * are not zero. */
518 if (options->keepalive && options->keep_alive_interval_sec != 0 && options->keep_alive_timeout_sec != 0) {
519 nw_tcp_options_set_enable_keepalive(tcp_options, options->keepalive);
520 nw_tcp_options_set_keepalive_idle_time(tcp_options, options->keep_alive_interval_sec);
521 nw_tcp_options_set_keepalive_interval(tcp_options, options->keep_alive_timeout_sec);
522 }
523
524 if (options->keep_alive_max_failed_probes) {
525 nw_tcp_options_set_keepalive_count(tcp_options, options->keep_alive_max_failed_probes);
526 }
527
528 if (g_aws_channel_max_fragment_size < KB_16) {
529 nw_tcp_options_set_maximum_segment_size(tcp_options, (uint32_t)g_aws_channel_max_fragment_size);
530 }
531 }
532
533 static void s_tls_verification_block(
534 sec_protocol_metadata_t metadata,
535 sec_trust_t trust,
536 sec_protocol_verify_complete_t complete,
537 struct nw_socket *nw_socket,
538 struct secure_transport_ctx *transport_ctx) {
539 (void)metadata;
540
541 CFErrorRef error = NULL;
542 SecPolicyRef policy = NULL;
543 SecTrustRef trust_ref = NULL;
544 OSStatus status;
545 bool verification_successful = false;
546
547 /*
548 * Because we manually handle the verification of the peer, the value set using
549 * sec_protocol_options_set_peer_authentication_required is ignored and this block is run instead. We force
550 * successful verification if verify_peer is false.
551 */
552 if (!transport_ctx->verify_peer) {
553 AWS_LOGF_WARN(
554 AWS_LS_IO_TLS,
555 "nw_socket=%p: x.509 validation has been disabled. If this is not running in a test environment, this is "
556 "likely a security vulnerability.",
557 (void *)nw_socket);
558 verification_successful = true;
559 goto verification_done;
560 }
561
562 trust_ref = sec_trust_copy_ref(trust);
563
564 /* Use root ca if provided. */
565 if (transport_ctx->ca_cert != NULL) {
566 AWS_LOGF_DEBUG(
567 AWS_LS_IO_TLS,
568 "nw_socket=%p: nw_socket verify block applying provided root CA for remote verification.",
569 (void *)nw_socket);
570 // We add the ca certificate as a anchor certificate in the trust_ref
571 status = SecTrustSetAnchorCertificates(trust_ref, transport_ctx->ca_cert);
572 if (status != errSecSuccess) {
573 AWS_LOGF_ERROR(
574 AWS_LS_IO_TLS,
575 "nw_socket=%p: nw_socket verify block SecTrustSetAnchorCertificates failed with "
576 "OSStatus: %d",
577 (void *)nw_socket,
578 (int)status);
579 aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
580 goto verification_done;
581 }
582 }
583
584 /* Add the host name to be checked against the available Certificate Authorities */
585 if (nw_socket->host_name != NULL) {
586 CFStringRef server_name = CFStringCreateWithCString(
587 transport_ctx->wrapped_allocator, aws_string_c_str(nw_socket->host_name), kCFStringEncodingUTF8);
588 policy = SecPolicyCreateSSL(true, server_name);
589 CFRelease(server_name);
590 } else {
591 policy = SecPolicyCreateBasicX509();
592 }
593
594 status = SecTrustSetPolicies(trust_ref, policy);
595 if (status != errSecSuccess) {
596 AWS_LOGF_ERROR(AWS_LS_IO_TLS, "nw_socket=%p: Failed to set trust policy %d\n", (void *)nw_socket, (int)status);
597 aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
598 goto verification_done;
599 }
600
601 SecTrustResultType trust_result;
602
603 /* verify peer */
604 bool success = SecTrustEvaluateWithError(trust_ref, &error);
605 if (success) {
606 status = SecTrustGetTrustResult(trust_ref, &trust_result);
607 if (status == errSecSuccess) {
608 AWS_LOGF_DEBUG(
609 AWS_LS_IO_TLS,
610 "nw_socket=%p: nw_socket verify block trust result: %s",
611 (void *)nw_socket,
612 s_aws_sec_trust_result_type_to_string(trust_result));
613
614 // Proceed based on the trust_result if necessary
615 if (trust_result == kSecTrustResultProceed || trust_result == kSecTrustResultUnspecified) {
616 verification_successful = true;
617 }
618 } else {
619 AWS_LOGF_DEBUG(
620 AWS_LS_IO_TLS,
621 "nw_socket=%p: nw_socket SecTrustGetTrustResult failed with OSStatus: %d",
622 (void *)nw_socket,
623 (int)status);
624 }
625 } else {
626 char description_buffer[256];
627 s_get_error_description(error, description_buffer, sizeof(description_buffer));
628 int crt_error_code = s_determine_socket_error((int)CFErrorGetCode(error));
629 AWS_LOGF_DEBUG(
630 AWS_LS_IO_TLS,
631 "nw_socket=%p: nw_socket SecTrustEvaluateWithError failed with crt error code: %d : %s translated from CF "
632 "error "
633 "code: %ld : %s",
634 (void *)nw_socket,
635 crt_error_code,
636 aws_error_name(crt_error_code),
637 (long)CFErrorGetCode(error),
638 description_buffer);
639 }
640
641 verification_done:
642 if (policy) {
643 CFRelease(policy);
644 }
645 if (trust_ref) {
646 CFRelease(trust_ref);
647 }
648 if (error) {
649 CFRelease(error);
650 }
651 complete(verification_successful);
652 }
653
654 static void s_setup_tls_options(
655 nw_protocol_options_t tls_options,
656 struct nw_socket *nw_socket,
657 struct secure_transport_ctx *transport_ctx) {
658 /*
659 * Obtain the security protocol options from tls_options. Changes made to the copy will impact the protocol options
660 * within the tls_options
661 */
662 sec_protocol_options_t sec_options = nw_tls_copy_sec_protocol_options(tls_options);
663
664 sec_protocol_options_set_local_identity(sec_options, transport_ctx->secitem_identity);
665
666 // Set the minimum TLS version
667 switch (transport_ctx->minimum_tls_version) {
668 case AWS_IO_TLSv1_2:
669 sec_protocol_options_set_min_tls_protocol_version(sec_options, tls_protocol_version_TLSv12);
670 break;
671 case AWS_IO_TLSv1_3:
672 sec_protocol_options_set_min_tls_protocol_version(sec_options, tls_protocol_version_TLSv13);
673 break;
674 case AWS_IO_TLS_VER_SYS_DEFAULTS:
675 /* not assigning a min tls protocol version automatically uses the system default version. */
676 break;
677 default:
678 /* Already validated with error thrown in s_setup_socket_params prior to this block being called. */
679 AWS_FATAL_ASSERT(false);
680 break;
681 }
682
683 /*
684 * Enable/Disable peer authentication. This setting is ignored by network framework due to our implementation of the
685 * verification block below but we set it in case anything else checks this value and/or in case we decide to remove
686 * the verify block in the future.
687 */
688 sec_protocol_options_set_peer_authentication_required(sec_options, transport_ctx->verify_peer);
689
690 if (nw_socket->host_name != NULL) {
691 sec_protocol_options_set_tls_server_name(sec_options, (const char *)nw_socket->host_name->bytes);
692 }
693
694 // Add alpn protocols
695 if (nw_socket->alpn_list != NULL) {
696 AWS_LOGF_DEBUG(
697 AWS_LS_IO_TLS,
698 "nw_socket=%p: Setting ALPN list %s",
699 (void *)nw_socket,
700 aws_string_c_str(nw_socket->alpn_list));
701
702 struct aws_byte_cursor alpn_data = aws_byte_cursor_from_string(nw_socket->alpn_list);
703 struct aws_array_list alpn_list_array;
704 if (aws_array_list_init_dynamic(&alpn_list_array, nw_socket->allocator, 2, sizeof(struct aws_byte_cursor)) ||
705 aws_byte_cursor_split_on_char(&alpn_data, ';', &alpn_list_array)) {
706 /*
707 * We cannot throw or fail from within a tls options block. We will log the error and in the event an ALPN
708 * was required for this connection to succeeed, the connection's state change handler will catch the
709 * connection failure.
710 */
711 AWS_LOGF_ERROR(
712 AWS_LS_IO_TLS, "nw_socket=%p: Failed to setup array list for ALPN setup.", (void *)nw_socket);
713 } else {
714 for (size_t i = 0; i < aws_array_list_length(&alpn_list_array); ++i) {
715 struct aws_byte_cursor protocol_cursor;
716 aws_array_list_get_at(&alpn_list_array, &protocol_cursor, i);
717 struct aws_string *protocol_string = aws_string_new_from_cursor(nw_socket->allocator, &protocol_cursor);
718 sec_protocol_options_add_tls_application_protocol(sec_options, aws_string_c_str(protocol_string));
719 aws_string_destroy(protocol_string);
720 }
721 }
722 aws_array_list_clean_up(&alpn_list_array);
723 }
724
725 /*
726 * We handle the verification of the remote end here. The verify block requires a dispatch queue to execute on.
727 */
728 struct aws_dispatch_loop *dispatch_loop = nw_socket->event_loop->impl_data;
729 sec_protocol_options_set_verify_block(
730 sec_options,
731 ^(sec_protocol_metadata_t metadata, sec_trust_t trust, sec_protocol_verify_complete_t complete) {
732 s_tls_verification_block(metadata, trust, complete, nw_socket, transport_ctx);
733 },
734 dispatch_loop->dispatch_queue);
735
736 nw_release(sec_options);
737 }
738
739 static int s_setup_socket_params(struct nw_socket *nw_socket, const struct aws_socket_options *options) {
740
741 /* If we already have parameters set, release them before re-establishing new parameters */
742 if (nw_socket->nw_parameters != NULL) {
743 nw_release(nw_socket->nw_parameters);
744 nw_socket->nw_parameters = NULL;
745 }
746 bool setup_tls = false;
747
748 if (aws_is_using_secitem()) {
749 /* If SecItem isn't being used then the nw_parameters should not be setup to handle the TLS Negotiation. */
750 if (nw_socket->tls_ctx) {
751 setup_tls = true;
752 }
753 }
754
755 if (options->type == AWS_SOCKET_STREAM) {
756 if (setup_tls) {
757 /* The verification block of the Network Framework TLS handshake requires a dispatch queue to run on. */
758 if (nw_socket->event_loop == NULL) {
759 AWS_LOGF_ERROR(
760 AWS_LS_IO_SOCKET,
761 "nw_socket=%p Apple Network Framework setup of TLS parameters requires the nw_socket to have a "
762 "valid "
763 "event_loop.",
764 (void *)nw_socket);
765 return aws_raise_error(AWS_IO_SOCKET_MISSING_EVENT_LOOP);
766 }
767
768 struct secure_transport_ctx *transport_ctx = nw_socket->tls_ctx->impl;
769
770 /* This check cannot be done within the TLS options block and must be handled here. */
771 if (transport_ctx->minimum_tls_version == AWS_IO_SSLv3 ||
772 transport_ctx->minimum_tls_version == AWS_IO_TLSv1 ||
773 transport_ctx->minimum_tls_version == AWS_IO_TLSv1_1) {
774 AWS_LOGF_ERROR(
775 AWS_LS_IO_SOCKET,
776 "nw_socket=%p options=%p: Selected minimum tls version not supported by Apple Network Framework "
777 "due "
778 "to deprecated status and known security flaws.",
779 (void *)nw_socket,
780 (void *)options);
781 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
782 }
783
784 switch (options->domain) {
785 case AWS_SOCKET_IPV4:
786 case AWS_SOCKET_IPV6:
787 case AWS_SOCKET_LOCAL:
788 nw_socket->nw_parameters = nw_parameters_create_secure_tcp(
789 // TLS options block
790 ^(nw_protocol_options_t tls_options) {
791 s_setup_tls_options(tls_options, nw_socket, transport_ctx);
792 },
793 // TCP options block
794 ^(nw_protocol_options_t tcp_options) {
795 s_setup_tcp_options(tcp_options, options);
796 });
797 break;
798 default:
799 AWS_LOGF_ERROR(
800 AWS_LS_IO_SOCKET,
801 "id=%p options=%p: AWS_SOCKET_VSOCK is not supported on nw_socket.",
802 (void *)nw_socket,
803 (void *)options);
804 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
805 }
806 } else {
807 switch (options->domain) {
808 case AWS_SOCKET_IPV4:
809 case AWS_SOCKET_IPV6:
810 case AWS_SOCKET_LOCAL:
811 // TLS options are not set and the TLS options block should be disabled.
812 nw_socket->nw_parameters = nw_parameters_create_secure_tcp(
813 // TLS options Block disabled
814 NW_PARAMETERS_DISABLE_PROTOCOL,
815 // TCP options Block
816 ^(nw_protocol_options_t tcp_options) {
817 s_setup_tcp_options(tcp_options, options);
818 });
819 break;
820 default:
821 AWS_LOGF_ERROR(
822 AWS_LS_IO_SOCKET,
823 "nw_socket=%p options=%p: AWS_SOCKET_VSOCK is not supported on nw_socket.",
824 (void *)nw_socket,
825 (void *)options);
826 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
827 }
828 }
829
830 /* allow a local address to be used by multiple parameters. */
831 if (options->domain == AWS_SOCKET_LOCAL) {
832 nw_parameters_set_reuse_local_address(nw_socket->nw_parameters, true);
833 }
834 } else if (options->type == AWS_SOCKET_DGRAM) {
835 if (setup_tls) {
836 AWS_LOGF_ERROR(
837 AWS_LS_IO_SOCKET,
838 "nw_socket=%p options=%p: Cannot use TLS with UDP.",
839 (void *)nw_socket,
840 (void *)options);
841 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
842 } else {
843 nw_socket->nw_parameters = nw_parameters_create_secure_udp(
844 NW_PARAMETERS_DISABLE_PROTOCOL,
845 // TCP options Block
846 ^(nw_protocol_options_t tcp_options) {
847 s_setup_tcp_options(tcp_options, options);
848 });
849 }
850 }
851
852 if (!nw_socket->nw_parameters) {
853 AWS_LOGF_ERROR(
854 AWS_LS_IO_SOCKET,
855 "nw_socket=%p options=%p: failed to create nw_parameters_t for nw_socket.",
856 (void *)nw_socket,
857 (void *)options);
858 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
859 }
860
861 return AWS_OP_SUCCESS;
862 }
863
864 static void s_socket_cleanup_fn(struct aws_socket *socket);
865 static int s_socket_connect_fn(struct aws_socket *socket, struct aws_socket_connect_options *socket_connect_options);
866 static int s_socket_bind_fn(struct aws_socket *socket, struct aws_socket_bind_options *socket_bind_options);
867 static int s_socket_listen_fn(struct aws_socket *socket, int backlog_size);
868 static int s_socket_start_accept_fn(
869 struct aws_socket *socket,
870 struct aws_event_loop *accept_loop,
871 struct aws_socket_listener_options options);
872 static int s_socket_stop_accept_fn(struct aws_socket *socket);
873 static int s_socket_close_fn(struct aws_socket *socket);
874 static int s_socket_shutdown_dir_fn(struct aws_socket *socket, enum aws_channel_direction dir);
875 static int s_socket_set_options_fn(struct aws_socket *socket, const struct aws_socket_options *options);
876 static int s_socket_assign_to_event_loop_fn(struct aws_socket *socket, struct aws_event_loop *event_loop);
877 static int s_socket_subscribe_to_readable_events_fn(
878 struct aws_socket *socket,
879 aws_socket_on_readable_fn *on_readable,
880 void *user_data);
881 static int s_socket_read_fn(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read);
882 static int s_socket_write_fn(
883 struct aws_socket *socket,
884 const struct aws_byte_cursor *cursor,
885 aws_socket_on_write_completed_fn *written_fn,
886 void *user_data);
887 static int s_socket_get_error_fn(struct aws_socket *socket);
888 static bool s_socket_is_open_fn(struct aws_socket *socket);
889 static int s_set_close_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
890 static int s_set_cleanup_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
891 static struct aws_byte_buf s_socket_get_protocol_fn(const struct aws_socket *socket);
892 static struct aws_string *s_socket_get_server_name_fn(const struct aws_socket *socket);
893
894 static struct aws_socket_vtable s_vtable = {
895 .socket_cleanup_fn = s_socket_cleanup_fn,
896 .socket_connect_fn = s_socket_connect_fn,
897 .socket_bind_fn = s_socket_bind_fn,
898 .socket_listen_fn = s_socket_listen_fn,
899 .socket_start_accept_fn = s_socket_start_accept_fn,
900 .socket_stop_accept_fn = s_socket_stop_accept_fn,
901 .socket_close_fn = s_socket_close_fn,
902 .socket_shutdown_dir_fn = s_socket_shutdown_dir_fn,
903 .socket_set_options_fn = s_socket_set_options_fn,
904 .socket_assign_to_event_loop_fn = s_socket_assign_to_event_loop_fn,
905 .socket_subscribe_to_readable_events_fn = s_socket_subscribe_to_readable_events_fn,
906 .socket_read_fn = s_socket_read_fn,
907 .socket_write_fn = s_socket_write_fn,
908 .socket_get_error_fn = s_socket_get_error_fn,
909 .socket_is_open_fn = s_socket_is_open_fn,
910 .socket_set_close_callback = s_set_close_callback,
911 .socket_set_cleanup_callback = s_set_cleanup_callback,
912 .socket_get_protocol_fn = s_socket_get_protocol_fn,
913 .socket_get_server_name_fn = s_socket_get_server_name_fn,
914 };
915
916 static int s_schedule_next_read(struct nw_socket *socket);
917
918 static void s_socket_cleanup_fn(struct aws_socket *socket) {
919 if (!socket->impl) {
920 /* protect from double clean */
921 return;
922 }
923
924 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p nw_socket=%p: is cleanup...", (void *)socket, (void *)socket->impl);
925 if (aws_socket_is_open(socket)) {
926 AWS_LOGF_DEBUG(
927 AWS_LS_IO_SOCKET, "id=%p nw_socket=%p: is still open, closing...", (void *)socket, (void *)socket->impl);
928 aws_socket_close(socket);
929 }
930
931 struct nw_socket *nw_socket = socket->impl;
932
933 if (s_validate_event_loop(socket->event_loop) && !aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
934 s_lock_base_socket(nw_socket);
935 nw_socket->base_socket_synced_data.base_socket = NULL;
936 s_unlock_base_socket(nw_socket);
937 } else {
938 // If we are already on event loop or event loop is unavailable, we should already acquire the lock for base
939 // socket access
940 nw_socket->base_socket_synced_data.base_socket = NULL;
941 }
942
943 aws_ref_count_release(&nw_socket->nw_socket_ref_count);
944 socket->impl = NULL;
945 AWS_ZERO_STRUCT(*socket);
946 }
947
948 struct read_queue_node {
949 struct aws_allocator *allocator;
950 dispatch_data_t received_data;
951 struct aws_linked_list_node node;
952 size_t region_offset;
953 // If we didn't finish reading the received_data, we need to keep track of the region offset that we would
954 // like to resume with
955 size_t resume_region;
956 };
957
958 static void s_read_queue_node_destroy(struct read_queue_node *node) {
959 /* releases reference count on dispatch_data_t that was increased during creation of read_queue_node */
960 dispatch_release(node->received_data);
961 aws_mem_release(node->allocator, node);
962 }
963
964 struct socket_close_complete_args {
965 struct aws_task task;
966 struct aws_allocator *allocator;
967 aws_socket_on_shutdown_complete_fn *shutdown_complete_fn;
968 void *user_data;
969 struct nw_socket *nw_socket;
970 };
971
972 static void s_close_complete_callback(struct aws_task *task, void *arg, enum aws_task_status status) {
973 (void)status;
974 (void)task;
975 struct socket_close_complete_args *task_arg = arg;
976 struct aws_allocator *allocator = task_arg->allocator;
977 if (task_arg->shutdown_complete_fn) {
978 task_arg->shutdown_complete_fn(task_arg->user_data);
979 }
980 aws_ref_count_release(&task_arg->nw_socket->nw_socket_ref_count);
981 aws_mem_release(allocator, task_arg);
982 }
983
984 static void s_socket_impl_destroy(void *sock_ptr) {
985 struct nw_socket *nw_socket = sock_ptr;
986 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p : start s_socket_impl_destroy", (void *)sock_ptr);
987 /* In case we have leftovers from the read queue, clean them up. */
988 while (!aws_linked_list_empty(&nw_socket->read_queue)) {
989 struct aws_linked_list_node *node = aws_linked_list_pop_front(&nw_socket->read_queue);
990 struct read_queue_node *read_queue_node = AWS_CONTAINER_OF(node, struct read_queue_node, node);
991 s_read_queue_node_destroy(read_queue_node);
992 }
993
994 /* Network Framework cleanup */
995 if (nw_socket->nw_parameters) {
996 nw_release(nw_socket->nw_parameters);
997 nw_socket->nw_parameters = NULL;
998 }
999
1000 aws_string_destroy(nw_socket->host_name);
1001
1002 aws_string_destroy(nw_socket->alpn_list);
1003
1004 aws_byte_buf_clean_up(&nw_socket->protocol_buf);
1005
1006 if (nw_socket->tls_ctx) {
1007 aws_tls_ctx_release(nw_socket->tls_ctx);
1008 nw_socket->tls_ctx = NULL;
1009 }
1010
1011 aws_socket_on_shutdown_complete_fn *on_cleanup_complete = nw_socket->on_socket_cleanup_complete_fn;
1012 void *cleanup_user_data = nw_socket->cleanup_user_data;
1013
1014 aws_mutex_clean_up(&nw_socket->synced_data.lock);
1015 aws_mutex_clean_up(&nw_socket->base_socket_synced_data.lock);
1016 aws_mem_release(nw_socket->allocator, nw_socket);
1017
1018 nw_socket = NULL;
1019
1020 if (on_cleanup_complete) {
1021 on_cleanup_complete(cleanup_user_data);
1022 }
1023 }
1024
1025 static void s_process_socket_cancel_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1026 (void)task;
1027 (void)status;
1028 struct nw_socket_cancel_task_args *args = arg;
1029 struct nw_socket *nw_socket = args->nw_socket;
1030
1031 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "nw_socket=%p: start to process socket cancel task.", (void *)nw_socket);
1032
1033 // The task should always run event when status == AWS_TASK_STATUS_CANCELLED. We rely on the task to clean up the
1034 // system connection/listener. And release the socket memory.
1035
1036 if ((nw_socket->mode == NWSM_CONNECTION && nw_socket->os_handle.nw_connection != NULL) ||
1037 (nw_socket->mode == NWSM_LISTENER && nw_socket->os_handle.nw_listener != NULL)) {
1038 // The timeout_args only setup for connected client connections.
1039 if (nw_socket->mode == NWSM_CONNECTION && nw_socket->timeout_args && !nw_socket->connection_setup) {
1040 // if the connection setup is not set, the timeout task has not yet triggered, cancel it.
1041 aws_event_loop_cancel_task(nw_socket->event_loop, &nw_socket->timeout_args->task);
1042 }
1043
1044 if (nw_socket->mode == NWSM_LISTENER) {
1045 nw_listener_cancel(nw_socket->os_handle.nw_listener);
1046 } else if (nw_socket->mode == NWSM_CONNECTION) {
1047 nw_connection_cancel(nw_socket->os_handle.nw_connection);
1048 }
1049 }
1050
1051 s_socket_release_internal_ref(nw_socket);
1052 aws_mem_release(args->allocator, args);
1053 }
1054
1055 // Cancel the socket and close the connection. The cancel should happened on the event loop.
1056 static void s_handle_socket_canceled(void *socket_ptr) {
1057 struct nw_socket *nw_socket = socket_ptr;
1058
1059 struct nw_socket_cancel_task_args *args =
1060 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_socket_cancel_task_args));
1061
1062 args->allocator = nw_socket->allocator;
1063 args->nw_socket = nw_socket;
1064
1065 /* The socket cancel should happened on the event loop if possible. The event loop will not set
1066 * in the case where the socket is never connected/ listener is never started accept.
1067 */
1068 if (s_validate_event_loop(nw_socket->event_loop)) {
1069
1070 aws_task_init(&args->task, s_process_socket_cancel_task, args, "SocketCanceledTask");
1071
1072 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1073 } else {
1074 s_process_socket_cancel_task(&args->task, args, AWS_TASK_STATUS_RUN_READY);
1075 }
1076 }
1077
1078 static void s_socket_internal_destroy(void *sock_ptr) {
1079 struct nw_socket *nw_socket = sock_ptr;
1080 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p : start s_socket_internal_destroy", (void *)sock_ptr);
1081
1082 if (s_validate_event_loop(nw_socket->event_loop)) {
1083 struct socket_close_complete_args *args =
1084 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct socket_close_complete_args));
1085
1086 args->shutdown_complete_fn = nw_socket->on_socket_close_complete_fn;
1087 args->user_data = nw_socket->close_user_data;
1088 args->allocator = nw_socket->allocator;
1089 args->nw_socket = nw_socket;
1090 // At this point the internal ref count has been dropped to 0, and we are about to release the external ref
1091 // count.
1092 // However, we would still keep the external ref count alive until the s_close_complete_callback callback is
1093 // invoked. Acquire another external ref count to keep the socket alive. It will be released in
1094 // s_close_complete_callback.
1095 aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
1096 aws_task_init(&args->task, s_close_complete_callback, args, "SocketShutdownCompleteTask");
1097
1098 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1099 } else {
1100 // If we are not on the event loop
1101 if (nw_socket->on_socket_close_complete_fn) {
1102 nw_socket->on_socket_close_complete_fn(nw_socket->close_user_data);
1103 }
1104 }
1105
1106 if (nw_socket->mode == NWSM_LISTENER) {
1107 nw_release(nw_socket->os_handle.nw_listener);
1108 } else if (nw_socket->mode == NWSM_CONNECTION) {
1109 nw_release(nw_socket->os_handle.nw_connection);
1110 }
1111
1112 s_release_event_loop(nw_socket);
1113 aws_ref_count_release(&nw_socket->nw_socket_ref_count);
1114 }
1115
1116 int aws_socket_init_apple_nw_socket(
1117 struct aws_socket *socket,
1118 struct aws_allocator *alloc,
1119 const struct aws_socket_options *options) {
1120 AWS_FATAL_ASSERT(options);
1121 AWS_ZERO_STRUCT(*socket);
1122
1123 // Network Interface is not supported with Apple Network Framework yet
1124 if (options->network_interface_name[0] != 0) {
1125 AWS_LOGF_DEBUG(
1126 AWS_LS_IO_SOCKET,
1127 "id=%p fd=%d: network_interface_name is not supported on this platform.",
1128 (void *)socket,
1129 socket->io_handle.data.fd);
1130 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
1131 }
1132
1133 struct nw_socket *nw_socket = aws_mem_calloc(alloc, 1, sizeof(struct nw_socket));
1134 nw_socket->allocator = alloc;
1135
1136 socket->allocator = alloc;
1137 socket->options = *options;
1138 socket->impl = nw_socket;
1139 socket->vtable = &s_vtable;
1140
1141 aws_mutex_init(&nw_socket->synced_data.lock);
1142 aws_mutex_init(&nw_socket->base_socket_synced_data.lock);
1143 nw_socket->base_socket_synced_data.base_socket = socket;
1144
1145 nw_socket->synced_data.state = AWS_NW_SOCKET_STATE_INIT;
1146 socket->state = AWS_NW_SOCKET_STATE_INIT;
1147
1148 aws_ref_count_init(&nw_socket->nw_socket_ref_count, nw_socket, s_socket_impl_destroy);
1149 aws_ref_count_init(&nw_socket->internal_ref_count, nw_socket, s_socket_internal_destroy);
1150 // The internal_ref_count should keep a reference of the nw_socket_ref_count. When the internal_ref_count
1151 // drop to 0, it would release the nw_socket_ref_count.
1152 aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
1153 aws_ref_count_init(&nw_socket->write_ref_count, nw_socket, s_handle_socket_canceled);
1154
1155 aws_linked_list_init(&nw_socket->read_queue);
1156
1157 AWS_LOGF_DEBUG(
1158 AWS_LS_IO_SOCKET,
1159 "id=%p nw_socket=%p fd=%d: socket created.",
1160 (void *)socket,
1161 (void *)nw_socket,
1162 socket->io_handle.data.fd);
1163
1164 return AWS_OP_SUCCESS;
1165 }
1166
1167 static void s_client_set_dispatch_queue(struct aws_io_handle *handle, void *queue) {
1168 nw_connection_set_queue(handle->data.handle, queue);
1169 }
1170
1171 static void s_handle_socket_timeout(struct aws_task *task, void *args, aws_task_status status) {
1172 (void)task;
1173 (void)status;
1174
1175 struct nw_socket_timeout_args *timeout_args = args;
1176 struct nw_socket *nw_socket = timeout_args->nw_socket;
1177
1178 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "task_id=%p: timeout task triggered, evaluating timeouts.", (void *)task);
1179
1180 s_lock_base_socket(nw_socket);
1181 struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
1182 if (!nw_socket->connection_setup && socket) {
1183 AWS_LOGF_DEBUG(
1184 AWS_LS_IO_SOCKET,
1185 "id=%p handle=%p: timed out, shutting down.",
1186 (void *)socket,
1187 (void *)nw_socket->os_handle.nw_connection);
1188
1189 int error_code = AWS_IO_SOCKET_TIMEOUT;
1190
1191 // Must set timeout_args to NULL to avoid double cancel. Clean up the timeout task
1192 aws_mem_release(nw_socket->allocator, nw_socket->timeout_args);
1193 nw_socket->timeout_args = NULL;
1194 aws_socket_close(socket);
1195 nw_socket->on_connection_result_fn(socket, error_code, nw_socket->connect_result_user_data);
1196 } else {
1197 // If the socket is already setup (either succeed or failed), we have already invoked the callback to notify the
1198 // connection result. No need to invoke again. If the aws_socket is NULL (cleaned up by user), there is no
1199 // meaning to invoke the callback anymore. Simply release the memory in these two cases.
1200 aws_mem_release(nw_socket->allocator, nw_socket->timeout_args);
1201 nw_socket->timeout_args = NULL;
1202 }
1203
1204 s_unlock_base_socket(nw_socket);
1205
1206 s_socket_release_internal_ref(nw_socket);
1207 // No need to release task, as task lives on timeout_args on nw_socket.
1208 }
1209
1210 static void s_process_incoming_data_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1211 (void)task;
1212 (void)status;
1213 struct nw_socket_scheduled_task_args *readable_args = arg;
1214 struct nw_socket *nw_socket = readable_args->nw_socket;
1215 int crt_error = readable_args->error_code;
1216
1217 AWS_LOGF_TRACE(
1218 AWS_LS_IO_SOCKET,
1219 "id=%p handle=%p: start to process read data.",
1220 (void *)nw_socket,
1221 (void *)nw_socket->os_handle.nw_connection);
1222
1223 // If data is valid, push it in read_queue. The read_queue should be only accessed in event loop, as the
1224 // task is scheduled in event loop, it is fine to directly access it.
1225 if (readable_args->data) {
1226 // We directly store the dispatch_data returned from kernel. This could potentially be performance concern.
1227 // Another option is to read the data out into heap buffer and store the heap buffer in read_queue. However,
1228 // this would introduce extra memory copy. We would like to keep the dispatch_data_t in read_queue for now.
1229 struct read_queue_node *node = aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct read_queue_node));
1230 node->allocator = nw_socket->allocator;
1231 node->received_data = readable_args->data;
1232 aws_linked_list_push_back(&nw_socket->read_queue, &node->node);
1233 AWS_LOGF_DEBUG(
1234 AWS_LS_IO_SOCKET,
1235 "id=%p handle=%p: read data is not empty, push data to read_queue",
1236 (void *)nw_socket,
1237 (void *)nw_socket->os_handle.nw_connection);
1238 }
1239
1240 if (status != AWS_TASK_STATUS_CANCELED) {
1241 s_lock_base_socket(nw_socket);
1242 struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
1243
1244 // If the protocol is TCP, `is_complete` means the connection is closed, raise the
1245 // AWS_IO_SOCKET_CLOSED error
1246 if (socket && socket->options.type != AWS_SOCKET_DGRAM && readable_args->is_complete) {
1247 crt_error = AWS_IO_SOCKET_CLOSED;
1248 s_lock_socket_synced_data(nw_socket);
1249 s_set_socket_state(nw_socket, ~AWS_NW_SOCKET_STATE_CONNECTED_READ);
1250 s_unlock_socket_synced_data(nw_socket);
1251 AWS_LOGF_TRACE(
1252 AWS_LS_IO_SOCKET,
1253 "id=%p handle=%p: socket is complete, flip read flag",
1254 (void *)nw_socket,
1255 (void *)nw_socket->os_handle.nw_connection);
1256 }
1257
1258 if (nw_socket->on_readable) {
1259 nw_socket->on_readable(socket, crt_error, nw_socket->on_readable_user_data);
1260 }
1261 s_unlock_base_socket(nw_socket);
1262 }
1263
1264 s_socket_release_internal_ref(nw_socket);
1265
1266 aws_mem_release(readable_args->allocator, readable_args);
1267 }
1268
1269 static void s_handle_incoming_data(
1270 struct nw_socket *nw_socket,
1271 int error_code,
1272 dispatch_data_t data,
1273 bool is_complete) {
1274
1275 if (s_validate_event_loop(nw_socket->event_loop)) {
1276 struct nw_socket_scheduled_task_args *args =
1277 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_socket_scheduled_task_args));
1278
1279 args->is_complete = is_complete;
1280 args->nw_socket = nw_socket;
1281 args->allocator = nw_socket->allocator;
1282 args->error_code = error_code;
1283
1284 if (data) {
1285 dispatch_retain(data);
1286 args->data = data;
1287 }
1288 s_socket_acquire_internal_ref(nw_socket);
1289 aws_task_init(&args->task, s_process_incoming_data_task, args, "readableTask");
1290
1291 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1292 }
1293 }
1294
1295 static void s_process_connection_result_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1296 (void)status;
1297 (void)task;
1298
1299 struct nw_socket_scheduled_task_args *task_args = arg;
1300 struct nw_socket *nw_socket = task_args->nw_socket;
1301
1302 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "nw_socket=%p: start to process connection result task.", (void *)nw_socket);
1303
1304 if (status != AWS_TASK_STATUS_CANCELED) {
1305 s_lock_base_socket(nw_socket);
1306 struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
1307 if (socket && nw_socket->on_connection_result_fn)
1308 nw_socket->on_connection_result_fn(socket, task_args->error_code, nw_socket->connect_result_user_data);
1309 s_unlock_base_socket(nw_socket);
1310 }
1311
1312 s_socket_release_internal_ref(nw_socket);
1313
1314 aws_mem_release(task_args->allocator, task_args);
1315 }
1316
1317 static void s_handle_on_connection_result(struct nw_socket *nw_socket, int error_code) {
1318
1319 if (s_validate_event_loop(nw_socket->event_loop)) {
1320 struct nw_socket_scheduled_task_args *args =
1321 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_socket_scheduled_task_args));
1322
1323 args->nw_socket = s_socket_acquire_internal_ref(nw_socket);
1324 args->allocator = nw_socket->allocator;
1325 args->error_code = error_code;
1326
1327 aws_task_init(&args->task, s_process_connection_result_task, args, "connectionSuccessTask");
1328 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1329 }
1330 }
1331
1332 struct connection_state_change_args {
1333 struct aws_task task;
1334 struct aws_allocator *allocator;
1335 struct nw_socket *nw_socket;
1336 nw_connection_t nw_connection;
1337 nw_connection_state_t state;
1338 int error;
1339 };
1340
1341 static void s_process_connection_state_changed_ready(struct nw_socket *nw_socket, nw_connection_t nw_connection) {
1342 s_lock_base_socket(nw_socket);
1343 struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
1344 if (socket) {
1345 nw_path_t path = nw_connection_copy_current_path(nw_connection);
1346 nw_endpoint_t local_endpoint = nw_path_copy_effective_local_endpoint(path);
1347 nw_release(path);
1348 const char *hostname = nw_endpoint_get_hostname(local_endpoint);
1349 uint16_t port = nw_endpoint_get_port(local_endpoint);
1350 nw_release(local_endpoint);
1351
1352 if (hostname != NULL) {
1353 size_t hostname_len = strlen(hostname);
1354 size_t buffer_size = AWS_ARRAY_SIZE(socket->local_endpoint.address);
1355 size_t to_copy = aws_min_size(hostname_len, buffer_size);
1356 memcpy(socket->local_endpoint.address, hostname, to_copy);
1357 socket->local_endpoint.port = port;
1358 }
1359
1360 AWS_LOGF_TRACE(
1361 AWS_LS_IO_SOCKET,
1362 "id=%p handle=%p: set local endpoint %s:%d",
1363 (void *)socket,
1364 socket->io_handle.data.handle,
1365 socket->local_endpoint.address,
1366 port);
1367
1368 /* Check and store protocol for connection */
1369 if (nw_socket->tls_ctx) {
1370 nw_protocol_metadata_t metadata =
1371 nw_connection_copy_protocol_metadata(socket->io_handle.data.handle, nw_protocol_copy_tls_definition());
1372 if (metadata != NULL) {
1373 sec_protocol_metadata_t sec_metadata = (sec_protocol_metadata_t)metadata;
1374
1375 #pragma clang diagnostic push
1376 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1377 /* sec_protocol_metadata_get_negotiated_protocol was deprecated in macOS 15.5 and iOS 18.5. It should be
1378 * replaced by sec_protocol_metadata_copy_negotiated_protocol, but this function became available in
1379 * macOS 15 and iOS 18.5 only.
1380 * To avoid bumping a minimum supported versions of Apple platforms or introducing a logic for choosing
1381 * an appropriate function in runtime, we use the deprecated function for now.
1382 */
1383 const char *negotiated_protocol = sec_protocol_metadata_get_negotiated_protocol(sec_metadata);
1384 #pragma clang diagnostic pop
1385
1386 if (negotiated_protocol) {
1387 nw_socket->protocol_buf = aws_byte_buf_from_c_str(negotiated_protocol);
1388 AWS_LOGF_DEBUG(
1389 AWS_LS_IO_TLS,
1390 "id=%p handle=%p: ALPN protocol set to: '%s'",
1391 (void *)socket,
1392 socket->io_handle.data.handle,
1393 nw_socket->protocol_buf.buffer);
1394 }
1395 nw_release(metadata);
1396 }
1397 }
1398 } else {
1399 /*
1400 * This happens when the aws_socket_clean_up() is called before the nw_connection_state_ready is
1401 * returned. We still want to set the socket to write/read state and fire the connection succeed
1402 * callback until we get the "nw_connection_state_cancelled" status.
1403 */
1404 AWS_LOGF_TRACE(
1405 AWS_LS_IO_SOCKET,
1406 "nw_socket=%p handle=%p: connection succeed, however, the base socket has been cleaned up.",
1407 (void *)nw_socket,
1408 (void *)nw_socket->os_handle.nw_connection);
1409 }
1410 s_lock_socket_synced_data(nw_socket);
1411 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_CONNECTED_WRITE | AWS_NW_SOCKET_STATE_CONNECTED_READ);
1412 s_unlock_socket_synced_data(nw_socket);
1413 s_unlock_base_socket(nw_socket);
1414
1415 nw_socket->connection_setup = true;
1416 // Cancel the connection timeout task
1417 if (nw_socket->timeout_args) {
1418 aws_event_loop_cancel_task(nw_socket->event_loop, &nw_socket->timeout_args->task);
1419 }
1420 aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
1421 s_handle_on_connection_result(nw_socket, AWS_OP_SUCCESS);
1422 aws_ref_count_release(&nw_socket->nw_socket_ref_count);
1423 }
1424
1425 static void s_process_connection_state_changed_task(struct aws_task *task, void *args, enum aws_task_status status) {
1426 (void)status;
1427 (void)task;
1428
1429 struct connection_state_change_args *connection_args = args;
1430
1431 struct nw_socket *nw_socket = connection_args->nw_socket;
1432 nw_connection_t nw_connection = connection_args->nw_connection;
1433 nw_connection_state_t state = connection_args->state;
1434
1435 /* Ideally we should not have a canceled task here, as nw_socket keeps a reference to event loop, therefore the
1436 * event loop should never be destroyed before the nw_socket get destroyed. If we manually cancel the task, we
1437 * should make sure we carefully handled the state change eventually, as the socket relies on this task to release
1438 * and cleanup.
1439 */
1440 if (status != AWS_TASK_STATUS_CANCELED) {
1441 switch (state) {
1442 case nw_connection_state_cancelled: {
1443 AWS_LOGF_INFO(
1444 AWS_LS_IO_SOCKET,
1445 "nw_socket=%p handle=%p: Apple network framework socket connection state changed to cancelled, nw "
1446 "error "
1447 "code : %d",
1448 (void *)nw_socket,
1449 (void *)nw_socket->os_handle.nw_connection,
1450 connection_args->error);
1451 s_lock_socket_synced_data(nw_socket);
1452 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_CLOSED);
1453 s_unlock_socket_synced_data(nw_socket);
1454
1455 s_socket_release_internal_ref(nw_socket);
1456 } break;
1457 case nw_connection_state_ready: {
1458 AWS_LOGF_INFO(
1459 AWS_LS_IO_SOCKET,
1460 "nw_socket=%p handle=%p: Apple network framework socket connection state changed to ready, nw "
1461 "error "
1462 "code : %d",
1463 (void *)nw_socket,
1464 (void *)nw_socket->os_handle.nw_connection,
1465 connection_args->error);
1466 s_process_connection_state_changed_ready(nw_socket, nw_connection);
1467 } break;
1468 case nw_connection_state_waiting:
1469 case nw_connection_state_preparing:
1470 case nw_connection_state_failed:
1471 default:
1472 break;
1473 }
1474
1475 int crt_error_code = connection_args->error;
1476 if (crt_error_code) {
1477 /* any error, including if closed remotely in error */
1478 AWS_LOGF_DEBUG(
1479 AWS_LS_IO_SOCKET,
1480 "nw_socket=%p handle=%p: socket connection got error: %d",
1481 (void *)nw_socket,
1482 (void *)nw_socket->os_handle.nw_connection,
1483 crt_error_code);
1484
1485 nw_socket->last_error = crt_error_code;
1486 s_lock_socket_synced_data(nw_socket);
1487 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_ERROR);
1488 s_unlock_socket_synced_data(nw_socket);
1489
1490 if (!nw_socket->connection_setup) {
1491 s_handle_on_connection_result(nw_socket, crt_error_code);
1492 nw_socket->connection_setup = true;
1493 // Cancel the connection timeout task
1494 if (nw_socket->timeout_args) {
1495 aws_event_loop_cancel_task(nw_socket->event_loop, &nw_socket->timeout_args->task);
1496 }
1497 } else {
1498 s_handle_incoming_data(nw_socket, nw_socket->last_error, NULL, false);
1499 }
1500 }
1501 }
1502
1503 s_socket_release_internal_ref(nw_socket);
1504 aws_mem_release(connection_args->allocator, connection_args);
1505 }
1506
1507 static void s_handle_connection_state_changed_fn(
1508 struct nw_socket *nw_socket,
1509 nw_connection_t nw_connection,
1510 nw_connection_state_t state,
1511 nw_error_t error) {
1512
1513 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "nw_socket=%p: s_handle_connection_state_changed_fn start...", (void *)nw_socket);
1514
1515 int crt_error_code = s_convert_nw_error(error);
1516 if (crt_error_code) {
1517 AWS_LOGF_DEBUG(
1518 AWS_LS_IO_SOCKET,
1519 "nw_socket=%p handle=%p: s_handle_connection_state_changed_fn invoked error code %d : %s.",
1520 (void *)nw_socket,
1521 (void *)nw_socket->os_handle.nw_connection,
1522 crt_error_code,
1523 aws_error_name(crt_error_code));
1524 }
1525
1526 if (s_validate_event_loop(nw_socket->event_loop)) {
1527 struct connection_state_change_args *args =
1528 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct connection_state_change_args));
1529
1530 args->nw_socket = nw_socket;
1531 args->allocator = nw_socket->allocator;
1532 args->error = crt_error_code;
1533 args->state = state;
1534 args->nw_connection = nw_connection;
1535
1536 s_socket_acquire_internal_ref(nw_socket);
1537
1538 aws_task_init(&args->task, s_process_connection_state_changed_task, args, "ConnectionStateChangedTask");
1539
1540 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1541
1542 } else if (state == nw_connection_state_cancelled) {
1543 s_socket_release_internal_ref(nw_socket);
1544 }
1545 }
1546
1547 static void s_process_listener_success_task(struct aws_task *task, void *args, enum aws_task_status status) {
1548 (void)task;
1549 struct nw_listener_connection_args *task_args = args;
1550 struct aws_allocator *allocator = task_args->allocator;
1551 struct nw_socket *listener_nw_socket = task_args->nw_socket;
1552 int error = task_args->error_code;
1553
1554 AWS_FATAL_ASSERT(listener_nw_socket && listener_nw_socket->mode == NWSM_LISTENER);
1555
1556 AWS_LOGF_TRACE(
1557 AWS_LS_IO_SOCKET,
1558 "id=%p handle=%p: start to process incoming connection.",
1559 (void *)listener_nw_socket,
1560 (void *)listener_nw_socket->os_handle.nw_listener);
1561
1562 if (status == AWS_TASK_STATUS_RUN_READY) {
1563 s_lock_base_socket(listener_nw_socket);
1564 struct aws_socket *listener = listener_nw_socket->base_socket_synced_data.base_socket;
1565 AWS_FATAL_ASSERT(listener && listener->accept_result_fn);
1566 struct aws_socket *new_socket = NULL;
1567
1568 if (error) {
1569 goto incoming_listener_error_cleanup;
1570 }
1571
1572 new_socket = aws_mem_calloc(allocator, 1, sizeof(struct aws_socket));
1573 struct aws_socket_options options = listener->options;
1574 error = aws_socket_init(new_socket, allocator, &options);
1575 if (error) {
1576 goto incoming_listener_error_cleanup;
1577 }
1578
1579 nw_endpoint_t endpoint = nw_connection_copy_endpoint(task_args->new_connection);
1580 const char *hostname = nw_endpoint_get_hostname(endpoint);
1581 uint16_t port = nw_endpoint_get_port(endpoint);
1582
1583 if (hostname != NULL) {
1584 size_t address_strlen;
1585 if (aws_secure_strlen(hostname, AWS_ADDRESS_MAX_LEN, &address_strlen)) {
1586 nw_release(endpoint);
1587 goto incoming_listener_error_cleanup;
1588 }
1589
1590 struct aws_byte_buf hostname_buf = aws_byte_buf_from_c_str(hostname);
1591 struct aws_byte_buf address_buf =
1592 aws_byte_buf_from_empty_array(new_socket->remote_endpoint.address, AWS_ADDRESS_MAX_LEN);
1593 aws_byte_buf_write_from_whole_buffer(&address_buf, hostname_buf);
1594 aws_byte_buf_clean_up(&address_buf);
1595 aws_byte_buf_clean_up(&hostname_buf);
1596
1597 new_socket->remote_endpoint.port = port;
1598 }
1599 nw_release(endpoint);
1600
1601 new_socket->io_handle.data.handle = task_args->new_connection;
1602 new_socket->io_handle.set_queue = s_client_set_dispatch_queue;
1603
1604 struct nw_socket *new_nw_socket = new_socket->impl;
1605 new_nw_socket->os_handle.nw_connection = task_args->new_connection;
1606 new_nw_socket->connection_setup = true;
1607
1608 // Setup socket state to start read/write operations. We didn't lock here as we are in initializing process, no
1609 // other process will touch the socket state.
1610 s_set_socket_state(new_nw_socket, AWS_NW_SOCKET_STATE_CONNECTED_READ | AWS_NW_SOCKET_STATE_CONNECTED_WRITE);
1611
1612 // this internal ref will be released when the connection canceled ( connection state changed to
1613 // nw_connection_state_cancelled)
1614 s_socket_acquire_internal_ref(new_nw_socket);
1615
1616 nw_connection_set_state_changed_handler(
1617 new_socket->io_handle.data.handle, ^(nw_connection_state_t state, nw_error_t error) {
1618 s_handle_connection_state_changed_fn(new_nw_socket, new_nw_socket->os_handle.nw_connection, state, error);
1619 });
1620
1621 AWS_LOGF_DEBUG(
1622 AWS_LS_IO_SOCKET,
1623 "id=%p handle=%p: incoming connection has been successfully connected to %s:%d, the incoming "
1624 "handle is %p",
1625 (void *)listener,
1626 listener->io_handle.data.handle,
1627 new_socket->remote_endpoint.address,
1628 new_socket->remote_endpoint.port,
1629 new_socket->io_handle.data.handle);
1630
1631 goto incoming_listener_finalize;
1632
1633 incoming_listener_error_cleanup:
1634 if (new_socket) {
1635 aws_socket_clean_up(new_socket);
1636 aws_mem_release(allocator, new_socket);
1637 new_socket = NULL;
1638 }
1639 AWS_LOGF_DEBUG(
1640 AWS_LS_IO_SOCKET,
1641 "id=%p handle=%p: failed to setup new socket for incoming connection with error code %d.",
1642 (void *)listener,
1643 listener->io_handle.data.handle,
1644 error);
1645 nw_release(task_args->new_connection);
1646
1647 incoming_listener_finalize:
1648 listener->accept_result_fn(listener, error, new_socket, task_args->user_data);
1649
1650 s_unlock_base_socket(listener_nw_socket);
1651
1652 } else {
1653 AWS_LOGF_DEBUG(
1654 AWS_LS_IO_SOCKET,
1655 "id=%p handle=%p: process incoming listener task canceled .",
1656 (void *)listener_nw_socket,
1657 (void *)listener_nw_socket->os_handle.nw_listener);
1658 // If the task is not scheduled, release the connection.
1659 nw_release(task_args->new_connection);
1660 }
1661
1662 s_socket_release_internal_ref(listener_nw_socket);
1663 aws_mem_release(task_args->allocator, task_args);
1664 }
1665
1666 static void s_handle_on_listener_success(
1667 struct nw_socket *nw_socket,
1668 int error_code,
1669 nw_connection_t new_connection,
1670 void *user_data) {
1671
1672 if (s_validate_event_loop(nw_socket->event_loop)) {
1673
1674 struct nw_listener_connection_args *args =
1675 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_listener_connection_args));
1676
1677 args->nw_socket = nw_socket;
1678 args->allocator = nw_socket->allocator;
1679 args->error_code = error_code;
1680 args->new_connection = new_connection;
1681 args->user_data = user_data;
1682
1683 s_socket_acquire_internal_ref(nw_socket);
1684 nw_retain(new_connection);
1685
1686 aws_task_init(&args->task, s_process_listener_success_task, args, "listenerSuccessTask");
1687 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1688 }
1689 }
1690
1691 static void s_process_write_task(struct aws_task *task, void *args, enum aws_task_status status) {
1692 (void)task;
1693 struct nw_socket_written_args *task_args = args;
1694 struct aws_allocator *allocator = task_args->allocator;
1695 struct nw_socket *nw_socket = task_args->nw_socket;
1696
1697 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "nw_socket=%p: start to process write task.", (void *)nw_socket);
1698
1699 if (status != AWS_TASK_STATUS_CANCELED) {
1700 s_lock_base_socket(nw_socket);
1701 struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
1702 if (task_args->written_fn) {
1703 task_args->written_fn(socket, task_args->error_code, task_args->bytes_written, task_args->user_data);
1704 }
1705 s_unlock_base_socket(nw_socket);
1706 }
1707
1708 s_socket_release_internal_ref(nw_socket);
1709
1710 aws_mem_release(allocator, task_args);
1711 }
1712
1713 static void s_handle_write_fn(
1714 struct nw_socket *nw_socket,
1715 int error_code,
1716 size_t bytes_written,
1717 void *user_data,
1718 aws_socket_on_write_completed_fn *written_fn) {
1719 AWS_FATAL_ASSERT(s_validate_event_loop(nw_socket->event_loop));
1720
1721 struct nw_socket_written_args *args =
1722 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_socket_written_args));
1723
1724 args->nw_socket = nw_socket;
1725 args->allocator = nw_socket->allocator;
1726 args->error_code = error_code;
1727 args->written_fn = written_fn;
1728 args->user_data = user_data;
1729 args->bytes_written = bytes_written;
1730 s_socket_acquire_internal_ref(nw_socket);
1731
1732 aws_task_init(&args->task, s_process_write_task, args, "writtenTask");
1733
1734 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
1735 }
1736
1737 /*
1738 * Because TLS negotiation is handled by Apple Network Framework connection using its parameters, we need access to a
1739 * number of items typically not needed until the TLS slot and handler are being initialized. This function along with
1740 * retrieves the necessary TLS items and stores them in nw_socket.
1741 */
1742 static int s_setup_tls_options_from_tls_connection_options(
1743 struct nw_socket *nw_socket,
1744 struct aws_tls_connection_options *tls_connection_options) {
1745 if (nw_socket->tls_ctx != NULL || nw_socket->host_name != NULL || nw_socket->alpn_list != NULL) {
1746 AWS_LOGF_ERROR(
1747 AWS_LS_IO_SOCKET, "nw_socket=%p: Socket cannot have TLS options set more than once.", (void *)nw_socket);
1748 return AWS_OP_ERR;
1749 }
1750
1751 /* This check allows us to safely call this function whether or not TLS related options have been set. */
1752 if (tls_connection_options == NULL) {
1753 return AWS_OP_SUCCESS;
1754 }
1755
1756 /* The host name is needed during the setup of the verification block */
1757 if (tls_connection_options->server_name != NULL) {
1758 nw_socket->host_name = aws_string_new_from_string(
1759 tls_connection_options->server_name->allocator, tls_connection_options->server_name);
1760 if (nw_socket->host_name == NULL) {
1761 AWS_LOGF_ERROR(
1762 AWS_LS_IO_SOCKET,
1763 "nw_socket=%p: Error encounterd during setup of host name from tls connection options.",
1764 (void *)nw_socket);
1765 return AWS_OP_ERR;
1766 }
1767 }
1768
1769 /* TLS negotiation needs the alpn list if one is present for use. */
1770 struct aws_string *alpn_list = NULL;
1771 if (tls_connection_options->alpn_list != NULL) {
1772 alpn_list = tls_connection_options->alpn_list;
1773 }
1774
1775 /* The tls_ctx is needed to setup TLS negotiation options in the Apple Network Framework connection's parameters */
1776 if (tls_connection_options->ctx != NULL) {
1777 nw_socket->tls_ctx = tls_connection_options->ctx;
1778 aws_tls_ctx_acquire(nw_socket->tls_ctx);
1779
1780 /* If alpn_list hasn't been set, try assigning it from the transport_ctx. It's fine if it's also NULL. */
1781 if (alpn_list == NULL) {
1782 struct secure_transport_ctx *transport_ctx = nw_socket->tls_ctx->impl;
1783 alpn_list = transport_ctx->alpn_list;
1784 }
1785 }
1786
1787 /* If an alpn_list was found, we store it for use in nw_socket for the setup of TLS parameters */
1788 if (alpn_list != NULL) {
1789 nw_socket->alpn_list = aws_string_new_from_string(alpn_list->allocator, alpn_list);
1790 if (nw_socket->alpn_list == NULL) {
1791 AWS_LOGF_ERROR(
1792 AWS_LS_IO_SOCKET,
1793 "nw_socket=%p: Error encounterd during setup of alpn list from tls context.",
1794 (void *)nw_socket);
1795 return AWS_OP_ERR;
1796 }
1797 }
1798
1799 return AWS_OP_SUCCESS;
1800 }
1801
1802 static int s_socket_connect_fn(struct aws_socket *socket, struct aws_socket_connect_options *socket_connect_options) {
1803 struct nw_socket *nw_socket = socket->impl;
1804
1805 const struct aws_socket_endpoint *remote_endpoint = socket_connect_options->remote_endpoint;
1806 struct aws_event_loop *event_loop = socket_connect_options->event_loop;
1807 aws_socket_on_connection_result_fn *on_connection_result = socket_connect_options->on_connection_result;
1808 void *user_data = socket_connect_options->user_data;
1809
1810 AWS_ASSERT(event_loop);
1811 AWS_FATAL_ASSERT(on_connection_result);
1812
1813 AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p beginning connect.", (void *)socket);
1814
1815 if (socket->event_loop) {
1816 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
1817 }
1818
1819 /* We take what we need for TLS negotiation from the tls_connection_options */
1820 if (s_setup_tls_options_from_tls_connection_options(nw_socket, socket_connect_options->tls_connection_options)) {
1821 return AWS_OP_ERR;
1822 }
1823
1824 /* event_loop must be set prior to setup of socket parameters. */
1825 if (s_set_event_loop(socket, event_loop)) {
1826 goto error;
1827 }
1828
1829 if (s_setup_socket_params(nw_socket, &socket->options)) {
1830 goto error;
1831 }
1832
1833 s_lock_socket_synced_data(nw_socket);
1834 if (nw_socket->synced_data.state != AWS_NW_SOCKET_STATE_INIT) {
1835 s_unlock_socket_synced_data(nw_socket);
1836 aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
1837 goto error;
1838 }
1839
1840 /* fill in posix sock addr, and then let Network framework sort it out. */
1841 size_t address_strlen;
1842 if (aws_secure_strlen(remote_endpoint->address, AWS_ADDRESS_MAX_LEN, &address_strlen)) {
1843 s_unlock_socket_synced_data(nw_socket);
1844 AWS_LOGF_DEBUG(
1845 AWS_LS_IO_SOCKET,
1846 "id=%p: failed to parse address %s:%d.",
1847 (void *)socket,
1848 remote_endpoint->address,
1849 (int)remote_endpoint->port);
1850 aws_raise_error(AWS_IO_SOCKET_INVALID_ADDRESS);
1851 goto error;
1852 }
1853
1854 struct socket_address address;
1855 AWS_ZERO_STRUCT(address);
1856 int pton_err = 1;
1857
1858 switch (socket->options.domain) {
1859 case AWS_SOCKET_IPV4: {
1860 pton_err = inet_pton(AF_INET, remote_endpoint->address, &address.sock_addr_types.addr_in.sin_addr);
1861 address.sock_addr_types.addr_in.sin_port = htons((uint16_t)remote_endpoint->port);
1862 address.sock_addr_types.addr_in.sin_family = AF_INET;
1863 address.sock_addr_types.addr_in.sin_len = sizeof(struct sockaddr_in);
1864 break;
1865 }
1866 case AWS_SOCKET_IPV6: {
1867 pton_err = inet_pton(AF_INET6, remote_endpoint->address, &address.sock_addr_types.addr_in6.sin6_addr);
1868 address.sock_addr_types.addr_in6.sin6_port = htons((uint16_t)remote_endpoint->port);
1869 address.sock_addr_types.addr_in6.sin6_family = AF_INET6;
1870 address.sock_addr_types.addr_in6.sin6_len = sizeof(struct sockaddr_in6);
1871 break;
1872 }
1873 case AWS_SOCKET_LOCAL: {
1874 address.sock_addr_types.un_addr.sun_family = AF_UNIX;
1875 strncpy(address.sock_addr_types.un_addr.sun_path, remote_endpoint->address, AWS_ADDRESS_MAX_LEN);
1876 address.sock_addr_types.un_addr.sun_len = sizeof(struct sockaddr_un);
1877 break;
1878 }
1879 default: {
1880 AWS_LOGF_ERROR(AWS_LS_IO_SOCKET, "id=%p: socket tried to bind to an unknow domain.", (void *)socket);
1881 s_unlock_socket_synced_data(nw_socket);
1882 aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
1883
1884 goto error;
1885 }
1886 }
1887
1888 if (pton_err != 1) {
1889 AWS_LOGF_ERROR(
1890 AWS_LS_IO_SOCKET,
1891 "id=%p: failed to parse address %s:%d.",
1892 (void *)socket,
1893 remote_endpoint->address,
1894 (int)remote_endpoint->port);
1895 s_unlock_socket_synced_data(nw_socket);
1896 aws_raise_error(s_convert_pton_error(pton_err));
1897 goto error;
1898 }
1899
1900 AWS_LOGF_DEBUG(
1901 AWS_LS_IO_SOCKET,
1902 "id=%p: connecting to endpoint %s:%d.",
1903 (void *)socket,
1904 remote_endpoint->address,
1905 (int)remote_endpoint->port);
1906
1907 nw_endpoint_t endpoint = nw_endpoint_create_address(&address.sock_addr_types.addr_base);
1908
1909 if (!endpoint) {
1910 AWS_LOGF_ERROR(
1911 AWS_LS_IO_SOCKET,
1912 "id=%p: failed to create remote address %s:%d.",
1913 (void *)socket,
1914 remote_endpoint->address,
1915 (int)remote_endpoint->port);
1916 s_unlock_socket_synced_data(nw_socket);
1917 aws_raise_error(AWS_IO_SOCKET_INVALID_ADDRESS);
1918 goto error;
1919 }
1920
1921 socket->io_handle.data.handle = nw_connection_create(endpoint, nw_socket->nw_parameters);
1922 nw_release(endpoint);
1923
1924 if (!socket->io_handle.data.handle) {
1925 AWS_LOGF_ERROR(
1926 AWS_LS_IO_SOCKET,
1927 "id=%p handle=%p: connection creation failed, please verify the socket options are setup properly.",
1928 (void *)socket,
1929 socket->io_handle.data.handle);
1930 s_unlock_socket_synced_data(nw_socket);
1931 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1932 goto error;
1933 } else {
1934 AWS_LOGF_DEBUG(
1935 AWS_LS_IO_SOCKET,
1936 "id=%p: nw_connection_create successfully created handle=%p",
1937 (void *)socket,
1938 socket->io_handle.data.handle);
1939 }
1940
1941 socket->remote_endpoint = *remote_endpoint;
1942 nw_socket->os_handle.nw_connection = socket->io_handle.data.handle;
1943
1944 socket->io_handle.set_queue = s_client_set_dispatch_queue;
1945 aws_event_loop_connect_handle_to_io_completion_port(event_loop, &socket->io_handle);
1946
1947 nw_socket->on_connection_result_fn = on_connection_result;
1948 nw_socket->connect_result_user_data = user_data;
1949
1950 nw_socket->timeout_args = aws_mem_calloc(socket->allocator, 1, sizeof(struct nw_socket_timeout_args));
1951
1952 nw_socket->timeout_args->nw_socket = nw_socket;
1953 nw_socket->timeout_args->allocator = socket->allocator;
1954
1955 aws_task_init(
1956 &nw_socket->timeout_args->task,
1957 s_handle_socket_timeout,
1958 nw_socket->timeout_args,
1959 "NWSocketConnectionTimeoutTask");
1960
1961 /* schedule a task to run at the connect timeout interval, if this task runs before the connect
1962 * happens, we consider that a timeout. */
1963
1964 uint64_t timeout = 0;
1965 aws_event_loop_current_clock_time(event_loop, &timeout);
1966 AWS_LOGF_DEBUG(
1967 AWS_LS_IO_SOCKET,
1968 "id=%p handle=%p: start connection at %llu.",
1969 (void *)socket,
1970 socket->io_handle.data.handle,
1971 (unsigned long long)timeout);
1972 timeout +=
1973 aws_timestamp_convert(socket->options.connect_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
1974 AWS_LOGF_TRACE(
1975 AWS_LS_IO_SOCKET,
1976 "id=%p handle=%p: scheduling timeout task for %llu.",
1977 (void *)socket,
1978 socket->io_handle.data.handle,
1979 (unsigned long long)timeout);
1980 nw_socket->timeout_args->task.timestamp = timeout;
1981 // Acquire a nw_socket for the timeout task
1982 s_socket_acquire_internal_ref(nw_socket);
1983
1984 // The timeout task must schedule before we start the system connection. We will release the timeout args when
1985 // we finished a connection. If we start the system connection first, then it is possible that the connection
1986 // finished before timeout task scheduled, and the timeout args is already released by the time we schedule it.
1987 aws_event_loop_schedule_task_future(event_loop, &nw_socket->timeout_args->task, timeout);
1988
1989 /* set a handler for socket state changes. This is where we find out if the connection timed out, was
1990 * successful, was disconnected etc .... */
1991 nw_connection_set_state_changed_handler(
1992 socket->io_handle.data.handle, ^(nw_connection_state_t state, nw_error_t error) {
1993 s_handle_connection_state_changed_fn(nw_socket, nw_socket->os_handle.nw_connection, state, error);
1994 });
1995
1996 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_CONNECTING);
1997
1998 socket->connect_accept_user_data = user_data;
1999 socket->connection_result_fn = on_connection_result;
2000
2001 // released when the connection state changed to nw_connection_state_cancelled
2002 s_socket_acquire_internal_ref(nw_socket);
2003 nw_connection_start(socket->io_handle.data.handle);
2004 s_unlock_socket_synced_data(nw_socket);
2005
2006 return AWS_OP_SUCCESS;
2007
2008 error:
2009 s_release_event_loop(nw_socket);
2010 return AWS_OP_ERR;
2011 }
2012
2013 static int s_socket_bind_fn(struct aws_socket *socket, struct aws_socket_bind_options *socket_bind_options) {
2014 struct nw_socket *nw_socket = socket->impl;
2015
2016 const struct aws_socket_endpoint *local_endpoint = socket_bind_options->local_endpoint;
2017
2018 s_lock_socket_synced_data(nw_socket);
2019 if (nw_socket->synced_data.state != AWS_NW_SOCKET_STATE_INIT) {
2020 AWS_LOGF_ERROR(AWS_LS_IO_SOCKET, "id=%p: invalid state for bind operation.", (void *)socket);
2021 s_unlock_socket_synced_data(nw_socket);
2022 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
2023 }
2024
2025 socket->local_endpoint = *local_endpoint;
2026 AWS_LOGF_TRACE(
2027 AWS_LS_IO_SOCKET,
2028 "id=%p: binding to %s:%d.",
2029 (void *)socket,
2030 local_endpoint->address,
2031 (int)local_endpoint->port);
2032
2033 if (nw_socket->nw_parameters == NULL) {
2034
2035 /* We take what we need for TLS negotiation from the tls_connection_options */
2036 if (s_setup_tls_options_from_tls_connection_options(nw_socket, socket_bind_options->tls_connection_options)) {
2037 return AWS_OP_ERR;
2038 }
2039
2040 if (nw_socket->tls_ctx != NULL) {
2041 /*
2042 * Apple Network's TLS negotiation verify block requires access to an event loop. We temporarily
2043 * assign it to the nw_socket for use during the setup of its parameters and then immediately NULL
2044 * it afterwards.
2045 */
2046 nw_socket->event_loop = socket_bind_options->event_loop;
2047 }
2048
2049 s_setup_socket_params(nw_socket, &socket->options);
2050 /* Because a refcount wasn't acquired, we NULL the event_loop right after its use in creating socket params.
2051 */
2052 nw_socket->event_loop = NULL;
2053 }
2054
2055 struct socket_address address;
2056 AWS_ZERO_STRUCT(address);
2057 int pton_err = 1;
2058 switch (socket->options.domain) {
2059 case AWS_SOCKET_IPV4: {
2060 pton_err = inet_pton(AF_INET, local_endpoint->address, &address.sock_addr_types.addr_in.sin_addr);
2061 address.sock_addr_types.addr_in.sin_port = htons((uint16_t)local_endpoint->port);
2062 address.sock_addr_types.addr_in.sin_family = AF_INET;
2063 address.sock_addr_types.addr_in.sin_len = sizeof(struct sockaddr_in);
2064 break;
2065 }
2066 case AWS_SOCKET_IPV6: {
2067 pton_err = inet_pton(AF_INET6, local_endpoint->address, &address.sock_addr_types.addr_in6.sin6_addr);
2068 address.sock_addr_types.addr_in6.sin6_port = htons((uint16_t)local_endpoint->port);
2069 address.sock_addr_types.addr_in6.sin6_family = AF_INET6;
2070 address.sock_addr_types.addr_in6.sin6_len = sizeof(struct sockaddr_in6);
2071 break;
2072 }
2073 case AWS_SOCKET_LOCAL: {
2074 address.sock_addr_types.un_addr.sun_family = AF_UNIX;
2075 address.sock_addr_types.un_addr.sun_len = sizeof(struct sockaddr_un);
2076
2077 strncpy(address.sock_addr_types.un_addr.sun_path, local_endpoint->address, AWS_ADDRESS_MAX_LEN);
2078 break;
2079 }
2080 default: {
2081 s_unlock_socket_synced_data(nw_socket);
2082 return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
2083 }
2084 }
2085
2086 if (pton_err != 1) {
2087 AWS_LOGF_ERROR(
2088 AWS_LS_IO_SOCKET,
2089 "id=%p: failed to parse address %s:%d.",
2090 (void *)socket,
2091 local_endpoint->address,
2092 (int)local_endpoint->port);
2093 s_unlock_socket_synced_data(nw_socket);
2094 return aws_raise_error(s_convert_pton_error(pton_err));
2095 }
2096
2097 nw_endpoint_t endpoint = nw_endpoint_create_address(&address.sock_addr_types.addr_base);
2098
2099 if (!endpoint) {
2100 s_unlock_socket_synced_data(nw_socket);
2101 return aws_raise_error(AWS_IO_SOCKET_INVALID_ADDRESS);
2102 }
2103
2104 nw_parameters_set_local_endpoint(nw_socket->nw_parameters, endpoint);
2105 nw_release(endpoint);
2106
2107 // Apple network framework requires connection besides bind.
2108 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_BOUND);
2109 s_unlock_socket_synced_data(nw_socket);
2110
2111 AWS_LOGF_DEBUG(
2112 AWS_LS_IO_SOCKET,
2113 "id=%p fd=%d: successfully bound to %s:%u",
2114 (void *)socket,
2115 socket->io_handle.data.fd,
2116 socket->local_endpoint.address,
2117 socket->local_endpoint.port);
2118
2119 return AWS_OP_SUCCESS;
2120 }
2121
2122 static void s_listener_set_dispatch_queue(struct aws_io_handle *handle, void *queue) {
2123 nw_listener_set_queue(handle->data.handle, queue);
2124 }
2125
2126 static int s_socket_listen_fn(struct aws_socket *socket, int backlog_size) {
2127 (void)backlog_size;
2128
2129 struct nw_socket *nw_socket = socket->impl;
2130
2131 s_lock_socket_synced_data(nw_socket);
2132 if (nw_socket->synced_data.state != AWS_NW_SOCKET_STATE_BOUND) {
2133 AWS_LOGF_ERROR(
2134 AWS_LS_IO_SOCKET, "id=%p: invalid state for listen operation. You must call bind first.", (void *)socket);
2135 aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
2136 goto done;
2137 }
2138
2139 if (nw_socket->nw_parameters == NULL) {
2140 AWS_LOGF_ERROR(
2141 AWS_LS_IO_SOCKET,
2142 "id=%p: socket nw_parameters needs to be set before creating a listener from socket.",
2143 (void *)socket);
2144 aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
2145 goto done;
2146 }
2147
2148 socket->io_handle.data.handle = nw_listener_create(nw_socket->nw_parameters);
2149 if (!socket->io_handle.data.handle) {
2150 AWS_LOGF_ERROR(
2151 AWS_LS_IO_SOCKET,
2152 "id=%p: listener creation failed, please verify the socket options are setup properly.",
2153 (void *)socket);
2154 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2155 goto done;
2156 }
2157
2158 socket->io_handle.set_queue = s_listener_set_dispatch_queue;
2159 nw_socket->os_handle.nw_listener = socket->io_handle.data.handle;
2160 nw_socket->mode = NWSM_LISTENER;
2161
2162 AWS_LOGF_TRACE(
2163 AWS_LS_IO_SOCKET,
2164 "id=%p handle=%p: nw_socket successfully listening",
2165 (void *)socket,
2166 socket->io_handle.data.handle);
2167
2168 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_LISTENING);
2169 s_unlock_socket_synced_data(nw_socket);
2170 return AWS_OP_SUCCESS;
2171
2172 done:
2173 s_unlock_socket_synced_data(nw_socket);
2174 return AWS_OP_ERR;
2175 }
2176
2177 struct listener_state_changed_args {
2178 struct aws_task task;
2179 struct aws_allocator *allocator;
2180 struct nw_socket *nw_socket;
2181 nw_listener_state_t state;
2182 int error;
2183 };
2184
2185 static void s_process_listener_state_changed_task(struct aws_task *task, void *args, enum aws_task_status status) {
2186 (void)status;
2187 (void)task;
2188
2189 struct listener_state_changed_args *listener_state_changed_args = args;
2190
2191 struct nw_socket *nw_socket = listener_state_changed_args->nw_socket;
2192 nw_listener_t nw_listener = nw_socket->os_handle.nw_listener;
2193 nw_listener_state_t state = listener_state_changed_args->state;
2194 int crt_error_code = listener_state_changed_args->error;
2195
2196 AWS_LOGF_TRACE(
2197 AWS_LS_IO_SOCKET,
2198 "nw_socket=%p handle=%p: start to process listener state change task.",
2199 (void *)nw_socket,
2200 (void *)nw_listener);
2201
2202 /* Ideally we should not have a task with AWS_TASK_STATUS_CANCELED here, as the event loop should never be
2203 * destroyed before the nw_socket get destroyed. If we manually cancel the task, we should make sure we
2204 * carefully handled the state change eventually, as the socket relies on this task to release and cleanup.
2205 */
2206 if (status != AWS_TASK_STATUS_CANCELED) {
2207
2208 AWS_LOGF_DEBUG(
2209 AWS_LS_IO_SOCKET,
2210 "nw_socket=%p handle=%p: listener state changed to %d ",
2211 (void *)nw_socket,
2212 (void *)nw_listener,
2213 state);
2214
2215 switch (state) {
2216 case nw_listener_state_failed: {
2217 AWS_LOGF_DEBUG(
2218 AWS_LS_IO_SOCKET,
2219 "nw_socket=%p handle=%p: listener failed with error %d",
2220 (void *)nw_socket,
2221 (void *)nw_listener,
2222 crt_error_code);
2223
2224 s_lock_base_socket(nw_socket);
2225 struct aws_socket *aws_socket = nw_socket->base_socket_synced_data.base_socket;
2226 s_lock_socket_synced_data(nw_socket);
2227 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_ERROR);
2228 s_unlock_socket_synced_data(nw_socket);
2229 if (nw_socket->on_accept_started_fn) {
2230 nw_socket->on_accept_started_fn(
2231 aws_socket, crt_error_code, nw_socket->listen_accept_started_user_data);
2232 }
2233 s_unlock_base_socket(nw_socket);
2234 break;
2235 }
2236 case nw_listener_state_ready: {
2237 s_lock_base_socket(nw_socket);
2238 struct aws_socket *aws_socket = nw_socket->base_socket_synced_data.base_socket;
2239 if (aws_socket) {
2240 AWS_FATAL_ASSERT(nw_socket->mode == NWSM_LISTENER);
2241 aws_socket->local_endpoint.port = nw_listener_get_port(nw_socket->os_handle.nw_listener);
2242 if (nw_socket->on_accept_started_fn) {
2243 nw_socket->on_accept_started_fn(
2244 aws_socket, AWS_OP_SUCCESS, nw_socket->listen_accept_started_user_data);
2245 }
2246 AWS_LOGF_DEBUG(
2247 AWS_LS_IO_SOCKET,
2248 "nw_socket=%p handle=%p: listener on port %d ready ",
2249 (void *)nw_socket,
2250 (void *)nw_listener,
2251 aws_socket->local_endpoint.port);
2252 }
2253
2254 s_unlock_base_socket(nw_socket);
2255 break;
2256 }
2257 case nw_listener_state_cancelled: {
2258 AWS_LOGF_DEBUG(
2259 AWS_LS_IO_SOCKET,
2260 "nw_socket=%p handle=%p: listener cancelled.",
2261 (void *)nw_socket,
2262 (void *)nw_listener);
2263 s_lock_socket_synced_data(nw_socket);
2264 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_CLOSED);
2265 s_unlock_socket_synced_data(nw_socket);
2266 s_socket_release_internal_ref(nw_socket);
2267 break;
2268 }
2269 default:
2270 break;
2271 }
2272 }
2273
2274 // Release the internal ref for the task
2275 s_socket_release_internal_ref(nw_socket);
2276 aws_mem_release(listener_state_changed_args->allocator, listener_state_changed_args);
2277 }
2278
2279 static void s_handle_listener_state_changed_fn(
2280 struct nw_socket *nw_socket,
2281 nw_listener_state_t state,
2282 nw_error_t error) {
2283
2284 AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "nw_socket=%p: s_handle_listener_state_changed_fn start...", (void *)nw_socket);
2285
2286 int crt_error_code = s_convert_nw_error(error);
2287 if (crt_error_code) {
2288 AWS_LOGF_DEBUG(
2289 AWS_LS_IO_SOCKET,
2290 "nw_socket=%p handle=%p: s_handle_listener_state_changed_fn invoked error code %d : %s",
2291 (void *)nw_socket,
2292 (void *)nw_socket->os_handle.nw_connection,
2293 crt_error_code,
2294 aws_error_name(crt_error_code));
2295 }
2296
2297 if (s_validate_event_loop(nw_socket->event_loop)) {
2298 struct listener_state_changed_args *args =
2299 aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct listener_state_changed_args));
2300
2301 args->nw_socket = nw_socket;
2302 args->allocator = nw_socket->allocator;
2303 args->error = crt_error_code;
2304 args->state = state;
2305
2306 s_socket_acquire_internal_ref(nw_socket);
2307 aws_task_init(&args->task, s_process_listener_state_changed_task, args, "ListenerStateChangedTask");
2308 aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
2309 } else {
2310 AWS_FATAL_ASSERT(false && "The nw_socket should be always attached to a valid event loop.");
2311 }
2312 }
2313
2314 static int s_socket_start_accept_fn(
2315 struct aws_socket *socket,
2316 struct aws_event_loop *accept_loop,
2317 struct aws_socket_listener_options options) {
2318 AWS_FATAL_ASSERT(options.on_accept_result);
2319 AWS_FATAL_ASSERT(accept_loop);
2320
2321 struct nw_socket *nw_socket = socket->impl;
2322 s_lock_socket_synced_data(nw_socket);
2323 if (nw_socket->synced_data.state != AWS_NW_SOCKET_STATE_LISTENING) {
2324 AWS_LOGF_ERROR(
2325 AWS_LS_IO_SOCKET,
2326 "id=%p handle=%p: invalid state for start_accept operation. You must call listen first.",
2327 (void *)socket,
2328 socket->io_handle.data.handle);
2329 s_unlock_socket_synced_data(nw_socket);
2330 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
2331 }
2332
2333 if (socket->event_loop) {
2334 AWS_LOGF_ERROR(
2335 AWS_LS_IO_SOCKET,
2336 "id=%p handle=%p: is already assigned to event-loop %p.",
2337 (void *)socket,
2338 socket->io_handle.data.handle,
2339 (void *)socket->event_loop);
2340 s_unlock_socket_synced_data(nw_socket);
2341 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
2342 }
2343
2344 if (s_set_event_loop(socket, accept_loop)) {
2345 AWS_LOGF_ERROR(
2346 AWS_LS_IO_SOCKET,
2347 "id=%p handle=%p: failed to set event loop %p, invalid event loop. It is most likely the event loop does "
2348 "not has a parent event loop group.",
2349 (void *)socket,
2350 socket->io_handle.data.handle,
2351 (void *)accept_loop);
2352 s_unlock_socket_synced_data(nw_socket);
2353 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
2354 }
2355
2356 aws_event_loop_connect_handle_to_io_completion_port(accept_loop, &socket->io_handle);
2357 socket->accept_result_fn = options.on_accept_result;
2358 socket->connect_accept_user_data = options.on_accept_result_user_data;
2359
2360 nw_socket->on_accept_started_fn = options.on_accept_start;
2361 nw_socket->listen_accept_started_user_data = options.on_accept_start_user_data;
2362
2363 nw_listener_set_state_changed_handler(
2364 socket->io_handle.data.handle, ^(nw_listener_state_t state, nw_error_t error) {
2365 s_handle_listener_state_changed_fn(nw_socket, state, error);
2366 });
2367
2368 nw_listener_set_new_connection_handler(socket->io_handle.data.handle, ^(nw_connection_t connection) {
2369 s_handle_on_listener_success(nw_socket, AWS_OP_SUCCESS, connection, socket->connect_accept_user_data);
2370 });
2371 // this ref should be released in nw_listener_set_state_changed_handler where get state ==
2372 // nw_listener_state_cancelled
2373 s_socket_acquire_internal_ref(nw_socket);
2374 nw_listener_start(socket->io_handle.data.handle);
2375 s_unlock_socket_synced_data(nw_socket);
2376 return AWS_OP_SUCCESS;
2377 }
2378
2379 static int s_socket_stop_accept_fn(struct aws_socket *socket) {
2380 struct nw_socket *nw_socket = socket->impl;
2381 s_lock_socket_synced_data(nw_socket);
2382 if (nw_socket->synced_data.state != AWS_NW_SOCKET_STATE_LISTENING) {
2383 AWS_LOGF_ERROR(
2384 AWS_LS_IO_SOCKET,
2385 "id=%p handle=%p: is not in a listening state, can't stop_accept.",
2386 (void *)socket,
2387 socket->io_handle.data.handle);
2388 s_unlock_socket_synced_data(nw_socket);
2389 return aws_raise_error(AWS_IO_SOCKET_ILLEGAL_OPERATION_FOR_STATE);
2390 }
2391
2392 AWS_LOGF_TRACE(
2393 AWS_LS_IO_SOCKET,
2394 "id=%p handle=%p: stopping accepting new connections",
2395 (void *)socket,
2396 socket->io_handle.data.handle);
2397
2398 nw_listener_cancel(socket->io_handle.data.handle);
2399
2400 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_STOPPED);
2401 s_unlock_socket_synced_data(nw_socket);
2402
2403 return AWS_OP_SUCCESS;
2404 }
2405
2406 // Close should always be run on event loop
2407 static int s_socket_close_fn(struct aws_socket *socket) {
2408
2409 struct nw_socket *nw_socket = socket->impl;
2410 s_lock_socket_synced_data(nw_socket);
2411
2412 AWS_LOGF_DEBUG(
2413 AWS_LS_IO_SOCKET,
2414 "id=%p handle=%p: socket is closing with current state %d",
2415 (void *)socket,
2416 socket->io_handle.data.handle,
2417 socket->state);
2418
2419 if (nw_socket->synced_data.state < AWS_NW_SOCKET_STATE_CLOSING) {
2420 // We would like to keep CONNECTED_READ so that we could continue processing any received data until the we
2421 // got the system callback indicates that the system connection has been closed in the receiving direction.
2422 s_set_socket_state(nw_socket, AWS_NW_SOCKET_STATE_CLOSING | AWS_NW_SOCKET_STATE_CONNECTED_READ);
2423 s_socket_release_write_ref(nw_socket);
2424 }
2425 s_unlock_socket_synced_data(nw_socket);
2426 return AWS_OP_SUCCESS;
2427 }
2428
2429 static int s_socket_shutdown_dir_fn(struct aws_socket *socket, enum aws_channel_direction dir) {
2430 (void)dir;
2431 AWS_ASSERT(false);
2432 AWS_LOGF_ERROR(
2433 AWS_LS_IO_SOCKET, "id=%p: shutdown by direction is not support for Apple network framework.", (void *)socket);
2434 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPERATION_FOR_TYPE);
2435 }
2436
2437 static int s_socket_set_options_fn(struct aws_socket *socket, const struct aws_socket_options *options) {
2438 if (socket->options.domain != options->domain || socket->options.type != options->type) {
2439 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
2440 }
2441
2442 AWS_LOGF_DEBUG(
2443 AWS_LS_IO_SOCKET,
2444 "id=%p handle=%p: setting socket options to: keep-alive %d, keep idle %d, keep-alive interval %d, "
2445 "keep-alive "
2446 "probe "
2447 "count %d.",
2448 (void *)socket,
2449 socket->io_handle.data.handle,
2450 (int)options->keepalive,
2451 (int)options->keep_alive_timeout_sec,
2452 (int)options->keep_alive_interval_sec,
2453 (int)options->keep_alive_max_failed_probes);
2454
2455 socket->options = *options;
2456
2457 struct nw_socket *nw_socket = socket->impl;
2458
2459 return s_setup_socket_params(nw_socket, options);
2460 }
2461
2462 static int s_socket_assign_to_event_loop_fn(struct aws_socket *socket, struct aws_event_loop *event_loop) {
2463 if (!socket->event_loop) {
2464 AWS_LOGF_DEBUG(
2465 AWS_LS_IO_SOCKET,
2466 "id=%p handle=%p: assigning to event loop %p",
2467 (void *)socket,
2468 socket->io_handle.data.handle,
2469 (void *)event_loop);
2470
2471 if (s_set_event_loop(socket, event_loop)) {
2472 AWS_LOGF_ERROR(
2473 AWS_LS_IO_SOCKET,
2474 "id=%p handle=%p: assigning event loop %p failed. Invalid event loop. It is likely the event loop "
2475 "does not has a parent event loop group.",
2476 (void *)socket,
2477 socket->io_handle.data.handle,
2478 (void *)event_loop);
2479 aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
2480 return AWS_IO_SOCKET_INVALID_OPTIONS;
2481 }
2482
2483 if (aws_event_loop_connect_handle_to_io_completion_port(event_loop, &socket->io_handle)) {
2484 AWS_LOGF_ERROR(
2485 AWS_LS_IO_SOCKET,
2486 "id=%p handle=%p: assigning event loop %p failed",
2487 (void *)socket,
2488 socket->io_handle.data.handle,
2489 (void *)event_loop);
2490 return AWS_OP_ERR;
2491 }
2492
2493 nw_connection_start(socket->io_handle.data.handle);
2494 return AWS_OP_SUCCESS;
2495 }
2496
2497 AWS_LOGF_DEBUG(
2498 AWS_LS_IO_SOCKET,
2499 "id=%p handle=%p: the socket is already assigned with an event loop %p",
2500 (void *)socket,
2501 socket->io_handle.data.handle,
2502 (void *)event_loop);
2503 return aws_raise_error(AWS_IO_EVENT_LOOP_ALREADY_ASSIGNED);
2504 }
2505
2506 static void s_handle_nw_connection_receive_completion_fn(
2507 dispatch_data_t data,
2508 nw_content_context_t context,
2509 bool is_complete,
2510 nw_error_t error,
2511 struct nw_socket *nw_socket) {
2512 s_lock_socket_synced_data(nw_socket);
2513 nw_socket->synced_data.read_scheduled = false;
2514 s_unlock_socket_synced_data(nw_socket);
2515
2516 bool complete = is_complete;
2517 int crt_error_code = s_convert_nw_error(error);
2518
2519 if (!crt_error_code) {
2520 /* For protocols such as TCP, `is_complete` will be marked when the entire stream has be closed in the
2521 * reading direction. For protocols such as UDP, this will be marked when the end of a datagram has
2522 * been reached. */
2523
2524 complete = is_complete && nw_content_context_get_is_final(context);
2525
2526 AWS_LOGF_TRACE(
2527 AWS_LS_IO_SOCKET,
2528 "nw_socket=%p handle=%p: queued read buffer of size %d",
2529 (void *)nw_socket,
2530 (void *)nw_socket->os_handle.nw_connection,
2531 data ? (int)dispatch_data_get_size(data) : 0);
2532 } else {
2533 AWS_LOGF_DEBUG(
2534 AWS_LS_IO_SOCKET,
2535 "nw_socket=%p handle=%p: s_handle_nw_connection_receive_completion_fn invoked error code %d : %s",
2536 (void *)nw_socket,
2537 (void *)nw_socket->os_handle.nw_connection,
2538 crt_error_code,
2539 aws_error_name(crt_error_code));
2540 }
2541
2542 // The callback should be fired before schedule next read, so that if the socket is closed, we could
2543 // prevent schedule next read earlier.
2544 s_handle_incoming_data(nw_socket, crt_error_code, data, complete);
2545
2546 // keep reading from the system socket
2547 s_schedule_next_read(nw_socket);
2548
2549 s_socket_release_internal_ref(nw_socket);
2550 }
2551
2552 /* s_schedule_next_read() will setup the nw_connection_receive_completion_t and start a read request to the system
2553 * socket. The handler will get invoked when the system socket has data to read.
2554 * The function is initially fired on the following conditions, and recursively call itself on handler invocation:
2555 * 1. on function call `aws_socket_read()`
2556 * 2. on function call `aws_socket_subscribe_to_readable_events`
2557 */
2558 static int s_schedule_next_read(struct nw_socket *nw_socket) {
2559 s_lock_socket_synced_data(nw_socket);
2560
2561 // Once a read operation is scheduled, we should not schedule another one until the current one is
2562 // completed.
2563 if (nw_socket->synced_data.read_scheduled) {
2564 AWS_LOGF_TRACE(
2565 AWS_LS_IO_SOCKET,
2566 "nw_socket=%p handle=%p: there is already read queued, do not queue further read",
2567 (void *)nw_socket,
2568 (void *)nw_socket->os_handle.nw_connection);
2569 s_unlock_socket_synced_data(nw_socket);
2570 return AWS_OP_SUCCESS;
2571 }
2572
2573 if (nw_socket->synced_data.state & AWS_NW_SOCKET_STATE_CLOSING ||
2574 !(nw_socket->synced_data.state & AWS_NW_SOCKET_STATE_CONNECTED_READ)) {
2575 AWS_LOGF_DEBUG(
2576 AWS_LS_IO_SOCKET,
2577 "nw_socket=%p handle=%p: cannot read to because socket is not connected",
2578 (void *)nw_socket,
2579 (void *)nw_socket->os_handle.nw_connection);
2580 s_unlock_socket_synced_data(nw_socket);
2581 return aws_raise_error(AWS_IO_SOCKET_NOT_CONNECTED);
2582 }
2583
2584 nw_socket->synced_data.read_scheduled = true;
2585
2586 // Acquire nw_socket as we called nw_connection_receive, and the ref will be released when the handler is
2587 // called.
2588 s_socket_acquire_internal_ref(nw_socket);
2589
2590 /* read and let me know when you've done it. */
2591 nw_connection_receive(
2592 nw_socket->os_handle.nw_connection,
2593 1,
2594 UINT32_MAX,
2595 ^(dispatch_data_t data, nw_content_context_t context, bool is_complete, nw_error_t error) {
2596 s_handle_nw_connection_receive_completion_fn(data, context, is_complete, error, nw_socket);
2597 });
2598
2599 s_unlock_socket_synced_data(nw_socket);
2600 return AWS_OP_SUCCESS;
2601 }
2602
2603 static int s_socket_subscribe_to_readable_events_fn(
2604 struct aws_socket *socket,
2605 aws_socket_on_readable_fn *on_readable,
2606 void *user_data) {
2607 struct nw_socket *nw_socket = socket->impl;
2608
2609 if (nw_socket->mode == NWSM_LISTENER) {
2610 AWS_LOGF_DEBUG(
2611 AWS_LS_IO_SOCKET,
2612 "nw_socket=%p handle=%p: Apple Network Framework does not support read/write on a listener. Please use "
2613 "the "
2614 "incoming socket to track the read/write operation.",
2615 (void *)nw_socket,
2616 (void *)nw_socket->os_handle.nw_listener);
2617 return aws_raise_error(AWS_IO_SOCKET_INVALID_OPERATION_FOR_TYPE);
2618 }
2619
2620 socket->readable_user_data = user_data;
2621 socket->readable_fn = on_readable;
2622
2623 nw_socket->on_readable = on_readable;
2624 nw_socket->on_readable_user_data = user_data;
2625
2626 AWS_LOGF_TRACE(
2627 AWS_LS_IO_SOCKET,
2628 "nw_socket=%p handle=%p: socket_subscribe_to_readable_events: start to schedule read request.",
2629 (void *)nw_socket,
2630 (void *)nw_socket->os_handle.nw_connection);
2631
2632 return s_schedule_next_read(nw_socket);
2633 }
2634
2635 // WARNING: This function should handle the locks carefully. aws_socket_read()&aws_socket_write() should always
2636 // called on event loop thread.
2637 static int s_socket_read_fn(struct aws_socket *socket, struct aws_byte_buf *read_buffer, size_t *amount_read) {
2638 struct nw_socket *nw_socket = socket->impl;
2639
2640 AWS_FATAL_ASSERT(amount_read);
2641
2642 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
2643 AWS_LOGF_ERROR(
2644 AWS_LS_IO_SOCKET,
2645 "id=%p handle=%p: cannot read from a different thread than event loop %p",
2646 (void *)socket,
2647 socket->io_handle.data.handle,
2648 (void *)socket->event_loop);
2649 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
2650 }
2651
2652 __block size_t max_to_read = read_buffer->capacity - read_buffer->len;
2653
2654 /* As the function is always called on event loop, we didn't lock protect the read_queue. */
2655 if (aws_linked_list_empty(&nw_socket->read_queue)) {
2656 AWS_LOGF_TRACE(
2657 AWS_LS_IO_SOCKET,
2658 "id=%p handle=%p: read queue is empty, scheduling another read",
2659 (void *)socket,
2660 socket->io_handle.data.handle);
2661 s_lock_socket_synced_data(nw_socket);
2662 if (!(nw_socket->synced_data.state & AWS_NW_SOCKET_STATE_CONNECTED_READ)) {
2663 AWS_LOGF_DEBUG(
2664 AWS_LS_IO_SOCKET,
2665 "id=%p handle=%p: socket is not connected to read.",
2666 (void *)socket,
2667 socket->io_handle.data.handle);
2668 s_unlock_socket_synced_data(nw_socket);
2669
2670 return aws_raise_error(AWS_IO_SOCKET_CLOSED);
2671 }
2672
2673 *amount_read = 0;
2674 s_unlock_socket_synced_data(nw_socket);
2675 s_schedule_next_read(nw_socket);
2676 return aws_raise_error(AWS_IO_READ_WOULD_BLOCK);
2677 }
2678
2679 /* loop over the read queue, take the data and copy it over, and do so til we're either out of data
2680 * and need to schedule another read, or we've read entirely into the requested buffer. */
2681 while (!aws_linked_list_empty(&nw_socket->read_queue) && max_to_read) {
2682 struct aws_linked_list_node *node = aws_linked_list_front(&nw_socket->read_queue);
2683 struct read_queue_node *read_node = AWS_CONTAINER_OF(node, struct read_queue_node, node);
2684
2685 bool buffer_processed = dispatch_data_apply(
2686 read_node->received_data,
2687 (dispatch_data_applier_t) ^ (dispatch_data_t region, size_t offset, const void *buffer, size_t size) {
2688 (void)region;
2689 (void)offset;
2690
2691 AWS_LOGF_TRACE(
2692 AWS_LS_IO_SOCKET,
2693 "id=%p handle=%p: Starting read dispatch data region offset: %lu, buffer %p, with size %lu.",
2694 (void *)socket,
2695 socket->io_handle.data.handle,
2696 offset,
2697 buffer,
2698 size);
2699
2700 if (read_node->resume_region && offset < read_node->resume_region) {
2701 AWS_LOGF_TRACE(
2702 AWS_LS_IO_SOCKET,
2703 "id=%p handle=%p: Skipped dispatch data region region : %lu, looking for region: %lu",
2704 (void *)socket,
2705 socket->io_handle.data.handle,
2706 offset,
2707 read_node->resume_region);
2708 return true;
2709 }
2710 size_t to_copy = aws_min_size(max_to_read, size - read_node->region_offset);
2711 aws_byte_buf_write(read_buffer, (const uint8_t *)buffer + read_node->region_offset, to_copy);
2712 max_to_read -= to_copy;
2713 *amount_read += to_copy;
2714 read_node->region_offset += to_copy;
2715 if (read_node->region_offset == size) {
2716 read_node->region_offset = 0;
2717 return true;
2718 }
2719 read_node->resume_region = offset;
2720 return false;
2721 });
2722
2723 if (buffer_processed) {
2724 aws_linked_list_remove(node);
2725 s_read_queue_node_destroy(read_node);
2726 }
2727
2728 AWS_LOGF_TRACE(
2729 AWS_LS_IO_SOCKET,
2730 "id=%p handle=%p: read of %d",
2731 (void *)socket,
2732 socket->io_handle.data.handle,
2733 (int)*amount_read);
2734 }
2735
2736 return AWS_OP_SUCCESS;
2737 }
2738
2739 static void s_handle_nw_connection_send_completion_fn(
2740 nw_error_t error,
2741 dispatch_data_t data,
2742 struct nw_socket *nw_socket,
2743 aws_socket_on_write_completed_fn *written_fn,
2744 void *user_data) {
2745
2746 int crt_error_code = s_convert_nw_error(error);
2747 if (crt_error_code) {
2748 nw_socket->last_error = crt_error_code;
2749 AWS_LOGF_ERROR(
2750 AWS_LS_IO_SOCKET,
2751 "nw_socket=%p handle=%p: error during write %d : %s",
2752 (void *)nw_socket,
2753 (void *)nw_socket->os_handle.nw_connection,
2754 crt_error_code,
2755 aws_error_name(crt_error_code));
2756 }
2757
2758 size_t written_size = dispatch_data_get_size(data);
2759 AWS_LOGF_TRACE(
2760 AWS_LS_IO_SOCKET,
2761 "nw_socket=%p handle=%p: send written size %d",
2762 (void *)nw_socket,
2763 (void *)nw_socket->os_handle.nw_connection,
2764 (int)written_size);
2765 s_handle_write_fn(nw_socket, crt_error_code, data ? written_size : 0, user_data, written_fn);
2766 s_socket_release_write_ref(nw_socket);
2767 s_socket_release_internal_ref(nw_socket);
2768 }
2769
2770 // WARNING: This function should be careful with locks. aws_socket_read()&aws_socket_write() should always called on
2771 // event loop thread.
2772 static int s_socket_write_fn(
2773 struct aws_socket *socket,
2774 const struct aws_byte_cursor *cursor,
2775 aws_socket_on_write_completed_fn *written_fn,
2776 void *user_data) {
2777 AWS_FATAL_ASSERT(written_fn);
2778 if (!aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
2779 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
2780 }
2781
2782 struct nw_socket *nw_socket = socket->impl;
2783 s_lock_socket_synced_data(nw_socket);
2784 if (!(nw_socket->synced_data.state & AWS_NW_SOCKET_STATE_CONNECTED_WRITE)) {
2785 AWS_LOGF_DEBUG(
2786 AWS_LS_IO_SOCKET,
2787 "id=%p handle=%p: cannot write to because it is not connected",
2788 (void *)socket,
2789 socket->io_handle.data.handle);
2790 s_unlock_socket_synced_data(nw_socket);
2791 return aws_raise_error(AWS_IO_SOCKET_NOT_CONNECTED);
2792 }
2793
2794 dispatch_data_t data = dispatch_data_create(cursor->ptr, cursor->len, NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
2795 if (!data) {
2796 AWS_LOGF_ERROR(
2797 AWS_LS_IO_SOCKET,
2798 "id=%p handle=%p: failed to process write data.",
2799 (void *)socket,
2800 socket->io_handle.data.handle);
2801 return AWS_OP_ERR;
2802 }
2803 s_socket_acquire_internal_ref(nw_socket);
2804 s_socket_acquire_write_ref(nw_socket);
2805
2806 nw_connection_send(
2807 socket->io_handle.data.handle, data, _nw_content_context_default_message, true, ^(nw_error_t error) {
2808 s_handle_nw_connection_send_completion_fn(error, data, nw_socket, written_fn, user_data);
2809 dispatch_release(data);
2810 });
2811
2812 s_unlock_socket_synced_data(nw_socket);
2813
2814 return AWS_OP_SUCCESS;
2815 }
2816
2817 static int s_socket_get_error_fn(struct aws_socket *socket) {
2818 struct nw_socket *nw_socket = socket->impl;
2819
2820 return nw_socket->last_error;
2821 }
2822
2823 static bool s_socket_is_open_fn(struct aws_socket *socket) {
2824 struct nw_socket *nw_socket = socket->impl;
2825 s_lock_socket_synced_data(nw_socket);
2826 bool is_open = nw_socket->synced_data.state < AWS_NW_SOCKET_STATE_CLOSING;
2827 s_unlock_socket_synced_data(nw_socket);
2828 return is_open;
2829 }
2830
2831 static int s_set_close_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data) {
2832 struct nw_socket *nw_socket = socket->impl;
2833 nw_socket->close_user_data = user_data;
2834 nw_socket->on_socket_close_complete_fn = fn;
2835 return 0;
2836 }
2837
2838 static int s_set_cleanup_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data) {
2839 struct nw_socket *nw_socket = socket->impl;
2840 nw_socket->cleanup_user_data = user_data;
2841 nw_socket->on_socket_cleanup_complete_fn = fn;
2842 return 0;
2843 }
2844
2845 static struct aws_byte_buf s_socket_get_protocol_fn(const struct aws_socket *socket) {
2846 struct nw_socket *nw_socket = socket->impl;
2847 return nw_socket->protocol_buf;
2848 }
2849
2850 static struct aws_string *s_socket_get_server_name_fn(const struct aws_socket *socket) {
2851 struct nw_socket *nw_socket = socket->impl;
2852 return nw_socket->host_name;
2853 }