-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPcscReaderAdapter.java
More file actions
699 lines (651 loc) · 20.6 KB
/
PcscReaderAdapter.java
File metadata and controls
699 lines (651 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
/* **************************************************************************************
* Copyright (c) 2021 Calypso Networks Association https://calypsonet.org/
*
* See the NOTICE file(s) distributed with this work for additional information
* regarding copyright ownership.
*
* This program and the accompanying materials are made available under the terms of the
* Eclipse Public License 2.0 which is available at http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
************************************************************************************** */
package org.eclipse.keyple.plugin.pcsc;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.smartcardio.*;
import jnasmartcardio.Smartcardio;
import org.eclipse.keyple.core.plugin.CardIOException;
import org.eclipse.keyple.core.plugin.ReaderIOException;
import org.eclipse.keyple.core.plugin.TaskCanceledException;
import org.eclipse.keyple.core.plugin.spi.reader.ConfigurableReaderSpi;
import org.eclipse.keyple.core.plugin.spi.reader.observable.ObservableReaderSpi;
import org.eclipse.keyple.core.plugin.spi.reader.observable.state.insertion.CardInsertionWaiterBlockingSpi;
import org.eclipse.keyple.core.plugin.spi.reader.observable.state.processing.CardPresenceMonitorBlockingSpi;
import org.eclipse.keyple.core.plugin.spi.reader.observable.state.removal.CardRemovalWaiterBlockingSpi;
import org.eclipse.keyple.core.util.Assert;
import org.eclipse.keyple.core.util.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link PcscReaderAdapter}.
*
* @since 2.0.0
*/
final class PcscReaderAdapter
implements PcscReader,
ConfigurableReaderSpi,
ObservableReaderSpi,
CardInsertionWaiterBlockingSpi,
CardPresenceMonitorBlockingSpi,
CardRemovalWaiterBlockingSpi {
private static final Logger logger = LoggerFactory.getLogger(PcscReaderAdapter.class);
private final CardTerminal communicationTerminal; // For connect/transmit operations
private final CardTerminal monitoringTerminal; // For waitForCardPresent/Absent operations
private final String name;
private final PcscPluginAdapter pluginAdapter;
private final boolean isWindows;
private final int cardMonitoringCycleDuration;
private final byte[] pingApdu = HexUtil.toByteArray("00C0000000"); // GET RESPONSE
private Card card;
private CardChannel channel;
private Boolean isContactless;
private String protocol = IsoProtocol.ANY.getValue();
private boolean isModeExclusive = false;
private DisconnectionMode disconnectionMode = DisconnectionMode.RESET;
private final AtomicBoolean loopWaitCard = new AtomicBoolean();
private final AtomicBoolean loopWaitCardRemoval = new AtomicBoolean();
private boolean isObservationActive;
/**
* Constructor.
*
* @since 2.0.0
*/
PcscReaderAdapter(
CardTerminal terminal, PcscPluginAdapter pluginAdapter, int cardMonitoringCycleDuration) {
this.communicationTerminal = terminal;
this.pluginAdapter = pluginAdapter;
this.name = terminal.getName();
this.isWindows = System.getProperty("os.name").toLowerCase().contains("win");
this.cardMonitoringCycleDuration = cardMonitoringCycleDuration;
// Create a separate PC/SC context for monitoring operations to avoid contention under Linux
// This is critical because Linux pcsc-lite does not handle concurrent access to a single
// SCARDCONTEXT as robustly as Windows (see threading differences documentation)
this.monitoringTerminal = createMonitoringTerminal(terminal.getName());
}
/**
* Creates a separate CardTerminal instance for monitoring operations using a dedicated PC/SC
* context.
*
* <p>Under Linux with pcsc-lite, sharing the same SCARDCONTEXT between blocking monitoring calls
* (waitForCardPresent/Absent) and communication operations (transmit) can cause thread contention
* and SCARD_E_SHARING_VIOLATION errors due to the self-pipe trick mechanism used for
* cancellation.
*
* <p>This method attempts to create a new TerminalFactory instance to obtain a separate context.
* If this fails (e.g., on older JRE versions or with certain security providers), it falls back
* to using the same terminal, which may cause issues on Linux but will still work on Windows.
*
* @param terminalName The name of the terminal to create a monitoring instance for.
* @return A CardTerminal instance for monitoring, either with a separate context or the same one.
*/
private CardTerminal createMonitoringTerminal(String terminalName) {
try {
// Attempt to create a new TerminalFactory instance to get a separate PC/SC context
TerminalFactory monitoringFactory = TerminalFactory.getDefault();
CardTerminals monitoringTerminals = monitoringFactory.terminals();
// Find the terminal with the same name in the new context
for (CardTerminal t : monitoringTerminals.list()) {
if (t.getName().equals(terminalName)) {
if (logger.isDebugEnabled()) {
logger.debug(
"[{}] creating separate monitoring context for improved Linux compatibility",
terminalName);
}
return t;
}
}
// Terminal not found in new context, fall back to same terminal
logger.warn(
"[{}] could not find terminal in separate context, using shared context (may cause issues on Linux)",
terminalName);
return communicationTerminal;
} catch (Exception e) {
// Failed to create separate context, fall back to same terminal
logger.warn(
"[{}] could not create separate monitoring context [reason={}], using shared context (may cause issues on Linux)",
terminalName,
e.getMessage());
return communicationTerminal;
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void waitForCardInsertion() throws TaskCanceledException, ReaderIOException {
if (logger.isTraceEnabled()) {
logger.trace(
"[{}] start waiting card insertion (loop latency: {} ms)...",
getName(),
cardMonitoringCycleDuration);
}
// activate loop
loopWaitCard.set(true);
try {
while (loopWaitCard.get()) {
if (monitoringTerminal.waitForCardPresent(cardMonitoringCycleDuration)) {
// card inserted
if (logger.isTraceEnabled()) {
logger.trace("[{}] card inserted", getName());
}
return;
}
if (Thread.interrupted()) {
break;
}
}
if (logger.isTraceEnabled()) {
logger.trace("[{}] waiting card insertion stopped", getName());
}
} catch (CardException e) {
// here, it is a communication failure with the reader
throw new ReaderIOException(
name + ": an error occurred while waiting for a card insertion", e);
}
throw new TaskCanceledException(
name + ": the wait for a card insertion task has been cancelled");
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void stopWaitForCardInsertion() {
loopWaitCard.set(false);
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public boolean isProtocolSupported(String readerProtocol) {
return pluginAdapter.getProtocolRule(readerProtocol) != null;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void activateProtocol(String readerProtocol) {
if (logger.isTraceEnabled()) {
logger.trace("[{}] activating protocol [{}] takes no action", getName(), readerProtocol);
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void deactivateProtocol(String readerProtocol) {
if (logger.isTraceEnabled()) {
logger.trace("[{}] de-activating protocol [{}] takes no action", getName(), readerProtocol);
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public boolean isCurrentProtocol(String readerProtocol) {
String protocolRule = pluginAdapter.getProtocolRule(readerProtocol);
boolean isCurrentProtocol;
if (protocolRule != null && !protocolRule.isEmpty()) {
String atr = HexUtil.toHex(card.getATR().getBytes());
isCurrentProtocol = Pattern.compile(protocolRule).matcher(atr).matches();
} else {
isCurrentProtocol = false;
}
return isCurrentProtocol;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void onStartDetection() {
isObservationActive = true;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void onStopDetection() {
isObservationActive = false;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public String getName() {
return name;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void openPhysicalChannel() throws ReaderIOException, CardIOException {
if (card != null) {
return;
}
/* init of the card physical channel: if not yet established, opening of a new physical channel */
try {
if (logger.isDebugEnabled()) {
logger.debug("[{}] opening card physical channel for protocol [{}]", getName(), protocol);
}
card = this.communicationTerminal.connect(protocol);
if (isModeExclusive) {
card.beginExclusive();
if (logger.isDebugEnabled()) {
logger.debug("[{}] card physical channel opened in EXCLUSIVE mode", getName());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("[{}] card physical channel opened in SHARED mode", getName());
}
}
channel = card.getBasicChannel();
} catch (CardNotPresentException e) {
throw new CardIOException(getName() + ": Card removed", e);
} catch (CardException e) {
throw new ReaderIOException(getName() + ": Error while opening Physical Channel", e);
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void closePhysicalChannel() throws ReaderIOException {
// If the reader is observed, the actual disconnection will be done in the card removal sequence
if (!isObservationActive) {
disconnect();
}
}
/**
* Disconnects the current card and resets the context and reader state.
*
* <p>This method handles the disconnection of a card, taking into account the specific
* disconnection mode. If the card is an instance of {@link Smartcardio.JnaCard}, it disconnects
* using the extended mode specified by {@link #getDisposition(DisconnectionMode)} and resets the
* reader state to avoid incorrect card detection in subsequent operations. For other card types,
* it disconnects using the specified disconnection mode directly.
*
* <p>If a {@link CardException} occurs during the operation, a {@link ReaderIOException} is
* thrown with the associated error message.
*
* <p>Once the disconnection is handled, the method ensures that the context is reset.
*
* @throws ReaderIOException If an error occurs while closing the physical channel.
*/
private void disconnect() throws ReaderIOException {
try {
if (card != null) {
if (card instanceof Smartcardio.JnaCard) {
// disconnect using the extended mode allowing UNPOWER
((Smartcardio.JnaCard) card).disconnect(getDisposition(disconnectionMode));
// reset the reader state to avoid bad card detection next time
resetReaderState();
} else {
card.disconnect(disconnectionMode == DisconnectionMode.RESET);
}
}
} catch (CardException e) {
throw new ReaderIOException("Error while closing physical channel", e);
} finally {
resetContext();
}
}
/**
* Maps a DisconnectionMode to the corresponding SCARD_* constant.
*
* @param mode The disconnection mode.
* @return The corresponding SCARD_* value.
*/
private static int getDisposition(DisconnectionMode mode) {
switch (mode) {
case RESET:
return Smartcardio.JnaCard.SCARD_RESET_CARD;
case LEAVE:
return Smartcardio.JnaCard.SCARD_LEAVE_CARD;
case UNPOWER:
return Smartcardio.JnaCard.SCARD_UNPOWER_CARD;
case EJECT:
return Smartcardio.JnaCard.SCARD_EJECT_CARD;
default:
throw new IllegalArgumentException("Unknown DisconnectionMode: " + mode);
}
}
/**
* Resets the state of the card reader.
*
* <p>This method attempts to reset the reader state based on the current disconnection mode. If
* the disconnection mode is set to UNPOWER, it reconnects to the terminal and then disconnects
* without powering off the reader. If any {@link CardException} occurs during this process, it is
* handled silently.
*/
private void resetReaderState() {
try {
if (disconnectionMode == DisconnectionMode.UNPOWER) {
communicationTerminal.connect("*").disconnect(false);
}
} catch (CardException e) {
// NOP
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public boolean isPhysicalChannelOpen() {
return card != null;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public boolean checkCardPresence() throws ReaderIOException {
try {
boolean isCardPresent = communicationTerminal.isCardPresent();
closePhysicalChannelSafely();
return isCardPresent;
} catch (CardException e) {
throw new ReaderIOException("Exception occurred in isCardPresent", e);
}
}
private void closePhysicalChannelSafely() {
try {
disconnect();
} catch (Exception e) {
// NOP
}
}
private void resetContext() {
card = null;
channel = null;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public String getPowerOnData() {
return HexUtil.toHex(card.getATR().getBytes());
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public byte[] transmitApdu(byte[] apduCommandData) throws ReaderIOException, CardIOException {
byte[] apduResponseData;
if (channel != null) {
try {
apduResponseData = channel.transmit(new CommandAPDU(apduCommandData)).getBytes();
} catch (CardNotPresentException e) {
throw new CardIOException(name + ": " + e.getMessage(), e);
} catch (CardException e) {
if (e.getMessage().contains("CARD")
|| e.getMessage().contains("NOT_TRANSACTED")
|| e.getMessage().contains("INVALID_ATR")) {
throw new CardIOException(name + ": " + e.getMessage(), e);
} else {
throw new ReaderIOException(name + ": " + e.getMessage(), e);
}
} catch (IllegalStateException | IllegalArgumentException e) {
// card could have been removed prematurely
throw new CardIOException(name + ": " + e.getMessage(), e);
}
} else {
// could occur if the card was removed
throw new CardIOException(name + ": null channel.");
}
return apduResponseData;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public boolean isContactless() {
if (isContactless == null) {
// First time initialisation, the transmission mode has not yet been determined or fixed
// explicitly, let's ask the plugin to determine it (only once)
isContactless = pluginAdapter.isContactless(getName());
}
return isContactless;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void onUnregister() {
/* Nothing to do here in this reader */
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void monitorCardPresenceDuringProcessing()
throws ReaderIOException, TaskCanceledException {
waitForCardRemoval();
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void stopCardPresenceMonitoringDuringProcessing() {
stopWaitForCardRemoval();
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void waitForCardRemoval() throws ReaderIOException, TaskCanceledException {
if (logger.isTraceEnabled()) {
logger.trace("[{}] start waiting card removal)", name);
}
loopWaitCardRemoval.set(true);
try {
if (disconnectionMode == DisconnectionMode.UNPOWER) {
waitForCardRemovalByPolling();
} else {
waitForCardRemovalStandard();
}
} finally {
try {
disconnect();
} catch (Exception e) {
logger.warn(
"[{}] error while disconnecting card during card removal: {}", name, e.getMessage());
}
}
if (logger.isTraceEnabled()) {
if (!loopWaitCardRemoval.get()) {
logger.trace("[{}] waiting card removal stopped", name);
} else {
logger.trace("[{}] card removed", name);
}
}
if (!loopWaitCardRemoval.get()) {
throw new TaskCanceledException(
name + ": the wait for the card removal task has been cancelled.");
}
}
private void waitForCardRemovalByPolling() {
try {
while (loopWaitCardRemoval.get()) {
transmitApdu(pingApdu);
Thread.sleep(25);
if (Thread.interrupted()) {
return;
}
}
} catch (CardIOException | ReaderIOException e) {
logger.trace("Expected IOException while waiting for card removal: {}", e.getMessage());
} catch (InterruptedException e) {
logger.trace("InterruptedException while waiting for card removal: {}", e.getMessage());
Thread.currentThread().interrupt();
}
}
private void waitForCardRemovalStandard() throws ReaderIOException {
try {
while (loopWaitCardRemoval.get()) {
if (monitoringTerminal.waitForCardAbsent(cardMonitoringCycleDuration)) {
return;
}
if (Thread.interrupted()) {
return;
}
}
} catch (CardException e) {
throw new ReaderIOException(
name + ": an error occurred while waiting for the card removal.", e);
}
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public void stopWaitForCardRemoval() {
loopWaitCardRemoval.set(false);
}
/**
* {@inheritDoc}
*
* <p>The default value is {@link SharingMode#SHARED}.
*
* @since 2.0.0
*/
@Override
public PcscReader setSharingMode(SharingMode sharingMode) {
Assert.getInstance().notNull(sharingMode, "sharingMode");
logger.info("[{}] set sharing mode [newValue={}]", getName(), sharingMode.name());
if (sharingMode == SharingMode.SHARED) {
// if a card is present, change the mode immediately
if (card != null) {
try {
card.endExclusive();
} catch (CardException e) {
throw new IllegalStateException("Couldn't disable exclusive mode", e);
}
}
isModeExclusive = false;
} else if (sharingMode == SharingMode.EXCLUSIVE) {
isModeExclusive = true;
}
return this;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public PcscReader setContactless(boolean contactless) {
logger.info("[{}] set contactless type [newValue={}]", getName(), contactless);
this.isContactless = contactless;
return this;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public PcscReader setIsoProtocol(IsoProtocol isoProtocol) {
Assert.getInstance().notNull(isoProtocol, "isoProtocol");
logger.info(
"[{}] set ISO protocol [protocolName={}, newValue={}]",
getName(),
isoProtocol.name(),
isoProtocol.getValue());
protocol = isoProtocol.getValue();
return this;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public PcscReader setDisconnectionMode(DisconnectionMode disconnectionMode) {
Assert.getInstance().notNull(disconnectionMode, "disconnectionMode");
logger.info("[{}] set disconnection mode [newValue={}]", getName(), disconnectionMode.name());
this.disconnectionMode = disconnectionMode;
return this;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public byte[] transmitControlCommand(int commandId, byte[] command) {
Assert.getInstance().notNull(command, "command");
byte[] response;
int controlCode = isWindows ? 0x00310000 | (commandId << 2) : 0x42000000 | commandId;
try {
if (card != null) {
response = card.transmitControlCommand(controlCode, command);
} else {
Card virtualCard = communicationTerminal.connect("DIRECT");
response = virtualCard.transmitControlCommand(controlCode, command);
virtualCard.disconnect(false);
}
} catch (CardException e) {
throw new IllegalStateException("Reader failure.", e);
}
return response;
}
/**
* {@inheritDoc}
*
* @since 2.0.0
*/
@Override
public int getIoctlCcidEscapeCommandId() {
return isWindows ? 3500 : 1;
}
}