]> git.saurik.com Git - apple/security.git/blob - keychain/SecureObjectSync/SOSEngine.c
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / SecureObjectSync / SOSEngine.c
1 /*
2 * Copyright (c) 2012-2017 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 /*
26 * SOSEngine.c - Implementation of a secure object syncing engine
27 */
28
29 #import "keychain/SecureObjectSync/SOSChangeTracker.h"
30 #include "keychain/SecureObjectSync/SOSEnginePriv.h"
31 #include "keychain/SecureObjectSync/SOSDigestVector.h"
32 #include "keychain/SecureObjectSync/SOSInternal.h"
33 #include "keychain/SecureObjectSync/SOSPeer.h"
34 #include <Security/SecureObjectSync/SOSViews.h>
35 #include "keychain/SecureObjectSync/SOSBackupEvent.h"
36 #include "keychain/SecureObjectSync/SOSPersist.h"
37 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
38
39 #include <corecrypto/ccder.h>
40 #include <stdlib.h>
41 #include <stdbool.h>
42 #include <utilities/array_size.h>
43 #include <utilities/SecCFCCWrappers.h>
44 #include <utilities/SecCFError.h>
45 #include <utilities/SecCFRelease.h>
46 #include <utilities/SecCFWrappers.h>
47 #include <utilities/der_plist.h>
48 #include <utilities/der_plist_internal.h>
49 #include <utilities/debugging.h>
50 #include <utilities/iCloudKeychainTrace.h>
51 #include <utilities/SecCoreCrypto.h>
52 #include <utilities/SecFileLocations.h>
53 #include <utilities/SecADWrapper.h>
54 #include <utilities/SecTrace.h>
55
56
57 #include <AssertMacros.h>
58 #include <CoreFoundation/CoreFoundation.h>
59
60 #include <securityd/SecItemServer.h> // TODO: We can't leave this here.
61 #include <securityd/SOSCloudCircleServer.h> // TODO: We can't leave this here.
62 #include <Security/SecItem.h> // TODO: We can't leave this here.
63 #include <Security/SecItemPriv.h> // TODO: We can't leave this here.
64 #include <securityd/SecItemSchema.h>
65 #include <securityd/iCloudTrace.h>
66
67 #include <keychain/ckks/CKKS.h>
68
69 #include <CoreFoundation/CFURL.h>
70
71 #include "keychain/SecureObjectSync/SOSEnsureBackup.h"
72
73 //
74 // MARK: SOSEngine The Keychain database with syncable keychain support.
75 //
76
77 //----------------------------------------------------------------------------------------
78 // MARK: Engine state v0
79 //----------------------------------------------------------------------------------------
80
81 // Key in dataSource for general engine state file.
82 // This file only has digest entries in it, no manifests.
83 static const CFStringRef kSOSEngineState = CFSTR("engine-state");
84
85 // Keys in state dictionary
86 static CFStringRef kSOSEngineManifestCacheKey = CFSTR("manifestCache");
87 static CFStringRef kSOSEnginePeerStateKey = CFSTR("peerState");
88 static CFStringRef kSOSEnginePeerIDsKey = CFSTR("peerIDs");
89 static CFStringRef kSOSEngineIDKey = CFSTR("id");
90 static CFStringRef kSOSEngineTraceDateKey = CFSTR("traceDate");
91
92 //----------------------------------------------------------------------------------------
93 // MARK: Engine state v2
94 //----------------------------------------------------------------------------------------
95
96 #if !TARGET_OS_SIMULATOR
97 static const CFIndex kCurrentEngineVersion = 2;
98 #endif
99 // Keychain/datasource items
100 // Used for the kSecAttrAccount when saving in the datasource with dsSetStateWithKey
101 // Class D [kSecAttrAccessibleAlwaysPrivate/kSecAttrAccessibleAlwaysThisDeviceOnly]
102 CFStringRef kSOSEngineStatev2 = CFSTR("engine-state-v2");
103 CFStringRef kSOSEnginePeerStates = CFSTR("engine-peer-states");
104 CFStringRef kSOSEngineManifestCache = CFSTR("engine-manifest-cache");
105 CFStringRef kSOSEngineCoders = CFSTR("engine-coders");
106 #define kSOSEngineProtectionDomainClassA kSecAttrAccessibleWhenUnlockedThisDeviceOnly
107
108 // Keys for individual dictionaries
109 // engine-state-v2
110 CFStringRef kSOSEngineStateVersionKey = CFSTR("engine-stateVersion");
111
112 // Current save/load routines
113 // SOSEngineCreate/SOSEngineLoad/SOSEngineSetState
114 // SOSEngineSave/SOSEngineDoSave/SOSEngineCopyState
115 // no save/load functions external to this file
116
117 /*
118 Divide engine state into five pieces:
119
120 - General engine state
121 - My peer ID
122 - List of other (trusted) peer IDs
123
124 - Coder data (formerly in peer state)
125 - Backup Keybags (backup peers only)
126 - Peer state (including manifest hashes -- just keys into ManifestCache)
127 [__OpaqueSOSPeer/SOSPeerRef]
128 must-send
129 send-objects
130 sequence-number
131 Peer object states:
132 pending-objects
133 unwanted-manifest
134 confirmed-manifest
135 local-manifest
136 pending-manifest
137 Views
138
139 - Manifest Cache
140 - local manifest hashes (copy of local keychain)
141 - peer manifest hashes
142
143 These divisions are based on size, frequency of update, and protection domain
144
145 The Manifest Cache is a dictionary where each key is a hash over its entry,
146 which is a concatenation of 20 byte hashes of the keychain items. The local
147 keychain is present as one entry. The other entries are subsets of that, one
148 for each confirmed/pending/missing/unwanted shared with a peer. The local
149 keychain entry can be re-created by iterating over the databse, whereas the
150 others are built up through communicating with other peers.
151
152 83:d=2 hl=2 l= 13 prim: UTF8STRING :manifestCache
153 98:d=2 hl=4 l= 912 cons: SET
154 102:d=3 hl=2 l= 24 cons: SEQUENCE
155 104:d=4 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
156 126:d=4 hl=2 l= 0 prim: OCTET STRING
157 128:d=3 hl=2 l= 124 cons: SEQUENCE
158 130:d=4 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:F9B59370A4733F0D174E8D220C5BE3AF062C775B
159 152:d=4 hl=2 l= 100 prim: OCTET STRING [HEX DUMP]:5A574BB4EC90C3BBCC69EE73CBFE039133AE807265D6A58003B8D205997EAB96390AAB207E63A2E270A476CAB5B2D9D2F7B0E55512AA957B58D5658E7EF907B069B83AA6BA941790A3C3C4A68292D59DABA3CA342966EFF82E1ACAEB691FD6E20772E17E
160 254:d=3 hl=4 l= 366 cons: SEQUENCE
161 258:d=4 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:2E69C2F7F3E014075B30004CE0EC6C1AD419EBF5
162 280:d=4 hl=4 l= 340 prim: OCTET STRING [HEX DUMP]:07571E9678FD7D68812E409CC96C1F54834A099A0C3A2D12CCE2EA95F4505EA52F2C982B2ADEE3DA14D4712C000309BF63D54A98B61AA1D963C40E0E2531C83B28CA5BE6DA0D26400C3C77A618F711DD3CC0BF86CCBAF8AA3332973268B30EEBF21CD8184D9C8427CA13DECCC7BB83C80009A2EF45CCC07F586315C80CEEEEF5D5352FD000AAE6D9CBB4294D5959FD00198225AF9ABD09B341A2FDC278E9FD1465D6A58003B8D205997EAB96390AAB207E63A2E270A476CAB5B2D9D2F7B0E55512AA957B58D5658E7EF907B069B83AA6BA941790A3C3C4A68292D59D95C9D4D8A8BCA2E8242AB0D409F671F298B6DCAE9BC4238C09E07548CEFB300098606F9E4F230C99ABA3CA342966EFF82E1ACAEB691FD6E20772E17EB4FEFB84F8CF75C0C69C59532C354D175A59F961BA4D4DFA017FD8192288F14278AE76712E127D65FE616C7E4FD0713644F7C9A7ABA1CE065694A968
163 624:d=3 hl=4 l= 386 cons: SEQUENCE
164 628:d=4 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:CCF179FF718C10F151E7409EDF1A06F0DF10DCAD
165 650:d=4 hl=4 l= 360 prim: OCTET STRING [HEX DUMP]:07571E9678FD7D68812E409CC96C1F54834A099A0C3A2D12CCE2EA95F4505EA52F2C982B2ADEE3DA14D4712C000309BF63D54A98B61AA1D963C40E0E2531C83B28CA5BE6DA0D26400C3C77A618F711DD3CC0BF86CCBAF8AA3332973268B30EEBF21CD8184D9C8427CA13DECCC7BB83C80009A2EF45CCC07F586315C80CEEEEF5D5352FD000AAE6D9CBB4294D5959FD00198225AF9ABD09B341A2FDC278E9FD145A574BB4EC90C3BBCC69EE73CBFE039133AE807265D6A58003B8D205997EAB96390AAB207E63A2E270A476CAB5B2D9D2F7B0E55512AA957B58D5658E7EF907B069B83AA6BA941790A3C3C4A68292D59D95C9D4D8A8BCA2E8242AB0D409F671F298B6DCAE9BC4238C09E07548CEFB300098606F9E4F230C99ABA3CA342966EFF82E1ACAEB691FD6E20772E17EB4FEFB84F8CF75C0C69C59532C354D175A59F961BA4D4DFA017FD8192288F14278AE76712E127D65FE616C7E4FD0713644F7C9A7ABA1CE065694A968
166
167 */
168
169
170
171 static bool SOSEngineLoad(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error);
172 static bool SOSEngineSetPeers_locked(SOSEngineRef engine, SOSPeerMetaRef myPeerMeta, CFArrayRef trustedPeerMetas, CFArrayRef untrustedPeerMetas);
173 static void SOSEngineApplyPeerState(SOSEngineRef engine, CFDictionaryRef peerStateMap);
174 static void SOSEngineSynthesizePeerMetas(SOSEngineRef engine, CFMutableArrayRef trustedPeersMetas, CFMutableArrayRef untrustedPeers);
175 static bool SOSEngineLoadCoders(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error);
176 #if !TARGET_OS_SIMULATOR
177 static bool SOSEngineDeleteV0State(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error);
178 #endif
179
180 static CFStringRef SOSPeerIDArrayCreateString(CFArrayRef peerIDs) {
181 return peerIDs ? CFStringCreateByCombiningStrings(kCFAllocatorDefault, peerIDs, CFSTR(" ")) : CFSTR("");
182 }
183
184 static CFStringRef SOSEngineCopyFormattingDesc(CFTypeRef cf, CFDictionaryRef formatOptions) {
185 SOSEngineRef engine = (SOSEngineRef)cf;
186 CFStringRef tpDesc = SOSPeerIDArrayCreateString(engine->peerIDs);
187 CFStringRef desc = CFStringCreateWithFormat(kCFAllocatorDefault, formatOptions, CFSTR("<Engine %@ peers %@ MC[%d] PS[%d]>"), engine->myID, tpDesc, engine->manifestCache ? (int)CFDictionaryGetCount(engine->manifestCache) : 0, engine->peerMap ? (int)CFDictionaryGetCount(engine->peerMap) : 0);
188 CFReleaseSafe(tpDesc);
189 return desc;
190 }
191
192 static CFStringRef SOSEngineCopyDebugDesc(CFTypeRef cf) {
193 return SOSEngineCopyFormattingDesc(cf, NULL);
194 }
195
196 static dispatch_queue_t sEngineQueue;
197 static CFDictionaryRef sEngineMap;
198
199 CFGiblisWithFunctions(SOSEngine, NULL, NULL, NULL, NULL, NULL, SOSEngineCopyFormattingDesc, SOSEngineCopyDebugDesc, NULL, NULL, ^{
200 sEngineQueue = dispatch_queue_create("SOSEngine queue", DISPATCH_QUEUE_SERIAL);
201 sEngineMap = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
202 });
203
204 #define _LOG_RAW_MESSAGES 0
205 void logRawMessage(CFDataRef message, bool sending, uint64_t seqno)
206 {
207 #if _LOG_RAW_MESSAGES
208 CFStringRef hexMessage = NULL;
209 if (message) {
210 hexMessage = CFDataCopyHexString(message);
211 if (sending)
212 secnoticeq("engine", "%s RAW%1d %@", sending ? "send" : "recv", seqno?2:0, hexMessage);
213 else
214 secnoticeq("engine", "%s RAWx %@", sending ? "send" : "recv", hexMessage); // we don't know vers of received msg here
215 }
216 CFReleaseSafe(hexMessage);
217 #endif
218 }
219
220 //
221 // Peer state layout. WRONG! It's an array now
222 // The peer state is an array.
223 // The first element of the array is a dictionary with any number of keys and
224 // values in it (for future expansion) such as changing the digest size or type
225 // or remembering boolean flags for a peers sake.
226 // The next three are special in that they are manifest digests with special
227 // meaning and rules as to how they are treated (These are dynamically updated
228 // based on database activity so they have a fully history of all changes made
229 // to the local db. The first is the manifest representing the pendingObjects
230 // to send to the other peer. This is normally only ever appending to, and in
231 // particular with transactions originating from the Keychain API that affect
232 // syncable items will need to add the new objects digests to the pendingObjects list
233 // while adding the digests of any tombstones encountered to the extra list.
234
235 CFStringRef SOSEngineGetMyID(SOSEngineRef engine) {
236 // TODO: this should not be needed
237 return engine->myID;
238 }
239
240 // TEMPORARY: Get the list of IDs for cleanup, this shouldn't be used instead it should iterate KVS.
241 CFArrayRef SOSEngineGetPeerIDs(SOSEngineRef engine) {
242 if(!engine) return NULL;
243 return engine->peerIDs;
244 }
245
246 void SOSEngineClearCache(SOSEngineRef engine){
247 CFReleaseNull(engine->manifestCache);
248 CFReleaseNull(engine->localMinusUnreadableDigest);
249 if (engine->save_timer)
250 dispatch_source_cancel(engine->save_timer);
251 dispatch_release(engine->queue);
252 engine->queue = NULL;
253 }
254
255 static SOSPeerRef SOSEngineCopyPeerWithMapEntry_locked(SOSEngineRef engine, CFStringRef peerID, CFTypeRef mapEntry, CFErrorRef *error) {
256 SOSPeerRef peer = NULL;
257 if (mapEntry && CFGetTypeID(mapEntry) == SOSPeerGetTypeID()) {
258 // The mapEntry is an SOSPeer, so we're done.
259 peer = (SOSPeerRef)CFRetain(mapEntry);
260 } else {
261 // The mapEntry is a peerState, attempt to initialize a new
262 // peer iff peerID is in the set of trusted peerIDs
263 if (engine->peerIDs && CFArrayContainsValue(engine->peerIDs, CFRangeMake(0, CFArrayGetCount(engine->peerIDs)), peerID)) {
264 CFErrorRef localError = NULL;
265 peer = SOSPeerCreateWithState(engine, peerID, mapEntry, &localError);
266 if (!peer) {
267 secerror("error inflating peer: %@: %@ from state: %@", peerID, localError, mapEntry);
268 CFReleaseNull(localError);
269 peer = SOSPeerCreateWithState(engine, peerID, NULL, error);
270 }
271 if (peer) {
272 // Replace the map entry with the inflated peer.
273 CFDictionarySetValue(engine->peerMap, peerID, peer);
274 }
275 } else {
276 SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("peer: %@ is untrusted inflating not allowed"), peerID);
277 }
278 }
279 return peer;
280 }
281
282 static SOSPeerRef SOSEngineCopyPeerWithID_locked(SOSEngineRef engine, CFStringRef peerID, CFErrorRef *error) {
283 CFTypeRef mapEntry = CFDictionaryGetValue(engine->peerMap, peerID);
284 SOSPeerRef peer = NULL;
285 if (mapEntry) {
286 peer = SOSEngineCopyPeerWithMapEntry_locked(engine, peerID, mapEntry, error);
287 } else {
288 peer = NULL;
289 secerror("peer: %@ not found, peerMap: %@, engine: %@", peerID, engine->peerMap, engine);
290 SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("peer: %@ not found"), peerID);
291 }
292 return peer;
293 }
294
295 struct SOSEngineWithPeerContext {
296 SOSEngineRef engine;
297 void (^with)(SOSPeerRef peer);
298 };
299
300 static void SOSEngineWithPeerMapEntry_locked(const void *peerID, const void *mapEntry, void *context) {
301 struct SOSEngineWithPeerContext *ewp = context;
302 SOSPeerRef peer = SOSEngineCopyPeerWithMapEntry_locked(ewp->engine, peerID, mapEntry, NULL);
303 if (peer) {
304 ewp->with(peer);
305 CFRelease(peer);
306 }
307 }
308
309 static void SOSEngineForEachPeer_locked(SOSEngineRef engine, void (^with)(SOSPeerRef peer)) {
310 struct SOSEngineWithPeerContext ewp = { .engine = engine, .with = with };
311 CFDictionaryRef peerMapCopy = CFDictionaryCreateCopy(NULL, engine->peerMap);
312 CFDictionaryApplyFunction(peerMapCopy, SOSEngineWithPeerMapEntry_locked, &ewp);
313 CFRelease(peerMapCopy);
314 }
315
316 static void SOSEngineWithBackupPeerMapEntry_locked(const void *peerID, const void *mapEntry, void *context) {
317 struct SOSEngineWithPeerContext *ewp = context;
318 // v0 backup peer is always in map but we only consider it a backup peer if it has a keybag.
319 if (SOSPeerMapEntryIsBackup(mapEntry)) {
320 SOSPeerRef peer = SOSEngineCopyPeerWithMapEntry_locked(ewp->engine, peerID, mapEntry, NULL);
321 if (peer) {
322 ewp->with(peer);
323 CFRelease(peer);
324 }
325 }
326 }
327
328 static void SOSEngineForEachBackupPeer_locked(SOSEngineRef engine, void (^with)(SOSPeerRef peer)) {
329 struct SOSEngineWithPeerContext ewp = { .engine = engine, .with = with };
330 CFDictionaryRef peerMapCopy = CFDictionaryCreateCopy(NULL, engine->peerMap);
331 CFDictionaryApplyFunction(peerMapCopy, SOSEngineWithBackupPeerMapEntry_locked, &ewp);
332 CFRelease(peerMapCopy);
333 }
334
335 //
336 // Manifest cache
337 //
338 SOSManifestRef SOSEngineGetManifestForDigest(SOSEngineRef engine, CFDataRef digest) {
339 if (!engine->manifestCache || !digest) return NULL;
340 SOSManifestRef manifest = (SOSManifestRef)CFDictionaryGetValue(engine->manifestCache, digest);
341 if (!manifest) return NULL;
342 if (CFGetTypeID(manifest) != SOSManifestGetTypeID()) {
343 secerror("dropping corrupt manifest for %@ from cache", digest);
344 CFDictionaryRemoveValue(engine->manifestCache, digest);
345 return NULL;
346 }
347
348 return manifest;
349 }
350
351 void SOSEngineAddManifest(SOSEngineRef engine, SOSManifestRef manifest) {
352 CFDataRef digest = SOSManifestGetDigest(manifest, NULL);
353 if (digest) {
354 if (!engine->manifestCache)
355 engine->manifestCache = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
356 CFDictionaryAddValue(engine->manifestCache, digest, manifest);
357 }
358 }
359
360 CFDataRef SOSEnginePatchRecordAndCopyDigest(SOSEngineRef engine, SOSManifestRef base, SOSManifestRef removals, SOSManifestRef additions, CFErrorRef *error) {
361 CFDataRef digest = NULL;
362 SOSManifestRef manifest = SOSManifestCreateWithPatch(base, removals, additions, error);
363 if (manifest) {
364 SOSEngineAddManifest(engine, manifest);
365 digest = CFRetainSafe(SOSManifestGetDigest(manifest, NULL));
366 }
367 CFReleaseSafe(manifest);
368 return digest;
369 }
370
371 SOSManifestRef SOSEngineCopyPersistedManifest(SOSEngineRef engine, CFDictionaryRef persisted, CFStringRef key) {
372 return CFRetainSafe(SOSEngineGetManifestForDigest(engine, asData(CFDictionaryGetValue(persisted, key), NULL)));
373 }
374
375 CFMutableArrayRef SOSEngineCopyPersistedManifestArray(SOSEngineRef engine, CFDictionaryRef persisted, CFStringRef key, CFErrorRef *error) {
376 CFMutableArrayRef manifests = NULL;
377 CFArrayRef digests = NULL;
378 CFDataRef digest;
379 if (asArrayOptional(CFDictionaryGetValue(persisted, key), &digests, error))
380 manifests = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
381 if (digests) CFArrayForEachC(digests, digest) {
382 SOSManifestRef manifest = SOSEngineGetManifestForDigest(engine, digest);
383 if (manifest)
384 CFArrayAppendValue(manifests, manifest);
385 }
386 return manifests;
387 }
388
389 #if !TARGET_OS_SIMULATOR
390 static CFDictionaryRef SOSEngineCopyEncodedManifestCache_locked(SOSEngineRef engine, CFErrorRef *error) {
391 CFMutableDictionaryRef mfc = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
392 SOSEngineForEachPeer_locked(engine, ^(SOSPeerRef peer) {
393 SOSPeerAddManifestsInUse(peer, mfc);
394 });
395 return mfc;
396 }
397 #endif
398
399 //
400 // End of Manifest cache
401 //
402
403 //----------------------------------------------------------------------------------------
404 // MARK: Coders
405 //----------------------------------------------------------------------------------------
406
407 /*
408 Each peer has an associated coder, whcih the engine keeps track of in a
409 CFDictionary indexed by peerID. The coders are read from disk when first needed,
410 then kept in memory as SOSCoders.
411
412 N.B. Don't rollback coder in memory if a transaction is rolled back, since this
413 might lead to reuse of an IV.
414 */
415
416 static bool SOSEngineCopyCoderData(SOSEngineRef engine, CFStringRef peerID, CFDataRef *coderData, CFErrorRef *error) {
417 bool ok = true;
418 SOSCoderRef coder = (SOSCoderRef)CFDictionaryGetValue(engine->coders, peerID);
419 if (coder && (CFGetTypeID(coder) == SOSCoderGetTypeID())) {
420 CFErrorRef localError = NULL;
421 ok = *coderData = SOSCoderCopyDER(coder, &localError);
422 if (!ok) {
423 secerror("failed to der encode coder for peer %@, dropping it: %@", peerID, localError);
424 CFDictionaryRemoveValue(engine->coders, peerID);
425 CFErrorPropagate(localError, error);
426 }
427 } else {
428 *coderData = NULL;
429 }
430 return ok;
431 }
432
433 static SOSCoderRef SOSEngineGetCoderInTx_locked(SOSEngineRef engine, SOSTransactionRef txn, CFStringRef peerID, CFErrorRef *error) {
434 if (!engine->haveLoadedCoders) {
435 engine->haveLoadedCoders = SOSEngineLoadCoders(engine, txn, error);
436
437 if (!engine->haveLoadedCoders) {
438 return NULL;
439 }
440 }
441
442 SOSCoderRef coder = (SOSCoderRef)CFDictionaryGetValue(engine->coders, peerID);
443 if (!coder || (CFGetTypeID(coder) != SOSCoderGetTypeID())) {
444 SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("No coder for peer: %@"), peerID);
445 }
446 return coder;
447 }
448
449 static bool SOSEngineEnsureCoder_locked(SOSEngineRef engine, SOSTransactionRef txn, CFStringRef peerID, SOSFullPeerInfoRef myPeerInfo, SOSPeerInfoRef peerInfo, SOSCoderRef ourCoder, CFErrorRef *error) {
450 //have to have caused coder loading, transactions do this.
451 if (!ourCoder || !SOSCoderIsFor(ourCoder, peerInfo, myPeerInfo)) {
452 secinfo("coder", "New coder for id %@.", peerID);
453 CFErrorRef localError = NULL;
454 SOSCoderRef coder = SOSCoderCreate(peerInfo, myPeerInfo, kCFBooleanFalse, &localError);
455 if (!coder) {
456 secerror("Failed to create coder for %@: %@", peerID, localError);
457 CFErrorPropagate(localError, error);
458 return false;
459 }
460 CFDictionarySetValue(engine->coders, peerID, coder);
461 secdebug("coder", "setting coder for peerid: %@, coder: %@", peerID, coder);
462 CFReleaseNull(coder);
463 engine->codersNeedSaving = true;
464 }
465 return true;
466 }
467
468 bool SOSEngineInitializePeerCoder(SOSEngineRef engine, SOSFullPeerInfoRef myPeerInfo, SOSPeerInfoRef peerInfo, CFErrorRef *error) {
469 __block bool ok = true;
470 CFStringRef peerID = SOSPeerInfoGetPeerID(peerInfo);
471
472 ok &= SOSEngineWithPeerID(engine, peerID, error, ^(SOSPeerRef peer, SOSCoderRef coder, SOSDataSourceRef dataSource, SOSTransactionRef txn, bool *forceSaveState) {
473 ok = SOSEngineEnsureCoder_locked(engine, txn, peerID, myPeerInfo, peerInfo, coder, error);
474 // Only set if the codersNeedSaving state gets set.
475 *forceSaveState = engine->codersNeedSaving;
476 });
477
478 return ok;
479 }
480
481 static bool SOSEngineGCPeerState_locked(SOSEngineRef engine, CFErrorRef *error) {
482 bool ok = true;
483
484 //require_quiet(ok = SOSEngineGCManifests_locked(engine, error), exit);
485
486 //exit:
487 return ok;
488 }
489 #if !TARGET_OS_SIMULATOR
490 static CFMutableDictionaryRef SOSEngineCopyPeerState_locked(SOSEngineRef engine, CFErrorRef *error) {
491 CFMutableDictionaryRef peerState = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
492 CFDictionaryForEach(engine->peerMap, ^(const void *key, const void *value) {
493 CFDictionaryRef state = NULL;
494 if (value && CFGetTypeID(value) == SOSPeerGetTypeID()) {
495 CFErrorRef localError = NULL;
496 // Inflated peer
497 state = SOSPeerCopyState((SOSPeerRef)value, &localError);
498 if (!state)
499 secnotice("engine", "%@ failed to encode peer: %@", key, localError);
500 CFReleaseNull(localError);
501 // TODO: Potentially replace inflated peer with deflated peer in peerMap
502 } else if (value) {
503 // We have a deflated peer.
504 state = CFRetainSafe(value);
505 }
506
507 if (state) {
508 CFDictionarySetValue(peerState, key, state);
509 CFReleaseSafe(state);
510 }
511 });
512 return peerState;
513 }
514 #endif
515 static CFMutableDictionaryRef SOSEngineCopyPeerCoders_locked(SOSEngineRef engine, CFErrorRef *error) {
516 CFMutableDictionaryRef coders = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
517 CFDictionaryForEach(engine->peerMap, ^(const void *key, const void *value) {
518 CFDataRef coderData = NULL;
519 CFErrorRef localError = NULL;
520 bool ok = SOSEngineCopyCoderData(engine, (CFStringRef)key, &coderData, &localError);
521
522 if (!ok) {
523 secnotice("engine", "%@ no coder for peer: %@", key, localError);
524 }
525 if (ok && coderData) {
526 CFDictionarySetValue(coders, key, coderData);
527 }
528 CFReleaseNull(coderData);
529 CFReleaseNull(localError);
530 });
531 return coders;
532 }
533
534 //----------------------------------------------------------------------------------------
535 // MARK: Engine state v2 Save
536 //----------------------------------------------------------------------------------------
537
538 // Coders and keybags
539
540 static CFDataRef SOSEngineCopyCoders(SOSEngineRef engine, CFErrorRef *error) {
541 // Copy the CFDataRef version of the coders into a dictionary, which is then DER-encoded for saving
542 CFDictionaryRef coders = SOSEngineCopyPeerCoders_locked(engine, error);
543 secdebug("coders", "copying coders! %@", coders);
544 CFDataRef der = CFPropertyListCreateDERData(kCFAllocatorDefault, coders, error);
545 CFReleaseSafe(coders);
546 return der;
547 }
548
549 #pragma clang diagnostic push
550 #pragma clang diagnostic fatal "-Wshadow"
551 static bool SOSEngineSaveCoders(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
552 // MUST hold engine lock
553 // Device must be unlocked for this to succeed
554
555 if(!engine->haveLoadedCoders){
556 secdebug("coders", "attempting to save coders before we have loaded them!");
557 }
558
559 bool ok = true;
560 if (engine->codersNeedSaving) {
561 CFErrorRef localError = NULL;
562 CFDataRef derCoders = SOSEngineCopyCoders(engine, &localError);
563 ok = derCoders && SOSDataSourceSetStateWithKey(engine->dataSource, txn, kSOSEngineCoders,
564 kSOSEngineProtectionDomainClassA, derCoders, &localError);
565 if (ok) {
566 engine->codersNeedSaving = false;
567 secnotice("coder", "saved coders: %@", engine->coders);
568 } else {
569 if(error) CFTransferRetained(*error, localError);
570 secnotice("coder", "failed to save coders: %@ (%@)", engine->coders, localError);
571 }
572 CFReleaseSafe(derCoders);
573 CFReleaseSafe(localError);
574 }
575 return ok;
576 }
577 #pragma clang diagnostic pop
578
579 bool SOSTestEngineSaveCoders(CFTypeRef engine, SOSTransactionRef txn, CFErrorRef *error){
580 return SOSEngineSaveCoders((SOSEngineRef)engine, txn, error);
581 }
582 #if !TARGET_OS_SIMULATOR
583
584 static CFDictionaryRef SOSEngineCopyBasicState(SOSEngineRef engine, CFErrorRef *error) {
585 // Create a version of the in-memory engine state for saving to disk
586 CFMutableDictionaryRef state = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
587 if (engine->myID)
588 CFDictionarySetValue(state, kSOSEngineIDKey, engine->myID);
589 if (engine->peerIDs)
590 CFDictionarySetValue(state, kSOSEnginePeerIDsKey, engine->peerIDs);
591 if (engine->lastTraceDate)
592 CFDictionarySetValue(state, kSOSEngineTraceDateKey, engine->lastTraceDate);
593
594 SOSPersistCFIndex(state, kSOSEngineStateVersionKey, kCurrentEngineVersion);
595 return state;
596 }
597
598 static bool SOSEngineDoSaveOneState(SOSEngineRef engine, SOSTransactionRef txn, CFStringRef key, CFStringRef pdmn,
599 CFDictionaryRef state, CFErrorRef *error) {
600 CFDataRef derState = CFPropertyListCreateDERData(kCFAllocatorDefault, state, error);
601 bool ok = derState && SOSDataSourceSetStateWithKey(engine->dataSource, txn, key, pdmn, derState, error);
602 CFReleaseSafe(derState);
603 return ok;
604 }
605
606 static bool SOSEngineDoSave(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
607 bool ok = true;
608
609 CFDictionaryRef state = SOSEngineCopyBasicState(engine, error);
610 ok &= state && SOSEngineDoSaveOneState(engine, txn, kSOSEngineStatev2, kSOSEngineProtectionDomainClassD, state, error);
611 CFReleaseNull(state);
612
613 state = SOSEngineCopyPeerState_locked(engine, error);
614 ok &= state && SOSEngineDoSaveOneState(engine, txn, kSOSEnginePeerStates, kSOSEngineProtectionDomainClassD, state, error);
615 CFReleaseNull(state);
616
617 state = SOSEngineCopyEncodedManifestCache_locked(engine, error);
618 ok &= state && SOSEngineDoSaveOneState(engine, txn, kSOSEngineManifestCache, kSOSEngineProtectionDomainClassD, state, error);
619 CFReleaseNull(state);
620
621 ok &= SOSEngineSaveCoders(engine, txn, error);
622
623 SOSEngineDeleteV0State(engine, txn, NULL);
624
625 return ok;
626 }
627 #endif
628
629 static bool SOSEngineSave(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
630 // Don't save engine state from tests
631 if (!engine->dataSource)
632 return true;
633 #if !TARGET_OS_SIMULATOR
634 return SOSEngineDoSave(engine, txn, error);
635 #endif
636 return true;
637 }
638
639 //----------------------------------------------------------------------------------------
640 // MARK: Engine state v2 Load/Restore
641 //----------------------------------------------------------------------------------------
642
643 // Restore the in-memory state of engine from saved state loaded from the db
644 static bool SOSEngineSetManifestCacheWithDictionary(SOSEngineRef engine, CFDictionaryRef manifestCache, CFErrorRef *error) {
645 __block bool ok = true;
646 CFReleaseNull(engine->manifestCache);
647 if (manifestCache) {
648 engine->manifestCache = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
649 CFDictionaryForEach(manifestCache, ^(const void *key, const void *value) {
650 CFDataRef data = (CFDataRef)value;
651 if (isData(data)) {
652 SOSManifestRef mf = SOSManifestCreateWithData(data, NULL);
653 if (mf)
654 CFDictionarySetValue(engine->manifestCache, key, mf);
655 CFReleaseSafe(mf);
656 }
657 });
658 }
659
660 return ok;
661 }
662
663 static bool SOSEngineUpdateStateWithDictionary(SOSEngineRef engine, CFDictionaryRef stateDict, CFErrorRef *error) {
664 bool ok = true;
665 #if 0
666 if (stateDict) {
667 // If kCurrentEngineVersion > 2, uncomment and fill in code below
668 CFIndex engineVersion = 0 ;
669 bool versionPresent = SOSPeerGetOptionalPersistedCFIndex(stateDict, kSOSEngineStateVersionKey, &engineVersion);
670 if (versionPresent && (engineVersion != kCurrentEngineVersion)) {
671 // need migration
672 }
673 }
674 #endif
675 return ok;
676 }
677
678 static bool SOSEngineSetStateWithDictionary(SOSEngineRef engine, CFDictionaryRef stateDict, CFErrorRef *error) {
679 bool ok = true;
680 if (stateDict) {
681 SOSEngineUpdateStateWithDictionary(engine, stateDict, error);
682 CFRetainAssign(engine->myID, asString(CFDictionaryGetValue(stateDict, kSOSEngineIDKey), NULL));
683 CFRetainAssign(engine->peerIDs, asArray(CFDictionaryGetValue(stateDict, kSOSEnginePeerIDsKey), NULL));
684 CFRetainAssign(engine->lastTraceDate, asDate(CFDictionaryGetValue(stateDict, kSOSEngineTraceDateKey), NULL));
685
686 }
687 secnotice("engine", "%@", engine);
688 return ok;
689 }
690
691 static bool SOSEngineSetPeerStateWithDictionary(SOSEngineRef engine, CFDictionaryRef peerStateDict, CFErrorRef *error) {
692 // Set the in-memory peer state using the dictionary version of the DER-encoded version from disk
693 CFMutableArrayRef untrustedPeers = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
694 CFMutableArrayRef trustedPeersMetas = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
695 SOSEngineApplyPeerState(engine, asDictionary(peerStateDict, NULL));
696 SOSEngineSynthesizePeerMetas(engine, trustedPeersMetas, untrustedPeers);
697 SOSEngineSetPeers_locked(engine, engine->myID, trustedPeersMetas, untrustedPeers);
698 CFReleaseNull(trustedPeersMetas);
699 CFReleaseNull(untrustedPeers);
700 return true;
701 }
702
703 CFMutableDictionaryRef derStateToDictionaryCopy(CFDataRef state, CFErrorRef *error) {
704 bool ok = true;
705 CFMutableDictionaryRef stateDict = NULL;
706 if (state) {
707 const uint8_t *der = CFDataGetBytePtr(state);
708 const uint8_t *der_end = der + CFDataGetLength(state);
709 ok = der = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListMutableContainers, (CFDictionaryRef *)&stateDict, error, der, der_end);
710 if (der && der != der_end) {
711 ok = SOSErrorCreate(kSOSErrorDecodeFailure, error, NULL, CFSTR("trailing %td bytes at end of state"), der_end - der);
712 }
713 if (!ok) {
714 CFReleaseNull(stateDict);
715 }
716 }
717 return stateDict;
718 }
719 bool TestSOSEngineLoadCoders(CFTypeRef engine, SOSTransactionRef txn, CFErrorRef *error)
720 {
721 return SOSEngineLoadCoders((SOSEngineRef)engine, txn, error);
722 }
723
724 static bool SOSEngineLoadCoders(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
725 // Read the serialized engine state from the datasource (aka keychain) and populate the in-memory engine
726 __block bool needPeerRegistration = false;
727 bool ok = true;
728 CFDataRef derCoders = NULL;
729 CFMutableDictionaryRef codersDict = NULL;
730 derCoders = SOSDataSourceCopyStateWithKey(engine->dataSource, kSOSEngineCoders, kSOSEngineProtectionDomainClassA, txn, error);
731 require_quiet(derCoders, xit);
732 codersDict = derStateToDictionaryCopy(derCoders, error);
733 require_quiet(codersDict, xit);
734
735 /*
736 * Make sure all peer have coders
737 */
738 CFDictionaryForEach(engine->peerMap, ^(const void *peerID, const void *peerState) {
739 /*
740 * Skip backup peer since they will never have coders
741 */
742 if (isString(peerID) && CFStringHasSuffix(peerID, CFSTR("-tomb"))) {
743 secnotice("coder", "Skipping coder check for peer: %@", peerID);
744 return;
745 }
746
747 CFTypeRef coderRef = CFDictionaryGetValue(codersDict, peerID);
748 if (coderRef) {
749 CFDataRef coderData = asData(coderRef, NULL);
750 if (coderData) {
751 CFErrorRef createError = NULL;
752 SOSCoderRef coder = SOSCoderCreateFromData(coderData, &createError);
753 if (coder) {
754 CFDictionaryAddValue(engine->coders, peerID, coder);
755 secnotice("coder", "adding coder: %@ for peerid: %@", coder, peerID);
756 } else {
757 secnotice("coder", "Coder for '%@' failed to create: %@", peerID, createError);
758 }
759 CFReleaseNull(createError);
760 CFReleaseNull(coder);
761 } else {
762 // Needed a coder, didn't find one, notify the account to help us out.
763 // Next attempt to sync will fix this
764 secnotice("coder", "coder for %@ was not cf data: %@", peerID, coderData);
765 needPeerRegistration = true;
766 }
767 } else{
768 secnotice("coder", "didn't find coder for peer: %@ engine dictionary: %@", peerID, codersDict);
769 needPeerRegistration = true;
770 }
771 });
772
773 secnotice("coder", "Will force peer registration: %s",needPeerRegistration ? "yes" : "no");
774
775 if (needPeerRegistration) {
776 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
777
778 dispatch_async(queue, ^{
779 CFErrorRef eprError = NULL;
780 if (!SOSCCProcessEnsurePeerRegistration_Server(&eprError)) {
781 secnotice("coder", "SOSCCProcessEnsurePeerRegistration failed with: %@", eprError);
782 }
783 CFReleaseNull(eprError);
784 });
785 }
786
787 engine->haveLoadedCoders = true;
788
789 xit:
790 CFReleaseNull(derCoders);
791 CFReleaseNull(codersDict);
792 return ok;
793 }
794 #if !TARGET_OS_SIMULATOR
795 static bool SOSEngineDeleteV0State(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
796 // SOSDataSourceDeleteStateWithKey(engine->dataSource, kSOSEngineState, kSOSEngineProtectionDomainClassD, txn, error);
797
798 // Create effectively empty state until delete is working
799 CFMutableDictionaryRef state = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
800 if (engine->myID)
801 CFDictionarySetValue(state, kSOSEngineIDKey, engine->myID);
802 CFDataRef derState = CFPropertyListCreateDERData(kCFAllocatorDefault, state, error);
803 CFReleaseNull(state);
804
805 bool ok = derState && SOSDataSourceSetStateWithKey(engine->dataSource, txn, kSOSEngineState, kSOSEngineProtectionDomainClassD, derState, error);
806 CFReleaseSafe(derState);
807 return ok;
808 }
809 #endif
810 static bool SOSEngineLoad(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
811 // Read the serialized engine state from the datasource (aka keychain) and populate the in-memory engine
812 bool ok = true;
813 CFDataRef basicEngineState = NULL;
814 CFMutableDictionaryRef engineState = NULL;
815 CFDictionaryRef manifestCache = NULL;
816 CFDictionaryRef peerStateDict = NULL;
817 CFMutableDictionaryRef codersDict = NULL;
818 // Look for the v2 engine state first
819 basicEngineState = SOSDataSourceCopyStateWithKey(engine->dataSource, kSOSEngineStatev2, kSOSEngineProtectionDomainClassD, txn, error);
820 if (basicEngineState) {
821 CFDataRef data = NULL;
822 engineState = derStateToDictionaryCopy(basicEngineState, error);
823
824 data = SOSDataSourceCopyStateWithKey(engine->dataSource, kSOSEngineManifestCache, kSOSEngineProtectionDomainClassD, txn, error);
825 manifestCache = derStateToDictionaryCopy(data, error);
826 CFReleaseNull(data);
827
828 data = SOSDataSourceCopyStateWithKey(engine->dataSource, kSOSEnginePeerStates, kSOSEngineProtectionDomainClassD, txn, error);
829 peerStateDict = derStateToDictionaryCopy(data, error);
830 CFReleaseNull(data);
831 } else {
832 // Look for original V0 engine state next
833 CFDataRef v0EngineStateData = SOSDataSourceCopyStateWithKey(engine->dataSource, kSOSEngineState, kSOSEngineProtectionDomainClassD, txn, error);
834 if (v0EngineStateData) {
835 engineState = derStateToDictionaryCopy(v0EngineStateData, error);
836 if (engineState) {
837 manifestCache = CFRetainSafe(asDictionary(CFDictionaryGetValue(engineState, kSOSEngineManifestCacheKey), NULL));
838 peerStateDict = CFRetainSafe(asDictionary(CFDictionaryGetValue(engineState, kSOSEnginePeerStateKey), NULL));
839 }
840 CFReleaseNull(v0EngineStateData);
841 }
842 secnotice("coder", "Migrating from v0 engine state; dropping coders and forcing re-negotiation");
843 SOSCCEnsurePeerRegistration();
844
845 if (engine->peerIDs) {
846 SOSCCRequestSyncWithPeersList(engine->peerIDs);
847 }
848 }
849
850 ok = engineState && SOSEngineSetStateWithDictionary(engine, engineState, error);
851
852 ok &= SOSEngineSetManifestCacheWithDictionary(engine, manifestCache, error);
853
854 ok &= peerStateDict && SOSEngineSetPeerStateWithDictionary(engine, peerStateDict, error);
855
856 CFReleaseSafe(basicEngineState);
857 CFReleaseSafe(engineState);
858 CFReleaseSafe(manifestCache);
859 CFReleaseSafe(peerStateDict);
860 CFReleaseSafe(codersDict);
861 return ok;
862 }
863
864 bool SOSTestEngineSaveWithDER(SOSEngineRef engine, CFDataRef derState, CFErrorRef *error) {
865 assert(true);
866 return true;
867 }
868
869 bool SOSTestEngineSave(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
870 bool bx = SOSEngineSave(engine, txn, error);
871 secnotice("test", "saved engine: %@", engine);
872 return bx;
873 }
874
875 bool SOSTestEngineLoad(SOSEngineRef engine, SOSTransactionRef txn, CFErrorRef *error) {
876 bool bx = SOSEngineLoad(engine, txn, error);
877 secnotice("test", "loaded engine: %@", engine);
878 return bx;
879 }
880
881 //----------------------------------------------------------------------------------------
882 // MARK: Change Trackers and Peer Manifests
883 //----------------------------------------------------------------------------------------
884
885 static SOSManifestRef SOSEngineCreateManifestWithViewNameSet_locked(SOSEngineRef engine, CFSetRef viewNameSet, CFErrorRef *error) {
886 // TODO: Potentially tell all changeTrackers to track manifests ( //forall ct do SOSChangeTrackerSetConcrete(ct, true);
887 // and read the entire dataSource and pass all objects though the filter here, instead of
888 // forcing the datasource to be able to do "smart" queries
889 return SOSDataSourceCopyManifestWithViewNameSet(engine->dataSource, viewNameSet, error);
890 }
891
892 static SOSChangeTrackerRef SOSEngineCopyChangeTrackerWithViewNameSet_locked(SOSEngineRef engine, CFSetRef viewNameSet, CFErrorRef *error) {
893 SOSChangeTrackerRef ct = (SOSChangeTrackerRef)CFDictionaryGetValue(engine->viewNameSet2ChangeTracker, viewNameSet);
894 if (!ct)
895 SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("no change tracker for view set %@"), viewNameSet);
896 return CFRetainSafe(ct);
897 }
898
899 static SOSManifestRef SOSEngineCopyManifestWithViewNameSet_locked(SOSEngineRef engine, CFSetRef viewNameSet, CFErrorRef *error) {
900 SOSChangeTrackerRef ct = SOSEngineCopyChangeTrackerWithViewNameSet_locked(engine, viewNameSet, error);
901 if (!ct)
902 return NULL;
903
904 SOSManifestRef manifest = SOSChangeTrackerCopyManifest(ct, NULL);
905 if (!manifest) {
906 manifest = SOSEngineCreateManifestWithViewNameSet_locked(engine, viewNameSet, error); // Do the SQL query
907 SOSChangeTrackerSetManifest(ct, manifest);
908 }
909 CFReleaseSafe(ct);
910 return manifest;
911 }
912
913 SOSManifestRef SOSEngineCopyLocalPeerManifest_locked(SOSEngineRef engine, SOSPeerRef peer, CFErrorRef *error) {
914 return SOSEngineCopyManifestWithViewNameSet_locked(engine, SOSPeerGetViewNameSet(peer), error);
915 }
916
917 #define withViewAndBackup(VIEW) do { with(VIEW); if (!isTomb) with(VIEW ## _tomb); } while(0)
918
919
920 // Invoke with once for each view an object is in.
921 // TODO: Move this function into the DataSource
922 static void SOSEngineObjectWithView(SOSEngineRef engine, SOSObjectRef object, void (^with)(CFStringRef view)) {
923 // Filter items into v0 only view here
924 SecDbItemRef item = (SecDbItemRef)object; // TODO: Layer violation, breaks tests
925 if (isDictionary(object)) {
926 CFTypeRef isTombValue = CFDictionaryGetValue((CFDictionaryRef)object, kSecAttrTombstone);
927 bool isTomb = isTombValue && CFBooleanGetValue(isTombValue);
928 // We are in the test just assume v0 and v2 views.
929 withViewAndBackup(kSOSViewKeychainV0);
930 } else if (SecDbItemIsSyncableOrCorrupted(item)) {
931 const SecDbClass *iclass = SecDbItemGetClass(item);
932 CFTypeRef pdmn = SecDbItemGetCachedValueWithName(item, kSecAttrAccessible);
933 if ((iclass == genp_class() || iclass == inet_class() || iclass == keys_class() || iclass == cert_class())
934 && isString(pdmn)
935 && (CFEqual(pdmn, kSecAttrAccessibleWhenUnlocked)
936 || CFEqual(pdmn, kSecAttrAccessibleAfterFirstUnlock)
937 || CFEqual(pdmn, kSecAttrAccessibleAlwaysPrivate)
938 || CFEqual(pdmn, kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
939 || CFEqual(pdmn, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
940 || CFEqual(pdmn, kSecAttrAccessibleAlwaysThisDeviceOnlyPrivate)))
941 {
942 CFTypeRef tomb = SecDbItemGetCachedValueWithName(item, kSecAttrTombstone);
943 char cvalue = 0;
944 bool isTomb = (isNumber(tomb) && CFNumberGetValue(tomb, kCFNumberCharType, &cvalue) && cvalue == 1);
945 CFStringRef viewHint = SecDbItemGetCachedValueWithName(item, kSecAttrSyncViewHint);
946
947 // check that view hint is a string, if its unset it will be kCFNull
948 if (!isString(viewHint)) {
949 viewHint = NULL;
950 }
951
952 // Intecept CKKS-handled items here and short-circuit function
953 if(SOSViewHintInCKKSSystem(viewHint)) {
954 return;
955 }
956
957 if (viewHint == NULL) {
958 if (iclass == cert_class()) {
959 withViewAndBackup(kSOSViewOtherSyncable);
960 } else {
961 if (!SecDbItemGetCachedValueWithName(item, kSecAttrTokenID)) {
962 withViewAndBackup(kSOSViewKeychainV0);
963 }
964 CFTypeRef agrp = SecDbItemGetCachedValueWithName(item, kSecAttrAccessGroup);
965 if (iclass == keys_class() && CFEqualSafe(agrp, CFSTR("com.apple.security.sos"))) {
966 withViewAndBackup(kSOSViewiCloudIdentity);
967 } else if (CFEqualSafe(agrp, CFSTR("com.apple.cfnetwork"))) {
968 withViewAndBackup(kSOSViewAutofillPasswords);
969 } else if (CFEqualSafe(agrp, CFSTR("com.apple.safari.credit-cards"))) {
970 withViewAndBackup(kSOSViewSafariCreditCards);
971 } else if (iclass == genp_class()) {
972 if (CFEqualSafe(agrp, CFSTR("apple")) &&
973 CFEqualSafe(SecDbItemGetCachedValueWithName(item, kSecAttrService), CFSTR("AirPort"))) {
974 withViewAndBackup(kSOSViewWiFi);
975 } else if (CFEqualSafe(agrp, CFSTR("com.apple.sbd"))) {
976 withViewAndBackup(kSOSViewBackupBagV0);
977 } else {
978 withViewAndBackup(kSOSViewOtherSyncable); // (genp)
979 }
980 } else {
981 withViewAndBackup(kSOSViewOtherSyncable); // (inet || keys)
982 }
983 }
984 } else {
985 with(viewHint);
986 if (!isTomb) {
987 CFStringRef viewHintTomb = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@-tomb"), viewHint);
988 if (viewHintTomb) {
989 with(viewHintTomb);
990 CFRelease(viewHintTomb);
991 }
992 }
993 }
994 }
995 } else {
996 // TODO: general queries
997 #if 0
998 SOSViewRef view;
999 CFArrayForEachC(engine->views, view) {
1000 bool inView = SOSViewQueryMatchItem(view, item);
1001 if (inView) {
1002 CFStringRef viewName = SOSViewCopyName(view);
1003 with(viewName);
1004 CFReleaseSafe(viewName);
1005 }
1006 }
1007 #endif
1008 }
1009 }
1010
1011 //
1012 // Deliver delayed notifiations of changes in keychain
1013 //
1014
1015 static void
1016 SOSSendViewNotification(CFSetRef viewNotifications)
1017 {
1018 CFNotificationCenterRef center = CFNotificationCenterGetDarwinNotifyCenter();
1019
1020 CFSetForEach(viewNotifications, ^(const void *value) {
1021 secinfo("view", "Sending view notification for view %@", value);
1022
1023 CFStringRef str = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.security.view-change.%@"), value);
1024 if (str == NULL)
1025 return;
1026
1027 CFNotificationCenterPostNotificationWithOptions(center, str, NULL, NULL, 0);
1028 CFRelease(str);
1029
1030 });
1031 }
1032
1033 static void
1034 SOSArmViewNotificationEvents(CFSetRef viewNotifications)
1035 {
1036 static CFMutableSetRef pendingViewNotifications;
1037 static dispatch_once_t onceToken;
1038 static dispatch_queue_t queue;
1039
1040 dispatch_once(&onceToken, ^{
1041 queue = dispatch_queue_create("ViewNotificationQueue", NULL);
1042 });
1043 if (queue == NULL || CFSetGetCount(viewNotifications) == 0)
1044 return;
1045
1046 /*
1047 * PendingViewNotifications is only modified on queue.
1048 * PendingViewNotifications is used as a signal if a timer is running.
1049 *
1050 * If a timer is running, new events are just added to the existing
1051 * pendingViewNotifications.
1052 */
1053
1054 #define DELAY_OF_NOTIFICATION_IN_NS (NSEC_PER_SEC)
1055
1056 CFRetain(viewNotifications);
1057
1058 dispatch_async(queue, ^{
1059 if (pendingViewNotifications == NULL) {
1060 pendingViewNotifications = CFSetCreateMutableCopy(NULL, 0, viewNotifications);
1061
1062 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)DELAY_OF_NOTIFICATION_IN_NS), queue, ^{
1063 SOSSendViewNotification(pendingViewNotifications);
1064
1065 // when timer hits, clear out set of modified views
1066 CFRelease(pendingViewNotifications);
1067 pendingViewNotifications = NULL;
1068 });
1069 } else {
1070 CFSetUnion(pendingViewNotifications, viewNotifications);
1071 }
1072 CFRelease(viewNotifications);
1073 });
1074 }
1075
1076
1077 //
1078 // SOSChangeMapper - Helper for SOSEngineUpdateChanges_locked
1079 //
1080 struct SOSChangeMapper {
1081 SOSEngineRef engine;
1082 SOSTransactionRef txn;
1083 SOSDataSourceTransactionPhase phase;
1084 SOSDataSourceTransactionSource source;
1085 CFMutableDictionaryRef ct2changes;
1086 CFMutableSetRef viewNotifications;
1087 };
1088
1089 static void SOSChangeMapperInit(struct SOSChangeMapper *cm, SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionPhase phase, SOSDataSourceTransactionSource source) {
1090 cm->engine = engine;
1091 cm->txn = txn;
1092 cm->phase = phase;
1093 cm->source = source;
1094 cm->ct2changes = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1095 cm->viewNotifications = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
1096 }
1097
1098 static void SOSChangeMapperSendNotifications(struct SOSChangeMapper *cm)
1099 {
1100 SOSArmViewNotificationEvents(cm->viewNotifications);
1101 }
1102
1103 static void SOSChangeMapperFree(struct SOSChangeMapper *cm) {
1104 CFReleaseSafe(cm->ct2changes);
1105 CFReleaseSafe(cm->viewNotifications);
1106 }
1107
1108 static void SOSChangeMapperAddViewNotification(struct SOSChangeMapper *cm, CFStringRef view)
1109 {
1110 assert(isString(view));
1111
1112 // aggregate the PCS view into one notification
1113 if (CFStringHasPrefix(view, CFSTR("PCS-"))) {
1114 view = CFSTR("PCS");
1115 }
1116 CFSetSetValue(cm->viewNotifications, view);
1117 }
1118
1119 static void SOSChangeMapperAppendObject(struct SOSChangeMapper *cm, SOSChangeTrackerRef ct, bool isAdd, CFTypeRef object) {
1120 CFMutableArrayRef changes = (CFMutableArrayRef)CFDictionaryGetValue(cm->ct2changes, ct);
1121 if (!changes) {
1122 changes = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1123 CFDictionarySetValue(cm->ct2changes, ct, changes);
1124 CFReleaseSafe(changes);
1125 }
1126 isAdd ? SOSChangesAppendAdd(changes, object) : SOSChangesAppendDelete(changes, object);
1127 }
1128
1129 static bool SOSChangeMapperIngestChange(struct SOSChangeMapper *cm, bool isAdd, CFTypeRef change) {
1130 bool someoneCares = false;
1131 if (isData(change)) {
1132 // TODO: Reenable assertion once the tests have been updated
1133 //assert(!isAdd);
1134 // We got a digest for a deleted object. Our dataSource probably couldn't find
1135 // an object with this digest, probably because it went missing, or it was
1136 // discovered to be corrupted.
1137 // Tell all our changeTrackers about this digest since we don't know who might need it.
1138 CFDictionaryForEach(cm->engine->viewNameSet2ChangeTracker, ^(const void *viewNameSet, const void *ct) {
1139 SOSChangeMapperAppendObject(cm, (SOSChangeTrackerRef)ct, isAdd, change);
1140 });
1141 someoneCares = CFDictionaryGetCount(cm->engine->viewNameSet2ChangeTracker);
1142 } else {
1143 // We got an object let's figure out which views it's in and schedule it for
1144 // delivery to all changeTrackers interested in any of those views.
1145 SOSObjectRef object = (SOSObjectRef)change;
1146 CFMutableSetRef changeTrackerSet = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
1147 // First gather all the changeTrackers interested in this object (eliminating dupes by collecting them in a set)
1148 SOSEngineObjectWithView(cm->engine, object, ^(CFStringRef viewName) {
1149 const void *ctorset = CFDictionaryGetValue(cm->engine->viewName2ChangeTracker, viewName);
1150 if (isSet(ctorset)) {
1151 CFSetForEach((CFSetRef)ctorset, ^(const void *ct) { CFSetAddValue(changeTrackerSet, ct); });
1152 } else if (ctorset) {
1153 CFSetAddValue(changeTrackerSet, ctorset);
1154 }
1155
1156
1157 SOSChangeMapperAddViewNotification(cm, viewName);
1158 });
1159 // Then append the object to the changes array in the ct2changes dictionary keyed by viewSet
1160 CFSetForEach(changeTrackerSet, ^(const void *ct) {
1161 SOSChangeMapperAppendObject(cm, (SOSChangeTrackerRef)ct, isAdd, object);
1162 });
1163 someoneCares = CFSetGetCount(changeTrackerSet);
1164 CFReleaseSafe(changeTrackerSet);
1165 }
1166 return someoneCares;
1167 }
1168
1169 static bool SOSChangeMapperSend(struct SOSChangeMapper *cm, CFErrorRef *error) {
1170 __block bool ok = true;
1171 CFDictionaryForEach(cm->ct2changes, ^(const void *ct, const void *changes) {
1172 ok &= SOSChangeTrackerTrackChanges((SOSChangeTrackerRef)ct, cm->engine, cm->txn, cm->source, cm->phase, (CFArrayRef)changes, error);
1173 });
1174 return ok;
1175 }
1176
1177 static bool SOSEngineUpdateChanges_locked(SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionPhase phase, SOSDataSourceTransactionSource source, CFArrayRef changes, CFErrorRef *error)
1178 {
1179 secnoticeq("engine", "%@: %s %s %ld changes, txn=%@, %p", engine->myID, phase == kSOSDataSourceTransactionWillCommit ? "will-commit" : phase == kSOSDataSourceTransactionDidCommit ? "did-commit" : "did-rollback",
1180 source == kSOSDataSourceSOSTransaction ? "sos" :
1181 source == kSOSDataSourceCKKSTransaction ? "ckks" :
1182 source == kSOSDataSourceAPITransaction ? "api" :
1183 "unknown",
1184 CFArrayGetCount(changes), txn, txn);
1185 bool ok = true;
1186 switch (phase) {
1187 case kSOSDataSourceTransactionDidRollback:
1188 ok &= SOSEngineLoad(engine, txn, error);
1189 break;
1190 case kSOSDataSourceTransactionDidCommit: // Corruption causes us to process items at DidCommit
1191 case kSOSDataSourceTransactionWillCommit:
1192 {
1193 bool mappedItemChanged = false;
1194
1195 struct SOSChangeMapper cm;
1196 SOSChangeMapperInit(&cm, engine, txn, phase, source);
1197 SecDbEventRef event;
1198 CFArrayForEachC(changes, event) {
1199 CFTypeRef deleted = NULL;
1200 CFTypeRef inserted = NULL;
1201 SecDbEventGetComponents(event, &deleted, &inserted, error);
1202 if (deleted) {
1203 bool someoneCares = SOSChangeMapperIngestChange(&cm, false, deleted);
1204 if (someoneCares) {
1205 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
1206 SecADAddValueForScalarKey(CFSTR("com.apple.security.sos.delete"), 1);
1207 #endif
1208 mappedItemChanged = true;
1209 }
1210 }
1211 if (inserted) {
1212 bool someoneCares = SOSChangeMapperIngestChange(&cm, true, inserted);
1213 if (someoneCares) {
1214 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
1215 if (deleted == NULL) {
1216 SecADAddValueForScalarKey(CFSTR("com.apple.security.sos.add"), 1);
1217 } else {
1218 SecADAddValueForScalarKey(CFSTR("com.apple.security.sos.update"), 1);
1219 }
1220 #endif
1221 mappedItemChanged = true;
1222 }
1223 if (!someoneCares && !isData(inserted) && SecDbItemIsTombstone((SecDbItemRef)inserted) && !CFEqualSafe(SecDbItemGetValue((SecDbItemRef)inserted, &v7utomb, NULL), kCFBooleanTrue)) {
1224 CFErrorRef localError = NULL;
1225 // A tombstone was inserted but there is no changetracker that
1226 // cares about it.
1227 if (!SecDbItemDoDeleteSilently((SecDbItemRef)inserted, (SecDbConnectionRef)txn, &localError)) {
1228 secerror("failed to delete tombstone %@ that no one cares about: %@", inserted, localError);
1229 CFReleaseNull(localError);
1230 }
1231 }
1232 }
1233 }
1234
1235 ok &= SOSChangeMapperSend(&cm, error);
1236 SOSChangeMapperSendNotifications(&cm); // Trigger notifications for view that changes changed
1237 SOSChangeMapperFree(&cm);
1238
1239 if (ok && phase == kSOSDataSourceTransactionWillCommit) {
1240 // Only consider writing if we're in the WillCommit phase.
1241 // DidCommit phases happen outside the database lock and
1242 // writing to the DBConn will cause deadlocks.
1243 if (mappedItemChanged || source == kSOSDataSourceSOSTransaction) {
1244 // Write SOSEngine and SOSPeer state to disk
1245 #if OCTAGON
1246 if(!SecCKKSTestDisableSOS()) {
1247 #endif
1248 secnotice("engine", "saving engine state");
1249 ok &= SOSEngineSave(engine, txn, error);
1250
1251 if (kSOSDataSourceAPITransaction == source || kSOSDataSourceCKKSTransaction == source)
1252 SOSCCRequestSyncWithPeersList(engine->peerIDs);
1253 #if OCTAGON
1254 }
1255 #endif
1256 } else {
1257 secinfo("engine", "Not saving engine state, nothing changed.");
1258 }
1259 }
1260
1261 break;
1262 }
1263 }
1264 return ok;
1265 }
1266
1267 static void SOSEngineSetNotifyPhaseBlock(SOSEngineRef engine) {
1268 SOSDataSourceAddNotifyPhaseBlock(engine->dataSource, ^(SOSDataSourceRef ds, SOSTransactionRef txn, SOSDataSourceTransactionPhase phase, SOSDataSourceTransactionSource source, CFArrayRef changes) {
1269 dispatch_sync(engine->queue, ^{
1270 CFErrorRef localError = NULL;
1271 if (!SOSEngineUpdateChanges_locked(engine, txn, phase, source, changes, &localError)) {
1272 secerror("updateChanged failed: %@", localError);
1273 }
1274 CFReleaseSafe(localError);
1275 });
1276 });
1277 }
1278
1279 #if 0 // TODO: update these checks
1280 static void SOSEngineCircleChanged_sanitycheck(SOSEngineRef engine, CFStringRef myPeerID, CFArrayRef trustedPeers, CFArrayRef untrustedPeers) {
1281 // Logging code
1282 CFMutableArrayRef addedPeers = CFArrayCreateDifference(kCFAllocatorDefault, trustedPeers, engine->peerIDs);
1283 CFMutableArrayRef deletedPeers = CFArrayCreateDifference(kCFAllocatorDefault, engine->peerIDs, trustedPeers);
1284 CFMutableArrayRef addedUntrustedPeers = CFArrayCreateDifference(kCFAllocatorDefault, untrustedPeers, engine->peerIDs);
1285 CFMutableArrayRef deletedUntrustedPeers = CFArrayCreateDifference(kCFAllocatorDefault, engine->peerIDs, untrustedPeers);
1286
1287 CFStringRef tpDesc = SOSPeerIDArrayCreateString(trustedPeers);
1288 CFStringRef apDesc = SOSPeerIDArrayCreateString(addedPeers);
1289 CFStringRef dpDesc = SOSPeerIDArrayCreateString(deletedPeers);
1290 CFStringRef aupDesc = SOSPeerIDArrayCreateString(addedUntrustedPeers);
1291 CFStringRef dupDesc = SOSPeerIDArrayCreateString(deletedUntrustedPeers);
1292 secnotice("engine", "trusted %@ added %@ removed %@ add ut: %@ rem ut: %@", tpDesc, apDesc, dpDesc, aupDesc, dupDesc);
1293 CFReleaseSafe(dupDesc);
1294 CFReleaseSafe(aupDesc);
1295 CFReleaseSafe(dpDesc);
1296 CFReleaseSafe(apDesc);
1297 CFReleaseSafe(tpDesc);
1298
1299 // Assertions:
1300 // Ensure SOSAccount isn't giving us the runaround.
1301 // Assert that trustedPeers, untrustedPeers and myPeerId are disjoint sets
1302 if (trustedPeers) {
1303 CFMutableArrayRef allTrustedPeers = CFArrayCreateDifference(kCFAllocatorDefault, trustedPeers, untrustedPeers);
1304 assert(CFEqual(trustedPeers, allTrustedPeers));
1305 CFReleaseSafe(allTrustedPeers);
1306 assert(!CFArrayContainsValue(trustedPeers, CFRangeMake(0, CFArrayGetCount(trustedPeers)), myPeerID));
1307 }
1308 if (untrustedPeers) {
1309 CFMutableArrayRef allUntrustedPeers = CFArrayCreateDifference(kCFAllocatorDefault, untrustedPeers, trustedPeers);
1310 assert(CFEqual(untrustedPeers, allUntrustedPeers));
1311 CFReleaseSafe(allUntrustedPeers);
1312 assert(!CFArrayContainsValue(untrustedPeers, CFRangeMake(0, CFArrayGetCount(trustedPeers)), myPeerID));
1313 }
1314
1315 CFReleaseNull(deletedUntrustedPeers);
1316 CFReleaseNull(addedUntrustedPeers);
1317 CFReleaseNull(deletedPeers);
1318 CFReleaseNull(addedPeers);
1319
1320 // End of logging and asertions, actual code here.
1321 }
1322 #endif
1323
1324 static SOSChangeTrackerRef SOSReferenceAndGetChangeTracker(CFDictionaryRef lookup, CFMutableDictionaryRef referenced, CFSetRef viewNameSet) {
1325 SOSChangeTrackerRef ct = (SOSChangeTrackerRef)CFDictionaryGetValue(referenced, viewNameSet);
1326 if (!ct) {
1327 ct = (SOSChangeTrackerRef)CFDictionaryGetValue(lookup, viewNameSet);
1328 if (ct) {
1329 SOSChangeTrackerResetRegistration(ct);
1330 CFDictionarySetValue(referenced, viewNameSet, ct);
1331 } else {
1332 ct = SOSChangeTrackerCreate(kCFAllocatorDefault, false, NULL, NULL);
1333 CFDictionarySetValue(referenced, viewNameSet, ct);
1334 CFReleaseSafe(ct);
1335 }
1336 }
1337 return ct;
1338 }
1339
1340 static void CFStringAppendPeerIDAndViews(CFMutableStringRef desc, CFStringRef peerID, CFSetRef vns) {
1341 CFStringSetPerformWithDescription(vns, ^(CFStringRef description) {
1342 CFStringAppendFormat(desc, NULL, CFSTR(" %@ (%@)"), peerID, description);
1343 });
1344 }
1345
1346 // Must be called after updating viewNameSet2ChangeTracker
1347 static void SOSEngineUpdateViewName2ChangeTracker(SOSEngineRef engine) {
1348 // Create the mapping from viewName -> ChangeTracker used for lookup during change notification
1349 CFMutableDictionaryRef newViewName2ChangeTracker = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1350 CFDictionaryForEach(engine->viewNameSet2ChangeTracker, ^(const void *viewNameSet, const void *ct) {
1351 CFSetForEach(viewNameSet, ^(const void *viewName) {
1352 const void *ctorset = NULL;
1353 if (CFDictionaryGetValueIfPresent(newViewName2ChangeTracker, viewName, &ctorset)) {
1354 if (isSet(ctorset)) {
1355 CFSetAddValue((CFMutableSetRef)ctorset, ct);
1356 } else if (!CFEqual(ct, ctorset)) {
1357 CFMutableSetRef set = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
1358 CFSetAddValue(set, ctorset);
1359 CFSetAddValue(set, ct);
1360 CFDictionaryReplaceValue(newViewName2ChangeTracker, viewName, set);
1361 CFRelease(set);
1362 }
1363 } else {
1364 CFDictionarySetValue(newViewName2ChangeTracker, viewName, ct);
1365 }
1366 });
1367 });
1368 CFAssignRetained(engine->viewName2ChangeTracker, newViewName2ChangeTracker);
1369 }
1370
1371 static void SOSEngineSetBackupBag(SOSEngineRef engine, SOSObjectRef bagItem);
1372
1373 // This is called only if we are in a circle and we should listen for keybag changes
1374 static void SOSEngineRegisterBackupBagV0Tracker(SOSEngineRef engine, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableStringRef desc) {
1375 SOSChangeTrackerRef bbct = SOSReferenceAndGetChangeTracker(engine->viewNameSet2ChangeTracker, newViewNameSet2ChangeTracker, SOSViewsGetV0BackupBagViewSet());
1376 SOSChangeTrackerRegisterChangeUpdate(bbct, ^bool(SOSChangeTrackerRef ct, SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionSource source, SOSDataSourceTransactionPhase phase, CFArrayRef changes, CFErrorRef *error) {
1377 SOSChangeRef change;
1378 CFArrayForEachC(changes, change) {
1379 CFTypeRef object = NULL;
1380 bool isAdd = SOSChangeGetObject(change, &object);
1381 SecDbItemRef dbi = (SecDbItemRef)object;
1382 if (!isData(object) &&
1383 CFEqualSafe(SecDbItemGetCachedValueWithName(dbi, kSecAttrService), CFSTR("SecureBackupService")) &&
1384 CFEqualSafe(SecDbItemGetCachedValueWithName(dbi, kSecAttrAccessible), kSecAttrAccessibleWhenUnlocked) &&
1385 CFEqualSafe(SecDbItemGetCachedValueWithName(dbi, kSecAttrAccount), CFSTR("SecureBackupPublicKeybag"))) {
1386 SOSEngineSetBackupBag(engine, isAdd ? (SOSObjectRef)object : NULL);
1387 }
1388 }
1389 return true;
1390 });
1391 }
1392
1393 static void SOSEngineReferenceBackupPeer(SOSEngineRef engine, CFStringRef peerID, CFSetRef viewNameSet, CFDataRef keyBag, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableDictionaryRef newPeerMap) {
1394 CFTypeRef oldEntry = CFDictionaryGetValue(engine->peerMap, peerID);
1395 CFTypeRef newEntry = SOSPeerOrStateSetViewsKeyBagAndCreateCopy(oldEntry, viewNameSet, keyBag);
1396 if (newEntry) {
1397 if (isDictionary(newEntry)) {
1398 // Backup peers, are always inflated
1399 CFAssignRetained(newEntry, SOSPeerCreateWithState(engine, peerID, newEntry, NULL));
1400 // If !oldEntry this is an edge (first creation of a peer).
1401 if (!oldEntry) {
1402 SOSPeerKeyBagDidChange((SOSPeerRef)newEntry);
1403 }
1404 }
1405 CFDictionarySetValue(newPeerMap, peerID, newEntry);
1406 CFRelease(newEntry);
1407
1408 if (keyBag) {
1409 SOSChangeTrackerRef ct = SOSReferenceAndGetChangeTracker(engine->viewNameSet2ChangeTracker, newViewNameSet2ChangeTracker, viewNameSet);
1410
1411 SOSChangeTrackerUpdatesChanges child = Block_copy(^bool(SOSChangeTrackerRef ct, SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionSource source, SOSDataSourceTransactionPhase phase, CFArrayRef changes, CFErrorRef *error) {
1412 return SOSPeerDataSourceWillChange((SOSPeerRef)newEntry, SOSEngineGetDataSource(engine), source, changes, error);
1413 });
1414
1415 SOSChangeTrackerRegisterChangeUpdate(ct, child);
1416 Block_release(child);
1417 }
1418 }
1419 }
1420
1421 static void SOSEngineReferenceSyncPeer(SOSEngineRef engine, CFStringRef peerID, CFSetRef viewNameSet, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableDictionaryRef newPeerMap) {
1422 CFTypeRef newEntry = SOSPeerOrStateSetViewsKeyBagAndCreateCopy(CFDictionaryGetValue(engine->peerMap, peerID), viewNameSet, NULL);
1423 if (newEntry) {
1424 SOSChangeTrackerRef ct = SOSReferenceAndGetChangeTracker(engine->viewNameSet2ChangeTracker, newViewNameSet2ChangeTracker, viewNameSet);
1425 // Standard peer, inflated on demand
1426 SOSChangeTrackerUpdatesManifests trackManifest;
1427 if (isDictionary(newEntry)) {
1428 // Uninflated peer, inflate on first notification.
1429 trackManifest = ^bool(SOSChangeTrackerRef ct, SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionSource source, SOSDataSourceTransactionPhase phase, SOSManifestRef removals, SOSManifestRef additions, CFErrorRef *error) {
1430 CFErrorRef localError = NULL;
1431 SOSPeerRef peer = SOSEngineCopyPeerWithID_locked(engine, peerID, &localError);
1432 bool ok;
1433 if (!peer) {
1434 secerror("%@: peer failed to inflate: %@", peerID, localError);
1435 CFReleaseSafe(localError);
1436 ok = false;
1437 } else {
1438 ok = SOSPeerDataSourceWillCommit(peer, source, removals, additions, error);
1439 }
1440 CFReleaseSafe(peer);
1441 return ok;
1442 };
1443 } else {
1444 // Inflated peer, just forward the changes to the peer
1445 trackManifest = ^bool(SOSChangeTrackerRef ct, SOSEngineRef engine, SOSTransactionRef txn, SOSDataSourceTransactionSource source, SOSDataSourceTransactionPhase phase, SOSManifestRef removals, SOSManifestRef additions, CFErrorRef *error) {
1446 return SOSPeerDataSourceWillCommit((SOSPeerRef)newEntry, source, removals, additions, error);
1447 };
1448 }
1449 SOSChangeTrackerUpdatesManifests trackManifestCopy = Block_copy(trackManifest);
1450 SOSChangeTrackerRegisterManifestUpdate(ct, trackManifestCopy);
1451 Block_release(trackManifestCopy);
1452
1453 CFDictionarySetValue(newPeerMap, peerID, newEntry);
1454 CFRelease(newEntry);
1455 }
1456 }
1457
1458
1459 static void SOSEngineReferenceTrustedPeer(SOSEngineRef engine, SOSPeerMetaRef peerMeta, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableDictionaryRef newPeerMap, CFMutableArrayRef peerIDs, CFMutableStringRef desc) {
1460 CFSetRef viewNameSet = NULL;
1461 CFDataRef keyBag = NULL;
1462 CFStringRef peerID = SOSPeerMetaGetComponents(peerMeta, &viewNameSet, &keyBag, NULL);
1463 // We trust peerID so append it to peerIDs
1464 CFArrayAppendValue(peerIDs, peerID);
1465 if (desc) CFStringAppendPeerIDAndViews(desc, peerID, viewNameSet);
1466 // Update the viewNameSet for this peer, to appease tests, default to a viewset of the V0 view.
1467 if (!viewNameSet)
1468 viewNameSet = SOSViewsGetV0ViewSet();
1469
1470 // Always inflate backup peers, since they need to register with their changeTrackers right away.
1471 if (keyBag) {
1472 SOSEngineReferenceBackupPeer(engine, peerID, viewNameSet, keyBag, newViewNameSet2ChangeTracker, newPeerMap);
1473 } else {
1474 SOSEngineReferenceSyncPeer(engine, peerID, viewNameSet, newViewNameSet2ChangeTracker, newPeerMap);
1475 }
1476 }
1477
1478 static CFDataRef SOSEngineCopyV0KeyBag(SOSEngineRef engine, CFErrorRef *error) {
1479 // Return the keybag for the given peerID.
1480 /*
1481 Values for V0 are:
1482 kSecAttrAccessGroup ==> CFSTR("com.apple.sbd")
1483 kSecAttrAccessible ==> kSecAttrAccessibleWhenUnlocked
1484 kSecAttrAccount ==> CFSTR("SecureBackupPublicKeybag")
1485 kSecAttrService ==> CFSTR("SecureBackupService")
1486 */
1487
1488 CFMutableDictionaryRef keys = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
1489 kSecAttrAccessGroup, CFSTR("com.apple.sbd"),
1490 kSecAttrAccount, CFSTR("SecureBackupPublicKeybag"),
1491 kSecAttrService, CFSTR("SecureBackupService"),
1492 kSecAttrAccessible, kSecAttrAccessibleWhenUnlocked,
1493 kSecAttrSynchronizable, kCFBooleanTrue,
1494 NULL);
1495
1496 CFDataRef keybag = engine->dataSource->dsCopyItemDataWithKeys(engine->dataSource, keys, error);
1497 CFReleaseSafe(keys);
1498
1499 return keybag;
1500 }
1501
1502 static void SOSEngineReferenceBackupV0Peer(SOSEngineRef engine, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableDictionaryRef newPeerMap, CFMutableArrayRef newPeerIDs, CFMutableStringRef desc) {
1503 SOSPeerRef backupPeer = (SOSPeerRef)CFDictionaryGetValue(engine->peerMap, kSOSViewKeychainV0_tomb);
1504 CFDataRef bag = NULL;
1505 if (backupPeer && CFGetTypeID(backupPeer) == SOSPeerGetTypeID()) {
1506 bag = CFRetainSafe(SOSPeerGetKeyBag(backupPeer));
1507 } else {
1508 CFErrorRef localError = NULL;
1509 bag = SOSEngineCopyV0KeyBag(engine, &localError);
1510 if (!bag) {
1511 secnotice("engine", "No keybag found for v0 backup peer: %@", localError);
1512 CFReleaseSafe(localError);
1513 }
1514 }
1515 SOSEngineReferenceBackupPeer(engine, kSOSViewKeychainV0_tomb, SOSViewsGetV0BackupViewSet(), bag, newViewNameSet2ChangeTracker, newPeerMap);
1516 CFReleaseNull(bag);
1517 }
1518
1519 static void SOSEngineReferenceTrustedPeers(SOSEngineRef engine, CFMutableDictionaryRef newViewNameSet2ChangeTracker, CFMutableDictionaryRef newPeerMap, CFMutableArrayRef newPeerIDs, CFArrayRef trustedPeerMetas, CFMutableStringRef desc) {
1520 // Then update the views for all trusted peers and add them to newPeerMap.
1521 if (trustedPeerMetas != NULL && CFArrayGetCount(trustedPeerMetas) != 0) {
1522 if (desc) CFStringAppend(desc, CFSTR(" trusted"));
1523 // Remake engine->peerIDs
1524 SOSPeerMetaRef peerMeta;
1525 CFArrayForEachC(trustedPeerMetas, peerMeta) {
1526 SOSEngineReferenceTrustedPeer(engine, peerMeta, newViewNameSet2ChangeTracker, newPeerMap, newPeerIDs, desc);
1527 }
1528 }
1529 }
1530
1531 static void SOSEngineReferenceUntrustedPeers(SOSEngineRef engine, CFMutableDictionaryRef newPeerMap, CFArrayRef untrustedPeerMetas, CFMutableStringRef description) {
1532 // Copy any untrustedPeers to newPeerMap as well if we have a state
1533 // for them, if not no big deal. We also serialize all the untrustedPeers
1534 // since they don't need to be deserializable
1535 if (untrustedPeerMetas != NULL && CFArrayGetCount(untrustedPeerMetas) != 0) {
1536 if (description) CFStringAppend(description, CFSTR(" untrusted"));
1537 SOSPeerMetaRef peerMeta;
1538 CFArrayForEachC(untrustedPeerMetas, peerMeta) {
1539 CFSetRef views = NULL;
1540 CFStringRef peerID = SOSPeerMetaGetComponents(peerMeta, &views, NULL, NULL);
1541 if (description) CFStringAppendPeerIDAndViews(description, peerID, views);
1542 CFSetRef nviews = NULL;
1543 if (!views)
1544 views = nviews = CFSetCreate(kCFAllocatorDefault, NULL, 0, &kCFTypeSetCallBacks);
1545 CFTypeRef newEntry = SOSPeerOrStateSetViewsAndCopyState(CFDictionaryGetValue(engine->peerMap, peerID), views);
1546 CFReleaseSafe(nviews);
1547 if (newEntry) {
1548 CFDictionarySetValue(newPeerMap, peerID, newEntry);
1549 CFReleaseSafe(newEntry);
1550 }
1551 }
1552 }
1553 }
1554
1555 static void SOSEngineReferenceChangeTrackers(SOSEngineRef engine, CFArrayRef trustedPeerMetas, CFArrayRef untrustedPeerMetas, CFMutableStringRef desc) {
1556 CFMutableArrayRef newPeerIDs = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1557 CFMutableDictionaryRef newPeerMap = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1558 CFMutableDictionaryRef newViewNameSet2ChangeTracker = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1559
1560 if (engine->myID) {
1561 // We have an engineID => in a circle (with 0 or more peers)
1562 // Ensure we have a v0 backup peer and it's listening for backup bag changes
1563 SOSEngineReferenceBackupV0Peer(engine, newViewNameSet2ChangeTracker, newPeerMap, newPeerIDs, desc);
1564 SOSEngineRegisterBackupBagV0Tracker(engine, newViewNameSet2ChangeTracker, desc);
1565 }
1566 SOSEngineReferenceTrustedPeers(engine, newViewNameSet2ChangeTracker, newPeerMap, newPeerIDs, trustedPeerMetas, desc);
1567 SOSEngineReferenceUntrustedPeers(engine, newPeerMap, untrustedPeerMetas, desc);
1568
1569 CFAssignRetained(engine->peerIDs, newPeerIDs);
1570 CFAssignRetained(engine->peerMap, newPeerMap);
1571 CFAssignRetained(engine->viewNameSet2ChangeTracker, newViewNameSet2ChangeTracker);
1572 SOSEngineUpdateViewName2ChangeTracker(engine);
1573 }
1574
1575 // Return true iff peers or views changed
1576 static bool SOSEngineSetPeers_locked(SOSEngineRef engine, SOSPeerMetaRef myPeerMeta, CFArrayRef trustedPeerMetas, CFArrayRef untrustedPeerMetas) {
1577 CFErrorRef error = NULL;
1578 CFSetRef myViews = NULL;
1579 CFDataRef myKeyBag = NULL;
1580 CFMutableStringRef desc = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("me"));
1581 CFStringRef myPeerID = myPeerMeta ? SOSPeerMetaGetComponents(myPeerMeta, &myViews, &myKeyBag, &error) : NULL;
1582 if (desc) CFStringAppendPeerIDAndViews(desc, myPeerID, myViews);
1583
1584 // Start with no coders
1585 CFMutableDictionaryRef codersToKeep = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1586
1587 if(engine->haveLoadedCoders){
1588 // If we're the same peerID we keep known peers (both trusted and untrusted)
1589 if (CFEqualSafe(myPeerID, engine->myID)) {
1590 void (^copyPeerMetasCoder)(const void *value) = ^(const void*element) {
1591 SOSPeerMetaRef peerMeta = (SOSPeerMetaRef) element;
1592
1593 CFStringRef currentID = SOSPeerMetaGetComponents(peerMeta, NULL, NULL, NULL);
1594 if (currentID) {
1595 SOSCoderRef coder = (SOSCoderRef) CFDictionaryGetValue(engine->coders, currentID);
1596 if (coder) {
1597 CFDictionarySetValue(codersToKeep, currentID, coder);
1598 }
1599 }
1600 };
1601
1602 if (trustedPeerMetas) {
1603 CFArrayForEach(trustedPeerMetas, copyPeerMetasCoder);
1604 }
1605 if (untrustedPeerMetas) {
1606 CFArrayForEach(untrustedPeerMetas, copyPeerMetasCoder);
1607 }
1608 }
1609
1610 engine->codersNeedSaving = true;
1611 }
1612 CFRetainAssign(engine->myID, myPeerID);
1613 CFTransferRetained(engine->coders, codersToKeep);
1614
1615 // Remake engine->peerMap from both trusted and untrusted peers
1616 SOSEngineReferenceChangeTrackers(engine, trustedPeerMetas, untrustedPeerMetas, desc);
1617
1618 secnotice("engine", "%@", desc);
1619 CFReleaseSafe(desc);
1620 return true;
1621 }
1622
1623 static void SOSEngineApplyPeerState(SOSEngineRef engine, CFDictionaryRef peerStateMap) {
1624 if (peerStateMap) CFDictionaryForEach(peerStateMap, ^(const void *peerID, const void *peerState) {
1625 CFTypeRef mapEntry = CFDictionaryGetValue(engine->peerMap, peerID);
1626 if (mapEntry && CFGetTypeID(mapEntry) == SOSPeerGetTypeID()) {
1627 // Update the state of any already inflated peers
1628 SOSPeerRef peer = (SOSPeerRef)mapEntry;
1629 CFErrorRef localError = NULL;
1630 if (!SOSPeerSetState(peer, engine, peerState, &localError)) {
1631 CFStringRef stateHex = NULL;
1632 stateHex = CFDataCopyHexString(peerState);
1633 secerror("peer: %@: bad state: %@ in engine state: %@", peerID, localError, stateHex);
1634 CFReleaseSafe(stateHex);
1635 CFReleaseNull(localError);
1636 // Possibly ask for an ensurePeerRegistration so we have a good list of peers again.
1637 }
1638 } else {
1639 // Just record the state for non inflated peers for now.
1640 CFDictionarySetValue(engine->peerMap, peerID, peerState);
1641 }
1642 });
1643 }
1644
1645 static void SOSEngineSynthesizePeerMetas(SOSEngineRef engine, CFMutableArrayRef trustedPeersMetas, CFMutableArrayRef untrustedPeers) {
1646 CFSetRef trustedPeerSet = engine->peerIDs ? CFSetCreateCopyOfArrayForCFTypes(engine->peerIDs) : NULL;
1647 CFDictionaryForEach(engine->peerMap, ^(const void *peerID, const void *peerState) {
1648 SOSPeerMetaRef meta = NULL;
1649 if (peerState && CFGetTypeID(peerState) == SOSPeerGetTypeID()) {
1650 SOSPeerRef peer = (SOSPeerRef)peerState;
1651 meta = SOSPeerMetaCreateWithComponents(peerID, SOSPeerGetViewNameSet(peer), SOSPeerGetKeyBag(peer));
1652 } else {
1653 // We don't need to add the meta for the backup case, since
1654 // SOSEngineReferenceBackupV0Peer will do the right thing
1655 if (!CFEqualSafe(peerID, kSOSViewKeychainV0_tomb)) {
1656 meta = SOSPeerMetaCreateWithState(peerID, peerState);
1657 }
1658 }
1659 // Any peer in peerStateMap that is not in trustedPeers is an untrustedPeer unless it's the v0 backup peer
1660 if ((trustedPeerSet && CFSetContainsValue(trustedPeerSet, peerID)) || CFEqualSafe(peerID, kSOSViewKeychainV0_tomb)) {
1661 if (meta) {
1662 CFArrayAppendValue(trustedPeersMetas, meta);
1663 }
1664 } else {
1665 CFArrayAppendValue(untrustedPeers, peerID);
1666 }
1667 CFReleaseNull(meta);
1668 });
1669 CFReleaseNull(trustedPeerSet);
1670 }
1671
1672 static void SOSEngineSetBackupBag(SOSEngineRef engine, SOSObjectRef bagItem) {
1673 CFMutableStringRef desc = NULL;
1674 SOSPeerRef backupPeer = SOSEngineCopyPeerWithID_locked(engine, kSOSViewKeychainV0_tomb, NULL);
1675 CFDataRef keybag = NULL;
1676 if (bagItem) {
1677 keybag = SecDbItemGetValue((SecDbItemRef)bagItem, &v6v_Data, NULL);
1678 }
1679
1680 // Since SOSPeerSetKeyBag() doesn't notify on the edge from NULL->initial keybag, since
1681 // that is the right behaviour for non v0 backup peers, we need to do it here for the v0 peer.
1682 bool hadBag = SOSPeerGetKeyBag(backupPeer);
1683 SOSPeerSetKeyBag(backupPeer, keybag);
1684 if (!hadBag)
1685 SOSPeerKeyBagDidChange(backupPeer);
1686
1687 CFReleaseSafe(backupPeer);
1688
1689 CFMutableArrayRef untrustedPeerMetas = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1690 CFMutableArrayRef trustedPeersMetas = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1691 SOSEngineSynthesizePeerMetas(engine, trustedPeersMetas, untrustedPeerMetas);
1692 SOSEngineReferenceChangeTrackers(engine, trustedPeersMetas, untrustedPeerMetas, desc);
1693 CFReleaseSafe(trustedPeersMetas);
1694 CFReleaseSafe(untrustedPeerMetas);
1695 }
1696
1697 static bool SOSEngineCircleChanged_locked(SOSEngineRef engine, SOSPeerMetaRef myPeerMeta, CFArrayRef trustedPeers, CFArrayRef untrustedPeers) {
1698 // Sanity check params
1699 // SOSEngineCircleChanged_sanitycheck(engine, myPeerID, trustedPeers, untrustedPeers);
1700
1701 // Transform from SOSPeerInfoRefs to CFDictionaries with the info we want per peer.
1702 // Or, Tell the real SOSPeerRef what the SOSPeerInfoRef is and have it copy out the data it needs.
1703 bool peersOrViewsChanged = SOSEngineSetPeers_locked(engine, myPeerMeta, trustedPeers, untrustedPeers);
1704
1705 // Run though all peers and only cache manifests for peers we still have
1706 CFErrorRef localError = NULL;
1707 if (!SOSEngineGCPeerState_locked(engine, &localError)) {
1708 secerror("SOSEngineGCPeerState_locked failed: %@", localError);
1709 CFReleaseNull(localError);
1710 }
1711 return peersOrViewsChanged;
1712 }
1713
1714 // Initialize the engine if a load fails. Basically this is our first time setup
1715 static bool SOSEngineInit(SOSEngineRef engine, CFErrorRef *error) {
1716 bool ok = true;
1717 secnotice("engine", "new engine for datasource named %@", SOSDataSourceGetName(engine->dataSource));
1718 CFAssignRetained(engine->peerMap, CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault));
1719 CFAssignRetained(engine->viewNameSet2ChangeTracker, CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault));
1720 CFAssignRetained(engine->viewName2ChangeTracker, CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault));
1721 CFReleaseNull(engine->manifestCache);
1722 CFReleaseNull(engine->peerIDs);
1723 // TODO: We shouldn't need to load the backup bag if there was no engine
1724 // state (load failed), since that means there was no circle nor were we an applicant.
1725
1726 // Set up change trackers so we know when a backup peer needs to be created?
1727 // no, since myID is not set, we are not in a circle, so no need to back up
1728 SOSEngineSetPeers_locked(engine, NULL, NULL, NULL);
1729 return ok;
1730 }
1731
1732 // Called by our DataSource in its constructor
1733 SOSEngineRef SOSEngineCreate(SOSDataSourceRef dataSource, CFErrorRef *error) {
1734 SOSEngineRef engine = NULL;
1735 engine = CFTypeAllocate(SOSEngine, struct __OpaqueSOSEngine, kCFAllocatorDefault);
1736 engine->dataSource = dataSource;
1737 engine->queue = dispatch_queue_create("engine", DISPATCH_QUEUE_SERIAL);
1738
1739 engine->peerMap = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1740 engine->viewNameSet2ChangeTracker = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1741 engine->viewName2ChangeTracker = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1742 //engine->syncCompleteQueue = NULL;
1743 engine->syncCompleteListener = NULL;
1744 engine->coders = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1745 engine->haveLoadedCoders = false;
1746 engine->codersNeedSaving = false;
1747
1748 CFErrorRef engineError = NULL;
1749 if (!SOSEngineLoad(engine, NULL, &engineError)) {
1750 secwarning("engine failed load state starting with nothing %@", engineError);
1751 CFReleaseNull(engineError);
1752 if (!SOSEngineInit(engine, error)) {
1753 secerror("engine failed to initialze %@ giving up", error ? *error : NULL);
1754 }
1755 }
1756 SOSEngineSetNotifyPhaseBlock(engine);
1757 return engine;
1758 }
1759
1760 // --- Called from off the queue, need to move to on the queue
1761
1762 static void SOSEngineDoOnQueue(SOSEngineRef engine, dispatch_block_t action)
1763 {
1764 dispatch_sync(engine->queue, action);
1765 }
1766
1767 static bool SOSEngineDoTxnOnQueue(SOSEngineRef engine, CFErrorRef *error, void(^transaction)(SOSTransactionRef txn, bool *commit))
1768 {
1769 return SOSDataSourceWithCommitQueue(engine->dataSource, error, ^(SOSTransactionRef txn, bool *commit) {
1770 SOSEngineDoOnQueue(engine, ^{ transaction(txn, commit); });
1771 });
1772 }
1773
1774 //
1775 // MARK: SOSEngine API
1776 //
1777
1778 void SOSEngineDispose(SOSEngineRef engine) {
1779 // NOOP Engines stick around forever to monitor dataSource changes.
1780 engine->dataSource = NULL;
1781 CFReleaseNull(engine->coders);
1782 }
1783
1784 void SOSEngineForEachPeer(SOSEngineRef engine, void (^with)(SOSPeerRef peer)) {
1785 SOSEngineDoOnQueue(engine, ^{
1786 SOSEngineForEachPeer_locked(engine, with);
1787 });
1788 }
1789
1790 static void SOSEngineForEachBackupPeer(SOSEngineRef engine, void (^with)(SOSPeerRef peer)) {
1791 SOSEngineDoOnQueue(engine, ^{
1792 SOSEngineForEachBackupPeer_locked(engine, with);
1793 });
1794 }
1795
1796 static const CFStringRef kSecADSecurityNewItemSyncTimeKey = CFSTR("com.apple.security.secureobjectsync.itemtime.new");
1797 static const CFStringRef kSecADSecurityKnownItemSyncTimeKey = CFSTR("com.apple.security.secureobjectsync.itemtime.known");
1798
1799
1800 static void ReportItemSyncTime(SOSDataSourceRef ds, bool known, SOSObjectRef object)
1801 {
1802 CFDateRef itemModDate = SOSObjectCopyModificationDate(ds, object, NULL);
1803 if (itemModDate) {
1804 CFAbsoluteTime syncTime = 0;
1805 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
1806
1807 CFAbsoluteTime peerModificationAbsoluteTime = CFDateGetAbsoluteTime(itemModDate);
1808 if (peerModificationAbsoluteTime > now) {
1809 syncTime = now - peerModificationAbsoluteTime;
1810 }
1811
1812 SecADClientPushValueForDistributionKey(known ? kSecADSecurityKnownItemSyncTimeKey : kSecADSecurityNewItemSyncTimeKey,
1813 SecBucket2Significant(syncTime));
1814 }
1815 CFReleaseNull(itemModDate);
1816 }
1817
1818 /* Handle incoming message from peer p. Return false if there was an error, true otherwise. */
1819 bool SOSEngineHandleMessage_locked(SOSEngineRef engine, CFStringRef peerID, SOSMessageRef message,
1820 SOSTransactionRef txn, bool *commit, bool *somethingChanged, CFErrorRef *error) {
1821 SOSPeerRef peer = SOSEngineCopyPeerWithID_locked(engine, peerID, error);
1822 if (!peer) return false;
1823
1824 CFStringRef peerDesc = NULL;
1825 SOSManifestRef localManifest = NULL;
1826 SOSManifestRef allAdditions = NULL;
1827 SOSManifestRef unwanted = NULL;
1828 SOSManifestRef confirmed = NULL;
1829 SOSManifestRef base = NULL;
1830 SOSManifestRef confirmedRemovals = NULL, confirmedAdditions = NULL;
1831 __block struct SOSDigestVector receivedObjects = SOSDigestVectorInit;
1832 __block struct SOSDigestVector unwantedObjects = SOSDigestVectorInit;
1833
1834 // Check for unknown criticial extensions in the message, and handle
1835 // any other extensions we support
1836 __block bool ok = true;
1837 CFMutableArrayRef changes = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1838
1839 require_action_quiet(peer, exit, ok = SOSErrorCreate(errSecParam, error, NULL, CFSTR("Couldn't create peer with Engine for %@"), peerID));
1840 peerDesc = CFCopyDescription(peer);
1841
1842 bool hadBeenInSyncAtStart = SOSPeerHasBeenInSync(peer);
1843
1844 SOSMessageWithExtensions(message, true, ^(CFDataRef oid, bool isCritical, CFDataRef extension, bool *stop) {
1845 // OMFG a Critical extension what shall I do!
1846 ok = SOSErrorCreate(kSOSErrorNotReady, error, NULL, CFSTR("Unknown criticial extension in peer message"));
1847 *stop = true;
1848 });
1849 require_quiet(ok, exit);
1850
1851 // Merge Objects from the message into our DataSource.
1852 // Should we move the transaction to the SOSAccount level?
1853 // TODO: Filter incoming objects
1854 //if (!SOSDataSourceForEachObjectInViewSet(engine->dataSource, pendingObjects, SOSPeerGetViewNameSet(peer), error, ^void(CFDataRef key, SOSObjectRef object, bool *stop) {
1855 require_quiet(ok &= SOSMessageWithSOSObjects(message, engine->dataSource, error, ^(SOSObjectRef peersObject, bool *stop) {
1856 CFDataRef digest = SOSObjectCopyDigest(engine->dataSource, peersObject, error);
1857 if (!digest) {
1858 *stop = true;
1859 *commit = false;
1860 secerror("%@ peer sent bad object: %@, rolling back changes", SOSPeerGetID(peer), error ? *error : NULL);
1861 return;
1862 }
1863 SOSDigestVectorAppend(&receivedObjects, CFDataGetBytePtr(digest));
1864 SOSObjectRef mergedObject = NULL;
1865 SOSMergeResult mr = SOSDataSourceMergeObject(engine->dataSource, txn, peersObject, &mergedObject, error);
1866 // TODO: If the mr is kSOSMergeLocalObject most of the time (or all of the time),
1867 // consider asking the peer to stop sending us objects, and send it objects instead.
1868 ok &= (mr != kSOSMergeFailure);
1869 if (!ok) {
1870 *stop = true;
1871 *commit = false;
1872 // TODO: Might want to change to warning since the race of us locking after ckd sends us a message could cause db locked errors here.
1873 secerror("%@ SOSDataSourceMergeObject failed %@ rolling back changes", SOSPeerGetID(peer), error ? *error : NULL);
1874 } else if (mr==kSOSMergePeersObject || mr==kSOSMergeCreatedObject) {
1875 *somethingChanged = true;
1876 } else {
1877 // mr == kSOSMergeLocalObject
1878 if (!CFEqual(mergedObject, peersObject)) {
1879 // Record this object as something we don't want peer to ever send us again. By adding it to
1880 // unwantedObjects we'll falsely claim to peer we have it until they tell us they don't have it anymore.
1881 SOSDigestVectorAppend(&unwantedObjects, CFDataGetBytePtr(digest));
1882 }
1883 // Ensure localObject is in local manifest (possible corruption) by posting an update when we are done.
1884 SOSChangesAppendAdd(changes, mergedObject);
1885 }
1886
1887 if (ok && hadBeenInSyncAtStart) {
1888 ReportItemSyncTime(engine->dataSource,
1889 mr == kSOSMergeLocalObject,
1890 peersObject);
1891 }
1892
1893 CFReleaseSafe(mergedObject);
1894 CFReleaseSafe(digest);
1895 }), exit);
1896 struct SOSDigestVector dvunion = SOSDigestVectorInit;
1897 SOSDigestVectorSort(&receivedObjects);
1898 SOSDigestVectorUnionSorted(SOSManifestGetDigestVector(SOSMessageGetAdditions(message)), &receivedObjects, &dvunion);
1899 allAdditions = SOSManifestCreateWithDigestVector(&dvunion, error);
1900 SOSDigestVectorFree(&receivedObjects);
1901 SOSDigestVectorFree(&dvunion);
1902
1903 unwanted = SOSManifestCreateWithDigestVector(&unwantedObjects, error);
1904 SOSDigestVectorFree(&unwantedObjects);
1905
1906 if (CFArrayGetCount(changes)) {
1907 // NOTE: This is always notifiying of all additions that end up choosing local, which should be rare, since we shouldn't
1908 // be receiving objects we already have. When we do we tell ourselves to add them all again so our views will properly
1909 // reflect that we actually have these objects if we didn't already.
1910
1911 // Ensure any objects that we received and have locally already are actually in our local manifest
1912 SOSEngineUpdateChanges_locked(engine, txn, kSOSDataSourceTransactionDidCommit, kSOSDataSourceSOSTransaction, changes, error);
1913 }
1914 CFReleaseSafe(changes);
1915
1916 // ---- Don't use local or peer manifests from above this line,
1917 // ---- since commiting the SOSDataSourceWith transaction might change them ---
1918
1919 // Take a snapshot of our dataSource's local manifest.
1920 require_quiet(ok = localManifest = SOSEngineCopyLocalPeerManifest_locked(engine, peer, error), exit);
1921
1922 CFDataRef baseDigest = SOSMessageGetBaseDigest(message);
1923 CFDataRef proposedDigest = SOSMessageGetProposedDigest(message);
1924
1925 #if 0
1926 // I believe this is no longer needed now that we have eliminated extra,
1927 // since this is handled below once we get a confirmed manifest from our
1928 // peer.
1929
1930 // If we just received a L00 reset pendingObjects to localManifest
1931 if (!baseDigest && !proposedDigest) {
1932 // TODO: This is definitely busted for v0 peers since v0 peers always send a
1933 // L00 (ManifestDigestMessage as an ack) whereas in v2 this is a protocol restart
1934 // However if we can still find a confirmed manifest below we probably
1935 // don't want to do this even for v2.
1936 // Also I don't think we will ever send a ManifestMessage right now in
1937 // response to a ManifestDigest
1938 SOSPeerSetPendingObjects(peer, localManifest);
1939 secnoticeq("engine", "%@:%@ SOSPeerSetPendingObjects: %@", engine->myID, peerID, localManifest);
1940 }
1941 #endif
1942
1943 base = SOSPeerCopyManifestForDigest(peer, baseDigest);
1944
1945 // Note that the sender digest will only exist if we receive a SOSManifestDigestMessageType (since we never receive v2 messages)
1946 confirmed = SOSPeerCopyManifestForDigest(peer, SOSMessageGetSenderDigest(message));
1947 if (!confirmed) {
1948 if (SOSManifestGetCount(SOSMessageGetRemovals(message)) || SOSManifestGetCount(allAdditions)) {
1949 if (base || !baseDigest) {
1950
1951 secnotice("engine", "SOSEngineHandleMessage_locked (%@): creating a confirmed manifest via a patch (base %zu %@, +%zu, -%zu)", SOSPeerGetID(peer),
1952 SOSManifestGetCount(base), SOSManifestGetDigest(base, NULL),
1953 SOSManifestGetCount(allAdditions), SOSManifestGetCount(SOSMessageGetRemovals(message)));
1954
1955 confirmed = SOSManifestCreateWithPatch(base, SOSMessageGetRemovals(message), allAdditions, error);
1956 }
1957 if (!confirmed) {
1958 confirmedRemovals = CFRetainSafe(SOSMessageGetRemovals(message));
1959 confirmedAdditions = CFRetainSafe(allAdditions);
1960 }
1961 } else if (baseDigest) {
1962 confirmed = CFRetainSafe(base);
1963 secerror("%@:%@ Protocol error send L00 - figure out later base: %@", engine->myID, peerID, base);
1964 }
1965
1966 } else {
1967 secnotice("engine", "SOSEngineHandleMessage_locked (%@): got a confirmed manifest by digest: (%zu, %@)", SOSPeerGetID(peer), SOSManifestGetCount(confirmed), SOSMessageGetSenderDigest(message));
1968 }
1969 secnoticeq("engine", "%@:%@ confirmed: %@ base: %@", engine->myID, peerID, confirmed, base);
1970 if (confirmed) {
1971 ok &= SOSManifestDiff(SOSPeerGetConfirmedManifest(peer), confirmed, &confirmedRemovals, &confirmedAdditions, error);
1972 if (SOSManifestGetCount(SOSMessageGetRemovals(message)))
1973 CFAssignRetained(confirmedRemovals, SOSManifestCreateUnion(confirmedRemovals, SOSMessageGetRemovals(message), error));
1974 }
1975 if (SOSManifestGetCount(confirmedRemovals) || SOSManifestGetCount(confirmedAdditions) || SOSManifestGetCount(unwanted)) {
1976 ok &= SOSPeerDidReceiveRemovalsAndAdditions(peer, confirmedRemovals, confirmedAdditions, unwanted, localManifest, error);
1977 }
1978
1979
1980 // TODO: We should probably remove the if below and always call SOSPeerSetConfirmedManifest,
1981 // since having a NULL confirmed will force us to send a manifest message to get in sync again.
1982 if (confirmed) {
1983
1984 SOSManifestRef previousConfirmedManifest = SOSPeerGetConfirmedManifest(peer);
1985 if(previousConfirmedManifest) {
1986 secnotice("engine", "SOSEngineHandleMessage_locked (%@): new confirmed manifest (%zu, %@) will replace existing confirmed manifest (%zu, %@)", SOSPeerGetID(peer),
1987 SOSManifestGetCount(confirmed), SOSManifestGetDigest(confirmed, NULL),
1988 SOSManifestGetCount(previousConfirmedManifest), SOSManifestGetDigest(previousConfirmedManifest, NULL));
1989 } else {
1990 secnotice("engine", "SOSEngineHandleMessage_locked (%@): new confirmed manifest (%zu, %@) is first manifest for peer", SOSPeerGetID(peer),
1991 SOSManifestGetCount(confirmed), SOSManifestGetDigest(confirmed, NULL));
1992 }
1993
1994 SOSPeerSetConfirmedManifest(peer, confirmed);
1995 } else if (SOSPeerGetConfirmedManifest(peer)) {
1996 secnoticeq("engine", "%@:%@ unable to find confirmed in %@, sync protocol reset", engine->myID, peer, message);
1997
1998 SOSPeerSetConfirmedManifest(peer, NULL);
1999 //SOSPeerSetSendObjects(peer, true);
2000 }
2001
2002 // ---- SendObjects and extra->pendingObjects promotion dance ----
2003
2004 // The first block of code below sets peer.sendObjects to true when we receive a L00 and the second block
2005 // moves extra to pendingObjects once we receive a confirmed manifest in or after the L00.
2006 if (!baseDigest && !proposedDigest) {
2007 SOSPeerSetSendObjects(peer, true);
2008 }
2009
2010 if (0 /* confirmed && SOSPeerSendObjects(peer) */) {
2011 SOSManifestRef allExtra = NULL;
2012 ok &= SOSManifestDiff(confirmed, localManifest, NULL, &allExtra, error);
2013 secnoticeq("engine", "%@:%@ confirmed %@ (re)setting O:%@", engine->myID, SOSPeerGetID(peer), confirmed, allExtra);
2014 SOSPeerSetPendingObjects(peer, allExtra);
2015 CFReleaseSafe(allExtra);
2016 }
2017
2018 exit:
2019 secnotice("engine", "recv %@:%@ %@", engine->myID, SOSPeerGetID(peer), message);
2020 secnotice("peer", "recv %@ -> %@", peerDesc, peer);
2021
2022 CFReleaseNull(base);
2023 CFReleaseSafe(confirmed);
2024 CFReleaseSafe(localManifest);
2025 CFReleaseSafe(peerDesc);
2026 CFReleaseSafe(allAdditions);
2027 CFReleaseSafe(unwanted);
2028 CFReleaseSafe(confirmedRemovals);
2029 CFReleaseSafe(confirmedAdditions);
2030 CFReleaseSafe(peer);
2031 return ok;
2032 }
2033
2034 static CFDataRef SOSEngineCopyObjectDER(SOSEngineRef engine, SOSObjectRef object, CFErrorRef *error) {
2035 CFDataRef der = NULL;
2036 CFDictionaryRef plist = SOSObjectCopyPropertyList(engine->dataSource, object, error);
2037 if (plist) {
2038 der = CFPropertyListCreateDERData(kCFAllocatorDefault, plist, error);
2039 CFRelease(plist);
2040 }
2041 return der;
2042 }
2043
2044
2045 /*
2046
2047 +-----------------------------+_
2048 | | | \
2049 | A | T | \
2050 | | | \
2051 _+=============================+ } L
2052 / | | /
2053 / | S | /
2054 / | |_/
2055 / +==============================
2056 / | |
2057 C { | |
2058 \ | M +------------|
2059 \ | | |
2060 \ | | U |
2061 \ | | |
2062 \_+-------------+---------------+
2063
2064 A assumed
2065 T to be sent
2066 S shared
2067 M missing
2068 U unwanted
2069 L local
2070 C confirmed
2071
2072 */
2073 #if 0
2074 static bool SOSAppendRemoveToPatch(CFTypeRef remove, CFMutableDictionaryRef patch, CFErrorRef *error) {
2075 }
2076
2077 static bool SOSAppendAddToPatch(CFTypeRef add, CFMutableDictionaryRef patch, CFErrorRef *error) {
2078 }
2079
2080 static bool SOSAppendDiffToPatch(CFTypeRef left, CFTypeRef right, CFMutableDictionaryRef patch, CFErrorRef *error) {
2081 bool ok = true;
2082 if (!left && right) {
2083 SOSAppendAddToPatch(right, patch, error);
2084 } else if (left && !right) {
2085 SOSAppendRemoveToPatch(left, patch, error);
2086 } else if (left && right) {
2087 CFTypeID ltype = CFGetTypeID(left);
2088 CFTypeID rtype = CFGetTypeID(right);
2089 if (ltype == rtype) {
2090 if (CFArrayGetTypeID() == ltype) {
2091 ok = SecError(errSecParam, error, CFSTR("unsupported type array"), ltype);
2092 } else if (CFBooleanGetTypeID == ltype) {
2093 ok = SecError(errSecParam, error, CFSTR("unsupported type boolean"), ltype);
2094 } else if (CFDataGetTypeID == ltype) {
2095 ok = SecError(errSecParam, error, CFSTR("unsupported type data"), ltype);
2096 } else if (CFDictionaryGetTypeID == ltype) {
2097 __block CFMutableDictionaryRef leftnotright = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
2098 __block CFMutableDictionaryRef rightnotleft = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, right);
2099
2100 CFDictionaryForEach(left, ^(const void *key, const void *lvalue) {
2101 const void *rvalue = NULL;
2102 if (CFDictionaryGetValueIfPresent(right, key, &rvalue)) {
2103 CFDictionaryRemoveValue(rightnotleft, key);
2104
2105 CFMutableDictionaryRef subpatch = CFDictionaryCreateForCFTypes(kCFAllocatorDefault);
2106 CFDictionaryAddValue(patch, key, subpatch);
2107 SOSAppendDiffToPatch(lvalue, rvalue, subpatch, error);
2108 CFReleaseSafe(subpatch);
2109 } else {
2110 CFDictionaryAddValue(leftnotright, key, lvalue);
2111 }
2112 });
2113 // Proccess leftnotright and rightnotleft
2114 CFReleaseSafe(leftnotright);
2115 CFReleaseSafe(rightnotleft);
2116 } else if (SOSManifestGetTypeID == ltype) {
2117 SOSManifestRef removed = NULL, added = NULL;
2118 ok &= SOSManifestDiff(left, right, &removed, &added, error);
2119 if (SOSManifestGetCount(removed) || SOSManifestGetCount(added)) {
2120 SOSAppendDiffToPatch(lvalue, rvalue, subpatch, error);
2121 CFStringAppend(, <#CFStringRef appendedString#>)
2122 }
2123 CFReleaseSafe(removed);
2124 CFReleaseSafe(added);
2125 } else if (CFNumberGetTypeID == ltype) {
2126 ok = SecError(errSecParam, error, CFSTR("unsupported type number"), ltype);
2127 } else if (CFSetGetTypeID == ltype) {
2128 ok = SecError(errSecParam, error, CFSTR("unsupported type set"), ltype);
2129 } else if (CFStringGetTypeID == ltype) {
2130 ok = SecError(errSecParam, error, CFSTR("unsupported type string"), ltype);
2131 } else {
2132 ok = SecError(errSecParam, error, CFSTR("unknown type %lu"), ltype);
2133 }
2134 }
2135 } else if (!left && !right) {
2136 // NOOP
2137 }
2138 }
2139 #endif
2140
2141 static __unused bool SOSEngineCheckPeerIntegrity(SOSEngineRef engine, SOSPeerRef peer, CFErrorRef *error) {
2142 #if 0
2143 //static CFMutableDictionaryRef p2amtu;
2144 if (!engine->p2amtu)
2145 engine->p2amtu = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
2146 CFDictionaryRef amtu = CFDictionaryGetValue(engine->p2amtu, SOSPeerGetID(peer));
2147 #endif
2148
2149 // Inputs
2150 SOSManifestRef L = SOSEngineCopyLocalPeerManifest_locked(engine, peer, error);
2151 SOSManifestRef T = SOSPeerGetPendingObjects(peer);
2152 SOSManifestRef C = SOSPeerGetConfirmedManifest(peer);
2153 SOSManifestRef U = SOSPeerGetUnwantedManifest(peer);
2154
2155 // Computed
2156 SOSManifestRef CunionU = SOSManifestCreateUnion(C, U, error);
2157 SOSManifestRef S = SOSManifestCreateIntersection(L, CunionU, error);
2158
2159 SOSManifestRef AunionT = NULL, MunionU = NULL;
2160 SOSManifestDiff(L, C, &AunionT, &MunionU, error);
2161
2162 SOSManifestRef A = SOSManifestCreateComplement(T, AunionT, error);
2163 SOSManifestRef M = SOSManifestCreateComplement(U, MunionU, error);
2164
2165 SOSManifestRef SunionAunionT = SOSManifestCreateUnion(S, AunionT, error);
2166 SOSManifestRef SunionMunionU = SOSManifestCreateUnion(S, MunionU, error);
2167
2168 SOSManifestRef AintersectM = SOSManifestCreateIntersection(A, M, error);
2169 SOSManifestRef AintersectS = SOSManifestCreateIntersection(A, S, error);
2170 SOSManifestRef AintersectT = SOSManifestCreateIntersection(A, T, error);
2171 SOSManifestRef AintersectU = SOSManifestCreateIntersection(A, U, error);
2172 SOSManifestRef MintersectS = SOSManifestCreateIntersection(M, S, error);
2173 SOSManifestRef MintersectT = SOSManifestCreateIntersection(M, T, error);
2174 SOSManifestRef MintersectU = SOSManifestCreateIntersection(M, U, error);
2175 SOSManifestRef SintersectT = SOSManifestCreateIntersection(S, T, error);
2176 SOSManifestRef SintersectU = SOSManifestCreateIntersection(S, U, error);
2177 SOSManifestRef TintersectU = SOSManifestCreateIntersection(T, U, error);
2178
2179 #if 0
2180 CFDictionaryRef newAmtu = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, CFSTR("A"), A, CFSTR("M"), M, CFSTR("T"), T, CFSTR("U") U, NULL);
2181 CFDictionarySetValue(engine->p2amtu, SOSPeerGetID(peer), newAmtu);
2182 CFMutableStringRef amtuChanges = CFStringCreateMutable(kCFAllocatorDefault, 0);
2183 SOSAppendDiffToString(amtu, newAmtu, amtuChanges);
2184 secnotice("engine", "%@: %@", SOSPeerGetID(peer), amtuChanges);
2185 #endif
2186
2187 #define SOSASSERT(e) (__builtin_expect(!(e), 0) ? secnotice("engine", "state-assertion %s", #e), assert(e) : (void)0)
2188
2189 SOSASSERT(L ? CFEqual(L, SunionAunionT) : SOSManifestGetCount(SunionAunionT) == 0);
2190 SOSASSERT(C ? CFEqual(C, SunionMunionU) : SOSManifestGetCount(SunionMunionU) == 0);
2191
2192 SOSASSERT(SOSManifestGetCount(AintersectM) == 0);
2193 SOSASSERT(SOSManifestGetCount(AintersectS) == 0);
2194 SOSASSERT(SOSManifestGetCount(AintersectT) == 0);
2195 SOSASSERT(SOSManifestGetCount(AintersectU) == 0);
2196 SOSASSERT(SOSManifestGetCount(MintersectS) == 0);
2197 SOSASSERT(SOSManifestGetCount(MintersectT) == 0);
2198 SOSASSERT(SOSManifestGetCount(MintersectU) == 0);
2199 SOSASSERT(SOSManifestGetCount(SintersectT) == 0);
2200 SOSASSERT(SOSManifestGetCount(SintersectU) == 0);
2201 SOSASSERT(SOSManifestGetCount(TintersectU) == 0);
2202
2203 CFReleaseSafe(AintersectM);
2204 CFReleaseSafe(AintersectS);
2205 CFReleaseSafe(AintersectT);
2206 CFReleaseSafe(AintersectU);
2207 CFReleaseSafe(MintersectS);
2208 CFReleaseSafe(MintersectT);
2209 CFReleaseSafe(MintersectU);
2210 CFReleaseSafe(SintersectT);
2211 CFReleaseSafe(SintersectU);
2212 CFReleaseSafe(TintersectU);
2213
2214 CFReleaseSafe(AunionT);
2215 CFReleaseSafe(MunionU);
2216 CFReleaseSafe(CunionU);
2217
2218 CFReleaseNull(SunionAunionT);
2219 CFReleaseNull(SunionMunionU);
2220
2221 CFReleaseSafe(A);
2222 CFReleaseSafe(M);
2223 CFReleaseSafe(S);
2224 //CFReleaseSafe(T); // Get
2225 //CFReleaseSafe(U); // Get
2226 //CFReleaseSafe(C); // Get
2227 CFReleaseSafe(L);
2228 return true;
2229 }
2230
2231 void SOSEngineSetSyncCompleteListener(SOSEngineRef engine, SOSEnginePeerInSyncBlock notify_block) {
2232 SOSEngineDoOnQueue(engine, ^{
2233 CFAssignRetained(engine->syncCompleteListener, Block_copy(notify_block));
2234 });
2235 }
2236
2237 void SOSEngineSetSyncCompleteListenerQueue(SOSEngineRef engine, dispatch_queue_t notify_queue) {
2238 SOSEngineDoOnQueue(engine, ^{
2239 CFRetainAssign(engine->syncCompleteQueue, notify_queue);
2240 });
2241 }
2242
2243 static void SOSEngineCompletedSyncWithPeer(SOSEngineRef engine, SOSPeerRef peer) {
2244 SOSEnginePeerInSyncBlock block_to_call = engine->syncCompleteListener;
2245
2246 if (block_to_call && engine->syncCompleteQueue) {
2247 CFStringRef ID = CFRetainSafe(SOSPeerGetID(peer));
2248 CFSetRef views = CFRetainSafe(SOSPeerGetViewNameSet(peer));
2249 CFRetainSafe(block_to_call);
2250
2251 dispatch_async(engine->syncCompleteQueue, ^{
2252 block_to_call(ID, views);
2253 CFReleaseSafe(ID);
2254 CFReleaseSafe(views);
2255 CFReleaseSafe(block_to_call);
2256 });
2257 }
2258
2259 SOSPeerSetHasBeenInSync(peer, true);
2260 }
2261
2262
2263 CFDataRef SOSEngineCreateMessage_locked(SOSEngineRef engine, SOSTransactionRef txn, SOSPeerRef peer,
2264 CFMutableArrayRef *attributeList, CFErrorRef *error, SOSEnginePeerMessageSentCallback **sent) {
2265 SOSManifestRef local = SOSEngineCopyLocalPeerManifest_locked(engine, peer, error);
2266 __block SOSMessageRef message = SOSMessageCreate(kCFAllocatorDefault, SOSPeerGetMessageVersion(peer), error);
2267 SOSManifestRef confirmed = SOSPeerGetConfirmedManifest(peer);
2268 SOSManifestRef pendingObjects = SOSPeerGetPendingObjects(peer);
2269 SOSManifestRef objectsSent = NULL;
2270 SOSManifestRef proposed = NULL;
2271 SOSManifestRef allMissing = NULL;
2272 SOSManifestRef allExtra = NULL;
2273 SOSManifestRef extra = NULL;
2274 SOSManifestRef excessPending = NULL;
2275 SOSManifestRef missing = NULL;
2276 SOSManifestRef unwanted = SOSPeerGetUnwantedManifest(peer);
2277 SOSManifestRef excessUnwanted = NULL;
2278 CFDataRef result = NULL;
2279
2280 // Given (C, L, T, U) compute (T, U, M, A)
2281 // (C \ L) \ U => M
2282 // (L \ C) \ T => A
2283 // we also compute
2284 // U \ (C \ L) => EU
2285 // T \ (L \ C) => ET
2286 // And assert that both EU and ET are empty and if not remove them from U and T respectively
2287 SOSManifestDiff(confirmed, local, &allMissing, &allExtra, error);
2288 SOSManifestDiff(allExtra, pendingObjects, &extra, &excessPending, error);
2289 if (SOSManifestGetCount(excessPending)) {
2290 // T \ (L \ C) => excessPending (items both in L and C or in neither that are still pending)
2291 // Can only happen if a member of T was removed from L without us having a chance to update T
2292 secerror("%@ ASSERTION FAILURE purging excess pendingObjects: %@", peer, excessPending);
2293 SOSManifestRef newPendingObjects = SOSManifestCreateComplement(excessPending, pendingObjects, error);
2294 SOSPeerSetPendingObjects(peer, newPendingObjects);
2295 CFReleaseSafe(newPendingObjects);
2296 pendingObjects = SOSPeerGetPendingObjects(peer);
2297 }
2298 SOSManifestDiff(allMissing, unwanted, &missing, &excessUnwanted, error);
2299 if (SOSManifestGetCount(excessUnwanted)) {
2300 // U \ (C \ L) => excessUnwanted (items both in L and C or in neither that are still unwanted)
2301 // Can only happen if a member of U was added to L without us having a chance to update U.
2302 // Since U only contains items the conflict resolver rejected, this implies L somehow got rolled back
2303 // The other option (and more likely) is a member of U was removed from C and not from U.
2304 secerror("%@ ASSERTION FAILURE purging excess unwanted: %@", peer, excessUnwanted);
2305 SOSManifestRef newUnwanted = SOSManifestCreateComplement(excessUnwanted, unwanted, error);
2306 SOSPeerSetUnwantedManifest(peer, newUnwanted);
2307 CFReleaseSafe(newUnwanted);
2308 unwanted = SOSPeerGetUnwantedManifest(peer);
2309 }
2310
2311 CFReleaseNull(allExtra);
2312 CFReleaseNull(excessPending);
2313 CFReleaseNull(allMissing);
2314 CFReleaseNull(excessUnwanted);
2315
2316 secnoticeq("engine", "%@:%@: send state for peer [%s%s%s][%s%s] local:%zu confirmed:%zu pending:%zu, extra:%zu, missing:%zu unwanted:%zu", engine->myID, SOSPeerGetID(peer),
2317 local ? "L":"l",
2318 confirmed ? "C":"0",
2319 pendingObjects ? "P":"0",
2320 SOSPeerSendObjects(peer) ? "O":"o",
2321 SOSPeerMustSendMessage(peer) ? "S":"s",
2322 SOSManifestGetCount(local),
2323 SOSManifestGetCount(confirmed),
2324 SOSManifestGetCount(pendingObjects),
2325 SOSManifestGetCount(extra),
2326 SOSManifestGetCount(missing),
2327 SOSManifestGetCount(unwanted)
2328 );
2329
2330 if (confirmed) {
2331 // TODO: Because of not letting things terminate while we have extra left
2332 // we might send objects when we didn't need to, but there is always an
2333 // extra roundtrip required for objects that we assume the other peer
2334 // should have already.
2335 // TODO: If there are extra objects left, calling this function is not
2336 // idempotent we should check if pending is what we are about to send and not send anything in this case.
2337 if (SOSManifestGetCount(pendingObjects) == 0 && SOSManifestGetCount(extra) == 0)
2338 SOSPeerSetSendObjects(peer, false);
2339
2340 // If we aren't missing anything, we've gotten all their data, so we're sync even if they haven't seen ours.
2341 if (missing && SOSManifestGetCount(missing) == 0) {
2342 SOSEngineCompletedSyncWithPeer(engine, peer);
2343 }
2344
2345 if (CFEqualSafe(local, SOSPeerGetProposedManifest(peer)) && !SOSPeerMustSendMessage(peer)) {
2346 bool send = false;
2347 if (CFEqual(confirmed, local)) {
2348 secnoticeq("engine", "synced <No MSG> %@:%@", engine->myID, peer);
2349 } else if (SOSManifestGetCount(pendingObjects) == 0 /* TODO: No entries moved from extra to pendingObjects. */
2350 && SOSManifestGetCount(missing) == 0) {
2351 secnoticeq("engine", "waiting <MSG not resent> %@:%@ extra: %@", engine->myID, peer, extra);
2352 } else {
2353 send = true;
2354 }
2355 if (!send) {
2356 CFReleaseNull(local);
2357 CFReleaseNull(message);
2358 CFReleaseNull(extra);
2359 CFReleaseNull(missing);
2360 return CFDataCreate(kCFAllocatorDefault, NULL, 0);
2361 }
2362 }
2363
2364 if (SOSManifestGetCount(pendingObjects)) {
2365 // If we have additions and we need to send objects, do so.
2366 __block size_t objectsSize = 0;
2367 __block struct SOSDigestVector dv = SOSDigestVectorInit;
2368 CFMutableArrayRef changes = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2369 __block CFErrorRef dsfeError = NULL;
2370
2371 if (!SOSDataSourceForEachObject(engine->dataSource, txn, pendingObjects, &dsfeError, ^void(CFDataRef key, SOSObjectRef object, bool *stop) {
2372 CFErrorRef localError = NULL;
2373 CFDataRef digest = NULL;
2374 CFDataRef der = NULL;
2375 #if !defined(NDEBUG)
2376 const uint8_t *d = CFDataGetBytePtr(key);
2377 #endif
2378 secdebug("engine", "%@:%@ object %02X%02X%02X%02X error from SOSDataSourceForEachObject: %@",
2379 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], dsfeError);
2380 if (!object) {
2381 const uint8_t *d = CFDataGetBytePtr(key);
2382 secerror("%@:%@ object %02X%02X%02X%02X dropping from manifest: not found in datasource: %@",
2383 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], dsfeError);
2384 SOSChangesAppendDelete(changes, key);
2385 } else if (!(der = SOSEngineCopyObjectDER(engine, object, &localError))
2386 || !(digest = SOSObjectCopyDigest(engine->dataSource, object, &localError))) {
2387 if (SecErrorGetOSStatus(localError) == errSecDecode) {
2388 // Decode error, we need to drop these objects from our manifests
2389 const uint8_t *d = CFDataGetBytePtr(key);
2390 secnoticeq("engine", "%@:%@ object %02X%02X%02X%02X dropping from manifest: %@",
2391 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], localError);
2392 SOSChangesAppendDelete(changes, key);
2393 CFRelease(localError);
2394 } else {
2395 // Stop iterating and propagate out all other errors.
2396 const uint8_t *d = CFDataGetBytePtr(key);
2397 secnoticeq("engine", "%@:%@ object %02X%02X%02X%02X in SOSDataSourceForEachObject: %@",
2398 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], localError);
2399 *stop = true;
2400 CFErrorPropagate(localError, error);
2401 CFReleaseNull(message);
2402 }
2403 } else {
2404 if (!CFEqual(key, digest)) {
2405 const uint8_t *d = CFDataGetBytePtr(key);
2406 const uint8_t *e = CFDataGetBytePtr(digest);
2407 secnoticeq("engine", "%@:%@ object %02X%02X%02X%02X is really %02X%02X%02X%02X dropping from local manifest",
2408 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], e[0], e[1], e[2], e[3]);
2409 SOSChangesAppendDelete(changes, key);
2410 SOSChangesAppendAdd(changes, object); // This is new behaviour but we think it's more correct
2411 }
2412
2413 size_t objectLen = (size_t)CFDataGetLength(der);
2414 if (SOSMessageAppendObject(message, der, &localError)) {
2415 SOSDigestVectorAppend(&dv, CFDataGetBytePtr(digest));
2416 if(!*attributeList)
2417 *attributeList = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2418 CFDictionaryRef itemPlist = SOSObjectCopyPropertyList(engine->dataSource, object, &localError);
2419 if(itemPlist && !CFArrayContainsValue(*attributeList, CFRangeMake(0, CFArrayGetCount(*attributeList)), (CFStringRef)CFDictionaryGetValue(itemPlist, kSecAttrAccessGroup))){
2420 CFArrayAppendValue(*attributeList, (CFStringRef)CFDictionaryGetValue(itemPlist, kSecAttrAccessGroup));
2421 }//copy access group to array
2422 CFReleaseNull(itemPlist);
2423 } else {
2424 const uint8_t *d = CFDataGetBytePtr(digest);
2425 CFStringRef hexder = CFDataCopyHexString(der);
2426 secnoticeq("engine", "%@:%@ object %02X%02X%02X%02X der: %@ dropping from manifest: %@",
2427 engine->myID, SOSPeerGetID(peer), d[0], d[1], d[2], d[3], hexder, localError);
2428 CFReleaseNull(hexder);
2429 CFReleaseNull(message);
2430 // Since we can't send these objects let's assume they are bad too?
2431 SOSChangesAppendDelete(changes, digest);
2432 }
2433
2434 objectsSize += objectLen;
2435 if (objectsSize > kSOSMessageMaxObjectsSize)
2436 *stop = true;
2437 }
2438 CFErrorPropagate(dsfeError, error); // this also releases dsfeError
2439 dsfeError = NULL;
2440 CFReleaseSafe(der);
2441 CFReleaseSafe(digest);
2442 })) {
2443 CFReleaseNull(message);
2444 }
2445 if (dv.count){
2446 objectsSent = SOSManifestCreateWithDigestVector(&dv, error);
2447 }
2448 if (CFArrayGetCount(changes)) {
2449 CFErrorRef localError = NULL;
2450 if (!SOSEngineUpdateChanges_locked(engine, NULL, kSOSDataSourceTransactionDidCommit, kSOSDataSourceSOSTransaction, changes, &localError))
2451 secerror("SOSEngineUpdateChanges_locked: %@ failed: %@", changes, localError);
2452 CFReleaseSafe(localError);
2453 CFAssignRetained(local, SOSEngineCopyLocalPeerManifest_locked(engine, peer, error));
2454 }
2455 CFReleaseSafe(changes);
2456 SOSDigestVectorFree(&dv);
2457 CFReleaseNull(dsfeError);
2458 }
2459 } else {
2460 // If we have no confirmed manifest, we want all pendedObjects going out as a manifest
2461 objectsSent = CFRetainSafe(pendingObjects);
2462 }
2463
2464 if (confirmed || SOSManifestGetCount(missing) || SOSManifestGetCount(extra) || objectsSent) {
2465 SOSManifestRef allExtra = SOSManifestCreateUnion(extra, objectsSent, error);
2466 proposed = SOSManifestCreateWithPatch(confirmed, missing, allExtra, error);
2467 CFReleaseNull(allExtra);
2468 }
2469
2470 SOSManifestRef sender = local;
2471 // We actually send the remote peer its own digest.
2472 // Note that both pendingObjects and unwanted may have been changed, so we get them again
2473 if (SOSManifestGetCount(SOSPeerGetPendingObjects(peer))==0 && SOSManifestGetCount(extra)==0 &&
2474 SOSManifestGetCount(missing)==0 && SOSManifestGetCount(SOSPeerGetUnwantedManifest(peer))!=0) {
2475 secnoticeq("engine", "%@:%@: only have differences in unwanted set; lying to peer to stop sync",engine->myID, SOSPeerGetID(peer));
2476 sender = confirmed;
2477 }
2478
2479 if (!SOSMessageSetManifests(message, sender, confirmed, proposed, proposed, confirmed ? objectsSent : NULL, error)) {
2480 secnoticeq("engine", "%@:%@: failed to set message manifests",engine->myID, SOSPeerGetID(peer));
2481 CFReleaseNull(message);
2482 }
2483
2484 CFReleaseNull(objectsSent);
2485
2486 if (message) {
2487 result = SOSMessageCreateData(message, SOSPeerNextSequenceNumber(peer), error);
2488 }
2489
2490 if (result) {
2491 SOSEnginePeerMessageSentCallback* pmsc = malloc(sizeof(SOSEnginePeerMessageSentCallback));
2492 memset(pmsc, 0, sizeof(SOSEnginePeerMessageSentCallback));
2493 pmsc->engine = engine; CFRetain(pmsc->engine);
2494 pmsc->peer = CFRetainSafe(peer);
2495 pmsc->local = CFRetainSafe(local);
2496 pmsc->proposed = CFRetainSafe(proposed);
2497 pmsc->message = CFRetainSafe(message);
2498 pmsc->confirmed = CFRetainSafe(confirmed);
2499
2500 SOSEngineMessageCallbackSetCallback(pmsc, ^(bool success) {
2501 // Have to copy pmsc so it'll still be around during the dispatch_async
2502 SOSEnginePeerMessageSentCallback* pmsc2 = malloc(sizeof(SOSEnginePeerMessageSentCallback));
2503 memset(pmsc2, 0, sizeof(SOSEnginePeerMessageSentCallback));
2504 pmsc2->engine = pmsc->engine; CFRetain(pmsc2->engine);
2505 pmsc2->peer = CFRetainSafe(pmsc->peer);
2506 pmsc2->local = CFRetainSafe(pmsc->local);
2507 pmsc2->proposed = CFRetainSafe(pmsc->proposed);
2508 pmsc2->message = CFRetainSafe(pmsc->message);
2509 pmsc2->confirmed = CFRetainSafe(pmsc->confirmed);
2510
2511 dispatch_async(pmsc->engine->queue, ^{
2512 if (success) {
2513 SOSPeerSetMustSendMessage(pmsc2->peer, false);
2514 if (!pmsc2->confirmed && !pmsc2->proposed) {
2515 SOSPeerSetSendObjects(pmsc2->peer, true);
2516 secnoticeq("engine", "%@:%@ sendObjects=true L:%@", pmsc2->engine->myID, SOSPeerGetID(pmsc2->peer), pmsc2->local);
2517 }
2518 SOSPeerAddLocalManifest(pmsc2->peer, pmsc2->local);
2519 SOSPeerAddProposedManifest(pmsc2->peer, pmsc2->proposed);
2520 secnoticeq("engine", "send %@:%@ %@", pmsc2->engine->myID, SOSPeerGetID(pmsc2->peer), pmsc2->message);
2521 //SOSEngineCheckPeerIntegrity(engine, peer, NULL);
2522 } else {
2523 secerror("%@:%@ failed to send %@", pmsc2->engine->myID, SOSPeerGetID(pmsc2->peer), pmsc2->message);
2524 }
2525 SOSEngineFreeMessageCallback(pmsc2);
2526 });
2527 });
2528
2529 *sent = pmsc;
2530 }
2531
2532 CFReleaseNull(local);
2533 CFReleaseNull(extra);
2534 CFReleaseNull(missing);
2535 CFReleaseNull(message);
2536 CFReleaseNull(proposed);
2537 if (error && *error)
2538 secerror("%@:%@ error in send: %@", engine->myID, SOSPeerGetID(peer), *error);
2539
2540 return result;
2541 }
2542
2543 void SOSEngineMessageCallbackSetCallback(SOSEnginePeerMessageSentCallback *sent, SOSEnginePeerMessageSentBlock block) {
2544 if(sent) {
2545 sent->block = Block_copy(block);
2546 }
2547 }
2548
2549
2550 void SOSEngineMessageCallCallback(SOSEnginePeerMessageSentCallback *sent, bool ok) {
2551 if (sent && sent->block) {
2552 (sent->block)(ok);
2553 }
2554 }
2555
2556 void SOSEngineFreeMessageCallback(SOSEnginePeerMessageSentCallback* psmc) {
2557 if(psmc) {
2558 CFReleaseNull(psmc->engine);
2559 CFReleaseNull(psmc->peer);
2560 CFReleaseNull(psmc->coder);
2561 CFReleaseNull(psmc->local);
2562 CFReleaseNull(psmc->proposed);
2563 CFReleaseNull(psmc->message);
2564 CFReleaseNull(psmc->confirmed);
2565
2566 if(psmc->block) {
2567 Block_release(psmc->block);
2568 }
2569
2570 free(psmc);
2571 }
2572 }
2573
2574 static void SOSEngineLogItemError(SOSEngineRef engine, CFStringRef peerID, CFDataRef key, CFDataRef optionalDigest, const char *where, CFErrorRef error) {
2575 if (!optionalDigest) {
2576 const uint8_t *d = CFDataGetBytePtr(key);
2577 secwarning("%@:%@ object %02X%02X%02X%02X %s: %@", engine->myID, peerID, d[0], d[1], d[2], d[3], where, error ? (CFTypeRef)error : CFSTR(""));
2578 } else {
2579 const uint8_t *d = CFDataGetBytePtr(key);
2580 const uint8_t *e = CFDataGetBytePtr(optionalDigest);
2581 secwarning("%@:%@ object %02X%02X%02X%02X is really %02X%02X%02X%02X dropping from local manifest", engine->myID, peerID, d[0], d[1], d[2], d[3], e[0], e[1], e[2], e[3]);
2582 }
2583 }
2584
2585 static bool SOSEngineWriteToBackup_locked(SOSEngineRef engine, SOSPeerRef peer, bool rewriteComplete, bool *didWrite, bool *incomplete, CFErrorRef *error) {
2586 __block bool ok = SOSPeerWritePendingReset(peer, error);
2587 if (!ok || !SOSPeerGetKeyBag(peer))
2588 return ok;
2589 __block SOSManifestRef local = SOSEngineCopyLocalPeerManifest_locked(engine, peer, error);
2590 __block SOSManifestRef proposed = SOSPeerGetProposedManifest(peer);
2591 __block bool notify = true;
2592 SOSManifestRef pendingObjects = NULL;
2593 SOSManifestRef missing = NULL;
2594 CFStringRef peerID = SOSPeerGetID(peer);
2595
2596 ok &= SOSManifestDiff(proposed, local, &missing, &pendingObjects, error);
2597
2598 secnoticeq("engine", "%@:%@: Send state for peer [%s%s%s] O: %zu, M: %zu", engine->myID, peerID,
2599 local ? "L":"l",
2600 proposed ? "P":"0",
2601 pendingObjects ? "O":"0",
2602 SOSManifestGetCount(pendingObjects),
2603 SOSManifestGetCount(missing));
2604
2605 if (SOSManifestGetCount(missing) == 0 && SOSManifestGetCount(pendingObjects) == 0) {
2606 // proposed == local (faster test than CFEqualSafe above), since we
2607 // already did the SOSManifestDiff
2608 if (rewriteComplete) {
2609 notify = false;
2610 } else {
2611 secnoticeq("engine", "%@:%@ backup still done", engine->myID, peer);
2612 goto done;
2613 }
2614 }
2615 ok &= SOSPeerAppendToJournal(peer, error, ^(FILE *journalFile, keybag_handle_t kbhandle) {
2616 SOSManifestRef objectsSent = NULL;
2617 __block struct SOSDigestVector dvdel = SOSDigestVectorInit;
2618 __block struct SOSDigestVector dvadd = SOSDigestVectorInit;
2619 SOSManifestForEach(missing, ^(CFDataRef key, bool *stop) {
2620 CFErrorRef localError = NULL;
2621 if (ftello(journalFile) > kSOSBackupMaxFileSize) {
2622 // Highwatermark hit on file.
2623 *stop = true;
2624 } else if (SOSBackupEventWriteDelete(journalFile, key, &localError)) {
2625 SOSDigestVectorAppend(&dvdel, CFDataGetBytePtr(key));
2626 } else {
2627 SOSEngineLogItemError(engine, peerID, key, NULL, "in SOSPeerWriteDelete", localError);
2628 CFErrorPropagate(localError, error);
2629 // TODO: Update of missing so proposed is updated properly
2630 *stop = true; // Disk full?
2631 ok = false;
2632 }
2633 });
2634 if (ok && SOSManifestGetCount(pendingObjects)) {
2635 CFMutableArrayRef changes = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2636 ok &= SOSDataSourceForEachObject(engine->dataSource, NULL, pendingObjects, error, ^void(CFDataRef key, SOSObjectRef object, bool *stop) {
2637 CFErrorRef localError = NULL;
2638 CFDataRef digest = NULL;
2639 CFDictionaryRef backupItem = NULL;
2640 if (ftello(journalFile) > kSOSBackupMaxFileSize) {
2641 // Highwatermark hit on file.
2642 *stop = true;
2643 } else if (!object) {
2644 SOSEngineLogItemError(engine, peerID, key, NULL, "dropping from manifest: not found in datasource", localError);
2645 SOSChangesAppendDelete(changes, key);
2646 } else if (!(backupItem = SOSObjectCopyBackup(engine->dataSource, object, kbhandle, &localError))
2647 || !(digest = SOSObjectCopyDigest(engine->dataSource, object, &localError))) {
2648 if (SecErrorGetOSStatus(localError) == errSecDecode) {
2649 // Decode error, we need to drop these objects from our manifests
2650 SOSEngineLogItemError(engine, peerID, key, NULL, "dropping from manifest", localError);
2651 SOSChangesAppendDelete(changes, key);
2652 CFRelease(localError);
2653 } else {
2654 // Stop iterating and propagate out all other errors.
2655 SOSEngineLogItemError(engine, peerID, key, NULL, "in SOSDataSourceForEachObject", localError);
2656 *stop = true;
2657 CFErrorPropagate(localError, error);
2658 ok = false;
2659 }
2660 } else {
2661 if (!CFEqual(key, digest)) {
2662 SOSEngineLogItemError(engine, peerID, key, digest, "", NULL);
2663 SOSChangesAppendDelete(changes, key);
2664 SOSChangesAppendAdd(changes, object); // This is new behaviour but we think it's more correct
2665 }
2666
2667 if (SOSBackupEventWriteAdd(journalFile, backupItem, &localError)) {
2668 SOSDigestVectorAppend(&dvadd, CFDataGetBytePtr(digest));
2669 } else {
2670 SOSEngineLogItemError(engine, peerID, key, NULL, "in SOSPeerWriteAdd", localError);
2671 *stop = true; // Disk full?
2672 CFErrorPropagate(localError, error);
2673 ok = false;
2674 }
2675 }
2676 CFReleaseSafe(backupItem);
2677 CFReleaseSafe(digest);
2678 });
2679 if (CFArrayGetCount(changes)) {
2680 CFErrorRef localError = NULL;
2681 if (!SOSEngineUpdateChanges_locked(engine, NULL, kSOSDataSourceTransactionDidCommit, kSOSDataSourceSOSTransaction, changes, &localError))
2682 secerror("SOSEngineUpdateChanges_locked: %@ failed: %@", changes, localError);
2683 CFReleaseSafe(localError);
2684 // Since calling SOSEngineUpdateChanges_locked might cause local to change and might cause the backup peer to update proposed, refetch them here.
2685 CFAssignRetained(local, SOSEngineCopyLocalPeerManifest_locked(engine, peer, error));
2686 proposed = SOSPeerGetProposedManifest(peer);
2687 }
2688 CFReleaseSafe(changes);
2689 }
2690
2691 if (dvadd.count || (proposed && dvdel.count)) {
2692 *didWrite = true;
2693 SOSManifestRef deleted = SOSManifestCreateWithDigestVector(&dvdel, error);
2694 SOSManifestRef objectsSent = SOSManifestCreateWithDigestVector(&dvadd, error);
2695 SOSManifestRef newProposed = SOSManifestCreateWithPatch(proposed, deleted, objectsSent, error);
2696 CFReleaseSafe(deleted);
2697 CFReleaseSafe(objectsSent);
2698 SOSPeerSetProposedManifest(peer, newProposed);
2699 CFReleaseSafe(newProposed);
2700 proposed = SOSPeerGetProposedManifest(peer);
2701 }
2702 SOSDigestVectorFree(&dvdel);
2703 SOSDigestVectorFree(&dvadd);
2704
2705 // TODO: If proposed is NULL, and local is empty we should still consider ourselves done.
2706 // It so happens this can't happen in practice today since there is at least a backupbag
2707 // in the backup, but this is a bug waiting to rear its head in the future.
2708 if (ok && CFEqualSafe(local, proposed)) {
2709 CFErrorRef localError = NULL;
2710 if (SOSBackupEventWriteCompleteMarker(journalFile, 899, &localError)) {
2711 SOSPeerSetSendObjects(peer, true);
2712 *didWrite = true;
2713 secnoticeq("backup", "%@:%@ backup done%s", engine->myID, peerID, notify ? " notifying sbd" : "");
2714 // TODO: Now switch to changes based writing to backup sync.
2715 // Currently we leave changes enabled but we probably shouldn't
2716 } else {
2717 secwarning("%@:%@ in SOSBackupPeerWriteCompleteMarker: %@", engine->myID, peerID, localError);
2718 ok = false;
2719 *incomplete = true;
2720 CFErrorPropagate(localError, error);
2721 }
2722 } else {
2723 secnoticeq("backup", "%@:%@ backup incomplete [%zu/%zu]%s", engine->myID, peerID, SOSManifestGetCount(local), SOSManifestGetCount(proposed), notify ? " notifying sbd" : "");
2724 *incomplete = true;
2725 }
2726 CFReleaseNull(objectsSent);
2727 });
2728 if (notify)
2729 SOSBackupPeerPostNotification("writing changes to backup");
2730
2731 done:
2732 CFReleaseSafe(local);
2733 CFReleaseNull(pendingObjects);
2734 CFReleaseNull(missing);
2735
2736 return ok;
2737 }
2738
2739 CF_RETURNS_RETAINED CFSetRef SOSEngineSyncWithBackupPeers(SOSEngineRef engine, CFSetRef /* CFStringRef */ peers, bool forceReset, CFErrorRef *error)
2740 {
2741 __block bool incomplete = false;
2742 CFMutableSetRef handledSet = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
2743
2744 bool ok = SOSEngineDoTxnOnQueue(engine, error, ^(SOSTransactionRef txn, bool *commit) {
2745 __block bool dirty = false;
2746 CFSetForEach(peers, ^(const void *value) {
2747 bool report_handled = true;
2748 CFErrorRef localError = NULL;
2749 SOSPeerRef peer = NULL;
2750 CFStringRef peerID = asString(value, &localError);
2751 require_action_quiet(peerID, done, report_handled = false);
2752
2753 peer = SOSEngineCopyPeerWithID_locked(engine, peerID, &localError);
2754 require_quiet(peerID, done);
2755
2756 if (SOSPeerMapEntryIsBackup(peer)) {
2757 if(forceReset) {
2758 SOSPeerSetMustSendMessage(peer, true);
2759 }
2760
2761 report_handled = SOSEngineWriteToBackup_locked(engine, peer, false, &dirty, &incomplete, &localError);
2762 }
2763
2764 done:
2765 if (localError) {
2766 secnotice("engine-sync", "Failed to process sync for %@: %@", peerID, localError);
2767 }
2768 if (report_handled) {
2769 CFSetAddValue(handledSet, peerID);
2770 }
2771 CFReleaseNull(localError);
2772 CFReleaseNull(peer);
2773 });
2774
2775 if (dirty) {
2776 CFErrorRef saveError = NULL;
2777 if (!SOSEngineSave(engine, txn, &saveError)) {
2778 secnotice("engine-save", "Failed to save engine: %@", saveError);
2779 }
2780 }
2781 });
2782 if (incomplete) {
2783 // Ensure we get called again in a while (after a backup timeout)
2784 // sbd will do this since we never wrote a complete marker.
2785 // TODO: This relies on us not writing complete marker for update
2786 // event while we havn't finished a full backup, which we currently still do.
2787 }
2788 if (!ok)
2789 CFReleaseNull(handledSet);
2790
2791 return handledSet;
2792 }
2793
2794 bool SOSEngineHandleMessage(SOSEngineRef engine, CFStringRef peerID,
2795 CFDataRef raw_message, CFErrorRef *error)
2796 {
2797 __block bool result = true;
2798 __block bool somethingChanged = false;
2799 SOSMessageRef message = SOSMessageCreateWithData(kCFAllocatorDefault, raw_message, error);
2800 result &= message && SOSEngineDoTxnOnQueue(engine, error, ^(SOSTransactionRef txn, bool *commit) {
2801 result = SOSEngineHandleMessage_locked(engine, peerID, message, txn, commit, &somethingChanged, error);
2802 });
2803 CFReleaseSafe(message);
2804 if (somethingChanged)
2805 SecKeychainChanged();
2806 return result;
2807 }
2808
2809 void SOSEngineCircleChanged(SOSEngineRef engine, CFStringRef myPeerID, CFArrayRef trustedPeers, CFArrayRef untrustedPeers) {
2810 __block bool peersOrViewsChanged = false;
2811 SOSEngineDoOnQueue(engine, ^{
2812 peersOrViewsChanged = SOSEngineCircleChanged_locked(engine, myPeerID, trustedPeers, untrustedPeers);
2813
2814 // We should probably get a more precise list of peers that actually need talking to
2815 if (peersOrViewsChanged && engine->myID && CFArrayGetCount(engine->peerIDs) != 0)
2816 SOSCCRequestSyncWithPeersList(engine->peerIDs);
2817 });
2818
2819 __block bool ok = true;
2820 __block CFErrorRef localError = NULL;
2821 ok &= SOSEngineDoTxnOnQueue(engine, &localError, ^(SOSTransactionRef txn, bool *commit) {
2822 ok = *commit = SOSEngineSave(engine, txn, &localError);
2823 });
2824 if (!ok) {
2825 secerror("failed to save engine state: %@", localError);
2826 CFReleaseSafe(localError);
2827 }
2828
2829 }
2830
2831 SOSManifestRef SOSEngineCopyManifest(SOSEngineRef engine, CFErrorRef *error) {
2832 __block SOSManifestRef result = NULL;
2833 SOSEngineDoOnQueue(engine, ^{
2834 result = SOSEngineCopyManifestWithViewNameSet_locked(engine, SOSViewsGetV0ViewSet(), error);
2835 });
2836 return result;
2837 }
2838
2839 SOSManifestRef SOSEngineCopyLocalPeerManifest(SOSEngineRef engine, SOSPeerRef peer, CFErrorRef *error) {
2840 __block SOSManifestRef result = NULL;
2841 SOSEngineDoOnQueue(engine, ^{
2842 result = SOSEngineCopyLocalPeerManifest_locked(engine, peer, error);
2843 });
2844 return result;
2845 }
2846
2847 bool SOSEngineUpdateChanges(SOSEngineRef engine, SOSDataSourceTransactionSource source, CFArrayRef changes, CFErrorRef *error) {
2848 __block bool result = true;
2849 SOSEngineDoOnQueue(engine, ^{
2850 result = SOSEngineUpdateChanges_locked(engine, NULL, kSOSDataSourceTransactionDidCommit, source, changes, error);
2851 });
2852 return result;
2853 }
2854
2855 //
2856 // Peer state layout. WRONG! It's an array now
2857 // The peer state is an array.
2858 // The first element of the array is a dictionary with any number of keys and
2859 // values in it (for future expansion) such as changing the digest size or type
2860 // or remebering boolean flags for a peers sake.
2861 // The next three are special in that they are manifest digests with special
2862 // meaning and rules as to how they are treated (These are dynamically updated
2863 // based on database activity so they have a fully history of all changes made
2864 // to the local db. The first is the manifest representing the pendingObjects
2865 // to send to the other peer. This is normally only ever appending to, and in
2866 // particular with transactions originating from the Keychain API that affect
2867 // syncable items will need to add the new objects digests to the pendingObjects list
2868 // while adding the digests of any tombstones encountered to the extra list.
2869
2870 SOSPeerRef SOSEngineCopyPeerWithID(SOSEngineRef engine, CFStringRef peer_id, CFErrorRef *error) {
2871 __block SOSPeerRef peer = NULL;
2872 SOSEngineDoOnQueue(engine, ^{
2873 peer = SOSEngineCopyPeerWithID_locked(engine, peer_id, error);
2874 });
2875 return peer;
2876 }
2877
2878 bool SOSEngineForPeerID(SOSEngineRef engine, CFStringRef peerID, CFErrorRef *error, void (^forPeer)(SOSTransactionRef txn, SOSPeerRef peer)) {
2879 __block bool ok = true;
2880 SOSDataSourceReadWithCommitQueue(engine->dataSource, error, ^(SOSTransactionRef txn) {
2881 SOSEngineDoOnQueue(engine, ^{
2882 SOSPeerRef peer = SOSEngineCopyPeerWithID_locked(engine, peerID, error);
2883 if (peer) {
2884 forPeer(txn, peer);
2885 CFRelease(peer);
2886 } else {
2887 ok = false;
2888 }
2889 });
2890 });
2891
2892 return ok;
2893 }
2894
2895 bool SOSEngineWithPeerID(SOSEngineRef engine, CFStringRef peerID, CFErrorRef *error, void (^with)(SOSPeerRef peer, SOSCoderRef coder, SOSDataSourceRef dataSource, SOSTransactionRef txn, bool *forceSaveState)) {
2896 __block bool result = true;
2897 result &= SOSEngineDoTxnOnQueue(engine, error, ^(SOSTransactionRef txn, bool *commit) {
2898 SOSPeerRef peer = SOSEngineCopyPeerWithID_locked(engine, peerID, error);
2899 if (!peer) {
2900 result = SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("Engine has no peer for %@"), peerID);
2901 } else {
2902 bool saveState = false;
2903 SOSCoderRef coder = SOSEngineGetCoderInTx_locked(engine, txn, peerID, error);
2904 with(peer, coder, engine->dataSource, txn, &saveState);
2905 CFReleaseSafe(peer);
2906 if (saveState)
2907 result = SOSEngineSave(engine, txn, error);
2908 // TODO: Don't commit if engineSave fails?
2909 }
2910 });
2911
2912 return result;
2913 }
2914
2915 CFDataRef SOSEngineCreateMessageToSyncToPeer(SOSEngineRef engine, CFStringRef peerID, CFMutableArrayRef *attributeList, SOSEnginePeerMessageSentCallback **sentCallback, CFErrorRef *error){
2916 __block CFDataRef message = NULL;
2917 SOSEngineForPeerID(engine, peerID, error, ^(SOSTransactionRef txn, SOSPeerRef peer) {
2918 message = SOSEngineCreateMessage_locked(engine, txn, peer, attributeList, error, sentCallback);
2919 });
2920 return message;
2921 }
2922
2923 bool SOSEnginePeerDidConnect(SOSEngineRef engine, CFStringRef peerID, CFErrorRef *error) {
2924 return SOSEngineWithPeerID(engine, peerID, error, ^(SOSPeerRef peer, SOSCoderRef coder, SOSDataSourceRef dataSource, SOSTransactionRef txn, bool *saveState) {
2925 *saveState = SOSPeerDidConnect(peer);
2926 });
2927 }
2928
2929 bool SOSEngineSetPeerConfirmedManifest(SOSEngineRef engine, CFStringRef backupName,
2930 CFDataRef keybagDigest, CFDataRef manifestData, CFErrorRef *error) {
2931 __block bool ok = true;
2932
2933 ok &= SOSEngineForPeerID(engine, backupName, error, ^(SOSTransactionRef txn, SOSPeerRef peer) {
2934 bool dirty = false;
2935 bool incomplete = false;
2936 SOSManifestRef confirmed = NULL;
2937 CFDataRef keybag = SOSPeerGetKeyBag(peer);
2938 CFDataRef computedKeybagDigest = keybag ? CFDataCopySHA1Digest(keybag, NULL) : NULL;
2939 if (CFEqualSafe(keybagDigest, computedKeybagDigest)) {
2940 ok = confirmed = SOSManifestCreateWithData(manifestData, error);
2941 if (ok) {
2942 // Set both confirmed and proposed (confirmed is just
2943 // for debug status, proposed is actually what's used
2944 // by the backup peer).
2945 SOSPeerSetConfirmedManifest(peer, confirmed);
2946 SOSPeerSetProposedManifest(peer, confirmed);
2947 }
2948 } else {
2949 // sbd missed a reset event, send it again
2950 // Force SOSEngineWriteToBackup_locked to call SOSPeerWriteReset, which clears
2951 // confirmed and proposed manifests and writes the keybag to the journal.
2952 SOSPeerSetMustSendMessage(peer, true);
2953 }
2954
2955 // Stop changes from writing complete markers, unless SOSEngineWriteToBackup_locked() detects we are in sync
2956 SOSPeerSetSendObjects(peer, false);
2957 // Write data for this peer if we can, technically not needed for non legacy protocol support all the time.
2958 ok = SOSEngineWriteToBackup_locked(engine, peer, true, &dirty, &incomplete, error);
2959
2960 if (!ok && error && SecErrorGetOSStatus(*error) == errSecInteractionNotAllowed) {
2961 SOSEnsureBackupWhileUnlocked();
2962 }
2963
2964 CFReleaseSafe(confirmed);
2965 CFReleaseSafe(computedKeybagDigest);
2966 });
2967 return ok;
2968 }
2969
2970 CFArrayRef SOSEngineCopyBackupPeerNames(SOSEngineRef engine, CFErrorRef *error) {
2971 __block CFMutableArrayRef backupNames = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2972 SOSEngineForEachBackupPeer(engine, ^(SOSPeerRef peer) {
2973 CFArrayAppendValue(backupNames, SOSPeerGetID(peer));
2974 });
2975 return backupNames;
2976 }
2977
2978 static CFMutableDictionaryRef SOSEngineCreateStateDictionary(CFStringRef peerID, SOSManifestRef manifest, CFSetRef vns, CFStringRef coderString) {
2979 CFNumberRef manifestCount = CFNumberCreateWithCFIndex(kCFAllocatorDefault, SOSManifestGetCount(manifest));
2980 CFDataRef manifestHash = SOSManifestGetDigest(manifest, NULL);
2981 CFMutableDictionaryRef result = CFDictionaryCreateMutableForCFTypesWithSafe(kCFAllocatorDefault,
2982 kSOSCCEngineStatePeerIDKey, peerID,
2983 kSOSCCEngineStateManifestCountKey, manifestCount,
2984 kSOSCCEngineStateManifestHashKey, manifestHash,
2985 kSOSCCEngineStateSyncSetKey, asSet(vns, NULL),
2986 kSOSCCEngineStateCoderKey, coderString,
2987 NULL);
2988 CFReleaseNull(manifestCount);
2989 return result;
2990 }
2991
2992 static void SOSEngineAppendStateDictionary(CFMutableArrayRef stateArray, CFStringRef peerID, SOSManifestRef manifest, CFSetRef vns, CFStringRef coderString) {
2993 CFMutableDictionaryRef newState = SOSEngineCreateStateDictionary(peerID, manifest, vns, coderString);
2994 CFArrayAppendValue(stateArray, newState);
2995 CFReleaseNull(newState);
2996 }
2997
2998 static CFArrayRef SOSEngineCopyPeerConfirmedDigests_locked(SOSEngineRef engine, CFErrorRef *error) {
2999 CFMutableArrayRef result = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
3000 CFDictionaryForEach(engine->viewNameSet2ChangeTracker, ^(const void *vns, const void *ct) {
3001 SOSManifestRef manifest = SOSEngineCopyManifestWithViewNameSet_locked(engine, vns, error);
3002 SOSEngineAppendStateDictionary(result, NULL, manifest, vns, NULL);
3003 CFReleaseNull(manifest);
3004 });
3005
3006 // Copy other peers even if we aren't in the circle, since we're observing it.
3007 SOSEngineForEachPeer_locked(engine, ^(SOSPeerRef peer) {
3008 CFTypeRef coderObject = engine->coders ? CFDictionaryGetValue(engine->coders, SOSPeerGetID(peer)) : CFSTR("Coders not loaded.");
3009 CFStringRef coderState = coderObject ? CFCopyDescription(coderObject) : NULL;
3010 SOSEngineAppendStateDictionary(result, SOSPeerGetID(peer), SOSPeerGetConfirmedManifest(peer), SOSPeerGetViewNameSet(peer), coderState);
3011 CFReleaseNull(coderState);
3012 });
3013 return result;
3014 }
3015
3016 CFArrayRef SOSEngineCopyPeerConfirmedDigests(SOSEngineRef engine, CFErrorRef *error) {
3017 __block CFArrayRef result = NULL;
3018 SOSEngineDoOnQueue(engine, ^{
3019 result = SOSEngineCopyPeerConfirmedDigests_locked(engine, error);
3020 });
3021 return result;
3022 }
3023
3024 SOSDataSourceRef SOSEngineGetDataSource(SOSEngineRef engine) {
3025 return engine->dataSource;
3026 }
3027
3028 #define ENGINELOGSTATE "engineLogState"
3029 void SOSEngineLogState(SOSEngineRef engine) {
3030 CFErrorRef error = NULL;
3031 CFArrayRef confirmedDigests = NULL;
3032
3033 secnotice(ENGINELOGSTATE, "Start");
3034
3035 require_action_quiet(engine, retOut, secnotice(ENGINELOGSTATE, "No Engine Available"));
3036 confirmedDigests = SOSEngineCopyPeerConfirmedDigests(engine, &error);
3037 require_action_quiet(confirmedDigests, retOut, secnotice(ENGINELOGSTATE, "No engine peers: %@\n", error));
3038
3039 SOSCCForEachEngineStateAsStringFromArray(confirmedDigests, ^(CFStringRef onePeerDescription) {
3040 secnotice(ENGINELOGSTATE, "%@", onePeerDescription);
3041 });
3042
3043 retOut:
3044 CFReleaseNull(error);
3045 CFReleaseNull(confirmedDigests);
3046 secnotice(ENGINELOGSTATE, "Finish");
3047
3048 return;
3049 }
3050
3051 //For Testing
3052 void TestSOSEngineDoOnQueue(CFTypeRef engine, dispatch_block_t action)
3053 {
3054 dispatch_sync(((SOSEngineRef)engine)->queue, action);
3055 }
3056 CFMutableDictionaryRef TestSOSEngineGetCoders(CFTypeRef engine){
3057 return ((SOSEngineRef)engine)->coders;
3058 }
3059
3060 bool TestSOSEngineDoTxnOnQueue(CFTypeRef engine, CFErrorRef *error, void(^transaction)(SOSTransactionRef txn, bool *commit))
3061 {
3062 return SOSDataSourceWithCommitQueue(((SOSEngineRef)engine)->dataSource, error, ^(SOSTransactionRef txn, bool *commit) {
3063 TestSOSEngineDoOnQueue((SOSEngineRef)engine, ^{ transaction(txn, commit); });
3064 });
3065 }
3066 bool SOSEngineGetCodersNeedSaving(SOSEngineRef engine){
3067 return engine->codersNeedSaving;
3068 }
3069
3070 void SOSEngineSetCodersNeedSaving(SOSEngineRef engine, bool saved){
3071 engine->codersNeedSaving = saved;
3072 }
3073