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