2 * Copyright (c) 2000-2004,2011-2016 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@
28 Contains: Code that communicates with processes that install a callback
29 with the Keychain Manager to receive keychain events.
33 #include "CCallbackMgr.h"
39 #include <security_cdsa_utilities/Schema.h>
40 #include <security_keychain/SecCFTypes.h>
41 #include <securityd_client/SharedMemoryCommon.h>
42 #include <securityd_client/ssnotify.h>
43 #include <utilities/SecCFRelease.h>
45 #include <Security/SecCertificatePriv.h>
47 using namespace KeychainCore;
48 using namespace CssmClient;
49 using namespace SecurityServer;
51 #pragma mark ÑÑÑÑ CallbackInfo ÑÑÑÑ
53 CallbackInfo::CallbackInfo() : mCallback(NULL),mEventMask(0),mContext(NULL), mRunLoop(NULL), mActive(false)
57 CallbackInfo::CallbackInfo(SecKeychainCallback inCallbackFunction,
58 SecKeychainEventMask inEventMask, void *inContext, CFRunLoopRef runLoop)
59 : mCallback(inCallbackFunction), mEventMask(inEventMask), mContext(inContext), mRunLoop(NULL), mActive(false)
62 CFRetainSafe(mRunLoop);
65 CallbackInfo::CallbackInfo(const CallbackInfo& cb) {
66 mCallback = cb.mCallback;
67 mEventMask = cb.mEventMask;
68 mContext = cb.mContext;
71 mRunLoop = cb.mRunLoop;
72 CFRetainSafe(mRunLoop);
75 CallbackInfo::~CallbackInfo()
77 CFReleaseNull(mRunLoop);
80 bool CallbackInfo::operator==(const CallbackInfo& other) const
82 return mCallback==other.mCallback;
85 bool CallbackInfo::operator!=(const CallbackInfo& other) const
87 return !(*this==other);
91 #pragma mark ÑÑÑÑ CCallbackMgr ÑÑÑÑ
97 RefPointer<CCallbackMgr> mCallbackManager;
101 CCallbackMgr& instance() {return *mCallbackManager;}
105 CallbackMaker::CallbackMaker()
107 CCallbackMgr* manager = new CCallbackMgr();
108 mCallbackManager = manager;
113 ModuleNexus<CallbackMaker> gCallbackMaker;
115 CCallbackMgr::CCallbackMgr() : EventListener (kNotificationDomainDatabase, kNotificationAllEvents)
117 EventListener::FinishedInitialization(this);
120 CCallbackMgr::~CCallbackMgr()
124 CCallbackMgr& CCallbackMgr::Instance()
126 return gCallbackMaker().instance();
129 void CCallbackMgr::AddCallback( SecKeychainCallback inCallbackFunction,
130 SecKeychainEventMask inEventMask,
134 CallbackInfo info( inCallbackFunction, inEventMask, inContext, CFRunLoopGetCurrent() );
136 CallbackInfoListIterator ix = find( CCallbackMgr::Instance().mEventCallbacks.begin(),
137 CCallbackMgr::Instance().mEventCallbacks.end(), info );
139 // make sure it is not already there
140 if ( ix!=CCallbackMgr::Instance().mEventCallbacks.end() )
142 // It's already there. This could mean that the old process died unexpectedly,
143 // so we need to validate the process ID of the existing callback.
144 // On Mac OS X this list is per process so this is always a duplicate
145 MacOSError::throwMe(errSecDuplicateCallback);
148 CCallbackMgr::Instance().mEventCallbacks.push_back(info);
150 // We want to deliver these notifications if the CFRunLoop we just wrote down is actually actively serviced.
151 // Otherwise, it'll be a continuous (undetectable) leak.
152 CFRunLoopTimerContext ctx;
153 memset(&ctx, 0, sizeof(ctx));
154 ctx.info = info.mRunLoop;
156 CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent(), 0, 0, 0, CCallbackMgr::cfrunLoopActive, &ctx);
157 secdebug("kcnotify", "adding a activate callback on run loop %p", info.mRunLoop);
158 CFRunLoopAddTimer(info.mRunLoop, timerRef, kCFRunLoopDefaultMode);
161 void CCallbackMgr::cfrunLoopActive(CFRunLoopTimerRef timer, void* info) {
162 CFRunLoopRef runLoop = (CFRunLoopRef) info;
163 secdebug("kcnotify", "activating run loop %p", runLoop);
165 // Use the notification queue to serialize setting the mActive bits
166 static dispatch_queue_t notification_queue = EventListener::getNotificationQueue();
167 dispatch_async(notification_queue, ^() {
168 // Iterate through list, and activate every notification on this run loop
169 for(CallbackInfoListIterator ix = CCallbackMgr::Instance().mEventCallbacks.begin(); ix != CCallbackMgr::Instance().mEventCallbacks.end(); ix++) {
170 // pointer comparison, not CFEqual.
171 if(ix->mRunLoop == runLoop) {
172 secdebug("kcnotify", "activating callback on run loop %p", runLoop);
184 SecKeychainCallback mCallbackFunction;
186 Predicate(SecKeychainCallback inCallbackFunction) : mCallbackFunction(inCallbackFunction) {}
187 bool operator()(const CallbackInfo &cbInfo) { return cbInfo.mCallback == mCallbackFunction; }
190 void CCallbackMgr::RemoveCallback(SecKeychainCallback inCallbackFunction)
192 size_t oldSize = CCallbackMgr::Instance().mEventCallbacks.size();
193 Predicate predicate(inCallbackFunction);
194 CCallbackMgr::Instance().mEventCallbacks.remove_if(predicate);
196 if (oldSize == CCallbackMgr::Instance().mEventCallbacks.size())
197 MacOSError::throwMe(errSecInvalidCallback);
200 struct CallbackMgrInfo {
201 SecKeychainEvent event;
202 SecKeychainCallbackInfo secKeychainCallbackInfo;
203 SecKeychainCallback callback;
204 void *callbackContext;
207 void CCallbackMgr::tellClient(CFRunLoopTimerRef timer, void* info) {
208 CallbackMgrInfo* cbmInfo = (CallbackMgrInfo*) info;
209 if(!cbmInfo || !(cbmInfo->callback)) {
213 cbmInfo->callback(cbmInfo->event, &(cbmInfo->secKeychainCallbackInfo), cbmInfo->callbackContext);
214 if (cbmInfo->secKeychainCallbackInfo.item) CFRelease(cbmInfo->secKeychainCallbackInfo.item);
215 if (cbmInfo->secKeychainCallbackInfo.keychain) CFRelease(cbmInfo->secKeychainCallbackInfo.keychain);
220 static SecKeychainItemRef createItemReference(const Item &inItem)
222 SecKeychainItemRef itemRef = (inItem) ? inItem->handle() : 0;
223 if(!itemRef) { return NULL; }
226 SecItemClass itemClass = Schema::itemClassFor(inItem->recordType());
227 if (itemClass == kSecCertificateItemClass) {
228 SecCertificateRef certRef = SecCertificateCreateFromItemImplInstance((SecCertificateRef)itemRef);
229 CFRelease(itemRef); /* certRef maintains its own internal reference to itemRef */
230 itemRef = (SecKeychainItemRef) certRef;
236 static SecKeychainRef createKeychainReference(const Keychain &inKeychain)
238 return (inKeychain) ? inKeychain->handle() : 0;
241 void CCallbackMgr::AlertClients(const list<CallbackInfo> &eventCallbacks,
242 SecKeychainEvent inEvent,
244 const Keychain &inKeychain,
247 secinfo("kcnotify", "dispatch event %ld pid %d keychain %p item %p",
248 (unsigned long)inEvent, inPid, &inKeychain, !!inItem ? &*inItem : NULL);
250 // Iterate through callbacks, looking for those registered for inEvent
251 const SecKeychainEventMask theMask = 1U << inEvent;
253 for (ConstCallbackInfoListIterator ix = eventCallbacks.begin(); ix != eventCallbacks.end(); ++ix)
255 if (!(ix->mEventMask & theMask))
259 // We haven't received our callback from this CFRunLoop yet. Assume it's not being pumped, and don't schedule.
260 secdebug("kcnotify", "not sending event to run loop %p", ix->mRunLoop);
264 // The previous notification system required a CFRunLoop to be executing. Schedule the client's notifications back on their CFRunLoop, just in case it's important.
265 CFRunLoopRef runLoop = ix->mRunLoop;
266 secdebug("kcnotify", "sending event to runloop %p", runLoop);
268 // Set up our callback structures
269 CallbackMgrInfo* cbmInfo = (CallbackMgrInfo*) calloc(sizeof(CallbackMgrInfo), 1);
271 cbmInfo->secKeychainCallbackInfo.version = 0; // @@@ kKeychainAPIVersion;
272 cbmInfo->secKeychainCallbackInfo.item = createItemReference(inItem);
273 cbmInfo->secKeychainCallbackInfo.keychain = createKeychainReference(inKeychain);
274 cbmInfo->secKeychainCallbackInfo.pid = inPid;
276 cbmInfo->event = inEvent;
277 cbmInfo->callback = ix->mCallback;
278 cbmInfo->callbackContext = ix->mContext;
280 CFRunLoopTimerContext ctx;
281 memset(&ctx, 0, sizeof(ctx));
284 // make a run loop timer
285 CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent(), 0, 0, 0, CCallbackMgr::tellClient, &ctx);
287 // Actually call the callback the next time the run loop fires
288 CFRunLoopAddTimer(runLoop, timerRef, kCFRunLoopDefaultMode);
294 void CCallbackMgr::consume (SecurityServer::NotificationDomain domain, SecurityServer::NotificationEvent whichEvent, const CssmData &data)
296 NameValueDictionary dictionary (data);
298 // Decode from userInfo the event type, 'keychain' CFDict, and 'item' CFDict
299 SecKeychainEvent thisEvent = whichEvent;
302 const NameValuePair* pidRef = dictionary.FindByName(PID_KEY);
309 thisPid = n2h(*reinterpret_cast<pid_t*>(pidRef->Value().data ()));
312 Keychain thisKeychain;
314 list<CallbackInfo> eventCallbacks;
316 // Lock the global API lock before doing stuff with StorageManager.
317 // make sure we have a database identifier
318 if (dictionary.FindByName (SSUID_KEY) != 0)
320 StLock<Mutex>_(*globals().storageManager.getStorageManagerMutex());
321 DLDbIdentifier dbid = NameValueDictionary::MakeDLDbIdentifierFromNameValueDictionary(dictionary);
322 thisKeychain = globals().storageManager.keychain(dbid);
325 const NameValuePair* item = dictionary.FindByName(ITEM_KEY);
327 if (item && thisKeychain)
329 PrimaryKey pk(item->Value());
331 // if this is a deletion event, do the lookup slightly differently
332 if(thisEvent != kSecDeleteEvent) {
333 thisItem = thisKeychain->item(pk);
335 thisItem = thisKeychain->itemdeleted(pk);
339 // Deal with events that we care about ourselves first.
340 if (thisEvent == kSecDeleteEvent && thisKeychain.get() && thisItem.get())
341 thisKeychain->didDeleteItem(thisItem.get());
342 else if (thisEvent == kSecKeychainListChangedEvent)
343 globals().storageManager.forceUserSearchListReread();
345 eventCallbacks = CCallbackMgr::Instance().mEventCallbacks;
346 // We can safely release the global API lock now since thisKeychain and thisItem
347 // are CFRetained and will be until they go out of scope.
350 // Notify our process of this event.
351 CCallbackMgr::AlertClients(eventCallbacks, thisEvent, thisPid, thisKeychain, thisItem);