]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSSQLDatabaseObject.m
Security-58286.1.32.tar.gz
[apple/security.git] / keychain / ckks / CKKSSQLDatabaseObject.m
1 /*
2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #import <Foundation/Foundation.h>
25 #import "CKKSSQLDatabaseObject.h"
26 #include <securityd/SecItemServer.h>
27
28 #import "CKKSKeychainView.h"
29
30 @implementation CKKSSQLDatabaseObject
31
32 + (bool) saveToDatabaseTable: (NSString*) table row: (NSDictionary*) row connection: (SecDbConnectionRef) dbconn error: (NSError * __autoreleasing *) error {
33 __block CFErrorRef cferror = NULL;
34
35 bool (^doWithConnection)(SecDbConnectionRef) = ^bool (SecDbConnectionRef dbconn) {
36 NSString * columns = [row.allKeys componentsJoinedByString:@", "];
37 NSMutableString * values = [[NSMutableString alloc] init];
38 for(NSUInteger i = 0; i < [row.allKeys count]; i++) {
39 if(i != 0) {
40 [values appendString: @",?"];
41 } else {
42 [values appendString: @"?"];
43 }
44 }
45
46 NSString *sql = [[NSString alloc] initWithFormat: @"INSERT OR REPLACE into %@ (%@) VALUES (%@);", table, columns, values];
47
48 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
49 [row.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
50 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) row[key], &cferror);
51 }];
52
53 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
54 // don't do anything, I guess?
55 });
56 });
57
58 return true;
59 };
60
61 if(dbconn) {
62 doWithConnection(dbconn);
63 } else {
64 kc_with_dbt(true, &cferror, doWithConnection);
65 }
66
67 bool ret = cferror == NULL;
68
69 SecTranslateError(error, cferror);
70
71 return ret;
72 }
73
74 + (NSString*) makeWhereClause: (NSDictionary*) whereDict {
75 if(!whereDict) {
76 return @"";
77 }
78 NSMutableString * whereClause = [[NSMutableString alloc] init];
79 __block bool conjunction = false;
80 [whereDict enumerateKeysAndObjectsUsingBlock: ^(NSString* key, NSNumber* value, BOOL* stop) {
81 if(!conjunction) {
82 [whereClause appendFormat: @" WHERE "];
83 } else {
84 [whereClause appendFormat: @" AND "];
85 }
86
87 if([value class] == [CKKSSQLWhereObject class]) {
88 // Use this string verbatim
89 CKKSSQLWhereObject* whereob = (CKKSSQLWhereObject*) value;
90 [whereClause appendFormat: @"%@%@%@", key, whereob.sqlOp, whereob.contents];
91 } else {
92 [whereClause appendFormat: @"%@=(?)", key];
93 }
94
95 conjunction = true;
96 }];
97 return whereClause;
98 }
99
100 + (NSString*) groupByClause: (NSArray*) columns {
101 if(!columns) {
102 return @"";
103 }
104 NSMutableString * groupByClause = [[NSMutableString alloc] init];
105 __block bool conjunction = false;
106 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
107 if(!conjunction) {
108 [groupByClause appendFormat: @" GROUP BY "];
109 } else {
110 [groupByClause appendFormat: @", "];
111 }
112
113 [groupByClause appendFormat: @"%@", column];
114
115 conjunction = true;
116 }];
117 return groupByClause;
118 }
119
120 + (NSString*)orderByClause: (NSArray*) columns {
121 if(!columns || columns.count == 0u) {
122 return @"";
123 }
124 NSMutableString * orderByClause = [[NSMutableString alloc] init];
125 __block bool conjunction = false;
126 [columns enumerateObjectsUsingBlock: ^(NSString* column, NSUInteger i, BOOL* stop) {
127 if(!conjunction) {
128 [orderByClause appendFormat: @" ORDER BY "];
129 } else {
130 [orderByClause appendFormat: @", "];
131 }
132
133 [orderByClause appendFormat: @"%@", column];
134
135 conjunction = true;
136 }];
137 return orderByClause;
138 }
139
140 + (bool) deleteFromTable: (NSString*) table where: (NSDictionary*) whereDict connection:(SecDbConnectionRef) dbconn error: (NSError * __autoreleasing *) error {
141 __block CFErrorRef cferror = NULL;
142
143 bool (^doWithConnection)(SecDbConnectionRef) = ^bool (SecDbConnectionRef dbconn) {
144 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
145
146 NSString * sql = [[NSString alloc] initWithFormat: @"DELETE FROM %@%@;", table, whereClause];
147 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
148
149 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
150 if([whereDict[key] class] != [CKKSSQLWhereObject class]) {
151 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) whereDict[key], &cferror);
152 }
153 }];
154
155 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
156 });
157 });
158 return true;
159 };
160
161 if(dbconn) {
162 doWithConnection(dbconn);
163 } else {
164 kc_with_dbt(true, &cferror, doWithConnection);
165 }
166
167 // Deletes finish in a single step, so if we didn't get an error, the delete 'happened'
168 bool status = (cferror == nil);
169
170 if(error) {
171 *error = (NSError*) CFBridgingRelease(cferror);
172 } else {
173 CFReleaseNull(cferror);
174 }
175
176 return status;
177 }
178
179 + (bool) queryDatabaseTable:(NSString*) table
180 where:(NSDictionary*) whereDict
181 columns:(NSArray*) names
182 groupBy:(NSArray*) groupColumns
183 orderBy:(NSArray*) orderColumns
184 limit:(ssize_t)limit
185 processRow:(void (^)(NSDictionary*)) processRow
186 error:(NSError * __autoreleasing *) error {
187 __block CFErrorRef cferror = NULL;
188
189 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbconn) {
190 NSString * columns = [names componentsJoinedByString:@", "];
191 NSString * whereClause = [CKKSSQLDatabaseObject makeWhereClause: whereDict];
192 NSString * groupByClause = [CKKSSQLDatabaseObject groupByClause: groupColumns];
193 NSString * orderByClause = [CKKSSQLDatabaseObject orderByClause: orderColumns];
194 NSString * limitClause = (limit > 0 ? [NSString stringWithFormat:@" LIMIT %lu", limit] : @"");
195
196 NSString * sql = [[NSString alloc] initWithFormat: @"SELECT %@ FROM %@%@%@%@%@;", columns, table, whereClause, groupByClause, orderByClause, limitClause];
197 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &cferror, ^void (sqlite3_stmt *stmt) {
198 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL * _Nonnull stop) {
199 if([whereDict[key] class] != [CKKSSQLWhereObject class]) {
200 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) whereDict[key], &cferror);
201 }
202 }];
203
204 SecDbStep(dbconn, stmt, &cferror, ^(bool *stop) {
205 __block NSMutableDictionary* row = [[NSMutableDictionary alloc] init];
206
207 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
208 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
209 row[name] = col ? [NSString stringWithUTF8String:col] : [NSNull null];
210 }];
211
212 processRow(row);
213 });
214 });
215 return true;
216 });
217
218 bool ret = (cferror == NULL);
219 SecTranslateError(error, cferror);
220 return ret;
221 }
222
223 + (bool)queryMaxValueForField:(NSString*)maxField inTable:(NSString*)table where:(NSDictionary*)whereDict columns:(NSArray*)names processRow:(void (^)(NSDictionary*))processRow
224 {
225 __block CFErrorRef cferror = NULL;
226
227 kc_with_dbt(false, &cferror, ^bool(SecDbConnectionRef dbconn) {
228 NSString* columns = [[names componentsJoinedByString:@", "] stringByAppendingFormat:@", %@", maxField];
229 NSString* whereClause = [CKKSSQLDatabaseObject makeWhereClause:whereDict];
230
231 NSString* sql = [[NSString alloc] initWithFormat:@"SELECT %@ FROM %@%@", columns, table, whereClause];
232 SecDbPrepare(dbconn, (__bridge CFStringRef)sql, &cferror, ^(sqlite3_stmt* stmt) {
233 [whereDict.allKeys enumerateObjectsUsingBlock:^(id _Nonnull key, NSUInteger i, BOOL* _Nonnull stop) {
234 if ([whereDict[key] class] != [CKKSSQLWhereObject class]) {
235 SecDbBindObject(stmt, (int)(i+1), (__bridge CFStringRef) whereDict[key], &cferror);
236 }
237 }];
238
239 SecDbStep(dbconn, stmt, &cferror, ^(bool*stop) {
240 __block NSMutableDictionary* row = [[NSMutableDictionary alloc] init];
241
242 [names enumerateObjectsUsingBlock:^(id _Nonnull name, NSUInteger i, BOOL * _Nonnull stop) {
243 const char * col = (const char *) sqlite3_column_text(stmt, (int)i);
244 row[name] = col ? [NSString stringWithUTF8String:col] : [NSNull null];
245 }];
246
247 processRow(row);
248 });
249 });
250
251 return true;
252 });
253
254 bool ret = (cferror == NULL);
255 return ret;
256 }
257
258 #pragma mark - Instance methods
259
260 - (bool) saveToDatabase: (NSError * __autoreleasing *) error {
261 return [self saveToDatabaseWithConnection:nil error: error];
262 }
263
264 - (bool) saveToDatabaseWithConnection: (SecDbConnectionRef) conn error: (NSError * __autoreleasing *) error {
265 // Todo: turn this into a transaction
266
267 NSDictionary* currentWhereClause = [self whereClauseToFindSelf];
268
269 // First, if we were loaded from the database and the where clause has changed, delete the old record.
270 if(self.originalSelfWhereClause && ![self.originalSelfWhereClause isEqualToDictionary: currentWhereClause]) {
271 secdebug("ckkssql", "Primary key changed; removing old row at %@", self.originalSelfWhereClause);
272 if(![CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: self.originalSelfWhereClause connection:conn error: error]) {
273 return false;
274 }
275 }
276
277 bool ok = [CKKSSQLDatabaseObject saveToDatabaseTable: [[self class] sqlTable]
278 row: [self sqlValues]
279 connection: conn
280 error: error];
281
282 if(ok) {
283 secdebug("ckkssql", "Saved %@", self);
284 } else {
285 secdebug("ckkssql", "Couldn't save %@: %@", self, error ? *error : @"unknown");
286 }
287 return ok;
288 }
289
290 - (bool) deleteFromDatabase: (NSError * __autoreleasing *) error {
291 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[[self class] sqlTable] where: [self whereClauseToFindSelf] connection:nil error: error];
292
293 if(ok) {
294 secdebug("ckkssql", "Deleted %@", self);
295 } else {
296 secdebug("ckkssql", "Couldn't delete %@: %@", self, error ? *error : @"unknown");
297 }
298 return ok;
299 }
300
301 + (bool) deleteAll: (NSError * __autoreleasing *) error {
302 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[self sqlTable] where: nil connection:nil error: error];
303
304 if(ok) {
305 secdebug("ckkssql", "Deleted all %@", self);
306 } else {
307 secdebug("ckkssql", "Couldn't delete all %@: %@", self, error ? *error : @"unknown");
308 }
309 return ok;
310 }
311
312 + (instancetype) fromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
313 id ret = [self tryFromDatabaseWhere: whereDict error:error];
314
315 if(!ret && error) {
316 *error = [NSError errorWithDomain:@"securityd"
317 code:errSecItemNotFound
318 userInfo:@{NSLocalizedDescriptionKey:
319 [NSString stringWithFormat: @"%@ does not exist in database where %@", [self class], whereDict]}];
320 }
321
322 return ret;
323 }
324
325 + (instancetype) tryFromDatabaseWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
326 __block id ret = nil;
327
328 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
329 where: whereDict
330 columns: [self sqlColumns]
331 groupBy: nil
332 orderBy:nil
333 limit: -1
334 processRow: ^(NSDictionary* row) {
335 ret = [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause];
336 }
337 error: error];
338
339 return ret;
340 }
341
342 + (NSArray*) all: (NSError * __autoreleasing *) error {
343 return [self allWhere: nil error:error];
344 }
345
346 + (NSArray*) allWhere: (NSDictionary*) whereDict error: (NSError * __autoreleasing *) error {
347 __block NSMutableArray* items = [[NSMutableArray alloc] init];
348
349 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
350 where: whereDict
351 columns: [self sqlColumns]
352 groupBy: nil
353 orderBy:nil
354 limit: -1
355 processRow: ^(NSDictionary* row) {
356 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
357 }
358 error: error];
359
360 return items;
361 }
362
363 + (NSArray*)fetch: (size_t)count error: (NSError * __autoreleasing *) error {
364 return [self fetch: count where:nil orderBy:nil error:error];
365 }
366
367 + (NSArray*)fetch: (size_t)count where:(NSDictionary*)whereDict error: (NSError * __autoreleasing *) error {
368 return [self fetch: count where:whereDict orderBy:nil error:error];
369 }
370
371 + (NSArray*)fetch:(size_t)count
372 where:(NSDictionary*)whereDict
373 orderBy:(NSArray*) orderColumns
374 error:(NSError * __autoreleasing *) error {
375 __block NSMutableArray* items = [[NSMutableArray alloc] init];
376
377 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
378 where: whereDict
379 columns: [self sqlColumns]
380 groupBy:nil
381 orderBy:orderColumns
382 limit: (ssize_t) count
383 processRow: ^(NSDictionary* row) {
384 [items addObject: [[self fromDatabaseRow: row] memoizeOriginalSelfWhereClause]];
385 }
386 error: error];
387
388 return items;
389 }
390
391 - (instancetype) memoizeOriginalSelfWhereClause {
392 _originalSelfWhereClause = [self whereClauseToFindSelf];
393 return self;
394 }
395
396 #pragma mark - Subclass methods
397
398 + (instancetype) fromDatabaseRow:(NSDictionary *)row {
399 @throw [NSException exceptionWithName:NSInternalInconsistencyException
400 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
401 userInfo:nil];
402 }
403
404 + (NSString*) sqlTable {
405 @throw [NSException exceptionWithName:NSInternalInconsistencyException
406 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
407 userInfo:nil];
408 }
409
410 + (NSArray<NSString*>*) sqlColumns {
411 @throw [NSException exceptionWithName:NSInternalInconsistencyException
412 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
413 userInfo:nil];
414 }
415
416 - (NSDictionary<NSString*,NSString*>*) sqlValues {
417 @throw [NSException exceptionWithName:NSInternalInconsistencyException
418 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
419 userInfo:nil];
420 }
421
422 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
423 @throw [NSException exceptionWithName:NSInternalInconsistencyException
424 reason:[NSString stringWithFormat:@"A subclass must override %@", NSStringFromSelector(_cmd)]
425 userInfo:nil];
426 }
427
428 - (instancetype)copyWithZone:(NSZone *)zone {
429 CKKSSQLDatabaseObject *dbCopy = [[[self class] allocWithZone:zone] init];
430 dbCopy->_originalSelfWhereClause = _originalSelfWhereClause;
431 return dbCopy;
432 }
433 @end
434
435 #pragma mark - CKKSSQLWhereObject
436
437 @implementation CKKSSQLWhereObject
438 - (instancetype)initWithOperation:(NSString*)op string: (NSString*) str {
439 if(self = [super init]) {
440 _sqlOp = op;
441 _contents = str;
442 }
443 return self;
444 }
445
446 + (instancetype)op:(NSString*) op string: (NSString*) str {
447 return [[CKKSSQLWhereObject alloc] initWithOperation:op string: str];
448 }
449
450 + (instancetype)op:(NSString*) op stringValue: (NSString*) str {
451 return [[CKKSSQLWhereObject alloc] initWithOperation:op string:[NSString stringWithFormat:@"'%@'", str]];
452 }
453
454
455 @end