TCP/TCPConnection.m
author Jens Alfke <jens@mooseyard.com>
Tue Jun 03 16:56:33 2008 -0700 (2008-06-03)
changeset 11 29e8b03c05d4
parent 7 5936db2c1987
child 15 f723174fbc24
permissions -rw-r--r--
* Initial checkin of BLIP.py. (Receiving seems to work.)
* FIXED: Abbreviation list in BLIPProperties was messed up.
* Renamed some instance variables to use 'request' instead of 'query'.
* Test client doesn't throw an assertion-failure now when the number of unresponded requests exceeds 100.
jens@0
     1
//
jens@0
     2
//  TCPConnection.m
jens@0
     3
//  MYNetwork
jens@0
     4
//
jens@0
     5
//  Created by Jens Alfke on 5/18/08.
jens@0
     6
//  Copyright 2008 Jens Alfke. All rights reserved.
jens@0
     7
//
jens@0
     8
jens@0
     9
#import "TCP_Internal.h"
jens@0
    10
#import "IPAddress.h"
jens@0
    11
jens@1
    12
#import "Logging.h"
jens@1
    13
#import "Test.h"
jens@0
    14
#import "ExceptionUtils.h"
jens@0
    15
jens@0
    16
jens@8
    17
#if TARGET_OS_IPHONE
jens@8
    18
// SecureTransport.h is missing on iPhone, with its SSL constants:
jens@8
    19
enum{
jens@8
    20
    errSSLClosedAbort 			= -9806,	/* connection closed via error */
jens@8
    21
};
jens@8
    22
#endif
jens@8
    23
jens@8
    24
jens@8
    25
jens@0
    26
NSString* const TCPErrorDomain = @"TCP";
jens@0
    27
jens@0
    28
jens@0
    29
@interface TCPConnection ()
jens@0
    30
@property TCPConnectionStatus status;
jens@7
    31
@property (retain) IPAddress *address;
jens@0
    32
- (BOOL) _checkIfClosed;
jens@0
    33
- (void) _closed;
jens@0
    34
@end
jens@0
    35
jens@0
    36
jens@0
    37
@implementation TCPConnection
jens@0
    38
jens@0
    39
jens@0
    40
static NSMutableArray *sAllConnections;
jens@0
    41
jens@0
    42
jens@0
    43
- (Class) readerClass   {return [TCPReader class];}
jens@0
    44
- (Class) writerClass   {return [TCPWriter class];}
jens@0
    45
jens@0
    46
jens@0
    47
- (id) _initWithAddress: (IPAddress*)address
jens@0
    48
            inputStream: (NSInputStream*)input
jens@0
    49
           outputStream: (NSOutputStream*)output
jens@0
    50
{
jens@0
    51
    self = [super init];
jens@0
    52
    if (self != nil) {
jens@7
    53
        if( !input || !output ) {
jens@0
    54
            LogTo(TCP,@"Failed to create %@: addr=%@, in=%@, out=%@",
jens@0
    55
                  self.class,address,input,output);
jens@0
    56
            [self release];
jens@0
    57
            return nil;
jens@0
    58
        }
jens@0
    59
        _address = [address copy];
jens@0
    60
        _reader = [[[self readerClass] alloc] initWithConnection: self stream: input];
jens@0
    61
        _writer = [[[self writerClass] alloc] initWithConnection: self stream: output];
jens@7
    62
        LogTo(TCP,@"%@ initialized, address=%@",self,address);
jens@0
    63
    }
jens@0
    64
    return self;
jens@0
    65
}
jens@0
    66
jens@0
    67
jens@0
    68
jens@0
    69
- (id) initToAddress: (IPAddress*)address
jens@0
    70
           localPort: (UInt16)localPort
jens@0
    71
{
jens@0
    72
    NSInputStream *input = nil;
jens@0
    73
    NSOutputStream *output = nil;
jens@8
    74
#if TARGET_OS_IPHONE
jens@8
    75
    // +getStreamsToHost: is missing for some stupid reason on iPhone. Grrrrrrrrrr.
jens@8
    76
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)address.hostname, address.port,
jens@8
    77
                                       (CFReadStreamRef*)&input, (CFWriteStreamRef*)&output);
