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