-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncSocket.m
4313 lines (3542 loc) · 121 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/
//
#if ! __has_feature(objc_arc)
#warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif
#import "AsyncSocket.h"
#import <TargetConditionals.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
// AsyncSocket is RunLoop based, and is thus not thread-safe.
// You must always access your AsyncSocket instance from the thread/runloop in which the instance is running.
// You can use methods such as performSelectorOnThread to accomplish this.
// Failure to comply with these thread-safety rules may result in errors.
// You can enable this option to help diagnose where you are incorrectly accessing your socket.
#if DEBUG
#define DEBUG_THREAD_SAFETY 1
#else
#define DEBUG_THREAD_SAFETY 0
#endif
//
// If you constantly need to access your socket from multiple threads
// then you may consider using GCDAsyncSocket instead, which is thread-safe.
NSString *const AsyncSocketException = @"AsyncSocketException";
NSString *const AsyncSocketErrorDomain = @"AsyncSocketErrorDomain";
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;
- (void)doConnectTimeout:(NSTimer *)timer;
// 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;
NSUInteger startOffset;
NSUInteger bytesDone;
NSUInteger maxLength;
NSTimeInterval timeout;
NSUInteger readLength;
NSData *term;
BOOL bufferOwner;
NSUInteger originalBufferLength;
long tag;
}
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i;
- (NSUInteger)readLengthForNonTerm;
- (NSUInteger)readLengthForTerm;
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr;
- (NSUInteger)prebufferReadLengthForTerm;
- (NSInteger)searchForTermAfterPreBuffering:(NSUInteger)numBytes;
@end
@implementation AsyncReadPacket
- (id)initWithData:(NSMutableData *)d
startOffset:(NSUInteger)s
maxLength:(NSUInteger)m
timeout:(NSTimeInterval)t
readLength:(NSUInteger)l
terminator:(NSData *)e
tag:(long)i
{
if((self = [super init]))
{
if (d)
{
buffer = d;
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 termLength = [term length];
// Shortcuts
if (bytesDone == 0) return termLength;
if (termLength == 1) return termLength;
// i = index within buffer at which to check data
// j = length of term to check against
NSUInteger i, j;
if (bytesDone >= termLength)
{
i = bytesDone - termLength + 1;
j = termLength - 1;
}
else
{
i = 0;
j = bytesDone;
}
NSUInteger result = termLength;
void *buf = [buffer mutableBytes];
const void *termBuf = [term bytes];
while (i < bytesDone)
{
void *subbuf = buf + startOffset + i;
if (memcmp(subbuf, termBuf, j) == 0)
{
result = termLength - 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;
}
/**
* For read packets with a set terminator,
* returns the safe length of data that can be read from the given preBuffer,
* without going over a terminator or the maxLength.
*
* It is assumed the terminator has not already been read.
**/
- (NSUInteger)readLengthForTermWithPreBuffer:(NSData *)preBuffer found:(BOOL *)foundPtr
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert([preBuffer length] > 0, @"Invoked with empty pre buffer!");
// We know that the terminator, as a whole, doesn't exist in our own buffer.
// But it is possible that a portion of it exists in our buffer.
// So we're going to look for the terminator starting with a portion of our own buffer.
//
// Example:
//
// term length = 3 bytes
// bytesDone = 5 bytes
// preBuffer length = 5 bytes
//
// If we append the preBuffer to our buffer,
// it would look like this:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------------
//
// So we start our search here:
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// -------^-^-^---------
//
// And move forwards...
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------^-^-^-------
//
// Until we find the terminator or reach the end.
//
// ---------------------
// |B|B|B|B|B|P|P|P|P|P|
// ---------------^-^-^-
BOOL found = NO;
NSUInteger termLength = [term length];
NSUInteger preBufferLength = [preBuffer length];
if ((bytesDone + preBufferLength) < termLength)
{
// Not enough data for a full term sequence yet
return preBufferLength;
}
NSUInteger maxPreBufferLength;
if (maxLength > 0) {
maxPreBufferLength = MIN(preBufferLength, (maxLength - bytesDone));
// Note: maxLength >= termLength
}
else {
maxPreBufferLength = preBufferLength;
}
Byte seq[termLength];
const void *termBuf = [term bytes];
NSUInteger bufLen = MIN(bytesDone, (termLength - 1));
void *buf = [buffer mutableBytes] + startOffset + bytesDone - bufLen;
NSUInteger preLen = termLength - bufLen;
void *pre = (void *)[preBuffer bytes];
NSUInteger loopCount = bufLen + maxPreBufferLength - termLength + 1; // Plus one. See example above.
NSUInteger result = preBufferLength;
NSUInteger i;
for (i = 0; i < loopCount; i++)
{
if (bufLen > 0)
{
// Combining bytes from buffer and preBuffer
memcpy(seq, buf, bufLen);
memcpy(seq + bufLen, pre, preLen);
if (memcmp(seq, termBuf, termLength) == 0)
{
result = preLen;
found = YES;
break;
}
buf++;
bufLen--;
preLen++;
}
else
{
// Comparing directly from preBuffer
if (memcmp(pre, termBuf, termLength) == 0)
{
NSUInteger preOffset = pre - [preBuffer bytes]; // pointer arithmetic
result = preOffset + termLength;
found = YES;
break;
}
pre++;
}
}
// There is no need to avoid resizing the buffer in this particular situation.
if (foundPtr) *foundPtr = found;
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.
**/
- (NSInteger)searchForTermAfterPreBuffering:(NSUInteger)numBytes
{
NSAssert(term != nil, @"This method does not apply to non-term reads");
NSAssert(bytesDone >= numBytes, @"Invoked with invalid numBytes!");
// 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.
NSUInteger termLength = [term length];
const void *termBuffer = [term bytes];
// Remember: This method is called after the bytesDone variable has been updated.
NSUInteger prevBytesDone = bytesDone - numBytes;
NSUInteger i;
if (prevBytesDone >= termLength)
i = prevBytesDone - termLength + 1;
else
i = 0;
while ((i + termLength) <= bytesDone)
{
void *subBuffer = [buffer mutableBytes] + startOffset + i;
if(memcmp(subBuffer, termBuffer, termLength) == 0)
{
return bytesDone - (i + termLength);
}
i++;
}
return -1;
}
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The AsyncWritePacket encompasses the instructions for any given write.
**/
@interface AsyncWritePacket : NSObject
{
@public
NSData *buffer;
NSUInteger 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;
timeout = t;
tag = i;
bytesDone = 0;
}
return self;
}
@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;
}
@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 = (__bridge void *)(self);
theContext.retain = nil;
theContext.release = nil;
theContext.copyDescription = nil;
// Default run loop modes
theRunLoopModes = [NSArray arrayWithObject:NSDefaultRunLoopMode];
}
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];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Thread-Safety
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)checkForThreadSafety
{
if (theRunLoop && (theRunLoop != CFRunLoopGetCurrent()))
{
// AsyncSocket is RunLoop based.
// It is designed to be run and accessed from a particular thread/runloop.
// As such, it is faster as it does not have the overhead of locks/synchronization.
//
// However, this places a minimal requirement on the developer to maintain thread-safety.
// If you are seeing errors or crashes in AsyncSocket,
// it is very likely that thread-safety has been broken.
// This method may be enabled via the DEBUG_THREAD_SAFETY macro,
// and will allow you to discover the place in your code where thread-safety is being broken.
//
// Note:
//
// If you find you constantly need to access your socket from various threads,
// you may prefer to use GCDAsyncSocket which is thread-safe.
[NSException raise:AsyncSocketException
format:@"Attempting to access AsyncSocket instance from incorrect thread."];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (long)userData
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theUserData;
}
- (void)setUserData:(long)userData
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theUserData = userData;
}
- (id)delegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theDelegate;
}
- (void)setDelegate:(id)delegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theDelegate = delegate;
}
- (BOOL)canSafelySetDelegate
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return ([theReadQueue count] == 0 && [theWriteQueue count] == 0 && theCurrentRead == nil && theCurrentWrite == nil);
}
- (CFSocketRef)getCFSocket
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
if(theSocket4)
return theSocket4;
else
return theSocket6;
}
- (CFReadStreamRef)getCFReadStream
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theReadStream;
}
- (CFWriteStreamRef)getCFWriteStream
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
return theWriteStream;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Progress
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (float)progressOfReadReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// 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]])
{
if (tag != NULL) *tag = 0;
if (done != NULL) *done = 0;
if (total != NULL) *total = 0;
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.
NSUInteger d = theCurrentRead->bytesDone;
NSUInteger 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:(NSUInteger *)done total:(NSUInteger *)total
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
// 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]])
{
if (tag != NULL) *tag = 0;
if (done != NULL) *done = 0;
if (total != NULL) *total = 0;
return NAN;
}
NSUInteger d = theCurrentWrite->bytesDone;
NSUInteger 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
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopAddSource(theRunLoop, source, (__bridge CFStringRef)runLoopMode);
}
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopRemoveSource(theRunLoop, source, (__bridge CFStringRef)runLoopMode);
}
}
- (void)runLoopAddSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopAddSource(theRunLoop, source, (__bridge CFStringRef)runLoopMode);
}
- (void)runLoopRemoveSource:(CFRunLoopSourceRef)source mode:(NSString *)runLoopMode
{
CFRunLoopRemoveSource(theRunLoop, source, (__bridge CFStringRef)runLoopMode);
}
- (void)runLoopAddTimer:(NSTimer *)timer
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopAddTimer(theRunLoop, (__bridge CFRunLoopTimerRef)timer, (__bridge CFStringRef)runLoopMode);
}
}
- (void)runLoopRemoveTimer:(NSTimer *)timer
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFRunLoopRemoveTimer(theRunLoop, (__bridge CFRunLoopTimerRef)timer, (__bridge CFStringRef)runLoopMode);
}
}
- (void)runLoopAddTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopAddTimer(theRunLoop, (__bridge CFRunLoopTimerRef)timer, (__bridge CFStringRef)runLoopMode);
}
- (void)runLoopRemoveTimer:(NSTimer *)timer mode:(NSString *)runLoopMode
{
CFRunLoopRemoveTimer(theRunLoop, (__bridge CFRunLoopTimerRef)timer, (__bridge CFStringRef)runLoopMode);
}
- (void)runLoopUnscheduleReadStream
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFReadStreamUnscheduleFromRunLoop(theReadStream, theRunLoop, (__bridge CFStringRef)runLoopMode);
}
CFReadStreamSetClient(theReadStream, kCFStreamEventNone, NULL, NULL);
}
- (void)runLoopUnscheduleWriteStream
{
for (NSString *runLoopMode in theRunLoopModes)
{
CFWriteStreamUnscheduleFromRunLoop(theWriteStream, theRunLoop, (__bridge CFStringRef)runLoopMode);
}
CFWriteStreamSetClient(theWriteStream, kCFStreamEventNone, NULL, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* See the header file for a full explanation of pre-buffering.
**/
- (void)enablePreBuffering
{
#if DEBUG_THREAD_SAFETY
[self checkForThreadSafety];
#endif
theFlags |= kEnablePreBuffering;
}