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@
26 #import <CloudKit/CloudKit.h>
27 #import <CloudKit/CloudKit_Private.h>
29 #import "keychain/ckks/CKKSAnalytics.h"
30 #import "keychain/ckks/CKKSCurrentKeyPointer.h"
31 #import "keychain/ckks/CKKSIncomingQueueEntry.h"
32 #import "keychain/ckks/CKKSItemEncrypter.h"
33 #import "keychain/ckks/CKKSKeychainView.h"
34 #import "keychain/ckks/CKKSManifest.h"
35 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
36 #import "keychain/ckks/CKKSOutgoingQueueOperation.h"
37 #import "keychain/ckks/CKKSReencryptOutgoingItemsOperation.h"
38 #import "keychain/ckks/CKKSStates.h"
39 #import "keychain/ckks/CKKSViewManager.h"
40 #import "keychain/ckks/CloudKitCategories.h"
41 #import "keychain/ot/ObjCImprovements.h"
43 #include "keychain/securityd/SecItemServer.h"
44 #include "keychain/securityd/SecItemDb.h"
45 #include <Security/SecItemPriv.h>
46 #import "CKKSPowerCollection.h"
47 #import "utilities/SecCoreAnalytics.h"
49 @interface CKKSOutgoingQueueOperation()
50 @property CKModifyRecordsOperation* modifyRecordsOperation;
53 @implementation CKKSOutgoingQueueOperation
54 @synthesize nextState = _nextState;
55 @synthesize intendedState = _intendedState;
57 - (instancetype)initWithDependencies:(CKKSOperationDependencies*)dependencies
58 ckks:(CKKSKeychainView*)ckks
59 intending:(OctagonState*)intending
60 errorState:(OctagonState*)errorState
61 ckoperationGroup:(CKOperationGroup*)ckoperationGroup
63 if(self = [super init]) {
66 _ckoperationGroup = ckoperationGroup;
68 _nextState = errorState;
69 _intendedState = intending;
71 [self addNullableDependency:ckks.holdOutgoingQueueOperation];
73 // Depend on all previous CKKSOutgoingQueueOperations
74 [self linearDependencies:ckks.outgoingQueueOperations];
76 // We also depend on the view being setup and the key hierarchy being reasonable
77 [self addNullableDependency:ckks.keyStateReadyDependency];
85 CKKSKeychainView* ckks = self.ckks;
87 ckkserror("ckksoutgoing", self.deps.zoneID, "no ckks object");
91 if(!ckks.itemSyncingEnabled) {
92 ckkserror("ckksoutgoing", self.deps.zoneID, "Item syncing for this view is disabled");
96 ckks.lastOutgoingQueueOperation = self;
98 [self.deps.databaseProvider dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
100 NSError* error = nil;
102 NSSet<NSString*>* priorityUUIDs = [[CKKSViewManager manager] pendingCallbackUUIDs];
104 NSMutableArray<CKKSOutgoingQueueEntry*>* priorityEntries = [NSMutableArray array];
105 NSMutableSet<NSString*>* priorityEntryUUIDs = [NSMutableSet set];
107 for(NSString* uuid in priorityUUIDs) {
108 NSError* priorityFetchError = nil;
109 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry tryFromDatabase:uuid zoneID:self.deps.zoneID error:&priorityFetchError];
111 if(priorityFetchError) {
112 ckkserror("ckksoutgoing", self.deps.zoneID, "Unable to fetch priority uuid %@: %@", uuid, priorityFetchError);
120 if(![oqe.state isEqualToString:SecCKKSStateNew]) {
121 ckksnotice("ckksoutgoing", self.deps.zoneID, "Priority uuid %@ is not in 'new': %@", uuid, oqe);
126 ckksnotice("ckksoutgoing", self.deps.zoneID, "Found OQE to fetch priority uuid %@: %@", uuid, priorityFetchError);
127 [priorityEntries addObject:oqe];
128 [priorityEntryUUIDs addObject:oqe.uuid];
132 // We only actually care about queue items in the 'new' state
133 NSArray<CKKSOutgoingQueueEntry*> * newEntries = [CKKSOutgoingQueueEntry fetch:SecCKKSOutgoingQueueItemsAtOnce
134 state:SecCKKSStateNew
135 zoneID:self.deps.zoneID
138 ckkserror("ckksoutgoing", self.deps.zoneID, "Error fetching outgoing queue records: %@", error);
140 return CKKSDatabaseTransactionRollback;
143 // Build our list of oqes to transmit
144 NSMutableArray<CKKSOutgoingQueueEntry*>* queueEntries = [priorityEntries mutableCopy];
145 for(CKKSOutgoingQueueEntry* oqe in newEntries) {
146 if(queueEntries.count >= SecCKKSOutgoingQueueItemsAtOnce) {
149 // We only need to add this OQE if it wasn't already there
150 if(![priorityEntryUUIDs containsObject:oqe.uuid]) {
151 [queueEntries addObject:oqe];
156 bool fullUpload = queueEntries.count >= SecCKKSOutgoingQueueItemsAtOnce;
158 [CKKSPowerCollection CKKSPowerEvent:kCKKSPowerEventOutgoingQueue zone:self.deps.zoneID.zoneName count:[queueEntries count]];
160 ckksinfo("ckksoutgoing", self.deps.zoneID, "processing outgoing queue: %@", queueEntries);
162 NSMutableDictionary<CKRecordID*, CKRecord*>* recordsToSave = [[NSMutableDictionary alloc] init];
163 NSMutableSet<CKRecordID*>* recordIDsModified = [[NSMutableSet alloc] init];
164 NSMutableSet<CKKSOutgoingQueueEntry*>*oqesModified = [[NSMutableSet alloc] init];
165 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
167 CKKSCurrentKeyPointer* currentClassAKeyPointer = [CKKSCurrentKeyPointer fromDatabase:SecCKKSKeyClassA zoneID:self.deps.zoneID error:&error];
168 CKKSCurrentKeyPointer* currentClassCKeyPointer = [CKKSCurrentKeyPointer fromDatabase:SecCKKSKeyClassC zoneID:self.deps.zoneID error:&error];
169 NSMutableDictionary<CKKSKeyClass*, CKKSCurrentKeyPointer*>* currentKeysToSave = [[NSMutableDictionary alloc] init];
170 bool needsReencrypt = false;
173 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't load current class keys: %@", error);
174 return CKKSDatabaseTransactionRollback;
177 for(CKKSOutgoingQueueEntry* oqe in queueEntries) {
179 secdebug("ckksoutgoing", "CKKSOutgoingQueueOperation cancelled, quitting");
180 return CKKSDatabaseTransactionRollback;
183 CKKSOutgoingQueueEntry* inflight = [CKKSOutgoingQueueEntry tryFromDatabase: oqe.uuid state:SecCKKSStateInFlight zoneID:self.deps.zoneID error:&error];
184 if(!error && inflight) {
185 // There is an inflight request with this UUID. Leave this request in-queue until CloudKit returns and we resolve the inflight request.
189 // If this item is not a delete, check the encryption status of this item.
190 if(![oqe.action isEqualToString: SecCKKSActionDelete]) {
191 // Check if this item is encrypted under a current key
192 if([oqe.item.parentKeyUUID isEqualToString: currentClassAKeyPointer.currentKeyUUID]) {
194 currentKeysToSave[SecCKKSKeyClassA] = currentClassAKeyPointer;
196 } else if([oqe.item.parentKeyUUID isEqualToString: currentClassCKeyPointer.currentKeyUUID]) {
198 currentKeysToSave[SecCKKSKeyClassC] = currentClassCKeyPointer;
201 // This item is encrypted under an old key. Set it up for reencryption and move on.
202 ckksnotice("ckksoutgoing", self.deps.zoneID, "Item's encryption key (%@ %@) is neither %@ or %@", oqe, oqe.item.parentKeyUUID, currentClassAKeyPointer, currentClassCKeyPointer);
203 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateReencrypt error:&error];
205 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save oqe to database: %@", error);
209 needsReencrypt = true;
214 if([oqe.action isEqualToString: SecCKKSActionAdd]) {
215 CKRecord* record = [oqe.item CKRecordWithZoneID:self.deps.zoneID];
216 recordsToSave[record.recordID] = record;
217 [recordIDsModified addObject: record.recordID];
218 [oqesModified addObject:oqe];
220 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateInFlight error:&error];
222 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save state for CKKSOutgoingQueueEntry: %@", error);
226 } else if ([oqe.action isEqualToString: SecCKKSActionDelete]) {
227 CKRecordID* recordIDToDelete = [[CKRecordID alloc] initWithRecordName:oqe.item.uuid zoneID:self.deps.zoneID];
228 [recordIDsToDelete addObject: recordIDToDelete];
229 [recordIDsModified addObject: recordIDToDelete];
230 [oqesModified addObject:oqe];
232 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateInFlight error:&error];
234 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save state for CKKSOutgoingQueueEntry: %@", error);
237 } else if ([oqe.action isEqualToString: SecCKKSActionModify]) {
238 // Load the existing item from the ckmirror.
239 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase:oqe.item.uuid zoneID:self.deps.zoneID error:&error];
241 // This is a problem: we have an update to an item that doesn't exist.
242 // Either: an Add operation we launched failed due to a CloudKit error (conflict?) and this is a follow-on update
244 ckkserror("ckksoutgoing", self.deps.zoneID, "update to a record that doesn't exist? %@", oqe.item.uuid);
246 CKRecord* record = [oqe.item CKRecordWithZoneID:self.deps.zoneID];
247 recordsToSave[record.recordID] = record;
248 [recordIDsModified addObject: record.recordID];
249 [oqesModified addObject:oqe];
251 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateInFlight error:&error];
253 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save state for CKKSOutgoingQueueEntry: %@", error);
257 if(![oqe.item.storedCKRecord.recordChangeTag isEqual: ckme.item.storedCKRecord.recordChangeTag]) {
258 // The mirror entry has updated since this item was created. If we proceed, we might end up with
259 // a badly-authenticated record.
260 ckksnotice("ckksoutgoing", self.deps.zoneID, "Record (%@)'s change tag doesn't match ckmirror's change tag, reencrypting", oqe);
261 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateReencrypt error:&error];
263 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save oqe to database: %@", error);
267 needsReencrypt = true;
270 // Grab the old ckrecord and update it
271 CKRecord* record = [oqe.item updateCKRecord: ckme.item.storedCKRecord zoneID: self.deps.zoneID];
272 recordsToSave[record.recordID] = record;
273 [recordIDsModified addObject: record.recordID];
274 [oqesModified addObject:oqe];
276 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateInFlight error:&error];
278 ckkserror("ckksoutgoing", self.deps.zoneID, "couldn't save state for CKKSOutgoingQueueEntry: %@", error);
285 ckksnotice("ckksoutgoing", self.deps.zoneID, "An item needs reencryption!");
286 [self.deps.flagHandler _onqueueHandleFlag:CKKSFlagItemReencryptionNeeded];
289 if([recordsToSave count] == 0 && [recordIDsToDelete count] == 0) {
290 // Nothing to do! exit.
291 ckksnotice("ckksoutgoing", self.deps.zoneID, "Nothing in outgoing queue to process");
292 if(self.ckoperationGroup) {
293 ckksinfo("ckksoutgoing", self.deps.zoneID, "End of operation group: %@", self.ckoperationGroup);
298 self.itemsProcessed = recordsToSave.count;
300 NSBlockOperation* modifyComplete = [[NSBlockOperation alloc] init];
301 modifyComplete.name = @"modifyRecordsComplete";
302 [self dependOnBeforeGroupFinished: modifyComplete];
304 void (^modifyRecordsCompletionBlock)(NSArray<CKRecord*>*, NSArray<CKRecordID*>*, NSError*) = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
306 CKKSKeychainView* strongCKKS = self.ckks;
307 if(!self || !strongCKKS) {
308 ckkserror("ckksoutgoing", self.deps.zoneID, "received callback for released object");
312 CKKSAnalytics* logger = [CKKSAnalytics logger];
314 [self.deps.databaseProvider dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
316 ckkserror("ckksoutgoing", self.deps.zoneID, "error processing outgoing queue: %@", ckerror);
318 [logger logRecoverableError:ckerror
319 forEvent:CKKSEventProcessOutgoingQueue
320 zoneName:self.deps.zoneID.zoneName
321 withAttributes:NULL];
323 // Tell CKKS about any out-of-date records
324 [strongCKKS _onqueueCKWriteFailed:ckerror attemptedRecordsChanged:recordsToSave];
326 // Check if these are due to key records being out of date. We'll see a CKErrorBatchRequestFailed, with a bunch of errors inside
327 if([ckerror.domain isEqualToString:CKErrorDomain] && (ckerror.code == CKErrorPartialFailure)) {
328 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = ckerror.userInfo[CKPartialErrorsByItemIDKey];
330 bool askForReencrypt = false;
332 if([self _onqueueIsErrorBadEtagOnKeyPointersOnly:ckerror]) {
333 // The current key pointers have updated without our knowledge, so CloudKit failed this operation. Mark all records as 'needs reencryption' and kick that off.
334 ckksnotice("ckksoutgoing", self.deps.zoneID, "Error is simply due to current key pointers changing; marking all records as 'needs reencrypt'");
335 [self _onqueueModifyAllRecords:failedRecords.allKeys as:SecCKKSStateReencrypt];
336 askForReencrypt = true;
338 } else if([self _onqueueIsErrorMissingSyncKey:ckerror]) {
339 ckksnotice("ckksoutgoing", self.deps.zoneID, "Error is due to the key records missing. Marking all as 'needs reencrypt'");
340 [self _onqueueModifyAllRecords:failedRecords.allKeys as:SecCKKSStateReencrypt];
341 askForReencrypt = true;
344 // Iterate all failures, and reset each item
345 for(CKRecordID* recordID in failedRecords) {
346 NSError* recordError = failedRecords[recordID];
348 ckksnotice("ckksoutgoing", self.deps.zoneID, "failed record: %@ %@", recordID, recordError);
350 if([recordError.domain isEqualToString: CKErrorDomain] && recordError.code == CKErrorServerRecordChanged) {
351 if([recordID.recordName isEqualToString: SecCKKSKeyClassA] ||
352 [recordID.recordName isEqualToString: SecCKKSKeyClassC]) {
353 // Note that _onqueueCKWriteFailed is responsible for kicking the key state machine, so we don't need to do it here.
354 askForReencrypt = true;
356 // CKErrorServerRecordChanged on an item update means that we've been overwritten.
357 if([recordIDsModified containsObject:recordID]) {
358 [self _onqueueModifyRecordAsError:recordID recordError:recordError];
361 } else if([recordError.domain isEqualToString: CKErrorDomain] && recordError.code == CKErrorBatchRequestFailed) {
362 // Also fine. This record only didn't succeed because something else failed.
363 // OQEs should be placed back into the 'new' state, unless they've been overwritten by a new OQE. Other records should be ignored.
365 if([recordIDsModified containsObject:recordID]) {
366 NSError* localerror = nil;
367 CKKSOutgoingQueueEntry* inflightOQE = [CKKSOutgoingQueueEntry tryFromDatabase:recordID.recordName state:SecCKKSStateInFlight zoneID:recordID.zoneID error:&localerror];
368 [strongCKKS _onqueueChangeOutgoingQueueEntry:inflightOQE toState:SecCKKSStateNew error:&localerror];
370 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't clean up outgoing queue entry: %@", localerror);
375 // Some unknown error occurred on this record. If it's an OQE, move it to the error state.
376 ckkserror("ckksoutgoing", self.deps.zoneID, "Unknown error on row: %@ %@", recordID, recordError);
377 if([recordIDsModified containsObject:recordID]) {
378 [self _onqueueModifyRecordAsError:recordID recordError:recordError];
384 if(askForReencrypt) {
385 [self.deps.flagHandler _onqueueHandleFlag:CKKSFlagItemReencryptionNeeded];
388 // Some non-partial error occured. We should place all "inflight" OQEs back into the outgoing queue.
389 ckksnotice("ckks", self.deps.zoneID, "Error is scary: putting all inflight OQEs back into state 'new'");
390 [self _onqueueModifyAllRecords:[recordIDsModified allObjects] as:SecCKKSStateNew];
393 self.error = ckerror;
394 return CKKSDatabaseTransactionCommit;
397 for(CKRecordID* deletedRecordID in deletedRecordIDs) {
398 ckksnotice("ckksoutgoing", self.deps.zoneID, "Record deletion successful for %@", deletedRecordID.recordName);
401 ckksnotice("ckksoutgoing", self.deps.zoneID, "Completed processing outgoing queue (%d modifications, %d deletions)", (int)savedRecords.count, (int)deletedRecordIDs.count);
402 NSError* error = NULL;
403 CKKSPowerCollection *plstats = [[CKKSPowerCollection alloc] init];
405 for(CKRecord* record in savedRecords) {
406 // Save the item records
407 if([record.recordType isEqualToString: SecCKRecordItemType]) {
408 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry fromDatabase:record.recordID.recordName
409 state:SecCKKSStateInFlight
410 zoneID:self.deps.zoneID
412 [strongCKKS _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&error];
414 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't update %@ in outgoingqueue: %@", record.recordID.recordName, error);
418 CKKSMirrorEntry* ckme = [[CKKSMirrorEntry alloc] initWithCKRecord: record];
419 [ckme saveToDatabase: &error];
421 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't save %@ to ckmirror: %@", record.recordID.recordName, error);
425 [plstats storedOQE:oqe];
427 // And the CKCurrentKeyRecords (do we need to do this? Will the server update the change tag on a save which saves nothing?)
428 } else if([record.recordType isEqualToString: SecCKRecordCurrentKeyType]) {
429 CKKSCurrentKeyPointer* currentkey = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: record];
430 [currentkey saveToDatabase: &error];
432 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't save %@ to currentkey: %@", record.recordID.recordName, error);
436 } else if ([record.recordType isEqualToString:SecCKRecordDeviceStateType]) {
437 CKKSDeviceStateEntry* newcdse = [[CKKSDeviceStateEntry alloc] initWithCKRecord:record];
438 [newcdse saveToDatabase:&error];
440 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't save %@ to ckdevicestate: %@", record.recordID.recordName, error);
444 } else if ([record.recordType isEqualToString:SecCKRecordManifestType]) {
446 } else if (![record.recordType isEqualToString:SecCKRecordManifestLeafType]) {
447 ckkserror("ckksoutgoing", self.deps.zoneID, "unknown record type in results: %@", record);
451 // Delete the deleted record IDs
452 for(CKRecordID* ckrecordID in deletedRecordIDs) {
454 NSError* error = nil;
455 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry fromDatabase:ckrecordID.recordName
456 state:SecCKKSStateInFlight
457 zoneID:self.deps.zoneID
459 [strongCKKS _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&error];
461 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't delete %@ from outgoingqueue: %@", ckrecordID.recordName, error);
465 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase: ckrecordID.recordName zoneID:self.deps.zoneID error:&error];
466 [ckme deleteFromDatabase: &error];
468 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't delete %@ from ckmirror: %@", ckrecordID.recordName, error);
472 [plstats deletedOQE:oqe];
478 ckkserror("ckksoutgoing", self.deps.zoneID, "Operation failed; rolling back: %@", self.error);
479 [logger logRecoverableError:self.error
480 forEvent:CKKSEventProcessOutgoingQueue
481 zoneName:strongCKKS.zoneName
482 withAttributes:NULL];
483 return CKKSDatabaseTransactionRollback;
485 [logger logSuccessForEvent:CKKSEventProcessOutgoingQueue zoneName:strongCKKS.zoneName];
487 return CKKSDatabaseTransactionCommit;
490 self.nextState = self.intendedState;
491 [self.operationQueue addOperation: modifyComplete];
493 // If this was a "full upload", or we errored in any way, then kick off another queue process. There might be more items to send!
494 if(fullUpload || self.error) {
495 // If we think the network is iffy, though, wait for it to come back
496 CKKSResultOperation* possibleNetworkDependency = nil;
497 CKKSReachabilityTracker* reachabilityTracker = strongCKKS.reachabilityTracker;
498 if(ckerror && [reachabilityTracker isNetworkError:ckerror]) {
499 possibleNetworkDependency = reachabilityTracker.reachabilityDependency;
502 [strongCKKS processOutgoingQueueAfter:possibleNetworkDependency
503 requiredDelay:fullUpload && !ckerror ? NSEC_PER_MSEC * 100 : DISPATCH_TIME_FOREVER
504 ckoperationGroup:self.ckoperationGroup];
508 ckksinfo("ckksoutgoing", self.deps.zoneID, "Current keys to update: %@", currentKeysToSave);
509 for(CKKSCurrentKeyPointer* keypointer in currentKeysToSave.allValues) {
510 CKRecord* record = [keypointer CKRecordWithZoneID:self.deps.zoneID];
511 recordsToSave[record.recordID] = record;
514 // Piggyback on this operation to update our device state
515 NSError* cdseError = nil;
516 CKKSDeviceStateEntry* cdse = [ckks _onqueueCurrentDeviceStateEntry:&cdseError];
517 CKRecord* cdseRecord = [cdse CKRecordWithZoneID:self.deps.zoneID];
519 ckkserror("ckksoutgoing", self.deps.zoneID, "Can't make current device state: %@", cdseError);
520 } else if(!cdseRecord) {
521 ckkserror("ckksoutgoing", self.deps.zoneID, "Can't make current device state cloudkit record, but no reason why");
523 // Add the CDSE to the outgoing records
524 // TODO: maybe only do this every few hours?
525 ckksnotice("ckksoutgoing", self.deps.zoneID, "Updating device state: %@", cdse);
526 recordsToSave[cdseRecord.recordID] = cdseRecord;
529 ckksinfo("ckksoutgoing", self.deps.zoneID, "Saving records %@ to CloudKit zone %@", recordsToSave, self.deps.zoneID);
531 self.modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave.allValues recordIDsToDelete:recordIDsToDelete];
532 self.modifyRecordsOperation.atomic = TRUE;
534 // Until <rdar://problem/38725728> Changes to discretionary-ness (explicit or derived from QoS) should be "live", all requests should be nondiscretionary
535 self.modifyRecordsOperation.configuration.automaticallyRetryNetworkFailures = NO;
536 self.modifyRecordsOperation.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
537 self.modifyRecordsOperation.configuration.isCloudKitSupportOperation = YES;
539 self.modifyRecordsOperation.savePolicy = CKRecordSaveIfServerRecordUnchanged;
540 self.modifyRecordsOperation.group = self.ckoperationGroup;
541 ckksnotice("ckksoutgoing", self.deps.zoneID, "QoS: %d; operation group is %@", (int)self.modifyRecordsOperation.qualityOfService, self.modifyRecordsOperation.group);
542 ckksnotice("ckksoutgoing", self.deps.zoneID, "Beginning upload for %d records, deleting %d records",
543 (int)recordsToSave.count,
544 (int)recordIDsToDelete.count);
546 for(CKRecordID* recordID in [recordsToSave allKeys]) {
547 ckksinfo("ckksoutgoing", self.deps.zoneID, "Record to save: %@", recordID);
549 for(CKRecordID* recordID in recordIDsToDelete) {
550 ckksinfo("ckksoutgoing", self.deps.zoneID, "Record to delete: %@", recordID);
553 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
557 ckksnotice("ckksoutgoing", self.deps.zoneID, "Record upload successful for %@ (%@)", record.recordID.recordName, record.recordChangeTag);
559 ckkserror("ckksoutgoing", self.deps.zoneID, "error on row: %@ %@", error, record);
563 self.modifyRecordsOperation.modifyRecordsCompletionBlock = modifyRecordsCompletionBlock;
564 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
565 [ckks.database addOperation: self.modifyRecordsOperation];
571 - (void)_onqueueModifyRecordAsError:(CKRecordID*)recordID recordError:(NSError*)itemerror {
572 CKKSKeychainView* ckks = self.ckks;
574 ckkserror("ckksoutgoing", self.deps.zoneID, "no CKKS object");
578 dispatch_assert_queue(ckks.queue);
580 NSError* error = nil;
583 // At this stage, cloudkit doesn't give us record types
584 if([recordID.recordName isEqualToString: SecCKKSKeyClassA] ||
585 [recordID.recordName isEqualToString: SecCKKSKeyClassC] ||
586 [recordID.recordName hasPrefix:@"Manifest:-:"] ||
587 [recordID.recordName hasPrefix:@"ManifestLeafRecord:-:"]) {
588 // Nothing to do here. We need a whole key refetch and synchronize.
590 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry fromDatabase:recordID.recordName state:SecCKKSStateInFlight zoneID:self.deps.zoneID error:&error];
591 [ckks _onqueueErrorOutgoingQueueEntry: oqe itemError: itemerror error:&error];
593 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't set OQE %@ as error: %@", recordID.recordName, error);
601 - (void)_onqueueModifyAllRecords:(NSArray<CKRecordID*>*)recordIDs as:(CKKSItemState*)state {
602 CKKSKeychainView* ckks = self.ckks;
604 ckkserror("ckksoutgoing", self.deps.zoneID, "no CKKS object");
608 dispatch_assert_queue(ckks.queue);
610 NSError* error = nil;
613 for(CKRecordID* recordID in recordIDs) {
614 // At this stage, cloudkit doesn't give us record types
615 if([recordID.recordName isEqualToString: SecCKKSKeyClassA] ||
616 [recordID.recordName isEqualToString: SecCKKSKeyClassC]) {
617 // Nothing to do here. We need a whole key refetch and synchronize.
619 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry fromDatabase:recordID.recordName state:SecCKKSStateInFlight zoneID:self.deps.zoneID error:&error];
620 [ckks _onqueueChangeOutgoingQueueEntry:oqe toState:state error:&error];
622 ckkserror("ckksoutgoing", self.deps.zoneID, "Couldn't set OQE %@ as %@: %@", recordID.recordName, state, error);
629 if([state isEqualToString:SecCKKSStateReencrypt]) {
630 [SecCoreAnalytics sendEvent:SecCKKSAggdItemReencryption event:@{SecCoreAnalyticsValue: [NSNumber numberWithUnsignedInteger:count]}];
634 - (BOOL)_onqueueIsErrorMissingSyncKey:(NSError*)ckerror {
635 if([ckerror.domain isEqualToString:CKErrorDomain] && (ckerror.code == CKErrorPartialFailure)) {
636 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = ckerror.userInfo[CKPartialErrorsByItemIDKey];
638 for(CKRecordID* recordID in failedRecords) {
639 NSError* recordError = failedRecords[recordID];
641 if([recordError isCKKSServerPluginError:CKKSServerMissingRecord]) {
642 ckksnotice("ckksoutgoing", recordID.zoneID, "Error is a 'missing record' error: %@", recordError);
651 - (bool)_onqueueIsErrorBadEtagOnKeyPointersOnly:(NSError*)ckerror {
652 CKKSKeychainView* ckks = self.ckks;
653 dispatch_assert_queue(ckks.queue);
654 bool anyOtherErrors = false;
656 if([ckerror.domain isEqualToString:CKErrorDomain] && (ckerror.code == CKErrorPartialFailure)) {
657 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = ckerror.userInfo[CKPartialErrorsByItemIDKey];
659 for(CKRecordID* recordID in failedRecords) {
660 NSError* recordError = failedRecords[recordID];
662 if([recordError.domain isEqualToString: CKErrorDomain] && recordError.code == CKErrorServerRecordChanged) {
663 if([recordID.recordName isEqualToString: SecCKKSKeyClassA] ||
664 [recordID.recordName isEqualToString: SecCKKSKeyClassC]) {
667 // Some record other than the key pointers changed.
668 anyOtherErrors |= true;
672 // Some other error than ServerRecordChanged
673 anyOtherErrors |= true;
679 return !anyOtherErrors;