BLIP/BLIPTest.m
author jim@Baldrick.local
Tue May 05 23:24:50 2009 -0700 (2009-05-05)
changeset 43 aab592ac36fc
parent 26 cb9cdf247239
child 35 a9dd5ac5ff11
permissions -rw-r--r--
bug fixes and improvements to new bonjour classes and tcplistener, also added a static library target
jens@0
     1
//
jens@0
     2
//  BLIPTest.m
jens@0
     3
//  MYNetwork
jens@0
     4
//
jens@0
     5
//  Created by Jens Alfke on 5/13/08.
jens@0
     6
//  Copyright 2008 Jens Alfke. All rights reserved.
jens@0
     7
//
jens@0
     8
jens@0
     9
#ifndef NDEBUG
jens@0
    10
jens@0
    11
jens@0
    12
#import "BLIPRequest.h"
jens@0
    13
#import "BLIPProperties.h"
jens@0
    14
#import "BLIPConnection.h"
jens@1
    15
jens@0
    16
#import "IPAddress.h"
jens@0
    17
#import "Target.h"
jens@1
    18
#import "CollectionUtils.h"
jens@1
    19
#import "Logging.h"
jens@1
    20
#import "Test.h"
jens@0
    21
jens@26
    22
#import <Security/Security.h>
jens@26
    23
#import <SecurityInterface/SFChooseIdentityPanel.h>
jens@26
    24
jens@26
    25
@interface TCPEndpoint ()
jens@26
    26
+ (NSString*) describeCert: (SecCertificateRef)cert;
jens@26
    27
+ (NSString*) describeIdentity: (SecIdentityRef)identity;
jens@26
    28
@end
jens@0
    29
jens@1
    30
jens@11
    31
#define kListenerHost               @"localhost"
jens@0
    32
#define kListenerPort               46353
jens@0
    33
#define kSendInterval               0.5
jens@0
    34
#define kNBatchedMessages           20
jens@0
    35
#define kUseCompression             YES
jens@0
    36
#define kUrgentEvery                4
jens@18
    37
#define kListenerCloseAfter         50
jens@22
    38
#define kClientAcceptCloseRequest   YES
jens@0
    39
jens@26
    40
#define kListenerUsesSSL            YES     // Does the listener (server) use an SSL connection?
jens@26
    41
#define kListenerRequiresClientCert YES     // Does the listener require clients to have an SSL cert?
jens@26
    42
#define kClientRequiresSSL          YES     // Does the client require the listener to use SSL?
jens@26
    43
#define kClientUsesSSLCert          YES     // Does the client use an SSL cert?
jens@26
    44
jens@26
    45
jens@26
    46
static SecIdentityRef ChooseIdentity( NSString *prompt ) {
jens@26
    47
    NSMutableArray *identities = [NSMutableArray array];
jens@26
    48
    SecKeychainRef kc;
jens@26
    49
    SecKeychainCopyDefault(&kc);
jens@26
    50
    SecIdentitySearchRef search;
jens@26
    51
    SecIdentitySearchCreate(kc, CSSM_KEYUSE_ANY, &search);
jens@26
    52
    SecIdentityRef identity;
jens@26
    53
    while (SecIdentitySearchCopyNext(search, &identity) == noErr)
jens@26
    54
        [identities addObject: (id)identity];
jens@29
    55
    CFRelease(search);
jens@26
    56
    Log(@"Found %u identities -- prompting '%@'", identities.count, prompt);
jens@26
    57
    if (identities.count > 0) {
jens@26
    58
        SFChooseIdentityPanel *panel = [SFChooseIdentityPanel sharedChooseIdentityPanel];
jens@26
    59
        if ([panel runModalForIdentities: identities message: prompt] == NSOKButton) {
jens@26
    60
            Log(@"Using SSL identity: %@", panel.identity);
jens@26
    61
            return panel.identity;
jens@26
    62
        }
jens@26
    63
    }
jens@26
    64
    return NULL;
jens@26
    65
}
jens@0
    66
jens@0
    67
static SecIdentityRef GetClientIdentity(void) {
jens@26
    68
    return ChooseIdentity(@"Choose an identity for the BLIP Client Test:");
jens@0
    69
}
jens@0
    70
jens@0
    71
