smartcard 3.8.0 → 3.10.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.
@@ -2,6 +2,7 @@
2
2
  #include "pcsc_card.h"
3
3
  #include "pcsc_errors.h"
4
4
  #include "pcsc_napi_error.h"
5
+ #include <chrono>
5
6
  #include <cstring>
6
7
 
7
8
  // ============================================================================
@@ -10,19 +11,21 @@
10
11
 
11
12
  WaitForChangeWorker::WaitForChangeWorker(
12
13
  Napi::Env env,
13
- Napi::Object owner,
14
- SCARDCONTEXT context,
14
+ PendingWaitsPtr pendingWaits,
15
15
  std::vector<std::string> readerNames,
16
16
  std::vector<DWORD> currentStates,
17
- DWORD timeout,
18
- Napi::Promise::Deferred deferred)
19
- : Napi::AsyncWorker(env),
20
- ownerRef_(Napi::Persistent(owner)),
21
- context_(context),
17
+ DWORD timeout)
18
+ : deferred_(Napi::Promise::Deferred::New(env)),
19
+ pendingWaits_(std::move(pendingWaits)),
22
20
  readerNames_(std::move(readerNames)),
23
21
  timeout_(timeout),
24
22
  result_(SCARD_S_SUCCESS),
25
- deferred_(deferred) {
23
+ context_(0),
24
+ contextValid_(false),
25
+ waited_(false),
26
+ cancelled_(false),
27
+ cleanupHookAdded_(false),
28
+ envTornDown_(false) {
26
29
 
27
30
  // Initialize reader states
28
31
  states_.resize(readerNames_.size());
@@ -33,14 +36,207 @@ WaitForChangeWorker::WaitForChangeWorker(
33
36
  }
34
37
  }
35
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
+ // At environment teardown this ends the wait and joins its thread.
62
+ // Node deletes the tsfn only once every cleanup hook has run, so the
63
+ // thread is gone by then. Without it nothing could end the wait at
64
+ // teardown, so no wait is started.
65
+ self->cleanupHookAdded_ =
66
+ napi_add_env_cleanup_hook(env, OnEnvCleanup, self) == napi_ok;
67
+
68
+ bool started = false;
69
+ if (self->cleanupHookAdded_) {
70
+ try {
71
+ // Within cancel()'s reach before it begins
72
+ self->pendingWaits_->insert(self);
73
+ self->thread_ = std::thread(&WaitForChangeWorker::Execute, self);
74
+ started = true;
75
+ } catch (...) {
76
+ // No thread to be had (std::system_error, std::bad_alloc)
77
+ self->pendingWaits_->erase(self);
78
+ }
79
+ }
80
+ if (!started) {
81
+ // Fail the wait: OnDone rejects it
82
+ self->result_ = SCARD_E_NO_MEMORY;
83
+ self->tsfn_.Release();
84
+ }
85
+
86
+ return promise;
87
+ }
88
+
36
89
  void WaitForChangeWorker::Execute() {
37
- // This runs on worker thread - safe to block
38
- result_ = SCardGetStatusChange(context_, timeout_, states_.data(), states_.size());
90
+ SCARDCONTEXT context = 0;
91
+ LONG established = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, &context);
92
+ bool cancelled;
93
+ {
94
+ std::lock_guard<std::mutex> lock(mutex_);
95
+ if (established == SCARD_S_SUCCESS) {
96
+ context_ = context;
97
+ contextValid_ = true;
98
+ }
99
+ cancelled = cancelled_;
100
+ }
101
+
102
+ if (established != SCARD_S_SUCCESS) {
103
+ result_ = established;
104
+ } else if (cancelled) {
105
+ result_ = SCARD_E_CANCELLED;
106
+ } else {
107
+ // One call, however long: separate calls would leave gaps between
108
+ // them, in which pcsc-lite misses a reader being added (the PnP
109
+ // entry counts only during a call) and fails the next call
110
+ // outright for a reader removed (spec/README.md, findings 2 and 3)
111
+ result_ = SCardGetStatusChange(context, timeout_, states_.data(), states_.size());
112
+ }
113
+
114
+ {
115
+ std::lock_guard<std::mutex> lock(mutex_);
116
+ if (contextValid_) {
117
+ SCardReleaseContext(context_);
118
+ contextValid_ = false;
119
+ }
120
+ // Cancelled before it returned, even if SCardCancel never reached
121
+ // it: it resolves with null, whatever ended it
122
+ if (cancelled_) {
123
+ result_ = SCARD_E_CANCELLED;
124
+ }
125
+ waited_ = true;
126
+ }
127
+ waitedCv_.notify_all();
128
+ tsfn_.Release();
39
129
  }
