TCP/TCPListener.m
author Jens Alfke <jens@mooseyard.com>
Fri May 23 17:37:36 2008 -0700 (2008-05-23)
changeset 0 9d67172bb323
child 1 8267d5c429c4
permissions -rwxr-xr-x
First checkin after breaking out of Cloudy
jens@0
     1
//
jens@0
     2
//  TCPListener.m
jens@0
     3
//  MYNetwork
jens@0
     4
//
jens@0
     5
//  Created by Jens Alfke on 5/10/08.
jens@0
     6
//  Copyright 2008 Jens Alfke. All rights reserved.
jens@0
     7
//  Portions based on TCPServer class from Apple's "CocoaEcho" sample code.
jens@0
     8
jens@0
     9
#import "TCPListener.h"
jens@0
    10
#import "TCPConnection.h"
jens@0
    11
jens@0
    12
#import "ExceptionUtils.h"
jens@0
    13
#import "IPAddress.h"
jens@0
    14
#include <sys/socket.h>
jens@0
    15
jens@0
    16
#include <netinet/in.h>
jens@0
    17
#include <unistd.h>
jens@0
    18
jens@0
    19
jens@0
    20
static void TCPListenerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, 
jens@0
    21
                                      CFDataRef address, const void *data, void *info);
jens@0
    22
jens@0
    23
@interface TCPListener()
jens@0
    24
@property BOOL bonjourPublished;
jens@0
    25
@property NSInteger bonjourError;
jens@0
    26
- (void) _updateTXTRecord;
jens@0
    27
@end
jens@0
    28
jens@0
    29
jens@0
    30
@implementation TCPListener
jens@0
    31
jens@0
    32
jens@0
    33
- (id) initWithPort: (UInt16)port
jens@0
    34
{
jens@0
    35
    self = [super init];
jens@0
    36
    if (self != nil) {
jens@0
    37
        _port = port;
jens@0
    38
    }
jens@0
    39
    return self;
jens@0
    40
}
jens@0
    41
jens@0
    42
jens@0
    43
- (void) dealloc 
jens@0
    44
{
jens@0
    45
    [self close];
jens@0
    46
    LogTo(TCP,@"DEALLOC %@",self);
jens@0
    47
    [super dealloc];
jens@0
    48
}
jens@0
    49
jens@0
    50
jens@0
    51
@synthesize delegate=_delegate, port=_port, useIPv6=_useIPv6,
jens@0
    52
            bonjourServiceType=_bonjourServiceType, bonjourServiceName=_bonjourServiceName,
jens@0
    53
            bonjourPublished=_bonjourPublished, bonjourError=_bonjourError,
jens@0
    54
            pickAvailablePort=_pickAvailablePort;
jens@0
    55
jens@0
    56
jens@0
    57
- (NSString*) description
jens@0
    58
{
jens@0
    59
    return $sprintf(@"%@[port %hu]",self.class,_port);
jens@0
    60
}
jens@0
    61
jens@0
    62
jens@0
    63
// Stores the last error from CFSocketCreate or CFSocketSetAddress into *ouError.
jens@0
    64
static void* getLastCFSocketError( NSError **outError ) {
jens@0
    65
    if( outError )
jens@0
    66
        *outError = [NSError errorWithDomain: NSPOSIXErrorDomain code: errno userInfo: nil];
jens@0
    67
    return NULL;
jens@0
    68
}
jens@0
    69
jens@0
    70
// Closes a socket (if it's not already NULL), and returns NULL to assign to it.
jens@0
    71
static CFSocketRef closeSocket( CFSocketRef socket ) {
jens@0
    72
    if( socket ) {
jens@0
    73
        CFSocketInvalidate(socket);
jens@0
    74
        CFRelease(socket);
jens@0
    75
    }
jens@0
    76
    return NULL;
jens@0
    77
}
jens@0
    78
jens@0
    79
// opens a socket of a given protocol, either ipv4 or ipv6.
jens@0
    80
- (CFSocketRef) _openProtocol: (SInt32) protocolFamily 
jens@0
    81
                      address: (struct sockaddr*)address
jens@0
    82
                        error: (NSError**)error
jens@0
    83
{
jens@0
    84
    CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL};
jens@0
    85
    CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP,
jens@0
    86
                                        kCFSocketAcceptCallBack, &TCPListenerAcceptCallBack, &socketCtxt);