static SecIdentityRef GetListenerIdentity(void) {
jens@26
    72
    return ChooseIdentity(@"Choose an identity for the BLIP Listener Test:");
jens@0
    73
}
jens@0
    74
jens@0
    75
jens@0
    76
#pragma mark -
jens@0
    77
#pragma mark CLIENT TEST:
jens@0
    78
jens@0
    79
jens@0
    80
@interface BLIPConnectionTester : NSObject <BLIPConnectionDelegate>
jens@0
    81
{
jens@0
    82
    BLIPConnection *_conn;
jens@0
    83
    NSMutableDictionary *_pending;
jens@0
    84
}
jens@0
    85
jens@0
    86
@end
jens@0
    87
jens@0
    88
jens@0
    89
@implementation BLIPConnectionTester
jens@0
    90
jens@0
    91
- (id) init
jens@0
    92
{
jens@0
    93
    self = [super init];
jens@0
    94
    if (self != nil) {
jens@0
    95
        Log(@"** INIT %@",self);
jens@0
    96
        _pending = [[NSMutableDictionary alloc] init];
jens@11
    97
        IPAddress *addr = [[IPAddress alloc] initWithHostname: kListenerHost port: kListenerPort];
jens@0
    98
        _conn = [[BLIPConnection alloc] initToAddress: addr];
jens@0
    99
        if( ! _conn ) {
jens@0
   100
            [self release];
jens@0
   101
            return nil;
jens@0
   102
        }
jens@26
   103
        if( kClientUsesSSLCert ) {
jens@26
   104
            [_conn setPeerToPeerIdentity: GetClientIdentity()];
jens@26
   105
        } else if( kClientRequiresSSL ) {
jens@26
   106
            _conn.SSLProperties = $mdict({kTCPPropertySSLAllowsAnyRoot, $true},
jens@26
   107
                                        {(id)kCFStreamSSLPeerName, [NSNull null]});
jens@0
   108
        }
jens@0
   109
        _conn.delegate = self;
jens@0
   110
        Log(@"** Opening connection...");
jens@0
   111
        [_conn open];
jens@0
   112
    }
jens@0
   113
    return self;
jens@0
   114
}
jens@0
   115
jens@0
   116
- (void) dealloc
jens@0
   117
{
jens@0
   118
    Log(@"** %@ closing",self);
jens@0
   119
    [_conn close];
jens@0
   120
    [_conn release];
jens@0
   121
    [super dealloc];
jens@0
   122
}
jens@0
   123
jens@0
   124
- (void) sendAMessage
jens@0
   125
{
jens@18
   126
    if( _conn.status==kTCP_Open || _conn.status==kTCP_Opening ) {
jens@18
   127
        if(_pending.count<100) {
jens@18
   128
            Log(@"** Sending another %i messages...", kNBatchedMessages);
jens@18
   129
            for( int i=0; i<kNBatchedMessages; i++ ) {
jens@18
   130
                size_t size = random() % 32768;
jens@18
   131
                NSMutableData *body = [NSMutableData dataWithLength: size];
jens@18
   132
                UInt8 *bytes = body.mutableBytes;
jens@18
   133
                for( size_t i=0; i<size; i++ )
jens@18
   134
                    bytes[i] = i % 256;
jens@18
   135
                
jens@18
   136
                BLIPRequest *q = [_conn requestWithBody: body
jens@18
   137
                                             properties: $dict({@"Content-Type", @"application/octet-stream"},
jens@18
   138
                                                               {@"User-Agent", @"BLIPConnectionTester"},
jens@18
   139
                                                               {@"Date", [[NSDate date] description]},
jens@18
   140
                                                               {@"Size",$sprintf(@"%u",size)})];
jens@18
   141
                Assert(q);
jens@18
   142
                if( kUseCompression && (random()%2==1) )
jens@18
   143
                    q.compressed = YES;
jens@18
   144
                if( random()%16 > 12 )
jens@18
   145
                    q.urgent = YES;
jens@18
   146
                BLIPResponse *response = [q send];
jens@18
   147
                Assert(response);
jens@18
   148
                Assert(q.number>0);
jens@18
   149
                Assert(response.number==q.number);
jens@18
   150
                [_pending setObject: $object(size) forKey: $object(q.number)];
jens@18
   151
                response.onComplete = $target(self,responseArrived:);
jens@18
   152
            }
jens@18
   153
        } else {
jens@18
   154
            Warn(@"There are %u pending messages; waiting for the listener to catch up...",_pending.count);
jens@11
   155
        }
jens@18
   156
        [self performSelector: @selector(sendAMessage) withObject: nil afterDelay: kSendInterval];
jens@0
   157
    }
jens@0
   158
}
jens@0
   159
