smartcard 3.7.2 → 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.
@@ -0,0 +1,23 @@
1
+ #pragma once
2
+
3
+ #include <napi.h>
4
+
5
+ // Per-environment addon state: the main thread and each worker_thread that
6
+ // loads the addon get their own, set up in Init (addon.cpp) and freed with
7
+ // that environment.
8
+ //
9
+ // No JS reference may be held in a static. A static is shared by all the
10
+ // environments that load the addon, so each load overwrote the last one's
11
+ // reference (deleting it from the wrong thread), and after a worker exited
12
+ // the others used a reference into that dead environment. Long-lived
13
+ // references that belong to the environment go here; references owned by
14
+ // one object (an async worker's, a monitor's tsfn) stay with that object.
15
+ struct AddonData {
16
+ // (message, code) => Error, registered by lib/index.ts via
17
+ // setErrorFactory() so native failures arrive as the typed PCSCError
18
+ // classes from lib/errors.ts
19
+ Napi::FunctionReference errorFactory;
20
+ // Classes the addon instantiates itself (listReaders, connect)
21
+ Napi::FunctionReference readerConstructor;
22
+ Napi::FunctionReference cardConstructor;
23
+ };
@@ -1,6 +1,8 @@
1
1
  #include "async_workers.h"
2
2
  #include "pcsc_card.h"
3
3
  #include "pcsc_errors.h"
4
+ #include "pcsc_napi_error.h"
5
+ #include <chrono>
4
6
  #include <cstring>
5
7
 
6
8
  // ============================================================================
@@ -9,17 +11,21 @@
9
11
 
10
12
  WaitForChangeWorker::WaitForChangeWorker(
11
13
  Napi::Env env,
12
- SCARDCONTEXT context,
14
+ PendingWaitsPtr pendingWaits,
13
15
  std::vector<std::string> readerNames,
14
16
  std::vector<DWORD> currentStates,
15
- DWORD timeout,
16
- Napi::Promise::Deferred deferred)
17
- : Napi::AsyncWorker(env),
18
- context_(context),
17
+ DWORD timeout)
18
+ : deferred_(Napi::Promise::Deferred::New(env)),
19
+ pendingWaits_(std::move(pendingWaits)),
19
20
  readerNames_(std::move(readerNames)),
20
21
  timeout_(timeout),
21
22
  result_(SCARD_S_SUCCESS),