jens@0
    87
    if( ! socket ) 
jens@0
    88
        return getLastCFSocketError(error);   // CFSocketCreate leaves error code in errno
jens@0
    89
    
jens@0
    90
    int yes = 1;
jens@0
    91
    setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
jens@0
    92
    
jens@0
    93
    NSData *addressData = [NSData dataWithBytes:address length:address->sa_len];
jens@0
    94
    if (kCFSocketSuccess != CFSocketSetAddress(socket, (CFDataRef)addressData)) {
jens@0
    95
        getLastCFSocketError(error);
jens@0
    96
        return closeSocket(socket);
jens@0
    97
    }
jens@0
    98
    // set up the run loop source for the socket
jens@0
    99
    CFRunLoopRef cfrl = CFRunLoopGetCurrent();
jens@0
   100
    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
jens@0
   101
    CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes);
jens@0
   102
    CFRelease(source);
jens@0
   103
    return socket;
jens@0
   104
}
jens@0
   105
jens@0
   106
- (BOOL) _failedToOpen: (NSError*)error
jens@0
   107
{
jens@0
   108
    LogTo(TCP,@"%@ failed to open: %@",self,error);
jens@0
   109
    [self tellDelegate: @selector(listener:failedToOpen:) withObject: error];
jens@0
   110
    return NO;
jens@0
   111
}
jens@0
   112
jens@0
   113
jens@0
   114
- (BOOL) open: (NSError**)outError 
jens@0
   115
{
jens@0
   116
    // set up the IPv4 endpoint; if port is 0, this will cause the kernel to choose a port for us
jens@0
   117
    do{
jens@0
   118
        struct sockaddr_in addr4;
jens@0
   119
        memset(&addr4, 0, sizeof(addr4));
jens@0
   120
        addr4.sin_len = sizeof(addr4);
jens@0
   121
        addr4.sin_family = AF_INET;
jens@0
   122
        addr4.sin_port = htons(_port);
jens@0
   123
        addr4.sin_addr.s_addr = htonl(INADDR_ANY);
jens@0
   124
jens@0
   125
        NSError *error;
jens@0
   126
        _ipv4socket = [self _openProtocol: PF_INET address: (struct sockaddr*)&addr4 error: &error];
jens@0
   127
        if( ! _ipv4socket ) {
jens@0
   128
            if( error.code==EADDRINUSE && _pickAvailablePort && _port<0xFFFF ) {
jens@0
   129
                LogTo(BLIPVerbose,@"%@: port busy, trying %hu...",self,_port+1);
jens@0
   130
                self.port++;        // try the next port
jens@0
   131
            } else {
jens@0
   132
                if( outError ) *outError = error;
jens@0
   133
                return [self _failedToOpen: error];
jens@0
   134
            }
jens@0
   135
        }
jens@0
   136
    }while( ! _ipv4socket );
jens@0
   137
    
jens@0
   138
    if (0 == _port) {
jens@0
   139
        // now that the binding was successful, we get the port number 
jens@0
   140
        NSData *addr = [(NSData *)CFSocketCopyAddress(_ipv4socket) autorelease];
jens@0
   141
        const struct sockaddr_in *addr4 = addr.bytes;
jens@0
   142
        self.port = ntohs(addr4->sin_port);
jens@0
   143
    }
jens@0
   144
    
jens@0
   145
    if( _useIPv6 ) {
jens@0
   146
        // set up the IPv6 endpoint
jens@0
   147
        struct sockaddr_in6 addr6;
jens@0
   148
        memset(&addr6, 0, sizeof(addr6));
jens@0
   149
        addr6.sin6_len = sizeof(addr6);
jens@0
   150
        addr6.sin6_family = AF_INET6;
jens@0
   151
        addr6.sin6_port = htons(_port);
jens@0
   152
        memcpy(&(addr6.sin6_addr), &in6addr_any, sizeof(addr6.sin6_addr));
jens@0
   153
        
jens@0
   154
        _ipv6socket = [self _openProtocol: PF_INET6 address: (struct sockaddr*)&addr6 error: outError];
jens@0
   155
        if( ! _ipv6socket ) {
jens@0
   156
            _ipv4socket = closeSocket(_ipv4socket);
jens@0
   157
            return [self _failedToOpen: *outError];
jens@0
   158
        }
jens@0
   159
    }
jens@0
   160
    
jens@0
   161
    // Open Bonjour:
jens@0
   162
    if( _bonjourServiceType && !_netService) {
jens@0
   163
        // instantiate the NSNetService object that will advertise on our behalf.
jens@0
   164
        _netService = [[NSNetService alloc] initWithDomain: @"local." 
jens@0
   165
                                                      type: _bonjourServiceType
jens@0
   166
                                                      name: _bonjourServiceName ?:@""
jens@0
   167
                                                      port: _port];
jens@0
   168
        if( _netService ) {
jens@0
   169
            [_netService setDelegate:self];
jens@0
   170
            if( _bonjourTXTRecord )
jens@0
   171
                [self _updateTXTRecord];
jens@0
   172
            [_netService publish];
jens@0
   173
        } else {
jens@0
   174
            self.bonjourError = -1;
jens@0
   175
            Warn(@"%@: Failed to create NSNetService",self);
jens@0
   176
        }
jens@0
   177
    }
jens@0
   178
jens@0
   179
    LogTo(TCP,@"%@ is open",self);
jens@0
   180
    [self tellDelegate: @selector(listenerDidOpen:) withObject: nil];
jens@0
   181
    return YES;
jens@0
   182
}
jens@0
   183
