-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathnw_socket.c
2242 lines (1899 loc) · 90.9 KB
/
nw_socket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/io/private/socket_impl.h>
#include <aws/io/socket.h>
#include <aws/common/clock.h>
#include <aws/common/mutex.h>
#include <aws/common/string.h>
#include <aws/common/uuid.h>
#include <aws/io/logging.h>
#include <aws/io/private/event_loop_impl.h>
#include <Network/Network.h>
#include <aws/io/private/tls_channel_handler_shared.h>
#include <arpa/inet.h>
#include <sys/socket.h>
static int s_determine_socket_error(int error) {
switch (error) {
case ECONNREFUSED:
return AWS_IO_SOCKET_CONNECTION_REFUSED;
case ETIMEDOUT:
return AWS_IO_SOCKET_TIMEOUT;
case EHOSTUNREACH:
case ENETUNREACH:
return AWS_IO_SOCKET_NO_ROUTE_TO_HOST;
case EADDRNOTAVAIL:
return AWS_IO_SOCKET_INVALID_ADDRESS;
case ENETDOWN:
return AWS_IO_SOCKET_NETWORK_DOWN;
case ECONNABORTED:
return AWS_IO_SOCKET_CONNECT_ABORTED;
case EADDRINUSE:
return AWS_IO_SOCKET_ADDRESS_IN_USE;
case ENOBUFS:
case ENOMEM:
return AWS_ERROR_OOM;
case EAGAIN:
return AWS_IO_READ_WOULD_BLOCK;
case EMFILE:
case ENFILE:
return AWS_ERROR_MAX_FDS_EXCEEDED;
case ENOENT:
case EINVAL:
return AWS_ERROR_FILE_INVALID_PATH;
case EAFNOSUPPORT:
return AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY;
case EACCES:
return AWS_ERROR_NO_PERMISSION;
default:
return AWS_IO_SOCKET_NOT_CONNECTED;
}
}
static inline int s_convert_pton_error(int pton_code) {
if (pton_code == 0) {
return AWS_IO_SOCKET_INVALID_ADDRESS;
}
return s_determine_socket_error(errno);
}
/*
* A socket is only in one of these states at a time, except for CONNECTED_READ | CONNECTED_WRITE.
*
* The state can only go increasing, except for the following cases
* 1. LISTENING and STOPPED: They can switch between each other.
* 2. CLOSING -> ERROR: It is a valid case where socket state tries to transfer from CLOSING to ERROR, but we never
* actually set it to ERROR if we are already in CLOSING state. This happened in the following scenario: After we
* called aws_socket_close(), the socket state is set to CLOSING. And if a read callback invoked at this time, it
* is possible that the socket reads an ERROR and tries to set the socket state to ERROR, which makes the socket
* state goes backwards. Though this is a valid case, we don't actually set it back to ERROR as we are shutting down the
* socket.
* 3. CONNECT_WRITE and CONNECT_READ: you are allow to flip the flags for these two state, while not going
* backwards to `CONNECTING` and `INIT` state.
*/
enum aws_nw_socket_state {
INVALID = 0x000,
INIT = 0x001,
CONNECTING = 0x002,
CONNECTED_READ = 0x004,
CONNECTED_WRITE = 0x008,
BOUND = 0x010,
LISTENING = 0x020,
STOPPED = 0x040, // Stop the io events, while we could restart it later
ERROR = 0x080,
CLOSING = 0X100, // Only set when aws_socket_close() is called.
CLOSED = 0x200,
};
enum aws_nw_socket_mode {
NWSM_CONNECTION,
NWSM_LISTENER,
};
struct nw_listener_connection_args {
struct aws_task task;
int error_code;
struct aws_allocator *allocator;
struct nw_socket *nw_socket;
nw_connection_t new_connection;
void *user_data;
};
struct nw_socket_timeout_args {
struct aws_task task;
struct aws_allocator *allocator;
struct nw_socket *nw_socket;
};
struct nw_socket_scheduled_task_args {
struct aws_task task;
int error_code;
struct aws_allocator *allocator;
struct nw_socket *nw_socket;
dispatch_data_t data;
bool is_complete;
};
struct nw_socket_written_args {
struct aws_task task;
int error_code;
struct aws_allocator *allocator;
struct nw_socket *nw_socket;
aws_socket_on_write_completed_fn *written_fn;
void *user_data;
size_t bytes_written;
};
struct nw_socket_cancel_task_args {
struct aws_allocator *allocator;
struct nw_socket *nw_socket;
struct aws_task task;
};
struct nw_socket {
struct aws_allocator *allocator;
/* The `nw_socket_ref_count` that keeps the nw_socket alive. The `nw_socket_ref_count` initalized on
* aws_socket_init() and decreased on aws_socket_clean_up() called. The `internal_ref_count` will also keep a
* reference of the `nw_socket_ref_count` so that the nw_socket would alive until all system callbacks and tasks are
* handled. On `nw_socket_ref_count` drops to 0, it invokes s_socket_impl_destroy, which cleanup the nw_socket
* memory and invoke on_socket_cleanup_complete_fn.
*/
struct aws_ref_count nw_socket_ref_count;
/* The `internal_ref_count` is used to track any in-flight socket operations. It would be init on socket init, and
* acquired on aws_socket_connect()/aws_socket_listen() called. The reference will be decreased on
* nw_connection/listener_state_changed_handler is invoked with a "nw_connection/listener_state_cancelled" state.
* Besides this, each network framework system call or each scheduled task in event loop would also acquire an
* internal reference, and release when the callback invoked or the task executed.
*/
struct aws_ref_count internal_ref_count;
/* The `write_ref_count` is used to track any in-flight write operations. It would be init on aws_socket_init() and
* dropped on aws_socket_close() call. Each aws_socket_write() function call will acquire a ref-count, and released
* the ref-count on nw_connection_send handler is invoked.
* When the reference is dropped to 0, it invoked the destroy function `s_nw_socket_canceled()`, and start to cancel
* and close the Apple nw_connection/nw_listener.
*/
struct aws_ref_count write_ref_count;
int last_error;
/* Apple's native structs for connection and listener. */
union {
nw_connection_t nw_connection;
nw_listener_t nw_listener;
} os_handle;
nw_parameters_t socket_options_to_params;
/* The socket would be either setup as nw_connection or nw_listener. */
enum aws_nw_socket_mode mode;
/* The linked list of `read_queue_node`. The read queue to store read data from io events. aws_socket_read()
* function would read data from the queue.
* WARNING: The read_queue is not lock protected so far, as we always access it on event loop thread. */
struct aws_linked_list read_queue;
/*
* nw_socket is ref counted. It is possible that the aws_socket object is released while nw_socket is still alive
* and processing events. We keep the callbacks and parameters on nw_socket to avoid bad access after the aws_socket
* is released.
*/
aws_socket_on_readable_fn *on_readable;
void *on_readable_user_data;
aws_socket_on_connection_result_fn *on_connection_result_fn;
void *connect_result_user_data;
aws_socket_on_accept_started_fn *on_accept_started_fn;
void *listen_accept_started_user_data;
aws_socket_on_shutdown_complete_fn *on_socket_close_complete_fn;
void *close_user_data;
aws_socket_on_shutdown_complete_fn *on_socket_cleanup_complete_fn;
void *cleanup_user_data;
/* nw_socket had to be assigned to an event loop to process events. The nw_socket will acquire a reference of the
* event_loop's base event group to kept the event loop alive.
*
* For client socket (nw_connection): setup on aws_socket_connect()
* For listener (nw_listener) : setup on aws_socket_start_accept()
* For incoming socket / server socket (nw_connection accepted on a listener): setup by calling
* aws_socket_assign_event_loop()
*/
struct aws_event_loop *event_loop;
/* Indicate the connection result is updated. This argument is used to cancel the timeout task. The argument should
* be only set on socket event loop. The value will be set to true if:
* 1. nw_connection returned with state=`nw_connection_state_ready`, indicating the connection succeed
* 2. nw_connection returned with state=`nw_connection_state_failed`, indicating the connection failed
* 3. directly set to true for the incoming socket, as the incoming socket is already connected
*/
bool connection_setup;
/* Timeout task that is created on aws_socket_connect(). The task will be flagged to be canceled if the connection
* succeed or failed. */
struct nw_socket_timeout_args *timeout_args;
/* synced_data and the lock to protect the synced data. */
struct {
/* Used to avoid scheduling a duplicate read call. We would like to wait for the read call complete back before
* we schedule another one. */
bool read_scheduled;
/* The aws_nw_socket_state. aws_socket also has a field `state` which should be represent the same parameter,
* however, as it is possible that the aws_socket object is released while nw_socket is still alive, we will use
* nw_socket->state instead of socket->state to verify the socket_state.
*/
enum aws_nw_socket_state state;
struct aws_mutex lock;
} synced_data;
/*
* The synced data to protect base_socket access. As aws_socket is not ref-counted. It is possible that the user
* called aws_socket_cleanup() to release the aws_socket(base_socket), while the nw_socket is still alive and the
* underlying system calls are still processing the data. Therefore, here nw_socket kept a point to base_socket to
* avoid bad access after aws_socket is cleaned up. The lock is acquired before we do any callback that might access
* the base_socket.
* We put aws_socket in a different base_socket_synced_data struct to avoid the lock contention between other
* cross-thread data, especially when we do a socket operation in a callback when the socket lock is acquired.
*
* As all the callbacks will hold the lock to make sure the base_socket is alive, we should avoid to use the lock in
* user API calls. So far we used it only in aws_socket_cleanup. And handle it in this way to avoid deadlock: if we
* are on the assigned event loop, we assume we are fired on the event loop thread, and we don't need to acquire the
* lock, otherwise, we acquire the lock.
*/
struct {
struct aws_mutex lock;
struct aws_socket *base_socket;
} base_socket_synced_data;
};
static size_t KB_16 = 16 * 1024;
static void *s_socket_acquire_internal_ref(struct nw_socket *nw_socket) {
return aws_ref_count_acquire(&nw_socket->internal_ref_count);
}
static size_t s_socket_release_internal_ref(struct nw_socket *nw_socket) {
return aws_ref_count_release(&nw_socket->internal_ref_count);
}
static void *s_socket_acquire_write_ref(struct nw_socket *nw_socket) {
return aws_ref_count_acquire(&nw_socket->write_ref_count);
}
static size_t s_socket_release_write_ref(struct nw_socket *nw_socket) {
return aws_ref_count_release(&nw_socket->write_ref_count);
}
static int s_lock_base_socket(struct nw_socket *nw_socket) {
return aws_mutex_lock(&nw_socket->base_socket_synced_data.lock);
}
static int s_unlock_base_socket(struct nw_socket *nw_socket) {
return aws_mutex_unlock(&nw_socket->base_socket_synced_data.lock);
}
static int s_lock_socket_synced_data(struct nw_socket *nw_socket) {
return aws_mutex_lock(&nw_socket->synced_data.lock);
}
static int s_unlock_socket_synced_data(struct nw_socket *nw_socket) {
return aws_mutex_unlock(&nw_socket->synced_data.lock);
}
static bool s_validate_event_loop(struct aws_event_loop *event_loop) {
return event_loop && event_loop->vtable && event_loop->impl_data;
}
static void s_set_event_loop(struct aws_socket *aws_socket, struct aws_event_loop *event_loop) {
aws_socket->event_loop = event_loop;
struct nw_socket *nw_socket = aws_socket->impl;
// Never re-assign an event loop
AWS_FATAL_ASSERT(nw_socket->event_loop == NULL);
nw_socket->event_loop = event_loop;
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p: s_set_event_loop: socket acquire event loop group.", (void *)nw_socket);
aws_event_loop_group_acquire(get_base_event_loop_group(event_loop));
}
static void s_release_event_loop(struct nw_socket *nw_socket) {
if (nw_socket->event_loop == NULL) {
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p: s_release_event_loop: socket has not event loop.", (void *)nw_socket);
return;
}
aws_event_loop_group_release(get_base_event_loop_group(nw_socket->event_loop));
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET, "id=%p: s_release_event_loop: socket release event loop group.", (void *)nw_socket);
nw_socket->event_loop = NULL;
}
static void s_set_socket_state(struct nw_socket *nw_socket, struct aws_socket *socket, enum aws_nw_socket_state state) {
AWS_LOGF_TRACE(
AWS_LS_IO_SOCKET,
"id=%p: s_set_socket_state: socket state set from %d to %d.",
(void *)nw_socket,
nw_socket->synced_data.state,
state);
enum aws_nw_socket_state result_state = nw_socket->synced_data.state;
// clip the read/write bits
enum aws_nw_socket_state read_write_bits = state & (CONNECTED_WRITE | CONNECTED_READ);
result_state = result_state & ~CONNECTED_WRITE & ~CONNECTED_READ;
// If the caller would like simply flip the read/write bits, set the state to invalid, as we dont have further
// information there.
if (~CONNECTED_WRITE == (int)state || ~CONNECTED_READ == (int)state) {
state = INVALID;
}
// The state can only go increasing, except for the following cases
// 1. LISTENING and STOPPED: They can switch between each other.
// 2. CLOSING -> ERROR: It is a valid case where socket state tries to transfer from CLOSING to ERROR. This
// happened in the following scenario: After we called aws_socket_close(), the socket state is set to CLOSING. And
// if a read callback invoked at this time, it is possible that the socket reads an ERROR and tries to set the
// socket state to ERROR, which makes the socket state goes backwards. Though this is a valid case, we don't
// actually set it back to ERROR as we are shutting down the socket.
// 3. CONNECT_WRITE and CONNECT_READ: you are allow to flip the flags for these two state, while not going
// backwards to `CONNECTING` and `INIT` state.
if (result_state < state || (state == LISTENING && result_state == STOPPED)) {
result_state = state;
}
// Set CONNECTED_WRITE and CONNECTED_READ
result_state = result_state | read_write_bits;
nw_socket->synced_data.state = result_state;
if (socket) {
socket->state = result_state;
}
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET,
"id=%p: s_set_socket_state: socket state set to %d.",
(void *)nw_socket,
nw_socket->synced_data.state);
}
static int s_setup_socket_params(struct nw_socket *nw_socket, const struct aws_socket_options *options) {
if (options->type == AWS_SOCKET_STREAM) {
/* if TCP, setup all the tcp options */
switch (options->domain) {
case AWS_SOCKET_IPV4:
case AWS_SOCKET_IPV6: {
// DEBUG WIP NW_PARAMETERS_DISABLE_PROTOCOL will need to be changed to use MTLS With SecItem
nw_socket->socket_options_to_params = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t nw_options) {
if (options->connect_timeout_ms) {
/* this value gets set in seconds. */
nw_tcp_options_set_connection_timeout(
nw_options, options->connect_timeout_ms / AWS_TIMESTAMP_MILLIS);
}
// Only change default keepalive values if keepalive is true and both interval and timeout
// are not zero.
if (options->keepalive && options->keep_alive_interval_sec != 0 &&
options->keep_alive_timeout_sec != 0) {
nw_tcp_options_set_enable_keepalive(nw_options, options->keepalive);
nw_tcp_options_set_keepalive_idle_time(nw_options, options->keep_alive_timeout_sec);
nw_tcp_options_set_keepalive_interval(nw_options, options->keep_alive_interval_sec);
}
if (options->keep_alive_max_failed_probes) {
nw_tcp_options_set_keepalive_count(nw_options, options->keep_alive_max_failed_probes);
}
if (g_aws_channel_max_fragment_size < KB_16) {
nw_tcp_options_set_maximum_segment_size(nw_options, g_aws_channel_max_fragment_size);
}
});
} break;
case AWS_SOCKET_LOCAL: {
nw_socket->socket_options_to_params = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION);
} break;
default:
AWS_LOGF_ERROR(
AWS_LS_IO_SOCKET,
"id=%p options=%p: AWS_SOCKET_VSOCK is not supported on nw_socket.",
(void *)nw_socket,
(void *)options);
return aws_raise_error(AWS_IO_SOCKET_UNSUPPORTED_ADDRESS_FAMILY);
}
} else if (options->type == AWS_SOCKET_DGRAM) {
nw_socket->socket_options_to_params =
nw_parameters_create_secure_udp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION);
}
if (!nw_socket->socket_options_to_params) {
AWS_LOGF_ERROR(
AWS_LS_IO_SOCKET,
"id=%p options=%p: failed to create nw_parameters_t for nw_socket.",
(void *)nw_socket,
(void *)options);
return aws_raise_error(AWS_IO_SOCKET_INVALID_OPTIONS);
}
nw_parameters_set_reuse_local_address(nw_socket->socket_options_to_params, true);
return AWS_OP_SUCCESS;
}
static void s_socket_cleanup_fn(struct aws_socket *socket);
static int s_socket_connect_fn(
struct aws_socket *socket,
const struct aws_socket_endpoint *remote_endpoint,
struct aws_event_loop *event_loop,
aws_socket_on_connection_result_fn *on_connection_result,
void *user_data);
static int s_socket_bind_fn(struct aws_socket *socket, const struct aws_socket_endpoint *local_endpoint);
static int s_socket_listen_fn(struct aws_socket *socket, int backlog_size);
static int s_socket_start_accept_fn(
struct aws_socket *socket,
struct aws_event_loop *accept_loop,
struct aws_socket_listener_options options);
static int s_socket_stop_accept_fn(struct aws_socket *socket);
static int s_socket_close_fn(struct aws_socket *socket);
static int s_socket_shutdown_dir_fn(struct aws_socket *socket, enum aws_channel_direction dir);
static int s_socket_set_options_fn(struct aws_socket *socket, const struct aws_socket_options *options);
static int s_socket_assign_to_event_loop_fn(struct aws_socket *socket, struct aws_event_loop *event_loop);
static int s_socket_subscribe_to_readable_events_fn(
struct aws_socket *socket,
aws_socket_on_readable_fn *on_readable,
void *user_data);
static int s_socket_read_fn(struct aws_socket *socket, struct aws_byte_buf *buffer, size_t *amount_read);
static int s_socket_write_fn(
struct aws_socket *socket,
const struct aws_byte_cursor *cursor,
aws_socket_on_write_completed_fn *written_fn,
void *user_data);
static int s_socket_get_error_fn(struct aws_socket *socket);
static bool s_socket_is_open_fn(struct aws_socket *socket);
static int s_set_close_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
static int s_set_cleanup_callback(struct aws_socket *socket, aws_socket_on_shutdown_complete_fn fn, void *user_data);
static struct aws_socket_vtable s_vtable = {
.socket_cleanup_fn = s_socket_cleanup_fn,
.socket_connect_fn = s_socket_connect_fn,
.socket_bind_fn = s_socket_bind_fn,
.socket_listen_fn = s_socket_listen_fn,
.socket_start_accept_fn = s_socket_start_accept_fn,
.socket_stop_accept_fn = s_socket_stop_accept_fn,
.socket_close_fn = s_socket_close_fn,
.socket_shutdown_dir_fn = s_socket_shutdown_dir_fn,
.socket_set_options_fn = s_socket_set_options_fn,
.socket_assign_to_event_loop_fn = s_socket_assign_to_event_loop_fn,
.socket_subscribe_to_readable_events_fn = s_socket_subscribe_to_readable_events_fn,
.socket_read_fn = s_socket_read_fn,
.socket_write_fn = s_socket_write_fn,
.socket_get_error_fn = s_socket_get_error_fn,
.socket_is_open_fn = s_socket_is_open_fn,
.socket_set_close_callback = s_set_close_callback,
.socket_set_cleanup_callback = s_set_cleanup_callback,
};
static int s_schedule_next_read(struct nw_socket *socket);
static void s_socket_cleanup_fn(struct aws_socket *socket) {
if (!socket->impl) {
/* protect from double clean */
return;
}
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p nw_socket=%p: is cleanup...", (void *)socket, (void *)socket->impl);
if (aws_socket_is_open(socket)) {
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET, "id=%p nw_socket=%p: is still open, closing...", (void *)socket, (void *)socket->impl);
aws_socket_close(socket);
}
struct nw_socket *nw_socket = socket->impl;
if (s_validate_event_loop(socket->event_loop) && !aws_event_loop_thread_is_callers_thread(socket->event_loop)) {
s_lock_base_socket(nw_socket);
nw_socket->base_socket_synced_data.base_socket = NULL;
s_unlock_base_socket(nw_socket);
} else {
// If we are already on event loop or event loop is unavailable, we should already acquire the lock for base
// socket access
nw_socket->base_socket_synced_data.base_socket = NULL;
}
aws_ref_count_release(&nw_socket->nw_socket_ref_count);
socket->impl = NULL;
AWS_ZERO_STRUCT(*socket);
}
struct read_queue_node {
struct aws_allocator *allocator;
dispatch_data_t received_data;
struct aws_linked_list_node node;
size_t region_offset;
// If we didn't finish reading the received_data, we need to keep track of the region offset that we would
// like to resume with
size_t resume_region;
};
static void s_read_queue_node_destroy(struct read_queue_node *node) {
/* releases reference count on dispatch_data_t that was increased during creation of read_queue_node */
dispatch_release(node->received_data);
aws_mem_release(node->allocator, node);
}
struct socket_close_complete_args {
struct aws_task task;
struct aws_allocator *allocator;
aws_socket_on_shutdown_complete_fn *shutdown_complete_fn;
void *user_data;
struct nw_socket *nw_socket;
};
static void s_close_complete_callback(struct aws_task *task, void *arg, enum aws_task_status status) {
(void)status;
(void)task;
struct socket_close_complete_args *task_arg = arg;
struct aws_allocator *allocator = task_arg->allocator;
if (task_arg->shutdown_complete_fn) {
task_arg->shutdown_complete_fn(task_arg->user_data);
}
aws_ref_count_release(&task_arg->nw_socket->nw_socket_ref_count);
aws_mem_release(allocator, task_arg);
}
static void s_socket_impl_destroy(void *sock_ptr) {
struct nw_socket *nw_socket = sock_ptr;
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p : start s_socket_impl_destroy", (void *)sock_ptr);
/* In case we have leftovers from the read queue, clean them up. */
while (!aws_linked_list_empty(&nw_socket->read_queue)) {
struct aws_linked_list_node *node = aws_linked_list_pop_front(&nw_socket->read_queue);
struct read_queue_node *read_queue_node = AWS_CONTAINER_OF(node, struct read_queue_node, node);
s_read_queue_node_destroy(read_queue_node);
}
/* Network Framework cleanup */
if (nw_socket->socket_options_to_params) {
nw_release(nw_socket->socket_options_to_params);
nw_socket->socket_options_to_params = NULL;
}
aws_socket_on_shutdown_complete_fn *on_cleanup_complete = nw_socket->on_socket_cleanup_complete_fn;
void *cleanup_user_data = nw_socket->cleanup_user_data;
aws_mutex_clean_up(&nw_socket->synced_data.lock);
aws_mutex_clean_up(&nw_socket->base_socket_synced_data.lock);
aws_mem_release(nw_socket->allocator, nw_socket);
nw_socket = NULL;
if (on_cleanup_complete) {
on_cleanup_complete(cleanup_user_data);
}
}
static void s_process_socket_cancel_task(struct aws_task *task, void *arg, enum aws_task_status status) {
(void)task;
(void)status;
struct nw_socket_cancel_task_args *args = arg;
struct nw_socket *nw_socket = args->nw_socket;
AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p: start to process socket cancel task.", (void *)nw_socket);
// The task should always run event when status == AWS_TASK_STATUS_CANCELLED. We rely on the task to clean up the
// system connection/listener. And release the socket memory.
if ((nw_socket->mode == NWSM_CONNECTION && nw_socket->os_handle.nw_connection != NULL) ||
(nw_socket->mode == NWSM_LISTENER && nw_socket->os_handle.nw_listener != NULL)) {
// The timeout_args only setup for connected client connections.
if (nw_socket->mode == NWSM_CONNECTION && nw_socket->timeout_args && !nw_socket->connection_setup) {
// if the connection setup is not set, the timeout task has not yet triggered, cancel it.
aws_event_loop_cancel_task(nw_socket->event_loop, &nw_socket->timeout_args->task);
}
if (nw_socket->mode == NWSM_LISTENER) {
nw_listener_cancel(nw_socket->os_handle.nw_listener);
nw_release(nw_socket->os_handle.nw_listener);
nw_socket->os_handle.nw_listener = NULL;
} else if (nw_socket->mode == NWSM_CONNECTION) {
nw_connection_cancel(nw_socket->os_handle.nw_connection);
nw_release(nw_socket->os_handle.nw_connection);
nw_socket->os_handle.nw_connection = NULL;
}
}
s_socket_release_internal_ref(nw_socket);
aws_mem_release(args->allocator, args);
}
// Cancel the socket and close the connection. The cancel should happened on the event loop.
static void s_handle_socket_canceled(void *socket_ptr) {
struct nw_socket *nw_socket = socket_ptr;
struct nw_socket_cancel_task_args *args =
aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct nw_socket_cancel_task_args));
args->allocator = nw_socket->allocator;
args->nw_socket = nw_socket;
/* The socket cancel should happened on the event loop if possible. The event loop will not set
* in the case where the socket is never connected/ listener is never started accept.
*/
if (s_validate_event_loop(nw_socket->event_loop)) {
aws_task_init(&args->task, s_process_socket_cancel_task, args, "SocketCanceledTask");
aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
} else {
s_process_socket_cancel_task(&args->task, args, AWS_TASK_STATUS_RUN_READY);
}
}
static void s_socket_internal_destroy(void *sock_ptr) {
struct nw_socket *nw_socket = sock_ptr;
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p : start s_socket_internal_destroy", (void *)sock_ptr);
if (s_validate_event_loop(nw_socket->event_loop)) {
struct socket_close_complete_args *args =
aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct socket_close_complete_args));
args->shutdown_complete_fn = nw_socket->on_socket_close_complete_fn;
args->user_data = nw_socket->close_user_data;
args->allocator = nw_socket->allocator;
args->nw_socket = nw_socket;
// At this point the internal ref count has been dropped to 0, and we are about to release the external ref
// count.
// However, we would still keep the external ref count alive until the s_close_complete_callback callback is
// invoked. Acquire another external ref count to keep the socket alive. It will be released in
// s_close_complete_callback.
aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
aws_task_init(&args->task, s_close_complete_callback, args, "SocketShutdownCompleteTask");
aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
} else {
// If we are not on the event loop
if (nw_socket->on_socket_close_complete_fn) {
nw_socket->on_socket_close_complete_fn(nw_socket->close_user_data);
}
}
s_release_event_loop(nw_socket);
aws_ref_count_release(&nw_socket->nw_socket_ref_count);
}
int aws_socket_init_apple_nw_socket(
struct aws_socket *socket,
struct aws_allocator *alloc,
const struct aws_socket_options *options) {
AWS_FATAL_ASSERT(options);
AWS_ZERO_STRUCT(*socket);
// Network Interface is not supported with Apple Network Framework yet
if (options->network_interface_name[0] != 0) {
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET,
"id=%p fd=%d: network_interface_name is not supported on this platform.",
(void *)socket,
socket->io_handle.data.fd);
return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
}
struct nw_socket *nw_socket = aws_mem_calloc(alloc, 1, sizeof(struct nw_socket));
nw_socket->allocator = alloc;
socket->allocator = alloc;
socket->options = *options;
socket->impl = nw_socket;
socket->vtable = &s_vtable;
if (s_setup_socket_params(nw_socket, options)) {
aws_mem_release(alloc, nw_socket);
return AWS_OP_ERR;
}
aws_mutex_init(&nw_socket->synced_data.lock);
aws_mutex_init(&nw_socket->base_socket_synced_data.lock);
nw_socket->base_socket_synced_data.base_socket = socket;
s_set_socket_state(nw_socket, socket, INIT);
aws_ref_count_init(&nw_socket->nw_socket_ref_count, nw_socket, s_socket_impl_destroy);
aws_ref_count_init(&nw_socket->internal_ref_count, nw_socket, s_socket_internal_destroy);
// The internal_ref_count should keep a reference of the nw_socket_ref_count. When the internal_ref_count
// drop to 0, it would release the nw_socket_ref_count.
aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
aws_ref_count_init(&nw_socket->write_ref_count, nw_socket, s_handle_socket_canceled);
aws_linked_list_init(&nw_socket->read_queue);
AWS_LOGF_DEBUG(AWS_LS_IO_SOCKET, "id=%p fd=%d: socket created.", (void *)nw_socket, socket->io_handle.data.fd);
return AWS_OP_SUCCESS;
}
static void s_client_set_dispatch_queue(struct aws_io_handle *handle, void *queue) {
nw_connection_set_queue(handle->data.handle, queue);
}
static void s_handle_socket_timeout(struct aws_task *task, void *args, aws_task_status status) {
(void)task;
(void)status;
struct nw_socket_timeout_args *timeout_args = args;
struct nw_socket *nw_socket = timeout_args->nw_socket;
AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "task_id=%p: timeout task triggered, evaluating timeouts.", (void *)task);
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (!nw_socket->connection_setup && socket) {
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: timed out, shutting down.",
(void *)socket,
(void *)nw_socket->os_handle.nw_connection);
int error_code = AWS_IO_SOCKET_TIMEOUT;
// Must set timeout_args to NULL to avoid double cancel. Clean up the timeout task
aws_mem_release(nw_socket->allocator, nw_socket->timeout_args);
nw_socket->timeout_args = NULL;
aws_socket_close(socket);
nw_socket->on_connection_result_fn(socket, error_code, nw_socket->connect_result_user_data);
} else {
// If the socket is already setup (either succeed or failed), we have already invoked the callback to notify the
// connection result. No need to invoke again. If the aws_socket is NULL (cleaned up by user), there is no
// meaning to invoke the callback anymore. Simply release the memory in these two cases.
aws_mem_release(nw_socket->allocator, nw_socket->timeout_args);
nw_socket->timeout_args = NULL;
}
s_unlock_base_socket(nw_socket);
s_socket_release_internal_ref(nw_socket);
// No need to release task, as task lives on timeout_args on nw_socket.
}
static void s_process_incoming_data_task(struct aws_task *task, void *arg, enum aws_task_status status) {
(void)task;
(void)status;
struct nw_socket_scheduled_task_args *readable_args = arg;
struct nw_socket *nw_socket = readable_args->nw_socket;
AWS_LOGF_TRACE(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: start to process read data.",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection);
// If data is valid, push it in read_queue. The read_queue should be only accessed in event loop, as the
// task is scheduled in event loop, it is fine to directly access it.
if (readable_args->data) {
// We directly store the dispatch_data returned from kernel. This could potentially be performance concern.
// Another option is to read the data out into heap buffer and store the heap buffer in read_queue. However,
// this would introduce extra memory copy. We would like to keep the dispatch_data_t in read_queue for now.
struct read_queue_node *node = aws_mem_calloc(nw_socket->allocator, 1, sizeof(struct read_queue_node));
node->allocator = nw_socket->allocator;
node->received_data = readable_args->data;
aws_linked_list_push_back(&nw_socket->read_queue, &node->node);
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: read data is not empty, push data to read_queue",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection);
}
if (status != AWS_TASK_STATUS_CANCELED) {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (readable_args->is_complete) {
s_lock_socket_synced_data(nw_socket);
s_set_socket_state(nw_socket, socket, ~CONNECTED_READ);
s_unlock_socket_synced_data(nw_socket);
AWS_LOGF_TRACE(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: socket is complete, flip read flag",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection);
}
if (nw_socket->on_readable) {
nw_socket->on_readable(socket, readable_args->error_code, nw_socket->on_readable_user_data);
}
s_unlock_base_socket(nw_socket);
}
s_socket_release_internal_ref(nw_socket);
aws_mem_release(readable_args->allocator, readable_args);
}
static void s_handle_incoming_data(
struct nw_socket *nw_socket,
int error_code,
dispatch_data_t data,
bool is_complete) {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (socket && s_validate_event_loop(nw_socket->event_loop)) {
struct nw_socket_scheduled_task_args *args =
aws_mem_calloc(socket->allocator, 1, sizeof(struct nw_socket_scheduled_task_args));
args->is_complete = is_complete;
args->nw_socket = nw_socket;
args->allocator = nw_socket->allocator;
args->error_code = error_code;
if (data) {
dispatch_retain(data);
args->data = data;
}
s_socket_acquire_internal_ref(nw_socket);
aws_task_init(&args->task, s_process_incoming_data_task, args, "readableTask");
aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
}
s_unlock_base_socket(nw_socket);
}
static void s_process_connection_result_task(struct aws_task *task, void *arg, enum aws_task_status status) {
(void)status;
(void)task;
struct nw_socket_scheduled_task_args *task_args = arg;
struct nw_socket *nw_socket = task_args->nw_socket;
AWS_LOGF_TRACE(AWS_LS_IO_SOCKET, "id=%p: start to process connection result task.", (void *)nw_socket);
if (status != AWS_TASK_STATUS_CANCELED) {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (socket && nw_socket->on_connection_result_fn)
nw_socket->on_connection_result_fn(socket, task_args->error_code, nw_socket->connect_result_user_data);
s_unlock_base_socket(nw_socket);
}
s_socket_release_internal_ref(nw_socket);
aws_mem_release(task_args->allocator, task_args);
}
static void s_handle_on_connection_result(struct nw_socket *nw_socket, int error_code) {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (socket && s_validate_event_loop(nw_socket->event_loop)) {
struct nw_socket_scheduled_task_args *args =
aws_mem_calloc(socket->allocator, 1, sizeof(struct nw_socket_scheduled_task_args));
args->nw_socket = s_socket_acquire_internal_ref(nw_socket);
args->allocator = socket->allocator;
args->error_code = error_code;
aws_task_init(&args->task, s_process_connection_result_task, args, "connectionSuccessTask");
aws_event_loop_schedule_task_now(nw_socket->event_loop, &args->task);
}
s_unlock_base_socket(nw_socket);
}
struct connection_state_change_args {
struct aws_task task;
struct aws_allocator *allocator;
struct aws_socket *socket;
struct nw_socket *nw_socket;
nw_connection_t nw_connection;
nw_connection_state_t state;
int error;
};
static void s_process_connection_state_changed_task(struct aws_task *task, void *args, enum aws_task_status status) {
(void)status;
(void)task;
struct connection_state_change_args *connection_args = args;
struct nw_socket *nw_socket = connection_args->nw_socket;
nw_connection_t nw_connection = connection_args->nw_connection;
nw_connection_state_t state = connection_args->state;
/* Ideally we should not have a canceled task here, as nw_socket keeps a reference to event loop, therefore the
* event loop should never be destroyed before the nw_socket get destroyed. If we manually cancel the task, we
* should make sure we carefully handled the state change eventually, as the socket relies on this task to release
* and cleanup.
*/
if (status != AWS_TASK_STATUS_CANCELED) {
AWS_LOGF_INFO(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: Apple network framework socket connection state changed to %d, nw error code : %d",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection,
connection_args->state,
connection_args->error);
switch (state) {
case nw_connection_state_cancelled: {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
s_unlock_base_socket(nw_socket);
s_lock_socket_synced_data(nw_socket);
s_set_socket_state(nw_socket, socket, CLOSED);
s_unlock_socket_synced_data(nw_socket);
s_socket_release_internal_ref(nw_socket);
} break;
case nw_connection_state_ready: {
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;
if (socket) {
nw_path_t path = nw_connection_copy_current_path(nw_connection);
nw_endpoint_t local_endpoint = nw_path_copy_effective_local_endpoint(path);
nw_release(path);
const char *hostname = nw_endpoint_get_hostname(local_endpoint);
uint16_t port = nw_endpoint_get_port(local_endpoint);
nw_release(local_endpoint);
if (hostname != NULL) {
size_t hostname_len = strlen(hostname);
size_t buffer_size = AWS_ARRAY_SIZE(socket->local_endpoint.address);
size_t to_copy = aws_min_size(hostname_len, buffer_size);
memcpy(socket->local_endpoint.address, hostname, to_copy);
socket->local_endpoint.port = port;
}
AWS_LOGF_TRACE(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: set local endpoint %s:%d",
(void *)socket,
socket->io_handle.data.handle,
socket->local_endpoint.address,
port);
} else {
// This happens when the aws_socket_clean_up() get called before the nw_connection_state_ready get
// returned. We still want to set the socket to write/read state and fire the connection succeed
// callback until we get the "nw_connection_state_cancelled" status.
AWS_LOGF_TRACE(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: connection succeed, however, the base socket has been cleaned up.",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection);
}
s_lock_socket_synced_data(nw_socket);
s_set_socket_state(nw_socket, socket, CONNECTED_WRITE | CONNECTED_READ);
s_unlock_socket_synced_data(nw_socket);
s_unlock_base_socket(nw_socket);
nw_socket->connection_setup = true;
// Cancel the connection timeout task
if (nw_socket->timeout_args) {
aws_event_loop_cancel_task(nw_socket->event_loop, &nw_socket->timeout_args->task);
}
aws_ref_count_acquire(&nw_socket->nw_socket_ref_count);
s_handle_on_connection_result(nw_socket, AWS_OP_SUCCESS);
aws_ref_count_release(&nw_socket->nw_socket_ref_count);
} break;
case nw_connection_state_waiting:
case nw_connection_state_preparing:
case nw_connection_state_failed:
default:
break;
}
int crt_error_code = connection_args->error;
if (crt_error_code) {
/* any error, including if closed remotely in error */
AWS_LOGF_DEBUG(
AWS_LS_IO_SOCKET,
"id=%p handle=%p: socket connection got error: %d",
(void *)nw_socket,
(void *)nw_socket->os_handle.nw_connection,
crt_error_code);
nw_socket->last_error = crt_error_code;
s_lock_base_socket(nw_socket);
struct aws_socket *socket = nw_socket->base_socket_synced_data.base_socket;