|
| 1 | +// Private CloudKit transport for the portable, validated save_sync bundle. |
| 2 | +#import <CloudKit/CloudKit.h> |
| 3 | +#import <CommonCrypto/CommonDigest.h> |
| 4 | +#import <Foundation/Foundation.h> |
| 5 | +#include <stdio.h> |
| 6 | +#include <string.h> |
| 7 | +#include "save_sync.h" |
| 8 | + |
| 9 | +static NSString *container_name(void) { |
| 10 | + NSString *name = [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMCloudSaveContainer"]; |
| 11 | + // The Mac game's helper executable inherits this from its signed launcher. |
| 12 | + if (![name isKindOfClass:NSString.class] || !name.length) { |
| 13 | + const char *v = getenv("DM_CLOUDKIT_CONTAINER"); |
| 14 | + if (v) name = [NSString stringWithUTF8String:v]; |
| 15 | + } |
| 16 | + return [name isKindOfClass:NSString.class] && [name hasPrefix:@"iCloud."] ? name : nil; |
| 17 | +} |
| 18 | + |
| 19 | +int front_cloudkit_configured(void) { |
| 20 | + @autoreleasepool { return container_name() != nil; } |
| 21 | +} |
| 22 | + |
| 23 | +static NSString *account_scope(CKContainer *container) { |
| 24 | + dispatch_semaphore_t done = dispatch_semaphore_create(0); |
| 25 | + __block NSString *account; |
| 26 | + [container fetchUserRecordIDWithCompletionHandler:^(CKRecordID *recordID, NSError *error) { |
| 27 | + if (!error && recordID.recordName.length) { |
| 28 | + NSString *identity = [NSString stringWithFormat:@"%@:%@", container.containerIdentifier, recordID.recordName]; |
| 29 | + NSData *data = [identity dataUsingEncoding:NSUTF8StringEncoding]; |
| 30 | + unsigned char digest[CC_SHA256_DIGEST_LENGTH]; |
| 31 | + CC_SHA256(data.bytes, (CC_LONG)data.length, digest); |
| 32 | + char hex[33] = {0}; |
| 33 | + for (unsigned i = 0; i < 16; ++i) snprintf(hex + 2*i, 3, "%02x", digest[i]); |
| 34 | + account = @(hex); |
| 35 | + } |
| 36 | + dispatch_semaphore_signal(done); |
| 37 | + }]; |
| 38 | + return dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 3*NSEC_PER_SEC)) == 0 ? account : nil; |
| 39 | +} |
| 40 | + |
| 41 | +int front_cloudkit_account(char scope[33]) { |
| 42 | + @autoreleasepool { |
| 43 | + NSString *name = container_name(); |
| 44 | + NSString *account = name ? account_scope([CKContainer containerWithIdentifier:name]) : nil; |
| 45 | + if (!account) return 0; |
| 46 | + memcpy(scope, account.UTF8String, 33); |
| 47 | + return 1; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +static CKDatabase *database_and_id(const char *path, CKRecordID **recordID) { |
| 52 | + NSString *name = container_name(); |
| 53 | + NSArray<NSString *> *components = [@(path) componentsSeparatedByString:@"/"]; |
| 54 | + if (!name || components.count != 4 || ![components[0] isEqualToString:@"cksave"] || |
| 55 | + components[1].length != 32 || components[2].length != 16 || |
| 56 | + ![components[3] isEqualToString:@"save.dmsync"]) return nil; |
| 57 | + CKContainer *container = [CKContainer containerWithIdentifier:name]; |
| 58 | + if (![account_scope(container) isEqualToString:components[1]]) return nil; |
| 59 | + // The account scope is also part of the private record key. An account |
| 60 | + // switch cannot write the same record in a different account mid-request. |
| 61 | + NSString *key = [NSString stringWithFormat:@"save1-%@-%@", components[1], components[2]]; |
| 62 | + *recordID = [[CKRecordID alloc] initWithRecordName:key]; |
| 63 | + return container.privateCloudDatabase; |
| 64 | +} |
| 65 | + |
| 66 | +static void configure(CKOperation *op, NSTimeInterval timeout) { |
| 67 | + op.configuration.qualityOfService = NSQualityOfServiceUserInitiated; |
| 68 | + op.configuration.timeoutIntervalForRequest = timeout; |
| 69 | + op.configuration.timeoutIntervalForResource = timeout; |
| 70 | +} |
| 71 | + |
| 72 | +static int fetch(CKDatabase *db, CKRecordID *rid, NSArray<NSString *> *keys, CKRecord **output) { |
| 73 | + CKFetchRecordsOperation *op = [[CKFetchRecordsOperation alloc] initWithRecordIDs:@[rid]]; |
| 74 | + op.desiredKeys = keys; |
| 75 | + configure(op, 5); |
| 76 | + dispatch_semaphore_t done = dispatch_semaphore_create(0); |
| 77 | + __block CKRecord *found; |
| 78 | + __block NSError *failure; |
| 79 | + // The Swift Result properties wrap these Objective-C completion blocks. |
| 80 | +#pragma clang diagnostic push |
| 81 | +#pragma clang diagnostic ignored "-Wdeprecated-declarations" |
| 82 | + op.perRecordCompletionBlock = ^(CKRecord *record, CKRecordID *recordID, NSError *error) { |
| 83 | + (void)recordID; |
| 84 | + found = record; failure = error; |
| 85 | + }; |
| 86 | + op.fetchRecordsCompletionBlock = ^(NSDictionary<CKRecordID *, CKRecord *> *records, NSError *error) { |
| 87 | + (void)records; |
| 88 | + if (!found && !failure) failure = error; |
| 89 | + dispatch_semaphore_signal(done); |
| 90 | + }; |
| 91 | + #pragma clang diagnostic pop |
| 92 | + [db addOperation:op]; |
| 93 | + if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 6*NSEC_PER_SEC))) { |
| 94 | + [op cancel]; return -1; |
| 95 | + } |
| 96 | + if (found) { *output = found; return 1; } |
| 97 | + return [failure.domain isEqualToString:CKErrorDomain] && failure.code == CKErrorUnknownItem ? 0 : -1; |
| 98 | +} |
| 99 | + |
| 100 | +int front_cloudkit_fetch(const char *path, const char *local) { |
| 101 | + @autoreleasepool { |
| 102 | + CKRecordID *rid = nil; |
| 103 | + CKDatabase *db = database_and_id(path, &rid); |
| 104 | + if (!db) return -1; |
| 105 | + CKRecord *record = nil; |
| 106 | + int got = fetch(db, rid, @[@"digest", @"bundle"], &record); |
| 107 | + if (got != 1) return got; |
| 108 | + CKAsset *asset = record[@"bundle"]; |
| 109 | + NSString *digest = record[@"digest"]; |
| 110 | + if (![asset isKindOfClass:CKAsset.class] || !asset.fileURL.isFileURL || |
| 111 | + ![digest isKindOfClass:NSString.class]) return -1; |
| 112 | + ss_meta meta; |
| 113 | + if (ss_read(asset.fileURL.fileSystemRepresentation, NULL, &meta) || ![digest isEqualToString:@(meta.hash)]) return -1; |
| 114 | + // The caller reserves a unique temporary path before starting fetch. |
| 115 | + NSFileManager *fm = NSFileManager.defaultManager; |
| 116 | + NSURL *dst = [NSURL fileURLWithPath:@(local)]; |
| 117 | + if (![fm removeItemAtURL:dst error:NULL]) return -1; |
| 118 | + return [fm copyItemAtURL:asset.fileURL toURL:dst error:NULL] ? 1 : -1; |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +int front_cloudkit_store(const char *local, const char *path, const char *expected) { |
| 123 | + @autoreleasepool { |
| 124 | + CKRecordID *rid = nil; |
| 125 | + CKDatabase *db = database_and_id(path, &rid); |
| 126 | + if (!db) return 0; |
| 127 | + CKRecord *record = nil; |
| 128 | + int got = fetch(db, rid, @[@"digest"], &record); |
| 129 | + if (got < 0 || (got == 0 && *expected) || |
| 130 | + (got == 1 && (!*expected || ![(id)record[@"digest"] isEqual:@(expected)]))) return 0; |
| 131 | + ss_meta meta; |
| 132 | + if (ss_read(local, NULL, &meta) || !meta.files) return 0; |
| 133 | + if (!record) record = [[CKRecord alloc] initWithRecordType:@"TonTonSaveV1" recordID:rid]; |
| 134 | + record[@"digest"] = @(meta.hash); |
| 135 | + record[@"bundle"] = [[CKAsset alloc] initWithFileURL:[NSURL fileURLWithPath:@(local)]]; |
| 136 | + CKModifyRecordsOperation *op = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:@[record] recordIDsToDelete:nil]; |
| 137 | + op.savePolicy = CKRecordSaveIfServerRecordUnchanged; |
| 138 | + configure(op, 10); |
| 139 | + dispatch_semaphore_t done = dispatch_semaphore_create(0); |
| 140 | + __block BOOL saved = NO; |
| 141 | + op.perRecordSaveBlock = ^(CKRecordID *key, CKRecord *savedRecord, NSError *error) { |
| 142 | + (void)key; |
| 143 | + saved = savedRecord != nil && error == nil; |
| 144 | + }; |
| 145 | + #pragma clang diagnostic push |
| 146 | + #pragma clang diagnostic ignored "-Wdeprecated-declarations" |
| 147 | + op.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deleted, NSError *error) { |
| 148 | + (void)savedRecords; (void)deleted; |
| 149 | + if (error) saved = NO; |
| 150 | + dispatch_semaphore_signal(done); |
| 151 | + }; |
| 152 | + #pragma clang diagnostic pop |
| 153 | + [db addOperation:op]; |
| 154 | + if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 11*NSEC_PER_SEC))) { |
| 155 | + [op cancel]; return 0; |
| 156 | + } |
| 157 | + return saved; |
| 158 | + } |
| 159 | +} |
0 commit comments