2 * Copyright (c) 2006-2014 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@
25 * SecItemDataSource.c - CoreFoundation-based constants and functions for
26 access to Security items (certificates, keys, identities, and
30 #include <securityd/SecItemDataSource.h>
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>
48 typedef struct SecItemDataSource
*SecItemDataSourceRef
;
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.
56 static const SecDbClass
*dsSyncedClasses
[] = {
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
;
71 CFStringRef sql
= SecDbItemCopySelectSQL(query
, return_attr
, use_attr_in_where
, add_where_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
); }));
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
);
91 Query
*q
= query_create(dsSyncedClasses
[class_ix
], NULL
, error
);
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
);
107 SOSDigestVectorAppend(&dv
, digest
);
110 secerror("SecDbItemSelect failed: %@", localError
);
112 query_destroy(q
, &localError
);
114 secerror("query_destroy failed: %@", localError
);
116 } else if (localError
) {
117 secerror("query_create failed: %@", localError
);
120 manifest
= SOSManifestCreateWithDigestVector(&dv
, &localError
);
121 SOSDigestVectorFree(&dv
);
123 CFReleaseNull(manifest
);
126 if (error
&& !*error
&& localError
)
129 CFReleaseSafe(localError
);
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
;
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
:
146 case kCFCompareLessThan
:
149 case kCFCompareEqualTo
:
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
:
159 case kCFCompareLessThan
:
162 } else if (SecErrorGetOSStatus(localError
) == errSecDecode
) {
163 if (digest1
) result
= item1
;
164 if (digest2
) result
= item2
;
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
;
176 if (!result
&& error
&& !*error
)
179 CFRelease(localError
);
181 return CFRetainSafe(result
);
185 // MARK: DataSource protocol implementation
188 static CFStringRef
dsGetName(SOSDataSourceRef data_source
) {
189 SecItemDataSourceRef ds
= (SecItemDataSourceRef
)data_source
;
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
);
201 static SOSManifestRef
dsCopyManifest(SOSDataSourceRef data_source
, CFErrorRef
*error
) {
202 struct SecItemDataSource
*ds
= (struct SecItemDataSource
*)data_source
;
203 return SecItemDataSourceCopyManifest(ds
, error
);
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
;
214 bool (^use_attr_in_where
)(const SecDbAttr
*attr
) = ^bool (const SecDbAttr
* attr
) {
215 return attr
->kind
== kSecDbSHA1Attr
;
217 Query
*select_queries
[array_size(dsSyncedClasses
)] = {};
218 CFStringRef select_sql
[array_size(dsSyncedClasses
)] = {};
219 sqlite3_stmt
*select_stmts
[array_size(dsSyncedClasses
)] = {};
221 __block Query
**queries
= select_queries
;
222 __block CFStringRef
*sqls
= select_sql
;
223 __block sqlite3_stmt
**stmts
= select_stmts
;
225 result
&= SecDbPerformRead(ds
->db
, error
, ^(SecDbConnectionRef dbconn
) {
227 for (size_t class_ix
= 0; class_ix
< array_size(dsSyncedClasses
); ++class_ix
) {
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
)));
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
);
242 handle_object(key
, (SOSObjectRef
)item
, stop
);
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
);
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.
262 static SOSObjectRef
objectCreateWithPropertyList(CFDictionaryRef plist
, CFErrorRef
*error
) {
263 SecDbItemRef item
= NULL
;
264 const SecDbClass
*class = NULL
;
265 CFTypeRef cname
= CFDictionaryGetValue(plist
, kSecClass
);
267 class = kc_class_with_name(cname
);
269 item
= SecDbItemCreateWithAttributes(kCFAllocatorDefault
, class, plist
, KEYBAG_DEVICE
, error
);
271 SecError(errSecNoSuchClass
, error
, CFSTR("can find class named: %@"), cname
);
274 SecError(errSecItemClassMissing
, error
, CFSTR("query missing %@ attribute"), kSecClass
);
276 return (SOSObjectRef
)item
;
279 static CFDataRef
copyObjectDigest(SOSObjectRef object
, CFErrorRef
*error
) {
280 SecDbItemRef item
= (SecDbItemRef
) object
;
281 CFDataRef digest
= SecDbItemGetSHA1(item
, error
);
282 CFRetainSafe(digest
);
286 static CFDataRef
objectCopyPrimaryKey(SOSObjectRef object
, CFErrorRef
*error
) {
287 SecDbItemRef item
= (SecDbItemRef
) object
;
288 CFDataRef pk
= SecDbItemGetPrimaryKey(item
, error
);
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
);
298 if (cryptoDataDict
) {
300 CFDictionaryForEach(authDataDict
, ^(const void *key
, const void *value
) {
301 CFDictionarySetValue(cryptoDataDict
, key
, value
);
304 CFDictionaryAddValue(cryptoDataDict
, kSecClass
, SecDbItemGetClass(item
)->name
);
307 CFReleaseSafe(authDataDict
);
308 return cryptoDataDict
;
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
);
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
;
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
;
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
);
351 *createdObject
= (SOSObjectRef
)CFRetain(mergedItem
);
352 mr
= kSOSMergeCreatedObject
;
356 if (mr
== kSOSMergeFailure
)
358 secnotice("ds", "kSOSMergeFailure => kSOSMergePeersObject");
359 mr
= kSOSMergePeersObject
;
363 if (error
&& *error
&& mr
!= kSOSMergeFailure
)
364 CFReleaseNull(*error
);
366 CFReleaseSafe(mergedItem
);
367 CFReleaseSafe(replacedItem
);
372 Truthy backup format is a dictionary from sha1 => item.
373 Each item has class, hash and item data.
375 TODO: sha1 is included as binary blob to avoid parsing key.
378 kSecBackupIndexHash
= 0,
379 kSecBackupIndexClass
,
383 static const void *kSecBackupKeys
[] = {
384 [kSecBackupIndexHash
] = CFSTR("hash"),
385 [kSecBackupIndexClass
] = CFSTR("class"),
386 [kSecBackupIndexData
] = CFSTR("data"),
389 #define kSecBackupHash kSecBackupKeys[kSecBackupIndexHash]
390 #define kSecBackupClass kSecBackupKeys[kSecBackupIndexClass]
391 #define kSecBackupData kSecBackupKeys[kSecBackupIndexData]
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
;
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
]);
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
,
419 CFReleaseSafe(dataSourceID
);
420 __block CFDataRef data
= NULL
;
421 SecDbQueryRef query
= query_create(&genp_class
, dict
, error
);
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
));
433 query_destroy(query
, error
);
437 if (!data
) secnotice("ds", "failed to load %@@%@ state: %@", key
, pdmn
, error
? *error
: NULL
);
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
,
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
);
458 return mr
!= kSOSMergeFailure
;
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
;
466 if (!item_class
|| !data
)
467 return SecError(errSecDecode
, error
, CFSTR("no class or data in object"));
469 dbclass
= kc_class_with_name(item_class
);
471 return SecError(errSecDecode
, error
, CFSTR("no such class %@; update kc_class_with_name "), item_class
);
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
);
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
;
489 ds
->ds
.dsMergeObject
= dsMergeObject
;
490 ds
->ds
.dsSetStateWithKey
= dsSetStateWithKey
;
491 ds
->ds
.dsRestoreObject
= dsRestoreObject
;
493 // Object field accessors
494 ds
->ds
.objectCopyDigest
= copyObjectDigest
;
495 ds
->ds
.objectCopyPrimaryKey
= objectCopyPrimaryKey
;
497 // Object encode and decode.
498 ds
->ds
.objectCreateWithPropertyList
= objectCreateWithPropertyList
;
499 ds
->ds
.objectCopyPropertyList
= objectCopyPropertyList
;
500 ds
->ds
.objectCopyBackup
= objectCopyBackup
;
502 ds
->db
= CFRetainSafe(db
);
503 ds
->name
= CFRetainSafe(name
);
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
) {
514 static CFArrayRef
SecItemDataSourceFactoryCopyNames(SOSDataSourceFactoryRef factory
)
516 return CFArrayCreateForCFTypes(kCFAllocatorDefault
,
517 kSecAttrAccessibleWhenUnlocked
,
518 //kSecAttrAccessibleAfterFirstUnlock,
519 //kSecAttrAccessibleAlways,
523 struct SecItemDataSourceFactory
{
524 struct SOSDataSourceFactory factory
;
525 CFMutableDictionaryRef dsCache
;
526 dispatch_queue_t queue
;
530 static SOSDataSourceRef
SecItemDataSourceFactoryCopyDataSource(SOSDataSourceFactoryRef factory
, CFStringRef dataSourceName
, CFErrorRef
*error
)
532 struct SecItemDataSourceFactory
*f
= (struct SecItemDataSourceFactory
*)factory
;
533 __block SOSDataSourceRef dataSource
= NULL
;
534 dispatch_sync(f
->queue
, ^{
535 dataSource
= (SOSDataSourceRef
)CFDictionaryGetValue(f
->dsCache
, dataSourceName
);
537 dataSource
= (SOSDataSourceRef
)SecItemDataSourceCreate(f
->db
, dataSourceName
, error
);
538 CFDictionarySetValue(f
->dsCache
, dataSourceName
, dataSource
);
544 static void SecItemDataSourceFactoryDispose(SOSDataSourceFactoryRef factory
)
546 // Nothing to do here.
549 // Fire up the SOSEngines so they can
550 static bool SOSDataSourceFactoryStartYourEngines(SOSDataSourceFactoryRef factory
) {
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
);
558 secerror("create_datasource %@ failed %@", dsName
, localError
);
559 CFReleaseNull(localError
);
560 SOSDataSourceRelease(ds
, &localError
);
561 CFReleaseNull(localError
);
563 CFReleaseSafe(dsNames
);
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
;
580 SOSDataSourceFactoryRef
SecItemDataSourceFactoryGetShared(SecDbRef db
) {
581 static dispatch_once_t sDSFQueueOnce
;
582 static dispatch_queue_t sDSFQueue
;
583 static CFMutableDictionaryRef sDSTable
= NULL
;
585 dispatch_once(&sDSFQueueOnce
, ^{
586 sDSFQueue
= dispatch_queue_create("dataSourceFactory queue", DISPATCH_QUEUE_SERIAL
);
589 __block SOSDataSourceFactoryRef result
= NULL
;
590 dispatch_sync(sDSFQueue
, ^{
591 CFStringRef dbPath
= SecDbGetPath(db
);
593 result
= (SOSDataSourceFactoryRef
) CFDictionaryGetValue(sDSTable
, dbPath
);
595 sDSTable
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, NULL
);
599 result
= SecItemDataSourceFactoryCreate(db
);
601 CFDictionaryAddValue(sDSTable
, dbPath
, result
);
608 void SecItemServerAppendItemDescription(CFMutableStringRef desc
, CFDictionaryRef object
) {
609 SOSObjectRef item
= objectCreateWithPropertyList(object
, NULL
);
611 CFStringRef itemDesc
= CFCopyDescription(item
);
613 CFStringAppend(desc
, itemDesc
);
614 CFReleaseSafe(itemDesc
);
620 SOSManifestRef
SOSCreateManifestWithBackup(CFDictionaryRef backup
, CFErrorRef
*error
)
622 __block
struct SOSDigestVector dv
= SOSDigestVectorInit
;
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
));
633 SOSManifestRef manifest
= SOSManifestCreateWithDigestVector(&dv
, error
);
634 SOSDigestVectorFree(&dv
);