jens@8
    78
    if( input )
jens@8
    79
        [(id)CFMakeCollectable(input) autorelease];
jens@8
    80
    if( output )
jens@8
    81
        [(id)CFMakeCollectable(output) autorelease];
jens@8
    82
#else
jens@0
    83
    [NSStream getStreamsToHost: [NSHost hostWithAddress: address.ipv4name]
jens@0
    84
                          port: address.port 
jens@0
    85
                   inputStream: &input 
jens@0
    86
                  outputStream: &output];
jens@8
    87
#endif
jens@0
    88
    return [self _initWithAddress: address inputStream: input outputStream: output];
jens@0
    89
    //FIX: Support localPort!
jens@0
    90
}
jens@0
    91
jens@0
    92
- (id) initToAddress: (IPAddress*)address
jens@0
    93
{
jens@0
    94
    return [self initToAddress: address localPort: 0];
jens@0
    95
}
jens@0
    96
jens@7
    97
- (id) initToNetService: (NSNetService*)service
jens@7
    98
{
jens@7
    99
    IPAddress *address = nil;
jens@7
   100
    NSInputStream *input;
jens@7
   101
    NSOutputStream *output;
jens@7
   102
    if( [service getInputStream: &input outputStream: &output] ) {
jens@7
   103
        NSArray *addresses = service.addresses;
jens@7
   104
        if( addresses.count > 0 )
jens@7
   105
            address = [[[IPAddress alloc] initWithSockAddr: [[addresses objectAtIndex: 0] bytes]] autorelease];
jens@7
   106
    } else {
jens@7
   107
        input = nil;
jens@7
   108
        output = nil;
jens@7
   109
    }
jens@7
   110
    return [self _initWithAddress: address inputStream: input outputStream: output];
jens@7
   111
}
jens@7
   112
jens@0
   113
jens@0
   114
- (id) initIncomingFromSocket: (CFSocketNativeHandle)socket
jens@0
   115
                     listener: (TCPListener*)listener
jens@0
   116
{
jens@0
   117
    CFReadStreamRef readStream = NULL;
jens@0
   118
    CFWriteStreamRef writeStream = NULL;
jens@0
   119
    CFStreamCreatePairWithSocket(kCFAllocatorDefault, socket, &readStream, &writeStream);
jens@0
   120
    self = [self _initWithAddress: [IPAddress addressOfSocket: socket] 
jens@0
   121
                      inputStream: (NSInputStream*)readStream
jens@0
   122
                     outputStream: (NSOutputStream*)writeStream];
jens@0
   123
    if( self ) {
jens@0
   124
        _isIncoming = YES;
jens@0
   125
        _server = [listener retain];
jens@0
   126
        CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
jens@0
   127
        CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
jens@0
   128
    }
jens@0
   129
    return self;
jens@0
   130
}    
jens@0
   131
jens@0
   132
jens@0
   133
- (void) dealloc
jens@0
   134
{
jens@0
   135
    LogTo(TCP,@"DEALLOC %@",self);
jens@0
   136
    [_reader release];
jens@0
   137
    [_writer release];
jens@0
   138
    [_address release];
jens@0
   139
    [super dealloc];
jens@0
   140
}
jens@0
   141
jens@0
   142
jens@0
   143
- (NSString*) description
jens@0
   144
{
jens@0
   145
    return $sprintf(@"%@[%@ %@]",self.class,(_isIncoming ?@"from" :@"to"),_address);
jens@0
   146
}
jens@0
   147
jens@0
   148
jens@0
   149
@synthesize address=_address, isIncoming=_isIncoming, status=_status, delegate=_delegate,
jens@0
   150
            reader=_reader, writer=_writer, server=_server;
jens@0
   151
jens@0
   152
jens@0
   153