22
- deferred_(deferred) {
23
+ context_(0),
24
+ contextValid_(false),
25
+ waited_(false),
26
+ cancelled_(false),
27
+ cleanupHookAdded_(false),
28
+ envTornDown_(false) {
23
29
 
24
30
  // Initialize reader states
25
31
  states_.resize(readerNames_.size());
@@ -30,14 +36,160 @@ WaitForChangeWorker::WaitForChangeWorker(
30
36
  }
31
37
  }
32
38
 
39
+ Napi::Promise WaitForChangeWorker::Start(
40
+ Napi::Env env,
41
+ PendingWaitsPtr pendingWaits,
42
+ std::vector<std::string> readerNames,
43
+ std::vector<DWORD> currentStates,
44
+ DWORD timeout) {
45
+
46
+ auto* self = new WaitForChangeWorker(
47
+ env, std::move(pendingWaits), std::move(readerNames),
48
+ std::move(currentStates), timeout);
49
+ Napi::Promise promise = self->deferred_.Promise();
50
+
51
+ try {
52
+ // Referenced until released, so a pending wait keeps the event
53
+ // loop alive, as threadpool work did
54
+ self->tsfn_ = DoneTsfn::New(env, "waitForChange", 0, 1, self, OnDone);
55
+ } catch (...) {
56
+ delete self;
57
+ throw;
58
+ }
59
+ // From here OnDone frees self
60
+
61
+ // Added after the tsfn, so that at environment teardown it runs before
62
+ // the tsfn's own hook: Node runs them newest first. Without it nothing
63
+ // could end the wait at teardown, so no wait is started.
64
+ self->cleanupHookAdded_ =
65
+ napi_add_env_cleanup_hook(env, OnEnvCleanup, self) == napi_ok;
66
+
67
+ bool started = false;
68
+ if (self->cleanupHookAdded_) {
69
+ try {
70
+ // Within cancel()'s reach before it begins
71
+ self->pendingWaits_->insert(self);
72
+ self->thread_ = std::thread(&WaitForChangeWorker::Execute, self);
73
+ started = true;
74
+ } catch (...) {
75
+ // No thread to be had (std::system_error, std::bad_alloc)
76
+ self->pendingWaits_->erase(self);
77
+ }
78
+ }
79
+ if (!started) {
80
+ // Fail the wait: OnDone rejects it
81
+ self->result_ = SCARD_E_NO_MEMORY;
82
+ self->tsfn_.Release();
83
+ }
84
+
85
+ return promise;
86
+ }
87
+
33
88
  void WaitForChangeWorker::Execute() {
34
- // This runs on worker thread - safe to block
35
- result_ = SCardGetStatusChange(context_, timeout_, states_.data(), states_.size());
89
+ SCARDCONTEXT context = 0;
90
+ LONG established = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
91
+ bool cancelled;
92
+ {
93
+ std::lock_guard<std::mutex> lock(mutex_);
94
+ if (established == SCARD_S_SUCCESS) {
95
+ context_ = context;
96
+ contextValid_ = true;
97
+ }
98
+ cancelled = cancelled_;
99
+ }
100
+
101
+ if (established != SCARD_S_SUCCESS) {
102
+ result_ = established;
103
+ } else if (cancelled) {
104
+ result_ = SCARD_E_CANCELLED;
105
+ } else {
106
+ // One call, however long: separate calls would leave gaps between
107
+ // them, in which pcsc-lite misses a reader being added (the PnP
108
+ // entry counts only during a call) and fails the next call
109
+ // outright for a reader removed (spec/README.md, findings 2 and 3)
110
+ result_ = SCardGetStatusChange(context, timeout_, states_.data(), states_.size());
111
+ }
112
+
113
+ {
114
+ std::lock_guard<std::mutex> lock(mutex_);
115
+ if (contextValid_) {
116
+ SCardReleaseContext(context_);
117
+ contextValid_ = false;
118
+ }
119
+ waited_ = true;
120
+ }
121
+ waitedCv_.notify_all();
122
+ tsfn_.Release();
36
123
  }
37
124
 
38
- void WaitForChangeWorker::OnOK() {
39
- Napi::Env env = Env();
125
+ void WaitForChangeWorker::CancelUntilReturned(int maxAttempts) {
126
+ std::unique_lock<std::mutex> lock(mutex_);
127
+ cancelled_ = true;
128
+ // SCardCancel ends only a wait in progress. One whose thread hasn't
129
+ // reached SCardGetStatusChange yet sees cancelled_ instead; one that
130
+ // has, but isn't waiting yet, needs another try.
131
+ for (int attempt = 0; !waited_ && (maxAttempts == 0 || attempt < maxAttempts); attempt++) {
132
+ if (contextValid_) {
133
+ SCardCancel(context_);
134
+ }
135
+ waitedCv_.wait_for(lock, std::chrono::milliseconds(5), [this] { return waited_; });
136
+ }
137
+ }
138
+
139
+ void WaitForChangeWorker::Cancel() {
140
+ CancelUntilReturned(200);
141
+ }
142
+
143
+ // The environment is being torn down (a worker exiting, or terminated)
144
+ // with the wait still pending: end it, so the tsfn's own cleanup hook,
145
+ // which runs next, finds the thread done with it (as in ReaderMonitor).
146
+ // The promise is left unsettled; nothing can observe it any more.
147
+ void WaitForChangeWorker::OnEnvCleanup(void* arg) {
148
+ auto* self = static_cast<WaitForChangeWorker*>(arg);
149
+ // Node drops the hook itself once it has run
150
+ self->cleanupHookAdded_ = false;
151
+ self->envTornDown_ = true;
152
+ if (self->thread_.joinable()) {
153
+ self->CancelUntilReturned(0);
154
+ self->thread_.join();
155
+ }
156
+ }
157
+
158
+ void WaitForChangeWorker::OnDone(Napi::Env env, void*, WaitForChangeWorker* self) {
159
+ if (self->thread_.joinable()) {
160
+ // Execute() has released the tsfn, so it is returning
161
+ self->thread_.join();
162
+ }
163
+ if (self->cleanupHookAdded_) {
164
+ napi_remove_env_cleanup_hook(env, OnEnvCleanup, self);
165
+ self->cleanupHookAdded_ = false;
166
+ }
167
+ self->pendingWaits_->erase(self);
168
+ if (!self->envTornDown_) {
169
+ // If building the result fails, fail the wait with that error.
170
+ // Node can also finalize the tsfn early in a teardown, before the
171
+ // cleanup hooks run, when JS can't run: then rejecting fails too,
172
+ // nothing can observe the promise any more, and the failure must
173
+ // not escape into Node.
174
+ try {
175
+ self->Settle(env);
176
+ } catch (const Napi::Error& e) {
177
+ try {
178
+ self->deferred_.Reject(e.Value());
179
+ } catch (...) {
180
+ }
181
+ } catch (...) {
182
+ try {
183
+ self->deferred_.Reject(Napi::Error::New(
184
+ env, "waitForChange() could not deliver its result").Value());
185
+ } catch (...) {
186
+ }
187
+ }
188
+ }
189
+ delete self;
190
+ }
40
191
 
192
+ void WaitForChangeWorker::Settle(Napi::Env env) {
41
193
  if (result_ == SCARD_S_SUCCESS) {
42
194
  // Build array of reader states
43
195
  Napi::Array changes = Napi::Array::New(env);
@@ -60,33 +212,31 @@ void WaitForChangeWorker::OnOK() {
60
212
  }
61
213
 
62
214
  deferred_.Resolve(changes);
63
- } else if (result_ == SCARD_E_CANCELLED) {
215
+ } else if (result_ == static_cast<LONG>(SCARD_E_CANCELLED)) {
64
216
  // Cancelled - resolve with null
65
217
  deferred_.Resolve(env.Null());
66
- } else if (result_ == SCARD_E_TIMEOUT) {
218
+ } else if (result_ == static_cast<LONG>(SCARD_E_TIMEOUT)) {
67
219
  // Timeout - resolve with empty array
68
220
  deferred_.Resolve(Napi::Array::New(env, 0));
69
221
  } else {
70
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
222
+ deferred_.Reject(NewPCSCError(env, result_).Value());
71
223
  }
72
224
  }
73
225
 
74
- void WaitForChangeWorker::OnError(const Napi::Error& error) {
75
- deferred_.Reject(error.Value());
76
- }
77
-
78
226
  // ============================================================================
79
227
  // TransmitWorker
80
228
  // ============================================================================
81
229
 
82
230
  TransmitWorker::TransmitWorker(
83
231
  Napi::Env env,
232
+ Napi::Object owner,
84
233
  SCARDHANDLE card,
85
234
  DWORD protocol,
86
235
  std::vector<uint8_t> sendBuffer,
87
236
  size_t maxRecvLength,
88
237
  Napi::Promise::Deferred deferred)
89
238
  : Napi::AsyncWorker(env),
239
+ ownerRef_(Napi::Persistent(owner)),
90
240
  card_(card),
91
241
  protocol_(protocol),
92
242
  sendBuffer_(std::move(sendBuffer)),
@@ -137,7 +287,7 @@ void TransmitWorker::OnOK() {
137
287
  env, recvBuffer_.data(), recvLength_);
138
288
  deferred_.Resolve(buffer);
139
289
  } else {
140
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
290
+ deferred_.Reject(NewPCSCError(env, result_).Value());
141
291
  }
142
292
  }