jens@0
   184
- (BOOL) open
jens@0
   185
{
jens@0
   186
    return [self open: nil];
jens@0
   187
}
jens@0
   188
    
jens@0
   189
jens@0
   190
- (void) close 
jens@0
   191
{
jens@0
   192
    if( _ipv4socket ) {
jens@0
   193
        if( _netService ) {
jens@0
   194
            [_netService stop];
jens@0
   195
            [_netService release];
jens@0
   196
            _netService = nil;
jens@0
   197
            self.bonjourPublished = NO;
jens@0
   198
        }
jens@0
   199
        self.bonjourError = 0;
jens@0
   200
jens@0
   201
        _ipv4socket = closeSocket(_ipv4socket);
jens@0
   202
        _ipv6socket = closeSocket(_ipv6socket);
jens@0
   203
jens@0
   204
        LogTo(BLIP,@"%@ is closed",self);
jens@0
   205
        [self tellDelegate: @selector(listenerDidClose:) withObject: nil];
jens@0
   206
    }
jens@0
   207
}
jens@0
   208
jens@0
   209
jens@0
   210
- (BOOL) isOpen
jens@0
   211
{
jens@0
   212
    return _ipv4socket != NULL;
jens@0
   213
}
jens@0
   214
jens@0
   215
jens@0
   216
#pragma mark -
jens@0
   217
#pragma mark ACCEPTING CONNECTIONS:
jens@0
   218
jens@0
   219
jens@0
   220
@synthesize connectionClass = _connectionClass;
jens@0
   221
jens@0
   222
jens@0
   223
- (BOOL) acceptConnection: (CFSocketNativeHandle)socket
jens@0
   224
{
jens@0
   225
    IPAddress *addr = [IPAddress addressOfSocket: socket];
jens@0
   226
    if( ! addr )
jens@0
   227
        return NO;
jens@0
   228
    if( [_delegate respondsToSelector: @selector(listener:shouldAcceptConnectionFrom:)]
jens@0
   229
       && ! [_delegate listener: self shouldAcceptConnectionFrom: addr] )
jens@0
   230
        return NO;
jens@0
   231
    
jens@0
   232
    Assert(_connectionClass);
jens@0
   233
    TCPConnection *conn = [[self.connectionClass alloc] initIncomingFromSocket: socket
jens@0
   234
                                                                      listener: self];
jens@0
   235
    if( ! conn )
jens@0
   236
        return NO;
jens@0
   237
    
jens@0
   238
    if( _sslProperties ) {
jens@0
   239
        conn.SSLProperties = _sslProperties;
jens@0
   240
        [conn setSSLProperty: $true forKey: (id)kCFStreamSSLIsServer];
jens@0
   241
    }
jens@0
   242
    [conn open];
jens@0
   243
    [self tellDelegate: @selector(listener:didAcceptConnection:) withObject: conn];
jens@0
   244
    return YES;
jens@0
   245
}
jens@0
   246
jens@0
   247
jens@0
   248