- (NSError*) error
jens@0
   154
{
jens@0
   155
    return _error;
jens@0
   156
}
jens@0
   157
jens@0
   158
jens@0
   159
- (NSString*) actualSecurityLevel
jens@0
   160
{
jens@0
   161
    return _reader.securityLevel;
jens@0
   162
jens@0
   163
}
jens@0
   164
jens@0
   165
- (NSArray*) peerSSLCerts
jens@0
   166
{
jens@0
   167
    return _reader.peerSSLCerts ?: _writer.peerSSLCerts;
jens@0
   168
}
jens@0
   169
jens@0
   170
jens@0
   171
- (void) _setStreamProperty: (id)value forKey: (NSString*)key
jens@0
   172
{
jens@0
   173
    [_reader setProperty: value forKey: (CFStringRef)key];
jens@0
   174
    [_writer setProperty: value forKey: (CFStringRef)key];
jens@0
   175
}
jens@0
   176
jens@0
   177
jens@0
   178
#pragma mark -
jens@0
   179
#pragma mark OPENING / CLOSING:
jens@0
   180
jens@0
   181
jens@0
   182
- (void) open
jens@0
   183
{
jens@0
   184
    if( _status<=kTCP_Closed && _reader ) {
jens@0
   185
        _reader.SSLProperties = _sslProperties;
jens@0
   186
        _writer.SSLProperties = _sslProperties;
jens@0
   187
        [_reader open];
jens@0
   188
        [_writer open];
jens@0
   189
        if( ! [sAllConnections my_containsObjectIdenticalTo: self] )
jens@0
   190
            [sAllConnections addObject: self];
jens@0
   191
        self.status = kTCP_Opening;
jens@0
   192
    }
jens@0
   193
}
jens@0
   194
jens@0
   195
jens@0
   196
- (void) disconnect
jens@0
   197
{
jens@0
   198
    if( _status > kTCP_Closed ) {
jens@0
   199
        LogTo(TCP,@"%@ disconnecting",self);
jens@0
   200
        [_writer disconnect];
jens@0
   201
        setObj(&_writer,nil);
jens@0
   202
        [_reader disconnect];
jens@0
   203
        setObj(&_reader,nil);
jens@0
   204
        self.status = kTCP_Disconnected;
jens@0
   205
    }
jens@0
   206
}
jens@0
   207
jens@0
   208
jens@0
   209
- (void) close
jens@0
   210
{
jens@0
   211
    [self closeWithTimeout: 60.0];
jens@0
   212
}
jens@0
   213
jens@0
   214
- (void) closeWithTimeout: (NSTimeInterval)timeout
jens@0
   215
{
jens@0
   216
    if( _status == kTCP_Opening ) {
jens@0
   217
        LogTo(TCP,@"%@ canceling open",self);
jens@0
   218
        [self _closed];
jens@0
   219
    } else if( _status == kTCP_Open ) {
jens@0
   220
        LogTo(TCP,@"%@ closing",self);
jens@0
   221
        self.status = kTCP_Closing;
jens@0
   222
        [self retain];
jens@0
   223
        [_reader close];
jens@0
   224
        [_writer close];
jens@0
   225
        if( ! [self _checkIfClosed] ) {
jens@0
   226
            if( timeout <= 0.0 )
jens@0
   227
                [self disconnect];
jens@0
   228
            else if( timeout != INFINITY )
jens@0
   229
                [self performSelector: @selector(_closeTimeoutExpired)
jens@0
   230
                           withObject: nil afterDelay: timeout];
jens@0
   231
        }
jens@0
   232
        [self release];
jens@0
   233
    }
jens@0
   234
}
jens@0
   235
jens@0
   236
- (void) _closeTimeoutExpired
jens@0
   237
{
jens@0
   238
    if( _status==kTCP_Closing )
jens@0
   239
        [self disconnect];
jens@0
   240
}
jens@0
   241
jens@0
   242
jens@0
   243