40
130
 
41
- void WaitForChangeWorker::OnOK() {
42
- Napi::Env env = Env();
131
+ // Cancelling: SCardCancel ends only a wait in progress. One whose thread
132
+ // hasn't reached SCardGetStatusChange yet sees cancelled_ instead; one that
133
+ // has, but isn't waiting yet, needs another try (SCardCancel succeeds then,
134
+ // doing nothing), so cancel() tries every kCancelRetry for up to
135
+ // kCancelFor. If SCardCancel itself fails for kCancelFailingFor without a
136
+ // break, it gives up: on pcsc-lite it needs a connection of its own to
137
+ // pcscd, which pcscd refuses once it serves its maximum number of contexts
138
+ // (200 by default), and trying for longer only blocks the caller. The
139
+ // teardown hook can't give up, so it backs off to kTeardownRetryMax.
140
+ static const std::chrono::milliseconds kCancelRetry(5);
141
+ static const std::chrono::milliseconds kCancelFor(1000);
142
+ static const std::chrono::milliseconds kCancelFailingFor(100);
143
+ static const std::chrono::milliseconds kTeardownRetryMax(1000);
144
+
145
+ void WaitForChangeWorker::MarkCancelled() {
146
+ std::lock_guard<std::mutex> lock(mutex_);
147
+ cancelled_ = true;
148
+ }
149
+
150
+ bool WaitForChangeWorker::CancelUntilReturned(bool teardown) {
151
+ using Clock = std::chrono::steady_clock;
152
+ std::unique_lock<std::mutex> lock(mutex_);
153
+ cancelled_ = true;
154
+ const Clock::time_point deadline = Clock::now() + kCancelFor;
155
+ std::chrono::milliseconds interval = kCancelRetry;
156
+ bool failing = false;
157
+ Clock::time_point failingSince;
158
+ while (!waited_) {
159
+ if (contextValid_) {
160
+ if (SCardCancel(context_) == SCARD_S_SUCCESS) {
161
+ failing = false;
162
+ interval = kCancelRetry;
163
+ } else {
164
+ if (!failing) {
165
+ failing = true;
166
+ failingSince = Clock::now();
167
+ }
168
+ if (teardown) {
169
+ // Not std::min: windows.h defines a min() macro
170
+ interval = interval * 2 < kTeardownRetryMax ? interval * 2 : kTeardownRetryMax;
171
+ } else if (Clock::now() - failingSince >= kCancelFailingFor) {
172
+ return false;
173
+ }
174
+ }
175
+ }
176
+ if (!teardown && Clock::now() >= deadline) {
177
+ break;
178
+ }
179
+ waitedCv_.wait_for(lock, interval, [this] { return waited_; });
180
+ }
181
+ return true;
182
+ }
183
+
184
+ bool WaitForChangeWorker::Cancel() {
185
+ return CancelUntilReturned(false);
186
+ }
187
+
188
+ // The environment is being torn down (a worker exiting, or terminated)
189
+ // with the wait still pending: end it, so the tsfn's own cleanup hook,
190
+ // which runs next, finds the thread done with it (as in ReaderMonitor).
191
+ // The promise is left unsettled; nothing can observe it any more.
192
+ void WaitForChangeWorker::OnEnvCleanup(void* arg) {
193
+ auto* self = static_cast<WaitForChangeWorker*>(arg);
194
+ // Node drops the hook itself once it has run
195
+ self->cleanupHookAdded_ = false;
196
+ self->envTornDown_ = true;
197
+ if (self->thread_.joinable()) {
198
+ // However long it takes: the thread must be done before Node
199
+ // frees the tsfn
200
+ self->CancelUntilReturned(true);
201
+ self->thread_.join();
202
+ }
203
+ }
204
+
205
+ void WaitForChangeWorker::OnDone(Napi::Env env, void*, WaitForChangeWorker* self) {
206
+ if (self->thread_.joinable()) {
207
+ // Execute() has released the tsfn, so it is returning
208
+ self->thread_.join();
209
+ }
210
+ if (self->cleanupHookAdded_) {
211
+ napi_remove_env_cleanup_hook(env, OnEnvCleanup, self);
212
+ self->cleanupHookAdded_ = false;
213
+ }
214
+ self->pendingWaits_->erase(self);
215
+ if (!self->envTornDown_) {
216
+ // If building the result fails, fail the wait with that error.
217
+ // Node can also finalize the tsfn early in a teardown, before the
218
+ // cleanup hooks run, when JS can't run: then rejecting fails too,
219
+ // nothing can observe the promise any more, and the failure must
220
+ // not escape into Node.
221
+ try {
222
+ self->Settle(env);
223
+ } catch (const Napi::Error& e) {
224
+ try {
225
+ self->deferred_.Reject(e.Value());
226
+ } catch (...) {
227
+ }
228
+ } catch (...) {
229
+ try {
230
+ self->deferred_.Reject(Napi::Error::New(
231
+ env, "waitForChange() could not deliver its result").Value());
232
+ } catch (...) {
233
+ }
234
+ }
235
+ }
236
+ delete self;
237
+ }
43
238
 
239
+ void WaitForChangeWorker::Settle(Napi::Env env) {
44
240
  if (result_ == SCARD_S_SUCCESS) {
45
241
  // Build array of reader states
46
242
  Napi::Array changes = Napi::Array::New(env);
@@ -74,10 +270,6 @@ void WaitForChangeWorker::OnOK() {
74
270
  }
75
271
  }
76
272
 
77
- void WaitForChangeWorker::OnError(const Napi::Error& error) {
78
- deferred_.Reject(error.Value());
79
- }
80
-
81
273
  // ============================================================================
82
274
  // TransmitWorker
83
275
  // ============================================================================
@@ -3,39 +3,112 @@
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
12
  #include "pcsc_context_handle.h"
8
13
 
9
- // Every worker holds a Napi::ObjectReference to the JS object that owns its
10
- // PC/SC handle (Card, Reader, or Context). Without it, GC can finalize the
11
- // owner while Execute() is blocked in a PC/SC call: the finalizer disconnects
12
- // or releases the handle out from under the worker, and PC/SC reuses handle
13
- // values, so a late call can even land on a different card. The reference is
14
- // released when the worker is destroyed on the main thread after OnOK/OnError.
15
-
16
- // Async worker for SCardGetStatusChange
17
- class WaitForChangeWorker : public Napi::AsyncWorker {
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
+ //
44
+ // spec/WaitLifecycle.tla models this class, cancel() and close(); change
45
+ // it in the same PR (spec/README.md, "waitForChange()").
46
+ class WaitForChangeWorker {
18
47
  public:
48
+ // The waits pending on one Context, for cancel() and close(). Main
49
+ // thread only; shared by the Context and its waits.
50
+ using PendingWaits = std::unordered_set<WaitForChangeWorker*>;
51
+ using PendingWaitsPtr = std::shared_ptr<PendingWaits>;
52
+
53
+ // Start the wait; returns the promise it settles
54
+ static Napi::Promise Start(Napi::Env env,
55
+ PendingWaitsPtr pendingWaits,
56
+ std::vector<std::string> readerNames,
57
+ std::vector<DWORD> currentStates,
58
+ DWORD timeout);
59
+
60
+ // The wait is cancelled: if it hasn't begun it won't, and when it
61
+ // returns it resolves with null. Cancel() ends it as well. Main thread.
62
+ void MarkCancelled();
63
+ // Mark the wait cancelled and end it: returns once it has returned,
64
+ // normally at once, or after about a second if SCardCancel can't end
65
+ // it. Returns false, sooner, if SCardCancel itself keeps failing (pcscd
66
+ // refusing new connections). Main thread.
67
+ bool Cancel();
68
+
69
+ private:
19
70
  WaitForChangeWorker(Napi::Env env,
20
- Napi::Object owner,
21
- SCARDCONTEXT context,
71
+ PendingWaitsPtr pendingWaits,
22
72
  std::vector<std::string> readerNames,
23
73
  std::vector<DWORD> currentStates,
24
- DWORD timeout,
25
- Napi::Promise::Deferred deferred);
26
-
27
- void Execute() override;
28
- void OnOK() override;
29
- void OnError(const Napi::Error& error) override;
74
+ DWORD timeout);
75
+
76
+ // On thread_: the wait, then releasing tsfn_
77
+ void Execute();
78
+ // Set cancelled_, then cancel the wait until it has returned (see
79
+ // kCancelFor in the .cpp). teardown: for as long as it takes
80
+ bool CancelUntilReturned(bool teardown);
81
+ // The tsfn's finalizer, on the main thread: Node calls it once
82
+ // Execute() has released the tsfn, or at environment teardown
83
+ static void OnDone(Napi::Env env, void*, WaitForChangeWorker* self);
84
+ static void OnEnvCleanup(void* arg);
85
+ void Settle(Napi::Env env);
86
+
87
+ // Only ever released, never called: OnDone delivers the result
88
+ using DoneTsfn = Napi::TypedThreadSafeFunction<WaitForChangeWorker>;
30
89
 
31
- private:
32
- Napi::ObjectReference ownerRef_;
33
- SCARDCONTEXT context_;
90
+ Napi::Promise::Deferred deferred_;
91
+ PendingWaitsPtr pendingWaits_;
34
92
  std::vector<std::string> readerNames_;
35
93
  std::vector<SCARD_READERSTATE> states_;
36
94
  DWORD timeout_;
37
95
  LONG result_;
38
- Napi::Promise::Deferred deferred_;
96
+ DoneTsfn tsfn_;
97
+ std::thread thread_;
98
+ // Guards the rest
99
+ std::mutex mutex_;
100
+ // This wait's own context, while thread_ holds it
101
+ SCARDCONTEXT context_;
102
+ bool contextValid_;
103
+ // Execute() is done with the context: the wait has returned
104
+ std::condition_variable waitedCv_;
105
+ bool waited_;
106
+ // Cancel() or OnEnvCleanup: end the wait, or don't begin it
107
+ bool cancelled_;
108
+ // OnEnvCleanup is registered with Node from Start() until OnDone
109
+ bool cleanupHookAdded_;
110
+ // OnEnvCleanup ran: the environment can't run JS any more
111
+ bool envTornDown_;
39
112
  };
40
113
 
41
114
  // Async worker for SCardTransmit
package/src/pcsc_card.cpp CHANGED
@@ -1,11 +1,10 @@
1
1
  #include "pcsc_card.h"
2
2
  #include "pcsc_errors.h"
3
3
  #include "pcsc_napi_error.h"
4
+ #include "addon_data.h"
4
5
  #include "async_workers.h"
5
6
  #include <cstring>
6
7
 
7
- Napi::FunctionReference PCSCCard::constructor;
8
-
9
8
  Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
10
9
  Napi::Function func = DefineClass(env, "Card", {
11
10
  InstanceAccessor("protocol", &PCSCCard::GetProtocolValue, nullptr),
@@ -18,8 +17,7 @@ Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
18
17
  InstanceMethod("reconnect", &PCSCCard::Reconnect),
19
18
  });
20
19
 
21
- constructor = Napi::Persistent(func);
22
- constructor.SuppressDestruct();
20
+ env.GetInstanceData<AddonData>()->cardConstructor = Napi::Persistent(func);
23
21
 
24
22
  exports.Set("Card", func);
25
23
  return exports;
@@ -28,7 +26,7 @@ Napi::Object PCSCCard::Init(Napi::Env env, Napi::Object exports) {
28
26
  Napi::Object PCSCCard::NewInstance(Napi::Env env, ContextHandlePtr context,
29
27
  SCARDHANDLE card, DWORD protocol,
30
28
  const std::string& readerName) {
31
- Napi::Object obj = constructor.New({});
29
+ Napi::Object obj = env.GetInstanceData<AddonData>()->cardConstructor.New({});
32
30
  PCSCCard* cardObj = Napi::ObjectWrap<PCSCCard>::Unwrap(obj);
33
31
  cardObj->context_ = std::move(context);
34
32
  cardObj->card_ = card;
package/src/pcsc_card.h CHANGED
@@ -25,8 +25,6 @@ public:
25
25
  bool IsConnected() const { return connected_ && context_ && context_->IsValid(); }
26
26
 
27
27
  private:
28
- static Napi::FunctionReference constructor;
29
-
30
28
  // Keeps the context alive for as long as this card; destroyed after
31
29
  // ~PCSCCard's body, so the card disconnects before the context goes
32
30
  ContextHandlePtr context_;
@@ -3,10 +3,9 @@
3
3
  #include "pcsc_errors.h"
4
4
  #include "pcsc_napi_error.h"
5
5
  #include "async_workers.h"
6
+ #include <cmath>
6
7
  #include <cstring>
7
8
 
8
- Napi::FunctionReference PCSCContext::constructor;
9
-
10
9
  Napi::Object PCSCContext::Init(Napi::Env env, Napi::Object exports) {
11
10
  Napi::Function func = DefineClass(env, "Context", {
12
11
  InstanceMethod("listReaders", &PCSCContext::ListReaders),
@@ -16,19 +15,13 @@ Napi::Object PCSCContext::Init(Napi::Env env, Napi::Object exports) {
16
15
  InstanceAccessor("isValid", &PCSCContext::GetIsValid, nullptr),
17
16
  });
18
17
 
19
- constructor = Napi::Persistent(func);
20
- constructor.SuppressDestruct();
21
-
22
18
  exports.Set("Context", func);
23
19
  return exports;
24
20
  }
25
21
 
26
- Napi::Object PCSCContext::NewInstance(Napi::Env env) {
27
- return constructor.New({});
28
- }
29
-
30
22
  PCSCContext::PCSCContext(const Napi::CallbackInfo& info)
31
- : Napi::ObjectWrap<PCSCContext>(info) {
23
+ : Napi::ObjectWrap<PCSCContext>(info),
24
+ pendingWaits_(std::make_shared<WaitForChangeWorker::PendingWaits>()) {
32
25
 
33
26
  Napi::Env env = info.Env();
34
27
 
@@ -121,40 +114,59 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
121
114
 
122
115
  SCARDCONTEXT context = handle_->Get();
123
116
 
124
- // Parse arguments: readers array (optional), timeout (optional)
125
117
  std::vector<std::string> readerNames;
126
118
  std::vector<DWORD> currentStates;
127
119
  DWORD timeout = INFINITE;
128
120
 
121
+ // Arguments: (readers?, timeout?) or (timeout). readers is an array of
122
+ // Readers, ReaderStates or reader names, or undefined/null for none; any
123
+ // first argument that isn't a number takes its place, so a timeout can
124
+ // always follow. timeout is in milliseconds: omitted, undefined, null or
125
+ // Infinity mean none, and a negative one is spent already.
129
126
  size_t argIndex = 0;
130
-
131
- // First argument can be array of readers or timeout
132
- if (info.Length() > 0 && info[0].IsArray()) {
133
- Napi::Array readersArray = info[0].As<Napi::Array>();
134
- for (uint32_t i = 0; i < readersArray.Length(); i++) {
135
- Napi::Value item = readersArray.Get(i);
136
- if (item.IsObject()) {
137
- // It's a Reader object
138
- Napi::Object obj = item.As<Napi::Object>();
139
- if (obj.Has("name")) {
140
- readerNames.push_back(obj.Get("name").As<Napi::String>().Utf8Value());
141
- if (obj.Has("state")) {
142
- currentStates.push_back(obj.Get("state").As<Napi::Number>().Uint32Value());
143
- } else {
144
- currentStates.push_back(SCARD_STATE_UNAWARE);
127
+ if (info.Length() > 0 && !info[0].IsNumber()) {
128
+ if (info[0].IsArray()) {
129
+ Napi::Array readersArray = info[0].As<Napi::Array>();
130
+ for (uint32_t i = 0; i < readersArray.Length(); i++) {
131
+ Napi::Value item = readersArray.Get(i);
132
+ if (item.IsObject()) {
133
+ // It's a Reader object
134
+ Napi::Object obj = item.As<Napi::Object>();
135
+ if (obj.Has("name")) {
136
+ readerNames.push_back(obj.Get("name").As<Napi::String>().Utf8Value());
137
+ if (obj.Has("state")) {
138
+ currentStates.push_back(obj.Get("state").As<Napi::Number>().Uint32Value());
139
+ } else {
140
+ currentStates.push_back(SCARD_STATE_UNAWARE);
141
+ }
145
142
  }
143
+ } else if (item.IsString()) {
144
+ readerNames.push_back(item.As<Napi::String>().Utf8Value());
145
+ currentStates.push_back(SCARD_STATE_UNAWARE);
146
146
  }
147
- } else if (item.IsString()) {
148
- readerNames.push_back(item.As<Napi::String>().Utf8Value());
149
- currentStates.push_back(SCARD_STATE_UNAWARE);
150
147
  }
148
+ } else if (!info[0].IsUndefined() && !info[0].IsNull()) {
149
+ Napi::TypeError::New(env, "waitForChange(): readers must be an array")
150
+ .ThrowAsJavaScriptException();
151
+ return env.Null();
151
152
  }
152
- argIndex++;
153
+ argIndex = 1;
153
154
  }
154
155
 
155
- // Next argument is timeout
156
- if (info.Length() > argIndex && info[argIndex].IsNumber()) {
157
- timeout = info[argIndex].As<Napi::Number>().Uint32Value();
156
+ if (info.Length() > argIndex && !info[argIndex].IsUndefined() && !info[argIndex].IsNull()) {
157
+ double ms = info[argIndex].IsNumber() ? info[argIndex].As<Napi::Number>().DoubleValue() : NAN;
158
+ if (std::isnan(ms)) {
159
+ Napi::TypeError::New(env, "waitForChange(): timeout must be a number of milliseconds")
160
+ .ThrowAsJavaScriptException();
161
+ return env.Null();
162
+ }
163
+ if (ms >= static_cast<double>(INFINITE)) {
164
+ timeout = INFINITE;
165
+ } else if (ms <= 0) {
166
+ timeout = 0;
167
+ } else {
168
+ timeout = static_cast<DWORD>(ms);
169
+ }
158
170
  }
159
171
 
160
172
  // If no readers specified, get all readers
@@ -178,43 +190,57 @@ Napi::Value PCSCContext::WaitForChange(const Napi::CallbackInfo& info) {
178
190
  }
179
191
  }
180
192
  }
193
+ if (result != SCARD_S_SUCCESS &&
194
+ result != static_cast<LONG>(SCARD_E_NO_READERS_AVAILABLE)) {
195
+ // No list to wait on: a wait on no readers would return at
196
+ // once, as if it had timed out
197
+ Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
198
+ deferred.Reject(NewPCSCError(env, result).Value());
199
+ return deferred.Promise();
200
+ }
181
201
  }
182
202
 
183
- // Create promise and start async worker
184
- Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
185
-
186
- WaitForChangeWorker* worker = new WaitForChangeWorker(
187
- env, info.This().As<Napi::Object>(), context, readerNames, currentStates,
188
- timeout, deferred);
189
- worker->Queue();
190
-
191
- return deferred.Promise();
203
+ return WaitForChangeWorker::Start(
204
+ env, pendingWaits_, std::move(readerNames), std::move(currentStates), timeout);
192
205
  }
193
206
 
194
- Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
195
- Napi::Env env = info.Env();
196
-
197
- if (!IsValid()) {
198
- return env.Undefined();
207
+ void PCSCContext::CancelPendingWaits() {
208
+ // All marked first, so that none still starting begins (and takes one
209
+ // of pcscd's contexts) while the others are being cancelled
210
+ for (WaitForChangeWorker* wait : *pendingWaits_) {
211
+ wait->MarkCancelled();
199
212
  }
200
-
201
- LONG result = SCardCancel(handle_->Get());
202
- if (result != SCARD_S_SUCCESS && result != static_cast<LONG>(SCARD_E_INVALID_HANDLE)) {
203
- NewPCSCError(env, result).ThrowAsJavaScriptException();
213
+ for (WaitForChangeWorker* wait : *pendingWaits_) {
214
+ if (!wait->Cancel()) {
215
+ // SCardCancel keeps failing: pcscd is refusing new connections,
216
+ // and would for the rest too. They resolve with null whenever
217
+ // they next return.
218
+ break;
219
+ }
204
220
  }
221
+ }
205
222
 
206
- return env.Undefined();
223
+ // Ends every waitForChange() pending on this context: one that hasn't
224
+ // returned yet resolves with null. A wait has a context of its own, so
225
+ // this works even once close() has released this one.
226
+ Napi::Value PCSCContext::Cancel(const Napi::CallbackInfo& info) {
227
+ CancelPendingWaits();
228
+ return info.Env().Undefined();
207
229
  }
208
230
 
209
231
  Napi::Value PCSCContext::Close(const Napi::CallbackInfo& info) {
210
232
  Napi::Env env = info.Env();
211
233
 
212
234
  // Release now, even if readers or cards still hold the handle: they
213
- // see it as invalid from here on and stop using it
235
+ // see it as invalid from here on and stop using it. First, as it frees
236
+ // one of pcscd's contexts, which cancelling the waits may need.
214
237
  if (handle_) {
215
238
  handle_->Release();
216
239
  }
217
240
 
241
+ // Pending waits end as if cancelled
242
+ CancelPendingWaits();
243
+
218
244
  return env.Undefined();
219
245
  }
220
246
 
@@ -5,11 +5,11 @@
5
5
  #include <vector>
6
6
  #include "platform/pcsc.h"
7
7
  #include "pcsc_context_handle.h"
8
+ #include "async_workers.h"
8
9
 
9
10
  class PCSCContext : public Napi::ObjectWrap<PCSCContext> {
10
11
  public:
11
12
  static Napi::Object Init(Napi::Env env, Napi::Object exports);
12
- static Napi::Object NewInstance(Napi::Env env);
13
13
 
14
14
  PCSCContext(const Napi::CallbackInfo& info);
15
15
 
@@ -18,12 +18,16 @@ public:
18
18
  bool IsValid() const { return handle_ && handle_->IsValid(); }
19
19
 
20
20
  private:
21
- static Napi::FunctionReference constructor;
22
-
23
21
  // Shared with the Readers (and their Cards) created from this context;
24
22
  // released when the last of them is finalized, or by close()
25
23
  ContextHandlePtr handle_;
26
24
 
25
+ // waitForChange() calls still pending, each on a context of its own:
26
+ // cancel() and close() end them
27
+ WaitForChangeWorker::PendingWaitsPtr pendingWaits_;
28
+
29
+ void CancelPendingWaits();
30
+
27
31
  // JavaScript-exposed methods
28
32
  Napi::Value ListReaders(const Napi::CallbackInfo& info);
29
33
  Napi::Value WaitForChange(const Napi::CallbackInfo& info);