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