- (BOOL) _checkIfClosed
jens@0
   244
{
jens@0
   245
    if( _status == kTCP_Closing && _writer==nil && _reader==nil ) {
jens@0
   246
        [self _closed];
jens@0
   247
        return YES;
jens@0
   248
    } else
jens@0
   249
        return NO;
jens@0
   250
}
jens@0
   251
jens@0
   252
jens@0
   253
// called by my streams when they close (after my -close is called)
jens@0
   254
- (void) _closed
jens@0
   255
{
jens@0
   256
    if( _status != kTCP_Closed && _status != kTCP_Disconnected ) {
jens@0
   257
        LogTo(TCP,@"%@ is now closed",self);
jens@0
   258
        self.status = (_status==kTCP_Closing ?kTCP_Closed :kTCP_Disconnected);
jens@0
   259
        [self tellDelegate: @selector(connectionDidClose:) withObject: nil];
jens@0
   260
    }
jens@0
   261
    [NSObject cancelPreviousPerformRequestsWithTarget: self
jens@0
   262
                                             selector: @selector(_closeTimeoutExpired)
jens@0
   263
                                               object: nil];
jens@0
   264
    [sAllConnections removeObjectIdenticalTo: self];
jens@0
   265
}
jens@0
   266
jens@0
   267
jens@0
   268
+ (void) closeAllWithTimeout: (NSTimeInterval)timeout
jens@0
   269
{
jens@0
   270
    NSArray *connections = [sAllConnections copy];
jens@0
   271
    for( TCPConnection *conn in connections )
jens@0
   272
        [conn closeWithTimeout: timeout];
jens@0
   273
    [connections release];
jens@0
   274
}
jens@0
   275
jens@0
   276
+ (void) waitTillAllClosed
jens@0
   277
{
jens@0
   278
    while( sAllConnections.count ) {
jens@0
   279
        if( ! [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
jens@0
   280
                                       beforeDate: [NSDate distantFuture]] )
jens@0
   281
            break;
jens@0
   282
    }
jens@0
   283
}
jens@0
   284
jens@0
   285
jens@0
   286
#pragma mark -
jens@0
   287
#pragma mark STREAM CALLBACKS:
jens@0
   288
jens@0
   289
jens@0
   290
- (void) _streamOpened: (TCPStream*)stream
jens@0
   291
{
jens@7
   292
    if( ! _address )
jens@7
   293
        self.address = stream.peerAddress;
jens@0
   294
    if( _status==kTCP_Opening && _reader.isOpen && _writer.isOpen ) {
jens@7
   295
        LogTo(TCP,@"%@ opened; address=%@",self,_address);
jens@0
   296
        self.status = kTCP_Open;
jens@0
   297
        [self tellDelegate: @selector(connectionDidOpen:) withObject: nil];
jens@0
   298
    }
jens@0
   299
}
jens@0
   300
jens@0
   301
jens@0
   302
- (BOOL) _streamPeerCertAvailable: (TCPStream*)stream
jens@0
   303
{
jens@0
   304
    BOOL allow = YES;
jens@0
   305
    if( ! _checkedPeerCert ) {
jens@0
   306
        @try{
jens@0
   307
            _checkedPeerCert = YES;
jens@0
   308
            if( stream.securityLevel != nil ) {
jens@0
   309
                NSArray *certs = stream.peerSSLCerts;
jens@0
   310
                if( ! certs && ! _isIncoming )
jens@0
   311
                    allow = NO; // Server MUST have a cert!
jens@0
   312
                else {
jens@0
   313
                    SecCertificateRef cert = certs.count ?(SecCertificateRef)[certs objectAtIndex:0] :NULL;
jens@0
   314
                    LogTo(TCP,@"%@: Peer cert = %@",self,cert);
jens@0
   315
                    if( [_delegate respondsToSelector: @selector(connection:authorizeSSLPeer:)] )
jens@0
   316
                        allow = [_delegate connection: self authorizeSSLPeer: cert];
jens@0
   317
                }
jens@0
   318
            }
jens@0
   319
        }@catch( NSException *x ) {
jens@0
   320
            MYReportException(x,@"TCPConnection _streamPeerCertAvailable");
jens@0
   321
            _checkedPeerCert = NO;
jens@0
   322
            allow = NO;
jens@0
   323
        }
jens@0
   324
        if( ! allow )
jens@0
   325
            [self _stream: stream 
jens@0
   326
                 gotError: [NSError errorWithDomain: NSStreamSocketSSLErrorDomain
jens@0
   327
                                               code: errSSLClosedAbort
jens@0
   328
                                           userInfo: nil]];
jens@0
   329
    }
jens@0
   330
    return allow;
jens@0
   331
}
jens@0
   332
