-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCFXMLPreferencesDomain.c
549 lines (490 loc) · 22.7 KB
/
CFXMLPreferencesDomain.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/*
* Copyright (c) 2008-2012 Brent Fulgham <bfulgham@gmail.org>. All rights reserved.
*
* This source code is a modified version of the CoreFoundation sources released by Apple Inc. under
* the terms of the APSL version 2.0 (see below).
*
* For information about changes from the original Apple source release can be found by reviewing the
* source control system for the project at https://sourceforge.net/svn/?group_id=246198.
*
* The original license information is as follows:
*
* Copyright (c) 2011 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* CFXMLPreferencesDomain.c
Copyright (c) 1998-2011, Apple Inc. All rights reserved.
Responsibility: David Smith
*/
#include <CoreFoundation/CFPreferences.h>
#include <CoreFoundation/CFURLAccess.h>
#include <CoreFoundation/CFPropertyList.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFDate.h>
#include <CoreFoundation/CoreFoundation_Prefix.h>
#include "CFInternal.h"
#include <time.h>
#if DEPLOYMENT_TARGET_MACOSX
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <mach/mach.h>
#include <mach/mach_syscalls.h>
#endif
Boolean __CFPreferencesShouldWriteXML(void);
typedef struct {
CFMutableDictionaryRef _domainDict; // Current value of the domain dictionary
CFMutableArrayRef _dirtyKeys; // The array of keys which must be synchronized
CFAbsoluteTime _lastReadTime; // The last time we synchronized with the disk
CFSpinLock_t _lock; // Lock for accessing fields in the domain
Boolean _isWorldReadable; // HACK - this is because we have no good way to propogate the kCFPreferencesAnyUser information from the upper level CFPreferences routines REW, 1/13/00
char _padding[3];
} _CFXMLPreferencesDomain;
static void *createXMLDomain(CFAllocatorRef allocator, CFTypeRef context);
static void freeXMLDomain(CFAllocatorRef allocator, CFTypeRef context, void *tDomain);
static CFTypeRef fetchXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef key);
static void writeXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef key, CFTypeRef value);
static Boolean synchronizeXMLDomain(CFTypeRef context, void *xmlDomain);
static void getXMLKeysAndValues(CFAllocatorRef alloc, CFTypeRef context, void *xmlDomain, void **buf[], CFIndex *numKeyValuePairs);
static CFDictionaryRef copyXMLDomainDictionary(CFTypeRef context, void *domain);
static void setXMLDomainIsWorldReadable(CFTypeRef context, void *domain, Boolean isWorldReadable);
__private_extern__ const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks = {createXMLDomain, freeXMLDomain, fetchXMLValue, writeXMLValue, synchronizeXMLDomain, getXMLKeysAndValues, copyXMLDomainDictionary, setXMLDomainIsWorldReadable};
// Directly ripped from Foundation....
static void __CFMilliSleep(uint32_t msecs) {
#if DEPLOYMENT_TARGET_WINDOWS
SleepEx(msecs, false);
#elif defined(__svr4__) || defined(__hpux__)
sleep((msecs + 900) / 1000);
#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
struct timespec input;
input.tv_sec = msecs / 1000;
input.tv_nsec = (msecs - input.tv_sec * 1000) * 1000000;
nanosleep(&input, NULL);
#else
#error Dont know how to define sleep for this platform
#endif
}
static CFSpinLock_t _propDictLock = CFSpinLockInit; // Annoying that we need this, but otherwise we have a multithreading risk
CF_INLINE CFDictionaryRef URLPropertyDictForPOSIXMode(SInt32 mode) {
static CFMutableDictionaryRef _propertyDict = NULL;
CFNumberRef num = CFNumberCreate(__CFPreferencesAllocator(), kCFNumberSInt32Type, &mode);
__CFSpinLock(&_propDictLock);
if (!_propertyDict) {
_propertyDict = CFDictionaryCreateMutable(__CFPreferencesAllocator(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
CFDictionarySetValue(_propertyDict, kCFURLFilePOSIXMode, num);
CFRelease(num);
return _propertyDict;
}
CF_INLINE void URLPropertyDictRelease(void) {
__CFSpinUnlock(&_propDictLock);
}
// Asssumes caller already knows the directory doesn't exist.
static Boolean _createDirectory(CFURLRef dirURL, Boolean worldReadable) {
CFAllocatorRef alloc = __CFPreferencesAllocator();
CFURLRef parentURL = CFURLCreateCopyDeletingLastPathComponent(alloc, dirURL);
CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
Boolean parentExists = (val && CFBooleanGetValue(val));
SInt32 mode;
Boolean result;
if (val) CFRelease(val);
if (!parentExists) {
CFStringRef path = CFURLCopyPath(parentURL);
if (!CFEqual(path, CFSTR("/"))) {
_createDirectory(parentURL, worldReadable);
val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
parentExists = (val && CFBooleanGetValue(val));
if (val) CFRelease(val);
}
CFRelease(path);
}
if (parentURL) CFRelease(parentURL);
if (!parentExists) return false;
#if DEPLOYMENT_TARGET_MACOSX
mode = worldReadable ? S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH : S_IRWXU;
#else
mode = 0666;
#endif
result = CFURLWriteDataAndPropertiesToResource(dirURL, (CFDataRef)dirURL, URLPropertyDictForPOSIXMode(mode), NULL);
URLPropertyDictRelease();
return result;
}
/* XML - context is the CFURL where the property list is stored on disk; domain is an _CFXMLPreferencesDomain */
static void *createXMLDomain(CFAllocatorRef allocator, CFTypeRef context) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain*) CFAllocatorAllocate(allocator, sizeof(_CFXMLPreferencesDomain), 0);
domain->_lastReadTime = 0.0;
domain->_domainDict = NULL;
domain->_dirtyKeys = CFArrayCreateMutable(allocator, 0, & kCFTypeArrayCallBacks);
const CFSpinLock_t lock = CFSpinLockInit;
domain->_lock = lock;
domain->_isWorldReadable = false;
return domain;
}
static void freeXMLDomain(CFAllocatorRef allocator, CFTypeRef context, void *tDomain) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)tDomain;
if (domain->_domainDict) CFRelease(domain->_domainDict);
if (domain->_dirtyKeys) CFRelease(domain->_dirtyKeys);
CFAllocatorDeallocate(allocator, domain);
}
// Assumes the domain has already been locked
static void _loadXMLDomainIfStale(CFURLRef url, _CFXMLPreferencesDomain *domain) {
CFAllocatorRef alloc = __CFPreferencesAllocator();
int idx;
if (domain->_domainDict) {
CFDateRef modDate;
CFAbsoluteTime modTime;
CFURLRef testURL = url;
if (CFDictionaryGetCount(domain->_domainDict) == 0) {
// domain never existed; check the parent directory, not the child
testURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR(".."), kCFURLPOSIXPathStyle, true, url);
}
modDate = (CFDateRef )CFURLCreatePropertyFromResource(alloc, testURL, kCFURLFileLastModificationTime, NULL);
modTime = modDate ? CFDateGetAbsoluteTime(modDate) : 0.0;
// free before possible return. we can test non-NULL of modDate but don't depend on contents after this.
if (testURL != url) CFRelease(testURL);
if (modDate) CFRelease(modDate);
if (modDate != NULL && modTime < domain->_lastReadTime) { // We're up-to-date
return;
}
}
// We're out-of-date; destroy domainDict and reload
if (domain->_domainDict) {
CFRelease(domain->_domainDict);
domain->_domainDict = NULL;
}
// We no longer lock on read; instead, we assume parse failures are because someone else is writing the file, and just try to parse again. If we fail 3 times in a row, we assume the file is corrupted. REW, 7/13/99
for (idx = 0; idx < 3; idx ++) {
CFDataRef data;
if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &data, NULL, NULL, NULL) || !data) {
// Either a file system error (so we can't read the file), or an empty (or perhaps non-existant) file
domain->_domainDict = CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
break;
} else {
CFTypeRef pList = CFPropertyListCreateFromXMLData(alloc, data, kCFPropertyListImmutable, NULL);
CFRelease(data);
if (pList && CFGetTypeID(pList) == CFDictionaryGetTypeID()) {
domain->_domainDict = CFDictionaryCreateMutableCopy(alloc, 0, (CFDictionaryRef)pList);
CFRelease(pList);
break;
} else if (pList) {
CFRelease(pList);
}
// Assume the file is being written; sleep for a short time (to allow the write to complete) then re-read
__CFMilliSleep(150);
}
}
if (!domain->_domainDict) {
// Failed to ever load
domain->_domainDict = CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
domain->_lastReadTime = CFAbsoluteTimeGetCurrent();
}
static CFTypeRef fetchXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef key) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
CFTypeRef result;
// Never reload if we've looked at the file system within the last 5 seconds.
__CFSpinLock(&domain->_lock);
if (domain->_domainDict == NULL) _loadXMLDomainIfStale((CFURLRef )context, domain);
result = CFDictionaryGetValue(domain->_domainDict, key);
if (result) CFRetain(result);
__CFSpinUnlock(&domain->_lock);
return result;
}
#if DEPLOYMENT_TARGET_MACOSX
#include <sys/fcntl.h>
/* __CFWriteBytesToFileWithAtomicity is a "safe save" facility. Write the bytes using the specified mode on the file to the provided URL. If the atomic flag is true, try to do it in a fashion that will enable a safe save.
*/
static Boolean __CFWriteBytesToFileWithAtomicity(CFURLRef url, const void *bytes, int length, SInt32 mode, Boolean atomic) {
int fd = -1;
char auxPath[CFMaxPathSize + 16];
char cpath[CFMaxPathSize];
uid_t owner = getuid();
gid_t group = getgid();
Boolean writingFileAsRoot = ((getuid() != geteuid()) && (geteuid() == 0));
if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)cpath, CFMaxPathSize)) {
return false;
}
if (-1 == mode || writingFileAsRoot) {
struct stat statBuf;
if (0 == stat(cpath, &statBuf)) {
mode = statBuf.st_mode;
owner = statBuf.st_uid;
group = statBuf.st_gid;
} else {
mode = 0664;
if (writingFileAsRoot && (0 == strncmp(cpath, "/Library/Preferences", 20))) {
owner = geteuid();
group = 80;
}
}
}
if (atomic) {
CFURLRef dir = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, url);
CFURLRef tempFile = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, dir, CFSTR("cf#XXXXX"), false);
CFRelease(dir);
if (!CFURLGetFileSystemRepresentation(tempFile, true, (uint8_t *)auxPath, CFMaxPathSize)) {
CFRelease(tempFile);
return false;
}
CFRelease(tempFile);
fd = mkstemp(auxPath);
} else {
fd = open(cpath, O_WRONLY|O_CREAT|O_TRUNC, mode);
}
if (fd < 0) return false;
if (length && (write(fd, bytes, length) != length || fsync(fd) < 0)) {
int saveerr = thread_errno();
close(fd);
if (atomic)
unlink(auxPath);
thread_set_errno(saveerr);
return false;
}
close(fd);
if (atomic) {
// preserve the mode as passed in originally
chmod(auxPath, mode);
if (0 != rename(auxPath, cpath)) {
unlink(auxPath);
return false;
}
// If the file was renamed successfully and we wrote it as root we need to reset the owner & group as they were.
if (writingFileAsRoot) {
chown(cpath, owner, group);
}
}
return true;
}
#endif
// domain should already be locked.
static Boolean _writeXMLFile(CFURLRef url, CFMutableDictionaryRef dict, Boolean isWorldReadable, Boolean *tryAgain) {
Boolean success = false;
CFAllocatorRef alloc = __CFPreferencesAllocator();
*tryAgain = false;
if (CFDictionaryGetCount(dict) == 0) {
// Destroy the file
CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
if (val && CFBooleanGetValue(val)) {
success = CFURLDestroyResource(url, NULL);
} else {
success = true;
}
if (val) CFRelease(val);
} else {
CFPropertyListFormat desiredFormat = __CFPreferencesShouldWriteXML() ? kCFPropertyListXMLFormat_v1_0 : kCFPropertyListBinaryFormat_v1_0;
CFDataRef data = CFPropertyListCreateData(alloc, dict, desiredFormat, 0, NULL);
if (data) {
SInt32 mode;
#if DEPLOYMENT_TARGET_MACOSX
mode = isWorldReadable ? S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH : S_IRUSR|S_IWUSR;
#else
mode = 0666;
#endif
#if DEPLOYMENT_TARGET_MACOSX
{ // Try quick atomic way first, then fallback to slower ways and error cases
CFStringRef scheme = CFURLCopyScheme(url);
if (!scheme) {
*tryAgain = false;
CFRelease(data);
return false;
} else if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
SInt32 length = CFDataGetLength(data);
const void *bytes = (0 == length) ? (const void *)"" : CFDataGetBytePtr(data);
Boolean atomicWriteSuccess = __CFWriteBytesToFileWithAtomicity(url, bytes, length, mode, true);
if (atomicWriteSuccess) {
CFRelease(scheme);
*tryAgain = false;
CFRelease(data);
return true;
}
if (!atomicWriteSuccess && thread_errno() == ENOSPC) {
CFRelease(scheme);
*tryAgain = false;
CFRelease(data);
return false;
}
}
CFRelease(scheme);
}
#endif
success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
URLPropertyDictRelease();
if (success) {
CFDataRef readData;
if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &readData, NULL, NULL, NULL) || !CFEqual(readData, data)) {
success = false;
*tryAgain = true;
}
if (readData) CFRelease(readData);
} else {
CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL);
if (!val || !CFBooleanGetValue(val)) {
CFURLRef tmpURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR("."), kCFURLPOSIXPathStyle, true, url); // Just "." because url is not a directory URL
CFURLRef parentURL = tmpURL ? CFURLCopyAbsoluteURL(tmpURL) : NULL;
if (tmpURL) CFRelease(tmpURL);
if (val) CFRelease(val);
val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL);
if ((!val || !CFBooleanGetValue(val)) && _createDirectory(parentURL, isWorldReadable)) {
// parent directory didn't exist; now it does; try again to write
success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL);
URLPropertyDictRelease();
if (success) {
CFDataRef rdData;
if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &rdData, NULL, NULL, NULL) || !CFEqual(rdData, data)) {
success = false;
*tryAgain = true;
}
if (rdData) CFRelease(rdData);
}
}
if (parentURL) CFRelease(parentURL);
}
if (val) CFRelease(val);
}
CFRelease(data);
} else {
// ??? This should never happen
CFLog(__kCFLogAssertion, CFSTR("Could not generate XML data for property list"));
success = false;
}
}
return success;
}
static void writeXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef key, CFTypeRef value) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
const void *existing = NULL;
__CFSpinLock(&domain->_lock);
if (domain->_domainDict == NULL) {
_loadXMLDomainIfStale((CFURLRef )context, domain);
}
// check to see if the value is the same
// if (1) the key is present AND value is !NULL and equal to existing, do nothing, or
// if (2) the key is not present AND value is NULL, do nothing
// these things are no-ops, and should not dirty the domain
if (CFDictionaryGetValueIfPresent(domain->_domainDict, key, &existing)) {
if (NULL != value && (existing == value || CFEqual(existing, value))) {
__CFSpinUnlock(&domain->_lock);
return;
}
} else {
if (NULL == value) {
__CFSpinUnlock(&domain->_lock);
return;
}
}
// We must append first so key gets another retain (in case we're
// about to remove it from the dictionary, and that's the sole reference)
// This should be a set not an array.
if (!CFArrayContainsValue(domain->_dirtyKeys, CFRangeMake(0, CFArrayGetCount(domain->_dirtyKeys)), key)) {
CFArrayAppendValue(domain->_dirtyKeys, key);
}
if (value) {
// Must copy for two reasons - we don't want mutable objects in the cache, and we don't want objects allocated from a different allocator in the cache.
CFTypeRef newValue = CFPropertyListCreateDeepCopy(__CFPreferencesAllocator(), value, kCFPropertyListImmutable);
CFDictionarySetValue(domain->_domainDict, key, newValue);
CFRelease(newValue);
} else {
CFDictionaryRemoveValue(domain->_domainDict, key);
}
__CFSpinUnlock(&domain->_lock);
}
static void getXMLKeysAndValues(CFAllocatorRef alloc, CFTypeRef context, void *xmlDomain, void **buf[], CFIndex *numKeyValuePairs) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
CFIndex count;
__CFSpinLock(&domain->_lock);
if (!domain->_domainDict) {
_loadXMLDomainIfStale((CFURLRef )context, domain);
}
count = CFDictionaryGetCount(domain->_domainDict);
if (buf) {
void **values;
if (count <= *numKeyValuePairs) {
values = *buf + count;
CFDictionaryGetKeysAndValues(domain->_domainDict, (const void **)*buf, (const void **)values);
} else if (alloc != kCFAllocatorNull) {
*buf = (void**) CFAllocatorReallocate(alloc, (*buf ? *buf : NULL), count * 2 * sizeof(void *), 0);
if (*buf) {
values = *buf + count;
CFDictionaryGetKeysAndValues(domain->_domainDict, (const void **)*buf, (const void **)values);
}
}
}
*numKeyValuePairs = count;
__CFSpinUnlock(&domain->_lock);
}
static CFDictionaryRef copyXMLDomainDictionary(CFTypeRef context, void *xmlDomain) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
CFDictionaryRef result;
__CFSpinLock(&domain->_lock);
if(!domain->_domainDict) {
_loadXMLDomainIfStale((CFURLRef)context, domain);
}
result = (CFDictionaryRef)CFPropertyListCreateDeepCopy(__CFPreferencesAllocator(), domain->_domainDict, kCFPropertyListImmutable);
__CFSpinUnlock(&domain->_lock);
return result;
}
static void setXMLDomainIsWorldReadable(CFTypeRef context, void *domain, Boolean isWorldReadable) {
((_CFXMLPreferencesDomain *)domain)->_isWorldReadable = isWorldReadable;
}
static Boolean synchronizeXMLDomain(CFTypeRef context, void *xmlDomain) {
_CFXMLPreferencesDomain *domain = (_CFXMLPreferencesDomain *)xmlDomain;
CFMutableDictionaryRef cachedDict;
CFMutableArrayRef changedKeys;
SInt32 idx, count;
Boolean success, tryAgain;
__CFSpinLock(&domain->_lock);
cachedDict = domain->_domainDict;
changedKeys = domain->_dirtyKeys;
count = CFArrayGetCount(changedKeys);
if (count == 0) {
// no changes were made to this domain; just remove it from the cache to guarantee it will be taken from disk next access
if (cachedDict) {
CFRelease(cachedDict);
domain->_domainDict = NULL;
}
__CFSpinUnlock(&domain->_lock);
return true;
}
domain->_domainDict = NULL; // This forces a reload. Note that we now have a retain on cachedDict
do {
_loadXMLDomainIfStale((CFURLRef )context, domain);
// now cachedDict holds our changes; domain->_domainDict has the latest version from the disk
for (idx = 0; idx < count; idx ++) {
CFStringRef key = (CFStringRef) CFArrayGetValueAtIndex(changedKeys, idx);
CFTypeRef value = CFDictionaryGetValue(cachedDict, key);
if (value)
CFDictionarySetValue(domain->_domainDict, key, value);
else
CFDictionaryRemoveValue(domain->_domainDict, key);
}
success = _writeXMLFile((CFURLRef )context, domain->_domainDict, domain->_isWorldReadable, &tryAgain);
if (tryAgain) {
__CFMilliSleep(50);
}
} while (tryAgain);
CFRelease(cachedDict);
if (success) {
CFArrayRemoveAllValues(domain->_dirtyKeys);
}
domain->_lastReadTime = CFAbsoluteTimeGetCurrent();
__CFSpinUnlock(&domain->_lock);
return success;
}