143
293
 
@@ -151,11 +301,13 @@ void TransmitWorker::OnError(const Napi::Error& error) {
151
301
 
152
302
  ControlWorker::ControlWorker(
153
303
  Napi::Env env,
304
+ Napi::Object owner,
154
305
  SCARDHANDLE card,
155
306
  DWORD controlCode,
156
307
  std::vector<uint8_t> sendBuffer,
157
308
  Napi::Promise::Deferred deferred)
158
309
  : Napi::AsyncWorker(env),
310
+ ownerRef_(Napi::Persistent(owner)),
159
311
  card_(card),
160
312
  controlCode_(controlCode),
161
313
  sendBuffer_(std::move(sendBuffer)),
@@ -186,7 +338,7 @@ void ControlWorker::OnOK() {
186
338
  env, recvBuffer_.data(), bytesReturned_);
187
339
  deferred_.Resolve(buffer);
188
340
  } else {
189
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
341
+ deferred_.Reject(NewPCSCError(env, result_).Value());
190
342
  }
191
343
  }
192
344
 
@@ -200,13 +352,16 @@ void ControlWorker::OnError(const Napi::Error& error) {
200
352
 
201
353
  ConnectWorker::ConnectWorker(
202
354
  Napi::Env env,
203
- SCARDCONTEXT context,
355
+ Napi::Object owner,
356
+ ContextHandlePtr context,
204
357
  std::string readerName,
205
358
  DWORD shareMode,
206
359
  DWORD preferredProtocols,
207
360
  Napi::Promise::Deferred deferred)
208
361
  : Napi::AsyncWorker(env),
209
- context_(context),
362
+ ownerRef_(Napi::Persistent(owner)),
363
+ contextHandle_(std::move(context)),
364
+ context_(contextHandle_->Get()),
210
365
  readerName_(std::move(readerName)),
211
366
  shareMode_(shareMode),
212
367
  preferredProtocols_(preferredProtocols),
@@ -231,10 +386,11 @@ void ConnectWorker::OnOK() {
231
386
  Napi::Env env = Env();
232
387
 
233
388
  if (result_ == SCARD_S_SUCCESS) {
234
- Napi::Object card = PCSCCard::NewInstance(env, card_, activeProtocol_, readerName_);
389
+ Napi::Object card = PCSCCard::NewInstance(
390
+ env, contextHandle_, card_, activeProtocol_, readerName_);
235
391
  deferred_.Resolve(card);
236
392
  } else {
237
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
393
+ deferred_.Reject(NewPCSCError(env, result_).Value());
238
394
  }
239
395
  }
240
396
 
@@ -248,6 +404,7 @@ void ConnectWorker::OnError(const Napi::Error& error) {
248
404
 
249
405
  ReconnectWorker::ReconnectWorker(
250
406
  Napi::Env env,
407
+ Napi::Object owner,
251
408
  SCARDHANDLE card,
252
409
  DWORD shareMode,
253
410
  DWORD preferredProtocols,
@@ -255,6 +412,7 @@ ReconnectWorker::ReconnectWorker(
255
412
  DWORD* protocolOut,
256
413
  Napi::Promise::Deferred deferred)
257
414
  : Napi::AsyncWorker(env),
415
+ ownerRef_(Napi::Persistent(owner)),
258
416
  card_(card),
259
417
  shareMode_(shareMode),
260
418
  preferredProtocols_(preferredProtocols),
@@ -285,7 +443,7 @@ void ReconnectWorker::OnOK() {
285
443
  }
286
444
  deferred_.Resolve(Napi::Number::New(env, activeProtocol_));
287
445
  } else {
288
- deferred_.Reject(Napi::Error::New(env, GetPCSCErrorString(result_)).Value());
446
+ deferred_.Reject(NewPCSCError(env, result_).Value());
289
447
  }
290
448
  }
291
449
 
@@ -3,35 +3,113 @@
3
3
  #include <napi.h>
4
4
  #include <vector>
5
5
  #include <string>
6
+ #include <thread>
7
+ #include <mutex>
8
+ #include <condition_variable>
9
+ #include <memory>
10
+ #include <unordered_set>
6
11
  #include "platform/pcsc.h"
7
-
8
- // Async worker for SCardGetStatusChange
9
- class WaitForChangeWorker : public Napi::AsyncWorker {
12
+ #include "pcsc_context_handle.h"
13
+
14
+ // Every AsyncWorker below holds a Napi::ObjectReference to the JS object
15
+ // that owns its PC/SC handle (Card or Reader). Without it, GC can finalize
16
+ // the owner while Execute() is blocked in a PC/SC call: the finalizer
17
+ // disconnects or releases the handle out from under the worker, and PC/SC
18
+ // reuses handle values, so a late call can even land on a different card.
19
+ // The reference is released on the main thread once the result is
20
+ // delivered (OnOK/OnError). WaitForChangeWorker needs none: its context is
21
+ // its own.
22
+
23
+ // waitForChange(): SCardGetStatusChange on a thread of its own, not as a
24
+ // Napi::AsyncWorker on libuv's threadpool, because the wait can last
25
+ // forever (with no timeout, the default):
26
+ // - The threadpool is shared by the whole process, 4 threads by default.
27
+ // Four pending waits stopped every fs, dns, crypto and zlib call, and
28
+ // this addon's transmit() and connect(), until one of them returned.
29
+ // - Node tears an environment down (a worker exiting, or terminated) only
30
+ // once its threadpool work has finished, and runs cleanup hooks only
31
+ // after that, so nothing could cancel the wait: the worker never ended,
32
+ // and nor did the process, whose exit waits for its workers.
33
+ // Off the threadpool the wait doesn't hold up teardown, and OnEnvCleanup
34
+ // cancels it.
35
+ //
36
+ // Each wait also has a PC/SC context of its own, established and released
37
+ // on its thread. pcsc-lite holds a context's lock for as long as a wait on
38
+ // it lasts, and a call that needs the lock waits for it while holding the
39
+ // library's global lock: on the waiting Context, listReaders() and close()
40
+ // blocked the main thread until the wait ended (with no timeout, forever),
41
+ // and a second wait, or a connect(), blocked every PC/SC call in the
42
+ // process, cancel() included.
43
+ class WaitForChangeWorker {
10
44
  public:
45
+ // The waits pending on one Context, for cancel() and close(). Main
46
+ // thread only; shared by the Context and its waits.
47
+ using PendingWaits = std::unordered_set<WaitForChangeWorker*>;
48
+ using PendingWaitsPtr = std::shared_ptr<PendingWaits>;
49
+
50
+ // Start the wait; returns the promise it settles
51
+ static Napi::Promise Start(Napi::Env env,
52
+ PendingWaitsPtr pendingWaits,
53
+ std::vector<std::string> readerNames,
54
+ std::vector<DWORD> currentStates,
55
+ DWORD timeout);
56
+
57
+ // End the wait, whether or not it has begun: one that hasn't returned
58
+ // yet resolves with null. Returns once it has returned, normally at
59
+ // once; gives up after about a second if SCardCancel can't end it.
60
+ // Main thread.
61
+ void Cancel();
62
+
63
+ private:
11
64
  WaitForChangeWorker(Napi::Env env,
12
- SCARDCONTEXT context,
65
+ PendingWaitsPtr pendingWaits,
13
66
  std::vector<std::string> readerNames,
14
67
  std::vector<DWORD> currentStates,
15
- DWORD timeout,
16
- Napi::Promise::Deferred deferred);
17
-
18
- void Execute() override;
19
- void OnOK() override;
20
- void OnError(const Napi::Error& error) override;
68
+ DWORD timeout);
69
+
70
+ // On thread_: the wait, then releasing tsfn_
71
+ void Execute();
72
+ // Set cancelled_, then cancel the wait until it has returned, trying
73
+ // at most maxAttempts times, 5 ms apart (0: no limit)
74
+ void CancelUntilReturned(int maxAttempts);
75
+ // The tsfn's finalizer, on the main thread: Node calls it once
76
+ // Execute() has released the tsfn, or at environment teardown
77
+ static void OnDone(Napi::Env env, void*, WaitForChangeWorker* self);
78
+ static void OnEnvCleanup(void* arg);
79
+ void Settle(Napi::Env env);
80
+
81
+ // Only ever released, never called: OnDone delivers the result
82
+ using DoneTsfn = Napi::TypedThreadSafeFunction<WaitForChangeWorker>;
21
83
 
22
- private:
23
- SCARDCONTEXT context_;
84
+ Napi::Promise::Deferred deferred_;
85
+ PendingWaitsPtr pendingWaits_;
24
86
  std::vector<std::string> readerNames_;
25
87
  std::vector<SCARD_READERSTATE> states_;
26
88
  DWORD timeout_;
27
89
  LONG result_;
28
- Napi::Promise::Deferred deferred_;
90
+ DoneTsfn tsfn_;
91
+ std::thread thread_;
92
+ // Guards the rest
93
+ std::mutex mutex_;
94
+ // This wait's own context, while thread_ holds it
95
+ SCARDCONTEXT context_;
96
+ bool contextValid_;
97
+ // Execute() is done with the context: the wait has returned
98
+ std::condition_variable waitedCv_;
99
+ bool waited_;
100
+ // Cancel() or OnEnvCleanup: end the wait, or don't begin it
101
+ bool cancelled_;
102
+ // OnEnvCleanup is registered with Node from Start() until OnDone
103
+ bool cleanupHookAdded_;
104
+ // OnEnvCleanup ran: the environment can't run JS any more
105
+ bool envTornDown_;
29
106
  };
30
107
 
31
108
  // Async worker for SCardTransmit
32
109
  class TransmitWorker : public Napi::AsyncWorker {
33
110
  public:
34
111
  TransmitWorker(Napi::Env env,
112
+ Napi::Object owner,
35
113
  SCARDHANDLE card,
36
114
  DWORD protocol,
37
115
  std::vector<uint8_t> sendBuffer,
@@ -43,6 +121,7 @@ public:
43
121
  void OnError(const Napi::Error& error) override;
44
122
 
45
123
  private:
124
+ Napi::ObjectReference ownerRef_;
46
125
  SCARDHANDLE card_;
47
126
  DWORD protocol_;
48
127
  std::vector<uint8_t> sendBuffer_;
@@ -56,6 +135,7 @@ private:
56
135
  class ControlWorker : public Napi::AsyncWorker {
57
136
  public:
58
137
  ControlWorker(Napi::Env env,
138
+ Napi::Object owner,
59
139
  SCARDHANDLE card,
60
140
  DWORD controlCode,
61
141
  std::vector<uint8_t> sendBuffer,
@@ -66,6 +146,7 @@ public:
66
146
  void OnError(const Napi::Error& error) override;
67
147
 
68
148
  private:
149
+ Napi::ObjectReference ownerRef_;
69
150
  SCARDHANDLE card_;
70
151
  DWORD controlCode_;
71
152
  std::vector<uint8_t> sendBuffer_;
@@ -79,7 +160,8 @@ private:
79
160
  class ConnectWorker : public Napi::AsyncWorker {
80
161
  public:
81
162
  ConnectWorker(Napi::Env env,
82
- SCARDCONTEXT context,
163
+ Napi::Object owner,
164
+ ContextHandlePtr context,
83
165
  std::string readerName,
84
166
  DWORD shareMode,
85
167
  DWORD preferredProtocols,
@@ -90,6 +172,10 @@ public:
90
172
  void OnError(const Napi::Error& error) override;
91
173
 
92
174
  private:
175
+ Napi::ObjectReference ownerRef_;
176
+ // Handed to the new Card, which needs the context alive as long as it is
177
+ ContextHandlePtr contextHandle_;
178
+ // Copied on the main thread; Execute() never touches contextHandle_
93
179
  SCARDCONTEXT context_;
94
180
  std::string readerName_;
95
181
  DWORD shareMode_;
@@ -104,6 +190,7 @@ private:
104
190
  class ReconnectWorker : public Napi::AsyncWorker {
105
191
  public:
106
192
  ReconnectWorker(Napi::Env env,
193
+ Napi::Object owner,
107
194
  SCARDHANDLE card,
108
195
  DWORD shareMode,
109
196
  DWORD preferredProtocols,
@@ -118,11 +205,14 @@ public:
118
205
  DWORD GetActiveProtocol() const { return activeProtocol_; }
119
206
 
120
207
  private:
208
+ Napi::ObjectReference ownerRef_;
121
209
  SCARDHANDLE card_;
122
210
  DWORD shareMode_;
123
211
  DWORD preferredProtocols_;
124
212
  DWORD initialization_;
125
213
  DWORD activeProtocol_;
214
+ // Points into the owning PCSCCard; ownerRef_ keeps that object alive
215
+ // for the duration, so the pointer cannot dangle
126
216
  DWORD* protocolOut_;
127
217
  LONG result_;
128
218
  Napi::Promise::Deferred deferred_;