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 #include <AssertMacros.h>
26 #import <Foundation/Foundation.h>
28 #import "CKKSKeychainView.h"
30 #include <Security/SecItemPriv.h>
32 #include <utilities/SecDb.h>
33 #include <securityd/SecDbItem.h>
34 #include <securityd/SecItemSchema.h>
38 #import <CloudKit/CloudKit.h>
39 #import "CKKSOutgoingQueueEntry.h"
40 #import "CKKSItemEncrypter.h"
44 @implementation CKKSOutgoingQueueEntry
46 - (NSString*)description {
47 return [NSString stringWithFormat: @"<%@(%@): %@ %@ (%@)>",
48 NSStringFromClass([self class]),
49 self.item.zoneID.zoneName,
55 - (instancetype) initWithCKKSItem:(CKKSItem*) item
56 action: (NSString*) action
57 state: (NSString*) state
58 waitUntil: (NSDate*) waitUntil
59 accessGroup: (NSString*) accessgroup
61 if((self = [super init])) {
65 _accessgroup = accessgroup;
66 _waitUntil = waitUntil;
72 - (BOOL)isEqual: (id) object {
73 if(![object isKindOfClass:[CKKSOutgoingQueueEntry class]]) {
77 CKKSOutgoingQueueEntry* obj = (CKKSOutgoingQueueEntry*) object;
79 return ([self.item isEqual: obj.item] &&
80 [self.action isEqual: obj.action] &&
81 [self.state isEqual: obj.state] &&
82 ((self.waitUntil == nil && obj.waitUntil == nil) || (fabs([self.waitUntil timeIntervalSinceDate: obj.waitUntil]) < 1)) &&
83 [self.accessgroup isEqual: obj.accessgroup] &&
87 + (instancetype)withItem: (SecDbItemRef) item action: (NSString*) action ckks:(CKKSKeychainView*) ckks error: (NSError * __autoreleasing *) error {
88 CFErrorRef cferror = NULL;
91 NSString* accessgroup = nil;
93 NSInteger newGenerationCount = -1;
96 NSMutableDictionary* objd = nil;
98 key = [ckks keyForItem: item error:error];
103 objd = (__bridge_transfer NSMutableDictionary*) SecDbItemCopyPListWithMask(item, kSecDbSyncFlag, &cferror);
105 SecTranslateError(error, cferror);
109 // Object classes aren't in the item plist, set them specifically
110 [objd setObject: (__bridge NSString*) item->class->name forKey: (__bridge NSString*) kSecClass];
112 uuid = (__bridge_transfer NSString*) CFRetain(SecDbItemGetValue(item, &v10itemuuid, &cferror));
113 if(!uuid || cferror) {
114 SecTranslateError(error, cferror);
117 if([uuid isKindOfClass:[NSNull class]]) {
118 NSError* localerror = [NSError errorWithDomain:@"securityd"
119 code:CKKSNoUUIDOnItem
120 userInfo:@{NSLocalizedDescriptionKey: @"UUID not found in object"}];
122 secerror("ckksitem: couldn't fetch UUID: %@ %@", localerror, item);
129 accessgroup = (__bridge_transfer NSString*) CFRetain(SecDbItemGetValue(item, &v6agrp, &cferror));
130 if(!accessgroup || cferror) {
131 SecTranslateError(error, cferror);
134 if([accessgroup isKindOfClass:[NSNull class]]) {
135 // That's okay; this is only used for rate limiting.
136 secerror("ckksitem: couldn't fetch accessgroup: %@", item);
137 accessgroup = @"no-group";
141 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase:uuid zoneID:ckks.zoneID error:error];
143 // The action this change should be depends on any existing pending action, if any
144 // Particularly, we need to coalesce (existing action, new action) to:
145 // (add, modify) => add
146 // (add, delete) => no-op
147 // (delete, add) => modify
148 NSString* actualAction = action;
150 CKKSOutgoingQueueEntry* existingOQE = [CKKSOutgoingQueueEntry tryFromDatabase:uuid state:SecCKKSStateNew zoneID:ckks.zoneID error:error];
152 if([existingOQE.action isEqual: SecCKKSActionAdd]) {
153 if([action isEqual:SecCKKSActionModify]) {
154 actualAction = SecCKKSActionAdd;
155 } else if([action isEqual:SecCKKSActionDelete]) {
156 // we're deleting an add. If there's a ckme, keep as a delete
158 // Otherwise, remove from outgoingqueue and don't make a new OQE.
159 [existingOQE deleteFromDatabase:error];
165 if([existingOQE.action isEqual: SecCKKSActionDelete] && [action isEqual:SecCKKSActionAdd]) {
166 actualAction = SecCKKSActionModify;
171 newGenerationCount = ckme ? ckme.item.generationCount : (NSInteger) 0; // TODO: this is wrong
173 // Pull out any unencrypted fields
174 NSNumber* pcsServiceIdentifier = objd[(id)kSecAttrPCSPlaintextServiceIdentifier];
175 objd[(id)kSecAttrPCSPlaintextServiceIdentifier] = nil;
177 NSData* pcsPublicKey = objd[(id)kSecAttrPCSPlaintextPublicKey];
178 objd[(id)kSecAttrPCSPlaintextPublicKey] = nil;
180 NSData* pcsPublicIdentity = objd[(id)kSecAttrPCSPlaintextPublicIdentity];
181 objd[(id)kSecAttrPCSPlaintextPublicIdentity] = nil;
183 CKKSItem* baseitem = [[CKKSItem alloc] initWithUUID:uuid
184 parentKeyUUID:key.uuid
189 generationCount:newGenerationCount
190 encver:currentCKKSItemEncryptionVersion
191 plaintextPCSServiceIdentifier:pcsServiceIdentifier
192 plaintextPCSPublicKey:pcsPublicKey
193 plaintextPCSPublicIdentity:pcsPublicIdentity];
195 CKKSItem* encryptedItem = [CKKSItemEncrypter encryptCKKSItem:baseitem
197 updatingCKKSItem:ckme.item
205 return [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:encryptedItem
207 state:SecCKKSStateNew
209 accessGroup:accessgroup];
212 #pragma mark - Property access to underlying CKKSItem
215 return self.item.uuid;
218 -(void)setUuid:(NSString *)uuid {
219 self.item.uuid = uuid;
222 #pragma mark - Database Operations
224 + (instancetype) fromDatabase: (NSString*) uuid state: (NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
225 return [self fromDatabaseWhere: @{@"UUID": CKKSNilToNSNull(uuid), @"state": CKKSNilToNSNull(state), @"ckzone":CKKSNilToNSNull(zoneID.zoneName)} error: error];
228 + (instancetype) tryFromDatabase: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
229 return [self tryFromDatabaseWhere: @{@"UUID": CKKSNilToNSNull(uuid), @"ckzone":CKKSNilToNSNull(zoneID.zoneName)} error: error];
232 + (instancetype) tryFromDatabase: (NSString*) uuid state: (NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
233 return [self tryFromDatabaseWhere: @{@"UUID": CKKSNilToNSNull(uuid), @"state":CKKSNilToNSNull(state), @"ckzone":CKKSNilToNSNull(zoneID.zoneName)} error: error];
236 + (NSArray<CKKSOutgoingQueueEntry*>*) fetch:(ssize_t) n state: (NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
237 return [self fetch:n where: @{@"state":CKKSNilToNSNull(state), @"ckzone":CKKSNilToNSNull(zoneID.zoneName)} error:error];
240 + (NSArray<CKKSOutgoingQueueEntry*>*) allInState: (NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
241 return [self allWhere: @{@"state":CKKSNilToNSNull(state), @"ckzone":CKKSNilToNSNull(zoneID.zoneName)} error:error];
245 #pragma mark - CKKSSQLDatabaseObject methods
247 + (NSString*)sqlTable {
248 return @"outgoingqueue";
251 + (NSArray<NSString*>*)sqlColumns {
252 return [[CKKSItem sqlColumns] arrayByAddingObjectsFromArray: @[@"action", @"state", @"waituntil", @"accessgroup"]];
255 - (NSDictionary<NSString*,NSString*>*)whereClauseToFindSelf {
256 return @{@"UUID": self.uuid, @"state": self.state, @"ckzone":self.item.zoneID.zoneName};
259 - (NSDictionary<NSString*,NSString*>*)sqlValues {
260 NSISO8601DateFormatter* dateFormat = [[NSISO8601DateFormatter alloc] init];
262 NSMutableDictionary* values = [[self.item sqlValues] mutableCopy];
263 values[@"action"] = self.action;
264 values[@"state"] = self.state;
265 values[@"waituntil"] = CKKSNilToNSNull(self.waitUntil ? [dateFormat stringFromDate: self.waitUntil] : nil);
266 values[@"accessgroup"] = self.accessgroup;
272 + (instancetype)fromDatabaseRow: (NSDictionary*) row {
273 NSISO8601DateFormatter* dateFormat = [[NSISO8601DateFormatter alloc] init];
275 return [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:[CKKSItem fromDatabaseRow: row]
276 action:row[@"action"]
278 waitUntil:[row[@"waituntil"] isEqual: [NSNull null]] ? nil : [dateFormat dateFromString: row[@"waituntil"]]
279 accessGroup:row[@"accessgroup"]];
282 + (NSDictionary<NSString*,NSNumber*>*)countsByState:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
283 NSMutableDictionary* results = [[NSMutableDictionary alloc] init];
285 [CKKSSQLDatabaseObject queryDatabaseTable: [[self class] sqlTable]
286 where: @{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)}
287 columns: @[@"state", @"count(rowid)"]
291 processRow: ^(NSDictionary* row) {
292 results[row[@"state"]] = [NSNumber numberWithInteger: [row[@"count(rowid)"] integerValue]];