jens@0
   160
- (void) responseArrived: (BLIPResponse*)response
jens@0
   161
{
jens@0
   162
    Log(@"********** called responseArrived: %@",response);
jens@0
   163
}
jens@0
   164
jens@0
   165
- (void) connectionDidOpen: (TCPConnection*)connection
jens@0
   166
{
jens@0
   167
    Log(@"** %@ didOpen",connection);
jens@0
   168
    [self sendAMessage];
jens@0
   169
}
jens@0
   170
- (BOOL) connection: (TCPConnection*)connection authorizeSSLPeer: (SecCertificateRef)peerCert
jens@0
   171
{
jens@26
   172
    Log(@"** %@ authorizeSSLPeer: %@",self, [TCPEndpoint describeCert:peerCert]);
jens@0
   173
    return peerCert != nil;
jens@0
   174
}
jens@0
   175
- (void) connection: (TCPConnection*)connection failedToOpen: (NSError*)error
jens@0
   176
{
jens@26
   177
    Warn(@"** %@ failedToOpen: %@",connection,error);
jens@0
   178
    CFRunLoopStop(CFRunLoopGetCurrent());
jens@0
   179
}
jens@0
   180
- (void) connectionDidClose: (TCPConnection*)connection
jens@0
   181
{
jens@26
   182
    if (connection.error)
jens@26
   183
        Warn(@"** %@ didClose: %@", connection,connection.error);
jens@26
   184
    else
jens@26
   185
        Log(@"** %@ didClose", connection);
jens@0
   186
    setObj(&_conn,nil);
jens@0
   187
    [NSObject cancelPreviousPerformRequestsWithTarget: self];
jens@0
   188
    CFRunLoopStop(CFRunLoopGetCurrent());
jens@0
   189
}
jens@0
   190
- (void) connection: (BLIPConnection*)connection receivedRequest: (BLIPRequest*)request
jens@0
   191
{
jens@0
   192
    Log(@"***** %@ received %@",connection,request);
jens@2
   193
    [request respondWithData: request.body contentType: request.contentType];
jens@0
   194
}
jens@0
   195
jens@0
   196
- (void) connection: (BLIPConnection*)connection receivedResponse: (BLIPResponse*)response
jens@0
   197
{
jens@0
   198
    Log(@"********** %@ received %@",connection,response);
jens@0
   199
    NSNumber *sizeObj = [_pending objectForKey: $object(response.number)];
jens@0
   200
jens@0
   201
    if( response.error )
jens@0
   202
        Warn(@"Got error response: %@",response.error);
jens@0
   203
    else {
jens@0
   204
        NSData *body = response.body;
jens@0
   205
        size_t size = body.length;
jens@0
   206
        Assert(size<32768);
jens@0
   207
        const UInt8 *bytes = body.bytes;
jens@0
   208
        for( size_t i=0; i<size; i++ )
jens@0
   209
            AssertEq(bytes[i],i % 256);
jens@26
   210
        AssertEq(size,sizeObj.unsignedIntValue);
jens@0
   211
    }
jens@0
   212
    Assert(sizeObj);
jens@0
   213
    [_pending removeObjectForKey: $object(response.number)];
jens@0
   214
    Log(@"Now %u replies pending", _pending.count);
jens@0
   215
}
jens@0
   216
jens@19
   217
- (BOOL) connectionReceivedCloseRequest: (BLIPConnection*)connection
jens@19
   218
{
jens@22
   219
    BOOL response = kClientAcceptCloseRequest;
jens@19
   220
    Log(@"***** %@ received a close request; returning %i",connection,response);
jens@19
   221
    return response;
jens@19
   222
}
jens@19
   223
jens@0
   224
jens@0
   225
@end
jens@0
   226
jens@0
   227
jens@0
   228
