]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurityd/lib/eventlistener.cpp
Security-58286.1.32.tar.gz
[apple/security.git] / OSX / libsecurityd / lib / eventlistener.cpp
1 /*
2 * Copyright (c) 2003-2004,2006,2011-2012,2014 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 #include <list>
25 #include <security_utilities/globalizer.h>
26 #include <security_utilities/threading.h>
27 #include "eventlistener.h"
28 #include "SharedMemoryClient.h"
29 #include <notify.h>
30 #include "sscommon.h"
31 #include <sys/syslog.h>
32 #include <Security/SecBasePriv.h>
33
34 using namespace MachPlusPlus;
35
36
37 namespace Security {
38 namespace SecurityServer {
39
40 typedef RefPointer<EventListener> EventPointer;
41 typedef std::list<EventPointer> EventListenerList;
42
43 static const char* GetNotificationName ()
44 {
45 // the name we give the client depends on the value of the environment variable "SECURITYSERVER"
46 const char* name = getenv (SECURITYSERVER_BOOTSTRAP_ENV);
47 if (name == NULL)
48 {
49 name = SharedMemoryCommon::kDefaultSecurityMessagesName;
50 }
51
52 return name;
53 }
54
55
56
57 class SharedMemoryClientMaker
58 {
59 private:
60 SharedMemoryClient mClient;
61
62 public:
63 SharedMemoryClientMaker ();
64 SharedMemoryClient* Client ();
65 };
66
67
68
69 SharedMemoryClientMaker::SharedMemoryClientMaker () : mClient (GetNotificationName (), kSharedMemoryPoolSize, SharedMemoryCommon::fixUID(getuid()))
70 {
71 secdebug("MDSPRIVACY","[%03d] SharedMemoryClientMaker uid: %d, euid: %d, name: %s", mClient.getUID(), getuid(), geteuid(), GetNotificationName ());
72 }
73
74
75
76 SharedMemoryClient* SharedMemoryClientMaker::Client ()
77 {
78 return &mClient;
79 }
80
81
82
83 ModuleNexus<EventListenerList> gEventListeners;
84 ModuleNexus<Mutex> gNotificationLock;
85 ModuleNexus<SharedMemoryClientMaker> gMemoryClient;
86
87 //
88 // Note that once we start notifications, we want receive them forever. Don't have a cancel option.
89 //
90 static bool InitializeNotifications () {
91 bool initializationComplete = false;
92 static dispatch_queue_t notification_queue = EventListener::getNotificationQueue();
93
94 secdebug("MDSPRIVACY","EventListener Init: uid: %d, euid: %d, name: %s", getuid(), geteuid(), GetNotificationName ());
95 // Initialize the memory client
96 gMemoryClient();
97
98 if (gMemoryClient().Client()->uninitialized()) {
99 secdebug("MDSPRIVACY","[%03d] FATAL: InitializeNotifications EventListener uninitialized; process will never get keychain notifications", getuid());
100 return initializationComplete;
101 }
102 int out_token;
103
104 notify_handler_t receive = ^(int token){
105 try {
106 SegmentOffsetType length;
107 UnavailableReason ur;
108
109 bool result;
110
111 // Trust the memory client to break our loop here
112 while (true)
113 {
114 u_int8_t *buffer = new u_int8_t[kSharedMemoryPoolSize];
115 {
116 StLock<Mutex> lock (gNotificationLock ());
117 result = gMemoryClient().Client()->ReadMessage(buffer, length, ur);
118 if (!result)
119 {
120 secdebug("MDSPRIVACY","[%03d] notify_handler ReadMessage ur: %d", getuid(), ur);
121 delete [] buffer;
122 return;
123 }
124 }
125
126 // Send this event off to the listeners
127 {
128 StLock<Mutex> lock (gNotificationLock ());
129 EventListenerList& eventList = gEventListeners();
130 std::set<EventPointer *> processedListeners;
131
132 // route the message to its destination
133 u_int32_t* ptr = (u_int32_t*) buffer;
134
135 // we have a message, do the semantics...
136 SecurityServer::NotificationDomain domain = (SecurityServer::NotificationDomain) OSSwapBigToHostInt32 (*ptr++);
137 SecurityServer::NotificationEvent event = (SecurityServer::NotificationEvent) OSSwapBigToHostInt32 (*ptr++);
138 CssmData data ((u_int8_t*) ptr, buffer + length - (u_int8_t*) ptr);
139
140 string descrip = SharedMemoryCommon::notificationDescription(domain, event);
141 secdebug("MDSPRIVACY","[%03d] notify_handler: %s", getuid(), descrip.c_str());
142 EventListenerList::iterator it = eventList.begin ();
143 while (it != eventList.end ())
144 {
145 EventPointer ep = *it++;
146 /*
147 * We can't hold the global event lock when processing callback handers
148 * so remember what items we have processes and don't process them again.
149 * and when we have done a callback we loop back and try again.
150 */
151 if (processedListeners.find(&ep) != processedListeners.end()) {
152 continue;
153 }
154 processedListeners.insert(&ep);
155
156 /* is this event for this Event handler */
157 if (ep->GetDomain() != domain || (ep->GetMask() & (1 << event)) == 0)
158 continue;
159
160 lock.unlock();
161
162 try {
163 ep->consume (domain, event, data);
164 } catch (CssmError &e) {
165 // If we throw, libnotify will abort the process. Log these...
166 secerror("caught CssmError while processing notification: %d %s", e.error, cssmErrorString(e.error));
167 }
168 lock.lock();
169 /*
170 * If we have to grab the lock again, start over iteration
171 */
172 it = eventList.begin ();
173 }
174 }
175
176 delete [] buffer;
177 }
178 }
179 // If these exceptions propagate, we crash our enclosing app. That's bad. Worse than silently swallowing the error.
180 catch(CssmError &cssme) {
181 secerror("caught CssmError during notification: %d %s", (int) cssme.error, cssmErrorString(cssme.error));
182 }
183 catch(UnixError &ue) {
184 secerror("caught UnixError during notification: %d %s", ue.unixError(), ue.what());
185 }
186 catch (MacOSError mose) {
187 secerror("caught MacOSError during notification: %d %s", (int) mose.osStatus(), mose.what());
188 }
189 catch (...) {
190 secerror("caught unknown error during notification");
191 }
192 };
193
194 uint32_t status = notify_register_dispatch(GetNotificationName(), &out_token, notification_queue, receive);
195 if (status) {
196 secerror("notify_register_dispatch failed: %d", status);
197 syslog(LOG_ERR, "notify_register_dispatch failed: %d", status);
198 } else {
199 initializationComplete = true;
200 }
201 return initializationComplete;
202 }
203
204
205 EventListener::EventListener (NotificationDomain domain, NotificationMask eventMask)
206 : mInitialized(false), mDomain (domain), mMask (eventMask)
207 {
208 // make sure that notifications are turned on.
209 mInitialized = InitializeNotifications();
210 }
211
212 //
213 // StopNotification() is needed on destruction; everyone else cleans up after themselves.
214 //
215 EventListener::~EventListener () {
216 if (initialized()) {
217 StLock<Mutex> lock (gNotificationLock ());
218
219 // find the listener in the list and remove it
220 EventListenerList::iterator it = std::find (gEventListeners ().begin (),
221 gEventListeners ().end (),
222 this);
223 if (it != gEventListeners ().end ())
224 {
225 gEventListeners ().erase (it);
226 }
227 }
228 }
229
230 // get rid of the pure virtual
231 void EventListener::consume(NotificationDomain, NotificationEvent, const Security::CssmData&)
232 {
233 }
234
235
236
237 void EventListener::FinishedInitialization(EventListener *eventListener) {
238 if (eventListener->initialized()) {
239 StLock<Mutex> lock (gNotificationLock ());
240 gEventListeners().push_back (eventListener);
241 }
242 }
243
244 dispatch_once_t EventListener::queueOnceToken = 0;
245 dispatch_queue_t EventListener::notificationQueue = NULL;
246
247 dispatch_queue_t EventListener::getNotificationQueue() {
248 dispatch_once(&queueOnceToken, ^{
249 notificationQueue = dispatch_queue_create("com.apple.security.keychain-notification-queue", DISPATCH_QUEUE_SERIAL);
250 });
251
252 return notificationQueue;
253 }
254
255
256 } // end namespace SecurityServer
257 } // end namespace Security