pEpObjCAdapter/PEPObjCAdapter.m
author Dirk Zimmermann <dirk@pep-project.org>
Fri, 09 Feb 2018 15:26:11 +0100
changeset 442 8de34676b7f5
parent 416 5a37145e3eca
child 484 e7b3f52190f1
permissions -rw-r--r--
IOS-937 set HOME early (and often) enough so tests can clean up
dirk@187
     1
//
edouard@191
     2
//  pEpObjCAdapter.m
edouard@191
     3
//  pEpObjCAdapter
dirk@187
     4
//
dirk@187
     5
//  Created by Volker Birk on 28.04.15.
dirk@187
     6
//  Copyright (c) 2015 p≡p. All rights reserved.
dirk@187
     7
//
dirk@187
     8
dirk@187
     9
@import Foundation;
dirk@187
    10
dirk@187
    11
#import "PEPObjCAdapter.h"
dirk@187
    12
#import "PEPObjCAdapter+Internal.h"
dirk@367
    13
#import "PEPMessageUtil.h"
dirk@187
    14
#include "keymanagement.h"
andreas@262
    15
#import "PEPCopyableThread.h"
dirk@187
    16
dirk@187
    17
///////////////////////////////////////////////////////////////////////////////
dirk@187
    18
//  Keyserver and Identity lookup - C part
dirk@187
    19
dirk@187
    20
int examine_identity(pEp_identity *ident, void *management)
dirk@187
    21
{
dirk@187
    22
    //PEPQueue *q = (__bridge PEPQueue *)management;
dirk@187
    23
    PEPQueue *q = [PEPObjCAdapter getLookupQueue];
dirk@187
    24
    
dirk@187
    25
    NSDictionary *identity = PEP_identityDictFromStruct(ident);
dirk@187
    26
    
dirk@187
    27
    [q enqueue:identity];
dirk@187
    28
    return 0;
dirk@187
    29
}
dirk@187
    30
dirk@187
    31
static pEp_identity *retrieve_next_identity(void *management)
dirk@187
    32
{
dirk@187
    33
    //PEPQueue *q = (__bridge PEPQueue *)management;
dirk@187
    34
    PEPQueue *q = [PEPObjCAdapter getLookupQueue];
dirk@187
    35
    
dirk@187
    36
    // Dequeue is a blocking operation
dirk@187
    37
    // that returns nil when queue is killed
dirk@187
    38
    NSDictionary *ident = [q dequeue];
dirk@187
    39
    
dirk@187
    40
    if (ident)
dirk@187
    41
        return PEP_identityDictToStruct(ident);
dirk@187
    42
    else
dirk@187
    43
        return NULL;
dirk@187
    44
}
dirk@187
    45
dirk@187
    46
///////////////////////////////////////////////////////////////////////////////
dirk@331
    47
// Sync - C part
dirk@331
    48
dirk@331
    49
// Called by sync thread only
dirk@331
    50
PEP_STATUS notify_handshake(void *unused_object, pEp_identity *me, pEp_identity *partner, sync_handshake_signal signal)
dirk@331
    51
{
dirk@331
    52
    id <PEPSyncDelegate> syncDelegate = [PEPObjCAdapter getSyncDelegate];
dirk@331
    53
    if ( syncDelegate )
dirk@331
    54
        return [syncDelegate
dirk@331
    55
                notifyHandshakeWithSignal:signal
dirk@331
    56
                me:PEP_identityDictFromStruct(me)
dirk@331
    57
                partner:PEP_identityDictFromStruct(partner)];
dirk@331
    58
    else
dirk@331
    59
        return PEP_SYNC_NO_NOTIFY_CALLBACK;
dirk@331
    60
}
dirk@331
    61
dirk@331
    62
// Called by sync thread only
dirk@331
    63
PEP_STATUS message_to_send(void *unused_object, message *msg)
dirk@331
    64
{
dirk@331
    65
    id <PEPSyncDelegate> syncDelegate = [PEPObjCAdapter getSyncDelegate];
dirk@331
    66
    if ( syncDelegate )
dirk@331
    67
        return [syncDelegate sendMessage:PEP_messageDictFromStruct(msg)];
dirk@331
    68
    else
dirk@331
    69
        return PEP_SEND_FUNCTION_NOT_REGISTERED;
dirk@331
    70
}
dirk@331
    71
