2 * Copyright (c) 2004 Apple Computer, 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@
26 // pcscmonitor - use PCSC to monitor smartcard reader/card state for securityd
28 // PCSCMonitor is the "glue" between PCSC and the securityd objects representing
29 // smartcard-related things. Its job is to manage the daemon and translate real-world
30 // events (such as card and device insertions) into the securityd object web.
32 // PCSCMonitor uses multiple inheritance to the hilt. It is (among others)
33 // (*) A notification listener, to listen to pcscd state notifications
34 // (*) A MachServer::Timer, to handle timed actions
35 // (*) A NotificationPort::Receiver, to get IOKit notifications of device insertions
36 // (*) A Child, to watch and manage the pcscd process
38 #include "pcscmonitor.h"
39 #include <security_utilities/logging.h>
40 #include <IOKit/usb/IOUSBLib.h>
44 // Fixed configuration parameters
46 static const char PCSCD_EXEC_PATH
[] = "/usr/sbin/pcscd"; // override with $PCSCDAEMON
47 static const char PCSCD_WORKING_DIR
[] = "/var/run/pcscd"; // pcscd's working directory
48 static const Time::Interval
PCSCD_IDLE_SHUTDOWN(120); // kill daemon if no devices present
52 // Construct a PCSCMonitor.
53 // We strongly assume there's only one of us around here.
55 // Note that this constructor may well run before the server loop has started.
56 // Don't call anything here that requires an active server loop (like Server::active()).
57 // In fact, you should push all the hard work into a timer, so as not to hold up the
58 // general startup process.
60 PCSCMonitor::PCSCMonitor(Server
&srv
, TokenCache
&tc
, ServiceLevel level
)
61 : Listener(kNotificationDomainPCSC
, SecurityServer::kNotificationAllEvents
),
62 MachServer::Timer(true), // "heavy" timer task
63 server(srv
), cache(tc
),
65 mTimerAction(&PCSCMonitor::initialSetup
),
68 // do all the smartcard-related work once the event loop has started
69 server
.setTimer(this, Time::now()); // ASAP
74 // Poll PCSC for smartcard status.
75 // We are enumerating all readers on each call.
77 void PCSCMonitor::pollReaders()
79 // open PCSC session if it's not already open
83 vector
<string
> names
; // will hold reader name C strings throughout
84 mSession
.listReaders(names
);
85 size_t count
= names
.size();
86 secdebug("pcsc", "%ld reader(s) in system", count
);
88 // build the PCSC status inquiry array
89 vector
<PCSC::ReaderState
> states(count
); // reader status array (PCSC style)
90 for (unsigned int n
= 0; n
< count
; n
++) {
91 PCSC::ReaderState
&state
= states
[n
];
92 ReaderMap::iterator it
= mReaders
.find(names
[n
]);
93 if (it
== mReaders
.end()) { // new reader
95 state
.name(names
[n
].c_str());
96 // lastKnown(PCSC_STATE_UNKNOWN)
97 // userData<Reader>() = NULL
99 state
= it
->second
->pcscState();
100 state
.name(names
[n
].c_str()); // OUR pointer
101 state
.lastKnown(state
.state());
102 state
.userData
<Reader
>() = it
->second
;
106 // now ask PCSC for status changes
107 mSession
.statusChange(states
);
109 if (Debug::dumping("pcsc"))
110 for (unsigned int n
= 0; n
< count
; n
++)
114 // make a set of previously known reader objects (to catch those who disappeared)
116 copy_second(mReaders
.begin(), mReaders
.end(), inserter(current
, current
.end()));
118 // match state array against them
119 for (unsigned int n
= 0; n
< count
; n
++) {
120 PCSC::ReaderState
&state
= states
[n
];
121 if (Reader
*reader
= state
.userData
<Reader
>()) {
122 // if PCSC flags a change, notify the Reader
124 reader
->update(state
);
125 // accounted for this reader
126 current
.erase(reader
);
128 RefPointer
<Reader
> newReader
= new Reader(cache
, state
);
129 mReaders
.insert(make_pair(state
.name(), newReader
));
130 Syslog::notice("Token reader %s inserted into system", state
.name());
131 newReader
->update(state
); // initial state setup
135 // now deal with vanished readers
136 for (ReaderSet::iterator it
= current
.begin(); it
!= current
.end(); it
++) {
137 secdebug("pcsc", "removing reader %s", (*it
)->name().c_str());
138 Syslog::notice("Token reader %s removed from system", (*it
)->name().c_str());
139 (*it
)->kill(); // prepare to die
140 mReaders
.erase((*it
)->name()); // remove from reader map
145 void PCSCMonitor::launchPcscd()
148 secdebug("pcsc", "launching pcscd to handle smartcard device(s)");
149 assert(Child::state() != alive
);
153 // if pcscd doesn't report a reader found soon, we'll kill it off
159 // Code to launch pcscd (run in child as a result of Child::fork())
161 void PCSCMonitor::childAction()
163 // move aside any old play area
164 const char *aside
= tempnam("/tmp", "pcscd");
165 if (::rename(PCSCD_WORKING_DIR
, aside
))
167 case ENOENT
: // no /tmp/pcsc (fine)
170 secdebug("pcsc", "failed too move %s - errno=%d", PCSCD_WORKING_DIR
, errno
);
174 secdebug("pcsc", "old /tmp/pcsc moved to %s", aside
);
176 // lessen the pain for debugging
178 freopen("/tmp/pcsc.debuglog", "a", stdout
); // shut up pcsc dumps to stdout
181 // execute the daemon
182 const char *pcscdPath
= PCSCD_EXEC_PATH
;
183 if (const char *env
= getenv("PCSCDAEMON"))
185 secdebug("pcsc", "exec(%s,-f)", pcscdPath
);
186 execl(pcscdPath
, pcscdPath
, "-f", NULL
);
192 // These events are sent by pcscd for our (sole) benefit.
194 void PCSCMonitor::notifyMe(SecurityServer::NotificationDomain domain
,
195 SecurityServer::NotificationEvent event
, const CssmData
&data
)
197 Server::active().longTermActivity();
198 StLock
<Mutex
> _(*this);
199 assert(mServiceLevel
== externalDaemon
|| Child::state() == alive
);
201 scheduleTimer(mReaders
.empty() && !mGoingToSleep
);
206 // Power event notifications
208 void PCSCMonitor::systemWillSleep()
210 StLock
<Mutex
> _(*this);
211 secdebug("pcsc", "setting sleep marker (%ld readers as of now)", mReaders
.size());
212 mGoingToSleep
= true;
213 server
.clearTimer(this);
216 void PCSCMonitor::systemIsWaking()
218 StLock
<Mutex
> _(*this);
219 secdebug("pcsc", "clearing sleep marker (%ld readers as of now)", mReaders
.size());
220 mGoingToSleep
= false;
221 scheduleTimer(mReaders
.empty());
228 void PCSCMonitor::action()
230 StLock
<Mutex
> _(*this);
231 (this->*mTimerAction
)();
232 mTimerAction
= &PCSCMonitor::noDeviceTimeout
;
237 // Update the timeout timer as requested (and indicated by context)
239 void PCSCMonitor::scheduleTimer(bool enable
)
241 if (Child::state() == alive
) // we ran pcscd; let's manage it
243 secdebug("pcsc", "setting idle timer for %g seconds", PCSCD_IDLE_SHUTDOWN
.seconds());
244 server
.setTimer(this, PCSCD_IDLE_SHUTDOWN
);
245 } else if (Timer::scheduled()) {
246 secdebug("pcsc", "clearing idle timer");
247 server
.clearTimer(this);
253 // Perform the initial PCSC subsystem initialization.
254 // This runs (shortly) after securityd is fully functional and the
255 // server loop has started.
257 void PCSCMonitor::initialSetup()
259 switch (mServiceLevel
) {
261 secdebug("pcsc", "smartcard operation is FORCED OFF");
265 secdebug("pcsc", "pcscd launch is forced on");
270 secdebug("pcsc", "using external pcscd (if any); no launch operations");
274 secdebug("pcsc", "setting up automatic PCSC management in %s mode",
275 mServiceLevel
== conservative
? "conservative" : "aggressive");
277 // receive Mach-based IOKit notifications through mIOKitNotifier
278 server
.add(mIOKitNotifier
);
280 // receive power event notifications (through our IOPowerWatcher personality)
283 // ask for IOKit notifications for all new USB devices and process present ones
284 IOKit::DeviceMatch
usbSelector(kIOUSBInterfaceClassName
);
285 IOKit::DeviceMatch
pcCardSelector("IOPCCard16Device");
286 mIOKitNotifier
.add(usbSelector
, *this); // this will scan existing USB devices
287 mIOKitNotifier
.add(pcCardSelector
, *this); // ditto for PC Card devices
288 if (mServiceLevel
== aggressive
) {
289 // catch custom non-composite USB devices - they don't have IOServices attached
290 IOKit::DeviceMatch
customUsbSelector(::IOServiceMatching("IOUSBDevice"));
291 mIOKitNotifier
.add(customUsbSelector
, *this); // ditto for custom USB devices
296 // we are NOT scanning for PCSC devices here. Pcscd will send us a notification when it's up
301 // This function is called (as a timer function) when there haven't been any (recognized)
302 // smartcard devicees in the system for a while.
304 void PCSCMonitor::noDeviceTimeout()
306 secdebug("pcsc", "killing pcscd (no smartcard devices present for %g seconds)",
307 PCSCD_IDLE_SHUTDOWN
.seconds());
308 assert(mReaders
.empty());
309 Child::kill(SIGTERM
);
314 // IOKit device event notification.
315 // Here we listen for newly inserted devices and check whether to launch pcscd.
317 void PCSCMonitor::ioChange(IOKit::DeviceIterator
&iterator
)
319 assert(mServiceLevel
!= externalDaemon
&& mServiceLevel
!= forcedOff
);
320 if (Child::state() == alive
) {
321 secdebug("pcsc", "pcscd is alive; ignoring device insertion(s)");
324 secdebug("pcsc", "processing device insertion notices");
325 while (IOKit::Device dev
= iterator()) {
327 switch (deviceSupport(dev
)) {
332 launch
= (mServiceLevel
== aggressive
);
342 secdebug("pcsc", "no relevant devices found");
347 // Check an IOKit device that's just come online to see if it's
348 // a smartcard device of some sort.
350 PCSCMonitor::DeviceSupport
PCSCMonitor::deviceSupport(const IOKit::Device
&dev
)
353 secdebug("scsel", "%s", dev
.path().c_str());
354 if (CFRef
<CFNumberRef
> cfInterface
= dev
.property
<CFNumberRef
>("bInterfaceClass"))
355 switch (IFDEBUG(uint32 clas
=) cfNumber(cfInterface
)) {
356 case kUSBChipSmartCardInterfaceClass
: // CCID smartcard reader - go
357 secdebug("scsel", " CCID smartcard reader recognized");
359 case kUSBVendorSpecificInterfaceClass
:
360 secdebug("scsel", " Vendor-specific interface - possible match");
363 secdebug("scsel", " interface class %ld is not a smartcard device", clas
);
366 if (CFRef
<CFNumberRef
> cfDevice
= dev
.property
<CFNumberRef
>("bDeviceClass"))
367 if (cfNumber(cfDevice
) == kUSBVendorSpecificClass
) {
368 secdebug("scsel", " Vendor-specific device - possible match");
373 secdebug("scsel", " exception while examining device - ignoring it");
380 // This gets called (by the Unix/Child system) when pcscd has died for any reason
382 void PCSCMonitor::dying()
384 Server::active().longTermActivity();
385 StLock
<Mutex
> _(*this);
386 assert(Child::state() == dead
);
387 if (!mReaders
.empty()) {
388 // uh-oh. We had readers connected when pcscd suddenly left
389 secdebug("pcsc", "%ld readers were present when pcscd died", mReaders
.size());
390 for (ReaderMap::const_iterator it
= mReaders
.begin(); it
!= mReaders
.end(); it
++) {
391 Reader
*reader
= it
->second
;
392 secdebug("pcsc", "removing reader %s", reader
->name().c_str());
393 reader
->kill(); // prepare to die
395 mReaders
.erase(mReaders
.begin(), mReaders
.end());
396 secdebug("pcsc", "orphaned readers cleared");
398 //@@@ this is where we would attempt a restart, if we wanted to...