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 "CKKSIncomingQueueOperation.h"
26 #import "CKKSIncomingQueueEntry.h"
27 #import "CKKSItemEncrypter.h"
28 #import "CKKSOutgoingQueueEntry.h"
30 #import "CKKSManifest.h"
31 #import "CKKSAnalytics.h"
32 #import "CKKSPowerCollection.h"
33 #import "keychain/ckks/CKKSCurrentItemPointer.h"
35 #include <securityd/SecItemServer.h>
36 #include <securityd/SecItemDb.h>
37 #include <Security/SecItemPriv.h>
39 #include <utilities/SecADWrapper.h>
43 @interface CKKSIncomingQueueOperation ()
44 @property bool newOutgoingEntries;
45 @property bool pendingClassAEntries;
46 @property bool missingKey;
49 @implementation CKKSIncomingQueueOperation
51 - (instancetype)init {
54 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks errorOnClassAFailure:(bool)errorOnClassAFailure {
55 if(self = [super init]) {
58 // Can't process unless we have a reasonable key hierarchy.
59 if(ckks.keyStateReadyDependency) {
60 [self addDependency: ckks.keyStateReadyDependency];
63 [self addNullableDependency: ckks.holdIncomingQueueOperation];
65 _errorOnClassAFailure = errorOnClassAFailure;
66 _pendingClassAEntries = false;
68 [self linearDependencies:ckks.incomingQueueOperations];
70 if ([CKKSManifest shouldSyncManifests]) {
71 __weak __typeof(self) weakSelf = self;
72 __weak CKKSKeychainView* weakCKKS = ckks;
73 CKKSResultOperation* updateManifestOperation = [CKKSResultOperation operationWithBlock:^{
74 __strong __typeof(self) strongSelf = weakSelf;
75 __strong CKKSKeychainView* strongCKKS = weakCKKS;
76 __block NSError* error = nil;
77 if (!strongCKKS || !strongSelf) {
78 ckkserror("ckksincoming", strongCKKS, "update manifest operation fired for released object");
82 [strongCKKS dispatchSyncWithAccountKeys:^bool{
83 strongCKKS.latestManifest = [CKKSManifest latestTrustedManifestForZone:strongCKKS.zoneName error:&error];
85 strongSelf.error = error;
86 ckkserror("ckksincoming", strongCKKS, "failed to get latest manifest: %@", error);
94 updateManifestOperation.name = @"update-manifest-operation";
96 [ckks scheduleOperation:updateManifestOperation];
97 [self addSuccessDependency:updateManifestOperation];
103 - (bool)processNewCurrentItemPointers:(NSArray<CKKSCurrentItemPointer*>*)queueEntries withManifest:(CKKSManifest*)manifest egoManifest:(CKKSEgoManifest*)egoManifest
105 CKKSKeychainView* ckks = self.ckks;
107 NSError* error = nil;
108 for(CKKSCurrentItemPointer* p in queueEntries) {
110 if ([CKKSManifest shouldSyncManifests]) {
111 if (![manifest validateCurrentItem:p withError:&error]) {
112 ckkserror("ckksincoming", ckks, "Unable to validate current item pointer (%@) against manifest (%@)", p, manifest);
113 if ([CKKSManifest shouldEnforceManifests]) {
119 p.state = SecCKKSProcessedStateLocal;
121 [p saveToDatabase:&error];
122 ckksnotice("ckkspointer", ckks, "Saving new current item pointer: %@", p);
124 ckkserror("ckksincoming", ckks, "Error saving new current item pointer: %@ %@", error, p);
127 // Schedule a view change notification
128 [ckks.notifyViewChangedScheduler trigger];
132 if(queueEntries.count > 0) {
133 // Schedule a view change notification
134 [ckks.notifyViewChangedScheduler trigger];
137 return (error == nil);
140 - (bool)processQueueEntries:(NSArray<CKKSIncomingQueueEntry*>*)queueEntries withManifest:(CKKSManifest*)manifest egoManifest:(CKKSEgoManifest*)egoManifest
142 CKKSKeychainView* ckks = self.ckks;
144 NSMutableArray* newOrChangedRecords = [[NSMutableArray alloc] init];
145 NSMutableArray* deletedRecordIDs = [[NSMutableArray alloc] init];
147 for(id entry in queueEntries) {
150 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
154 NSError* error = nil;
156 CKKSIncomingQueueEntry* iqe = (CKKSIncomingQueueEntry*) entry;
157 ckksnotice("ckksincoming", ckks, "ready to process an incoming queue entry: %@ %@ %@", iqe, iqe.uuid, iqe.action);
159 // Note that we currently unencrypt the item before deleting it, instead of just deleting it
160 // This finds the class, which is necessary for the deletion process. We could just try to delete
161 // across all classes, though...
162 NSMutableDictionary* attributes = [[CKKSItemEncrypter decryptItemToDictionary: iqe.item error:&error] mutableCopy];
163 if(!attributes || error) {
164 if([ckks.lockStateTracker isLockedError:error]) {
165 NSError* localerror = nil;
166 ckkserror("ckksincoming", ckks, "Keychain is locked; can't decrypt IQE %@", iqe);
167 CKKSKey* key = [CKKSKey tryFromDatabase:iqe.item.parentKeyUUID zoneID:ckks.zoneID error:&localerror];
168 if(localerror || ([key.keyclass isEqualToString:SecCKKSKeyClassA] && self.errorOnClassAFailure)) {
172 // If this isn't an error, make sure it gets processed later.
173 if([key.keyclass isEqualToString:SecCKKSKeyClassA] && !self.errorOnClassAFailure) {
174 self.pendingClassAEntries = true;
177 } else if ([error.domain isEqualToString:@"securityd"] && error.code == errSecItemNotFound) {
178 ckkserror("ckksincoming", ckks, "Coudn't find key in keychain; will attempt to poke key hierarchy: %@", error)
179 self.missingKey = true;
182 ckkserror("ckksincoming", ckks, "Couldn't decrypt IQE %@ for some reason: %@", iqe, error);
185 self.errorItemsProcessed += 1;
189 // Add the UUID (which isn't stored encrypted)
190 [attributes setValue: iqe.item.uuid forKey: (__bridge NSString*) kSecAttrUUID];
192 // Add the PCS plaintext fields, if they exist
193 if(iqe.item.plaintextPCSServiceIdentifier) {
194 [attributes setValue: iqe.item.plaintextPCSServiceIdentifier forKey: (__bridge NSString*) kSecAttrPCSPlaintextServiceIdentifier];
196 if(iqe.item.plaintextPCSPublicKey) {
197 [attributes setValue: iqe.item.plaintextPCSPublicKey forKey: (__bridge NSString*) kSecAttrPCSPlaintextPublicKey];
199 if(iqe.item.plaintextPCSPublicIdentity) {
200 [attributes setValue: iqe.item.plaintextPCSPublicIdentity forKey: (__bridge NSString*) kSecAttrPCSPlaintextPublicIdentity];
203 // This item is also synchronizable (by definition)
204 [attributes setValue: @(YES) forKey: (__bridge NSString*) kSecAttrSynchronizable];
206 NSString* classStr = [attributes objectForKey: (__bridge NSString*) kSecClass];
207 if(![classStr isKindOfClass: [NSString class]]) {
208 self.error = [NSError errorWithDomain:@"securityd"
209 code:errSecInternalError
210 userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Item did not have a reasonable class: %@", classStr]}];
211 ckkserror("ckksincoming", ckks, "Synced item seems wrong: %@", self.error);
212 self.errorItemsProcessed += 1;
216 const SecDbClass * classP = !classStr ? NULL : kc_class_with_name((__bridge CFStringRef) classStr);
219 ckkserror("ckksincoming", ckks, "unknown class in object: %@ %@", classStr, iqe);
220 iqe.state = SecCKKSStateError;
221 [iqe saveToDatabase:&error];
223 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
226 self.errorItemsProcessed += 1;
231 // Now, filter: if this item was added locally, would it go to this view?
232 // In this release, this is based solely on viewhint
233 NSString* viewHint = attributes[(id)kSecAttrSyncViewHint];
234 bool itemIsForView = [viewHint isEqualToString: ckks.zoneName];
237 ckkserror("ckksincoming", ckks, "ViewHint in decrypted item (%@) does not match (%@), skipping item", viewHint, ckks.zoneName);
238 iqe.state = SecCKKSStateZoneMismatch;
239 [iqe saveToDatabase:&error];
241 ckkserror("ckksincoming", ckks, "Couldn't save zone mismatch IQE to database: %@", error);
247 if([iqe.action isEqualToString: SecCKKSActionAdd] || [iqe.action isEqualToString: SecCKKSActionModify]) {
248 BOOL requireManifestValidation = [CKKSManifest shouldEnforceManifests];
249 BOOL manifestValidatesItem = [manifest validateItem:iqe.item withError:&error];
251 if (!requireManifestValidation || manifestValidatesItem) {
252 [self _onqueueHandleIQEChange: iqe attributes:attributes class:classP];
253 [newOrChangedRecords addObject:[iqe.item CKRecordWithZoneID:ckks.zoneID]];
256 ckkserror("ckksincoming", ckks, "could not validate incoming item against manifest with error: %@", error);
257 if (![self _onqueueUpdateIQE:iqe withState:SecCKKSStateUnauthenticated error:&error]) {
258 ckkserror("ckksincoming", ckks, "failed to save incoming item back to database in unauthenticated state with error: %@", error);
261 self.errorItemsProcessed += 1;
264 } else if ([iqe.action isEqualToString: SecCKKSActionDelete]) {
265 BOOL requireManifestValidation = [CKKSManifest shouldEnforceManifests];
266 BOOL manifestValidatesDelete = ![manifest itemUUIDExistsInManifest:iqe.uuid];
268 if (!requireManifestValidation || manifestValidatesDelete) {
269 // if the item does not exist in the latest manifest, we're good to delete it
270 [self _onqueueHandleIQEDelete: iqe class:classP];
271 [deletedRecordIDs addObject:[[CKRecordID alloc] initWithRecordName:iqe.uuid zoneID:ckks.zoneID]];
274 // if the item DOES exist in the manifest, we can't trust the deletion
275 ckkserror("ckksincoming", ckks, "could not validate incoming item deletion against manifest");
276 if (![self _onqueueUpdateIQE:iqe withState:SecCKKSStateUnauthenticated error:&error]) {
277 ckkserror("ckksincoming", ckks, "failed to save incoming item deletion back to database in unauthenticated state with error: %@", error);
279 self.errorItemsProcessed += 1;
287 if(newOrChangedRecords.count > 0 || deletedRecordIDs > 0) {
288 // Schedule a view change notification
289 [ckks.notifyViewChangedScheduler trigger];
292 if(self.missingKey) {
293 [ckks.pokeKeyStateMachineScheduler trigger];
296 if ([CKKSManifest shouldSyncManifests]) {
297 [egoManifest updateWithNewOrChangedRecords:newOrChangedRecords deletedRecordIDs:deletedRecordIDs];
302 - (bool)_onqueueUpdateIQE:(CKKSIncomingQueueEntry*)iqe withState:(NSString*)newState error:(NSError**)error
304 if (![iqe.state isEqualToString:newState]) {
305 NSMutableDictionary* oldWhereClause = iqe.whereClauseToFindSelf.mutableCopy;
306 oldWhereClause[@"state"] = iqe.state;
307 iqe.state = newState;
308 if ([iqe saveToDatabase:error]) {
309 if (![CKKSSQLDatabaseObject deleteFromTable:[iqe.class sqlTable] where:oldWhereClause connection:NULL error:error]) {
322 // Synchronous, on some thread. Get back on the CKKS queue for thread-safety.
323 CKKSKeychainView* ckks = self.ckks;
325 ckkserror("ckksincoming", ckks, "no CKKS object");
329 __weak __typeof(self) weakSelf = self;
330 self.completionBlock = ^(void) {
331 __strong __typeof(self) strongSelf = weakSelf;
333 ckkserror("ckksincoming", ckks, "received callback for released object");
337 CKKSAnalytics* logger = [CKKSAnalytics logger];
339 if (!strongSelf.error) {
340 [logger logSuccessForEvent:CKKSEventProcessIncomingQueueClassC inView:ckks];
341 if (!strongSelf.pendingClassAEntries) {
342 [logger logSuccessForEvent:CKKSEventProcessIncomingQueueClassA inView:ckks];
345 [logger logRecoverableError:strongSelf.error
346 forEvent:strongSelf.errorOnClassAFailure ? CKKSEventProcessIncomingQueueClassA : CKKSEventProcessIncomingQueueClassC
348 withAttributes:NULL];
352 __block bool errored = false;
353 [ckks dispatchSync: ^bool{
355 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
358 ckks.lastIncomingQueueOperation = self;
360 ckksnotice("ckksincoming", ckks, "Processing incoming queue");
362 if ([CKKSManifest shouldSyncManifests]) {
363 if (!ckks.latestManifest) {
364 // Until we can make manifests in our unit tests, we can't abort here
365 ckkserror("ckksincoming", ckks, "no manifest in ckks");
367 if (!ckks.egoManifest) {
368 ckkserror("ckksincoming", ckks, "no ego manifest in ckks");
372 bool ok = true; // Should commit transaction?
373 __block NSError* error = nil;
375 if ([CKKSManifest shouldSyncManifests]) {
376 NSInteger unauthenticatedItemCount = [CKKSIncomingQueueEntry countByState:SecCKKSStateUnauthenticated zone:ckks.zoneID error:&error];
377 if (error || unauthenticatedItemCount < 0) {
378 ckkserror("ckksincoming", ckks, "Error fetching incoming queue state counts: %@", error);
383 // take any existing unauthenticated entries and put them back in the new state
384 NSArray<CKKSIncomingQueueEntry*>* unauthenticatedEntries = nil;
385 NSString* lastMaxUUID = nil;
386 NSInteger numEntriesProcessed = 0;
387 while (numEntriesProcessed < unauthenticatedItemCount && (unauthenticatedEntries == nil || unauthenticatedEntries.count == SecCKKSIncomingQueueItemsAtOnce)) {
389 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
393 unauthenticatedEntries = [CKKSIncomingQueueEntry fetch:SecCKKSIncomingQueueItemsAtOnce
394 startingAtUUID:lastMaxUUID
395 state:SecCKKSStateUnauthenticated
399 ckkserror("ckksincoming", ckks, "Error fetching unauthenticated queue records: %@", error);
404 if (unauthenticatedEntries.count == 0) {
405 ckksinfo("ckksincoming", ckks, "No unauthenticated entries in incoming queue to process");
409 for (CKKSIncomingQueueEntry* unauthenticatedEntry in unauthenticatedEntries) {
410 if (![self _onqueueUpdateIQE:unauthenticatedEntry withState:SecCKKSStateNew error:&error]) {
411 ckkserror("ckksincoming", ckks, "Error saving unauthenticated entry back to new state: %@", error);
416 lastMaxUUID = ([lastMaxUUID compare:unauthenticatedEntry.uuid] == NSOrderedDescending) ? lastMaxUUID : unauthenticatedEntry.uuid;
425 ckksnotice("ckksincoming", ckks, "Early-exiting from IncomingQueueOperation");
429 // Now for the tricky bit: take and drop the account queue for each batch of queue entries
430 // This is for peak memory concerns, but also to allow keychain API clients to make changes while we're processing many items
431 // Note that IncomingQueueOperations are no longer transactional: they can partially succeed. This might make them harder to reason about.
432 __block NSUInteger lastCount = SecCKKSIncomingQueueItemsAtOnce;
433 __block NSString* lastMaxUUID = nil;
435 while(lastCount == SecCKKSIncomingQueueItemsAtOnce) {
436 [ckks dispatchSync: ^bool{
437 NSArray<CKKSIncomingQueueEntry*> * queueEntries = nil;
439 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
444 NSError* error = nil;
446 queueEntries = [CKKSIncomingQueueEntry fetch: SecCKKSIncomingQueueItemsAtOnce
447 startingAtUUID:lastMaxUUID
448 state:SecCKKSStateNew
453 ckkserror("ckksincoming", ckks, "Error fetching incoming queue records: %@", error);
459 lastCount = queueEntries.count;
461 if([queueEntries count] == 0) {
462 // Nothing to do! exit.
463 ckksnotice("ckksincoming", ckks, "Nothing in incoming queue to process");
467 [CKKSPowerCollection CKKSPowerEvent:kCKKSPowerEventOutgoingQueue zone:ckks.zoneName count:[queueEntries count]];
469 if (![self processQueueEntries:queueEntries withManifest:ckks.latestManifest egoManifest:ckks.egoManifest]) {
470 ckksnotice("ckksincoming", ckks, "processQueueEntries didn't complete successfully");
475 // Find the highest UUID for the next fetch.
476 for(CKKSIncomingQueueEntry* iqe in queueEntries) {
477 lastMaxUUID = ([lastMaxUUID compare:iqe.uuid] == NSOrderedDescending) ? lastMaxUUID : iqe.uuid;
483 ckksnotice("ckksincoming", ckks, "Early-exiting from IncomingQueueOperation");
488 ckksnotice("ckksincoming", ckks, "Processed %lu items in incoming queue (%lu errors)", (unsigned long)self.successfulItemsProcessed, (unsigned long)self.errorItemsProcessed);
490 [ckks dispatchSync: ^bool{
491 NSError* error = nil;
493 NSArray<CKKSCurrentItemPointer*>* newCIPs = [CKKSCurrentItemPointer remoteItemPointers:ckks.zoneID error:&error];
494 if(error || !newCIPs) {
495 ckkserror("ckksincoming", ckks, "Could not load remote item pointers: %@", error);
497 if (![self processNewCurrentItemPointers:newCIPs withManifest:ckks.latestManifest egoManifest:ckks.egoManifest]) {
500 ckksnotice("ckksincoming", ckks, "Processed %lu items in CIP queue", (unsigned long)newCIPs.count);
503 if(self.newOutgoingEntries) {
504 // No operation group
505 [ckks processOutgoingQueue:nil];
508 if(self.pendingClassAEntries) {
509 [self.ckks processIncomingQueueAfterNextUnlock];
516 - (void)_onqueueHandleIQEChange: (CKKSIncomingQueueEntry*) iqe attributes:(NSDictionary*)attributes class:(const SecDbClass *)classP {
517 CKKSKeychainView* ckks = self.ckks;
519 ckkserror("ckksincoming", ckks, "no CKKS object");
523 dispatch_assert_queue(ckks.queue);
526 __block CFErrorRef cferror = NULL;
527 __block NSError* error = NULL;
529 SecDbItemRef item = SecDbItemCreateWithAttributes(NULL, classP, (__bridge CFDictionaryRef) attributes, KEYBAG_DEVICE, &cferror);
531 __block NSDate* moddate = (__bridge NSDate*) CFDictionaryGetValue(item->attributes, kSecAttrModificationDate);
533 ok = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt){
534 bool replaceok = SecDbItemInsertOrReplace(item, dbt, &cferror, ^(SecDbItemRef olditem, SecDbItemRef *replace) {
535 // If the UUIDs do not match, then select the item with the 'lower' UUID, and tell CKKS to
536 // delete the item with the 'higher' UUID.
537 // Otherwise, the cloud wins.
539 SecADAddValueForScalarKey((__bridge CFStringRef) SecCKKSAggdPrimaryKeyConflict,1);
541 // Note that SecDbItemInsertOrReplace CFReleases any replace pointer it's given, so, be careful
543 if(!CFDictionaryContainsKey(olditem->attributes, kSecAttrUUID)) {
544 // No UUID -> no good.
545 ckksnotice("ckksincoming", ckks, "Replacing item (it doesn't have a UUID) for %@", iqe.uuid);
547 *replace = CFRetainSafe(item);
552 CFStringRef itemUUID = CFDictionaryGetValue(item->attributes, kSecAttrUUID);
553 CFStringRef olditemUUID = CFDictionaryGetValue(olditem->attributes, kSecAttrUUID);
555 CFComparisonResult compare = CFStringCompare(itemUUID, olditemUUID, 0);
556 CKKSOutgoingQueueEntry* oqe = nil;
558 case kCFCompareLessThan:
559 // item wins; delete olditem
560 ckksnotice("ckksincoming", ckks, "Primary key conflict; replacing %@ with CK item %@", olditem, item);
562 *replace = CFRetainSafe(item);
563 moddate = (__bridge NSDate*) CFDictionaryGetValue(item->attributes, kSecAttrModificationDate);
566 oqe = [CKKSOutgoingQueueEntry withItem:olditem action:SecCKKSActionDelete ckks:ckks error:&error];
567 [oqe saveToDatabase: &error];
568 self.newOutgoingEntries = true;
570 case kCFCompareGreaterThan:
571 // olditem wins; don't change olditem; delete item
572 ckksnotice("ckksincoming", ckks, "Primary key conflict; dropping CK item %@", item);
574 oqe = [CKKSOutgoingQueueEntry withItem:item action:SecCKKSActionDelete ckks:ckks error:&error];
575 [oqe saveToDatabase: &error];
576 self.newOutgoingEntries = true;
580 case kCFCompareEqualTo:
581 // remote item wins; this is the normal update case
582 ckksnotice("ckksincoming", ckks, "Primary key conflict; replacing %@ with CK item %@", olditem, item);
584 *replace = CFRetainSafe(item);
585 moddate = (__bridge NSDate*) CFDictionaryGetValue(item->attributes, kSecAttrModificationDate);
591 // SecDbItemInsertOrReplace returns an error even when it succeeds.
592 if(!replaceok && SecErrorIsSqliteDuplicateItemError(cferror)) {
593 CFReleaseNull(cferror);
602 ckkserror("ckksincoming", ckks, "couldn't process item from IncomingQueue: %@", cferror);
603 SecTranslateError(&error, cferror);
606 iqe.state = SecCKKSStateError;
607 [iqe saveToDatabase:&error];
609 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
616 ckkserror("ckksincoming", ckks, "Couldn't handle IQE, but why?: %@", error);
622 ckksinfo("ckksincoming", ckks, "Correctly processed an IQE; deleting");
623 [iqe deleteFromDatabase: &error];
626 ckkserror("ckksincoming", ckks, "couldn't delete CKKSIncomingQueueEntry: %@", error);
628 self.errorItemsProcessed += 1;
630 self.successfulItemsProcessed += 1;
634 // Log the number of seconds it took to propagate this change
635 uint64_t secondsDelay = (uint64_t) ([[NSDate date] timeIntervalSinceDate:moddate]);
636 SecADClientPushValueForDistributionKey((__bridge CFStringRef) SecCKKSAggdPropagationDelay, secondsDelay);
640 ckksnotice("ckksincoming", ckks, "IQE not correctly processed, but why? %@ %@", error, cferror);
643 iqe.state = SecCKKSStateError;
644 [iqe saveToDatabase:&error];
646 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
650 self.errorItemsProcessed += 1;
654 - (void)_onqueueHandleIQEDelete: (CKKSIncomingQueueEntry*) iqe class:(const SecDbClass *)classP {
655 CKKSKeychainView* ckks = self.ckks;
657 ckkserror("ckksincoming", ckks, "no CKKS object");
661 dispatch_assert_queue(ckks.queue);
664 __block CFErrorRef cferror = NULL;
665 NSError* error = NULL;
666 NSDictionary* queryAttributes = @{(__bridge NSString*) kSecClass: (__bridge NSString*) classP->name,
667 (__bridge NSString*) kSecAttrUUID: iqe.uuid,
668 (__bridge NSString*) kSecAttrSyncViewHint: ckks.zoneID.zoneName,
669 (__bridge NSString*) kSecAttrSynchronizable: @(YES)};
670 ckksnotice("ckksincoming", ckks, "trying to delete with query: %@", queryAttributes);
671 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) queryAttributes, NULL, kSecMatchUnlimited, &cferror);
675 ckkserror("ckksincoming", ckks, "couldn't create query: %@", cferror);
676 SecTranslateError(&error, cferror);
681 ok = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt) {
682 return s3dl_query_delete(dbt, q, NULL, &cferror);
686 if(CFErrorGetCode(cferror) == errSecItemNotFound) {
687 ckkserror("ckksincoming", ckks, "couldn't delete item (as it's already gone); this is okay: %@", cferror);
689 CFReleaseNull(cferror);
691 ckkserror("ckksincoming", ckks, "couldn't delete item: %@", cferror);
692 SecTranslateError(&error, cferror);
694 query_destroy(q, NULL);
700 ok = query_notify_and_destroy(q, ok, &cferror);
703 ckkserror("ckksincoming", ckks, "couldn't delete query: %@", cferror);
704 SecTranslateError(&error, cferror);
710 ckksnotice("ckksincoming", ckks, "Correctly processed an IQE; deleting");
711 [iqe deleteFromDatabase: &error];
714 ckkserror("ckksincoming", ckks, "couldn't delete CKKSIncomingQueueEntry: %@", error);
716 self.errorItemsProcessed += 1;
718 self.successfulItemsProcessed += 1;
721 ckkserror("ckksincoming", ckks, "IQE not correctly processed, but why? %@ %@", error, cferror);
723 self.errorItemsProcessed += 1;