]> git.saurik.com Git - apple/security.git/blob - Security/sec/securityd/SecItemDataSource.c
Security-57031.40.6.tar.gz
[apple/security.git] / Security / sec / securityd / SecItemDataSource.c
1 /*
2 * Copyright (c) 2006-2014 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 /*
25 * SecItemDataSource.c - CoreFoundation-based constants and functions for
26 access to Security items (certificates, keys, identities, and
27 passwords.)
28 */
29
30 #include <securityd/SecItemDataSource.h>
31
32 #include <securityd/SecItemDb.h>
33 #include <securityd/SecItemSchema.h>
34 #include <securityd/SOSCloudCircleServer.h>
35 #include <SecureObjectSync/SOSDigestVector.h>
36 #include <Security/SecBasePriv.h>
37 #include <Security/SecItem.h>
38 #include <Security/SecItemPriv.h>
39 #include <utilities/array_size.h>
40
41 /*
42 *
43 *
44 * SecItemDataSource
45 *
46 *
47 */
48 typedef struct SecItemDataSource *SecItemDataSourceRef;
49
50 struct SecItemDataSource {
51 struct SOSDataSource ds;
52 SecDbRef db; // The database we operate on
53 CFStringRef name; // The name of the slice of the database we represent.
54 };
55
56 static const SecDbClass *dsSyncedClasses[] = {
57 &genp_class,
58 &inet_class,
59 &keys_class,
60 };
61
62 static bool SecDbItemSelectSHA1(SecDbQueryRef query, SecDbConnectionRef dbconn, CFErrorRef *error,
63 bool (^use_attr_in_where)(const SecDbAttr *attr),
64 bool (^add_where_sql)(CFMutableStringRef sql, bool *needWhere),
65 bool (^bind_added_where)(sqlite3_stmt *stmt, int col),
66 void (^row)(sqlite3_stmt *stmt, bool *stop)) {
67 __block bool ok = true;
68 bool (^return_attr)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
69 return attr->kind == kSecDbSHA1Attr;
70 };
71 CFStringRef sql = SecDbItemCopySelectSQL(query, return_attr, use_attr_in_where, add_where_sql);
72 if (sql) {
73 ok &= SecDbPrepare(dbconn, sql, error, ^(sqlite3_stmt *stmt) {
74 ok = (SecDbItemSelectBind(query, stmt, error, use_attr_in_where, bind_added_where) &&
75 SecDbStep(dbconn, stmt, error, ^(bool *stop){ row(stmt, stop); }));
76 });
77 CFRelease(sql);
78 } else {
79 ok = false;
80 }
81 return ok;
82 }
83
84 static SOSManifestRef SecItemDataSourceCopyManifest(SecItemDataSourceRef ds, CFErrorRef *error) {
85 __block SOSManifestRef manifest = NULL;
86 __block CFErrorRef localError = NULL;
87 if (!SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
88 __block struct SOSDigestVector dv = SOSDigestVectorInit;
89 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClasses);
90 ++class_ix) {
91 Query *q = query_create(dsSyncedClasses[class_ix], NULL, error);
92 if (q) {
93 q->q_return_type = kSecReturnDataMask | kSecReturnAttributesMask;
94 q->q_limit = kSecMatchUnlimited;
95 q->q_keybag = KEYBAG_DEVICE;
96 query_add_attribute(kSecAttrSynchronizable, kCFBooleanTrue, q);
97 //query_add_attribute(kSecAttrAccessible, ds->name, q);
98 // Select everything including tombstones that is synchronizable.
99 if (!SecDbItemSelectSHA1(q, dbconn, &localError, ^bool(const SecDbAttr *attr) {
100 return attr->kind == kSecDbSyncAttr;
101 }, NULL, NULL, ^(sqlite3_stmt *stmt, bool *stop) {
102 const uint8_t *digest = sqlite3_column_blob(stmt, 0);
103 size_t digestLen = sqlite3_column_bytes(stmt, 0);
104 if (digestLen != SOSDigestSize) {
105 secerror("digest %zu bytes", digestLen);
106 } else {
107 SOSDigestVectorAppend(&dv, digest);
108 }
109 })) {
110 secerror("SecDbItemSelect failed: %@", localError);
111 }
112 query_destroy(q, &localError);
113 if (localError) {
114 secerror("query_destroy failed: %@", localError);
115 }
116 } else if (localError) {
117 secerror("query_create failed: %@", localError);
118 }
119 }
120 manifest = SOSManifestCreateWithDigestVector(&dv, &localError);
121 SOSDigestVectorFree(&dv);
122 })) {
123 CFReleaseNull(manifest);
124 };
125
126 if (error && !*error && localError)
127 *error = localError;
128 else
129 CFReleaseSafe(localError);
130
131 return manifest;
132 }
133
134 // Return the newest object (conflict resolver)
135 static SecDbItemRef SecItemDataSourceCopyMergedItem(SecDbItemRef item1, SecDbItemRef item2, CFErrorRef *error) {
136 CFErrorRef localError = NULL;
137 SecDbItemRef result = NULL;
138 CFDateRef m1, m2;
139 const SecDbAttr *desc = SecDbAttrWithKey(SecDbItemGetClass(item1), kSecAttrModificationDate, error);
140 m1 = SecDbItemGetValue(item1, desc, &localError);
141 m2 = SecDbItemGetValue(item2, desc, &localError);
142 if (m1 && m2) switch (CFDateCompare(m1, m2, NULL)) {
143 case kCFCompareGreaterThan:
144 result = item1;
145 break;
146 case kCFCompareLessThan:
147 result = item2;
148 break;
149 case kCFCompareEqualTo:
150 {
151 // Return the item with the smallest digest.
152 CFDataRef digest1 = SecDbItemGetSHA1(item1, &localError);
153 CFDataRef digest2 = SecDbItemGetSHA1(item2, &localError);
154 if (digest1 && digest2) switch (CFDataCompare(digest1, digest2)) {
155 case kCFCompareGreaterThan:
156 case kCFCompareEqualTo:
157 result = item2;
158 break;
159 case kCFCompareLessThan:
160 result = item1;
161 break;
162 } else if (SecErrorGetOSStatus(localError) == errSecDecode) {
163 if (digest1) result = item1;
164 if (digest2) result = item2;
165 }
166 break;
167 }
168 } else if (SecErrorGetOSStatus(localError) == errSecDecode) {
169 // If one of the two objects has an unparsable date,
170 // the object with the parsable date wins.
171 if (m1) result = item1;
172 if (m2) result = item2;
173 }
174
175 if (localError) {
176 if (!result && error && !*error)
177 *error = localError;
178 else
179 CFRelease(localError);
180 }
181 return CFRetainSafe(result);
182 }
183
184 //
185 // MARK: DataSource protocol implementation
186 //
187
188 static CFStringRef dsGetName(SOSDataSourceRef data_source) {
189 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
190 return ds->name;
191 }
192
193 static void dsSetNotifyPhaseBlock(SOSDataSourceRef data_source, dispatch_queue_t queue, SOSDataSourceNotifyBlock notifyBlock) {
194 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
195 SecDbSetNotifyPhaseBlock(ds->db, queue, notifyBlock ? ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, struct SOSDigestVector *removals, struct SOSDigestVector *additions) {
196 notifyBlock(&ds->ds, (SOSTransactionRef)dbconn, phase, source, removals, additions);
197 } : NULL);
198 }
199
200
201 static SOSManifestRef dsCopyManifest(SOSDataSourceRef data_source, CFErrorRef *error) {
202 struct SecItemDataSource *ds = (struct SecItemDataSource *)data_source;
203 return SecItemDataSourceCopyManifest(ds, error);
204 }
205
206 static bool dsForEachObject(SOSDataSourceRef data_source, SOSManifestRef manifest, CFErrorRef *error, void (^handle_object)(CFDataRef key, SOSObjectRef object, bool *stop)) {
207 struct SecItemDataSource *ds = (struct SecItemDataSource *)data_source;
208 __block bool result = true;
209 const SecDbAttr *sha1Attr = SecDbClassAttrWithKind(&genp_class, kSecDbSHA1Attr, error);
210 if (!sha1Attr) return false;
211 bool (^return_attr)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
212 return attr->kind == kSecDbRowIdAttr || attr->kind == kSecDbEncryptedDataAttr;
213 };
214 bool (^use_attr_in_where)(const SecDbAttr *attr) = ^bool (const SecDbAttr * attr) {
215 return attr->kind == kSecDbSHA1Attr;
216 };
217 Query *select_queries[array_size(dsSyncedClasses)] = {};
218 CFStringRef select_sql[array_size(dsSyncedClasses)] = {};
219 sqlite3_stmt *select_stmts[array_size(dsSyncedClasses)] = {};
220
221 __block Query **queries = select_queries;
222 __block CFStringRef *sqls = select_sql;
223 __block sqlite3_stmt **stmts = select_stmts;
224
225 result &= SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
226 // Setup
227 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClasses); ++class_ix) {
228 result = (result
229 && (queries[class_ix] = query_create(dsSyncedClasses[class_ix], NULL, error))
230 && (sqls[class_ix] = SecDbItemCopySelectSQL(queries[class_ix], return_attr, use_attr_in_where, NULL))
231 && (stmts[class_ix] = SecDbCopyStmt(dbconn, sqls[class_ix], NULL, error)));
232 }
233
234 if (result) SOSManifestForEach(manifest, ^(CFDataRef key, bool *stop) {
235 __block SecDbItemRef item = NULL;
236 for (size_t class_ix = 0; result && !item && class_ix < array_size(dsSyncedClasses); ++class_ix) {
237 CFDictionarySetValue(queries[class_ix]->q_item, sha1Attr->name, key);
238 result = (SecDbItemSelectBind(queries[class_ix], stmts[class_ix], error, use_attr_in_where, NULL) && SecDbStep(dbconn, stmts[class_ix], error, ^(bool *unused_stop) {
239 item = SecDbItemCreateWithStatement(kCFAllocatorDefault, queries[class_ix]->q_class, stmts[class_ix], KEYBAG_DEVICE, error, return_attr);
240 })) && SecDbReset(stmts[class_ix], error);
241 }
242 handle_object(key, (SOSObjectRef)item, stop);
243 CFReleaseSafe(item);
244 });
245
246 // Cleanup
247 for (size_t class_ix = 0; class_ix < array_size(dsSyncedClasses); ++class_ix) {
248 result &= SecDbReleaseCachedStmt(dbconn, sqls[class_ix], stmts[class_ix], error);
249 CFReleaseSafe(sqls[class_ix]);
250 result &= query_destroy(queries[class_ix], error);
251 }
252 });
253 return result;
254 }
255
256 static bool dsRelease(SOSDataSourceRef data_source, CFErrorRef *error) {
257 // We never release our dataSource since it's tracking changes
258 // to the keychain for the engine and its peers.
259 return true;
260 }
261
262 static SOSObjectRef objectCreateWithPropertyList(CFDictionaryRef plist, CFErrorRef *error) {
263 SecDbItemRef item = NULL;
264 const SecDbClass *class = NULL;
265 CFTypeRef cname = CFDictionaryGetValue(plist, kSecClass);
266 if (cname) {
267 class = kc_class_with_name(cname);
268 if (class) {
269 item = SecDbItemCreateWithAttributes(kCFAllocatorDefault, class, plist, KEYBAG_DEVICE, error);
270 } else {
271 SecError(errSecNoSuchClass, error, CFSTR("can find class named: %@"), cname);
272 }
273 } else {
274 SecError(errSecItemClassMissing, error, CFSTR("query missing %@ attribute"), kSecClass);
275 }
276 return (SOSObjectRef)item;
277 }
278
279 static CFDataRef copyObjectDigest(SOSObjectRef object, CFErrorRef *error) {
280 SecDbItemRef item = (SecDbItemRef) object;
281 CFDataRef digest = SecDbItemGetSHA1(item, error);
282 CFRetainSafe(digest);
283 return digest;
284 }
285
286 static CFDataRef objectCopyPrimaryKey(SOSObjectRef object, CFErrorRef *error) {
287 SecDbItemRef item = (SecDbItemRef) object;
288 CFDataRef pk = SecDbItemGetPrimaryKey(item, error);
289 CFRetainSafe(pk);
290 return pk;
291 }
292
293 static CFDictionaryRef objectCopyPropertyList(SOSObjectRef object, CFErrorRef *error) {
294 SecDbItemRef item = (SecDbItemRef) object;
295 CFMutableDictionaryRef cryptoDataDict = SecDbItemCopyPListWithMask(item, kSecDbInCryptoDataFlag, error);
296 CFMutableDictionaryRef authDataDict = SecDbItemCopyPListWithMask(item, kSecDbInAuthenticatedDataFlag, error);
297
298 if (cryptoDataDict) {
299 if (authDataDict) {
300 CFDictionaryForEach(authDataDict, ^(const void *key, const void *value) {
301 CFDictionarySetValue(cryptoDataDict, key, value);
302 });
303 }
304 CFDictionaryAddValue(cryptoDataDict, kSecClass, SecDbItemGetClass(item)->name);
305 }
306
307 CFReleaseSafe(authDataDict);
308 return cryptoDataDict;
309 }
310
311 static bool dsWith(SOSDataSourceRef data_source, CFErrorRef *error, SOSDataSourceTransactionSource source, void(^transaction)(SOSTransactionRef txn, bool *commit)) {
312 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
313 __block bool ok = true;
314 ok &= SecDbPerformWrite(ds->db, error, ^(SecDbConnectionRef dbconn) {
315 ok &= SecDbTransaction(dbconn,
316 source == kSOSDataSourceAPITransaction ? kSecDbExclusiveTransactionType : kSecDbExclusiveRemoteTransactionType,
317 error, ^(bool *commit) {
318 transaction((SOSTransactionRef)dbconn, commit);
319 });
320 });
321 return ok;
322 }
323
324 static SOSMergeResult dsMergeObject(SOSTransactionRef txn, SOSObjectRef peersObject, SOSObjectRef *createdObject, CFErrorRef *error) {
325 SecDbConnectionRef dbconn = (SecDbConnectionRef)txn;
326 SecDbItemRef peersItem = (SecDbItemRef)peersObject;
327 __block SOSMergeResult mr = kSOSMergeFailure;
328 __block SecDbItemRef mergedItem = NULL;
329 __block SecDbItemRef replacedItem = NULL;
330 if (!peersItem || !dbconn || !SecDbItemSetKeybag(peersItem, KEYBAG_DEVICE, error)) return mr;
331 if (SecDbItemInsertOrReplace(peersItem, dbconn, NULL, error, ^(SecDbItemRef myItem, SecDbItemRef *replace) {
332 // An item with the same primary key as dbItem already exists in the the database. That item is old_item.
333 // Let the conflict resolver choose which item to keep.
334 mergedItem = SecItemDataSourceCopyMergedItem(peersItem, myItem, error);
335 if (!mergedItem) return;
336 if (CFEqual(mergedItem, myItem)) {
337 // Conflict resolver choose my (local) item
338 secnotice("ds", "Conflict resolver choose my (local) item: %@", myItem);
339 mr = kSOSMergeLocalObject;
340 } else {
341 CFRetainAssign(replacedItem, myItem);
342 *replace = CFRetainSafe(mergedItem);
343 if (CFEqual(mergedItem, peersItem)) {
344 // Conflict resolver choose peers item
345 secnotice("ds", "Conflict resolver choose peers item: %@", peersItem);
346 mr = kSOSMergePeersObject;
347 } else {
348 // Conflict resolver created a new item; return it to our caller
349 secnotice("ds", "Conflict resolver created a new item; return it to our caller: %@", mergedItem);
350 if (createdObject)
351 *createdObject = (SOSObjectRef)CFRetain(mergedItem);
352 mr = kSOSMergeCreatedObject;
353 }
354 }
355 })) {
356 if (mr == kSOSMergeFailure)
357 {
358 secnotice("ds", "kSOSMergeFailure => kSOSMergePeersObject");
359 mr = kSOSMergePeersObject;
360 }
361 }
362
363 if (error && *error && mr != kSOSMergeFailure)
364 CFReleaseNull(*error);
365
366 CFReleaseSafe(mergedItem);
367 CFReleaseSafe(replacedItem);
368 return mr;
369 }
370
371 /*
372 Truthy backup format is a dictionary from sha1 => item.
373 Each item has class, hash and item data.
374
375 TODO: sha1 is included as binary blob to avoid parsing key.
376 */
377 enum {
378 kSecBackupIndexHash = 0,
379 kSecBackupIndexClass,
380 kSecBackupIndexData,
381 };
382
383 static const void *kSecBackupKeys[] = {
384 [kSecBackupIndexHash] = CFSTR("hash"),
385 [kSecBackupIndexClass] = CFSTR("class"),
386 [kSecBackupIndexData] = CFSTR("data"),
387 };
388
389 #define kSecBackupHash kSecBackupKeys[kSecBackupIndexHash]
390 #define kSecBackupClass kSecBackupKeys[kSecBackupIndexClass]
391 #define kSecBackupData kSecBackupKeys[kSecBackupIndexData]
392
393 static CFDictionaryRef objectCopyBackup(SOSObjectRef object, uint64_t handle, CFErrorRef *error) {
394 const void *values[array_size(kSecBackupKeys)];
395 SecDbItemRef item = (SecDbItemRef)object;
396 CFDictionaryRef backup_item = NULL;
397
398 if ((values[kSecBackupIndexHash] = SecDbItemGetSHA1(item, error))) {
399 if ((values[kSecBackupIndexData] = SecDbItemCopyEncryptedDataToBackup(item, handle, error))) {
400 values[kSecBackupIndexClass] = SecDbItemGetClass(item)->name;
401 backup_item = CFDictionaryCreate(kCFAllocatorDefault, kSecBackupKeys, values, array_size(kSecBackupKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
402 CFRelease(values[kSecBackupIndexData]);
403 }
404 }
405
406 return backup_item;
407 }
408
409 static CFDataRef dsCopyStateWithKey(SOSDataSourceRef data_source, CFStringRef key, CFStringRef pdmn, CFErrorRef *error) {
410 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
411 CFStringRef dataSourceID = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("SOSDataSource-%@"), ds->name);
412 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
413 kSecAttrAccessGroup, kSOSInternalAccessGroup,
414 kSecAttrAccount, key,
415 kSecAttrService, dataSourceID,
416 kSecAttrAccessible, pdmn,
417 kSecAttrSynchronizable, kCFBooleanFalse,
418 NULL);
419 CFReleaseSafe(dataSourceID);
420 __block CFDataRef data = NULL;
421 SecDbQueryRef query = query_create(&genp_class, dict, error);
422 if (query) {
423 if (query->q_item) CFReleaseSafe(query->q_item);
424 query->q_item = dict;
425 SecDbPerformRead(ds->db, error, ^(SecDbConnectionRef dbconn) {
426 SecDbItemSelect(query, dbconn, error, ^bool(const SecDbAttr *attr) {
427 return CFDictionaryContainsKey(dict, attr->name);
428 }, NULL, NULL, ^(SecDbItemRef item, bool *stop) {
429 secnotice("ds", "found item for key %@@%@", key, pdmn);
430 data = CFRetainSafe(SecDbItemGetValue(item, &v6v_Data, error));
431 });
432 });
433 query_destroy(query, error);
434 } else {
435 CFReleaseSafe(dict);
436 }
437 if (!data) secnotice("ds", "failed to load %@@%@ state: %@", key, pdmn, error ? *error : NULL);
438 return data;
439 }
440
441 static bool dsSetStateWithKey(SOSDataSourceRef data_source, SOSTransactionRef txn, CFStringRef key, CFStringRef pdmn, CFDataRef state, CFErrorRef *error) {
442 SecItemDataSourceRef ds = (SecItemDataSourceRef)data_source;
443 CFStringRef dataSourceID = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("SOSDataSource-%@"), ds->name);
444 CFMutableDictionaryRef dict = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
445 kSecAttrAccessGroup, kSOSInternalAccessGroup,
446 kSecAttrAccount, key,
447 kSecAttrService, dataSourceID,
448 kSecAttrAccessible, pdmn,
449 kSecAttrSynchronizable, kCFBooleanFalse,
450 kSecValueData, state,
451 NULL);
452 CFReleaseSafe(dataSourceID);
453 SecDbItemRef item = SecDbItemCreateWithAttributes(kCFAllocatorDefault, &genp_class, dict, KEYBAG_DEVICE, error);
454 SOSMergeResult mr = dsMergeObject(txn, (SOSObjectRef)item, NULL, error);
455 if (mr == kSOSMergeFailure) secerror("failed to save %@@%@ state: %@", key, pdmn, error ? *error : NULL);
456 CFReleaseSafe(item);
457 CFReleaseSafe(dict);
458 return mr != kSOSMergeFailure;
459 }
460
461 static bool dsRestoreObject(SOSTransactionRef txn, uint64_t handle, CFDictionaryRef item, CFErrorRef *error) {
462 CFStringRef item_class = CFDictionaryGetValue(item, kSecBackupClass);
463 CFDataRef data = CFDictionaryGetValue(item, kSecBackupData);
464 const SecDbClass *dbclass = NULL;
465
466 if (!item_class || !data)
467 return SecError(errSecDecode, error, CFSTR("no class or data in object"));
468
469 dbclass = kc_class_with_name(item_class);
470 if (!dbclass)
471 return SecError(errSecDecode, error, CFSTR("no such class %@; update kc_class_with_name "), item_class);
472
473 SecDbItemRef dbitem = SecDbItemCreateWithEncryptedData(kCFAllocatorDefault, dbclass, data, (keybag_handle_t)handle, error);
474 bool ok = dbitem && (dsMergeObject(txn, (SOSObjectRef)dbitem, NULL, error) != kSOSMergeFailure);
475 CFReleaseSafe(dbitem);
476 return ok;
477 }
478
479 SOSDataSourceRef SecItemDataSourceCreate(SecDbRef db, CFStringRef name, CFErrorRef *error) {
480 SecItemDataSourceRef ds = calloc(1, sizeof(struct SecItemDataSource));
481 ds->ds.dsGetName = dsGetName;
482 ds->ds.dsSetNotifyPhaseBlock = dsSetNotifyPhaseBlock;
483 ds->ds.dsCopyManifest = dsCopyManifest;
484 ds->ds.dsCopyStateWithKey = dsCopyStateWithKey;
485 ds->ds.dsForEachObject = dsForEachObject;
486 ds->ds.dsWith = dsWith;
487 ds->ds.dsRelease = dsRelease;
488
489 ds->ds.dsMergeObject = dsMergeObject;
490 ds->ds.dsSetStateWithKey = dsSetStateWithKey;
491 ds->ds.dsRestoreObject = dsRestoreObject;
492
493 // Object field accessors
494 ds->ds.objectCopyDigest = copyObjectDigest;
495 ds->ds.objectCopyPrimaryKey = objectCopyPrimaryKey;
496
497 // Object encode and decode.
498 ds->ds.objectCreateWithPropertyList = objectCreateWithPropertyList;
499 ds->ds.objectCopyPropertyList = objectCopyPropertyList;
500 ds->ds.objectCopyBackup = objectCopyBackup;
501
502 ds->db = CFRetainSafe(db);
503 ds->name = CFRetainSafe(name);
504
505 // Do this after the ds is fully setup so the engine can query us right away.
506 ds->ds.engine = SOSEngineCreate(&ds->ds, error);
507 if (!ds->ds.engine) {
508 free(ds);
509 ds = NULL;
510 }
511 return &ds->ds;
512 }
513
514 static CFArrayRef SecItemDataSourceFactoryCopyNames(SOSDataSourceFactoryRef factory)
515 {
516 return CFArrayCreateForCFTypes(kCFAllocatorDefault,
517 kSecAttrAccessibleWhenUnlocked,
518 //kSecAttrAccessibleAfterFirstUnlock,
519 //kSecAttrAccessibleAlways,
520 NULL);
521 }
522
523 struct SecItemDataSourceFactory {
524 struct SOSDataSourceFactory factory;
525 CFMutableDictionaryRef dsCache;
526 dispatch_queue_t queue;
527 SecDbRef db;
528 };
529
530 static SOSDataSourceRef SecItemDataSourceFactoryCopyDataSource(SOSDataSourceFactoryRef factory, CFStringRef dataSourceName, CFErrorRef *error)
531 {
532 struct SecItemDataSourceFactory *f = (struct SecItemDataSourceFactory *)factory;
533 __block SOSDataSourceRef dataSource = NULL;
534 dispatch_sync(f->queue, ^{
535 dataSource = (SOSDataSourceRef)CFDictionaryGetValue(f->dsCache, dataSourceName);
536 if (!dataSource) {
537 dataSource = (SOSDataSourceRef)SecItemDataSourceCreate(f->db, dataSourceName, error);
538 CFDictionarySetValue(f->dsCache, dataSourceName, dataSource);
539 }
540 });
541 return dataSource;
542 }
543
544 static void SecItemDataSourceFactoryDispose(SOSDataSourceFactoryRef factory)
545 {
546 // Nothing to do here.
547 }
548
549 // Fire up the SOSEngines so they can
550 static bool SOSDataSourceFactoryStartYourEngines(SOSDataSourceFactoryRef factory) {
551 bool ok = true;
552 CFArrayRef dsNames = factory->copy_names(factory);
553 CFStringRef dsName = NULL;
554 CFArrayForEachC(dsNames, dsName) {
555 CFErrorRef localError = NULL;
556 SOSDataSourceRef ds = factory->create_datasource(factory, dsName, &localError);
557 if (!ds)
558 secerror("create_datasource %@ failed %@", dsName, localError);
559 CFReleaseNull(localError);
560 SOSDataSourceRelease(ds, &localError);
561 CFReleaseNull(localError);
562 }
563 CFReleaseSafe(dsNames);
564 return ok;
565 }
566
567 static SOSDataSourceFactoryRef SecItemDataSourceFactoryCreate(SecDbRef db) {
568 struct SecItemDataSourceFactory *dsf = calloc(1, sizeof(struct SecItemDataSourceFactory));
569 dsf->factory.copy_names = SecItemDataSourceFactoryCopyNames;
570 dsf->factory.create_datasource = SecItemDataSourceFactoryCopyDataSource;
571 dsf->factory.release = SecItemDataSourceFactoryDispose;
572 dsf->dsCache = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
573 dsf->queue = dispatch_queue_create("dsf queue", DISPATCH_QUEUE_SERIAL);
574 dsf->db = CFRetainSafe(db);
575 if (!SOSDataSourceFactoryStartYourEngines(&dsf->factory))
576 secerror("Failed to start engines, gonna lose the race.");
577 return &dsf->factory;
578 }
579
580 SOSDataSourceFactoryRef SecItemDataSourceFactoryGetShared(SecDbRef db) {
581 static dispatch_once_t sDSFQueueOnce;
582 static dispatch_queue_t sDSFQueue;
583 static CFMutableDictionaryRef sDSTable = NULL;
584
585 dispatch_once(&sDSFQueueOnce, ^{
586 sDSFQueue = dispatch_queue_create("dataSourceFactory queue", DISPATCH_QUEUE_SERIAL);
587 });
588
589 __block SOSDataSourceFactoryRef result = NULL;
590 dispatch_sync(sDSFQueue, ^{
591 CFStringRef dbPath = SecDbGetPath(db);
592 if (sDSTable) {
593 result = (SOSDataSourceFactoryRef) CFDictionaryGetValue(sDSTable, dbPath);
594 } else {
595 sDSTable = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
596 }
597
598 if (!result) {
599 result = SecItemDataSourceFactoryCreate(db);
600
601 CFDictionaryAddValue(sDSTable, dbPath, result);
602 }
603 });
604
605 return result;
606 }
607
608 void SecItemServerAppendItemDescription(CFMutableStringRef desc, CFDictionaryRef object) {
609 SOSObjectRef item = objectCreateWithPropertyList(object, NULL);
610 if (item) {
611 CFStringRef itemDesc = CFCopyDescription(item);
612 if (itemDesc) {
613 CFStringAppend(desc, itemDesc);
614 CFReleaseSafe(itemDesc);
615 }
616 CFRelease(item);
617 }
618 }
619
620 SOSManifestRef SOSCreateManifestWithBackup(CFDictionaryRef backup, CFErrorRef *error)
621 {
622 __block struct SOSDigestVector dv = SOSDigestVectorInit;
623 if (backup) {
624 CFDictionaryForEach(backup, ^void (const void * key, const void * value) {
625 if (isDictionary(value)) {
626 /* converting key back to binary blob is horrible */
627 CFDataRef sha1 = CFDictionaryGetValue(value, kSecBackupHash);
628 if (isData(sha1) && CFDataGetLength(sha1) == CCSHA1_OUTPUT_SIZE)
629 SOSDigestVectorAppend(&dv, CFDataGetBytePtr(sha1));
630 }
631 });
632 }
633 SOSManifestRef manifest = SOSManifestCreateWithDigestVector(&dv, error);
634 SOSDigestVectorFree(&dv);
635 return manifest;
636 }