-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNetSocket.m
1126 lines (880 loc) · 28 KB
/
NetSocket.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
// NetSocket
// NetSocket.m
// Version 0.9
// Created by Dustin Mierau
#import "NetSocket.h"
#import <arpa/inet.h>
#import <sys/socket.h>
#import <sys/time.h>
#import <sys/ioctl.h>
#import <fcntl.h>
#import <netdb.h>
#import <unistd.h>
static void _cfsocketCallback( CFSocketRef inCFSocketRef, CFSocketCallBackType inType, CFDataRef inAddress, const void* inData, void* inContext );
#pragma mark -
@interface NetSocket (Private)
- (id)initWithNativeSocket:(int)inNativeSocket;
- (void)unscheduleFromRunLoop;;
- (void)_cfsocketCreateForNative:(CFSocketNativeHandle)inNativeSocket;
- (BOOL)_cfsocketCreated;
- (void)_cfsocketConnected;
- (void)_cfsocketDisconnected;
- (void)_cfsocketNewConnection;
- (void)_cfsocketDataAvailable;
- (void)_cfsocketWritable;
- (void)_socketConnectionTimedOut:(NSTimer*)inTimer;
- (NetSocket*)_socketAcceptConnection;
- (void)_socketReadData;
- (void)_socketWriteData;
- (BOOL)_socketIsWritable;
- (int)_socketReadableByteCount;
- (void)_scheduleConnectionTimeoutTimer:(NSTimeInterval)inTimeout;
- (void)_unscheduleConnectionTimeoutTimer;
@end
#pragma mark -
@implementation NetSocket
- (id)init
{
if( ![super init] )
return nil;
// Initialize some values
mCFSocketRef = NULL;
mCFSocketRunLoopSourceRef = NULL;
mDelegate = nil;
mConnectionTimer = nil;
mSocketConnected = NO;
mSocketListening = NO;
mOutgoingBuffer = nil;
mIncomingBuffer = [[NSMutableData alloc] init];
return self;
}
- (id)initWithNativeSocket:(int)inNativeSocket
{
if( ![self init] )
return nil;
// Create CFSocketRef based on specified native socket
[self _cfsocketCreateForNative:inNativeSocket];
// If creation of the CFSocketRef failed, we return nothing and cleanup
if( ![self _cfsocketCreated] )
{
[super dealloc];
return nil;
}
// Remember that we are a connected socket
mSocketConnected = YES;
return self;
}
- (void)dealloc
{
// We don't want the delegate receiving anymore messages from us
mDelegate = nil;
// Unschedule connection timeout timer
[self _unscheduleConnectionTimeoutTimer];
// Unschedule socket from runloop
[self unscheduleFromRunLoop];
// Close socket if it is still open
[self close];
// Reset some values
mSocketConnected = NO;
mSocketListening = NO;
// Release our incoming buffer
[mIncomingBuffer release];
mIncomingBuffer = nil;
[super dealloc];
}
#pragma mark -
+ (NetSocket*)netsocket
{
NetSocket* netsocket;
BOOL success = NO;
// Allocate new NetSocket
netsocket = [[[NetSocket alloc] init] autorelease];
// Attempt to open the socket and schedule it on the current runloop
if( [netsocket open] )
if( [netsocket scheduleOnCurrentRunLoop] )
success = YES;
// Return the new NetSocket if creation was successful
return ( success ? netsocket : nil );
}
+ (NetSocket*)netsocketListeningOnRandomPort
{
// Return a new netsocket listening on a random open port
return [self netsocketListeningOnPort:0];
}
+ (NetSocket*)netsocketListeningOnPort:(UInt16)inPort
{
NetSocket* netsocket;
BOOL success = NO;
// Create a new NetSocket
netsocket = [self netsocket];
// Set the NetSocket to listen on the specified port
if( [netsocket listenOnPort:inPort] )
success = YES;
// Return the new NetSocket if everything went alright
return ( success ? netsocket : nil );
}
+ (NetSocket*)netsocketConnectedToHost:(NSString*)inHostname port:(UInt16)inPort
{
NetSocket* netsocket;
BOOL success = NO;
// Create a new NetSocket
netsocket = [self netsocket];
// Attempt to connect to the specified host on the specified port
if( [netsocket connectToHost:inHostname port:inPort] )
success = YES;
// Return the new NetSocket if everything went alright
return ( success ? netsocket : nil );
}
#pragma mark -
- (id)delegate
{
return mDelegate;
}
- (void)setDelegate:(id)inDelegate
{
// Set the delegate to the specified delegate
mDelegate = inDelegate;
}
#pragma mark -
- (BOOL)open
{
// If the CFSocketRef has not been allocated, try and do so now
if( ![self _cfsocketCreated] )
{
int nativeSocket;
// Create native socket
nativeSocket = socket( AF_INET, SOCK_STREAM, 0 );
if( nativeSocket < 0 )
return NO;
// Create CFSocketRef based on new native socket
[self _cfsocketCreateForNative:nativeSocket];
}
// Return whether or not the CFSocket was successfully created
return [self _cfsocketCreated];
}
- (void)close
{
CFSocketNativeHandle nativeSocket;
// Unschedule from runloop
[self unscheduleFromRunLoop];
// If the CFSocket was created, destroy it
if( [self _cfsocketCreated] )
{
// Get native socket descriptor
nativeSocket = [self nativeSocketHandle];
// Close socket descriptor
if( nativeSocket > -1 )
close( nativeSocket );
// Invalidate the CFSocketRef
CFSocketInvalidate( mCFSocketRef );
// Release the CFSocketRef and reset our reference to it
CFRelease( mCFSocketRef );
mCFSocketRef = NULL;
}
// Remember that we are no longer connected
mSocketConnected = NO;
// Remember that we are no longer listening
mSocketListening = NO;
// Release outgoing buffer
[mOutgoingBuffer release];
mOutgoingBuffer = nil;
}
#pragma mark -
- (BOOL)scheduleOnCurrentRunLoop
{
return [self scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
}
- (BOOL)scheduleOnRunLoop:(NSRunLoop*)inRunLoop
{
CFRunLoopRef runloop;
// If our CFSocketRef has not been created or we have already been scheduled in a runloop, return
if( ![self _cfsocketCreated] || mCFSocketRunLoopSourceRef )
return NO;
// Remove ourselves from any other runloop we might be apart of
[self unscheduleFromRunLoop];
// Get specified CFRunLoop
runloop = [inRunLoop getCFRunLoop];
if( !runloop )
return NO;
// Create a CFRunLoopSource for our CFSocketRef
mCFSocketRunLoopSourceRef = CFSocketCreateRunLoopSource( kCFAllocatorDefault, mCFSocketRef, 0 );
if( !mCFSocketRunLoopSourceRef )
return NO;
// Finally schedule our runloop source with the specified CFRunLoop
CFRunLoopAddSource( runloop, mCFSocketRunLoopSourceRef, kCFRunLoopDefaultMode );
return YES;
}
- (void)unscheduleFromRunLoop
{
// If our CFSocketRef has not been created than it probably hasn't been scheduled yet
if( ![self _cfsocketCreated] || mCFSocketRunLoopSourceRef == NULL )
return;
// If the runloop source is not valid, return
if( !CFRunLoopSourceIsValid( mCFSocketRunLoopSourceRef ) )
return;
// Invalidate and release the runloop source
CFRunLoopSourceInvalidate( mCFSocketRunLoopSourceRef );
CFRelease( mCFSocketRunLoopSourceRef );
// Reset our reference to the runloop source
mCFSocketRunLoopSourceRef = NULL;
}
#pragma mark -
- (BOOL)listenOnRandomPort
{
return [self listenOnPort:0 maxPendingConnections:5];
}
- (BOOL)listenOnPort:(UInt16)inPort
{
return [self listenOnPort:inPort maxPendingConnections:5];
}
- (BOOL)listenOnPort:(UInt16)inPort maxPendingConnections:(int)inMaxPendingConnections
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in socketAddress;
int socketOptionFlag;
int result;
// If the CFSocket was never created, is connected to another host or is already listening, we cannot use it
if( ![self _cfsocketCreated] || [self isConnected] || [self isListening] )
return NO;
// Get native socket descriptor
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return NO;
// Set this socket option so we can reuse the address immediately
socketOptionFlag = 1;
result = setsockopt( nativeSocket, SOL_SOCKET, SO_REUSEADDR, &socketOptionFlag, sizeof( socketOptionFlag ) );
if( result < 0 )
return NO;
// Setup socket address
bzero( &socketAddress, sizeof( socketAddress ) );
socketAddress.sin_family = PF_INET;
socketAddress.sin_addr.s_addr = htonl( INADDR_ANY );
socketAddress.sin_port = htons( inPort );
// Bind socket to the specified port
result = bind( nativeSocket, (struct sockaddr*)&socketAddress, sizeof( socketAddress ) );
if( result < 0 )
return NO;
// Start the socket listening on the specified port
result = listen( nativeSocket, inMaxPendingConnections );
if( result < 0 )
return NO;
// Note that we are actually listening now
mSocketListening = YES;
return YES;
}
#pragma mark -
- (BOOL)connectToHost:(NSString*)inHostname port:(UInt16)inPort
{
return [self connectToHost:inHostname port:inPort timeout:-1.0];
}
- (BOOL)connectToHost:(NSString*)inHostname port:(UInt16)inPort timeout:(NSTimeInterval)inTimeout
{
struct hostent* socketHost;
struct sockaddr_in socketAddress;
NSData* socketAddressData;
CFSocketError socketError;
// If the CFSocket was never created, is connected to another host or is already listening, we cannot use it
if( ![self _cfsocketCreated] || [self isConnected] || [self isListening] )
return NO;
// Get host information
socketHost = gethostbyname( [inHostname cString] );
if( !socketHost )
return NO;
// Setup socket address
bzero( &socketAddress, sizeof( socketAddress ) );
bcopy( (char*)socketHost->h_addr, (char*)&socketAddress.sin_addr, socketHost->h_length );
socketAddress.sin_family = PF_INET;
socketAddress.sin_port = htons( inPort );
// Enclose socket address in an NSData object
socketAddressData = [NSData dataWithBytes:(void*)&socketAddress length:sizeof( socketAddress )];
// Attempt to connect our CFSocketRef to the specified host
socketError = CFSocketConnectToAddress( mCFSocketRef, (CFDataRef)socketAddressData, -1.0 );
if( socketError != kCFSocketSuccess )
return NO;
// Schedule our timeout timer if the timeout is greater than zero
if( inTimeout >= 0.0 )
[self _scheduleConnectionTimeoutTimer:inTimeout];
// Remove any data left in our outgoing buffer
[mIncomingBuffer setLength:0];
return YES;
}
#pragma mark -
- (NSData*)peekData
{
return mIncomingBuffer;
}
#pragma mark -
- (unsigned)read:(void*)inBuffer amount:(unsigned)inAmount
{
unsigned amountToRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return 0;
// Determine how much to actually read
amountToRead = MIN( inAmount, [mIncomingBuffer length] );
// Read bytes from our incoming buffer
[mIncomingBuffer getBytes:inBuffer length:amountToRead];
[mIncomingBuffer replaceBytesInRange:NSMakeRange( 0, amountToRead ) withBytes:NULL length:0];
return amountToRead;
}
- (unsigned)readOntoData:(NSMutableData*)inData
{
unsigned amountRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return 0;
// Remember the length of our incoming buffer
amountRead = [mIncomingBuffer length];
// Read bytes from our incoming buffer
[inData appendData:mIncomingBuffer];
// Empty out our incoming buffer as we have read it all
[mIncomingBuffer setLength:0];
return amountRead;
}
- (unsigned)readOntoData:(NSMutableData*)inData amount:(unsigned)inAmount
{
unsigned amountToRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return 0;
// Determine how much to actually read
amountToRead = MIN( inAmount, [mIncomingBuffer length] );
// Read bytes from our incoming buffer
[inData appendBytes:[mIncomingBuffer bytes] length:amountToRead];
[mIncomingBuffer replaceBytesInRange:NSMakeRange( 0, amountToRead ) withBytes:NULL length:0];
return amountToRead;
}
- (unsigned)readOntoString:(NSMutableString*)inString encoding:(NSStringEncoding)inEncoding amount:(unsigned)inAmount
{
NSData* readData;
NSString* readString;
unsigned amountToRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return 0;
// Determine how much to actually read
amountToRead = MIN( inAmount, [mIncomingBuffer length] );
// Reference our incoming buffer, we cut down some overhead when the requested amount is the same length as our incoming buffer
if( amountToRead == [mIncomingBuffer length] )
readData = mIncomingBuffer;
else
readData = [[NSData alloc] initWithBytesNoCopy:(void*)[mIncomingBuffer bytes] length:amountToRead freeWhenDone:NO];
// If for some reason we could not create the data object, return
if( !readData )
return 0;
// Create an NSString from the read data using the specified string encoding
readString = [[NSString alloc] initWithData:readData encoding:inEncoding];
if( readString )
{
// Read bytes from our incoming buffer
[mIncomingBuffer replaceBytesInRange:NSMakeRange( 0, amountToRead ) withBytes:NULL length:0];
// Append created string
[inString appendString:readString];
// Release the NSString we created
[readString release];
}
// Release our buffer if it is not our incoming data buffer
if( readData != mIncomingBuffer )
[readData release];
return amountToRead;
}
- (NSData*)readData
{
NSData* readData;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return nil;
// Create new data object with contents of our incoming buffer
readData = [NSData dataWithData:mIncomingBuffer];
if( !readData )
return nil;
// Size our incoming data buffer as we have now read it all
[mIncomingBuffer setLength:0];
return readData;
}
- (NSData*)readData:(unsigned)inAmount
{
NSData* readData;
unsigned amountToRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return nil;
// Determine how much to actually read
amountToRead = MIN( inAmount, [mIncomingBuffer length] );
// Read bytes from our incoming buffer
readData = [NSData dataWithBytes:[mIncomingBuffer bytes] length:amountToRead];
if( !readData )
return nil;
// Read bytes from our incoming buffer
[mIncomingBuffer replaceBytesInRange:NSMakeRange( 0, amountToRead ) withBytes:NULL length:0];
return readData;
}
- (NSString*)readString:(NSStringEncoding)inEncoding
{
NSString* readString;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return nil;
// Read bytes from our incoming buffer
readString = [[[NSString alloc] initWithData:mIncomingBuffer encoding:inEncoding] autorelease];
if( !readString )
return nil;
// Size our incoming data buffer as we have now read it all
[mIncomingBuffer setLength:0];
return readString;
}
- (NSString*)readString:(NSStringEncoding)inEncoding amount:(unsigned)inAmount
{
NSString* readString;
NSData* readData;
unsigned amountToRead;
// If there is no data to read, simply return
if( [mIncomingBuffer length] == 0 )
return nil;
// Determine how much to actually read
amountToRead = MIN( inAmount, [mIncomingBuffer length] );
// Reference our incoming buffer, we cut down some overhead when the requested amount is the same length as our incoming buffer
if( amountToRead == [mIncomingBuffer length] )
readData = mIncomingBuffer;
else
readData = [[NSData alloc] initWithBytesNoCopy:(void*)[mIncomingBuffer bytes] length:amountToRead freeWhenDone:NO];
// If for some reason we could not create the data object, return
if( !readData )
return nil;
// Create a new NSString from the read bytes using the specified encoding
readString = [[[NSString alloc] initWithData:readData encoding:inEncoding] autorelease];
if( readString )
{
// Read bytes from our incoming buffer
[mIncomingBuffer replaceBytesInRange:NSMakeRange( 0, amountToRead ) withBytes:NULL length:0];
}
// Release our buffer if it is not our incoming data buffer
if( readData != mIncomingBuffer )
[readData release];
return readString;
}
#pragma mark -
- (void)write:(const void*)inBytes length:(unsigned)inLength
{
// Return if there are no bytes to write
if( inLength == 0 )
return;
// If the socket is not connected, simply return
if( ![self isConnected] )
return;
// Create outgoing buffer if needed
if( !mOutgoingBuffer )
mOutgoingBuffer = [[NSMutableData alloc] initWithCapacity:inLength];
// Append specified bytes to our outgoing buffer
[mOutgoingBuffer appendBytes:inBytes length:inLength];
// Attempt to write the data to the socket
[self _socketWriteData];
}
- (void)writeData:(NSData*)inData
{
[self write:[inData bytes] length:[inData length]];
}
- (void)writeString:(NSString*)inString encoding:(NSStringEncoding)inEncoding
{
[self writeData:[inString dataUsingEncoding:inEncoding]];
}
#pragma mark -
- (NSString*)remoteHost
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in address;
int addressLength = sizeof( address );
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return nil;
// Get peer name information
if( getpeername( nativeSocket, (struct sockaddr*)&address, &addressLength ) < 0 )
return nil;
// Return string representation of the remote hostname
return [NetSocket stringWithSocketAddress:&address.sin_addr];
}
- (UInt16)remotePort
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in address;
int addressLength = sizeof( address );
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return 0;
// Get peer name information
if( getpeername( nativeSocket, (struct sockaddr*)&address, &addressLength ) < 0 )
return 0;
// Return remote port
return ntohs( address.sin_port );
}
- (NSString*)localHost
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in address;
int addressLength = sizeof( address );
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return nil;
// Get socket name information
if( getsockname( nativeSocket, (struct sockaddr*)&address, &addressLength ) < 0 )
return nil;
// Return string representation of the local hostname
return [NetSocket stringWithSocketAddress:&address.sin_addr];
}
- (UInt16)localPort
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in address;
int addressLength = sizeof( address );
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return 0;
// Get socket name information
if( getsockname( nativeSocket, (struct sockaddr*)&address, &addressLength ) < 0 )
return 0;
// Return local port
return ntohs( address.sin_port );
}
- (BOOL)isConnected
{
return mSocketConnected;
}
- (BOOL)isListening
{
return mSocketListening;
}
- (unsigned)incomingBufferLength
{
return [mIncomingBuffer length];
}
- (unsigned)outgoingBufferLength
{
return [mOutgoingBuffer length];
}
- (CFSocketNativeHandle)nativeSocketHandle
{
// If the CFSocketRef was never created, return an invalid handle
if( ![self _cfsocketCreated] )
return -1;
// Return a valid native socket handle
return CFSocketGetNative( mCFSocketRef );
}
- (CFSocketRef)cfsocketRef
{
return mCFSocketRef;
}
#pragma mark -
+ (void)ignoreBrokenPipes
{
// Ignore the broken pipe signal
signal( SIGPIPE, SIG_IGN );
}
+ (NSString*)stringWithSocketAddress:(struct in_addr*)inAddress
{
return [NSString stringWithCString:inet_ntoa( *inAddress )];
}
#pragma mark -
- (void)_cfsocketCreateForNative:(CFSocketNativeHandle)inNativeSocket
{
CFSocketContext socketContext;
CFOptionFlags socketCallbacks;
CFOptionFlags socketOptions;
int socketFlags;
BOOL success = NO;
// Create socket context
bzero( &socketContext, sizeof( socketContext ) );
socketContext.info = self;
// Set socket callbacks
socketCallbacks = kCFSocketConnectCallBack + kCFSocketReadCallBack + kCFSocketWriteCallBack;
// Get the sockets flags
socketFlags = fcntl( inNativeSocket, F_GETFL, 0 );
if( socketFlags >= 0 )
{
// Put the socket into non-blocking mode
if( fcntl( inNativeSocket, F_SETFL, socketFlags | O_NONBLOCK ) >= 0 )
{
// Create CFSocketRef based on native socket, if it is created...success!
mCFSocketRef = CFSocketCreateWithNative( kCFAllocatorDefault, inNativeSocket, socketCallbacks, &_cfsocketCallback, &socketContext );
if( mCFSocketRef )
success = YES;
}
}
if( !success )
{
close( inNativeSocket );
return;
}
// Set socket options
socketOptions = kCFSocketAutomaticallyReenableReadCallBack;
CFSocketSetSocketFlags( mCFSocketRef, socketOptions );
}
- (BOOL)_cfsocketCreated
{
return ( mCFSocketRef != NULL );
}
- (void)_cfsocketConnected
{
// Unschedule connection timeout timer and release it if it's still running
[self _unscheduleConnectionTimeoutTimer];
// Remember that we are now connected
mSocketConnected = YES;
// Notify our delegate that the socket has connected successfully
if( [mDelegate respondsToSelector:@selector( netsocketConnected: )] )
[mDelegate netsocketConnected:self];
// Attempt to write any data that has already been added to our outgoing buffer
[self _socketWriteData];
}
- (void)_cfsocketDisconnected
{
// Close socket
[self close];
// Notify our delegate that the socket has been disconnected
if( [mDelegate respondsToSelector:@selector( netsocketDisconnected: )] )
[mDelegate netsocketDisconnected:self];
}
- (void)_cfsocketNewConnection
{
NetSocket* netsocket;
// Accept all pending connections
while( netsocket = [self _socketAcceptConnection] )
{
// Notify our delegate that a new connection has been accepted
if( [mDelegate respondsToSelector:@selector( netsocket:connectionAccepted: )] )
[mDelegate netsocket:self connectionAccepted:netsocket];
}
}
- (void)_cfsocketDataAvailable
{
unsigned oldIncomingBufferLength;
// Store the old incoming buffer length
oldIncomingBufferLength = [mIncomingBuffer length];
// Read in available data
[self _socketReadData];
// Return if there was no data added to our incoming data buffer
if( [mIncomingBuffer length] <= oldIncomingBufferLength )
return;
// Notify our delegate that new data is now available
if( [mDelegate respondsToSelector:@selector( netsocket:dataAvailable: )] )
[mDelegate netsocket:self dataAvailable:[mIncomingBuffer length]];
}
- (void)_cfsocketWritable
{
// Attempt to write more data to the socket
[self _socketWriteData];
}
#pragma mark -
- (void)_socketConnectionTimedOut:(NSTimer*)inTimer
{
NSTimeInterval timeInterval;
// Store the timers time interval
timeInterval = [mConnectionTimer timeInterval];
// Unschedule the timeout timer and release it
[self _unscheduleConnectionTimeoutTimer];
// Notify our delegate that our attempt to connect to the specified remote host failed
if( [mDelegate respondsToSelector:@selector( netsocket:connectionTimedOut: )] )
[mDelegate netsocket:self connectionTimedOut:timeInterval];
}
- (NetSocket*)_socketAcceptConnection
{
CFSocketNativeHandle nativeSocket;
struct sockaddr_in socketAddress;
NetSocket* netsocket;
int socketAddressSize;
int socketDescriptor;
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return nil;
// Accept pending connection
socketAddressSize = sizeof( socketAddress );
socketDescriptor = accept( nativeSocket, (struct sockaddr*)&socketAddress, &socketAddressSize );
if( socketDescriptor < 0 )
return nil;
// Create a new NetSocket object based on the accepted connection
netsocket = [[[NetSocket alloc] initWithNativeSocket:socketDescriptor] autorelease];
// If creating the NetSocket object failed, let's close the connection and never speak of this to anyone
if( !netsocket )
close( socketDescriptor );
// Return NetSocket based on accepted connection
return netsocket;
}
- (void)_socketReadData
{
CFSocketNativeHandle nativeSocket;
void* readBuffer;
int amountAvailable;
int amountRead;
// Determine how many bytes are available on the socket to read
amountAvailable = [self _socketReadableByteCount];
if( amountAvailable < 0 )
return;
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return;
// Create read buffer
readBuffer = malloc( ( amountAvailable == 0 ) ? 1 : amountAvailable );
if( !readBuffer )
return;
// Attempt to read the available data
amountRead = read( nativeSocket, readBuffer, ( amountAvailable == 0 ) ? 1 : amountAvailable );
if( amountRead > 0 )
{
// Append data to our incoming buffer
[mIncomingBuffer appendBytes:readBuffer length:amountRead];
}
else
if( amountRead == 0 )
{
// We have been disconnected
[self _cfsocketDisconnected];
}
else
if( amountRead < 0 )
{
if( errno != EAGAIN )
[self _cfsocketDisconnected];
}
// Free our read buffer
free( readBuffer );
}
- (void)_socketWriteData
{
CFSocketNativeHandle nativeSocket;
int amountSent;
// Return if our CFSocketRef has not been created, the outgoing buffer has no data in it or we are simply not connected
if( ![self _cfsocketCreated] || [mOutgoingBuffer length] == 0 || ![self isConnected] )
return;
// Get the native socket
nativeSocket = [self nativeSocketHandle];
if( nativeSocket < 0 )
return;
// Send all we can
amountSent = write( nativeSocket, [mOutgoingBuffer bytes], [mOutgoingBuffer length] );
if( amountSent == [mOutgoingBuffer length] )
{
// We managed to write the entire outgoing buffer to the socket
// Disable the write callback for now since we know we are writable
CFSocketDisableCallBacks( mCFSocketRef, kCFSocketWriteCallBack );
}
else
if( amountSent >= 0 )
{
// We managed to write some of our buffer to the socket
// Enable the write callback on our CFSocketRef so we know when the socket is writable again
CFSocketEnableCallBacks( mCFSocketRef, kCFSocketWriteCallBack );
}
else
if( errno == EWOULDBLOCK )
{
// No data has actually been written here
amountSent = 0;
// Enable the write callback on our CFSocketRef so we know when the socket is writable again
CFSocketEnableCallBacks( mCFSocketRef, kCFSocketWriteCallBack );
}
else