dirk@331
    72
// called indirectly by decrypt message - any thread/session
dirk@331
    73
int inject_sync_msg(void *msg, void *unused_management)
dirk@331
    74
{
dirk@331
    75
    PEPQueue *q = [PEPObjCAdapter getSyncQueue];
dirk@331
    76
    [q enqueue:[NSValue valueWithPointer:msg]];
dirk@331
    77
    
dirk@331
    78
    return 0;
dirk@331
    79
}
dirk@331
    80
dirk@331
    81
// Called by sync thread only
dirk@331
    82
void *retrieve_next_sync_msg(void *unused_mamagement, time_t *timeout)
dirk@331
    83
{
dirk@331
    84
    bool needs_fastpoll = (*timeout != 0);
dirk@331
    85
    
dirk@331
    86
    id <PEPSyncDelegate> syncDelegate = [PEPObjCAdapter getSyncDelegate];
dirk@331
    87
    if ( syncDelegate && needs_fastpoll )
dirk@331
    88
        [syncDelegate fastPolling:true];
dirk@331
    89
    
dirk@331
    90
    PEPQueue *q = [PEPObjCAdapter getSyncQueue];
dirk@331
    91
    
dirk@331
    92
    void* result = (void*)[[q timedDequeue:timeout] pointerValue];
dirk@331
    93
    
dirk@331
    94
    if ( syncDelegate && needs_fastpoll )
dirk@331
    95
        [syncDelegate fastPolling:false];
dirk@331
    96
    
dirk@331
    97
    return result;
dirk@331
    98
    
dirk@331
    99
}
dirk@331
   100
dirk@187
   101
const char* _Nullable SystemDB = NULL;
dirk@187
   102
NSURL *s_homeURL;
dirk@254
   103
static NSLock *s_initLock;
andreas@416
   104
static BOOL s_unecryptedSubjectEnabled = NO;
dirk@187
   105
dirk@187
   106
@implementation PEPObjCAdapter
dirk@187
   107
andreas@416
   108
#pragma mark - SUBJECT PROTECTION
andreas@416
   109
andreas@416
   110
+ (BOOL)unecryptedSubjectEnabled;
andreas@416
   111
{
andreas@416
   112
    return s_unecryptedSubjectEnabled;
andreas@416
   113
}
andreas@416
   114
andreas@416
   115
+ (void)setUnecryptedSubjectEnabled:(BOOL)enabled;
andreas@416
   116
{
andreas@416
   117
    s_unecryptedSubjectEnabled = enabled;
andreas@416
   118
}
andreas@416
   119
andreas@416
   120
#pragma mark - DB PATHS
andreas@416
   121
dirk@187
   122
+ (void)initialize
dirk@187
   123
{
dirk@187
   124
    s_homeURL = [self createApplicationDirectory];
dirk@442
   125
    [self setHomeDirectory:s_homeURL]; // Important, defines $HOME and $TEMP for the engine
dirk@254
   126
    s_initLock = [[NSLock alloc] init];
dirk@254
   127
}
dirk@254
   128
dirk@254
   129
+ (NSLock *)initLock
dirk@254
   130
{
dirk@254
   131
    return s_initLock;
dirk@187
   132
}
dirk@187
   133
dirk@187
   134
+ (NSURL *)homeURL
dirk@187
   135
{
dirk@187
   136
    return s_homeURL;
dirk@187
   137
}
dirk@187
   138
dirk@187
   139
+ (NSURL *)createApplicationDirectory
dirk@187
   140
{
dirk@187
   141
    NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
dirk@187
   142
    if (!bundleID) {
dirk@187
   143
        // This can happen in unit tests
dirk@187
   144
        bundleID = @"test";
dirk@187
   145
    }
dirk@187
   146
    NSFileManager *fm = [NSFileManager defaultManager];
dirk@187
   147
    NSURL *dirPath = nil;
andreas@268
   148
    
dirk@187
   149
    // Find the application support directory in the home directory.
dirk@187
   150
    NSArray *appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory
dirk@187
   151
                                        inDomains:NSUserDomainMask];
