-
Notifications
You must be signed in to change notification settings - Fork 8
/
AsyncUdpSocket.m
2343 lines (1959 loc) · 64.8 KB
/
AsyncUdpSocket.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
//
// AsyncUdpSocket.m
//
// This class is in the public domain.
// Originally created by Robbie Hanson on Wed Oct 01 2008.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import "AsyncUdpSocket.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <netdb.h>
#if TARGET_OS_IPHONE
// Note: You may need to add the CFNetwork Framework to your project
#import <CFNetwork/CFNetwork.h>
#endif
#define SENDQUEUE_CAPACITY 5 // Initial capacity
#define RECEIVEQUEUE_CAPACITY 5 // Initial capacity
#define DEFAULT_MAX_RECEIVE_BUFFER_SIZE 9216
NSString *const AsyncUdpSocketException = @"AsyncUdpSocketException";
NSString *const AsyncUdpSocketErrorDomain = @"AsyncUdpSocketErrorDomain";
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Mutex lock used by all instances of AsyncUdpSocket, to protect getaddrinfo.
// Prior to Mac OS X 10.5 this method was not thread-safe.
static NSString *getaddrinfoLock = @"lock";
#endif
enum AsyncUdpSocketFlags
{
kDidBind = 1 << 0, // If set, bind has been called.
kDidConnect = 1 << 1, // If set, connect has been called.
kSock4CanAcceptBytes = 1 << 2, // If set, we know socket4 can accept bytes. If unset, it's unknown.
kSock6CanAcceptBytes = 1 << 3, // If set, we know socket6 can accept bytes. If unset, it's unknown.
kSock4HasBytesAvailable = 1 << 4, // If set, we know socket4 has bytes available. If unset, it's unknown.
kSock6HasBytesAvailable = 1 << 5, // If set, we know socket6 has bytes available. If unset, it's unknown.
kForbidSendReceive = 1 << 6, // If set, no new send or receive operations are allowed to be queued.
kCloseAfterSends = 1 << 7, // If set, close as soon as no more sends are queued.
kCloseAfterReceives = 1 << 8, // If set, close as soon as no more receives are queued.
kDidClose = 1 << 9, // If set, the socket has been closed, and should not be used anymore.
kDequeueSendScheduled = 1 << 10, // If set, a maybeDequeueSend operation is already scheduled.
kDequeueReceiveScheduled = 1 << 11, // If set, a maybeDequeueReceive operation is already scheduled.
kFlipFlop = 1 << 12, // Used to alternate between IPv4 and IPv6 sockets.
};
@interface AsyncUdpSocket (Private)
// Run Loop
- (void)runLoopAddSource:(CFRunLoopSourceRef)source;
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source;
- (void)runLoopAddTimer:(NSTimer *)timer;
- (void)runLoopRemoveTimer:(NSTimer *)timer;
// Utilities
- (NSString *)addressHost4:(struct sockaddr_in *)pSockaddr4;
- (NSString *)addressHost6:(struct sockaddr_in6 *)pSockaddr6;
- (NSString *)addressHost:(struct sockaddr *)pSockaddr;
// Disconnect Implementation
- (void)emptyQueues;
- (void)closeSocket4;
- (void)closeSocket6;
- (void)maybeScheduleClose;
// Errors
- (NSError *)getErrnoError;
- (NSError *)getSocketError;
- (NSError *)getIPv4UnavailableError;
- (NSError *)getIPv6UnavailableError;
- (NSError *)getSendTimeoutError;
- (NSError *)getReceiveTimeoutError;
// Diagnostics
- (NSString *)connectedHost:(CFSocketRef)socket;
- (UInt16)connectedPort:(CFSocketRef)socket;
- (NSString *)localHost:(CFSocketRef)socket;
- (UInt16)localPort:(CFSocketRef)socket;
// Sending
- (BOOL)canAcceptBytes:(CFSocketRef)sockRef;
- (void)scheduleDequeueSend;
- (void)maybeDequeueSend;
- (void)doSend:(CFSocketRef)sockRef;
- (void)completeCurrentSend;
- (void)failCurrentSend:(NSError *)error;
- (void)endCurrentSend;
- (void)doSendTimeout:(NSTimer *)timer;
// Receiving
- (BOOL)hasBytesAvailable:(CFSocketRef)sockRef;
- (void)scheduleDequeueReceive;
- (void)maybeDequeueReceive;
- (void)doReceive4;
- (void)doReceive6;
- (void)doReceive:(CFSocketRef)sockRef;
- (BOOL)maybeCompleteCurrentReceive;
- (void)failCurrentReceive:(NSError *)error;
- (void)endCurrentReceive;
- (void)doReceiveTimeout:(NSTimer *)timer;
@end
static void MyCFSocketCallback(CFSocketRef, CFSocketCallBackType, CFDataRef, const void *, void *);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncSendPacket encompasses the instructions for a single send/write.
**/
@interface AsyncSendPacket : NSObject
{
@public
NSData *buffer;
NSData *address;
NSTimeInterval timeout;
long tag;
}
- (id)initWithData:(NSData *)d address:(NSData *)a timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncSendPacket
- (id)initWithData:(NSData *)d address:(NSData *)a timeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
buffer = [d retain];
address = [a retain];
timeout = t;
tag = i;
}
return self;
}
- (void)dealloc
{
[buffer release];
[address release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncReceivePacket encompasses the instructions for a single receive/read.
**/
@interface AsyncReceivePacket : NSObject
{
@public
NSTimeInterval timeout;
long tag;
NSMutableData *buffer;
NSString *host;
UInt16 port;
}
- (id)initWithTimeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncReceivePacket
- (id)initWithTimeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
timeout = t;
tag = i;
buffer = nil;
host = nil;
port = 0;
}
return self;
}
- (void)dealloc
{
[buffer release];
[host release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation AsyncUdpSocket
- (id)initWithDelegate:(id)delegate userData:(long)userData enableIPv4:(BOOL)enableIPv4 enableIPv6:(BOOL)enableIPv6
{
if((self = [super init]))
{
theFlags = 0;
theDelegate = delegate;
theUserData = userData;
maxReceiveBufferSize = DEFAULT_MAX_RECEIVE_BUFFER_SIZE;
theSendQueue = [[NSMutableArray alloc] initWithCapacity:SENDQUEUE_CAPACITY];
theCurrentSend = nil;
theSendTimer = nil;
theReceiveQueue = [[NSMutableArray alloc] initWithCapacity:RECEIVEQUEUE_CAPACITY];
theCurrentReceive = nil;
theReceiveTimer = nil;
// Socket context
theContext.version = 0;
theContext.info = self;
theContext.retain = nil;
theContext.release = nil;
theContext.copyDescription = nil;
// Create the sockets
theSocket4 = NULL;
theSocket6 = NULL;
if(enableIPv4)
{
theSocket4 = CFSocketCreate(kCFAllocatorDefault,
PF_INET,
SOCK_DGRAM,
IPPROTO_UDP,
kCFSocketReadCallBack | kCFSocketWriteCallBack,
(CFSocketCallBack)&MyCFSocketCallback,
&theContext);
}
if(enableIPv6)
{
theSocket6 = CFSocketCreate(kCFAllocatorDefault,
PF_INET6,
SOCK_DGRAM,
IPPROTO_UDP,
kCFSocketReadCallBack | kCFSocketWriteCallBack,
(CFSocketCallBack)&MyCFSocketCallback,
&theContext);
}
// Disable continuous callbacks for read and write.
// If we don't do this, the socket(s) will just sit there firing read callbacks
// at us hundreds of times a second if we don't immediately read the available data.
if(theSocket4)
{
CFSocketSetSocketFlags(theSocket4, kCFSocketCloseOnInvalidate);
}
if(theSocket6)
{
CFSocketSetSocketFlags(theSocket6, kCFSocketCloseOnInvalidate);
}
// Get the CFRunLoop to which the socket should be attached.
theRunLoop = CFRunLoopGetCurrent();
// Set default run loop modes
theRunLoopModes = [[NSArray arrayWithObject:NSDefaultRunLoopMode] retain];
// Attach the sockets to the run loop
if(theSocket4)
{
theSource4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, theSocket4, 0);
[self runLoopAddSource:theSource4];
}
if(theSocket6)
{
theSource6 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, theSocket6, 0);
[self runLoopAddSource:theSource6];
}
cachedLocalPort = 0;
cachedConnectedPort = 0;
}
return self;
}
- (id)init
{
return [self initWithDelegate:nil userData:0 enableIPv4:YES enableIPv6:YES];
}
- (id)initWithDelegate:(id)delegate
{
return [self initWithDelegate:delegate userData:0 enableIPv4:YES enableIPv6:YES];
}
- (id)initWithDelegate:(id)delegate userData:(long)userData
{
return [self initWithDelegate:delegate userData:userData enableIPv4:YES enableIPv6:YES];
}
- (id)initIPv4
{
return [self initWithDelegate:nil userData:0 enableIPv4:YES enableIPv6:NO];
}
- (id)initIPv6
{
return [self initWithDelegate:nil userData:0 enableIPv4:NO enableIPv6:YES];
}
- (void) dealloc
{
[self close];
[theSendQueue release];
[theReceiveQueue release];
[theRunLoopModes release];
[cachedLocalHost release];
[cachedConnectedHost release];
[NSObject cancelPreviousPerformRequestsWithTarget:theDelegate selector:@selector(onUdpSocketDidClose:) object:self];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)delegate
{
return theDelegate;
}
- (void)setDelegate:(id)delegate
{
theDelegate = delegate;
}
- (long)userData
{
return theUserData;
}
- (void)setUserData:(long)userData
{
theUserData = userData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Run Loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)runLoopAddSource:(CFRunLoopSourceRef)source
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopAddSource(theRunLoop, source, runLoopMode);
}
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopRemoveSource(theRunLoop, source, runLoopMode);
}
}
- (void)runLoopAddTimer:(NSTimer *)timer
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopAddTimer(theRunLoop, (CFRunLoopTimerRef)timer, runLoopMode);
}
}
- (void)runLoopRemoveTimer:(NSTimer *)timer
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFRunLoopRemoveTimer(theRunLoop, (CFRunLoopTimerRef)timer, runLoopMode);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (UInt32)maxReceiveBufferSize
{
return maxReceiveBufferSize;
}
- (void)setMaxReceiveBufferSize:(UInt32)max
{
maxReceiveBufferSize = max;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"moveToRunLoop must be called from within the current RunLoop!");
if(runLoop == nil)
{
return NO;
}
if(theRunLoop == [runLoop getCFRunLoop])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueSendScheduled;
theFlags &= ~kDequeueReceiveScheduled;
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theSendTimer retain];
[theReceiveTimer retain];
if(theSendTimer) [self runLoopRemoveTimer:theSendTimer];
if(theReceiveTimer) [self runLoopRemoveTimer:theReceiveTimer];
theRunLoop = [runLoop getCFRunLoop];
if(theSendTimer) [self runLoopAddTimer:theSendTimer];
if(theReceiveTimer) [self runLoopAddTimer:theReceiveTimer];
// Release timers since we retained them above
[theSendTimer release];
[theReceiveTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
[runLoop performSelector:@selector(maybeDequeueSend) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeDequeueReceive) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeScheduleClose) target:self argument:nil order:0 modes:theRunLoopModes];
return YES;
}
/**
* See the header file for a full explanation of this method.
**/
- (BOOL)setRunLoopModes:(NSArray *)runLoopModes
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"setRunLoopModes must be called from within the current RunLoop!");
if([runLoopModes count] == 0)
{
return NO;
}
if([theRunLoopModes isEqualToArray:runLoopModes])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueSendScheduled;
theFlags &= ~kDequeueReceiveScheduled;
if(theSource4) [self runLoopRemoveSource:theSource4];
if(theSource6) [self runLoopRemoveSource:theSource6];
// We do not retain the timers - they get retained by the runloop when we add them as a source.
// Since we're about to remove them as a source, we retain now, and release again below.
[theSendTimer retain];
[theReceiveTimer retain];
if(theSendTimer) [self runLoopRemoveTimer:theSendTimer];
if(theReceiveTimer) [self runLoopRemoveTimer:theReceiveTimer];
[theRunLoopModes release];
theRunLoopModes = [runLoopModes copy];
if(theSendTimer) [self runLoopAddTimer:theSendTimer];
if(theReceiveTimer) [self runLoopAddTimer:theReceiveTimer];
// Release timers since we retained them above
[theSendTimer release];
[theReceiveTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
[self performSelector:@selector(maybeDequeueSend) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueReceive) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleClose) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (NSArray *)runLoopModes
{
return [[theRunLoopModes retain] autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Utilities:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Attempts to convert the given host/port into and IPv4 and/or IPv6 data structure.
* The data structure is of type sockaddr_in for IPv4 and sockaddr_in6 for IPv6.
*
* Returns zero on success, or one of the error codes listed in gai_strerror if an error occurs (as per getaddrinfo).
**/
- (int)convertForBindHost:(NSString *)host
port:(UInt16)port
intoAddress4:(NSData **)address4
address6:(NSData **)address6
{
if(host == nil || ([host length] == 0))
{
// Use ANY address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_any;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else if([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
{
// Note: getaddrinfo("localhost",...) fails on 10.5.3
// Use LOOPBACK address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
@synchronized (getaddrinfoLock)
#endif
{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
int error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
if(error) return error;
for(res = res0; res; res = res->ai_next)
{
if(address4 && !*address4 && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if(address6 && !*address6 && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structures for CFSocketSetAddress.
if(address6) *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
}
return 0;
}
}
/**
* Attempts to convert the given host/port into and IPv4 and/or IPv6 data structure.
* The data structure is of type sockaddr_in for IPv4 and sockaddr_in6 for IPv6.
*
* Returns zero on success, or one of the error codes listed in gai_strerror if an error occurs (as per getaddrinfo).
**/
- (int)convertForSendHost:(NSString *)host
port:(UInt16)port
intoAddress4:(NSData **)address4
address6:(NSData **)address6
{
if(host == nil || ([host length] == 0))
{
// We're not binding, so what are we supposed to do with this?
return EAI_NONAME;
}
else if([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
{
// Note: getaddrinfo("localhost",...) fails on 10.5.3
// Use LOOPBACK address
struct sockaddr_in nativeAddr;
nativeAddr.sin_len = sizeof(struct sockaddr_in);
nativeAddr.sin_family = AF_INET;
nativeAddr.sin_port = htons(port);
nativeAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(nativeAddr.sin_zero), 0, sizeof(nativeAddr.sin_zero));
struct sockaddr_in6 nativeAddr6;
nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
nativeAddr6.sin6_family = AF_INET6;
nativeAddr6.sin6_port = htons(port);
nativeAddr6.sin6_flowinfo = 0;
nativeAddr6.sin6_addr = in6addr_loopback;
nativeAddr6.sin6_scope_id = 0;
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:&nativeAddr length:sizeof(nativeAddr)];
if(address6) *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
return 0;
}
else
{
NSString *portStr = [NSString stringWithFormat:@"%hu", port];
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
@synchronized (getaddrinfoLock)
#endif
{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
// No passive flag on a send or connect
int error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
if(error) return error;
for(res = res0; res; res = res->ai_next)
{
if(address4 && !*address4 && (res->ai_family == AF_INET))
{
// Found IPv4 address
// Wrap the native address structures for CFSocketSetAddress.
if(address4) *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
else if(address6 && !*address6 && (res->ai_family == AF_INET6))
{
// Found IPv6 address
// Wrap the native address structures for CFSocketSetAddress.
if(address6) *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
}
}
freeaddrinfo(res0);
}
return 0;
}
}
- (NSString *)addressHost4:(struct sockaddr_in *)pSockaddr4
{
char addrBuf[INET_ADDRSTRLEN];
if(inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (NSString *)addressHost6:(struct sockaddr_in6 *)pSockaddr6
{
char addrBuf[INET6_ADDRSTRLEN];
if(inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, sizeof(addrBuf)) == NULL)
{
[NSException raise:NSInternalInconsistencyException format:@"Cannot convert address to string."];
}
return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
}
- (NSString *)addressHost:(struct sockaddr *)pSockaddr
{
if(pSockaddr->sa_family == AF_INET)
{
return [self addressHost4:(struct sockaddr_in *)pSockaddr];
}
else
{
return [self addressHost6:(struct sockaddr_in6 *)pSockaddr];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Implementation:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Binds the underlying socket(s) to the given port.
* The socket(s) will be able to receive data on any interface.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)bindToPort:(UInt16)port error:(NSError **)errPtr
{
return [self bindToAddress:nil port:port error:errPtr];
}
/**
* Binds the underlying socket(s) to the given address and port.
* The sockets(s) will be able to receive data only on the given interface.
*
* To receive data on any interface, pass nil or "".
* To receive data only on the loopback interface, pass "localhost" or "loopback".
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)bindToAddress:(NSString *)host port:(UInt16)port error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidBind)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot bind a socket more than once."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot bind after connecting. If needed, bind first, then connect."];
}
// Convert the given host/port into native address structures for CFSocketSetAddress
NSData *address4 = nil, *address6 = nil;
int gai_error = [self convertForBindHost:host port:port intoAddress4:&address4 address6:&address6];
if(gai_error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding];
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:info];
}
return NO;
}
NSAssert((address4 || address6), @"address4 and address6 are nil");
// Set the SO_REUSEADDR flags
int reuseOn = 1;
if (theSocket4) setsockopt(CFSocketGetNative(theSocket4), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
if (theSocket6) setsockopt(CFSocketGetNative(theSocket6), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
// Bind the sockets
if(address4)
{
if(theSocket4)
{
CFSocketError error = CFSocketSetAddress(theSocket4, (CFDataRef)address4);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
if(!address6)
{
// Using IPv4 only
[self closeSocket6];
}
}
else if(!address6)
{
if(errPtr) *errPtr = [self getIPv4UnavailableError];
return NO;
}
}
if(address6)
{
// Note: The iPhone doesn't currently support IPv6
if(theSocket6)
{
CFSocketError error = CFSocketSetAddress(theSocket6, (CFDataRef)address6);
if(error != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
if(!address4)
{
// Using IPv6 only
[self closeSocket4];
}
}
else if(!address4)
{
if(errPtr) *errPtr = [self getIPv6UnavailableError];
return NO;
}
}
theFlags |= kDidBind;
return YES;
}
/**
* Connects the underlying UDP socket to the given host and port.
* If an IPv4 address is resolved, the IPv4 socket is connected, and the IPv6 socket is invalidated and released.
* If an IPv6 address is resolved, the IPv6 socket is connected, and the IPv4 socket is invalidated and released.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)connectToHost:(NSString *)host onPort:(UInt16)port error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot connect a socket more than once."];
}
// Convert the given host/port into native address structures for CFSocketSetAddress
NSData *address4 = nil, *address6 = nil;
int error = [self convertForSendHost:host port:port intoAddress4:&address4 address6:&address6];
if(error)
{
if(errPtr)
{
NSString *errMsg = [NSString stringWithCString:gai_strerror(error) encoding:NSASCIIStringEncoding];
NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:error userInfo:info];
}
return NO;
}
NSAssert((address4 || address6), @"address4 and address6 are nil");
// We only want to connect via a single interface.
// IPv4 is currently preferred, but this may change in the future.
if(address4)
{
if(theSocket4)
{
CFSocketError sockErr = CFSocketConnectToAddress(theSocket4, (CFDataRef)address4, (CFTimeInterval)0.0);
if(sockErr != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv4 address, so no need for the IPv6 socket
[self closeSocket6];
return YES;
}
else if(!address6)
{
if(errPtr) *errPtr = [self getIPv4UnavailableError];
return NO;
}
}
if(address6)
{
// Note: The iPhone doesn't currently support IPv6
if(theSocket6)
{
CFSocketError sockErr = CFSocketConnectToAddress(theSocket6, (CFDataRef)address6, (CFTimeInterval)0.0);
if(sockErr != kCFSocketSuccess)
{
if(errPtr) *errPtr = [self getSocketError];
return NO;
}
theFlags |= kDidConnect;
// We're connected to an IPv6 address, so no need for the IPv4 socket
[self closeSocket4];
return YES;
}
else
{
if(errPtr) *errPtr = [self getIPv6UnavailableError];
return NO;
}
}
// It shouldn't be possible to get to this point because either address4 or address6 was non-nil.
if(errPtr) *errPtr = nil;
return NO;
}
/**
* Connects the underlying UDP socket to the remote address.
* If the address is an IPv4 address, the IPv4 socket is connected, and the IPv6 socket is invalidated and released.
* If the address is an IPv6 address, the IPv6 socket is connected, and the IPv4 socket is invalidated and released.
*
* The address is a native address structure, as may be returned from API's such as Bonjour.
* An address may be created manually by simply wrapping a sockaddr_in or sockaddr_in6 in an NSData object.
*
* On success, returns YES.
* Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
**/
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
{
if(theFlags & kDidClose)
{
[NSException raise:AsyncUdpSocketException
format:@"The socket is closed."];
}
if(theFlags & kDidConnect)
{
[NSException raise:AsyncUdpSocketException
format:@"Cannot connect a socket more than once."];
}
// Is remoteAddr an IPv4 address?
if([remoteAddr length] == sizeof(struct sockaddr_in))
{
if(theSocket4)
{
CFSocketError error = CFSocketConnectToAddress(theSocket4, (CFDataRef)remoteAddr, (CFTimeInterval)0.0);
if(error != kCFSocketSuccess)
{