jens@0
   333
jens@0
   334
- (void) _stream: (TCPStream*)stream gotError: (NSError*)error
jens@0
   335
{
jens@0
   336
    LogTo(TCP,@"%@ got %@ on %@",self,error,stream.class);
jens@0
   337
    Assert(error);
jens@0
   338
    setObj(&_error,error);
jens@0
   339
    [_reader disconnect];
jens@0
   340
    setObj(&_reader,nil);
jens@0
   341
    [_writer disconnect];
jens@0
   342
    setObj(&_writer,nil);
jens@0
   343
    [self _closed];
jens@0
   344
}
jens@0
   345
jens@0
   346
- (void) _streamGotEOF: (TCPStream*)stream
jens@0
   347
{
jens@0
   348
    LogTo(TCP,@"%@ got EOF on %@",self,stream);
jens@0
   349
    if( stream == _reader ) {
jens@0
   350
        setObj(&_reader,nil);
jens@0
   351
        // This is the expected way for he peer to initiate closing the connection.
jens@0
   352
        if( _status==kTCP_Open ) {
jens@0
   353
            [self closeWithTimeout: INFINITY];
jens@0
   354
            return;
jens@0
   355
        }
jens@0
   356
    } else if( stream == _writer ) {
jens@0
   357
        setObj(&_writer,nil);
jens@0
   358
    }
jens@0
   359
    
jens@0
   360
    if( _status == kTCP_Closing ) {
jens@0
   361
        [self _checkIfClosed];
jens@0
   362
    } else {
jens@0
   363
        [self _stream: stream 
jens@0
   364
             gotError: [NSError errorWithDomain: NSPOSIXErrorDomain code: ECONNRESET userInfo: nil]];
jens@0
   365
    }
jens@0
   366
}
jens@0
   367
jens@0
   368
jens@0
   369
// Called after I called -close on a stream and it finished closing:
jens@0
   370
- (void) _streamClosed: (TCPStream*)stream
jens@0
   371
{
jens@0
   372
    LogTo(TCP,@"%@ finished closing %@",self,stream);
jens@0
   373
    if( stream == _reader )
jens@0
   374
        setObj(&_reader,nil);
jens@0
   375
    else if( stream == _writer )
jens@0
   376
        setObj(&_writer,nil);
jens@0
   377
    if( !_reader.isOpen && !_writer.isOpen )
jens@0
   378
        [self _closed];
jens@0
   379
}
jens@0
   380
jens@0
   381
jens@0
   382
@end
jens@0
   383
jens@0
   384
jens@0
   385
/*
jens@0
   386
 Copyright (c) 2008, Jens Alfke <jens@mooseyard.com>. All rights reserved.
jens@0
   387
 
jens@0
   388
 Redistribution and use in source and binary forms, with or without modification, are permitted
jens@0
   389
 provided that the following conditions are met:
jens@0
   390
 
jens@0
   391
 * Redistributions of source code must retain the above copyright notice, this list of conditions
jens@0
   392
 and the following disclaimer.
jens@0
   393
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
jens@0
   394
 and the following disclaimer in the documentation and/or other materials provided with the
jens@0
   395
 distribution.
jens@0
   396
 
jens@0
   397
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
jens@0
   398
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
jens@0
   399
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
jens@0
   400
 BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
jens@0
   401
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
jens@0
   402
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
jens@0
   403
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
jens@0
   404
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
jens@0
   405
 */