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"
34 #import "keychain/ot/ObjCImprovements.h"
36 #include "keychain/securityd/SecItemServer.h"
37 #include "keychain/securityd/SecItemDb.h"
38 #include <Security/SecItemPriv.h>
40 #include <utilities/SecADWrapper.h>
41 #import <utilities/SecCoreAnalytics.h>
45 @interface CKKSIncomingQueueOperation ()
46 @property bool newOutgoingEntries;
47 @property bool pendingClassAEntries;
48 @property bool missingKey;
51 @implementation CKKSIncomingQueueOperation
53 - (instancetype)init {
56 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks errorOnClassAFailure:(bool)errorOnClassAFailure {
57 if(self = [super init]) {
60 // Can't process unless we have a reasonable key hierarchy.
61 if(ckks.keyStateReadyDependency) {
62 [self addDependency: ckks.keyStateReadyDependency];
65 [self addNullableDependency: ckks.holdIncomingQueueOperation];
67 _errorOnClassAFailure = errorOnClassAFailure;
68 _pendingClassAEntries = false;
70 [self linearDependencies:ckks.incomingQueueOperations];
72 if ([CKKSManifest shouldSyncManifests]) {
74 CKKSResultOperation* updateManifestOperation = [CKKSResultOperation operationWithBlock:^{
76 CKKSKeychainView* strongCKKS = self.ckks;
77 __block NSError* error = nil;
78 if (!strongCKKS || !self) {
79 ckkserror("ckksincoming", strongCKKS, "update manifest operation fired for released object");
83 [strongCKKS dispatchSyncWithAccountKeys:^bool{
84 strongCKKS.latestManifest = [CKKSManifest latestTrustedManifestForZone:strongCKKS.zoneName error:&error];
87 ckkserror("ckksincoming", strongCKKS, "failed to get latest manifest: %@", error);
95 updateManifestOperation.name = @"update-manifest-operation";
97 [ckks scheduleOperation:updateManifestOperation];
98 [self addSuccessDependency:updateManifestOperation];
104 - (bool)processNewCurrentItemPointers:(NSArray<CKKSCurrentItemPointer*>*)queueEntries withManifest:(CKKSManifest*)manifest egoManifest:(CKKSEgoManifest*)egoManifest
106 CKKSKeychainView* ckks = self.ckks;
108 NSError* error = nil;
109 for(CKKSCurrentItemPointer* p in queueEntries) {
111 if ([CKKSManifest shouldSyncManifests]) {
112 if (![manifest validateCurrentItem:p withError:&error]) {
113 ckkserror("ckksincoming", ckks, "Unable to validate current item pointer (%@) against manifest (%@)", p, manifest);
114 if ([CKKSManifest shouldEnforceManifests]) {
120 p.state = SecCKKSProcessedStateLocal;
122 [p saveToDatabase:&error];
123 ckksnotice("ckkspointer", ckks, "Saving new current item pointer: %@", p);
125 ckkserror("ckksincoming", ckks, "Error saving new current item pointer: %@ %@", error, p);
128 // Schedule a view change notification
129 [ckks.notifyViewChangedScheduler trigger];
133 if(queueEntries.count > 0) {
134 // Schedule a view change notification
135 [ckks.notifyViewChangedScheduler trigger];
138 return (error == nil);
141 - (bool)processQueueEntries:(NSArray<CKKSIncomingQueueEntry*>*)queueEntries withManifest:(CKKSManifest*)manifest egoManifest:(CKKSEgoManifest*)egoManifest
143 CKKSKeychainView* ckks = self.ckks;
145 NSMutableArray* newOrChangedRecords = [[NSMutableArray alloc] init];
146 NSMutableArray* deletedRecordIDs = [[NSMutableArray alloc] init];
148 for(id entry in queueEntries) {
151 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
155 NSError* error = nil;
157 CKKSIncomingQueueEntry* iqe = (CKKSIncomingQueueEntry*) entry;
158 ckksnotice("ckksincoming", ckks, "ready to process an incoming queue entry: %@ %@ %@", iqe, iqe.uuid, iqe.action);
160 // Note that we currently unencrypt the item before deleting it, instead of just deleting it
161 // This finds the class, which is necessary for the deletion process. We could just try to delete
162 // across all classes, though...
163 NSDictionary* attributes = [CKKSIncomingQueueOperation decryptCKKSItemToAttributes:iqe.item error:&error];
165 if(!attributes || error) {
166 if([ckks.lockStateTracker isLockedError:error]) {
167 NSError* localerror = nil;
168 ckkserror("ckksincoming", ckks, "Keychain is locked; can't decrypt IQE %@", iqe);
169 CKKSKey* key = [CKKSKey tryFromDatabase:iqe.item.parentKeyUUID zoneID:ckks.zoneID error:&localerror];
170 if(localerror || ([key.keyclass isEqualToString:SecCKKSKeyClassA] && self.errorOnClassAFailure)) {
174 // If this isn't an error, make sure it gets processed later.
175 if([key.keyclass isEqualToString:SecCKKSKeyClassA] && !self.errorOnClassAFailure) {
176 self.pendingClassAEntries = true;
179 } else if ([error.domain isEqualToString:@"securityd"] && error.code == errSecItemNotFound) {
180 ckkserror("ckksincoming", ckks, "Coudn't find key in keychain; will attempt to poke key hierarchy: %@", error)
181 self.missingKey = true;
184 ckkserror("ckksincoming", ckks, "Couldn't decrypt IQE %@ for some reason: %@", iqe, error);
187 self.errorItemsProcessed += 1;
191 NSString* classStr = [attributes objectForKey: (__bridge NSString*) kSecClass];
192 if(![classStr isKindOfClass: [NSString class]]) {
193 self.error = [NSError errorWithDomain:@"securityd"
194 code:errSecInternalError
195 userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Item did not have a reasonable class: %@", classStr]}];
196 ckkserror("ckksincoming", ckks, "Synced item seems wrong: %@", self.error);
197 self.errorItemsProcessed += 1;
201 const SecDbClass * classP = !classStr ? NULL : kc_class_with_name((__bridge CFStringRef) classStr);
204 ckkserror("ckksincoming", ckks, "unknown class in object: %@ %@", classStr, iqe);
205 iqe.state = SecCKKSStateError;
206 [iqe saveToDatabase:&error];
208 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
211 self.errorItemsProcessed += 1;
215 if([iqe.action isEqualToString: SecCKKSActionAdd] || [iqe.action isEqualToString: SecCKKSActionModify]) {
216 BOOL requireManifestValidation = [CKKSManifest shouldEnforceManifests];
217 BOOL manifestValidatesItem = [manifest validateItem:iqe.item withError:&error];
219 if (!requireManifestValidation || manifestValidatesItem) {
220 [self _onqueueHandleIQEChange: iqe attributes:attributes class:classP];
221 [newOrChangedRecords addObject:[iqe.item CKRecordWithZoneID:ckks.zoneID]];
224 ckkserror("ckksincoming", ckks, "could not validate incoming item against manifest with error: %@", error);
225 if (![self _onqueueUpdateIQE:iqe withState:SecCKKSStateUnauthenticated error:&error]) {
226 ckkserror("ckksincoming", ckks, "failed to save incoming item back to database in unauthenticated state with error: %@", error);
229 self.errorItemsProcessed += 1;
232 } else if ([iqe.action isEqualToString: SecCKKSActionDelete]) {
233 BOOL requireManifestValidation = [CKKSManifest shouldEnforceManifests];
234 BOOL manifestValidatesDelete = ![manifest itemUUIDExistsInManifest:iqe.uuid];
236 if (!requireManifestValidation || manifestValidatesDelete) {
237 // if the item does not exist in the latest manifest, we're good to delete it
238 [self _onqueueHandleIQEDelete: iqe class:classP];
239 [deletedRecordIDs addObject:[[CKRecordID alloc] initWithRecordName:iqe.uuid zoneID:ckks.zoneID]];
242 // if the item DOES exist in the manifest, we can't trust the deletion
243 ckkserror("ckksincoming", ckks, "could not validate incoming item deletion against manifest");
244 if (![self _onqueueUpdateIQE:iqe withState:SecCKKSStateUnauthenticated error:&error]) {
245 ckkserror("ckksincoming", ckks, "failed to save incoming item deletion back to database in unauthenticated state with error: %@", error);
247 self.errorItemsProcessed += 1;
255 if(newOrChangedRecords.count > 0 || deletedRecordIDs > 0) {
256 // Schedule a view change notification
257 [ckks.notifyViewChangedScheduler trigger];
260 if(self.missingKey) {
261 [ckks.pokeKeyStateMachineScheduler trigger];
264 if ([CKKSManifest shouldSyncManifests]) {
265 [egoManifest updateWithNewOrChangedRecords:newOrChangedRecords deletedRecordIDs:deletedRecordIDs];
270 + (NSDictionary* _Nullable)decryptCKKSItemToAttributes:(CKKSItem*)item error:(NSError**)error
272 NSMutableDictionary* attributes = [[CKKSItemEncrypter decryptItemToDictionary:item error:error] mutableCopy];
277 // Add the UUID (which isn't stored encrypted)
278 attributes[(__bridge NSString*)kSecAttrUUID] = item.uuid;
280 // Add the PCS plaintext fields, if they exist
281 if(item.plaintextPCSServiceIdentifier) {
282 attributes[(__bridge NSString*)kSecAttrPCSPlaintextServiceIdentifier] = item.plaintextPCSServiceIdentifier;
284 if(item.plaintextPCSPublicKey) {
285 attributes[(__bridge NSString*)kSecAttrPCSPlaintextPublicKey] = item.plaintextPCSPublicKey;
287 if(item.plaintextPCSPublicIdentity) {
288 attributes[(__bridge NSString*)kSecAttrPCSPlaintextPublicIdentity] = item.plaintextPCSPublicIdentity;
291 // This item is also synchronizable (by definition)
292 [attributes setValue:@(YES) forKey:(__bridge NSString*)kSecAttrSynchronizable];
297 - (bool)_onqueueUpdateIQE:(CKKSIncomingQueueEntry*)iqe withState:(NSString*)newState error:(NSError**)error
299 if (![iqe.state isEqualToString:newState]) {
300 NSMutableDictionary* oldWhereClause = iqe.whereClauseToFindSelf.mutableCopy;
301 oldWhereClause[@"state"] = iqe.state;
302 iqe.state = newState;
303 if ([iqe saveToDatabase:error]) {
304 if (![CKKSSQLDatabaseObject deleteFromTable:[iqe.class sqlTable] where:oldWhereClause connection:NULL error:error]) {
317 // Synchronous, on some thread. Get back on the CKKS queue for thread-safety.
318 CKKSKeychainView* ckks = self.ckks;
320 ckkserror("ckksincoming", ckks, "no CKKS object");
325 self.completionBlock = ^(void) {
328 ckkserror("ckksincoming", ckks, "received callback for released object");
332 CKKSAnalytics* logger = [CKKSAnalytics logger];
335 [logger logSuccessForEvent:CKKSEventProcessIncomingQueueClassC inView:ckks];
336 if (!self.pendingClassAEntries) {
337 [logger logSuccessForEvent:CKKSEventProcessIncomingQueueClassA inView:ckks];
340 [logger logRecoverableError:self.error
341 forEvent:self.errorOnClassAFailure ? CKKSEventProcessIncomingQueueClassA : CKKSEventProcessIncomingQueueClassC
343 withAttributes:NULL];
347 __block bool errored = false;
348 [ckks dispatchSync: ^bool{
350 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
353 ckks.lastIncomingQueueOperation = self;
355 ckksnotice("ckksincoming", ckks, "Processing incoming queue");
357 if ([CKKSManifest shouldSyncManifests]) {
358 if (!ckks.latestManifest) {
359 // Until we can make manifests in our unit tests, we can't abort here
360 ckkserror("ckksincoming", ckks, "no manifest in ckks");
362 if (!ckks.egoManifest) {
363 ckkserror("ckksincoming", ckks, "no ego manifest in ckks");
367 bool ok = true; // Should commit transaction?
368 __block NSError* error = nil;
370 if ([CKKSManifest shouldSyncManifests]) {
371 NSInteger unauthenticatedItemCount = [CKKSIncomingQueueEntry countByState:SecCKKSStateUnauthenticated zone:ckks.zoneID error:&error];
372 if (error || unauthenticatedItemCount < 0) {
373 ckkserror("ckksincoming", ckks, "Error fetching incoming queue state counts: %@", error);
378 // take any existing unauthenticated entries and put them back in the new state
379 NSArray<CKKSIncomingQueueEntry*>* unauthenticatedEntries = nil;
380 NSString* lastMaxUUID = nil;
381 NSInteger numEntriesProcessed = 0;
382 while (numEntriesProcessed < unauthenticatedItemCount && (unauthenticatedEntries == nil || unauthenticatedEntries.count == SecCKKSIncomingQueueItemsAtOnce)) {
384 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
388 unauthenticatedEntries = [CKKSIncomingQueueEntry fetch:SecCKKSIncomingQueueItemsAtOnce
389 startingAtUUID:lastMaxUUID
390 state:SecCKKSStateUnauthenticated
394 ckkserror("ckksincoming", ckks, "Error fetching unauthenticated queue records: %@", error);
399 if (unauthenticatedEntries.count == 0) {
400 ckksinfo("ckksincoming", ckks, "No unauthenticated entries in incoming queue to process");
404 for (CKKSIncomingQueueEntry* unauthenticatedEntry in unauthenticatedEntries) {
405 if (![self _onqueueUpdateIQE:unauthenticatedEntry withState:SecCKKSStateNew error:&error]) {
406 ckkserror("ckksincoming", ckks, "Error saving unauthenticated entry back to new state: %@", error);
411 lastMaxUUID = ([lastMaxUUID compare:unauthenticatedEntry.uuid] == NSOrderedDescending) ? lastMaxUUID : unauthenticatedEntry.uuid;
420 ckksnotice("ckksincoming", ckks, "Early-exiting from IncomingQueueOperation");
424 // Now for the tricky bit: take and drop the account queue for each batch of queue entries
425 // This is for peak memory concerns, but also to allow keychain API clients to make changes while we're processing many items
426 // Note that IncomingQueueOperations are no longer transactional: they can partially succeed. This might make them harder to reason about.
427 __block NSUInteger lastCount = SecCKKSIncomingQueueItemsAtOnce;
428 __block NSString* lastMaxUUID = nil;
430 while(lastCount == SecCKKSIncomingQueueItemsAtOnce) {
431 [ckks dispatchSync: ^bool{
432 NSArray<CKKSIncomingQueueEntry*> * queueEntries = nil;
434 ckksnotice("ckksincoming", ckks, "CKKSIncomingQueueOperation cancelled, quitting");
439 NSError* error = nil;
441 queueEntries = [CKKSIncomingQueueEntry fetch: SecCKKSIncomingQueueItemsAtOnce
442 startingAtUUID:lastMaxUUID
443 state:SecCKKSStateNew
448 ckkserror("ckksincoming", ckks, "Error fetching incoming queue records: %@", error);
454 lastCount = queueEntries.count;
456 if([queueEntries count] == 0) {
457 // Nothing to do! exit.
458 ckksnotice("ckksincoming", ckks, "Nothing in incoming queue to process");
462 [CKKSPowerCollection CKKSPowerEvent:kCKKSPowerEventOutgoingQueue zone:ckks.zoneName count:[queueEntries count]];
464 if (![self processQueueEntries:queueEntries withManifest:ckks.latestManifest egoManifest:ckks.egoManifest]) {
465 ckksnotice("ckksincoming", ckks, "processQueueEntries didn't complete successfully");
470 // Find the highest UUID for the next fetch.
471 for(CKKSIncomingQueueEntry* iqe in queueEntries) {
472 lastMaxUUID = ([lastMaxUUID compare:iqe.uuid] == NSOrderedDescending) ? lastMaxUUID : iqe.uuid;
478 ckksnotice("ckksincoming", ckks, "Early-exiting from IncomingQueueOperation");
483 ckksnotice("ckksincoming", ckks, "Processed %lu items in incoming queue (%lu errors)", (unsigned long)self.successfulItemsProcessed, (unsigned long)self.errorItemsProcessed);
485 [ckks dispatchSync: ^bool{
486 NSError* error = nil;
488 NSArray<CKKSCurrentItemPointer*>* newCIPs = [CKKSCurrentItemPointer remoteItemPointers:ckks.zoneID error:&error];
489 if(error || !newCIPs) {
490 ckkserror("ckksincoming", ckks, "Could not load remote item pointers: %@", error);
492 if (![self processNewCurrentItemPointers:newCIPs withManifest:ckks.latestManifest egoManifest:ckks.egoManifest]) {
495 ckksnotice("ckksincoming", ckks, "Processed %lu items in CIP queue", (unsigned long)newCIPs.count);
498 if(self.newOutgoingEntries) {
499 // No operation group
500 [ckks processOutgoingQueue:nil];
503 if(self.pendingClassAEntries) {
504 [self.ckks processIncomingQueueAfterNextUnlock];
511 - (void)_onqueueHandleIQEChange: (CKKSIncomingQueueEntry*) iqe attributes:(NSDictionary*)attributes class:(const SecDbClass *)classP {
512 CKKSKeychainView* ckks = self.ckks;
514 ckkserror("ckksincoming", ckks, "no CKKS object");
518 dispatch_assert_queue(ckks.queue);
521 __block CFErrorRef cferror = NULL;
522 __block NSError* error = NULL;
524 SecDbItemRef item = SecDbItemCreateWithAttributes(NULL, classP, (__bridge CFDictionaryRef) attributes, KEYBAG_DEVICE, &cferror);
526 __block NSDate* moddate = (__bridge NSDate*) CFDictionaryGetValue(item->attributes, kSecAttrModificationDate);
528 ok = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt){
529 bool replaceok = SecDbItemInsertOrReplace(item, dbt, &cferror, ^(SecDbItemRef olditem, SecDbItemRef *replace) {
530 // If the UUIDs do not match, then select the item with the 'lower' UUID, and tell CKKS to
531 // delete the item with the 'higher' UUID.
532 // Otherwise, the cloud wins.
534 SecADAddValueForScalarKey((__bridge CFStringRef) SecCKKSAggdPrimaryKeyConflict,1);
536 // Note that SecDbItemInsertOrReplace CFReleases any replace pointer it's given, so, be careful
538 if(!CFDictionaryContainsKey(olditem->attributes, kSecAttrUUID)) {
539 // No UUID -> no good.
540 ckksnotice("ckksincoming", ckks, "Replacing item (it doesn't have a UUID) for %@", iqe.uuid);
542 *replace = CFRetainSafe(item);
547 CFStringRef itemUUID = CFDictionaryGetValue(item->attributes, kSecAttrUUID);
548 CFStringRef olditemUUID = CFDictionaryGetValue(olditem->attributes, kSecAttrUUID);
550 CFComparisonResult compare = CFStringCompare(itemUUID, olditemUUID, 0);
551 CKKSOutgoingQueueEntry* oqe = nil;
552 if (compare == kCFCompareGreaterThan) {
553 // olditem wins; don't change olditem; delete item
554 ckksnotice("ckksincoming", ckks, "Primary key conflict; dropping CK item %@", item);
555 oqe = [CKKSOutgoingQueueEntry withItem:item action:SecCKKSActionDelete ckks:ckks error:&error];
556 [oqe saveToDatabase: &error];
557 self.newOutgoingEntries = true;
561 ckksnotice("ckksincoming", ckks, "Primary key conflict; replacing %@ with CK item %@", olditem, item);
563 *replace = CFRetainSafe(item);
564 moddate = (__bridge NSDate*) CFDictionaryGetValue(item->attributes, kSecAttrModificationDate);
566 // delete olditem if UUID differs (same UUID is the normal update case)
567 if (compare != kCFCompareEqualTo) {
568 oqe = [CKKSOutgoingQueueEntry withItem:olditem action:SecCKKSActionDelete ckks:ckks error:&error];
569 [oqe saveToDatabase: &error];
570 self.newOutgoingEntries = true;
575 // SecDbItemInsertOrReplace returns an error even when it succeeds.
576 if(!replaceok && SecErrorIsSqliteDuplicateItemError(cferror)) {
577 CFReleaseNull(cferror);
586 ckkserror("ckksincoming", ckks, "couldn't process item from IncomingQueue: %@", cferror);
587 SecTranslateError(&error, cferror);
590 iqe.state = SecCKKSStateError;
591 [iqe saveToDatabase:&error];
593 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
600 ckkserror("ckksincoming", ckks, "Couldn't handle IQE, but why?: %@", error);
606 ckksinfo("ckksincoming", ckks, "Correctly processed an IQE; deleting");
607 [iqe deleteFromDatabase: &error];
610 ckkserror("ckksincoming", ckks, "couldn't delete CKKSIncomingQueueEntry: %@", error);
612 self.errorItemsProcessed += 1;
614 self.successfulItemsProcessed += 1;
618 // Log the number of ms it took to propagate this change
619 uint64_t delayInMS = [[NSDate date] timeIntervalSinceDate:moddate] * 1000;
620 [SecCoreAnalytics sendEvent:@"com.apple.ckks.item.propagation" event:@{
621 @"time" : @(delayInMS)
627 ckksnotice("ckksincoming", ckks, "IQE not correctly processed, but why? %@ %@", error, cferror);
630 iqe.state = SecCKKSStateError;
631 [iqe saveToDatabase:&error];
633 ckkserror("ckksincoming", ckks, "Couldn't save errored IQE to database: %@", error);
637 self.errorItemsProcessed += 1;
641 - (void)_onqueueHandleIQEDelete: (CKKSIncomingQueueEntry*) iqe class:(const SecDbClass *)classP {
642 CKKSKeychainView* ckks = self.ckks;
644 ckkserror("ckksincoming", ckks, "no CKKS object");
648 dispatch_assert_queue(ckks.queue);
651 __block CFErrorRef cferror = NULL;
652 NSError* error = NULL;
653 NSDictionary* queryAttributes = @{(__bridge NSString*) kSecClass: (__bridge NSString*) classP->name,
654 (__bridge NSString*) kSecAttrUUID: iqe.uuid,
655 (__bridge NSString*) kSecAttrSyncViewHint: ckks.zoneID.zoneName,
656 (__bridge NSString*) kSecAttrSynchronizable: @(YES)};
657 ckksnotice("ckksincoming", ckks, "trying to delete with query: %@", queryAttributes);
658 Query *q = query_create_with_limit( (__bridge CFDictionaryRef) queryAttributes, NULL, kSecMatchUnlimited, &cferror);
662 ckkserror("ckksincoming", ckks, "couldn't create query: %@", cferror);
663 SecTranslateError(&error, cferror);
668 ok = kc_with_dbt(true, &cferror, ^(SecDbConnectionRef dbt) {
669 return s3dl_query_delete(dbt, q, NULL, &cferror);
673 if(CFErrorGetCode(cferror) == errSecItemNotFound) {
674 ckkserror("ckksincoming", ckks, "couldn't delete item (as it's already gone); this is okay: %@", cferror);
676 CFReleaseNull(cferror);
678 ckkserror("ckksincoming", ckks, "couldn't delete item: %@", cferror);
679 SecTranslateError(&error, cferror);
681 query_destroy(q, NULL);
687 ok = query_notify_and_destroy(q, ok, &cferror);
690 ckkserror("ckksincoming", ckks, "couldn't delete query: %@", cferror);
691 SecTranslateError(&error, cferror);
697 ckksnotice("ckksincoming", ckks, "Correctly processed an IQE; deleting");
698 [iqe deleteFromDatabase: &error];
701 ckkserror("ckksincoming", ckks, "couldn't delete CKKSIncomingQueueEntry: %@", error);
703 self.errorItemsProcessed += 1;
705 self.successfulItemsProcessed += 1;
708 ckkserror("ckksincoming", ckks, "IQE not correctly processed, but why? %@ %@", error, cferror);
710 self.errorItemsProcessed += 1;