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