-
Notifications
You must be signed in to change notification settings - Fork 0
/
GCDAsyncUdpSocket.m
executable file
·5430 lines (4233 loc) · 130 KB
/
GCDAsyncUdpSocket.m
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
//
// GCDAsyncUdpSocket
//
// This class is in the public domain.
// Originally created by Robbie Hanson of Deusty LLC.
// Updated and maintained by Deusty LLC and the Apple development community.
//
// https://github.com/robbiehanson/CocoaAsyncSocket
//
#import "GCDAsyncUdpSocket.h"
#if ! __has_feature(objc_arc)
#warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
// For more information see: https://github.com/robbiehanson/CocoaAsyncSocket/wiki/ARC
#endif
#if TARGET_OS_IPHONE
#import <CFNetwork/CFNetwork.h>
#import <UIKit/UIKit.h>
#endif
#import <arpa/inet.h>
#import <fcntl.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <net/if.h>
#import <sys/socket.h>
#import <sys/types.h>
#if 0
// Logging Enabled - See log level below
// Logging uses the CocoaLumberjack framework (which is also GCD based).
// http://code.google.com/p/cocoalumberjack/
//
// It allows us to do a lot of logging without significantly slowing down the code.
#import "DDLog.h"
#define LogAsync NO
#define LogContext 65535
#define LogObjc(flg, frmt, ...) LOG_OBJC_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
#define LogC(flg, frmt, ...) LOG_C_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
#define LogError(frmt, ...) LogObjc(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogWarn(frmt, ...) LogObjc(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogInfo(frmt, ...) LogObjc(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogVerbose(frmt, ...) LogObjc(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCError(frmt, ...) LogC(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCWarn(frmt, ...) LogC(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCInfo(frmt, ...) LogC(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogCVerbose(frmt, ...) LogC(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
#define LogTrace() LogObjc(LOG_FLAG_VERBOSE, @"%@: %@", THIS_FILE, THIS_METHOD)
#define LogCTrace() LogC(LOG_FLAG_VERBOSE, @"%@: %s", THIS_FILE, __FUNCTION__)
// Log levels : off, error, warn, info, verbose
static const int logLevel = LOG_LEVEL_VERBOSE;
#else
// Logging Disabled
#define LogError(frmt, ...) {}
#define LogWarn(frmt, ...) {}
#define LogInfo(frmt, ...) {}
#define LogVerbose(frmt, ...) {}
#define LogCError(frmt, ...) {}
#define LogCWarn(frmt, ...) {}
#define LogCInfo(frmt, ...) {}
#define LogCVerbose(frmt, ...) {}
#define LogTrace() {}
#define LogCTrace(frmt, ...) {}
#endif
/**
* Seeing a return statements within an inner block
* can sometimes be mistaken for a return point of the enclosing method.
* This makes inline blocks a bit easier to read.
**/
#define return_from_block return
/**
* A socket file descriptor is really just an integer.
* It represents the index of the socket within the kernel.
* This makes invalid file descriptor comparisons easier to read.
**/
#define SOCKET_NULL -1
/**
* Just to type less code.
**/
#define AutoreleasedBlock(block) ^{ @autoreleasepool { block(); }}
@class GCDAsyncUdpSendPacket;
NSString *const GCDAsyncUdpSocketException = @"GCDAsyncUdpSocketException";
NSString *const GCDAsyncUdpSocketErrorDomain = @"GCDAsyncUdpSocketErrorDomain";
NSString *const GCDAsyncUdpSocketQueueName = @"GCDAsyncUdpSocket";
NSString *const GCDAsyncUdpSocketThreadName = @"GCDAsyncUdpSocket-CFStream";
enum GCDAsyncUdpSocketFlags
{
kDidCreateSockets = 1 << 0, // If set, the sockets have been created.
kDidBind = 1 << 1, // If set, bind has been called.
kConnecting = 1 << 2, // If set, a connection attempt is in progress.
kDidConnect = 1 << 3, // If set, socket is connected.
kReceiveOnce = 1 << 4, // If set, one-at-a-time receive is enabled
kReceiveContinuous = 1 << 5, // If set, continuous receive is enabled
kIPv4Deactivated = 1 << 6, // If set, socket4 was closed due to bind or connect on IPv6.
kIPv6Deactivated = 1 << 7, // If set, socket6 was closed due to bind or connect on IPv4.
kSend4SourceSuspended = 1 << 8, // If set, send4Source is suspended.
kSend6SourceSuspended = 1 << 9, // If set, send6Source is suspended.
kReceive4SourceSuspended = 1 << 10, // If set, receive4Source is suspended.
kReceive6SourceSuspended = 1 << 11, // If set, receive6Source is suspended.
kSock4CanAcceptBytes = 1 << 12, // If set, we know socket4 can accept bytes. If unset, it's unknown.
kSock6CanAcceptBytes = 1 << 13, // If set, we know socket6 can accept bytes. If unset, it's unknown.
kForbidSendReceive = 1 << 14, // If set, no new send or receive operations are allowed to be queued.
kCloseAfterSends = 1 << 15, // If set, close as soon as no more sends are queued.
kFlipFlop = 1 << 16, // Used to alternate between IPv4 and IPv6 sockets.
#if TARGET_OS_IPHONE
kAddedStreamListener = 1 << 17, // If set, CFStreams have been added to listener thread
#endif
};
enum GCDAsyncUdpSocketConfig
{
kIPv4Disabled = 1 << 0, // If set, IPv4 is disabled
kIPv6Disabled = 1 << 1, // If set, IPv6 is disabled
kPreferIPv4 = 1 << 2, // If set, IPv4 is preferred over IPv6
kPreferIPv6 = 1 << 3, // If set, IPv6 is preferred over IPv4
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface GCDAsyncUdpSocket ()
{
#if __has_feature(objc_arc_weak)
__weak id delegate;
#else
__unsafe_unretained id delegate;
#endif
dispatch_queue_t delegateQueue;
GCDAsyncUdpSocketReceiveFilterBlock receiveFilterBlock;
dispatch_queue_t receiveFilterQueue;
BOOL receiveFilterAsync;
GCDAsyncUdpSocketSendFilterBlock sendFilterBlock;
dispatch_queue_t sendFilterQueue;
BOOL sendFilterAsync;
uint32_t flags;
uint16_t config;
uint16_t max4ReceiveSize;
uint32_t max6ReceiveSize;
int socket4FD;
int socket6FD;
dispatch_queue_t socketQueue;
dispatch_source_t send4Source;
dispatch_source_t send6Source;
dispatch_source_t receive4Source;
dispatch_source_t receive6Source;
dispatch_source_t sendTimer;
GCDAsyncUdpSendPacket *currentSend;
NSMutableArray *sendQueue;
unsigned long socket4FDBytesAvailable;
unsigned long socket6FDBytesAvailable;
uint32_t pendingFilterOperations;
NSData *cachedLocalAddress4;
NSString *cachedLocalHost4;
uint16_t cachedLocalPort4;
NSData *cachedLocalAddress6;
NSString *cachedLocalHost6;
uint16_t cachedLocalPort6;
NSData *cachedConnectedAddress;
NSString *cachedConnectedHost;
uint16_t cachedConnectedPort;
int cachedConnectedFamily;
void *IsOnSocketQueueOrTargetQueueKey;
#if TARGET_OS_IPHONE
CFStreamClientContext streamContext;
CFReadStreamRef readStream4;
CFReadStreamRef readStream6;
CFWriteStreamRef writeStream4;
CFWriteStreamRef writeStream6;
#endif
id userData;
}
- (void)resumeSend4Source;
- (void)resumeSend6Source;
- (void)resumeReceive4Source;
- (void)resumeReceive6Source;
- (void)closeSockets;
- (void)maybeConnect;
- (BOOL)connectWithAddress4:(NSData *)address4 error:(NSError **)errPtr;
- (BOOL)connectWithAddress6:(NSData *)address6 error:(NSError **)errPtr;
- (void)maybeDequeueSend;
- (void)doPreSend;
- (void)doSend;
- (void)endCurrentSend;
- (void)setupSendTimerWithTimeout:(NSTimeInterval)timeout;
- (void)doReceive;
- (void)doReceiveEOF;
- (void)closeWithError:(NSError *)error;
- (BOOL)performMulticastRequest:(int)requestType forGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr;
#if TARGET_OS_IPHONE
- (BOOL)createReadAndWriteStreams:(NSError **)errPtr;
- (BOOL)registerForStreamCallbacks:(NSError **)errPtr;
- (BOOL)addStreamsToRunLoop:(NSError **)errPtr;
- (BOOL)openStreams:(NSError **)errPtr;
- (void)removeStreamsFromRunLoop;
- (void)closeReadAndWriteStreams;
#endif
+ (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4;
+ (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6;
+ (uint16_t)portFromSockaddr4:(const struct sockaddr_in *)pSockaddr4;
+ (uint16_t)portFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6;
#if TARGET_OS_IPHONE
// Forward declaration
+ (void)listenerThread;
#endif
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The GCDAsyncUdpSendPacket encompasses the instructions for a single send/write.
**/
@interface GCDAsyncUdpSendPacket : NSObject {
@public
NSData *buffer;
NSTimeInterval timeout;
long tag;
BOOL resolveInProgress;
BOOL filterInProgress;
NSArray *resolvedAddresses;
NSError *resolveError;
NSData *address;
int addressFamily;
}
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation GCDAsyncUdpSendPacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
if ((self = [super init]))
{
buffer = d;
timeout = t;
tag = i;
resolveInProgress = NO;
}
return self;
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface GCDAsyncUdpSpecialPacket : NSObject {
@public
// uint8_t type;
BOOL resolveInProgress;
NSArray *addresses;
NSError *error;
}
- (id)init;
@end
@implementation GCDAsyncUdpSpecialPacket
- (id)init
{
self = [super init];
return self;
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation GCDAsyncUdpSocket
- (id)init
{
LogTrace();
return [self initWithDelegate:nil delegateQueue:NULL socketQueue:NULL];
}
- (id)initWithSocketQueue:(dispatch_queue_t)sq
{
LogTrace();
return [self initWithDelegate:nil delegateQueue:NULL socketQueue:sq];
}
- (id)initWithDelegate:(id <GCDAsyncUdpSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq
{
LogTrace();
return [self initWithDelegate:aDelegate delegateQueue:dq socketQueue:NULL];
}
- (id)initWithDelegate:(id <GCDAsyncUdpSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq
{
LogTrace();
if ((self = [super init]))
{
delegate = aDelegate;
if (dq)
{
delegateQueue = dq;
#if !OS_OBJECT_USE_OBJC
dispatch_retain(delegateQueue);
#endif
}
max4ReceiveSize = 9216;
max6ReceiveSize = 9216;
socket4FD = SOCKET_NULL;
socket6FD = SOCKET_NULL;
if (sq)
{
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
socketQueue = sq;
#if !OS_OBJECT_USE_OBJC
dispatch_retain(socketQueue);
#endif
}
else
{
socketQueue = dispatch_queue_create([GCDAsyncUdpSocketQueueName UTF8String], NULL);
}
// The dispatch_queue_set_specific() and dispatch_get_specific() functions take a "void *key" parameter.
// From the documentation:
//
// > Keys are only compared as pointers and are never dereferenced.
// > Thus, you can use a pointer to a static variable for a specific subsystem or
// > any other value that allows you to identify the value uniquely.
//
// We're just going to use the memory address of an ivar.
// Specifically an ivar that is explicitly named for our purpose to make the code more readable.
//
// However, it feels tedious (and less readable) to include the "&" all the time:
// dispatch_get_specific(&IsOnSocketQueueOrTargetQueueKey)
//
// So we're going to make it so it doesn't matter if we use the '&' or not,
// by assigning the value of the ivar to the address of the ivar.
// Thus: IsOnSocketQueueOrTargetQueueKey == &IsOnSocketQueueOrTargetQueueKey;
IsOnSocketQueueOrTargetQueueKey = &IsOnSocketQueueOrTargetQueueKey;
void *nonNullUnusedPointer = (__bridge void *)self;
dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
currentSend = nil;
sendQueue = [[NSMutableArray alloc] initWithCapacity:5];
#if TARGET_OS_IPHONE
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
#endif
}
return self;
}
- (void)dealloc
{
LogInfo(@"%@ - %@ (start)", THIS_METHOD, self);
#if TARGET_OS_IPHONE
[[NSNotificationCenter defaultCenter] removeObserver:self];
#endif
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
{
[self closeWithError:nil];
}
else
{
dispatch_sync(socketQueue, ^{
[self closeWithError:nil];
});
}
delegate = nil;
#if !OS_OBJECT_USE_OBJC
if (delegateQueue) dispatch_release(delegateQueue);
#endif
delegateQueue = NULL;
#if !OS_OBJECT_USE_OBJC
if (socketQueue) dispatch_release(socketQueue);
#endif
socketQueue = NULL;
LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)delegate
{
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
{
return delegate;
}
else
{
__block id result = nil;
dispatch_sync(socketQueue, ^{
result = delegate;
});
return result;
}
}
- (void)setDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
delegate = newDelegate;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate
{
[self setDelegate:newDelegate synchronously:NO];
}
- (void)synchronouslySetDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate
{
[self setDelegate:newDelegate synchronously:YES];
}
- (dispatch_queue_t)delegateQueue
{
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
{
return delegateQueue;
}
else
{
__block dispatch_queue_t result = NULL;
dispatch_sync(socketQueue, ^{
result = delegateQueue;
});
return result;
}
}
- (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
#if !OS_OBJECT_USE_OBJC
if (delegateQueue) dispatch_release(delegateQueue);
if (newDelegateQueue) dispatch_retain(newDelegateQueue);
#endif
delegateQueue = newDelegateQueue;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegateQueue:newDelegateQueue synchronously:NO];
}
- (void)synchronouslySetDelegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegateQueue:newDelegateQueue synchronously:YES];
}
- (void)getDelegate:(id <GCDAsyncUdpSocketDelegate> *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr
{
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
{
if (delegatePtr) *delegatePtr = delegate;
if (delegateQueuePtr) *delegateQueuePtr = delegateQueue;
}
else
{
__block id dPtr = NULL;
__block dispatch_queue_t dqPtr = NULL;
dispatch_sync(socketQueue, ^{
dPtr = delegate;
dqPtr = delegateQueue;
});
if (delegatePtr) *delegatePtr = dPtr;
if (delegateQueuePtr) *delegateQueuePtr = dqPtr;
}
}
- (void)setDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
{
dispatch_block_t block = ^{
delegate = newDelegate;
#if !OS_OBJECT_USE_OBJC
if (delegateQueue) dispatch_release(delegateQueue);
if (newDelegateQueue) dispatch_retain(newDelegateQueue);
#endif
delegateQueue = newDelegateQueue;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
block();
}
else {
if (synchronously)
dispatch_sync(socketQueue, block);
else
dispatch_async(socketQueue, block);
}
}
- (void)setDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:NO];
}
- (void)synchronouslySetDelegate:(id <GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
{
[self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:YES];
}
- (BOOL)isIPv4Enabled
{
// Note: YES means kIPv4Disabled is OFF
__block BOOL result = NO;
dispatch_block_t block = ^{
result = ((config & kIPv4Disabled) == 0);
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setIPv4Enabled:(BOOL)flag
{
// Note: YES means kIPv4Disabled is OFF
dispatch_block_t block = ^{
LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO"));
if (flag)
config &= ~kIPv4Disabled;
else
config |= kIPv4Disabled;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (BOOL)isIPv6Enabled
{
// Note: YES means kIPv6Disabled is OFF
__block BOOL result = NO;
dispatch_block_t block = ^{
result = ((config & kIPv6Disabled) == 0);
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setIPv6Enabled:(BOOL)flag
{
// Note: YES means kIPv6Disabled is OFF
dispatch_block_t block = ^{
LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO"));
if (flag)
config &= ~kIPv6Disabled;
else
config |= kIPv6Disabled;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (BOOL)isIPv4Preferred
{
__block BOOL result = NO;
dispatch_block_t block = ^{
result = (config & kPreferIPv4) ? YES : NO;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (BOOL)isIPv6Preferred
{
__block BOOL result = NO;
dispatch_block_t block = ^{
result = (config & kPreferIPv6) ? YES : NO;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (BOOL)isIPVersionNeutral
{
__block BOOL result = NO;
dispatch_block_t block = ^{
result = (config & (kPreferIPv4 | kPreferIPv6)) == 0;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setPreferIPv4
{
dispatch_block_t block = ^{
LogTrace();
config |= kPreferIPv4;
config &= ~kPreferIPv6;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (void)setPreferIPv6
{
dispatch_block_t block = ^{
LogTrace();
config &= ~kPreferIPv4;
config |= kPreferIPv6;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (void)setIPVersionNeutral
{
dispatch_block_t block = ^{
LogTrace();
config &= ~kPreferIPv4;
config &= ~kPreferIPv6;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (uint16_t)maxReceiveIPv4BufferSize
{
__block uint16_t result = 0;
dispatch_block_t block = ^{
result = max4ReceiveSize;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setMaxReceiveIPv4BufferSize:(uint16_t)max
{
dispatch_block_t block = ^{
LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max);
max4ReceiveSize = max;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (uint32_t)maxReceiveIPv6BufferSize
{
__block uint32_t result = 0;
dispatch_block_t block = ^{
result = max6ReceiveSize;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setMaxReceiveIPv6BufferSize:(uint32_t)max
{
dispatch_block_t block = ^{
LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max);
max6ReceiveSize = max;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
- (id)userData
{
__block id result = nil;
dispatch_block_t block = ^{
result = userData;
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
return result;
}
- (void)setUserData:(id)arbitraryUserData
{
dispatch_block_t block = ^{
if (userData != arbitraryUserData)
{
userData = arbitraryUserData;
}
};
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_async(socketQueue, block);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Delegate Helpers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)notifyDidConnectToAddress:(NSData *)anAddress
{
LogTrace();
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didConnectToAddress:)])
{
NSData *address = [anAddress copy]; // In case param is NSMutableData
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocket:self didConnectToAddress:address];
}});
}
}
- (void)notifyDidNotConnect:(NSError *)error
{
LogTrace();
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotConnect:)])
{
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocket:self didNotConnect:error];
}});
}
}
- (void)notifyDidSendDataWithTag:(long)tag
{
LogTrace();
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didSendDataWithTag:)])
{
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocket:self didSendDataWithTag:tag];
}});
}
}
- (void)notifyDidNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
LogTrace();
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotSendDataWithTag:dueToError:)])
{
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocket:self didNotSendDataWithTag:tag dueToError:error];
}});
}
}
- (void)notifyDidReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)context
{
LogTrace();
SEL selector = @selector(udpSocket:didReceiveData:fromAddress:withFilterContext:);
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:selector])
{
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocket:self didReceiveData:data fromAddress:address withFilterContext:context];
}});
}
}
- (void)notifyDidCloseWithError:(NSError *)error
{
LogTrace();
__strong id theDelegate = delegate;
if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocketDidClose:withError:)])
{
dispatch_async(delegateQueue, ^{ @autoreleasepool {
[theDelegate udpSocketDidClose:self withError:error];
}});
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Errors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSError *)badConfigError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];