dirk@187
   152
    if ([appSupportDir count] > 0)
dirk@187
   153
    {
dirk@187
   154
        // Append the bundle ID to the URL for the
dirk@187
   155
        // Application Support directory.
dirk@187
   156
        // Mainly needed for OS X, but doesn't do any harm on iOS
dirk@187
   157
        dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:bundleID];
andreas@268
   158
        
dirk@187
   159
        // If the directory does not exist, this method creates it.
dirk@187
   160
        // This method is only available in OS X v10.7 and iOS 5.0 or later.
dirk@187
   161
        NSError *theError = nil;
dirk@187
   162
        if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
dirk@187
   163
                           attributes:nil error:&theError])
dirk@187
   164
        {
dirk@187
   165
            // Handle the error.
dirk@187
   166
            return nil;
dirk@187
   167
        }
dirk@187
   168
    }
andreas@268
   169
    
dirk@187
   170
    return dirPath;
dirk@187
   171
}
dirk@187
   172
dirk@442
   173
+ (void)setHomeDirectory:(NSURL *)homeDir
dirk@187
   174
{
dirk@187
   175
    // create and set home directory
dirk@442
   176
    setenv("HOME", [[homeDir path] cStringUsingEncoding:NSUTF8StringEncoding], 1);
andreas@268
   177
    
dirk@187
   178
    // create and set temp directory
dirk@187
   179
    NSURL *tmpDirUrl = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
dirk@187
   180
    setenv("TEMP", [[tmpDirUrl path] cStringUsingEncoding:NSUTF8StringEncoding], 1);
dirk@187
   181
}
dirk@187
   182
andreas@276
   183
+ (NSString *)getBundlePathFor: (NSString *) filename
dirk@187
   184
{
dirk@187
   185
    return nil;
dirk@187
   186
}
dirk@187
   187
dirk@442
   188
+ (NSString *)copyAssetsIntoDocumentsDirectory:(NSBundle *)rootBundle
dirk@442
   189
                                    bundleName:(NSString *)bundleName
dirk@442
   190
                                      fileName:(NSString *)fileName {
andreas@268
   191
    
dirk@442
   192
    NSURL *homeUrl = s_homeURL;
dirk@187
   193
    NSString *documentsDirectory = [homeUrl path];
dirk@187
   194
    
dirk@187
   195
    if(!(documentsDirectory && bundleName && fileName))
dirk@187
   196
        return nil;
dirk@187
   197
    
dirk@187
   198
    // Check if the database file exists in the documents directory.
dirk@187
   199
    NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:fileName];
dirk@187
   200
    if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
dirk@187
   201
        // The file does not exist in the documents directory, so copy it from bundle now.
dirk@187
   202
        NSBundle *bundleObj = [NSBundle bundleWithPath:
dirk@187
   203
                               [[rootBundle resourcePath]
dirk@187
   204
                                stringByAppendingPathComponent: bundleName]];
dirk@187
   205
        if (!bundleObj)
dirk@187
   206
            return nil;
dirk@187
   207
        
dirk@187
   208
        NSString *sourcePath =[[bundleObj resourcePath] stringByAppendingPathComponent: fileName];
dirk@187
   209
        
dirk@187
   210
        NSError *error;
dirk@187
   211
        [[NSFileManager defaultManager]
dirk@187
   212
         copyItemAtPath:sourcePath toPath:destinationPath error:&error];
dirk@187
   213
        
dirk@187
   214
        // Check if any error occurred during copying and display it.
dirk@187
   215
        if (error != nil) {
dirk@187
   216
            NSLog(@"%@", [error localizedDescription]);
dirk@187
   217
            return nil;
dirk@187
   218
        }
dirk@187
   219
    }
dirk@187
   220
    NSLog(@"Asset %@ copied into %@", fileName, destinationPath);
