smartcard 3.8.0 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/binding.gyp +5 -1
- package/dist/lib/devices.d.ts +14 -0
- package/dist/lib/devices.d.ts.map +1 -1
- package/dist/lib/devices.js +54 -23
- package/dist/lib/devices.js.map +1 -1
- package/dist/lib/types.d.ts +4 -2
- package/dist/lib/types.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/addon.cpp +4 -1
- package/src/addon_data.h +23 -0
- package/src/async_workers.cpp +161 -16
- package/src/async_workers.h +88 -21
- package/src/pcsc_card.cpp +3 -5
- package/src/pcsc_card.h +0 -2
- package/src/pcsc_context.cpp +25 -30
- package/src/pcsc_context.h +7 -3
- package/src/pcsc_napi_error.h +1 -8
- package/src/pcsc_reader.cpp +3 -5
- package/src/pcsc_reader.h +0 -2
- package/src/platform/pcsc.h +22 -0
- package/src/reader_monitor.cpp +339 -162
- package/src/reader_monitor.h +37 -6
- package/src/reader_state_utils.h +42 -2
package/src/reader_monitor.cpp
CHANGED
|
@@ -9,8 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
using smartcard::CardEvent;
|
|
11
11
|
using smartcard::DetectCardStateChange;
|
|
12
|
-
|
|
13
|
-
Napi::FunctionReference ReaderMonitor::constructor;
|
|
12
|
+
using smartcard::DetectCardStateChangeAcrossOutage;
|
|
14
13
|
|
|
15
14
|
// Format a PC/SC error as "message (0xXXXXXXXX)" so the numeric code
|
|
16
15
|
// survives to JS even when only the message string is consumed.
|
|
@@ -20,11 +19,31 @@ static std::string FormatPCSCError(LONG code) {
|
|
|
20
19
|
return std::string(GetPCSCErrorString(code)) + hex;
|
|
21
20
|
}
|
|
22
21
|
|
|
22
|
+
// The context will never work again (Smart Card service stopped or
|
|
23
|
+
// restarted, dead handle), so release it and re-establish (Issue #119).
|
|
24
|
+
// SCARD_E_INVALID_PARAMETER is deliberately not one: it is a per-call
|
|
25
|
+
// argument error, and recycling a healthy context would re-seed lastState
|
|
26
|
+
// and latch away pending transitions.
|
|
27
|
+
static bool IsContextFatal(LONG result) {
|
|
28
|
+
DWORD code = static_cast<DWORD>(result);
|
|
29
|
+
if (code == SCARD_E_SERVICE_STOPPED || code == SCARD_E_NO_SERVICE ||
|
|
30
|
+
code == SCARD_E_INVALID_HANDLE) {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
#ifdef _WIN32
|
|
34
|
+
// WinSCard may report a dead context as the Win32 error instead
|
|
35
|
+
if (code == ERROR_INVALID_HANDLE) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
#endif
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
23
42
|
// Number of iterations between forced full state refreshes (Windows reliability fix)
|
|
24
43
|
static const int STATE_REFRESH_INTERVAL = 10;
|
|
25
44
|
|
|
26
45
|
// Event data passed from worker thread to JS thread
|
|
27
|
-
struct EventData {
|
|
46
|
+
struct ReaderMonitor::EventData {
|
|
28
47
|
std::string eventType;
|
|
29
48
|
std::string readerName;
|
|
30
49
|
DWORD state;
|
|
@@ -39,9 +58,6 @@ Napi::Object ReaderMonitor::Init(Napi::Env env, Napi::Object exports) {
|
|
|
39
58
|
InstanceAccessor("isRunning", &ReaderMonitor::GetIsRunning, nullptr),
|
|
40
59
|
});
|
|
41
60
|
|
|
42
|
-
constructor = Napi::Persistent(func);
|
|
43
|
-
constructor.SuppressDestruct();
|
|
44
|
-
|
|
45
61
|
exports.Set("ReaderMonitor", func);
|
|
46
62
|
return exports;
|
|
47
63
|
}
|
|
@@ -51,19 +67,43 @@ ReaderMonitor::ReaderMonitor(const Napi::CallbackInfo& info)
|
|
|
51
67
|
context_(0),
|
|
52
68
|
contextValid_(false),
|
|
53
69
|
running_(false),
|
|
54
|
-
tsfnActive_(false)
|
|
70
|
+
tsfnActive_(false),
|
|
71
|
+
cleanupHookAdded_(false),
|
|
72
|
+
outagePending_(false) {
|
|
55
73
|
}
|
|
56
74
|
|
|
57
75
|
ReaderMonitor::~ReaderMonitor() {
|
|
58
|
-
|
|
76
|
+
Shutdown();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Stop the monitor thread and release the tsfn and the PC/SC context.
|
|
80
|
+
// stop(), the destructor (GC, or Node finalizing objects at environment
|
|
81
|
+
// teardown) and the environment cleanup hook all end up here.
|
|
82
|
+
void ReaderMonitor::Shutdown() {
|
|
83
|
+
if (cleanupHookAdded_) {
|
|
84
|
+
napi_remove_env_cleanup_hook(Env(), OnEnvCleanup, this);
|
|
85
|
+
cleanupHookAdded_ = false;
|
|
86
|
+
}
|
|
87
|
+
|
|
59
88
|
if (running_) {
|
|
60
89
|
running_ = false;
|
|
90
|
+
|
|
91
|
+
// Wake the monitor thread if it is pausing between retries
|
|
92
|
+
{
|
|
93
|
+
std::lock_guard<std::mutex> lock(pauseMutex_);
|
|
94
|
+
}
|
|
95
|
+
pauseCv_.notify_all();
|
|
96
|
+
|
|
97
|
+
// Cancel any blocking SCardGetStatusChange call. mutex_ guards
|
|
98
|
+
// context_/contextValid_ against the recovery path swapping them
|
|
99
|
+
// on the monitor thread.
|
|
61
100
|
{
|
|
62
101
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
63
102
|
if (contextValid_) {
|
|
64
103
|
SCardCancel(context_);
|
|
65
104
|
}
|
|
66
105
|
}
|
|
106
|
+
|
|
67
107
|
if (monitorThread_.joinable()) {
|
|
68
108
|
monitorThread_.join();
|
|
69
109
|
}
|
|
@@ -79,7 +119,28 @@ ReaderMonitor::~ReaderMonitor() {
|
|
|
79
119
|
|
|
80
120
|
if (contextValid_) {
|
|
81
121
|
SCardReleaseContext(context_);
|
|
122
|
+
contextValid_ = false;
|
|
123
|
+
context_ = 0;
|
|
82
124
|
}
|
|
125
|
+
|
|
126
|
+
readerStates_.clear();
|
|
127
|
+
outagePending_ = false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Node is tearing the environment down (a worker exiting or terminated)
|
|
131
|
+
// with the monitor still running. The tsfn's own cleanup hook would close
|
|
132
|
+
// it first and finalize this object only afterwards, so the destructor's
|
|
133
|
+
// Release() would reach a tsfn Node has finished with: on Node 24.15+ it
|
|
134
|
+
// locks the tsfn's mutex again (SIGABRT, or a hang on Linux); on Node
|
|
135
|
+
// 20/22 it touches a tsfn being deleted, and the monitor thread may still
|
|
136
|
+
// push to it (spec/README.md, finding 4). Node runs cleanup hooks newest
|
|
137
|
+
// first, and start() adds this one after the tsfn has added its own, so
|
|
138
|
+
// it stops the monitor while the tsfn is still alive.
|
|
139
|
+
void ReaderMonitor::OnEnvCleanup(void* arg) {
|
|
140
|
+
auto* self = static_cast<ReaderMonitor*>(arg);
|
|
141
|
+
// Node drops the hook itself once it has run
|
|
142
|
+
self->cleanupHookAdded_ = false;
|
|
143
|
+
self->Shutdown();
|
|
83
144
|
}
|
|
84
145
|
|
|
85
146
|
Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
|
|
@@ -114,19 +175,25 @@ Napi::Value ReaderMonitor::Start(const Napi::CallbackInfo& info) {
|
|
|
114
175
|
auto sessionActive = std::make_shared<std::atomic<bool>>(true);
|
|
115
176
|
|
|
116
177
|
// Create thread-safe function
|
|
117
|
-
tsfn_ =
|
|
178
|
+
tsfn_ = EventTsfn::New(
|
|
118
179
|
env,
|
|
119
180
|
callback,
|
|
120
181
|
"ReaderMonitor",
|
|
121
|
-
0,
|
|
122
|
-
1,
|
|
123
|
-
|
|
124
|
-
|
|
182
|
+
0, // Unlimited queue size
|
|
183
|
+
1, // 1 initial thread
|
|
184
|
+
nullptr, // No context
|
|
185
|
+
[sessionActive](Napi::Env, void*, std::nullptr_t*) {
|
|
186
|
+
// Called when Node finalizes the tsfn: once it is released
|
|
187
|
+
// (stop()) and its queue has drained, or at environment teardown
|
|
125
188
|
sessionActive->store(false);
|
|
126
189
|
}
|
|
127
190
|
);
|
|
128
191
|
tsfnActive_ = true;
|
|
129
192
|
|
|
193
|
+
// Added after the tsfn, so that at environment teardown it runs first
|
|
194
|
+
cleanupHookAdded_ =
|
|
195
|
+
napi_add_env_cleanup_hook(env, OnEnvCleanup, this) == napi_ok;
|
|
196
|
+
|
|
130
197
|
// Start monitoring
|
|
131
198
|
running_ = true;
|
|
132
199
|
monitorThread_ = std::thread(&ReaderMonitor::MonitorLoop, this, sessionActive);
|
|
@@ -141,35 +208,7 @@ Napi::Value ReaderMonitor::Stop(const Napi::CallbackInfo& info) {
|
|
|
141
208
|
return env.Undefined();
|
|
142
209
|
}
|
|
143
210
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
// Cancel any blocking SCardGetStatusChange call. mutex_ guards
|
|
147
|
-
// context_/contextValid_ against the recovery path swapping them
|
|
148
|
-
// on the monitor thread.
|
|
149
|
-
{
|
|
150
|
-
std::lock_guard<std::mutex> lock(mutex_);
|
|
151
|
-
if (contextValid_) {
|
|
152
|
-
SCardCancel(context_);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Wait for thread to finish
|
|
157
|
-
if (monitorThread_.joinable()) {
|
|
158
|
-
monitorThread_.join();
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// Release thread-safe function
|
|
162
|
-
tsfn_.Release();
|
|
163
|
-
tsfnActive_ = false;
|
|
164
|
-
|
|
165
|
-
// Release context
|
|
166
|
-
if (contextValid_) {
|
|
167
|
-
SCardReleaseContext(context_);
|
|
168
|
-
contextValid_ = false;
|
|
169
|
-
context_ = 0;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
readerStates_.clear();
|
|
211
|
+
Shutdown();
|
|
173
212
|
|
|
174
213
|
return env.Undefined();
|
|
175
214
|
}
|
|
@@ -178,37 +217,57 @@ Napi::Value ReaderMonitor::GetIsRunning(const Napi::CallbackInfo& info) {
|
|
|
178
217
|
return Napi::Boolean::New(info.Env(), running_.load());
|
|
179
218
|
}
|
|
180
219
|
|
|
181
|
-
//
|
|
182
|
-
//
|
|
183
|
-
//
|
|
220
|
+
// Emit what a detected card event means to JS. state is the reader's
|
|
221
|
+
// state now; a Replaced card is reported as the old card leaving, then the
|
|
222
|
+
// new one arriving, and the leaving event gets that state as an empty
|
|
223
|
+
// reader so its flags match the event.
|
|
224
|
+
void ReaderMonitor::EmitCardEvent(CardEvent event, const std::string& readerName,
|
|
225
|
+
DWORD state, const std::vector<uint8_t>& atr) {
|
|
226
|
+
if (event == CardEvent::Removed) {
|
|
227
|
+
EmitEvent("card-removed", readerName, state, {});
|
|
228
|
+
} else if (event == CardEvent::Replaced) {
|
|
229
|
+
EmitEvent("card-removed", readerName,
|
|
230
|
+
(state & ~SCARD_STATE_PRESENT) | SCARD_STATE_EMPTY, {});
|
|
231
|
+
}
|
|
232
|
+
if (event == CardEvent::Inserted || event == CardEvent::Replaced) {
|
|
233
|
+
EmitEvent("card-inserted", readerName, state, atr);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Commit point for card state transitions seen by the main wait.
|
|
238
|
+
// ResyncReaderList (PnP, timeouts, periodic refresh, recovery) detects
|
|
239
|
+
// events from its fresh reads with the same DetectCardStateChange and
|
|
240
|
+
// EmitCardEvent; UpdateReaderList, which stores those reads, applies the
|
|
241
|
+
// same IGNORE masking.
|
|
184
242
|
void ReaderMonitor::ApplyCardStateChange(ReaderInfo& info, const std::string& readerName,
|
|
185
243
|
const SCARD_READERSTATE& readerState) {
|
|
186
244
|
DWORD newState = readerState.dwEventState & ~SCARD_STATE_CHANGED;
|
|
187
|
-
CardEvent event = DetectCardStateChange(info.lastState, newState, SCARD_STATE_PRESENT
|
|
245
|
+
CardEvent event = DetectCardStateChange(info.lastState, newState, SCARD_STATE_PRESENT,
|
|
246
|
+
SMARTCARD_PCSC_COUNTS_CARD_EVENTS);
|
|
188
247
|
|
|
189
248
|
// Commit so a stale lastState can't make the next SCardGetStatusChange
|
|
190
249
|
// re-report the same change - but never store SCARD_STATE_IGNORE (fed
|
|
191
250
|
// back as dwCurrentState it excludes the reader from future waits), and
|
|
192
|
-
// don't absorb an unknown/empty no-event result:
|
|
193
|
-
// vanished
|
|
251
|
+
// don't absorb an unknown/empty no-event result: a reader that vanished
|
|
252
|
+
// during the wait is dropped by the PnP resync, one that vanished
|
|
253
|
+
// between waits by the SCARD_E_UNKNOWN_READER resync.
|
|
194
254
|
bool unusable = readerState.dwEventState == 0 ||
|
|
195
255
|
(newState & SCARD_STATE_UNKNOWN) != 0;
|
|
196
256
|
if (event != CardEvent::None || !unusable) {
|
|
197
257
|
info.lastState = newState & ~SCARD_STATE_IGNORE;
|
|
198
258
|
}
|
|
199
259
|
|
|
200
|
-
if (event == CardEvent::Inserted) {
|
|
260
|
+
if (event == CardEvent::Inserted || event == CardEvent::Replaced) {
|
|
201
261
|
// cbAtr comes from the PC/SC service; clamp to the actual buffer size
|
|
202
262
|
DWORD atrLen = readerState.cbAtr;
|
|
203
263
|
if (atrLen > sizeof(readerState.rgbAtr)) {
|
|
204
264
|
atrLen = sizeof(readerState.rgbAtr);
|
|
205
265
|
}
|
|
206
266
|
info.atr.assign(readerState.rgbAtr, readerState.rgbAtr + atrLen);
|
|
207
|
-
EmitEvent("card-inserted", readerName, newState, info.atr);
|
|
208
267
|
} else if (event == CardEvent::Removed) {
|
|
209
268
|
info.atr.clear();
|
|
210
|
-
EmitEvent("card-removed", readerName, newState, {});
|
|
211
269
|
}
|
|
270
|
+
EmitCardEvent(event, readerName, newState, info.atr);
|
|
212
271
|
}
|
|
213
272
|
|
|
214
273
|
void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive) {
|
|
@@ -227,14 +286,48 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
227
286
|
std::vector<SCARD_READERSTATE> states;
|
|
228
287
|
std::vector<std::string> readerNames;
|
|
229
288
|
int iterationCount = 0;
|
|
289
|
+
// The last wait failed with SCARD_E_UNKNOWN_READER right after a resync
|
|
290
|
+
bool resyncedForUnknownReader = false;
|
|
291
|
+
// The PnP entry's dwCurrentState: the reader event count from the last
|
|
292
|
+
// wait (SMARTCARD_PCSC_PNP_COUNTS_READER_EVENTS), so that a reader
|
|
293
|
+
// plugged in or unplugged between two waits ends the next one at once
|
|
294
|
+
// rather than at the next re-list. SCARD_STATE_UNAWARE until known.
|
|
295
|
+
DWORD pnpCurrentState = SCARD_STATE_UNAWARE;
|
|
230
296
|
|
|
231
297
|
while (running_ && sessionActive->load()) {
|
|
232
|
-
//
|
|
233
|
-
//
|
|
298
|
+
// The context died in a service outage and re-establishing it
|
|
299
|
+
// failed: keep trying, once a second, before anything uses it.
|
|
300
|
+
// (Waiting on the dead handle instead relied on the error that
|
|
301
|
+
// returns, which differs by platform: pcsc-lite says
|
|
302
|
+
// SCARD_E_INVALID_HANDLE, which was in the recovery list below,
|
|
303
|
+
// but WinSCard may say ERROR_INVALID_HANDLE, which isn't.)
|
|
304
|
+
if (!contextValid_) {
|
|
305
|
+
LONG recovered = RecoverContext();
|
|
306
|
+
if (recovered != SCARD_S_SUCCESS) {
|
|
307
|
+
// One error event a second while the service is down
|
|
308
|
+
EmitEvent("error", FormatPCSCError(recovered), 0, {},
|
|
309
|
+
static_cast<DWORD>(recovered));
|
|
310
|
+
// Still down a second after it failed: no reader can be
|
|
311
|
+
// used, so report them all detached (once). On Windows the
|
|
312
|
+
// service stops when its last reader is unplugged, so this
|
|
313
|
+
// is also how that unplug is reported.
|
|
314
|
+
DetachAllReaders();
|
|
315
|
+
PauseBeforeRetry(sessionActive);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
// The recovery re-listed the readers
|
|
319
|
+
iterationCount = 0;
|
|
320
|
+
resyncedForUnknownReader = false;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Periodic full resync to handle Windows PC/SC state drift (Issue
|
|
324
|
+
// #111). It re-lists readers too, because under constant card
|
|
325
|
+
// activity the wait may not time out, and the timeout path's
|
|
326
|
+
// re-list (see below) catches what the waits can't see.
|
|
234
327
|
if (++iterationCount >= STATE_REFRESH_INTERVAL) {
|
|
235
328
|
iterationCount = 0;
|
|
236
329
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
237
|
-
|
|
330
|
+
ResyncReaderList();
|
|
238
331
|
}
|
|
239
332
|
|
|
240
333
|
// Build states array using reader names from our map
|
|
@@ -244,10 +337,13 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
244
337
|
readerNames.clear();
|
|
245
338
|
|
|
246
339
|
// Reserve for all tracked readers + the PnP entry so no
|
|
247
|
-
// push_back reallocates after szReader pointers are taken
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
//
|
|
340
|
+
// push_back reallocates after szReader pointers are taken: a
|
|
341
|
+
// reallocation moves the strings, and short names live inline
|
|
342
|
+
// in the string object (SSO - 15 chars on MSVC, e.g. "ACS ACR122
|
|
343
|
+
// 0"), so every szReader taken earlier would dangle and
|
|
344
|
+
// SCardGetStatusChange would read garbage. With a single reader
|
|
345
|
+
// the PnP push_back below would otherwise reallocate on the first
|
|
346
|
+
// iteration.
|
|
251
347
|
readerNames.reserve(readerStates_.size() + 1);
|
|
252
348
|
|
|
253
349
|
// Add known readers - use the map for name-based lookup
|
|
@@ -263,7 +359,7 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
263
359
|
readerNames.push_back("\\\\?PnP?\\Notification");
|
|
264
360
|
SCARD_READERSTATE pnpState = {};
|
|
265
361
|
pnpState.szReader = readerNames.back().c_str();
|
|
266
|
-
pnpState.dwCurrentState =
|
|
362
|
+
pnpState.dwCurrentState = pnpCurrentState;
|
|
267
363
|
states.push_back(pnpState);
|
|
268
364
|
}
|
|
269
365
|
|
|
@@ -278,13 +374,48 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
278
374
|
break;
|
|
279
375
|
}
|
|
280
376
|
|
|
377
|
+
// A returned wait has the count in the PnP entry (pushed last);
|
|
378
|
+
// a failed one may not
|
|
379
|
+
if (SMARTCARD_PCSC_PNP_COUNTS_READER_EVENTS &&
|
|
380
|
+
(result == SCARD_S_SUCCESS ||
|
|
381
|
+
result == static_cast<LONG>(SCARD_E_TIMEOUT))) {
|
|
382
|
+
pnpCurrentState = states.back().dwEventState & 0xFFFF0000;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// A reader passed to the wait has gone: pcsc-lite checks every name
|
|
386
|
+
// before waiting and rejects the whole call, so every later wait
|
|
387
|
+
// would fail the same way and no reader's events get through
|
|
388
|
+
// (spec/README.md, finding 3). An unplug is routine, so re-list and
|
|
389
|
+
// wait again at once - no error event, no sleep. If it fails the
|
|
390
|
+
// same way straight after a re-list, take the error path below (one
|
|
391
|
+
// error a second, still re-listing) so a lasting failure can't spin.
|
|
392
|
+
bool unknownReader = result == static_cast<LONG>(SCARD_E_UNKNOWN_READER);
|
|
393
|
+
if (unknownReader && !resyncedForUnknownReader) {
|
|
394
|
+
resyncedForUnknownReader = true;
|
|
395
|
+
std::lock_guard<std::mutex> lock(mutex_);
|
|
396
|
+
ResyncReaderList();
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
resyncedForUnknownReader = unknownReader;
|
|
400
|
+
|
|
281
401
|
if (result == static_cast<LONG>(SCARD_E_TIMEOUT)) {
|
|
282
|
-
// Timeout -
|
|
283
|
-
//
|
|
284
|
-
//
|
|
285
|
-
//
|
|
402
|
+
// Timeout - re-list readers and re-read every reader with
|
|
403
|
+
// SCARD_STATE_UNAWARE to catch missed events:
|
|
404
|
+
// - On Windows, dwEventState after timeout may just mirror
|
|
405
|
+
// dwCurrentState rather than the hardware (Issue #111).
|
|
406
|
+
// - Without a reader event count (see pnpCurrentState) the PnP
|
|
407
|
+
// entry reports only reader changes made during a call; a
|
|
408
|
+
// reader plugged in between two waits is otherwise never
|
|
409
|
+
// announced (spec/README.md, finding 2). With the count, one
|
|
410
|
+
// plugged in before the first wait still isn't.
|
|
411
|
+
// - pcsc-lite compares a reader's card event counter only if
|
|
412
|
+
// the one passed in is nonzero, so a card swapped between
|
|
413
|
+
// waits in a reader that was plugged in with it doesn't end
|
|
414
|
+
// the wait (Events-seeded-swap).
|
|
415
|
+
// That is the periodic resync's work too, so restart its count.
|
|
416
|
+
iterationCount = 0;
|
|
286
417
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
287
|
-
|
|
418
|
+
ResyncReaderList();
|
|
288
419
|
continue;
|
|
289
420
|
}
|
|
290
421
|
|
|
@@ -294,44 +425,28 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
294
425
|
// consumers); state stays 0 so it keeps its bitmask meaning.
|
|
295
426
|
EmitEvent("error", FormatPCSCError(result), 0, {}, static_cast<DWORD>(result));
|
|
296
427
|
|
|
297
|
-
//
|
|
298
|
-
//
|
|
299
|
-
// is
|
|
300
|
-
//
|
|
301
|
-
// SCardGetStatusChange on the zeroed handle fails fast and we
|
|
302
|
-
// land back here - still one attempt per second.
|
|
303
|
-
// SCARD_E_INVALID_PARAMETER is deliberately not in this list: it
|
|
304
|
-
// is a per-call argument error, and recycling a healthy context
|
|
305
|
-
// would re-seed lastState and latch away pending transitions.
|
|
428
|
+
// The context is dead: release it. The top of the loop
|
|
429
|
+
// re-establishes it after the pause - once a second until the
|
|
430
|
+
// service is back - so there is one recovery path, and it
|
|
431
|
+
// can't spin.
|
|
306
432
|
DWORD ucode = static_cast<DWORD>(result);
|
|
307
|
-
if (
|
|
308
|
-
ucode == SCARD_E_NO_SERVICE ||
|
|
309
|
-
ucode == SCARD_E_INVALID_HANDLE) {
|
|
433
|
+
if (IsContextFatal(result)) {
|
|
310
434
|
// mutex_ also guards context_/contextValid_ against Stop()
|
|
311
|
-
// and the destructor reading them for SCardCancel
|
|
435
|
+
// and the destructor reading them for SCardCancel
|
|
312
436
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
313
437
|
if (contextValid_) {
|
|
314
438
|
SCardReleaseContext(context_);
|
|
315
439
|
contextValid_ = false;
|
|
316
440
|
}
|
|
317
441
|
context_ = 0;
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
// rebuild, emit whatever changed during the outage, and
|
|
324
|
-
// tell the JS layer to refresh its own context.
|
|
325
|
-
ResyncReaderList();
|
|
326
|
-
EmitEvent("monitor-recovered", "", 0, {});
|
|
327
|
-
} else {
|
|
328
|
-
// The error event above already fired this cycle - stay
|
|
329
|
-
// at one error event per second while the service is down.
|
|
330
|
-
context_ = 0;
|
|
331
|
-
}
|
|
442
|
+
} else if (ucode == SCARD_E_UNKNOWN_READER) {
|
|
443
|
+
// Still failing after the re-list above: keep re-listing,
|
|
444
|
+
// once a second
|
|
445
|
+
std::lock_guard<std::mutex> lock(mutex_);
|
|
446
|
+
ResyncReaderList();
|
|
332
447
|
}
|
|
333
448
|
|
|
334
|
-
|
|
449
|
+
PauseBeforeRetry(sessionActive);
|
|
335
450
|
continue;
|
|
336
451
|
}
|
|
337
452
|
|
|
@@ -363,54 +478,71 @@ void ReaderMonitor::MonitorLoop(std::shared_ptr<std::atomic<bool>> sessionActive
|
|
|
363
478
|
}
|
|
364
479
|
}
|
|
365
480
|
|
|
366
|
-
// Re-
|
|
367
|
-
//
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
481
|
+
// Re-establish the context after a service outage. On success tell JS
|
|
482
|
+
// (monitor-recovered), then report what changed during the outage.
|
|
483
|
+
LONG ReaderMonitor::RecoverContext() {
|
|
484
|
+
// Establish outside mutex_: it can take a while when the service is
|
|
485
|
+
// starting, and Shutdown() needs mutex_ to cancel
|
|
486
|
+
SCARDCONTEXT context = 0;
|
|
487
|
+
LONG result = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
|
|
488
|
+
if (result != SCARD_S_SUCCESS) {
|
|
489
|
+
return result;
|
|
372
490
|
}
|
|
491
|
+
std::lock_guard<std::mutex> lock(mutex_);
|
|
492
|
+
context_ = context;
|
|
493
|
+
contextValid_ = true;
|
|
494
|
+
// JS's own context died in the same outage. Tell it first, so it
|
|
495
|
+
// replaces that context before handling the card events below.
|
|
496
|
+
EmitEvent("monitor-recovered", "", 0, {});
|
|
497
|
+
// Reader states were tracked against the dead context: rebuild them.
|
|
498
|
+
// Every card handle died too, so each card still in its reader is
|
|
499
|
+
// reported as replaced, and JS connects to it again. (If the readers
|
|
500
|
+
// were reported detached during the outage, they are attached again.)
|
|
501
|
+
ResyncReaderList(true);
|
|
502
|
+
return SCARD_S_SUCCESS;
|
|
503
|
+
}
|
|
373
504
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
std::
|
|
378
|
-
names.reserve(readerStates_.size());
|
|
379
|
-
states.reserve(readerStates_.size());
|
|
380
|
-
|
|
505
|
+
// The service is unavailable: report every reader detached and forget
|
|
506
|
+
// them. Recovery's resync attaches whatever is there when it is back.
|
|
507
|
+
void ReaderMonitor::DetachAllReaders() {
|
|
508
|
+
std::lock_guard<std::mutex> lock(mutex_);
|
|
381
509
|
for (const auto& pair : readerStates_) {
|
|
382
|
-
|
|
383
|
-
SCARD_READERSTATE state = {};
|
|
384
|
-
state.szReader = names.back().c_str();
|
|
385
|
-
state.dwCurrentState = SCARD_STATE_UNAWARE; // Force fresh state
|
|
386
|
-
states.push_back(state);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
if (SCardGetStatusChange(context_, 0, states.data(), states.size()) != SCARD_S_SUCCESS) {
|
|
390
|
-
return;
|
|
510
|
+
EmitEvent("reader-detached", pair.first, 0, {});
|
|
391
511
|
}
|
|
512
|
+
readerStates_.clear();
|
|
513
|
+
outagePending_ = false;
|
|
514
|
+
}
|
|
392
515
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
516
|
+
// The 1 s pause between retries on the error path. Shutdown() cuts it
|
|
517
|
+
// short, so stop(), the destructor and the teardown hook don't wait it out.
|
|
518
|
+
void ReaderMonitor::PauseBeforeRetry(const std::shared_ptr<std::atomic<bool>>& sessionActive) {
|
|
519
|
+
std::unique_lock<std::mutex> lock(pauseMutex_);
|
|
520
|
+
pauseCv_.wait_for(lock, std::chrono::milliseconds(1000), [&] {
|
|
521
|
+
return !running_ || !sessionActive->load();
|
|
522
|
+
});
|
|
399
523
|
}
|
|
400
524
|
|
|
401
525
|
// Rebuild readerStates_ and emit the difference: reader-attached/detached
|
|
402
|
-
// for membership changes, card-inserted/removed for presence changes
|
|
403
|
-
// surviving readers. Needed because UpdateReaderList re-seeds
|
|
404
|
-
// from a fresh SCARD_STATE_UNAWARE query, which would otherwise
|
|
405
|
-
// latch away any transition that happened since the last wait
|
|
406
|
-
//
|
|
407
|
-
|
|
526
|
+
// for membership changes, card-inserted/removed for presence changes and
|
|
527
|
+
// swaps on surviving readers. Needed because UpdateReaderList re-seeds
|
|
528
|
+
// lastState from a fresh SCARD_STATE_UNAWARE query, which would otherwise
|
|
529
|
+
// silently latch away any transition that happened since the last wait
|
|
530
|
+
// (PnP churn, a vanished reader, a timeout, or a service outage the
|
|
531
|
+
// recovery path just healed). Caller holds mutex_. acrossOutage: the old
|
|
532
|
+
// states were read before a service outage (see RecoverContext).
|
|
533
|
+
void ReaderMonitor::ResyncReaderList(bool acrossOutage) {
|
|
408
534
|
std::unordered_map<std::string, DWORD> oldStates;
|
|
409
535
|
for (const auto& pair : readerStates_) {
|
|
410
536
|
oldStates[pair.first] = pair.second.lastState;
|
|
411
537
|
}
|
|
412
538
|
|
|
413
|
-
UpdateReaderList();
|
|
539
|
+
bool fresh = UpdateReaderList();
|
|
540
|
+
|
|
541
|
+
// Across an outage only a fresh reading shows which cards are still
|
|
542
|
+
// there; if this one isn't, the next resync owes the comparison
|
|
543
|
+
acrossOutage = acrossOutage || outagePending_;
|
|
544
|
+
outagePending_ = acrossOutage && !fresh;
|
|
545
|
+
bool replaceHeldCards = acrossOutage && fresh;
|
|
414
546
|
|
|
415
547
|
for (const auto& pair : readerStates_) {
|
|
416
548
|
if (oldStates.find(pair.first) == oldStates.end()) {
|
|
@@ -429,27 +561,38 @@ void ReaderMonitor::ResyncReaderList() {
|
|
|
429
561
|
if (oldIt == oldStates.end()) {
|
|
430
562
|
continue; // New reader - reader-attached already emitted
|
|
431
563
|
}
|
|
432
|
-
CardEvent event =
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
564
|
+
CardEvent event = replaceHeldCards
|
|
565
|
+
? DetectCardStateChangeAcrossOutage(oldIt->second, pair.second.lastState,
|
|
566
|
+
SCARD_STATE_PRESENT)
|
|
567
|
+
: DetectCardStateChange(oldIt->second, pair.second.lastState,
|
|
568
|
+
SCARD_STATE_PRESENT,
|
|
569
|
+
SMARTCARD_PCSC_COUNTS_CARD_EVENTS);
|
|
570
|
+
EmitCardEvent(event, pair.first, pair.second.lastState, pair.second.atr);
|
|
438
571
|
}
|
|
439
572
|
}
|
|
440
573
|
|
|
441
|
-
|
|
574
|
+
// Returns whether readerStates_ now comes from a fresh reading (false: it
|
|
575
|
+
// kept what it had, because a call failed)
|
|
576
|
+
bool ReaderMonitor::UpdateReaderList() {
|
|
442
577
|
// Get reader list size
|
|
443
578
|
DWORD readersLen = 0;
|
|
444
579
|
LONG result = SCardListReaders(context_, nullptr, nullptr, &readersLen);
|
|
445
580
|
|
|
446
|
-
if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)
|
|
581
|
+
if (result == static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
|
|
447
582
|
readerStates_.clear();
|
|
448
|
-
return;
|
|
583
|
+
return true;
|
|
449
584
|
}
|
|
450
585
|
|
|
586
|
+
// Any other failure (the service went away, say) says nothing about
|
|
587
|
+
// the readers: keep the map rather than report every reader detached.
|
|
588
|
+
// readersLen is left untouched on failure, so check this first.
|
|
451
589
|
if (result != SCARD_S_SUCCESS) {
|
|
452
|
-
return;
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (readersLen == 0) {
|
|
594
|
+
readerStates_.clear();
|
|
595
|
+
return true;
|
|
453
596
|
}
|
|
454
597
|
|
|
455
598
|
// Get reader names
|
|
@@ -457,7 +600,7 @@ void ReaderMonitor::UpdateReaderList() {
|
|
|
457
600
|
result = SCardListReaders(context_, nullptr, buffer.data(), &readersLen);
|
|
458
601
|
|
|
459
602
|
if (result != SCARD_S_SUCCESS) {
|
|
460
|
-
return;
|
|
603
|
+
return false;
|
|
461
604
|
}
|
|
462
605
|
|
|
463
606
|
// Parse multi-string
|
|
@@ -476,6 +619,12 @@ void ReaderMonitor::UpdateReaderList() {
|
|
|
476
619
|
}
|
|
477
620
|
|
|
478
621
|
LONG statusResult = SCardGetStatusChange(context_, 0, states.data(), states.size());
|
|
622
|
+
if (statusResult == static_cast<LONG>(SCARD_E_UNKNOWN_READER)) {
|
|
623
|
+
// A listed reader vanished before this read (pcsc-lite rejects the
|
|
624
|
+
// whole call). Keep the current map rather than announce readers
|
|
625
|
+
// with no state; the next resync lists again.
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
479
628
|
bool seeded = (statusResult == SCARD_S_SUCCESS);
|
|
480
629
|
|
|
481
630
|
// Update reader states map (Issue #111 fix: use map keyed by name)
|
|
@@ -484,7 +633,9 @@ void ReaderMonitor::UpdateReaderList() {
|
|
|
484
633
|
ReaderInfo info;
|
|
485
634
|
info.lastState = SCARD_STATE_UNAWARE;
|
|
486
635
|
if (seeded) {
|
|
487
|
-
|
|
636
|
+
// Never store SCARD_STATE_IGNORE: fed back as dwCurrentState it
|
|
637
|
+
// excludes the reader from future waits (as ApplyCardStateChange)
|
|
638
|
+
info.lastState = states[i].dwEventState & ~(SCARD_STATE_CHANGED | SCARD_STATE_IGNORE);
|
|
488
639
|
DWORD atrLen = states[i].cbAtr;
|
|
489
640
|
if (atrLen > sizeof(states[i].rgbAtr)) {
|
|
490
641
|
atrLen = sizeof(states[i].rgbAtr);
|
|
@@ -504,35 +655,61 @@ void ReaderMonitor::UpdateReaderList() {
|
|
|
504
655
|
newStates[newNames[i]] = info;
|
|
505
656
|
}
|
|
506
657
|
readerStates_ = std::move(newStates);
|
|
658
|
+
return seeded;
|
|
507
659
|
}
|
|
508
660
|
|
|
509
661
|
void ReaderMonitor::EmitEvent(const std::string& eventType, const std::string& readerName,
|
|
510
662
|
DWORD state, const std::vector<uint8_t>& atr, DWORD code) {
|
|
511
|
-
//
|
|
512
|
-
//
|
|
513
|
-
auto data =
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
663
|
+
// Owned by the tsfn's queue from here: DeliverEvent frees it.
|
|
664
|
+
// If the tsfn won't take it (closing), it was never queued.
|
|
665
|
+
auto* data = new EventData{eventType, readerName, state, atr, code};
|
|
666
|
+
if (tsfn_.BlockingCall(data) != napi_ok) {
|
|
667
|
+
delete data;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
void ReaderMonitor::DeliverEvent(Napi::Env env, Napi::Function callback,
|
|
672
|
+
std::nullptr_t* /*context*/, EventData* data) {
|
|
673
|
+
std::unique_ptr<EventData> owned(data);
|
|
674
|
+
|
|
675
|
+
// Node is draining the queue because the environment is being torn
|
|
676
|
+
// down (a worker exiting) before the event was dispatched
|
|
677
|
+
if (static_cast<napi_env>(env) == nullptr || callback.IsEmpty()) {
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
napi_value event;
|
|
682
|
+
napi_value recv;
|
|
683
|
+
try {
|
|
684
|
+
Napi::Object object = Napi::Object::New(env);
|
|
685
|
+
object.Set("type", Napi::String::New(env, owned->eventType));
|
|
686
|
+
object.Set("reader", Napi::String::New(env, owned->readerName));
|
|
687
|
+
object.Set("state", Napi::Number::New(env, owned->state));
|
|
688
|
+
if (!owned->atr.empty()) {
|
|
689
|
+
object.Set("atr", Napi::Buffer<uint8_t>::Copy(env, owned->atr.data(),
|
|
690
|
+
owned->atr.size()));
|
|
526
691
|
} else {
|
|
527
|
-
|
|
692
|
+
object.Set("atr", env.Null());
|
|
528
693
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
event.Set("code", Napi::Number::New(env, ptr->code));
|
|
694
|
+
if (owned->code != 0) {
|
|
695
|
+
object.Set("code", Napi::Number::New(env, owned->code));
|
|
532
696
|
}
|
|
697
|
+
event = object;
|
|
698
|
+
} catch (const Napi::Error& e) {
|
|
699
|
+
// A live environment gets the exception, as before; one that is
|
|
700
|
+
// shutting down can't take it, and the event is dropped
|
|
701
|
+
napi_throw(env, e.Value());
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (napi_get_undefined(env, &recv) != napi_ok) {
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
533
707
|
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
708
|
+
// Through the C API, not callback.Call(): if the callback throws, its
|
|
709
|
+
// exception stays pending and Node reports it as uncaught (as before);
|
|
710
|
+
// if the call is refused because the environment is shutting down,
|
|
711
|
+
// the event is dropped. callback.Call() turned that refusal into a C++
|
|
712
|
+
// exception which node-addon-api, unable to throw it into JS, rethrew
|
|
713
|
+
// into Node - std::terminate, killing the whole process.
|
|
714
|
+
napi_call_function(env, recv, callback, 1, &event, nullptr);
|
|
538
715
|
}
|