static void TCPListenerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) 
jens@0
   249
{
jens@0
   250
    TCPListener *server = (TCPListener *)info;
jens@0
   251
    if (kCFSocketAcceptCallBack == type) { 
jens@0
   252
        CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;
jens@0
   253
        BOOL accepted = NO;
jens@0
   254
        @try{
jens@0
   255
            accepted = [server acceptConnection: nativeSocketHandle];
jens@0
   256
        }catchAndReport(@"TCPListenerAcceptCallBack");
jens@0
   257
        if( ! accepted )
jens@0
   258
            close(nativeSocketHandle);
jens@0
   259
    }
jens@0
   260
}
jens@0
   261
jens@0
   262
jens@0
   263
#pragma mark -
jens@0
   264
#pragma mark BONJOUR:
jens@0
   265
jens@0
   266
jens@0
   267
- (NSDictionary*) bonjourTXTRecord
jens@0
   268
{
jens@0
   269
    return _bonjourTXTRecord;
jens@0
   270
}
jens@0
   271
jens@0
   272
- (void) setBonjourTXTRecord: (NSDictionary*)txt
jens@0
   273
{
jens@0
   274
    if( ifSetObj(&_bonjourTXTRecord,txt) )
jens@0
   275
        [self _updateTXTRecord];
jens@0
   276
}
jens@0
   277
jens@0
   278
- (void) _updateTXTRecord
jens@0
   279
{
jens@0
   280
    if( _netService ) {
jens@0
   281
        NSData *data;
jens@0
   282
        if( _bonjourTXTRecord ) {
jens@0
   283
            data = [NSNetService dataFromTXTRecordDictionary: _bonjourTXTRecord];
jens@0
   284
            if( data )
jens@0
   285
                LogTo(BLIP,@"%@: Set %u-byte TXT record", self,data.length);
jens@0
   286
            else
jens@0
   287
                Warn(@"TCPListener: Couldn't convert txt dict to data: %@",_bonjourTXTRecord);
jens@0
   288
        } else
jens@0
   289
            data = nil;
jens@0
   290
        [_netService setTXTRecordData: data];
jens@0
   291
    }
jens@0
   292
}
jens@0
   293
jens@0
   294
jens@0
   295
- (void)netServiceWillPublish:(NSNetService *)sender
jens@0
   296
{
jens@0
   297
    LogTo(BLIP,@"%@: Advertising %@",self,sender);
jens@0
   298
    self.bonjourPublished = YES;
jens@0
   299
}
jens@0
   300
jens@0
   301
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict
jens@0
   302
{
jens@0
   303
    self.bonjourError = [[errorDict objectForKey:NSNetServicesErrorCode] intValue];
jens@0
   304
    LogTo(BLIP,@"%@: Failed to advertise %@: error %i",self,sender,self.bonjourError);
jens@0
   305
    [_netService release];
jens@0
   306
    _netService = nil;
jens@0
   307
}
jens@0
   308
jens@0
   309
- (void)netServiceDidStop:(NSNetService *)sender
jens@0
   310
{
jens@0
   311
    LogTo(BLIP,@"%@: Stopped advertising %@",self,sender);
jens@0
   312
    self.bonjourPublished = NO;
jens@0
   313
    [_netService release];
jens@0
   314
    _netService = nil;
jens@0
   315
}
jens@0
   316
jens@0
   317
jens@0
   318
@end
jens@0
   319
jens@0
   320
jens@0
   321
jens@0
   322
/*
jens@0
   323
 Copyright (c) 2008, Jens Alfke <jens@mooseyard.com>. All rights reserved.
jens@0
   324
 
jens@0
   325
 Redistribution and use in source and binary forms, with or without modification, are permitted
jens@0
   326
 provided that the following conditions are met:
jens@0
   327
 
jens@0
   328
 * Redistributions of source code must retain the above copyright notice, this list of conditions
jens@0
   329
 and the following disclaimer.
jens@0
   330
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
jens@0
   331
 and the following disclaimer in the documentation and/or other materials provided with the
jens@0
   332
 distribution.
jens@0
   333
 
jens@0
   334
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
jens@0
   335
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
jens@0
   336
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
jens@0
   337
 BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
jens@0
   338
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
jens@0
   339
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
jens@0
   340
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
jens@0
   341
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
jens@0
   342
 */