2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import "CKKSKeychainView.h"
25 #import "CKKSGroupOperation.h"
26 #import "CKKSSynchronizeOperation.h"
27 #import "CKKSFetchAllRecordZoneChangesOperation.h"
28 #import "CKKSScanLocalItemsOperation.h"
29 #import "keychain/ckks/CloudKitCategories.h"
30 #import "keychain/categories/NSError+UsefulConstructors.h"
31 #import "keychain/ot/ObjCImprovements.h"
35 @interface CKKSSynchronizeOperation ()
36 @property int32_t restartCount;
39 @implementation CKKSSynchronizeOperation
41 - (instancetype)init {
44 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks {
45 if(self = [super init]) {
56 * Synchronizations (or resynchronizations) are complicated beasts. We will:
58 * 1. Finish processing the outgoing queue. You can't be in-sync with cloudkit if you have an update that hasn't propagated.
59 * 2. Kick off a normal CloudKit fetch.
60 * 3. Process the incoming queue as normal.
61 * (Note that this requires the keybag to be unlocked.)
63 * So far, this is normal operation. Now:
65 * 4. Start another CloudKit fetch, giving it the nil change tag. This fetches all objects in CloudKit.
66 * 4a. Compare those objects against our local mirror. If any discrepancies, this is a bug.
67 * 4b. All conflicts: CloudKit data wins.
68 * 4c. All items we have that CloudKit doesn't: delete locally.
70 * 5. Process the incoming queue again. This should be empty.
71 * 6. Scan the local keychain for items which exist locally but are not in CloudKit. Upload them.
72 * 7. If there are any such items in 6, restart the sync.
75 // Promote to strong reference
76 CKKSKeychainView* ckks = self.ckks;
78 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
79 [ckks dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
81 ckksnotice("ckksresync", ckks, "CKKSSynchronizeOperation cancelled, quitting");
82 return CKKSDatabaseTransactionRollback;
85 ckks.lastSynchronizeOperation = self;
89 ckksnotice("ckksresync", ckks, "Beginning resynchronize (attempt %u)", self.restartCount);
91 CKOperationGroup* operationGroup = [CKOperationGroup CKKSGroupWithName:@"ckks-resync"];
94 CKKSFetchAllRecordZoneChangesOperation* fetchOp = [[CKKSFetchAllRecordZoneChangesOperation alloc] initWithContainer:ckks.container
95 fetchClass:ckks.cloudKitClassDependencies.fetchRecordZoneChangesOperationClass
97 fetchReasons:[NSSet setWithObject:CKKSFetchBecauseResync]
100 ckoperationGroup:operationGroup];
101 fetchOp.name = [NSString stringWithFormat: @"resync-step%u-fetch", self.restartCount * steps + 1];
102 [self runBeforeGroupFinished: fetchOp];
105 CKKSIncomingQueueOperation* incomingOp = [[CKKSIncomingQueueOperation alloc] initWithDependencies:ckks.operationDependencies
107 intending:SecCKKSZoneKeyStateReady
108 errorState:SecCKKSZoneKeyStateUnhealthy
109 errorOnClassAFailure:true
110 handleMismatchedViewItems:false];
112 incomingOp.name = [NSString stringWithFormat: @"resync-step%u-incoming", self.restartCount * steps + 2];
113 [incomingOp addSuccessDependency:fetchOp];
114 [self runBeforeGroupFinished:incomingOp];
117 CKKSScanLocalItemsOperation* scan = [[CKKSScanLocalItemsOperation alloc] initWithDependencies:ckks.operationDependencies
119 intending:SecCKKSZoneKeyStateReady
120 errorState:SecCKKSZoneKeyStateError
121 ckoperationGroup:operationGroup];
122 scan.name = [NSString stringWithFormat: @"resync-step%u-scan", self.restartCount * steps + 3];
123 [scan addSuccessDependency: incomingOp];
124 [self runBeforeGroupFinished: scan];
127 CKKSOutgoingQueueOperation* outgoingOp = [ckks processOutgoingQueue: operationGroup];
128 outgoingOp.name = [NSString stringWithFormat: @"resync-step%u-outgoing", self.restartCount * steps + 4];
129 [self dependOnBeforeGroupFinished:outgoingOp];
130 [outgoingOp addDependency:scan];
133 CKKSResultOperation* restart = [[CKKSResultOperation alloc] init];
134 restart.name = [NSString stringWithFormat: @"resync-step%u-consider-restart", self.restartCount * steps + 5];
135 [restart addExecutionBlock:^{
138 ckkserror("ckksresync", ckks, "received callback for released object");
142 if(scan.recordsFound > 0) {
143 if(self.restartCount >= 3) {
144 // we've restarted too many times. Fail and stop.
145 ckkserror("ckksresync", ckks, "restarted synchronization too often; Failing");
146 self.error = [NSError errorWithDomain:@"securityd"
148 userInfo:@{NSLocalizedDescriptionKey: @"resynchronization restarted too many times; churn in database?"}];
150 // restart the sync operation.
151 self.restartCount += 1;
152 ckkserror("ckksresync", ckks, "restarting synchronization operation due to new local items");
158 [restart addSuccessDependency: outgoingOp];
159 [self runBeforeGroupFinished: restart];
161 return CKKSDatabaseTransactionCommit;