This repository has been archived by the owner on Dec 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
AsyncSocket.m
4005 lines (3308 loc) · 115 KB
/
AsyncSocket.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
//
// AsyncSocket.m
//
// This class is in the public domain.
// Originally created by Dustin Voss on Wed Jan 29 2003.
// Updated and maintained by Deusty Designs and the Mac development community.
//
// http://code.google.com/p/cocoaasyncsocket/
//
#import "AsyncSocket.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.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
#pragma mark Declarations
#define DEFAULT_PREBUFFERING YES // Whether pre-buffering is enabled by default
#define READQUEUE_CAPACITY 5 // Initial capacity
#define WRITEQUEUE_CAPACITY 5 // Initial capacity
#define READALL_CHUNKSIZE 256 // Incremental increase in buffer size
#define WRITE_CHUNKSIZE (1024 * 4) // Limit on size of each write pass
NSString *const AsyncSocketException = @"AsyncSocketException";
NSString *const AsyncSocketErrorDomain = @"AsyncSocketErrorDomain";
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Mutex lock used by all instances of AsyncSocket, to protect getaddrinfo.
// Prior to Mac OS X 10.5 this method was not thread-safe.
static NSString *getaddrinfoLock = @"lock";
#endif
enum AsyncSocketFlags
{
kEnablePreBuffering = 1 << 0, // If set, pre-buffering is enabled
kDidStartDelegate = 1 << 1, // If set, disconnection results in delegate call
kDidCompleteOpenForRead = 1 << 2, // If set, open callback has been called for read stream
kDidCompleteOpenForWrite = 1 << 3, // If set, open callback has been called for write stream
kStartingReadTLS = 1 << 4, // If set, we're waiting for TLS negotiation to complete
kStartingWriteTLS = 1 << 5, // If set, we're waiting for TLS negotiation to complete
kForbidReadsWrites = 1 << 6, // If set, no new reads or writes are allowed
kDisconnectAfterReads = 1 << 7, // If set, disconnect after no more reads are queued
kDisconnectAfterWrites = 1 << 8, // If set, disconnect after no more writes are queued
kClosingWithError = 1 << 9, // If set, the socket is being closed due to an error
kDequeueReadScheduled = 1 << 10, // If set, a maybeDequeueRead operation is already scheduled
kDequeueWriteScheduled = 1 << 11, // If set, a maybeDequeueWrite operation is already scheduled
kSocketCanAcceptBytes = 1 << 12, // If set, we know socket can accept bytes. If unset, it's unknown.
kSocketHasBytesAvailable = 1 << 13, // If set, we know socket has bytes available. If unset, it's unknown.
};
@interface AsyncSocket (Private)
// Connecting
- (void)startConnectTimeout:(NSTimeInterval)timeout;
- (void)endConnectTimeout;
// Socket Implementation
- (CFSocketRef)newAcceptSocketForAddress:(NSData *)addr error:(NSError **)errPtr;
- (BOOL)createSocketForAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
- (BOOL)bindSocketToAddress:(NSData *)interfaceAddr error:(NSError **)errPtr;
- (BOOL)attachSocketsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr;
- (BOOL)configureSocketAndReturnError:(NSError **)errPtr;
- (BOOL)connectSocketToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
- (void)doAcceptWithSocket:(CFSocketNativeHandle)newSocket;
- (void)doSocketOpen:(CFSocketRef)sock withCFSocketError:(CFSocketError)err;
// Stream Implementation
- (BOOL)createStreamsFromNative:(CFSocketNativeHandle)native error:(NSError **)errPtr;
- (BOOL)createStreamsToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)attachStreamsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr;
- (BOOL)configureStreamsAndReturnError:(NSError **)errPtr;
- (BOOL)openStreamsAndReturnError:(NSError **)errPtr;
- (void)doStreamOpen;
- (BOOL)setSocketFromStreamsAndReturnError:(NSError **)errPtr;
// Disconnect Implementation
- (void)closeWithError:(NSError *)err;
- (void)recoverUnreadData;
- (void)emptyQueues;
- (void)close;
// Errors
- (NSError *)getErrnoError;
- (NSError *)getAbortError;
- (NSError *)getStreamError;
- (NSError *)getSocketError;
- (NSError *)getConnectTimeoutError;
- (NSError *)getReadMaxedOutError;
- (NSError *)getReadTimeoutError;
- (NSError *)getWriteTimeoutError;
- (NSError *)errorFromCFStreamError:(CFStreamError)err;
// Diagnostics
- (BOOL)isDisconnected;
- (BOOL)areStreamsConnected;
- (NSString *)connectedHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)connectedHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)connectedHostFromCFSocket4:(CFSocketRef)socket;
- (NSString *)connectedHostFromCFSocket6:(CFSocketRef)socket;
- (UInt16)connectedPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)connectedPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)connectedPortFromCFSocket4:(CFSocketRef)socket;
- (UInt16)connectedPortFromCFSocket6:(CFSocketRef)socket;
- (NSString *)localHostFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)localHostFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (NSString *)localHostFromCFSocket4:(CFSocketRef)socket;
- (NSString *)localHostFromCFSocket6:(CFSocketRef)socket;
- (UInt16)localPortFromNativeSocket4:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)localPortFromNativeSocket6:(CFSocketNativeHandle)theNativeSocket;
- (UInt16)localPortFromCFSocket4:(CFSocketRef)socket;
- (UInt16)localPortFromCFSocket6:(CFSocketRef)socket;
- (NSString *)hostFromAddress4:(struct sockaddr_in *)pSockaddr4;
- (NSString *)hostFromAddress6:(struct sockaddr_in6 *)pSockaddr6;
- (UInt16)portFromAddress4:(struct sockaddr_in *)pSockaddr4;
- (UInt16)portFromAddress6:(struct sockaddr_in6 *)pSockaddr6;
// Reading
- (void)doBytesAvailable;
- (void)completeCurrentRead;
- (void)endCurrentRead;
- (void)scheduleDequeueRead;
- (void)maybeDequeueRead;
- (void)doReadTimeout:(NSTimer *)timer;
// Writing
- (void)doSendBytes;
- (void)completeCurrentWrite;
- (void)endCurrentWrite;
- (void)scheduleDequeueWrite;
- (void)maybeDequeueWrite;
- (void)maybeScheduleDisconnect;
- (void)doWriteTimeout:(NSTimer *)timer;
// Run Loop
- (void)runLoopAddSource:(CFRunLoopSourceRef)source;
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source;
- (void)runLoopAddTimer:(NSTimer *)timer;
- (void)runLoopRemoveTimer:(NSTimer *)timer;
- (void)runLoopUnscheduleReadStream;
- (void)runLoopUnscheduleWriteStream;
// Security
- (void)maybeStartTLS;
- (void)onTLSHandshakeSuccessful;
// Callbacks
- (void)doCFCallback:(CFSocketCallBackType)type
forSocket:(CFSocketRef)sock withAddress:(NSData *)address withData:(const void *)pData;
- (void)doCFReadStreamCallback:(CFStreamEventType)type forStream:(CFReadStreamRef)stream;
- (void)doCFWriteStreamCallback:(CFStreamEventType)type forStream:(CFWriteStreamRef)stream;
@end
static void MyCFSocketCallback(CFSocketRef, CFSocketCallBackType, CFDataRef, const void *, void *);
static void MyCFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType type, void *pInfo);
static void MyCFWriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType type, void *pInfo);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncReadPacket encompasses the instructions for any given read.
* The content of a read packet allows the code to determine if we're:
* - reading to a certain length
* - reading to a certain separator
* - or simply reading the first chunk of available data
**/
@interface AsyncReadPacket : NSObject
{
@public
NSMutableData *buffer;
CFIndex startOffset;
CFIndex bytesDone;
CFIndex maxLength;
NSTimeInterval timeout;
CFIndex readLength;
NSData *term;
BOOL bufferOwner;
NSUInteger originalBufferLength;
long tag;
}
- (id)initWithData:(NSMutableData *)d
startOffset:(CFIndex)s
maxLength:(CFIndex)m
timeout:(NSTimeInterval)t
readLength:(CFIndex)l
terminator:(NSData *)e
tag:(long)i;
- (NSUInteger)readLengthForNonTerm;
- (NSUInteger)readLengthForTerm;
- (NSUInteger)prebufferReadLengthForTerm;
- (CFIndex)searchForTermAfterPreBuffering:(CFIndex)numBytes;
@end
@implementation AsyncReadPacket
- (id)initWithData:(NSMutableData *)d
startOffset:(CFIndex)s
maxLength:(CFIndex)m
timeout:(NSTimeInterval)t
readLength:(CFIndex)l
terminator:(NSData *)e
tag:(long)i
{
if((self = [super init]))
{
if (d)
{
buffer = [d retain];
startOffset = s;
bufferOwner = NO;
originalBufferLength = [d length];
}
else
{
if (readLength > 0)
buffer = [[NSMutableData alloc] initWithLength:readLength];
else
buffer = [[NSMutableData alloc] initWithLength:0];
startOffset = 0;
bufferOwner = YES;
originalBufferLength = 0;
}
bytesDone = 0;
maxLength = m;
timeout = t;
readLength = l;
term = [e copy];
tag = i;
}
return self;
}
/**
* For read packets without a set terminator, returns the safe length of data that can be read
* without exceeding the maxLength, or forcing a resize of the buffer if at all possible.
**/
- (NSUInteger)readLengthForNonTerm
{
NSAssert(term == nil, @"This method does not apply to term reads");
if (readLength > 0)
{
// Read a specific length of data
return readLength - bytesDone;
// No need to avoid resizing the buffer.
// It should be resized if the buffer space is less than the requested read length.
}
else
{
// Read all available data
NSUInteger result = READALL_CHUNKSIZE;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
}
/**
* For read packets with a set terminator, returns the safe length of data that can be read
* without going over a terminator, or the maxLength, or forcing a resize of the buffer if at all possible.
*
* It is assumed the terminator has not already been read.
**/
- (NSUInteger)readLengthForTerm
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
// What we're going to do is look for a partial sequence of the terminator at the end of the buffer.
// If a partial sequence occurs, then we must assume the next bytes to arrive will be the rest of the term,
// and we can only read that amount.
// Otherwise, we're safe to read the entire length of the term.
NSUInteger result = [term length];
// Shortcut when term is a single byte
if(result == 1) return result;
// i = index within buffer at which to check data
// j = length of term to check against
// Note: Beware of implicit casting rules
// This could give you -1: MAX(0, (0 - [term length] + 1));
CFIndex i = MAX(0, (CFIndex)(bytesDone - [term length] + 1));
CFIndex j = MIN([term length] - 1, bytesDone);
while(i < bytesDone)
{
void *subBuffer = [buffer mutableBytes] + startOffset + i;
if(memcmp(subBuffer, [term bytes], j) == 0)
{
result = [term length] - j;
break;
}
i++;
j--;
}
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
/**
* Assuming pre-buffering is enabled, returns the amount of data that can be read
* without going over the maxLength.
**/
- (NSUInteger)prebufferReadLengthForTerm
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSUInteger result = READALL_CHUNKSIZE;
if (maxLength > 0)
{
result = MIN(result, (maxLength - bytesDone));
}
if (!bufferOwner)
{
// We did NOT create the buffer.
// It is owned by the caller.
// Avoid resizing the buffer if at all possible.
if ([buffer length] == originalBufferLength)
{
NSUInteger buffSize = [buffer length];
NSUInteger buffSpace = buffSize - startOffset - bytesDone;
if (buffSpace > 0)
{
result = MIN(result, buffSpace);
}
}
}
return result;
}
/**
* For read packets with a set terminator, scans the packet buffer for the term.
* It is assumed the terminator had not been fully read prior to the new bytes.
*
* If the term is found, the number of excess bytes after the term are returned.
* If the term is not found, this method will return -1.
*
* Note: A return value of zero means the term was found at the very end.
**/
- (CFIndex)searchForTermAfterPreBuffering:(CFIndex)numBytes
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
// We try to start the search such that the first new byte read matches up with the last byte of the term.
// We continue searching forward after this until the term no longer fits into the buffer.
// Note: Beware of implicit casting rules
// This could give you -1: MAX(0, 1 - 1 - [term length] + 1);
CFIndex i = MAX(0, (CFIndex)(bytesDone - numBytes - [term length] + 1));
while(i + [term length] <= bytesDone)
{
void *subBuffer = [buffer mutableBytes] + startOffset + i;
if(memcmp(subBuffer, [term bytes], [term length]) == 0)
{
return bytesDone - (i + [term length]);
}
i++;
}
return -1;
}
- (void)dealloc
{
[buffer release];
[term release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncWritePacket encompasses the instructions for any given write.
**/
@interface AsyncWritePacket : NSObject
{
@public
NSData *buffer;
CFIndex bytesDone;
long tag;
NSTimeInterval timeout;
}
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
@end
@implementation AsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
{
if((self = [super init]))
{
buffer = [d retain];
timeout = t;
tag = i;
bytesDone = 0;
}
return self;
}
- (void)dealloc
{
[buffer release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncSpecialPacket encompasses special instructions for interruptions in the read/write queues.
* This class my be altered to support more than just TLS in the future.
**/
@interface AsyncSpecialPacket : NSObject
{
@public
NSDictionary *tlsSettings;
}
- (id)initWithTLSSettings:(NSDictionary *)settings;
@end
@implementation AsyncSpecialPacket
- (id)initWithTLSSettings:(NSDictionary *)settings
{
if((self = [super init]))
{
tlsSettings = [settings copy];
}
return self;
}
- (void)dealloc
{
[tlsSettings release];
[super dealloc];
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation AsyncSocket
- (id)init
{
return [self initWithDelegate:nil userData:0];
}
- (id)initWithDelegate:(id)delegate
{
return [self initWithDelegate:delegate userData:0];
}
// Designated initializer.
- (id)initWithDelegate:(id)delegate userData:(long)userData
{
if((self = [super init]))
{
theFlags = DEFAULT_PREBUFFERING ? kEnablePreBuffering : 0;
theDelegate = delegate;
theUserData = userData;
theNativeSocket4 = 0;
theNativeSocket6 = 0;
theSocket4 = NULL;
theSource4 = NULL;
theSocket6 = NULL;
theSource6 = NULL;
theRunLoop = NULL;
theReadStream = NULL;
theWriteStream = NULL;
theConnectTimer = nil;
theReadQueue = [[NSMutableArray alloc] initWithCapacity:READQUEUE_CAPACITY];
theCurrentRead = nil;
theReadTimer = nil;
partialReadBuffer = [[NSMutableData alloc] initWithCapacity:READALL_CHUNKSIZE];
theWriteQueue = [[NSMutableArray alloc] initWithCapacity:WRITEQUEUE_CAPACITY];
theCurrentWrite = nil;
theWriteTimer = nil;
// Socket context
NSAssert(sizeof(CFSocketContext) == sizeof(CFStreamClientContext), @"CFSocketContext != CFStreamClientContext");
theContext.version = 0;
theContext.info = self;
theContext.retain = nil;
theContext.release = nil;
theContext.copyDescription = nil;
// Default run loop modes
theRunLoopModes = [[NSArray arrayWithObject:NSDefaultRunLoopMode] retain];
}
return self;
}
// The socket may been initialized in a connected state and auto-released, so this should close it down cleanly.
- (void)dealloc
{
[self close];
[theReadQueue release];
[theWriteQueue release];
[theRunLoopModes release];
[partialReadBuffer release];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (long)userData
{
return theUserData;
}
- (void)setUserData:(long)userData
{
theUserData = userData;
}
- (id)delegate
{
return theDelegate;
}
- (void)setDelegate:(id)delegate
{
theDelegate = delegate;
}
- (BOOL)canSafelySetDelegate
{
return ([theReadQueue count] == 0 && [theWriteQueue count] == 0 && theCurrentRead == nil && theCurrentWrite == nil);
}
- (CFSocketRef)getCFSocket
{
if(theSocket4)
return theSocket4;
else
return theSocket6;
}
- (CFReadStreamRef)getCFReadStream
{
return theReadStream;
}
- (CFWriteStreamRef)getCFWriteStream
{
return theWriteStream;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Progress
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (float)progressOfReadReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total
{
// Check to make sure we're actually reading something right now,
// and that the read packet isn't an AsyncSpecialPacket (upgrade to TLS).
if (!theCurrentRead || ![theCurrentRead isKindOfClass:[AsyncReadPacket class]]) return NAN;
// It's only possible to know the progress of our read if we're reading to a certain length.
// If we're reading to data, we of course have no idea when the data will arrive.
// If we're reading to timeout, then we have no idea when the next chunk of data will arrive.
CFIndex d = theCurrentRead->bytesDone;
CFIndex t = theCurrentRead->readLength;
if (tag != NULL) *tag = theCurrentRead->tag;
if (done != NULL) *done = d;
if (total != NULL) *total = t;
if (t > 0.0)
return (float)d / (float)t;
else
return 1.0F;
}
- (float)progressOfWriteReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total
{
// Check to make sure we're actually writing something right now,
// and that the write packet isn't an AsyncSpecialPacket (upgrade to TLS).
if (!theCurrentWrite || ![theCurrentWrite isKindOfClass:[AsyncWritePacket class]]) return NAN;
CFIndex d = theCurrentWrite->bytesDone;
CFIndex t = [theCurrentWrite->buffer length];
if (tag != NULL) *tag = theCurrentWrite->tag;
if (done != NULL) *done = d;
if (total != NULL) *total = t;
return (float)d / (float)t;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#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)runLoopAddSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopAddSource(theRunLoop, source, (CFStringRef)runLoopMode);
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopRemoveSource(theRunLoop, source, (CFStringRef)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);
}
}
- (void)runLoopAddTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopAddTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
- (void)runLoopRemoveTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopRemoveTimer(theRunLoop, (CFRunLoopTimerRef)timer, (CFStringRef)runLoopMode);
}
- (void)runLoopUnscheduleReadStream
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFReadStreamUnscheduleFromRunLoop(theReadStream, theRunLoop, runLoopMode);
}
CFReadStreamSetClient(theReadStream, kCFStreamEventNone, NULL, NULL);
}
- (void)runLoopUnscheduleWriteStream
{
NSUInteger i, count = [theRunLoopModes count];
for(i = 0; i < count; i++)
{
CFStringRef runLoopMode = (CFStringRef)[theRunLoopModes objectAtIndex:i];
CFWriteStreamUnscheduleFromRunLoop(theWriteStream, theRunLoop, runLoopMode);
}
CFWriteStreamSetClient(theWriteStream, kCFStreamEventNone, NULL, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* See the header file for a full explanation of pre-buffering.
**/
- (void)enablePreBuffering
{
theFlags |= kEnablePreBuffering;
}
/**
* 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 &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
if(theReadStream && theWriteStream)
{
[self runLoopUnscheduleReadStream];
[self runLoopUnscheduleWriteStream];
}
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.
[theReadTimer retain];
[theWriteTimer retain];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer];
theRunLoop = [runLoop getCFRunLoop];
if(theReadTimer) [self runLoopAddTimer:theReadTimer];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer];
// Release timers since we retained them above
[theReadTimer release];
[theWriteTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
if(theReadStream && theWriteStream)
{
if(![self attachStreamsToRunLoop:runLoop error:nil])
{
return NO;
}
}
[runLoop performSelector:@selector(maybeDequeueRead) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeDequeueWrite) target:self argument:nil order:0 modes:theRunLoopModes];
[runLoop performSelector:@selector(maybeScheduleDisconnect) 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 &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
if(theReadStream && theWriteStream)
{
[self runLoopUnscheduleReadStream];
[self runLoopUnscheduleWriteStream];
}
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.
[theReadTimer retain];
[theWriteTimer retain];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer];
[theRunLoopModes release];
theRunLoopModes = [runLoopModes copy];
if(theReadTimer) [self runLoopAddTimer:theReadTimer];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer];
// Release timers since we retained them above
[theReadTimer release];
[theWriteTimer release];
if(theSource4) [self runLoopAddSource:theSource4];
if(theSource6) [self runLoopAddSource:theSource6];
if(theReadStream && theWriteStream)
{
// Note: theRunLoop variable is a CFRunLoop, and NSRunLoop is NOT toll-free bridged with CFRunLoop.
// So we cannot pass theRunLoop to the method below, which is expecting a NSRunLoop parameter.
// Instead we pass nil, which will result in the method properly using the current run loop.
if(![self attachStreamsToRunLoop:nil error:nil])
{
return NO;
}
}
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleDisconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (BOOL)addRunLoopMode:(NSString *)runLoopMode
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"addRunLoopMode must be called from within the current RunLoop!");
if(runLoopMode == nil)
{
return NO;
}
if([theRunLoopModes containsObject:runLoopMode])
{
return YES;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
NSArray *newRunLoopModes = [theRunLoopModes arrayByAddingObject:runLoopMode];
[theRunLoopModes release];
theRunLoopModes = [newRunLoopModes retain];
if(theReadTimer) [self runLoopAddTimer:theReadTimer mode:runLoopMode];
if(theWriteTimer) [self runLoopAddTimer:theWriteTimer mode:runLoopMode];
if(theSource4) [self runLoopAddSource:theSource4 mode:runLoopMode];
if(theSource6) [self runLoopAddSource:theSource6 mode:runLoopMode];
if(theReadStream && theWriteStream)
{
CFReadStreamScheduleWithRunLoop(theReadStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
CFWriteStreamScheduleWithRunLoop(theWriteStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
}
[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0 inModes:theRunLoopModes];
[self performSelector:@selector(maybeScheduleDisconnect) withObject:nil afterDelay:0 inModes:theRunLoopModes];
return YES;
}
- (BOOL)removeRunLoopMode:(NSString *)runLoopMode
{
NSAssert((theRunLoop == NULL) || (theRunLoop == CFRunLoopGetCurrent()),
@"addRunLoopMode must be called from within the current RunLoop!");
if(runLoopMode == nil)
{
return NO;
}
if(![theRunLoopModes containsObject:runLoopMode])
{
return YES;
}
NSMutableArray *newRunLoopModes = [[theRunLoopModes mutableCopy] autorelease];
[newRunLoopModes removeObject:runLoopMode];
if([newRunLoopModes count] == 0)
{
return NO;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self];
theFlags &= ~kDequeueReadScheduled;
theFlags &= ~kDequeueWriteScheduled;
[theRunLoopModes release];
theRunLoopModes = [newRunLoopModes copy];
if(theReadTimer) [self runLoopRemoveTimer:theReadTimer mode:runLoopMode];
if(theWriteTimer) [self runLoopRemoveTimer:theWriteTimer mode:runLoopMode];
if(theSource4) [self runLoopRemoveSource:theSource4 mode:runLoopMode];
if(theSource6) [self runLoopRemoveSource:theSource6 mode:runLoopMode];
if(theReadStream && theWriteStream)
{
CFReadStreamScheduleWithRunLoop(theReadStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);
CFWriteStreamScheduleWithRunLoop(theWriteStream, CFRunLoopGetCurrent(), (CFStringRef)runLoopMode);