dirk@187
   221
    return destinationPath;
dirk@187
   222
}
dirk@187
   223
dirk@187
   224
+ (void)setupTrustWordsDB:(NSBundle *)rootBundle{
dirk@442
   225
    NSString *systemDBPath = [PEPObjCAdapter
dirk@442
   226
                              copyAssetsIntoDocumentsDirectory:rootBundle
dirk@442
   227
                              bundleName:@"pEpTrustWords.bundle"
dirk@442
   228
                              fileName:@"system.db"];
dirk@187
   229
    if (SystemDB) {
dirk@187
   230
        free((void *) SystemDB);
dirk@187
   231
    }
dirk@187
   232
    SystemDB = strdup(systemDBPath.UTF8String);
dirk@187
   233
}
dirk@187
   234
dirk@187
   235
+ (void)setupTrustWordsDB
dirk@187
   236
{
dirk@187
   237
    [PEPObjCAdapter setupTrustWordsDB:[NSBundle mainBundle]];
dirk@187
   238
}
dirk@187
   239
dirk@187
   240
static NSMutableArray* boundSessions = nil;
dirk@187
   241
dirk@187
   242
+ (NSMutableArray*)boundSessions
dirk@187
   243
{
dirk@187
   244
    static dispatch_once_t once;
dirk@187
   245
    dispatch_once(&once, ^{
dirk@187
   246
        boundSessions =  [[NSMutableArray alloc] init];
dirk@187
   247
    });
dirk@187
   248
    return boundSessions;
dirk@187
   249
}
dirk@187
   250
dirk@187
   251
///////////////////////////////////////////////////////////////////////////////
dirk@187
   252
//  Keyserver and Identity lookup - ObjC part
dirk@187
   253
dirk@187
   254
static PEPQueue *lookupQueue = nil;
dirk@187
   255
static NSThread *lookupThread = nil;
dirk@187
   256
static NSConditionLock *lookupThreadJoinCond = nil;
dirk@187
   257
dirk@187
   258
+ (void)lookupThreadRoutine:(id)object
dirk@187
   259
{
dirk@187
   260
    [lookupThreadJoinCond lock];
andreas@268
   261
    
dirk@187
   262
    // FIXME: do_KeyManagement asserts if management is null.
dirk@187
   263
    do_keymanagement(retrieve_next_identity, "NOTNULL" /* (__bridge void *)queue */);
dirk@187
   264
    
dirk@187
   265
    // Set and signal join()
dirk@187
   266
    [lookupThreadJoinCond unlockWithCondition:YES];
dirk@187
   267
}
dirk@187
   268
dirk@187
   269
+ (void)startKeyserverLookup
dirk@187
   270
{
dirk@187
   271
    if (!lookupQueue)
dirk@187
   272
    {
dirk@187
   273
        lookupQueue = [[PEPQueue alloc]init];
dirk@187
   274
        
dirk@187
   275
        // There is no join() call on NSThreads.
dirk@187
   276
        lookupThreadJoinCond = [[NSConditionLock alloc] initWithCondition:NO];
dirk@187
   277
        
dirk@187
   278
        lookupThread = [[NSThread alloc] initWithTarget:self selector:@selector(lookupThreadRoutine:) object:nil];
dirk@187
   279
        [lookupThread start];
dirk@187
   280
    }
dirk@187
   281
}
dirk@187
   282
dirk@187
   283
+ (void)stopKeyserverLookup
dirk@187
   284
{
dirk@187
   285
    
dirk@187
   286
    if (lookupQueue)
dirk@187
   287
    {
dirk@187
   288
        // Flush queue and kick the consumer
dirk@187
   289
        [lookupQueue kill];
dirk@187
   290
        
dirk@187
   291
        // Thread then bailout. Wait for that.
dirk@187
   292
        [lookupThreadJoinCond lockWhenCondition:YES];
dirk@187
   293
        [lookupThreadJoinCond unlock];
dirk@187
   294
        
dirk@187
   295
        lookupThread = nil;
dirk@187
   296
        lookupQueue = nil;
dirk@187
   297
        lookupThreadJoinCond = nil;
dirk@187
   298
    }
dirk@187
   299
}
dirk@187
   300
