-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCDAsyncSocket.m
More file actions
1120 lines (976 loc) · 40.8 KB
/
GCDAsyncSocket.m
File metadata and controls
1120 lines (976 loc) · 40.8 KB
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
//
// GCDAsyncSocket.m
// GCDAsyncSocket (NWAsyncSocket)
//
// TCP socket using Network.framework's C API (nw_connection_t).
// Drop-in replacement for GCDAsyncSocket from CocoaAsyncSocket.
// Only compiles on Apple platforms (iOS 13+, macOS 10.15+).
//
#import "GCDAsyncSocket.h"
#import "NWStreamBuffer.h"
#import "NWSSEParser.h"
#import "NWReadRequest.h"
#if __has_include(<Network/Network.h>)
#define NW_FRAMEWORK_AVAILABLE 1
#import <Network/Network.h>
#include <arpa/inet.h>
#include <netdb.h>
#else
#define NW_FRAMEWORK_AVAILABLE 0
#endif
NSString * const GCDAsyncSocketErrorDomain = @"GCDAsyncSocketErrorDomain";
static const void *kGCDAsyncSocketQueueKey = &kGCDAsyncSocketQueueKey;
static NSString * const GCDAsyncSocketDisconnectReasonKey = @"GCDAsyncSocketDisconnectReason";
static NSString * const GCDAsyncSocketNWErrorDomainKey = @"GCDAsyncSocketNWErrorDomain";
static NSString * const GCDAsyncSocketNWErrorCodeKey = @"GCDAsyncSocketNWErrorCode";
@interface GCDAsyncSocket ()
@property (atomic, readwrite, copy, nullable) NSString *connectedHost;
@property (atomic, readwrite) uint16_t connectedPort;
@property (atomic, readwrite, copy, nullable) NSString *localHost;
@property (atomic, readwrite) uint16_t localPort;
@property (atomic, readwrite) BOOL isConnected;
#if NW_FRAMEWORK_AVAILABLE
@property (nonatomic, assign) nw_connection_t connection;
@property (nonatomic, assign, nullable) nw_listener_t listener;
#endif
@property (nonatomic, strong) dispatch_queue_t socketQueue;
@property (nonatomic, strong) NWStreamBuffer *buffer;
@property (nonatomic, strong) NSMutableArray<NWReadRequest *> *readQueue;
@property (nonatomic, assign) BOOL isReadingContinuously;
@property (atomic, assign) BOOL isListening;
// SSE / streaming text mode
@property (nonatomic, strong, nullable) NWSSEParser *sseParser;
@property (nonatomic, assign) BOOL streamingTextEnabled;
// TLS
@property (nonatomic, assign) BOOL tlsEnabled;
// Write queue tracking
@property (nonatomic, assign) NSUInteger pendingWriteCount;
@property (nonatomic, assign) BOOL flagDisconnectAfterWrites;
@property (nonatomic, assign) BOOL flagDisconnectAfterReads;
@end
@implementation GCDAsyncSocket
@synthesize connectedHost = _connectedHost;
@synthesize connectedPort = _connectedPort;
@synthesize localHost = _localHost;
@synthesize localPort = _localPort;
@synthesize isConnected = _isConnected;
+ (NSData *)CRLFData {
return [NSData dataWithBytes:"\x0D\x0A" length:2];
}
+ (NSData *)CRData {
return [NSData dataWithBytes:"\x0D" length:1];
}
+ (NSData *)LFData {
return [NSData dataWithBytes:"\x0A" length:1];
}
+ (NSData *)ZeroData {
return [NSData dataWithBytes:"" length:1];
}
#pragma mark - Error Helpers
#if NW_FRAMEWORK_AVAILABLE
- (NSString *)nwErrorDomainString:(nw_error_domain_t)domain {
switch (domain) {
case nw_error_domain_posix:
return @"posix";
case nw_error_domain_dns:
return @"dns";
case nw_error_domain_tls:
return @"tls";
default:
return @"unknown";
}
}
- (NSError *)socketErrorWithCode:(GCDAsyncSocketError)code
description:(NSString *)description
reason:(NSString *)reason
nwError:(nw_error_t _Nullable)nwError {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (description.length > 0) {
userInfo[NSLocalizedDescriptionKey] = description;
}
if (reason.length > 0) {
userInfo[GCDAsyncSocketDisconnectReasonKey] = reason;
}
if (nwError) {
nw_error_domain_t domain = nw_error_get_error_domain(nwError);
int errorCode = nw_error_get_error_code(nwError);
userInfo[GCDAsyncSocketNWErrorDomainKey] = [self nwErrorDomainString:domain];
userInfo[GCDAsyncSocketNWErrorCodeKey] = @(errorCode);
}
return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:code userInfo:userInfo];
}
- (NSString *)preferredHostForHost:(NSString *)host {
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *result = NULL;
int ga = getaddrinfo(host.UTF8String, NULL, &hints, &result);
if (ga != 0 || !result) {
return host;
}
NSString *firstIPv4 = nil;
NSString *firstIPv6 = nil;
char addressBuffer[INET6_ADDRSTRLEN] = {0};
for (struct addrinfo *p = result; p != NULL; p = p->ai_next) {
if (p->ai_family == AF_INET && !firstIPv4) {
struct sockaddr_in *addr = (struct sockaddr_in *)p->ai_addr;
if (inet_ntop(AF_INET, &(addr->sin_addr), addressBuffer, sizeof(addressBuffer))) {
firstIPv4 = [NSString stringWithUTF8String:addressBuffer];
}
} else if (p->ai_family == AF_INET6 && !firstIPv6) {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p->ai_addr;
if (inet_ntop(AF_INET6, &(addr6->sin6_addr), addressBuffer, sizeof(addressBuffer))) {
firstIPv6 = [NSString stringWithUTF8String:addressBuffer];
}
}
if (firstIPv4 && firstIPv6) {
break;
}
}
freeaddrinfo(result);
if (self.IPv4PreferredOverIPv6) {
return firstIPv4 ?: firstIPv6 ?: host;
}
return firstIPv6 ?: firstIPv4 ?: host;
}
#endif
#pragma mark - Init
- (instancetype)initWithDelegate:(id<GCDAsyncSocketDelegate>)delegate
delegateQueue:(dispatch_queue_t)delegateQueue {
return [self initWithDelegate:delegate delegateQueue:delegateQueue socketQueue:NULL];
}
- (instancetype)initWithDelegate:(id<GCDAsyncSocketDelegate>)delegate
delegateQueue:(dispatch_queue_t)delegateQueue
socketQueue:(dispatch_queue_t)socketQueue {
self = [super init];
if (self) {
_delegate = delegate;
_delegateQueue = delegateQueue ?: dispatch_get_main_queue();
_socketQueue = socketQueue ?: dispatch_queue_create("com.gcdasyncsocket.nw.socketQueue",
DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(_socketQueue, kGCDAsyncSocketQueueKey, (void *)kGCDAsyncSocketQueueKey, NULL);
_buffer = [[NWStreamBuffer alloc] init];
_readQueue = [NSMutableArray array];
_isReadingContinuously = NO;
_tlsEnabled = NO;
_allowInsecureTLS = YES;
_streamingTextEnabled = NO;
_IPv4PreferredOverIPv6 = YES;
}
return self;
}
- (void)setDelegate:(id<GCDAsyncSocketDelegate>)delegate delegateQueue:(dispatch_queue_t)delegateQueue {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
strongSelf.delegate = delegate;
strongSelf.delegateQueue = delegateQueue ?: dispatch_get_main_queue();
});
}
- (void)performSyncOnSocketQueue:(dispatch_block_t)block {
if (!block) {
return;
}
if (dispatch_get_specific(kGCDAsyncSocketQueueKey)) {
block();
} else {
dispatch_sync(self.socketQueue, block);
}
}
- (void)setIsConnected:(BOOL)isConnected {
[self performSyncOnSocketQueue:^{
self->_isConnected = isConnected;
}];
}
- (BOOL)isConnected {
__block BOOL connected = NO;
[self performSyncOnSocketQueue:^{
connected = self->_isConnected;
}];
return connected;
}
- (BOOL)isDisconnected {
return !self.isConnected;
}
- (BOOL)isSecure {
__block BOOL secure = NO;
[self performSyncOnSocketQueue:^{
secure = self->_isConnected && self->_tlsEnabled;
}];
return secure;
}
- (void)setConnectedHost:(NSString *)connectedHost {
[self performSyncOnSocketQueue:^{
self->_connectedHost = [connectedHost copy];
}];
}
- (NSString *)connectedHost {
__block NSString *host = nil;
[self performSyncOnSocketQueue:^{
host = self->_isConnected ? [self->_connectedHost copy] : nil;
}];
return host;
}
- (void)setConnectedPort:(uint16_t)connectedPort {
[self performSyncOnSocketQueue:^{
self->_connectedPort = connectedPort;
}];
}
- (uint16_t)connectedPort {
__block uint16_t port = 0;
[self performSyncOnSocketQueue:^{
port = self->_isConnected ? self->_connectedPort : 0;
}];
return port;
}
- (void)setLocalPort:(uint16_t)localPort {
[self performSyncOnSocketQueue:^{
self->_localPort = localPort;
}];
}
- (uint16_t)localPort {
__block uint16_t port = 0;
[self performSyncOnSocketQueue:^{
if (self->_isListening) {
port = self->_localPort;
} else {
port = self->_isConnected ? self->_localPort : 0;
}
}];
return port;
}
- (void)setLocalHost:(NSString *)localHost {
[self performSyncOnSocketQueue:^{
self->_localHost = [localHost copy];
}];
}
- (NSString *)localHost {
__block NSString *host = nil;
[self performSyncOnSocketQueue:^{
host = self->_isConnected ? [self->_localHost copy] : nil;
}];
return host;
}
- (void)dealloc {
#if NW_FRAMEWORK_AVAILABLE
if (_listener) {
nw_listener_cancel(_listener);
}
if (_connection) {
nw_connection_cancel(_connection);
}
#endif
}
#pragma mark - Configuration
- (void)enableTLS {
_tlsEnabled = YES;
}
- (void)enableSSEParsing {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
weakSelf.sseParser = [[NWSSEParser alloc] init];
});
}
- (void)enableStreamingText {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
weakSelf.streamingTextEnabled = YES;
});
}
#pragma mark - Connect
- (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr {
return [self connectToHost:host onPort:port withTimeout:-1 error:errPtr];
}
- (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr {
return [self acceptOnInterface:nil port:port error:errPtr];
}
- (BOOL)acceptOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr {
#if NW_FRAMEWORK_AVAILABLE
if (self.isListening) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorAlreadyConnected
userInfo:@{NSLocalizedDescriptionKey: @"Socket is already listening."}];
}
return NO;
}
nw_parameters_t parameters = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DISABLE_PROTOCOL,
NW_PARAMETERS_DEFAULT_CONFIGURATION
);
if (interface.length > 0) {
// Bind to a specific interface/address
NSString *portStr = [NSString stringWithFormat:@"%u", port];
nw_endpoint_t localEndpoint = nw_endpoint_create_host(interface.UTF8String, portStr.UTF8String);
nw_parameters_set_local_endpoint(parameters, localEndpoint);
}
nw_listener_t listener = nw_listener_create_with_port([NSString stringWithFormat:@"%u", port].UTF8String, parameters);
if (!listener) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: @"Failed to create listener."}];
}
return NO;
}
self.listener = listener;
__weak typeof(self) weakSelf = self;
nw_listener_set_state_changed_handler(listener, ^(nw_listener_state_t state, nw_error_t _Nullable error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
switch (state) {
case nw_listener_state_ready: {
strongSelf.isListening = YES;
uint16_t assignedPort = nw_listener_get_port(listener);
strongSelf.localPort = assignedPort;
break;
}
case nw_listener_state_failed: {
strongSelf.isListening = NO;
NSError *nsError = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Listener failed."
reason:@"NW listener entered failed state"
nwError:error];
[strongSelf disconnectInternalWithError:nsError];
break;
}
case nw_listener_state_cancelled: {
strongSelf.isListening = NO;
break;
}
default:
break;
}
});
nw_listener_set_new_connection_handler(listener, ^(nw_connection_t newConnection) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// Create a new GCDAsyncSocket for the accepted connection.
// The new socket inherits the listener's delegate – this matches
// GCDAsyncSocket from CocoaAsyncSocket. The user may reassign the
// delegate on newSocket inside socket:didAcceptNewSocket: if needed.
GCDAsyncSocket *newSocket = [[GCDAsyncSocket alloc] initWithDelegate:strongSelf.delegate
delegateQueue:strongSelf.delegateQueue
socketQueue:nil];
newSocket.connection = newConnection;
// State change handler for the accepted connection
nw_connection_set_state_changed_handler(newConnection, ^(nw_connection_state_t state, nw_error_t _Nullable error) {
[newSocket handleStateChange:state error:error];
});
nw_connection_set_queue(newConnection, newSocket.socketQueue);
nw_connection_start(newConnection);
dispatch_async(strongSelf.delegateQueue, ^{
id delegate = strongSelf.delegate;
if ([delegate respondsToSelector:@selector(socket:didAcceptNewSocket:)]) {
[delegate socket:strongSelf didAcceptNewSocket:newSocket];
}
});
});
nw_listener_set_queue(listener, self.socketQueue);
nw_listener_start(listener);
return YES;
#else
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: @"Network.framework is not available on this platform."}];
}
return NO;
#endif
}
- (BOOL)acceptOnUrl:(NSURL *)url error:(NSError **)errPtr {
#if NW_FRAMEWORK_AVAILABLE
if (self.isListening) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorAlreadyConnected
userInfo:@{NSLocalizedDescriptionKey: @"Socket is already listening."}];
}
return NO;
}
if (!url.isFileURL) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorInvalidParameter
userInfo:@{NSLocalizedDescriptionKey: @"URL must be a file URL for Unix Domain Socket."}];
}
return NO;
}
nw_parameters_t parameters = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DISABLE_PROTOCOL,
NW_PARAMETERS_DEFAULT_CONFIGURATION
);
// Remove existing socket file if present
NSString *path = url.path;
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
// Construct a unix:// URL for the endpoint (Network.framework expects this scheme)
NSString *unixURLString = [NSString stringWithFormat:@"unix://%@", path];
nw_endpoint_t localEndpoint = nw_endpoint_create_url(unixURLString.UTF8String);
nw_parameters_set_local_endpoint(parameters, localEndpoint);
nw_listener_t listener = nw_listener_create(parameters);
if (!listener) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: @"Failed to create Unix Domain Socket listener."}];
}
return NO;
}
self.listener = listener;
__weak typeof(self) weakSelf = self;
nw_listener_set_state_changed_handler(listener, ^(nw_listener_state_t state, nw_error_t _Nullable error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
switch (state) {
case nw_listener_state_ready: {
strongSelf.isListening = YES;
break;
}
case nw_listener_state_failed: {
strongSelf.isListening = NO;
NSError *nsError = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Unix Domain Socket listener failed."
reason:@"NW listener entered failed state"
nwError:error];
[strongSelf disconnectInternalWithError:nsError];
break;
}
case nw_listener_state_cancelled: {
strongSelf.isListening = NO;
break;
}
default:
break;
}
});
nw_listener_set_new_connection_handler(listener, ^(nw_connection_t newConnection) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// See acceptOnInterface:port:error: for rationale on delegate sharing.
GCDAsyncSocket *newSocket = [[GCDAsyncSocket alloc] initWithDelegate:strongSelf.delegate
delegateQueue:strongSelf.delegateQueue
socketQueue:nil];
newSocket.connection = newConnection;
nw_connection_set_state_changed_handler(newConnection, ^(nw_connection_state_t state, nw_error_t _Nullable error) {
[newSocket handleStateChange:state error:error];
});
nw_connection_set_queue(newConnection, newSocket.socketQueue);
nw_connection_start(newConnection);
dispatch_async(strongSelf.delegateQueue, ^{
id delegate = strongSelf.delegate;
if ([delegate respondsToSelector:@selector(socket:didAcceptNewSocket:)]) {
[delegate socket:strongSelf didAcceptNewSocket:newSocket];
}
});
});
nw_listener_set_queue(listener, self.socketQueue);
nw_listener_start(listener);
return YES;
#else
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: @"Network.framework is not available on this platform."}];
}
return NO;
#endif
}
- (BOOL)connectToHost:(NSString *)host
onPort:(uint16_t)port
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr {
if (self.isConnected) {
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorAlreadyConnected
userInfo:@{NSLocalizedDescriptionKey: @"Socket is already connected."}];
}
return NO;
}
#if NW_FRAMEWORK_AVAILABLE
// Create endpoint (resolve with configurable IPv4/IPv6 preference)
NSString *portStr = [NSString stringWithFormat:@"%u", port];
NSString *targetHost = [self preferredHostForHost:host];
nw_endpoint_t endpoint = nw_endpoint_create_host(targetHost.UTF8String, portStr.UTF8String);
// Create parameters
nw_parameters_t parameters;
if (self.tlsEnabled) {
if (self.allowInsecureTLS) {
dispatch_queue_t verifyQueue = self.socketQueue ?: dispatch_get_main_queue();
parameters = nw_parameters_create_secure_tcp(
^(nw_protocol_options_t _Nonnull tlsOptions) {
sec_protocol_options_t secOptions = nw_tls_copy_sec_protocol_options(tlsOptions);
sec_protocol_options_set_verify_block(secOptions, ^(sec_protocol_metadata_t _Nonnull metadata,
sec_trust_t _Nonnull trust,
sec_protocol_verify_complete_t _Nonnull complete) {
(void)metadata;
(void)trust;
complete(true);
}, verifyQueue);
},
NW_PARAMETERS_DEFAULT_CONFIGURATION
);
} else {
parameters = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DEFAULT_CONFIGURATION,
NW_PARAMETERS_DEFAULT_CONFIGURATION
);
}
} else {
parameters = nw_parameters_create_secure_tcp(
NW_PARAMETERS_DISABLE_PROTOCOL,
NW_PARAMETERS_DEFAULT_CONFIGURATION
);
}
// Create connection
nw_connection_t conn = nw_connection_create(endpoint, parameters);
self.connection = conn;
self.connectedHost = targetHost;
self.connectedPort = port;
self.localHost = nil;
self.localPort = 0;
// State change handler
__weak typeof(self) weakSelf = self;
nw_connection_set_state_changed_handler(conn, ^(nw_connection_state_t state, nw_error_t _Nullable error) {
[weakSelf handleStateChange:state error:error];
});
// Start connection
nw_connection_set_queue(conn, self.socketQueue);
nw_connection_start(conn);
// Connection timeout
if (timeout > 0) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)),
self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf && !strongSelf.isConnected) {
NSError *timeoutError = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Connection timed out."
reason:@"Connect timeout"
nwError:nil];
[strongSelf disconnectWithError:timeoutError];
}
});
}
return YES;
#else
if (errPtr) {
*errPtr = [NSError errorWithDomain:GCDAsyncSocketErrorDomain
code:GCDAsyncSocketErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: @"Network.framework is not available on this platform."}];
}
return NO;
#endif
}
#pragma mark - Disconnect
- (void)disconnect {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
#if NW_FRAMEWORK_AVAILABLE
// Stop listener if in server mode
if (strongSelf.listener) {
nw_listener_cancel(strongSelf.listener);
strongSelf.listener = nil;
strongSelf.isListening = NO;
strongSelf.localPort = 0;
}
#endif
[strongSelf disconnectInternalWithError:nil];
});
}
- (void)disconnectAfterWriting {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
strongSelf.flagDisconnectAfterWrites = YES;
// If no writes are in flight, disconnect immediately.
// Otherwise the send-completion handler will disconnect
// once the last pending write finishes.
if (strongSelf.pendingWriteCount == 0) {
[strongSelf disconnectInternalWithError:nil];
}
});
}
- (void)disconnectAfterReading {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
strongSelf.flagDisconnectAfterReads = YES;
// If no read requests are pending, disconnect immediately.
// Otherwise the read-completion callback will disconnect
// once the last pending read request is fulfilled.
if (strongSelf.readQueue.count == 0) {
[strongSelf disconnectInternalWithError:nil];
}
});
}
#pragma mark - Reading
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
NWReadRequest *req = [NWReadRequest availableRequestWithTimeout:timeout tag:tag];
[strongSelf.readQueue addObject:req];
[strongSelf dequeueNextRead];
});
}
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
NWReadRequest *req = [NWReadRequest toLengthRequest:length timeout:timeout tag:tag];
[strongSelf.readQueue addObject:req];
[strongSelf dequeueNextRead];
});
}
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag {
[self readDataToData:data withTimeout:timeout maxLength:0 tag:tag];
}
- (void)readDataToData:(NSData *)data
withTimeout:(NSTimeInterval)timeout
maxLength:(NSUInteger)maxLength
tag:(long)tag {
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
NWReadRequest *req = [NWReadRequest toDelimiterRequest:data
timeout:timeout
maxLength:maxLength
tag:tag];
[strongSelf.readQueue addObject:req];
[strongSelf dequeueNextRead];
});
}
#pragma mark - Writing
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag {
#if NW_FRAMEWORK_AVAILABLE
__weak typeof(self) weakSelf = self;
dispatch_async(self.socketQueue, ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
if (!strongSelf.connection || !strongSelf.isConnected) {
dispatch_async(strongSelf.delegateQueue, ^{
NSError *err = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorNotConnected
description:@"Socket is not connected."
reason:@"Write requested while socket not connected"
nwError:nil];
id delegate = strongSelf.delegate;
if ([delegate respondsToSelector:@selector(socketDidDisconnect:withError:)]) {
[delegate socketDidDisconnect:strongSelf withError:err];
}
});
return;
}
// Convert NSData to dispatch_data_t
dispatch_data_t dispatchData = dispatch_data_create(data.bytes, data.length,
strongSelf.socketQueue,
DISPATCH_DATA_DESTRUCTOR_DEFAULT);
__block BOOL timedOut = NO;
__block BOOL writeCompleted = NO;
__block dispatch_block_t timeoutBlock = nil;
if (timeout > 0) {
timeoutBlock = dispatch_block_create(0, ^{
if (!writeCompleted) {
timedOut = YES;
NSError *err = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorWriteTimeout
description:@"Write timed out."
reason:@"Write timeout"
nwError:nil];
[strongSelf disconnectWithError:err];
}
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)),
strongSelf.socketQueue, timeoutBlock);
}
strongSelf.pendingWriteCount++;
// is_complete must be false so the TCP stream stays open for
// subsequent writes (e.g. HTTP header followed by body).
// Passing true here would send a TCP FIN after each write,
// closing the write side of the connection prematurely.
nw_connection_send(strongSelf.connection, dispatchData,
NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT,
false, ^(nw_error_t _Nullable error) {
writeCompleted = YES;
if (timeoutBlock) {
dispatch_block_cancel(timeoutBlock);
}
if (timedOut) return;
__strong typeof(weakSelf) sself = weakSelf;
if (!sself) return;
// This completion handler fires on socketQueue (set via
// nw_connection_set_queue), so we can safely mutate state.
sself.pendingWriteCount--;
if (error) {
NSError *nsError = [sself socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Write failed."
reason:@"nw_connection_send failed"
nwError:error];
[sself disconnectInternalWithError:nsError];
} else {
dispatch_async(sself.delegateQueue, ^{
id delegate = sself.delegate;
if ([delegate respondsToSelector:@selector(socket:didWriteDataWithTag:)]) {
[delegate socket:sself didWriteDataWithTag:tag];
}
});
// Check if we should disconnect after all writes complete
if (sself.flagDisconnectAfterWrites && sself.pendingWriteCount == 0) {
[sself disconnectInternalWithError:nil];
}
}
});
});
#endif
}
#pragma mark - Private: State handling
#if NW_FRAMEWORK_AVAILABLE
- (void)handleStateChange:(nw_connection_state_t)state error:(nw_error_t _Nullable)error {
switch (state) {
case nw_connection_state_ready: {
self.isConnected = YES;
#if NW_FRAMEWORK_AVAILABLE
nw_path_t path = nw_connection_copy_current_path(self.connection);
if (path) {
nw_endpoint_t localEndpoint = nw_path_copy_effective_local_endpoint(path);
if (localEndpoint) {
const char *localHostStr = nw_endpoint_get_hostname(localEndpoint);
if (localHostStr) {
self.localHost = [NSString stringWithUTF8String:localHostStr];
}
uint16_t localPortValue = nw_endpoint_get_port(localEndpoint);
self.localPort = localPortValue;
}
}
#endif
NSString *host = self.connectedHost ?: @"";
uint16_t port = self.connectedPort;
__weak typeof(self) weakSelf = self;
dispatch_async(self.delegateQueue, ^{
id delegate = weakSelf.delegate;
if ([delegate respondsToSelector:@selector(socket:didConnectToHost:port:)]) {
[delegate socket:weakSelf didConnectToHost:host port:port];
}
});
[self startContinuousRead];
break;
}
case nw_connection_state_failed: {
NSError *nsError = [self socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Connection failed."
reason:@"NW connection entered failed state"
nwError:error];
[self disconnectInternalWithError:nsError];
break;
}
case nw_connection_state_cancelled: {
[self disconnectInternalWithError:nil];
break;
}
default:
break;
}
}
#endif
#pragma mark - Private: Continuous read loop
- (void)startContinuousRead {
if (self.isReadingContinuously) return;
self.isReadingContinuously = YES;
[self readNextChunk];
}
- (void)readNextChunk {
#if NW_FRAMEWORK_AVAILABLE
if (!self.connection || !self.isConnected) return;
__weak typeof(self) weakSelf = self;
nw_connection_receive(self.connection, 1, 65536,
^(dispatch_data_t _Nullable content,
nw_content_context_t _Nullable context,
bool is_complete,
nw_error_t _Nullable error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
if (content) {
// Convert dispatch_data_t to NSData
const void *buffer;
size_t size;
__unused dispatch_data_t contiguous = dispatch_data_create_map(content, &buffer, &size);
NSData *data = [NSData dataWithBytes:buffer length:size];
[strongSelf.buffer appendData:data];
// SSE parsing mode
if (strongSelf.sseParser) {
NSArray<NWSSEEvent *> *events = [strongSelf.sseParser parseData:data];
for (NWSSEEvent *event in events) {
dispatch_async(strongSelf.delegateQueue, ^{
if ([strongSelf.delegate respondsToSelector:@selector(socket:didReceiveSSEEvent:)]) {
[strongSelf.delegate socket:strongSelf didReceiveSSEEvent:event];
}
});
}
}
// Streaming text mode: extract UTF-8 safe string from the
// newly received data without consuming the buffer.
if (strongSelf.streamingTextEnabled) {
NSUInteger safeCount = [NWStreamBuffer utf8SafeByteCountForData:data];
if (safeCount > 0) {
NSData *safeData = [data subdataWithRange:NSMakeRange(0, safeCount)];
NSString *str = [[NSString alloc] initWithData:safeData encoding:NSUTF8StringEncoding];
if (str) {
dispatch_async(strongSelf.delegateQueue, ^{
if ([strongSelf.delegate respondsToSelector:@selector(socket:didReceiveString:)]) {
[strongSelf.delegate socket:strongSelf didReceiveString:str];
}
});
}
}
}
// Process read queue
[strongSelf processReadQueue];
}
if (is_complete) {
NSError *eofError = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Connection closed by peer."
reason:@"EOF received (nw_connection_receive is_complete=1)"
nwError:nil];
[strongSelf disconnectInternalWithError:eofError];
return;
}
if (error) {
NSError *nsError = [strongSelf socketErrorWithCode:GCDAsyncSocketErrorConnectionFailed
description:@"Read error."
reason:@"nw_connection_receive returned error"
nwError:error];
[strongSelf disconnectInternalWithError:nsError];
return;
}
// Continue reading
[strongSelf readNextChunk];
});
#endif
}
#pragma mark - Private: Read queue processing
- (void)dequeueNextRead {
[self processReadQueue];
}
- (void)processReadQueue {
while (self.readQueue.count > 0) {
NWReadRequest *request = self.readQueue[0];
switch (request.type) {
case NWReadRequestTypeAvailable: {