1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/TCP/TCPConnection.m Fri May 23 17:37:36 2008 -0700
1.3 @@ -0,0 +1,365 @@
1.4 +//
1.5 +// TCPConnection.m
1.6 +// MYNetwork
1.7 +//
1.8 +// Created by Jens Alfke on 5/18/08.
1.9 +// Copyright 2008 Jens Alfke. All rights reserved.
1.10 +//
1.11 +
1.12 +#import "TCP_Internal.h"
1.13 +#import "IPAddress.h"
1.14 +
1.15 +#import "ExceptionUtils.h"
1.16 +
1.17 +
1.18 +NSString* const TCPErrorDomain = @"TCP";
1.19 +
1.20 +
1.21 +@interface TCPConnection ()
1.22 +@property TCPConnectionStatus status;
1.23 +- (BOOL) _checkIfClosed;
1.24 +- (void) _closed;
1.25 +@end
1.26 +
1.27 +
1.28 +@implementation TCPConnection
1.29 +
1.30 +
1.31 +static NSMutableArray *sAllConnections;
1.32 +
1.33 +
1.34 +- (Class) readerClass {return [TCPReader class];}
1.35 +- (Class) writerClass {return [TCPWriter class];}
1.36 +
1.37 +
1.38 +- (id) _initWithAddress: (IPAddress*)address
1.39 + inputStream: (NSInputStream*)input
1.40 + outputStream: (NSOutputStream*)output
1.41 +{
1.42 + self = [super init];
1.43 + if (self != nil) {
1.44 + if( !address || !input || !output ) {
1.45 + LogTo(TCP,@"Failed to create %@: addr=%@, in=%@, out=%@",
1.46 + self.class,address,input,output);
1.47 + [self release];
1.48 + return nil;
1.49 + }
1.50 + _address = [address copy];
1.51 + _reader = [[[self readerClass] alloc] initWithConnection: self stream: input];
1.52 + _writer = [[[self writerClass] alloc] initWithConnection: self stream: output];
1.53 + LogTo(TCP,@"%@ initialized",self);
1.54 + }
1.55 + return self;
1.56 +}
1.57 +
1.58 +
1.59 +
1.60 +- (id) initToAddress: (IPAddress*)address
1.61 + localPort: (UInt16)localPort
1.62 +{
1.63 + NSInputStream *input = nil;
1.64 + NSOutputStream *output = nil;
1.65 + [NSStream getStreamsToHost: [NSHost hostWithAddress: address.ipv4name]
1.66 + port: address.port
1.67 + inputStream: &input
1.68 + outputStream: &output];
1.69 + return [self _initWithAddress: address inputStream: input outputStream: output];
1.70 + //FIX: Support localPort!
1.71 +}
1.72 +
1.73 +- (id) initToAddress: (IPAddress*)address
1.74 +{
1.75 + return [self initToAddress: address localPort: 0];
1.76 +}
1.77 +
1.78 +
1.79 +- (id) initIncomingFromSocket: (CFSocketNativeHandle)socket
1.80 + listener: (TCPListener*)listener
1.81 +{
1.82 + CFReadStreamRef readStream = NULL;
1.83 + CFWriteStreamRef writeStream = NULL;
1.84 + CFStreamCreatePairWithSocket(kCFAllocatorDefault, socket, &readStream, &writeStream);
1.85 + self = [self _initWithAddress: [IPAddress addressOfSocket: socket]
1.86 + inputStream: (NSInputStream*)readStream
1.87 + outputStream: (NSOutputStream*)writeStream];
1.88 + if( self ) {
1.89 + _isIncoming = YES;
1.90 + _server = [listener retain];
1.91 + CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
1.92 + CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
1.93 + }
1.94 + return self;
1.95 +}
1.96 +
1.97 +
1.98 +- (void) dealloc
1.99 +{
1.100 + LogTo(TCP,@"DEALLOC %@",self);
1.101 + [_reader release];
1.102 + [_writer release];
1.103 + [_address release];
1.104 + [super dealloc];
1.105 +}
1.106 +
1.107 +
1.108 +- (NSString*) description
1.109 +{
1.110 + return $sprintf(@"%@[%@ %@]",self.class,(_isIncoming ?@"from" :@"to"),_address);
1.111 +}
1.112 +
1.113 +
1.114 +@synthesize address=_address, isIncoming=_isIncoming, status=_status, delegate=_delegate,
1.115 + reader=_reader, writer=_writer, server=_server;
1.116 +
1.117 +
1.118 +- (NSError*) error
1.119 +{
1.120 + return _error;
1.121 +}
1.122 +
1.123 +
1.124 +- (NSString*) actualSecurityLevel
1.125 +{
1.126 + return _reader.securityLevel;
1.127 +
1.128 +}
1.129 +
1.130 +- (NSArray*) peerSSLCerts
1.131 +{
1.132 + return _reader.peerSSLCerts ?: _writer.peerSSLCerts;
1.133 +}
1.134 +
1.135 +
1.136 +- (void) _setStreamProperty: (id)value forKey: (NSString*)key
1.137 +{
1.138 + [_reader setProperty: value forKey: (CFStringRef)key];
1.139 + [_writer setProperty: value forKey: (CFStringRef)key];
1.140 +}
1.141 +
1.142 +
1.143 +#pragma mark -
1.144 +#pragma mark OPENING / CLOSING:
1.145 +
1.146 +
1.147 +- (void) open
1.148 +{
1.149 + if( _status<=kTCP_Closed && _reader ) {
1.150 + _reader.SSLProperties = _sslProperties;
1.151 + _writer.SSLProperties = _sslProperties;
1.152 + [_reader open];
1.153 + [_writer open];
1.154 + if( ! [sAllConnections my_containsObjectIdenticalTo: self] )
1.155 + [sAllConnections addObject: self];
1.156 + self.status = kTCP_Opening;
1.157 + }
1.158 +}
1.159 +
1.160 +
1.161 +- (void) disconnect
1.162 +{
1.163 + if( _status > kTCP_Closed ) {
1.164 + LogTo(TCP,@"%@ disconnecting",self);
1.165 + [_writer disconnect];
1.166 + setObj(&_writer,nil);
1.167 + [_reader disconnect];
1.168 + setObj(&_reader,nil);
1.169 + self.status = kTCP_Disconnected;
1.170 + }
1.171 +}
1.172 +
1.173 +
1.174 +- (void) close
1.175 +{
1.176 + [self closeWithTimeout: 60.0];
1.177 +}
1.178 +
1.179 +- (void) closeWithTimeout: (NSTimeInterval)timeout
1.180 +{
1.181 + if( _status == kTCP_Opening ) {
1.182 + LogTo(TCP,@"%@ canceling open",self);
1.183 + [self _closed];
1.184 + } else if( _status == kTCP_Open ) {
1.185 + LogTo(TCP,@"%@ closing",self);
1.186 + self.status = kTCP_Closing;
1.187 + [self retain];
1.188 + [_reader close];
1.189 + [_writer close];
1.190 + if( ! [self _checkIfClosed] ) {
1.191 + if( timeout <= 0.0 )
1.192 + [self disconnect];
1.193 + else if( timeout != INFINITY )
1.194 + [self performSelector: @selector(_closeTimeoutExpired)
1.195 + withObject: nil afterDelay: timeout];
1.196 + }
1.197 + [self release];
1.198 + }
1.199 +}
1.200 +
1.201 +- (void) _closeTimeoutExpired
1.202 +{
1.203 + if( _status==kTCP_Closing )
1.204 + [self disconnect];
1.205 +}
1.206 +
1.207 +
1.208 +- (BOOL) _checkIfClosed
1.209 +{
1.210 + if( _status == kTCP_Closing && _writer==nil && _reader==nil ) {
1.211 + [self _closed];
1.212 + return YES;
1.213 + } else
1.214 + return NO;
1.215 +}
1.216 +
1.217 +
1.218 +// called by my streams when they close (after my -close is called)
1.219 +- (void) _closed
1.220 +{
1.221 + if( _status != kTCP_Closed && _status != kTCP_Disconnected ) {
1.222 + LogTo(TCP,@"%@ is now closed",self);
1.223 + self.status = (_status==kTCP_Closing ?kTCP_Closed :kTCP_Disconnected);
1.224 + [self tellDelegate: @selector(connectionDidClose:) withObject: nil];
1.225 + }
1.226 + [NSObject cancelPreviousPerformRequestsWithTarget: self
1.227 + selector: @selector(_closeTimeoutExpired)
1.228 + object: nil];
1.229 + [sAllConnections removeObjectIdenticalTo: self];
1.230 +}
1.231 +
1.232 +
1.233 ++ (void) closeAllWithTimeout: (NSTimeInterval)timeout
1.234 +{
1.235 + NSArray *connections = [sAllConnections copy];
1.236 + for( TCPConnection *conn in connections )
1.237 + [conn closeWithTimeout: timeout];
1.238 + [connections release];
1.239 +}
1.240 +
1.241 ++ (void) waitTillAllClosed
1.242 +{
1.243 + while( sAllConnections.count ) {
1.244 + if( ! [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
1.245 + beforeDate: [NSDate distantFuture]] )
1.246 + break;
1.247 + }
1.248 +}
1.249 +
1.250 +
1.251 +#pragma mark -
1.252 +#pragma mark STREAM CALLBACKS:
1.253 +
1.254 +
1.255 +- (void) _streamOpened: (TCPStream*)stream
1.256 +{
1.257 + if( _status==kTCP_Opening && _reader.isOpen && _writer.isOpen ) {
1.258 + LogTo(TCP,@"%@ opened",self);
1.259 + self.status = kTCP_Open;
1.260 + [self tellDelegate: @selector(connectionDidOpen:) withObject: nil];
1.261 + }
1.262 +}
1.263 +
1.264 +
1.265 +- (BOOL) _streamPeerCertAvailable: (TCPStream*)stream
1.266 +{
1.267 + BOOL allow = YES;
1.268 + if( ! _checkedPeerCert ) {
1.269 + @try{
1.270 + _checkedPeerCert = YES;
1.271 + if( stream.securityLevel != nil ) {
1.272 + NSArray *certs = stream.peerSSLCerts;
1.273 + if( ! certs && ! _isIncoming )
1.274 + allow = NO; // Server MUST have a cert!
1.275 + else {
1.276 + SecCertificateRef cert = certs.count ?(SecCertificateRef)[certs objectAtIndex:0] :NULL;
1.277 + LogTo(TCP,@"%@: Peer cert = %@",self,cert);
1.278 + if( [_delegate respondsToSelector: @selector(connection:authorizeSSLPeer:)] )
1.279 + allow = [_delegate connection: self authorizeSSLPeer: cert];
1.280 + }
1.281 + }
1.282 + }@catch( NSException *x ) {
1.283 + MYReportException(x,@"TCPConnection _streamPeerCertAvailable");
1.284 + _checkedPeerCert = NO;
1.285 + allow = NO;
1.286 + }
1.287 + if( ! allow )
1.288 + [self _stream: stream
1.289 + gotError: [NSError errorWithDomain: NSStreamSocketSSLErrorDomain
1.290 + code: errSSLClosedAbort
1.291 + userInfo: nil]];
1.292 + }
1.293 + return allow;
1.294 +}
1.295 +
1.296 +
1.297 +- (void) _stream: (TCPStream*)stream gotError: (NSError*)error
1.298 +{
1.299 + LogTo(TCP,@"%@ got %@ on %@",self,error,stream.class);
1.300 + Assert(error);
1.301 + setObj(&_error,error);
1.302 + [_reader disconnect];
1.303 + setObj(&_reader,nil);
1.304 + [_writer disconnect];
1.305 + setObj(&_writer,nil);
1.306 + [self _closed];
1.307 +}
1.308 +
1.309 +- (void) _streamGotEOF: (TCPStream*)stream
1.310 +{
1.311 + LogTo(TCP,@"%@ got EOF on %@",self,stream);
1.312 + if( stream == _reader ) {
1.313 + setObj(&_reader,nil);
1.314 + // This is the expected way for he peer to initiate closing the connection.
1.315 + if( _status==kTCP_Open ) {
1.316 + [self closeWithTimeout: INFINITY];
1.317 + return;
1.318 + }
1.319 + } else if( stream == _writer ) {
1.320 + setObj(&_writer,nil);
1.321 + }
1.322 +
1.323 + if( _status == kTCP_Closing ) {
1.324 + [self _checkIfClosed];
1.325 + } else {
1.326 + [self _stream: stream
1.327 + gotError: [NSError errorWithDomain: NSPOSIXErrorDomain code: ECONNRESET userInfo: nil]];
1.328 + }
1.329 +}
1.330 +
1.331 +
1.332 +// Called after I called -close on a stream and it finished closing:
1.333 +- (void) _streamClosed: (TCPStream*)stream
1.334 +{
1.335 + LogTo(TCP,@"%@ finished closing %@",self,stream);
1.336 + if( stream == _reader )
1.337 + setObj(&_reader,nil);
1.338 + else if( stream == _writer )
1.339 + setObj(&_writer,nil);
1.340 + if( !_reader.isOpen && !_writer.isOpen )
1.341 + [self _closed];
1.342 +}
1.343 +
1.344 +
1.345 +@end
1.346 +
1.347 +
1.348 +/*
1.349 + Copyright (c) 2008, Jens Alfke <jens@mooseyard.com>. All rights reserved.
1.350 +
1.351 + Redistribution and use in source and binary forms, with or without modification, are permitted
1.352 + provided that the following conditions are met:
1.353 +
1.354 + * Redistributions of source code must retain the above copyright notice, this list of conditions
1.355 + and the following disclaimer.
1.356 + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
1.357 + and the following disclaimer in the documentation and/or other materials provided with the
1.358 + distribution.
1.359 +
1.360 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
1.361 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1.362 + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
1.363 + BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1.364 + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
1.365 + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1.366 + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
1.367 + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.368 + */