dirk@187
   301
+ (void)registerExamineFunction:(PEP_SESSION)session
dirk@187
   302
{
dirk@187
   303
    register_examine_function(session, examine_identity, NULL /* (__bridge void *)queue */);
dirk@187
   304
}
dirk@187
   305
dirk@187
   306
+ (PEPQueue*)getLookupQueue
dirk@187
   307
{
dirk@187
   308
    return lookupQueue;
dirk@187
   309
}
dirk@187
   310
dirk@331
   311
///////////////////////////////////////////////////////////////////////////////
dirk@331
   312
// Sync - ObjC part
dirk@331
   313
dirk@331
   314
static PEPQueue *syncQueue = nil;
dirk@331
   315
static NSThread *syncThread = nil;
dirk@331
   316
static NSConditionLock *syncThreadJoinCond = nil;
dirk@331
   317
static PEP_SESSION sync_session = NULL;
dirk@331
   318
static id <PEPSyncDelegate> syncDelegate = nil;
dirk@331
   319
dirk@331
   320
dirk@331
   321
+ (void)syncThreadRoutine:(id)object
dirk@331
   322
{
dirk@331
   323
    [syncThreadJoinCond lock];
dirk@331
   324
    
dirk@331
   325
    
dirk@331
   326
    PEP_STATUS status;
dirk@331
   327
    
dirk@331
   328
    status = do_sync_protocol(sync_session,
dirk@331
   329
                              /* "object" : notifying, sending (unused) */
dirk@331
   330
                              "NOTNULL");
dirk@331
   331
    
dirk@331
   332
    // TODO : log something if status not as expected
dirk@331
   333
dirk@331
   334
    [syncThreadJoinCond unlockWithCondition:YES];
dirk@331
   335
}
dirk@331
   336
dirk@331
   337
+ (void)attachSyncSession:(PEP_SESSION)session
dirk@331
   338
{
dirk@331
   339
    if(sync_session)
dirk@331
   340
        attach_sync_session(session, sync_session);
dirk@331
   341
}
dirk@331
   342
dirk@331
   343
+ (void)detachSyncSession:(PEP_SESSION)session
dirk@331
   344
{
dirk@331
   345
    detach_sync_session(session);
dirk@331
   346
}
dirk@331
   347
dirk@331
   348
+ (void)startSync:(id <PEPSyncDelegate>)delegate;
dirk@331
   349
{
dirk@331
   350
    syncDelegate = delegate;
dirk@331
   351
    
dirk@333
   352
    if (!syncQueue) {
dirk@333
   353
        syncQueue = [[PEPQueue alloc] init];
dirk@331
   354
        
dirk@331
   355
        syncThreadJoinCond = [[NSConditionLock alloc] initWithCondition:NO];
dirk@331
   356
        
dirk@331
   357
        [[PEPObjCAdapter initLock] lock];
dirk@331
   358
        PEP_STATUS status = init(&sync_session);
dirk@331
   359
        [[PEPObjCAdapter initLock] unlock];
dirk@331
   360
        if (status != PEP_STATUS_OK) {
dirk@331
   361
            return;
dirk@331
   362
        }
dirk@331
   363
        
dirk@331
   364
        register_sync_callbacks(sync_session,
dirk@331
   365
                                /* "management" : queuing (unused) */
dirk@331
   366
                                "NOTNULL",
dirk@331
   367
                                message_to_send,
dirk@331
   368
                                notify_handshake,
dirk@331
   369
                                inject_sync_msg,
dirk@331
   370
                                retrieve_next_sync_msg);
dirk@331
   371
        
dirk@331
   372
        syncThread = [[NSThread alloc]
dirk@331
   373
                      initWithTarget:self
dirk@331
   374
                      selector:@selector(syncThreadRoutine:)
dirk@331
   375
                      object:nil];
dirk@331
   376
        
dirk@331
   377
        [syncThread start];
dirk@331
   378
    }
dirk@331
   379
    
dirk@331
   380
    NSMutableArray* sessionList = [PEPObjCAdapter boundSessions];
dirk@331
   381
    NSValue* v;
dirk@331
   382
    PEPInternalSession* session;
dirk@331
   383
    @synchronized (sessionList) {
dirk@331
   384
        for (v in sessionList) {
dirk@331
   385
            session = [v nonretainedObjectValue];
dirk@331
   386
            [PEPObjCAdapter attachSyncSession:[session session]];
dirk@331
   387
        }
dirk@331
   388
    }
dirk@331
   389
}
dirk@331
   390