TestCase(BLIPConnection) {
jens@26
   229
    SecKeychainSetUserInteractionAllowed(true);
jens@0
   230
    BLIPConnectionTester *tester = [[BLIPConnectionTester alloc] init];
jens@0
   231
    CAssert(tester);
jens@0
   232
    
jens@0
   233
    [[NSRunLoop currentRunLoop] run];
jens@0
   234
    
jens@0
   235
    Log(@"** Runloop stopped");
jens@0
   236
    [tester release];
jens@0
   237
}
jens@0
   238
jens@0
   239
jens@0
   240
jens@0
   241
jens@0
   242
#pragma mark LISTENER TEST:
jens@0
   243
jens@0
   244
jens@0
   245
@interface BLIPTestListener : NSObject <TCPListenerDelegate, BLIPConnectionDelegate>
jens@0
   246
{
jens@0
   247
    BLIPListener *_listener;
jens@18
   248
    int _nReceived;
jens@0
   249
}
jens@0
   250
jens@0
   251
@end
jens@0
   252
jens@0
   253
jens@0
   254
@implementation BLIPTestListener
jens@0
   255
jens@0
   256
- (id) init
jens@0
   257
{
jens@0
   258
    self = [super init];
jens@0
   259
    if (self != nil) {
jens@0
   260
        _listener = [[BLIPListener alloc] initWithPort: kListenerPort];
jens@0
   261
        _listener.delegate = self;
jens@0
   262
        _listener.pickAvailablePort = YES;
jens@0
   263
        _listener.bonjourServiceType = @"_bliptest._tcp";
jens@26
   264
        if( kListenerUsesSSL ) {
jens@26
   265
            [_listener setPeerToPeerIdentity: GetListenerIdentity()];
jens@26
   266
            if (!kListenerRequiresClientCert)
jens@26
   267
                [_listener setSSLProperty: $object(kTCPTryAuthenticate) 
jens@26
   268
                                   forKey: kTCPPropertySSLClientSideAuthentication];
jens@0
   269
        }
jens@0
   270
        Assert( [_listener open] );
jens@0
   271
        Log(@"%@ is listening...",self);
jens@0
   272
    }
jens@0
   273
    return self;
jens@0
   274
}
jens@0
   275
jens@0
   276
- (void) dealloc
jens@0
   277
{
jens@0
   278
    Log(@"%@ closing",self);
jens@0
   279
    [_listener close];
jens@0
   280
    [_listener release];
jens@0
   281
    [super dealloc];
jens@0
   282
}
jens@0
   283
jens@0
   284
- (void) listener: (TCPListener*)listener didAcceptConnection: (TCPConnection*)connection
jens@0
   285
{
jens@0
   286
    Log(@"** %@ accepted %@",self,connection);
jens@0
   287
    connection.delegate = self;
jens@0
   288
}
jens@0
   289
jens@0
   290
- (void) listener: (TCPListener*)listener failedToOpen: (NSError*)error
jens@0
   291
{
jens@0
   292
    Log(@"** BLIPTestListener failed to open: %@",error);
jens@0
   293
}
jens@0
   294
jens@0
   295
- (void) listenerDidOpen: (TCPListener*)listener   {Log(@"** BLIPTestListener did open");}
jens@0
   296
- (void) listenerDidClose: (TCPListener*)listener   {Log(@"** BLIPTestListener did close");}
jens@0
   297
jens@0
   298
- (BOOL) listener: (TCPListener*)listener shouldAcceptConnectionFrom: (IPAddress*)address
jens@0
   299
{
jens@0
   300
    Log(@"** %@ shouldAcceptConnectionFrom: %@",self,address);
jens@0
   301
    return YES;
jens@0
   302
}
jens@0
   303
jens@0
   304
jens@0
   305
- (void) connectionDidOpen: (TCPConnection*)connection
jens@0
   306
{
jens@0
   307
    Log(@"** %@ didOpen [SSL=%@]",connection,connection.actualSecurityLevel);
jens@18
   308
    _nReceived = 0;
jens@0
   309
}
jens@0
   310
- (BOOL) connection: (TCPConnection*)connection authorizeSSLPeer: (SecCertificateRef)peerCert
jens@0
   311
{
jens@26
   312
    Log(@"** %@ authorizeSSLPeer: %@",self, [TCPEndpoint describeCert:peerCert]);
jens@0
   313
    return peerCert != nil || ! kListenerRequiresClientCert;
jens@0
   314
}
jens@0
   315
