2 * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 #ifndef _SECCFWRAPPERS_H_
26 #define _SECCFWRAPPERS_H_
28 #include <CoreFoundation/CFRuntime.h>
29 #include <CoreFoundation/CoreFoundation.h>
31 #include "utilities/SecCFRelease.h"
32 #include "utilities/debugging.h"
33 #include "utilities/SecCFError.h"
35 #include <IOKit/IOReturn.h>
38 #include <dispatch/dispatch.h>
43 #include <corecrypto/ccdigest.h>
47 #if __has_feature(objc_arc)
48 #define __SECBRIDGE __bridge
54 // Convenience routines.
58 // Macros for the pattern
60 // typedef struct _privateNewClass* NewClassRef;
62 // struct _privateNewClass {
63 // CFRuntimeBase _base;
64 // ... class additions
67 // kClassNameRegisterClass
70 // ClassNameGetTypeID()
72 // CFGiblisFor(NewClass);
74 // .. define NewClassDestroy
75 // .. define NewClassCopyDescription
77 // .. use CFTypeAllocate(NewClass, _privateNewClass, allocator);
81 // Call this to create a function that returns a singleton instance of type stype,
82 // which is initialized once by calling doThisOnce, with result in its context. Upon
83 // completion body should assign to *result.
85 extern CFStringRef kSecDebugFormatOption
;
87 extern CFDictionaryRef
SecGetDebugDescriptionFormatOptions(void);
89 typedef void (^SecBoolCFErrorCallback
) (bool, CFErrorRef
);
91 #define CFGiblisGetSingleton(returnType, giblisClassName, result, doThisOnce) \
92 returnType giblisClassName(void); \
93 returnType giblisClassName(void) { \
94 static dispatch_once_t s##giblisClassName##Once; \
95 static returnType s##giblisClassName##Singleton; \
96 returnType *result = &s##giblisClassName##Singleton; \
97 dispatch_once(&s##giblisClassName##Once, doThisOnce); \
98 return s##giblisClassName##Singleton; \
101 #define CFGiblisWithFunctions(gibliClassName, init_func, copy_func, finalize_func, equal_func, hash_func, copyFormattingDesc_func, copyDebugDesc_func, reclaim_func, refcount_func, run_once_block) \
102 CFGiblisGetSingleton(CFTypeID, gibliClassName##GetTypeID, typeID, (^{ \
103 void (^ const _onceBlock)(void) = (run_once_block); \
104 static const CFRuntimeClass s##gibliClassName##Class = { \
105 .version = (reclaim_func == NULL ? 0 : _kCFRuntimeResourcefulObject) \
106 | (refcount_func == NULL ? 0 : _kCFRuntimeCustomRefCount), \
107 .className = #gibliClassName, \
110 .finalize = finalize_func, \
111 .equal = equal_func, \
113 .copyFormattingDesc = copyFormattingDesc_func, \
114 .copyDebugDesc = copyDebugDesc_func, \
115 .reclaim = reclaim_func, \
116 .refcount = refcount_func, \
118 *typeID = _CFRuntimeRegisterClass(&s##gibliClassName##Class); \
123 #define CFGiblisWithHashFor(gibliClassName) \
124 static CFStringRef gibliClassName##CopyFormatDescription(CFTypeRef cf, CFDictionaryRef formatOptions); \
125 static void gibliClassName##Destroy(CFTypeRef cf); \
126 static Boolean gibliClassName##Compare(CFTypeRef lhs, CFTypeRef rhs); \
127 static CFHashCode gibliClassName##Hash(CFTypeRef cf); \
128 static CFStringRef gibliClassName##CopyDescription(CFTypeRef cf){\
129 return gibliClassName##CopyFormatDescription(cf, SecGetDebugDescriptionFormatOptions());\
132 CFGiblisWithFunctions(gibliClassName, NULL, NULL, gibliClassName##Destroy, gibliClassName##Compare, gibliClassName##Hash, gibliClassName##CopyFormatDescription, gibliClassName##CopyDescription, NULL, NULL, NULL)
134 #define CFGiblisWithCompareFor(gibliClassName) \
135 static CFStringRef gibliClassName##CopyFormatDescription(CFTypeRef cf, CFDictionaryRef formatOptions); \
136 static void gibliClassName##Destroy(CFTypeRef cf); \
137 static Boolean gibliClassName##Compare(CFTypeRef lhs, CFTypeRef rhs); \
138 static CFStringRef gibliClassName##CopyDescription(CFTypeRef cf){\
139 return gibliClassName##CopyFormatDescription(cf, SecGetDebugDescriptionFormatOptions());\
142 CFGiblisWithFunctions(gibliClassName, NULL, NULL, gibliClassName##Destroy, gibliClassName##Compare, NULL, gibliClassName##CopyFormatDescription, gibliClassName##CopyDescription, NULL, NULL, NULL)
145 #define CFGiblisFor(gibliClassName) \
146 static CFStringRef gibliClassName##CopyFormatDescription(CFTypeRef cf, CFDictionaryRef formatOptions); \
147 static void gibliClassName##Destroy(CFTypeRef cf); \
148 static CFStringRef gibliClassName##CopyDescription(CFTypeRef cf){\
149 return gibliClassName##CopyFormatDescription(cf, SecGetDebugDescriptionFormatOptions());\
152 CFGiblisWithFunctions(gibliClassName, NULL, NULL, gibliClassName##Destroy, NULL, NULL, gibliClassName##CopyFormatDescription, gibliClassName##CopyDescription, NULL, NULL, NULL)
154 #define CFTypeAllocateWithSpace(classType, space, allocator) \
155 (classType##Ref) _CFRuntimeCreateInstance(allocator, classType##GetTypeID(), space, NULL)
157 #define CFTypeAllocate(classType, internalType, allocator) \
158 CFTypeAllocateWithSpace(classType, sizeof(internalType) - sizeof(CFRuntimeBase), allocator)
160 #define SECWRAPPER_SENTINEL __attribute__((__sentinel__))
164 void withStringOfAbsoluteTime(CFAbsoluteTime at
, void (^action
)(CFStringRef decription
));
168 // MARK: Call block function
172 static void apply_block_1(const void *value
, void *context
)
174 ((__SECBRIDGE
void (^)(const void *value
))context
)(value
);
177 static void apply_block_2(const void *key
, const void *value
, void *context
)
179 ((__SECBRIDGE
void (^)(const void *key
, const void *value
))context
)(key
, value
);
183 // MARK: Type checking
186 static inline bool isArray(CFTypeRef cfType
) {
187 return cfType
&& CFGetTypeID(cfType
) == CFArrayGetTypeID();
190 static inline bool isSet(CFTypeRef cfType
) {
191 return cfType
&& CFGetTypeID(cfType
) == CFSetGetTypeID();
194 static inline bool isData(CFTypeRef cfType
) {
195 return cfType
&& CFGetTypeID(cfType
) == CFDataGetTypeID();
198 static inline bool isDate(CFTypeRef cfType
) {
199 return cfType
&& CFGetTypeID(cfType
) == CFDateGetTypeID();
202 static inline bool isDictionary(CFTypeRef cfType
) {
203 return cfType
&& CFGetTypeID(cfType
) == CFDictionaryGetTypeID();
206 static inline bool isNumber(CFTypeRef cfType
) {
207 return cfType
&& CFGetTypeID(cfType
) == CFNumberGetTypeID();
210 static inline bool isNumberOfType(CFTypeRef cfType
, CFNumberType number
) {
211 return isNumber(cfType
) && CFNumberGetType((CFNumberRef
)cfType
) == number
;
214 static inline bool isString(CFTypeRef cfType
) {
215 return cfType
&& CFGetTypeID(cfType
) == CFStringGetTypeID();
218 static inline bool isBoolean(CFTypeRef cfType
) {
219 return cfType
&& CFGetTypeID(cfType
) == CFBooleanGetTypeID();
222 static inline bool isNull(CFTypeRef cfType
) {
223 return cfType
&& CFGetTypeID(cfType
) == CFNullGetTypeID();
226 // Usage: void foo(CFTypeRef value) { CFDataRef data = CFCast(CFData, value); }
227 #define CFCast(type, value) \
228 ((value != NULL) && CFGetTypeID(value) == type ## GetTypeID() ? (type ## Ref)(value) : NULL)
230 #define CFCastWithError(type, value, error) \
231 ((value != NULL) && CFGetTypeID(value) == type ## GetTypeID() ? \
232 (type ## Ref)(value) : \
233 (SecError(errSecParam, error, CFSTR("Unexpected type")), NULL))
236 // MARK CFEqual Helpers
239 static inline bool CFEqualSafe(CFTypeRef left
, CFTypeRef right
)
241 if (left
== NULL
|| right
== NULL
)
242 return left
== right
;
244 return CFEqual(left
, right
);
252 static void fprint_string(FILE *file
, CFStringRef string
) {
254 CFRange range
= { .location
= 0 };
255 range
.length
= CFStringGetLength(string
);
256 while (range
.length
> 0) {
257 CFIndex bytesUsed
= 0;
258 CFIndex converted
= CFStringGetBytes(string
, range
, kCFStringEncodingUTF8
, 0, false, buf
, sizeof(buf
), &bytesUsed
);
259 fwrite(buf
, 1, bytesUsed
, file
);
260 range
.length
-= converted
;
261 range
.location
+= converted
;
265 static inline void cffprint_v(FILE *file
, CFStringRef fmt
, va_list args
) CF_FORMAT_FUNCTION(2, 0);
266 static void cffprint(FILE *file
, CFStringRef fmt
, ...) CF_FORMAT_FUNCTION(2,0);
268 static inline void cffprint_v(FILE *file
, CFStringRef fmt
, va_list args
) {
269 CFStringRef line
= CFStringCreateWithFormatAndArguments(NULL
, NULL
, fmt
, args
);
270 fprint_string(file
, line
);
274 static inline void cffprint(FILE *file
, CFStringRef fmt
, ...) {
277 cffprint_v(file
, fmt
, args
);
282 // MARK: CFError Helpers
285 /* Return false if possibleError is set. Propagates possibleError into *error
286 if *error is NULL, otherwise releases possibleError. */
288 bool CFErrorPropagate(CFErrorRef possibleError CF_CONSUMED
, CFErrorRef
*error
) {
290 if (error
&& !*error
) {
291 *error
= possibleError
;
293 CFRelease(possibleError
);
300 static inline bool CFErrorIsMalfunctioningKeybagError(CFErrorRef error
){
301 switch(CFErrorGetCode(error
))
303 case(kAKSReturnError
):
304 case(kAKSReturnBusy
):
305 case(kAKSReturnNoPermission
):
310 return CFEqualSafe(CFErrorGetDomain(error
), kSecKernDomain
);
314 // MARK: CFNumber Helpers
317 static inline CFNumberRef
CFNumberCreateWithCFIndex(CFAllocatorRef allocator
, CFIndex value
)
319 return CFNumberCreate(allocator
, kCFNumberCFIndexType
, &value
);
323 // MARK: CFData Helpers
326 static inline CFMutableDataRef
CFDataCreateMutableWithScratch(CFAllocatorRef allocator
, CFIndex size
) {
327 CFMutableDataRef result
= CFDataCreateMutable(allocator
, 0);
328 CFDataSetLength(result
, size
);
333 static inline void CFDataAppend(CFMutableDataRef appendTo
, CFDataRef dataToAppend
)
335 CFDataAppendBytes(appendTo
, CFDataGetBytePtr(dataToAppend
), CFDataGetLength(dataToAppend
));
338 static inline CFDataRef
CFDataCreateReferenceFromRange(CFAllocatorRef allocator
, CFDataRef sourceData
, CFRange range
)
340 return CFDataCreateWithBytesNoCopy(allocator
,
341 CFDataGetBytePtr(sourceData
) + range
.location
, range
.length
,
345 static inline CFDataRef
CFDataCreateCopyFromRange(CFAllocatorRef allocator
, CFDataRef sourceData
, CFRange range
)
347 return CFDataCreate(allocator
, CFDataGetBytePtr(sourceData
) + range
.location
, range
.length
);
350 CFDataRef
CFDataCreateWithRandomBytes(size_t len
);
352 CFDataRef
CFDataCreateWithInitializer(CFAllocatorRef allocator
, CFIndex size
, bool (^operation
)(size_t size
, uint8_t *buffer
));
354 static inline uint8_t* CFDataIncreaseLengthAndGetMutableBytes(CFMutableDataRef data
, CFIndex extraLength
)
356 CFIndex startOffset
= CFDataGetLength(data
);
358 CFDataIncreaseLength(data
, extraLength
);
360 return CFDataGetMutableBytePtr(data
) + startOffset
;
363 static inline uint8_t* CFDataGetMutablePastEndPtr(CFMutableDataRef theData
)
365 return CFDataGetMutableBytePtr(theData
) + CFDataGetLength(theData
);
368 static inline const uint8_t* CFDataGetPastEndPtr(CFDataRef theData
) {
369 return CFDataGetBytePtr(theData
) + CFDataGetLength(theData
);
372 static inline CFComparisonResult
CFDataCompare(CFDataRef left
, CFDataRef right
)
374 const size_t left_size
= CFDataGetLength(left
);
375 const size_t right_size
= CFDataGetLength(right
);
376 const size_t shortest
= (left_size
<= right_size
) ? left_size
: right_size
;
378 int comparison
= memcmp(CFDataGetBytePtr(left
), CFDataGetBytePtr(right
), shortest
);
380 if (comparison
> 0 || (comparison
== 0 && left_size
> right_size
))
381 return kCFCompareGreaterThan
;
382 else if (comparison
< 0 || (comparison
== 0 && left_size
< right_size
))
383 return kCFCompareLessThan
;
385 return kCFCompareEqualTo
;
388 static inline CFDataRef
CFDataCreateWithHash(CFAllocatorRef allocator
, const struct ccdigest_info
*di
, const uint8_t *buffer
, const uint8_t length
) {
389 CFMutableDataRef result
= CFDataCreateMutableWithScratch(allocator
, di
->output_size
);
391 ccdigest(di
, length
, buffer
, CFDataGetMutableBytePtr(result
));
397 static inline CFDataRef
CFDataCreateCopyFromPositions(CFAllocatorRef allocator
, CFDataRef source
, CFIndex start
, CFIndex end
)
399 return CFDataCreateCopyFromRange(allocator
, source
, CFRangeMake(start
, end
- start
));
402 static inline int nibletToByte(char niblet
) {
403 if(niblet
>= '0' && niblet
<= '9') return niblet
- '0';
404 if(niblet
>= 'a' && niblet
<= 'f') return niblet
- 'a' + 10;
405 if(niblet
>= 'A' && niblet
<= 'F') return niblet
- 'A' + 10;
409 static inline CFDataRef
CFDataCreateFromHexString(CFAllocatorRef allocator
, CFStringRef sourceHex
) {
410 CFIndex sourceLen
= CFStringGetLength(sourceHex
);
411 if((sourceLen
% 2) != 0) return NULL
;
412 const char *src
= CFStringGetCStringPtr(sourceHex
, kCFStringEncodingUTF8
);
413 UInt8 bytes
[sourceLen
/2];
414 for(int i
= 0; i
< sourceLen
; i
+=2) {
415 bytes
[i
/2] = (UInt8
) (nibletToByte(src
[i
]) * 16 + nibletToByte(src
[i
+1]));
417 return CFDataCreate(allocator
, bytes
, sourceLen
/2);
422 // MARK: CFString Helpers
425 CFComparisonResult
CFStringCompareSafe(const void *val1
, const void *val2
, void *context
);
428 // Turn a CFString into an allocated UTF8-encoded C string.
430 static inline char *CFStringToCString(CFStringRef inStr
)
433 return (char *)strdup("");
434 CFRetain(inStr
); // compensate for release on exit
436 // need to extract into buffer
437 CFIndex length
= CFStringGetLength(inStr
); // in 16-bit character units
438 size_t len
= CFStringGetMaximumSizeForEncoding(length
, kCFStringEncodingUTF8
) + 1;
439 char *buffer
= (char *)malloc(len
); // pessimistic
440 if (!CFStringGetCString(inStr
, buffer
, len
, kCFStringEncodingUTF8
))
447 // runs operation with inStr as a zero terminated C string
448 // in utf8 encoding passed to the operation block.
449 void CFStringPerformWithCString(CFStringRef inStr
, void(^operation
)(const char *utf8Str
));
451 // runs operation with inStr as a zero terminated C string
452 // in utf8 passed to the operation block, the length of
453 // the string is also provided to the block.
454 void CFStringPerformWithCStringAndLength(CFStringRef inStr
, void(^operation
)(const char *utf8Str
, size_t utf8Length
));
456 void CFStringPerformWithUTF8CFData(CFStringRef inStr
, void (^operation
)(CFDataRef stringAsData
));
458 #include <CommonNumerics/CommonCRC.h>
460 static inline void CFStringAppendEncryptedData(CFMutableStringRef s
, CFDataRef edata
)
462 const uint8_t *bytes
= CFDataGetBytePtr(edata
);
463 CFIndex len
= CFDataGetLength(edata
);
464 CFStringAppendFormat(s
, 0, CFSTR("%04lx:"), len
);
466 for (CFIndex ix
= 0; ix
< len
; ++ix
) {
467 CFStringAppendFormat(s
, 0, CFSTR("%02X"), bytes
[ix
]);
471 CNCRC(kCN_CRC_64_ECMA_182
, bytes
+8, len
-8, &crc
);
472 for (CFIndex ix
= 0; ix
< 8; ++ix
) {
473 CFStringAppendFormat(s
, 0, CFSTR("%02X"), bytes
[ix
]);
475 CFStringAppendFormat(s
, 0, CFSTR("...|%08llx"), crc
);
479 static inline void CFStringAppendHexData(CFMutableStringRef s
, CFDataRef data
) {
480 const uint8_t *bytes
= CFDataGetBytePtr(data
);
481 CFIndex len
= CFDataGetLength(data
);
482 for (CFIndex ix
= 0; ix
< len
; ++ix
) {
483 CFStringAppendFormat(s
, 0, CFSTR("%02X"), bytes
[ix
]);
487 static inline CF_RETURNS_RETAINED CFStringRef
CFDataCopyHexString(CFDataRef data
) {
488 CFMutableStringRef hexString
= CFStringCreateMutable(kCFAllocatorDefault
, 2 * CFDataGetLength(data
));
489 CFStringAppendHexData(hexString
, data
);
493 static inline void CFDataPerformWithHexString(CFDataRef data
, void (^operation
)(CFStringRef dataString
)) {
494 CFStringRef hexString
= data
? CFDataCopyHexString(data
) : CFSTR("(null)");
495 operation(hexString
);
496 CFRelease(hexString
);
499 static inline void BufferPerformWithHexString(const UInt8
*bytes
, CFIndex length
, void (^operation
)(CFStringRef dataString
)) {
500 CFDataRef bufferAsData
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, bytes
, length
, kCFAllocatorNull
);
502 CFDataPerformWithHexString(bufferAsData
, operation
);
504 CFReleaseNull(bufferAsData
);
509 static inline void CFStringWriteToFile(CFStringRef inStr
, FILE* file
)
511 CFStringPerformWithCStringAndLength(inStr
, ^(const char *utf8Str
, size_t utf8Length
) {
512 fwrite(utf8Str
, 1, utf8Length
, file
);
516 static inline void CFStringWriteToFileWithNewline(CFStringRef inStr
, FILE* file
)
518 CFStringWriteToFile(inStr
, file
);
522 static inline CFStringRef
CFStringCreateTruncatedCopy(CFStringRef s
, CFIndex len
) {
524 if(len
>= CFStringGetLength(s
)) return CFStringCreateCopy(kCFAllocatorDefault
, s
);
525 return CFStringCreateWithSubstring(kCFAllocatorDefault
, s
, CFRangeMake(0, len
));
529 // MARK: CFCollectionHelpers
533 const void *SecCFRetainForCollection(CFAllocatorRef allocator
, const void *value
)
535 return CFRetain(value
);
539 void SecCFReleaseForCollection(CFAllocatorRef allocator
, const void *value
)
545 // MARK: CFArray Helpers
548 static inline CFIndex
CFArrayRemoveAllValue(CFMutableArrayRef array
, const void* value
)
550 CFIndex position
= kCFNotFound
;
551 CFIndex numberRemoved
= 0;
553 position
= CFArrayGetFirstIndexOfValue(array
, CFRangeMake(0, CFArrayGetCount(array
)), value
);
554 while (position
!= kCFNotFound
) {
555 CFArrayRemoveValueAtIndex(array
, position
);
557 position
= CFArrayGetFirstIndexOfValue(array
, CFRangeMake(0, CFArrayGetCount(array
)), value
);
560 return numberRemoved
;
563 static inline void CFArrayAppendAll(CFMutableArrayRef array
, CFArrayRef arrayToAppend
) {
564 CFArrayAppendArray(array
, arrayToAppend
, CFRangeMake(0, CFArrayGetCount(arrayToAppend
)));
567 #define CFArrayForEachC(array, value) for (CFIndex _aCount = CFArrayGetCount(array), _aIX = 0;value = (__typeof__(value))(_aIX < _aCount ? CFArrayGetValueAtIndex(array, _aIX) : 0), _aIX < _aCount; ++_aIX)
569 static inline void CFArrayForEach(CFArrayRef array
, void (^operation
)(const void *value
)) {
570 CFArrayApplyFunction(array
, CFRangeMake(0, CFArrayGetCount(array
)), apply_block_1
, (__SECBRIDGE
void *)operation
);
573 static inline void CFArrayForEachReverse(CFArrayRef array
, void (^operation
)(const void *value
)) {
574 for(CFIndex count
= CFArrayGetCount(array
); count
> 0; --count
) {
575 operation(CFArrayGetValueAtIndex(array
, count
- 1));
579 static inline const void *CFArrayGetValueMatching(CFArrayRef array
, bool (^match
)(const void *value
)) {
580 CFIndex i
, n
= CFArrayGetCount(array
);
581 for (i
= 0; i
< n
; ++i
) {
582 const void *value
= CFArrayGetValueAtIndex(array
, i
);
590 static inline bool CFArrayHasValueMatching(CFArrayRef array
, bool (^match
)(const void *value
)) {
591 return CFArrayGetValueMatching(array
, match
) != NULL
;
594 static inline void CFMutableArrayModifyValues(CFMutableArrayRef array
, const void * (^process
)(const void *value
)) {
595 CFIndex i
, n
= CFArrayGetCount(array
);
596 for (i
= 0; i
< n
; ++i
) {
597 const void *value
= CFArrayGetValueAtIndex(array
, i
);
598 CFArraySetValueAtIndex(array
, i
, process(value
));
602 static inline void CFArraySubtract(CFMutableArrayRef from
, CFArrayRef remove
) {
603 if (remove
&& from
) {
604 CFArrayForEach(remove
, ^(const void *value
) {
605 CFArrayRemoveAllValue(from
, value
);
610 static inline CFMutableArrayRef
CFArrayCreateDifference(CFAllocatorRef alloc
, CFArrayRef set
, CFArrayRef remove
) {
611 CFMutableArrayRef result
;
613 result
= CFArrayCreateMutable(alloc
, 0, &kCFTypeArrayCallBacks
);
615 result
= CFArrayCreateMutableCopy(alloc
, 0, set
);
617 CFArraySubtract(result
, remove
);
624 // MARK: CFArray creation Var args helper functions.
626 static inline CFArrayRef
CFArrayCreateCountedForVC(CFAllocatorRef allocator
, const CFArrayCallBacks
*cbs
, CFIndex entries
, va_list args
)
628 CFMutableArrayRef array
= CFArrayCreateMutable(allocator
, entries
, cbs
);
632 for (CFIndex currentValue
= 0; currentValue
< entries
; ++currentValue
) {
633 const void * value
= va_arg(args
, const void *);
637 CFArrayAppendValue(array
, value
);
640 CFArrayRef constArray
= CFArrayCreateCopy(allocator
, array
);
645 static inline CFArrayRef
CFArrayCreateForVC(CFAllocatorRef allocator
, const CFArrayCallBacks
*cbs
, va_list args
)
648 va_copy(count
, args
);
651 while (NULL
!= va_arg(count
, void*)) {
655 return CFArrayCreateCountedForVC(allocator
, cbs
, entries
, args
);
661 // MARK: CFArray of CFTypes support
664 static inline CFMutableArrayRef
CFArrayCreateMutableForCFTypesWithCapacity(CFAllocatorRef allocator
, CFIndex capacity
)
666 return CFArrayCreateMutable(allocator
, capacity
, &kCFTypeArrayCallBacks
);
669 static inline CFMutableArrayRef SECWRAPPER_SENTINEL
CFArrayCreateMutableForCFTypesWith(CFAllocatorRef allocator
, ...)
673 va_start(args
, allocator
);
674 CFIndex capacity
= 0;
675 void* object
= va_arg(args
, void*);
677 while (object
!= NULL
) {
678 object
= va_arg(args
, void*);
684 CFMutableArrayRef result
= CFArrayCreateMutableForCFTypesWithCapacity(allocator
, capacity
);
686 va_start(args
, allocator
);
687 object
= va_arg(args
, void*);
689 while (object
!= NULL
) {
690 CFArrayAppendValue(result
, object
);
691 object
= va_arg(args
, void*);
699 static inline CFMutableArrayRef
CFArrayCreateMutableForCFTypes(CFAllocatorRef allocator
)
701 return CFArrayCreateMutable(allocator
, 0, &kCFTypeArrayCallBacks
);
704 static inline CFArrayRef SECWRAPPER_SENTINEL
CFArrayCreateForCFTypes(CFAllocatorRef allocator
, ...)
707 va_start(args
, allocator
);
708 CFArrayRef allocatedArray
= CFArrayCreateForVC(allocator
, &kCFTypeArrayCallBacks
, args
);
710 return allocatedArray
;
714 static inline CFArrayRef
CFArrayCreateCountedForCFTypes(CFAllocatorRef allocator
, CFIndex entries
, ...)
717 va_start(args
, entries
);
718 CFArrayRef allocatedArray
= CFArrayCreateCountedForVC(allocator
, &kCFTypeArrayCallBacks
, entries
, args
);
720 return allocatedArray
;
723 static inline CFArrayRef
CFArrayCreateCountedForCFTypesV(CFAllocatorRef allocator
, CFIndex entries
, va_list args
)
725 return CFArrayCreateCountedForVC(allocator
, &kCFTypeArrayCallBacks
, entries
, args
);
729 // MARK: CFDictionary of CFTypes helpers
732 static void CFDictionarySetIfNonNull(CFMutableDictionaryRef dictionary
, const void *key
, const void *value
) {
734 CFDictionarySetValue(dictionary
, key
, value
);
738 static inline CFDictionaryRef
CFDictionaryCreateCountedForCFTypesV(CFAllocatorRef allocator
, CFIndex entries
, va_list args
)
740 CFMutableDictionaryRef dictionary
= CFDictionaryCreateMutable(allocator
, entries
,
741 &kCFTypeDictionaryKeyCallBacks
,
742 &kCFTypeDictionaryValueCallBacks
);
743 if (dictionary
== NULL
) {
747 for(CFIndex currentValue
= 0; currentValue
< entries
; ++currentValue
) {
748 CFTypeRef key
= va_arg(args
, CFTypeRef
);
749 CFTypeRef value
= va_arg(args
, CFTypeRef
);
753 CFDictionarySetValue(dictionary
, key
, value
);
756 CFDictionaryRef constDictionary
= CFDictionaryCreateCopy(allocator
, dictionary
);
757 CFRelease(dictionary
);
758 return constDictionary
;
761 static inline CFDictionaryRef SECWRAPPER_SENTINEL
CFDictionaryCreateForCFTypes(CFAllocatorRef allocator
, ...)
764 va_start(args
, allocator
);
767 while (NULL
!= va_arg(args
, void*)) {
769 (void) va_arg(args
, void*);
774 va_start(args
, allocator
);
775 CFDictionaryRef allocatedDictionary
= CFDictionaryCreateCountedForCFTypesV(allocator
, entries
, args
);
777 return allocatedDictionary
;
780 static inline CFDictionaryRef
CFDictionaryCreateCountedForCFTypes(CFAllocatorRef allocator
, CFIndex entries
, ...)
783 va_start(args
, entries
);
784 CFDictionaryRef allocatedDictionary
= CFDictionaryCreateCountedForCFTypesV(allocator
, entries
, args
);
787 return allocatedDictionary
;
790 static inline CFMutableDictionaryRef
CFDictionaryCreateMutableForCFTypes(CFAllocatorRef allocator
)
792 return CFDictionaryCreateMutable(allocator
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
795 static inline CFMutableDictionaryRef SECWRAPPER_SENTINEL
CFDictionaryCreateMutableForCFTypesWith(CFAllocatorRef allocator
, ...)
797 CFMutableDictionaryRef result
= CFDictionaryCreateMutableForCFTypes(allocator
);
800 va_start(args
, allocator
);
802 void* key
= va_arg(args
, void*);
804 while (key
!= NULL
) {
805 CFDictionarySetValue(result
, key
, va_arg(args
, void*));
806 key
= va_arg(args
, void*);
812 static inline CFMutableDictionaryRef SECWRAPPER_SENTINEL
CFDictionaryCreateMutableForCFTypesWithSafe(CFAllocatorRef allocator
, ...)
814 CFMutableDictionaryRef result
= CFDictionaryCreateMutableForCFTypes(allocator
);
817 va_start(args
, allocator
);
819 void* key
= va_arg(args
, void*);
821 while (key
!= NULL
) {
822 CFDictionarySetIfNonNull(result
, key
, va_arg(args
, void*));
823 key
= va_arg(args
, void*);
830 // MARK: CFSet Helpers
833 static inline CFMutableSetRef
CFSetCreateMutableForCFTypes(CFAllocatorRef allocator
)
835 return CFSetCreateMutable(allocator
, 0, &kCFTypeSetCallBacks
);
838 static inline bool CFSetIsEmpty(CFSetRef set
) {
839 return CFSetGetCount(set
) == 0;
842 static inline void CFSetForEach(CFSetRef set
, void (^operation
)(const void *value
)) {
843 CFSetApplyFunction(set
, apply_block_1
, (__SECBRIDGE
void *)operation
);
846 static inline void CFSetUnion(CFMutableSetRef set
, CFSetRef unionWith
) {
847 CFSetForEach(unionWith
, ^(const void *value
) {
848 CFSetSetValue(set
, value
);
852 static inline void CFSetSubtract(CFMutableSetRef set
, CFSetRef subtract
) {
853 CFSetForEach(subtract
, ^(const void *value
) {
854 CFSetRemoveValue(set
, value
);
858 static inline bool CFSetIsSubset(CFSetRef smaller
, CFSetRef bigger
) {
859 __block
bool isSubset
= true;
860 CFSetForEach(smaller
, ^(const void *value
) {
861 if (!CFSetContainsValue(bigger
, value
)) {
869 static inline void CFSetSetValues(CFMutableSetRef set
, CFArrayRef valuesToSet
) {
870 CFArrayForEach(valuesToSet
, ^(const void *value
) {
871 CFSetSetValue(set
, value
);
875 static inline CFMutableArrayRef
CFSetCopyValues(CFSetRef set
) {
876 CFMutableArrayRef values
= CFArrayCreateMutableForCFTypes(kCFAllocatorDefault
);
878 CFSetForEach(set
, ^(const void *value
) {
879 CFArrayAppendValue(values
, value
);
885 static inline bool CFSetIntersectionIsEmpty(CFSetRef set1
, CFSetRef set2
) {
886 __block
bool intersectionIsEmpty
= true;
887 if(set1
!= NULL
&& set2
!= NULL
) {
888 CFSetForEach(set1
, ^(const void *value
) {
889 intersectionIsEmpty
&= !CFSetContainsValue(set2
, value
);
892 return intersectionIsEmpty
;
895 static inline bool CFSetIntersects(CFSetRef set1
, CFSetRef set2
) {
896 return !CFSetIntersectionIsEmpty(set1
, set2
);
899 static inline CFMutableSetRef
CFSetCreateIntersection(CFAllocatorRef allocator
, CFSetRef a
, CFSetRef b
) {
900 CFMutableSetRef result
= CFSetCreateMutableCopy(allocator
, 0, a
);
902 CFSetRemoveAllValues(result
);
903 CFSetForEach(a
, ^(const void *value
) {
904 if (CFSetContainsValue(b
, value
)) {
905 CFSetAddValue(result
, value
);
912 static inline CFSetRef
CFSetCreateCopyOfArrayForCFTypes(CFArrayRef array
) {
913 CFIndex count
= CFArrayGetCount(array
);
914 if (SIZE_MAX
/sizeof(const void *) < (size_t)count
) {
917 const void **values
= (const void **)malloc(sizeof(const void *) * count
);
918 CFArrayGetValues(array
, CFRangeMake(0, count
), values
);
919 CFSetRef set
= CFSetCreate(CFGetAllocator(array
), values
, count
, &kCFTypeSetCallBacks
);
924 static inline void CFSetTransferObject(CFTypeRef object
, CFMutableSetRef from
, CFMutableSetRef to
) {
925 CFSetAddValue(to
, object
);
926 CFSetRemoveValue(from
, object
);
930 // MARK: CFStringXxx Helpers
933 void CFStringArrayPerformWithDelimiterWithDescription(CFArrayRef strings
, CFStringRef start
, CFStringRef end
, void (^action
)(CFStringRef description
));
934 void CFStringArrayPerformWithDescription(CFArrayRef strings
, void (^action
)(CFStringRef description
));
935 void CFStringSetPerformWithDescription(CFSetRef set
, void (^action
)(CFStringRef description
));
938 // MARK: CFDictionary Helpers
941 static inline void CFDictionaryForEach(CFDictionaryRef dictionary
, void (^operation
)(const void *key
, const void *value
)) {
942 CFDictionaryApplyFunction(dictionary
, apply_block_2
, (__SECBRIDGE
void *)operation
);
945 CFStringRef
CFDictionaryCopyCompactDescription(CFDictionaryRef dictionary
);
946 CFStringRef
CFDictionaryCopySuperCompactDescription(CFDictionaryRef dictionary
);
949 // MARK: CFCalendar helpers
952 void SecCFCalendarDoWithZuluCalendar(void(^action
)(CFCalendarRef zuluCalendar
));
955 // MARK: CFAbsoluteTime helpers
958 static inline CFAbsoluteTime
CFAbsoluteTimeForCalendarMoment(CFCalendarRef cal
, int year
, int month
, int day
, int hour
, int minute
, int second
) {
960 CFCalendarComposeAbsoluteTime(cal
, &at
, "yMdHms", year
, month
, day
, hour
, minute
, second
);
964 static inline CFAbsoluteTime
CFAbsoluteTimeForCalendarDay(CFCalendarRef cal
, int year
, int month
, int day
) {
966 CFCalendarComposeAbsoluteTime(cal
, &at
, "yMd", year
, month
, day
);
970 static inline CFAbsoluteTime
CFAbsoluteTimeForGregorianMoment(CFTimeZoneRef tz
, int year
, int month
, int day
, int hour
, int minute
, int second
)
972 CFCalendarRef cal
= CFCalendarCreateWithIdentifier(NULL
, kCFGregorianCalendar
);
973 CFCalendarSetTimeZone(cal
, tz
);
974 CFAbsoluteTime at
= CFAbsoluteTimeForCalendarMoment(cal
, year
, month
, day
, hour
, minute
, second
);
979 static inline CFAbsoluteTime
CFAbsoluteTimeForGregorianDay(CFTimeZoneRef tz
, int year
, int month
, int day
)
981 CFCalendarRef cal
= CFCalendarCreateWithIdentifier(NULL
, kCFGregorianCalendar
);
982 CFCalendarSetTimeZone(cal
, tz
);
983 CFAbsoluteTime at
= CFAbsoluteTimeForCalendarDay(cal
, year
, month
, day
);
988 static inline CFAbsoluteTime
CFAbsoluteTimeForGregorianZuluMoment(int year
, int month
, int day
, int hour
, int minute
, int second
)
990 __block CFAbsoluteTime result
= 0.0;
991 SecCFCalendarDoWithZuluCalendar(^(CFCalendarRef zuluCalendar
) {
992 result
= CFAbsoluteTimeForCalendarMoment(zuluCalendar
, year
, month
, day
, hour
, minute
, second
);
998 static inline CFAbsoluteTime
CFAbsoluteTimeForGregorianZuluDay(int year
, int month
, int day
)
1000 __block CFAbsoluteTime result
= 0.0;
1001 SecCFCalendarDoWithZuluCalendar(^(CFCalendarRef zuluCalendar
) {
1002 result
= CFAbsoluteTimeForCalendarDay(zuluCalendar
, year
, month
, day
);
1010 // MARK: CFDate Helpers
1013 static inline CFDateRef
CFDateCreateForGregorianMoment(CFAllocatorRef allocator
, CFTimeZoneRef tz
, int year
, int month
, int day
, int hour
, int minute
, int second
)
1015 return CFDateCreate(allocator
, CFAbsoluteTimeForGregorianMoment(tz
, year
, month
, day
, hour
, minute
, second
));
1018 static inline CFDateRef
CFDateCreateForGregorianDay(CFAllocatorRef allocator
, CFTimeZoneRef tz
, int year
, int month
, int day
, int hour
, int minute
, int second
)
1020 return CFDateCreate(allocator
, CFAbsoluteTimeForGregorianDay(tz
, year
, month
, day
));
1023 static inline CFDateRef
CFDateCreateForGregorianZuluMoment(CFAllocatorRef allocator
, int year
, int month
, int day
, int hour
, int minute
, int second
)
1025 return CFDateCreate(allocator
, CFAbsoluteTimeForGregorianZuluMoment(year
, month
, day
, hour
, minute
, second
));
1028 static inline CFDateRef
CFDateCreateForGregorianZuluDay(CFAllocatorRef allocator
, int year
, int month
, int day
)
1030 return CFDateCreate(allocator
, CFAbsoluteTimeForGregorianZuluDay(year
, month
, day
));
1034 // MARK: PropertyList Helpers
1038 // Crazy reading and writing stuff
1041 static inline void CFPropertyListWriteToFile(CFPropertyListRef plist
, CFURLRef file
)
1043 CFWriteStreamRef writeStream
= CFWriteStreamCreateWithFile(kCFAllocatorDefault
, file
);
1044 CFErrorRef error
= NULL
;
1046 CFWriteStreamOpen(writeStream
);
1047 CFPropertyListWrite(plist
, writeStream
, kCFPropertyListBinaryFormat_v1_0
, 0, &error
);
1049 secerror("Can't write plist: %@", error
);
1051 CFReleaseNull(error
);
1052 CFReleaseNull(writeStream
);
1055 static inline CF_RETURNS_RETAINED CFPropertyListRef
CFPropertyListReadFromFile(CFURLRef file
)
1057 CFPropertyListRef result
= NULL
;
1058 CFErrorRef error
= NULL
;
1059 CFBooleanRef isRegularFile
;
1060 if (!CFURLCopyResourcePropertyForKey(file
, kCFURLIsRegularFileKey
, &isRegularFile
, &error
)) {
1061 secinfo("plist", "file %@: %@", file
, error
);
1062 } else if (CFBooleanGetValue(isRegularFile
)) {
1063 CFReadStreamRef readStream
= CFReadStreamCreateWithFile(kCFAllocatorDefault
, file
);
1065 if (CFReadStreamOpen(readStream
)) {
1066 CFPropertyListFormat format
;
1067 result
= CFPropertyListCreateWithStream(kCFAllocatorDefault
, readStream
, 0, kCFPropertyListMutableContainers
, &format
, &error
);
1069 secerror("read plist from %@: %@", file
, error
);
1072 CFRelease(readStream
);
1075 CFReleaseNull(error
);
1082 #endif /* _SECCFWRAPPERS_H_ */