dirk@331
   391
+ (void)stopSync
dirk@331
   392
{
dirk@331
   393
    NSMutableArray* sessionList = [PEPObjCAdapter boundSessions];
dirk@331
   394
    NSValue* v;
dirk@331
   395
    PEPInternalSession* session;
dirk@331
   396
    @synchronized (sessionList) {
dirk@331
   397
        for (v in sessionList) {
dirk@331
   398
            session = [v nonretainedObjectValue];
dirk@331
   399
            [PEPObjCAdapter detachSyncSession:[session session]];
dirk@331
   400
        }
dirk@331
   401
    }
dirk@331
   402
    
dirk@331
   403
    syncDelegate = nil;
dirk@331
   404
    
dirk@331
   405
    if (syncQueue)
dirk@331
   406
    {
dirk@331
   407
        [syncQueue purge:^(id item){
dirk@331
   408
            sync_msg_t *msg = [item pointerValue];
dirk@331
   409
            free_sync_msg(msg);
dirk@331
   410
        }];
dirk@331
   411
        
dirk@331
   412
        [syncThreadJoinCond lockWhenCondition:YES];
dirk@331
   413
        [syncThreadJoinCond unlock];
dirk@331
   414
        
dirk@331
   415
        [[PEPObjCAdapter initLock] lock];
dirk@331
   416
        release(sync_session);
dirk@331
   417
        [[PEPObjCAdapter initLock] unlock];
dirk@331
   418
        
dirk@331
   419
        sync_session = NULL;
dirk@331
   420
        syncThread = nil;
dirk@331
   421
        syncQueue = nil;
dirk@331
   422
        syncThreadJoinCond = nil;
dirk@331
   423
    }
dirk@331
   424
}
dirk@331
   425
dirk@331
   426
+ (PEPQueue*)getSyncQueue
dirk@331
   427
{
dirk@331
   428
    return syncQueue;
dirk@331
   429
}
dirk@331
   430
dirk@331
   431
+ (id <PEPSyncDelegate>)getSyncDelegate
dirk@331
   432
{
dirk@331
   433
    return syncDelegate;
dirk@331
   434
}
dirk@331
   435
dirk@331
   436
+ (void)bindSession:(PEPInternalSession*)session
dirk@331
   437
{
dirk@331
   438
    NSMutableArray* sessionList = [PEPObjCAdapter boundSessions];
dirk@331
   439
    @synchronized (sessionList) {
dirk@331
   440
        [sessionList addObject:[NSValue valueWithNonretainedObject:session]];
dirk@331
   441
    }
dirk@331
   442
    
dirk@331
   443
    [PEPObjCAdapter registerExamineFunction:[session session]];
dirk@331
   444
    [PEPObjCAdapter attachSyncSession:[session session]];
dirk@331
   445
}
dirk@331
   446
dirk@331
   447
+ (void)unbindSession:(PEPInternalSession*)session
dirk@331
   448
{
dirk@331
   449
    [PEPObjCAdapter detachSyncSession:[session session]];
dirk@331
   450
    
dirk@331
   451
    NSMutableArray* sessionList = [PEPObjCAdapter boundSessions];
dirk@331
   452
    @synchronized (sessionList) {
dirk@331
   453
        [sessionList removeObject:[NSValue valueWithNonretainedObject:session]];
dirk@331
   454
    }
dirk@331
   455
}
dirk@331
   456
dirk@187
   457
@end