- (void) connection: (TCPConnection*)connection failedToOpen: (NSError*)error
jens@0
   316
{
jens@0
   317
    Log(@"** %@ failedToOpen: %@",connection,error);
jens@0
   318
}
jens@0
   319
- (void) connectionDidClose: (TCPConnection*)connection
jens@0
   320
{
jens@26
   321
    if (connection.error)
jens@26
   322
        Warn(@"** %@ didClose: %@", connection,connection.error);
jens@26
   323
    else
jens@26
   324
        Log(@"** %@ didClose", connection);
jens@0
   325
    [connection release];
jens@0
   326
}
jens@0
   327
- (void) connection: (BLIPConnection*)connection receivedRequest: (BLIPRequest*)request
jens@0
   328
{
jens@0
   329
    Log(@"***** %@ received %@",connection,request);
jens@0
   330
    NSData *body = request.body;
jens@0
   331
    size_t size = body.length;
jens@0
   332
    Assert(size<32768);
jens@0
   333
    const UInt8 *bytes = body.bytes;
jens@0
   334
    for( size_t i=0; i<size; i++ )
jens@0
   335
        AssertEq(bytes[i],i % 256);
jens@0
   336
    
jens@0
   337
    AssertEqual([request valueOfProperty: @"Content-Type"], @"application/octet-stream");
jens@13
   338
    Assert([request valueOfProperty: @"User-Agent"] != nil);
jens@26
   339
    AssertEq((size_t)[[request valueOfProperty: @"Size"] intValue], size);
jens@0
   340
jens@2
   341
    [request respondWithData: body contentType: request.contentType];
jens@18
   342
    
jens@18
   343
    if( ++ _nReceived == kListenerCloseAfter ) {
jens@18
   344
        Log(@"********** Closing BLIPTestListener after %i requests",_nReceived);
jens@18
   345
        [connection close];
jens@18
   346
    }
jens@0
   347
}
jens@0
   348
jens@19
   349
- (BOOL) connectionReceivedCloseRequest: (BLIPConnection*)connection;
jens@19
   350
{
jens@19
   351
    Log(@"***** %@ received a close request",connection);
jens@19
   352
    return YES;
jens@19
   353
}
jens@19
   354
jens@19
   355
- (void) connection: (BLIPConnection*)connection closeRequestFailedWithError: (NSError*)error
jens@19
   356
{
jens@19
   357
    Log(@"***** %@'s close request failed: %@",connection,error);
jens@19
   358
}
jens@19
   359
jens@0
   360
jens@0
   361
@end
jens@0
   362
jens@0
   363
jens@0
   364
TestCase(BLIPListener) {
jens@0
   365
    EnableLogTo(BLIP,YES);
jens@0
   366
    EnableLogTo(PortMapper,YES);
jens@0
   367
    EnableLogTo(Bonjour,YES);
jens@26
   368
    SecKeychainSetUserInteractionAllowed(true);
jens@0
   369
    BLIPTestListener *listener = [[BLIPTestListener alloc] init];
jens@0
   370
    
jens@0
   371
    [[NSRunLoop currentRunLoop] run];
jens@0
   372
    
jens@0
   373
    [listener release];
jens@0
   374
}
jens@0
   375
jens@0
   376
jens@0
   377
#endif
jens@0
   378
jens@0
   379
jens@0
   380
/*
jens@0
   381
 Copyright (c) 2008, Jens Alfke <jens@mooseyard.com>. All rights reserved.
jens@0
   382
 
jens@0
   383
 Redistribution and use in source and binary forms, with or without modification, are permitted
jens@0
   384
 provided that the following conditions are met:
jens@0
   385
 
jens@0
   386
 * Redistributions of source code must retain the above copyright notice, this list of conditions
jens@0
   387
 and the following disclaimer.
jens@0
   388
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
jens@0
   389
 and the following disclaimer in the documentation and/or other materials provided with the
jens@0
   390
 distribution.
jens@0
   391
 
jens@0
   392
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
jens@0
   393
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
jens@0
   394
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
jens@0
   395
 BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
jens@0
   396
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
jens@0
   397
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
jens@0
   398
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
jens@0
   399
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
jens@0
   400
 */