"Fossies" - the Fresh Open Source Software Archive

Member "opensc-0.22.0/src/libopensc/reader-pcsc.c" (10 Aug 2021, 78529 Bytes) of package /linux/privat/opensc-0.22.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "reader-pcsc.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 0.21.0_vs_0.22.0.

    1 /*
    2  * reader-pcsc.c: Reader driver for PC/SC interface
    3  *
    4  * Copyright (C) 2002  Juha Yrjölä <juha.yrjola@iki.fi>
    5  * Copyright (C) 2009,2010 Martin Paljak <martin@martinpaljak.net>
    6  *
    7  * This library is free software; you can redistribute it and/or
    8  * modify it under the terms of the GNU Lesser General Public
    9  * License as published by the Free Software Foundation; either
   10  * version 2.1 of the License, or (at your option) any later version.
   11  *
   12  * This library is distributed in the hope that it will be useful,
   13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   15  * Lesser General Public License for more details.
   16  *
   17  * You should have received a copy of the GNU Lesser General Public
   18  * License along with this library; if not, write to the Free Software
   19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   20  */
   21 
   22 #if HAVE_CONFIG_H
   23 #include "config.h"
   24 #endif
   25 
   26 #ifdef ENABLE_PCSC  /* empty file without pcsc */
   27 
   28 #include <assert.h>
   29 #include <stdlib.h>
   30 #include <string.h>
   31 #include <time.h>
   32 
   33 #ifdef _WIN32
   34 #include <winsock2.h>
   35 #else
   36 #include <arpa/inet.h>
   37 #endif
   38 
   39 #include "common/libscdl.h"
   40 #include "internal.h"
   41 #include "internal-winscard.h"
   42 #include "card-sc-hsm.h"
   43 
   44 #include "pace.h"
   45 
   46 #ifdef HAVE_PCSCLITE_H
   47 #if !defined (__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED < 101000
   48 #define HAVE_PCSCLITE 1
   49 #endif
   50 #endif
   51 
   52 #define SCARD_CLASS_SYSTEM     0x7fff
   53 #define SCARD_ATTR_VALUE(Class, Tag) ((((ULONG)(Class)) << 16) | ((ULONG)(Tag)))
   54 
   55 #ifndef SCARD_ATTR_DEVICE_FRIENDLY_NAME_A
   56 #define SCARD_ATTR_DEVICE_FRIENDLY_NAME_A SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0003)
   57 #endif
   58 
   59 #ifndef SCARD_ATTR_DEVICE_SYSTEM_NAME_A
   60 #define SCARD_ATTR_DEVICE_SYSTEM_NAME_A SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0004)
   61 #endif
   62 
   63 #define SCARD_CLASS_VENDOR_INFO 1
   64 
   65 #ifndef SCARD_ATTR_VENDOR_NAME
   66 #define SCARD_ATTR_VENDOR_NAME SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0100) /**< Vendor name. */
   67 #endif
   68 
   69 #ifndef SCARD_ATTR_VENDOR_IFD_TYPE
   70 #define SCARD_ATTR_VENDOR_IFD_TYPE SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0101) /**< Vendor-supplied interface device type (model designation of reader). */
   71 #endif
   72 
   73 #ifndef SCARD_ATTR_VENDOR_IFD_VERSION
   74 #define SCARD_ATTR_VENDOR_IFD_VERSION SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0102) /**< Vendor-supplied interface device version (DWORD in the form 0xMMmmbbbb where MM = major version, mm = minor version, and bbbb = build number). */
   75 #endif
   76 
   77 /* Logging */
   78 #define PCSC_TRACE(reader, desc, rv) do { sc_log(reader->ctx, "%s:" desc ": 0x%08lx\n", reader->name, (unsigned long)((ULONG)rv)); } while (0)
   79 #define PCSC_LOG(ctx, desc, rv) do { sc_log(ctx, desc ": 0x%08lx\n", (unsigned long)((ULONG)rv)); } while (0)
   80 
   81 /* #define APDU_LOG_FILE "apdulog" */
   82 #ifdef APDU_LOG_FILE
   83 void APDU_LOG(u8 *rbuf, uint16_t rsize)
   84 {
   85     static FILE *fd = NULL;
   86     u8 *lenb = (u8*)&rsize;
   87 
   88     if (fd == NULL) {
   89         fd = fopen(APDU_LOG_FILE, "w");
   90     }
   91     /* First two bytes denote the length */
   92     (void) fwrite(lenb, 2, 1, fd);
   93     (void) fwrite(rbuf, rsize, 1, fd);
   94     fflush(fd);
   95 }
   96 #else
   97 #define APDU_LOG(rbuf, rsize)
   98 #endif
   99 
  100 struct pcsc_global_private_data {
  101     int cardmod;
  102     SCARDCONTEXT pcsc_ctx;
  103     SCARDCONTEXT pcsc_wait_ctx;
  104     int enable_pinpad;
  105     int fixed_pinlength;
  106     int enable_pace;
  107     size_t force_max_recv_size;
  108     size_t force_max_send_size;
  109     int connect_exclusive;
  110     DWORD disconnect_action;
  111     DWORD transaction_end_action;
  112     DWORD reconnect_action;
  113     const char *provider_library;
  114     void *dlhandle;
  115     SCardEstablishContext_t SCardEstablishContext;
  116     SCardReleaseContext_t SCardReleaseContext;
  117     SCardConnect_t SCardConnect;
  118     SCardReconnect_t SCardReconnect;
  119     SCardDisconnect_t SCardDisconnect;
  120     SCardBeginTransaction_t SCardBeginTransaction;
  121     SCardEndTransaction_t SCardEndTransaction;
  122     SCardStatus_t SCardStatus;
  123     SCardGetStatusChange_t SCardGetStatusChange;
  124     SCardCancel_t SCardCancel;
  125     SCardControlOLD_t SCardControlOLD;
  126     SCardControl_t SCardControl;
  127     SCardTransmit_t SCardTransmit;
  128     SCardListReaders_t SCardListReaders;
  129     SCardGetAttrib_t SCardGetAttrib;
  130 
  131     sc_reader_t *attached_reader;
  132     sc_reader_t *removed_reader;
  133 };
  134 
  135 struct pcsc_private_data {
  136     struct pcsc_global_private_data *gpriv;
  137     SCARDHANDLE pcsc_card;
  138     SCARD_READERSTATE reader_state;
  139     DWORD verify_ioctl;
  140     DWORD verify_ioctl_start;
  141     DWORD verify_ioctl_finish;
  142 
  143     DWORD modify_ioctl;
  144     DWORD modify_ioctl_start;
  145     DWORD modify_ioctl_finish;
  146 
  147     DWORD pace_ioctl;
  148 
  149     DWORD pin_properties_ioctl;
  150 
  151     DWORD get_tlv_properties;
  152 
  153     int locked;
  154 };
  155 
  156 static int pcsc_detect_card_presence(sc_reader_t *reader);
  157 static int pcsc_reconnect(sc_reader_t * reader, DWORD action);
  158 static int pcsc_connect(sc_reader_t *reader);
  159 
  160 static DWORD pcsc_reset_action(const char *str)
  161 {
  162     if (!strcmp(str, "reset"))
  163         return SCARD_RESET_CARD;
  164     else if (!strcmp(str, "unpower"))
  165         return SCARD_UNPOWER_CARD;
  166     else
  167         return SCARD_LEAVE_CARD;
  168 }
  169 
  170 static int pcsc_to_opensc_error(LONG rv)
  171 {
  172     switch (rv) {
  173     case SCARD_S_SUCCESS:
  174         return SC_SUCCESS;
  175     case SCARD_W_REMOVED_CARD:
  176         return SC_ERROR_CARD_REMOVED;
  177     case SCARD_E_NOT_TRANSACTED:
  178         return SC_ERROR_TRANSMIT_FAILED;
  179     case SCARD_W_UNRESPONSIVE_CARD:
  180         return SC_ERROR_CARD_UNRESPONSIVE;
  181     case SCARD_W_UNPOWERED_CARD:
  182         return SC_ERROR_CARD_UNRESPONSIVE;
  183     case SCARD_E_SHARING_VIOLATION:
  184         return SC_ERROR_READER_LOCKED;
  185     case SCARD_E_NO_READERS_AVAILABLE:
  186         return SC_ERROR_NO_READERS_FOUND;
  187     case SCARD_E_UNKNOWN_READER:
  188         return SC_ERROR_READER_DETACHED;
  189 
  190     case SCARD_E_NO_SERVICE:
  191     case SCARD_E_SERVICE_STOPPED:
  192         /* If the service is (auto)started, there could be readers later */
  193         return SC_ERROR_NO_READERS_FOUND;
  194     case SCARD_E_NO_SMARTCARD:
  195         return SC_ERROR_CARD_NOT_PRESENT;
  196     case SCARD_E_PROTO_MISMATCH: /* Should not happen */
  197         return SC_ERROR_READER;
  198     default:
  199         return SC_ERROR_UNKNOWN;
  200     }
  201 }
  202 
  203 static unsigned int pcsc_proto_to_opensc(DWORD proto)
  204 {
  205     switch (proto) {
  206     case SCARD_PROTOCOL_T0:
  207         return SC_PROTO_T0;
  208     case SCARD_PROTOCOL_T1:
  209         return SC_PROTO_T1;
  210     case SCARD_PROTOCOL_RAW:
  211         return SC_PROTO_RAW;
  212     default:
  213         return 0;
  214     }
  215 }
  216 
  217 static DWORD opensc_proto_to_pcsc(unsigned int proto)
  218 {
  219     switch (proto) {
  220     case SC_PROTO_T0:
  221         return SCARD_PROTOCOL_T0;
  222     case SC_PROTO_T1:
  223         return SCARD_PROTOCOL_T1;
  224     case SC_PROTO_RAW:
  225         return SCARD_PROTOCOL_RAW;
  226     default:
  227         return 0;
  228     }
  229 }
  230 
  231 static int pcsc_internal_transmit(sc_reader_t *reader,
  232              const u8 *sendbuf, size_t sendsize,
  233              u8 *recvbuf, size_t *recvsize,
  234              unsigned long control)
  235 {
  236     struct pcsc_private_data *priv = reader->drv_data;
  237     SCARD_IO_REQUEST sSendPci, sRecvPci;
  238     DWORD dwSendLength, dwRecvLength;
  239     LONG rv;
  240     SCARDHANDLE card;
  241 
  242     LOG_FUNC_CALLED(reader->ctx);
  243     card = priv->pcsc_card;
  244 
  245     if (reader->ctx->flags & SC_CTX_FLAG_TERMINATE)
  246         return SC_ERROR_NOT_ALLOWED;
  247 
  248     sSendPci.dwProtocol = opensc_proto_to_pcsc(reader->active_protocol);
  249     sSendPci.cbPciLength = sizeof(sSendPci);
  250     sRecvPci.dwProtocol = opensc_proto_to_pcsc(reader->active_protocol);
  251     sRecvPci.cbPciLength = sizeof(sRecvPci);
  252 
  253     dwSendLength = sendsize;
  254     dwRecvLength = *recvsize;
  255 
  256     if (!control) {
  257         rv = priv->gpriv->SCardTransmit(card, &sSendPci, sendbuf, dwSendLength,
  258                    &sRecvPci, recvbuf, &dwRecvLength);
  259     } else {
  260         if (priv->gpriv->SCardControlOLD != NULL) {
  261             rv = priv->gpriv->SCardControlOLD(card, sendbuf, dwSendLength,
  262                   recvbuf, &dwRecvLength);
  263         }
  264         else {
  265             rv = priv->gpriv->SCardControl(card, (DWORD) control, sendbuf, dwSendLength,
  266                   recvbuf, dwRecvLength, &dwRecvLength);
  267         }
  268     }
  269 
  270     if (rv != SCARD_S_SUCCESS) {
  271         PCSC_TRACE(reader, "SCardTransmit/Control failed", rv);
  272         switch (rv) {
  273         case SCARD_W_REMOVED_CARD:
  274             return SC_ERROR_CARD_REMOVED;
  275         case SCARD_E_INVALID_HANDLE:
  276         case SCARD_E_INVALID_VALUE:
  277         case SCARD_E_READER_UNAVAILABLE:
  278             pcsc_connect(reader);
  279             /* return failure so that upper layers will be notified */
  280             return SC_ERROR_READER_REATTACHED;
  281         case SCARD_W_RESET_CARD:
  282             pcsc_reconnect(reader, SCARD_LEAVE_CARD);
  283             /* return failure so that upper layers will be notified */
  284             return SC_ERROR_CARD_RESET;
  285         default:
  286             /* Translate strange errors from card removal to a proper return code */
  287             pcsc_detect_card_presence(reader);
  288             if (!(pcsc_detect_card_presence(reader) & SC_READER_CARD_PRESENT))
  289                 return SC_ERROR_CARD_REMOVED;
  290             return SC_ERROR_TRANSMIT_FAILED;
  291         }
  292     }
  293     if (!control && dwRecvLength < 2)
  294         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
  295     *recvsize = dwRecvLength;
  296 
  297     return SC_SUCCESS;
  298 }
  299 
  300 static int pcsc_transmit(sc_reader_t *reader, sc_apdu_t *apdu)
  301 {
  302     size_t ssize, rsize, rbuflen = 0;
  303     u8 *sbuf = NULL, *rbuf = NULL;
  304     int r;
  305 
  306     /* we always use a at least 258 byte size big return buffer
  307      * to mimic the behaviour of the old implementation (some readers
  308      * seems to require a larger than necessary return buffer).
  309      * The buffer for the returned data needs to be at least 2 bytes
  310      * larger than the expected data length to store SW1 and SW2. */
  311     rsize = rbuflen = apdu->resplen <= 256 ? 258 : apdu->resplen + 2;
  312     rbuf     = malloc(rbuflen);
  313     if (rbuf == NULL) {
  314         r = SC_ERROR_OUT_OF_MEMORY;
  315         goto out;
  316     }
  317 
  318     /* encode and log the APDU */
  319     r = sc_apdu_get_octets(reader->ctx, apdu, &sbuf, &ssize, reader->active_protocol);
  320     if (r != SC_SUCCESS)
  321         goto out;
  322     if (reader->name)
  323         sc_log(reader->ctx, "reader '%s'", reader->name);
  324     sc_apdu_log(reader->ctx, sbuf, ssize, 1);
  325 
  326     r = pcsc_internal_transmit(reader, sbuf, ssize,
  327                 rbuf, &rsize, apdu->control);
  328     if (r < 0) {
  329         /* unable to transmit ... most likely a reader problem */
  330         sc_log(reader->ctx, "unable to transmit");
  331         goto out;
  332     }
  333     sc_apdu_log(reader->ctx, rbuf, rsize, 0);
  334     APDU_LOG(rbuf, (uint16_t)rsize);
  335     /* set response */
  336     r = sc_apdu_set_resp(reader->ctx, apdu, rbuf, rsize);
  337 
  338 out:
  339     if (sbuf != NULL) {
  340         sc_mem_clear(sbuf, ssize);
  341         free(sbuf);
  342     }
  343     if (rbuf != NULL) {
  344         sc_mem_clear(rbuf, rbuflen);
  345         free(rbuf);
  346     }
  347 
  348     return r;
  349 }
  350 
  351 /* Calls SCardGetStatusChange on the reader to set ATR and associated flags
  352  * (card present/changed) */
  353 static int refresh_attributes(sc_reader_t *reader)
  354 {
  355     struct pcsc_private_data *priv = reader->drv_data;
  356     int old_flags = reader->flags;
  357     DWORD state, prev_state;
  358     LONG rv;
  359 
  360     sc_log(reader->ctx, "%s check", reader->name);
  361 
  362     if (reader->ctx->flags & SC_CTX_FLAG_TERMINATE)
  363         return SC_ERROR_NOT_ALLOWED;
  364 
  365     if (priv->reader_state.szReader == NULL || reader->ctx->flags & SC_READER_REMOVED) {
  366         priv->reader_state.szReader = reader->name;
  367         priv->reader_state.dwCurrentState = SCARD_STATE_UNAWARE;
  368         priv->reader_state.dwEventState = SCARD_STATE_UNAWARE;
  369     } else {
  370         priv->reader_state.dwCurrentState = priv->reader_state.dwEventState;
  371     }
  372 
  373     rv = priv->gpriv->SCardGetStatusChange(priv->gpriv->pcsc_ctx, 0, &priv->reader_state, 1);
  374 
  375     if (rv != SCARD_S_SUCCESS) {
  376         if (rv == (LONG)SCARD_E_TIMEOUT) {
  377             /* Timeout, no change from previous recorded state. Make sure that
  378              * changed flag is not set. */
  379             reader->flags &= ~SC_READER_CARD_CHANGED;
  380             /* Make sure to preserve the CARD_PRESENT flag if the reader was
  381              * reattached and we called the refresh_attributes too recently */
  382             if (priv->reader_state.dwEventState & SCARD_STATE_PRESENT) {
  383                 reader->flags |= SC_READER_CARD_PRESENT;
  384             }
  385             LOG_FUNC_RETURN(reader->ctx, SC_SUCCESS);
  386         }
  387         
  388         /* the system could not detect the reader. It means, the prevoiusly attached reader is disconnected. */
  389         if (rv == (LONG)SCARD_E_UNKNOWN_READER
  390 #ifdef SCARD_E_NO_READERS_AVAILABLE
  391                 || rv == (LONG)SCARD_E_NO_READERS_AVAILABLE
  392 #endif
  393                 || rv == (LONG)SCARD_E_SERVICE_STOPPED) {
  394             if (old_flags & SC_READER_CARD_PRESENT) {
  395                 reader->flags |= SC_READER_CARD_CHANGED;
  396             }
  397             
  398             SC_FUNC_RETURN(reader->ctx, SC_LOG_DEBUG_VERBOSE, SC_SUCCESS);
  399         }
  400 
  401         PCSC_TRACE(reader, "SCardGetStatusChange failed", rv);
  402         return pcsc_to_opensc_error(rv);
  403     }
  404     state = priv->reader_state.dwEventState;
  405     prev_state = priv->reader_state.dwCurrentState;
  406 
  407     sc_log(reader->ctx, "current  state: 0x%08X", (unsigned int)state);
  408     sc_log(reader->ctx, "previous state: 0x%08X", (unsigned int)prev_state);
  409 
  410     if (state & SCARD_STATE_UNKNOWN) {
  411         /* State means "reader unknown", but we have listed it at least once.
  412          * There can be no cards in this reader.
  413          * XXX: We'll hit it again, as no readers are removed currently.
  414          */
  415         reader->flags &= ~(SC_READER_CARD_PRESENT);
  416         return SC_ERROR_READER_DETACHED;
  417     }
  418 
  419     reader->flags &= ~(SC_READER_CARD_CHANGED|SC_READER_CARD_INUSE|SC_READER_CARD_EXCLUSIVE);
  420 
  421     if (state & SCARD_STATE_PRESENT) {
  422         reader->flags |= SC_READER_CARD_PRESENT;
  423 
  424         if (priv->reader_state.cbAtr > SC_MAX_ATR_SIZE)
  425             return SC_ERROR_INTERNAL;
  426 
  427         /* Some cards have a different cold (after a powerup) and warm (after a reset) ATR  */
  428         if (memcmp(priv->reader_state.rgbAtr, reader->atr.value, priv->reader_state.cbAtr) != 0) {
  429             reader->atr.len = priv->reader_state.cbAtr;
  430             memcpy(reader->atr.value, priv->reader_state.rgbAtr, reader->atr.len);
  431             APDU_LOG(reader->atr.value, (uint16_t) reader->atr.len);
  432         }
  433 
  434         /* Is the reader in use by some other application ? */
  435         if (state & SCARD_STATE_INUSE)
  436             reader->flags |= SC_READER_CARD_INUSE;
  437         if (state & SCARD_STATE_EXCLUSIVE)
  438             reader->flags |= SC_READER_CARD_EXCLUSIVE;
  439 
  440         if (old_flags & SC_READER_CARD_PRESENT) {
  441             /* Requires pcsc-lite 1.6.5+ to function properly */
  442             if ((state & 0xFFFF0000) != (prev_state & 0xFFFF0000)) {
  443                 reader->flags |= SC_READER_CARD_CHANGED;
  444             } else {
  445                 /* Check if the card handle is still valid. If the card changed,
  446                  * the handle will be invalid. */
  447                 DWORD readers_len = 0, cstate, prot, atr_len = SC_MAX_ATR_SIZE;
  448                 unsigned char atr[SC_MAX_ATR_SIZE];
  449                 rv = priv->gpriv->SCardStatus(priv->pcsc_card, NULL,
  450                         &readers_len, &cstate, &prot, atr, &atr_len);
  451                 if (rv == (LONG)SCARD_W_REMOVED_CARD || rv == (LONG)SCARD_E_INVALID_VALUE)
  452                     reader->flags |= SC_READER_CARD_CHANGED;
  453             }
  454         } else {
  455             reader->flags |= SC_READER_CARD_CHANGED;
  456         }
  457     } else {
  458         reader->flags &= ~SC_READER_CARD_PRESENT;
  459         if (old_flags & SC_READER_CARD_PRESENT)
  460             reader->flags |= SC_READER_CARD_CHANGED;
  461     }
  462     sc_log(reader->ctx, "card %s%s",
  463             reader->flags & SC_READER_CARD_PRESENT ? "present" : "absent",
  464             reader->flags & SC_READER_CARD_CHANGED ? ", changed": "");
  465 
  466     return SC_SUCCESS;
  467 }
  468 
  469 static int pcsc_detect_card_presence(sc_reader_t *reader)
  470 {
  471     int rv;
  472     LOG_FUNC_CALLED(reader->ctx);
  473 
  474     rv = refresh_attributes(reader);
  475     if (rv != SC_SUCCESS)
  476         LOG_FUNC_RETURN(reader->ctx, rv);
  477     LOG_FUNC_RETURN(reader->ctx, reader->flags);
  478 }
  479 
  480 static int check_forced_protocol(sc_reader_t *reader, DWORD *protocol)
  481 {
  482     scconf_block *atrblock = NULL;
  483     int forced = 0;
  484 
  485     atrblock = _sc_match_atr_block(reader->ctx, NULL, &reader->atr);
  486     if (atrblock != NULL) {
  487         const char *forcestr;
  488 
  489         forcestr = scconf_get_str(atrblock, "force_protocol", "unknown");
  490         if (!strcmp(forcestr, "t0")) {
  491             *protocol = SCARD_PROTOCOL_T0;
  492             forced = 1;
  493         } else if (!strcmp(forcestr, "t1")) {
  494             *protocol = SCARD_PROTOCOL_T1;
  495             forced = 1;
  496         } else if (!strcmp(forcestr, "raw")) {
  497             *protocol = SCARD_PROTOCOL_RAW;
  498             forced = 1;
  499         }
  500         if (forced)
  501             sc_log(reader->ctx, "force_protocol: %s", forcestr);
  502     }
  503 
  504     if (!forced && reader->uid.len) {
  505         /* We identify contactless cards by their UID. Communication
  506          * defined by ISO/IEC 14443 is identical to T=1. */
  507         *protocol = SCARD_PROTOCOL_T1;
  508         forced = 1;
  509     }
  510 
  511     if (!forced) {
  512         sc_card_t card;
  513         memset(&card, 0, sizeof card);
  514         card.ctx = reader->ctx;
  515         card.atr = reader->atr;
  516         if (0 <= _sc_match_atr(&card, sc_hsm_atrs, NULL)) {
  517             *protocol = SCARD_PROTOCOL_T1;
  518             forced = 1;
  519         }
  520     }
  521 
  522     return forced;
  523 }
  524 
  525 
  526 static int pcsc_reconnect(sc_reader_t * reader, DWORD action)
  527 {
  528     DWORD active_proto = opensc_proto_to_pcsc(reader->active_protocol),
  529           tmp, protocol = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1;
  530     LONG rv;
  531     struct pcsc_private_data *priv = reader->drv_data;
  532     int r;
  533 
  534     sc_log(reader->ctx, "Reconnecting to the card...");
  535 
  536     r = refresh_attributes(reader);
  537     if (r!= SC_SUCCESS)
  538         return r;
  539 
  540     if (!(reader->flags & SC_READER_CARD_PRESENT))
  541         return SC_ERROR_CARD_NOT_PRESENT;
  542 
  543     /* Check if we need a specific protocol. refresh_attributes above already sets the ATR */
  544     if (check_forced_protocol(reader, &tmp))
  545         protocol = tmp;
  546 
  547 #ifndef HAVE_PCSCLITE
  548     /* reconnect unlocks transaction everywhere but in PCSC-lite */
  549     priv->locked = 0;
  550 #endif
  551 
  552     rv = priv->gpriv->SCardReconnect(priv->pcsc_card,
  553             priv->gpriv->connect_exclusive ? SCARD_SHARE_EXCLUSIVE : SCARD_SHARE_SHARED,
  554             protocol, action, &active_proto);
  555 
  556     
  557     PCSC_TRACE(reader, "SCardReconnect returned", rv);
  558     if (rv != SCARD_S_SUCCESS) {
  559         PCSC_TRACE(reader, "SCardReconnect failed", rv);
  560         return pcsc_to_opensc_error(rv);
  561     }
  562 
  563     reader->active_protocol = pcsc_proto_to_opensc(active_proto);
  564     return pcsc_to_opensc_error(rv);
  565 }
  566 
  567 static void initialize_uid(sc_reader_t *reader)
  568 {
  569     if (reader->flags & SC_READER_ENABLE_ESCAPE) {
  570         sc_apdu_t apdu;
  571         /* though we only expect 10 bytes max, we want to set the Le to 0x00 to not
  572          * get 0x6282 as SW in case of a UID variant shorter than 10 bytes */
  573         u8 rbuf[256];
  574 
  575         memset(&apdu, 0, sizeof(apdu));
  576         apdu.cse = SC_APDU_CASE_2_SHORT;
  577         apdu.cla = 0xFF;
  578         apdu.ins = 0xCA;
  579         apdu.p1 = 0x00;
  580         apdu.p2 = 0x00;
  581         apdu.le = 0x00;
  582         apdu.resp = rbuf;
  583         apdu.resplen = sizeof rbuf;
  584 
  585         if (SC_SUCCESS == pcsc_transmit(reader, &apdu)
  586                 && apdu.sw1 == 0x90 && apdu.sw2 == 0x00
  587                 && 0 < apdu.resplen && apdu.resplen <= SC_MAX_UID_SIZE) {
  588             reader->uid.len = apdu.resplen;
  589             memcpy(reader->uid.value, apdu.resp, reader->uid.len);
  590             sc_log_hex(reader->ctx, "UID",
  591                     reader->uid.value, reader->uid.len);
  592         } else {
  593             sc_log(reader->ctx,  "unable to get UID");
  594         }
  595     }
  596 }
  597 
  598 static int pcsc_connect(sc_reader_t *reader)
  599 {
  600     DWORD active_proto, tmp, protocol = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1;
  601     SCARDHANDLE card_handle;
  602     LONG rv;
  603     struct pcsc_private_data *priv = reader->drv_data;
  604     int r;
  605 
  606     LOG_FUNC_CALLED(reader->ctx);
  607 
  608     r = refresh_attributes(reader);
  609     if (r != SC_SUCCESS)
  610         LOG_FUNC_RETURN(reader->ctx, r);
  611 
  612     if (!(reader->flags & SC_READER_CARD_PRESENT))
  613         LOG_FUNC_RETURN(reader->ctx, SC_ERROR_CARD_NOT_PRESENT);
  614 
  615 
  616     if (!priv->gpriv->cardmod) {
  617         rv = priv->gpriv->SCardConnect(priv->gpriv->pcsc_ctx, reader->name,
  618                 priv->gpriv->connect_exclusive ? SCARD_SHARE_EXCLUSIVE : SCARD_SHARE_SHARED,
  619                 protocol, &card_handle, &active_proto);
  620 #ifdef __APPLE__
  621         if (rv == (LONG)SCARD_E_SHARING_VIOLATION) {
  622             sleep(1); /* Try again to compete with Tokend probes */
  623             rv = priv->gpriv->SCardConnect(priv->gpriv->pcsc_ctx, reader->name,
  624                     priv->gpriv->connect_exclusive ? SCARD_SHARE_EXCLUSIVE : SCARD_SHARE_SHARED,
  625                     protocol, &card_handle, &active_proto);
  626         }
  627 #endif
  628         if (rv != SCARD_S_SUCCESS) {
  629             PCSC_TRACE(reader, "SCardConnect failed", rv);
  630             return pcsc_to_opensc_error(rv);
  631         }
  632 
  633         reader->active_protocol = pcsc_proto_to_opensc(active_proto);
  634         priv->pcsc_card = card_handle;
  635 
  636         initialize_uid(reader);
  637 
  638         sc_log(reader->ctx, "Initial protocol: %s", reader->active_protocol == SC_PROTO_T1 ? "T=1" : "T=0");
  639 
  640         /* Check if we need a specific protocol. refresh_attributes above already sets the ATR */
  641         if (check_forced_protocol(reader, &tmp)) {
  642             if (active_proto != tmp) {
  643                 sc_log(reader->ctx, "Reconnecting to force protocol");
  644                 r = pcsc_reconnect(reader, SCARD_UNPOWER_CARD);
  645                 if (r != SC_SUCCESS) {
  646                     sc_log(reader->ctx,
  647                             "pcsc_reconnect (to force protocol) failed (%d)",
  648                             r);
  649                     return r;
  650                 }
  651             }
  652             sc_log(reader->ctx, "Final protocol: %s", reader->active_protocol == SC_PROTO_T1 ? "T=1" : "T=0");
  653         }
  654     } else {
  655         initialize_uid(reader);
  656     }
  657 
  658     /* After connect reader is not locked yet */
  659     priv->locked = 0;
  660 
  661     return SC_SUCCESS;
  662 }
  663 
  664 static int pcsc_disconnect(sc_reader_t * reader)
  665 {
  666     struct pcsc_private_data *priv = reader->drv_data;
  667 
  668     if (!priv->gpriv->cardmod && !(reader->ctx->flags & SC_CTX_FLAG_TERMINATE)) {
  669         LONG rv = priv->gpriv->SCardDisconnect(priv->pcsc_card, priv->gpriv->disconnect_action);
  670         PCSC_TRACE(reader, "SCardDisconnect returned", rv);
  671     }
  672     reader->flags = 0;
  673     return SC_SUCCESS;
  674 }
  675 
  676 static int pcsc_lock(sc_reader_t *reader)
  677 {
  678     LONG rv;
  679     int r;
  680     struct pcsc_private_data *priv = reader->drv_data;
  681 
  682     if (priv->gpriv->cardmod)
  683         return SC_SUCCESS;
  684 
  685     LOG_FUNC_CALLED(reader->ctx);
  686 
  687     if (reader->ctx->flags & SC_CTX_FLAG_TERMINATE)
  688         return SC_ERROR_NOT_ALLOWED;
  689 
  690     rv = priv->gpriv->SCardBeginTransaction(priv->pcsc_card);
  691 
  692 
  693     if (rv != SCARD_S_SUCCESS)
  694         PCSC_TRACE(reader, "SCardBeginTransaction returned", rv);
  695 
  696     switch (rv) {
  697         case SCARD_E_INVALID_VALUE:
  698             /* This is returned in case of the same reader was re-attached */
  699         case SCARD_E_INVALID_HANDLE:
  700         case SCARD_E_READER_UNAVAILABLE:
  701             r = pcsc_connect(reader);
  702             if (r != SC_SUCCESS) {
  703                 sc_log(reader->ctx, "pcsc_connect failed (%d)",
  704                         r);
  705                 return r;
  706             }
  707             /* return failure so that upper layers will be notified and try to lock again */
  708             return SC_ERROR_READER_REATTACHED;
  709         case SCARD_W_RESET_CARD:
  710             /* try to reconnect if the card was reset by some other application */
  711             PCSC_TRACE(reader, "SCardBeginTransaction calling pcsc_reconnect", rv);
  712             r = pcsc_reconnect(reader, SCARD_LEAVE_CARD);
  713             if (r != SC_SUCCESS) {
  714                 sc_log(reader->ctx,
  715                         "pcsc_reconnect failed (%d)", r);
  716                 return r;
  717             }
  718             /* return failure so that upper layers will be notified and try to lock again */
  719             return SC_ERROR_CARD_RESET;
  720         case SCARD_S_SUCCESS:
  721             priv->locked = 1;
  722             return SC_SUCCESS;
  723         default:
  724             PCSC_TRACE(reader, "SCardBeginTransaction failed", rv);
  725             return pcsc_to_opensc_error(rv);
  726     }
  727 }
  728 
  729 static int pcsc_unlock(sc_reader_t *reader)
  730 {
  731     LONG rv;
  732     struct pcsc_private_data *priv = reader->drv_data;
  733 
  734     if (priv->gpriv->cardmod)
  735         return SC_SUCCESS;
  736 
  737     LOG_FUNC_CALLED(reader->ctx);
  738 
  739     if (reader->ctx->flags & SC_CTX_FLAG_TERMINATE)
  740         return SC_ERROR_NOT_ALLOWED;
  741 
  742     rv = priv->gpriv->SCardEndTransaction(priv->pcsc_card, priv->gpriv->transaction_end_action);
  743 
  744     priv->locked = 0;
  745     if (rv != SCARD_S_SUCCESS) {
  746         PCSC_TRACE(reader, "SCardEndTransaction failed", rv);
  747         return pcsc_to_opensc_error(rv);
  748     }
  749     return SC_SUCCESS;
  750 }
  751 
  752 static int pcsc_release(sc_reader_t *reader)
  753 {
  754     struct pcsc_private_data *priv = reader->drv_data;
  755 
  756     free(priv);
  757     return SC_SUCCESS;
  758 }
  759 
  760 static int pcsc_reset(sc_reader_t *reader, int do_cold_reset)
  761 {
  762     int r;
  763 #ifndef HAVE_PCSCLITE
  764     struct pcsc_private_data *priv = reader->drv_data;
  765     int old_locked = priv->locked;
  766 #endif
  767 
  768     r = pcsc_reconnect(reader, do_cold_reset ? SCARD_UNPOWER_CARD : SCARD_RESET_CARD);
  769     if(r != SC_SUCCESS)
  770         return r;
  771 
  772 #ifndef HAVE_PCSCLITE
  773     /* reconnect unlocks transaction everywhere but in PCSC-lite */
  774     if(old_locked)
  775         r = pcsc_lock(reader);
  776 #endif
  777 
  778     return r;
  779 }
  780 
  781 
  782 static int pcsc_cancel(sc_context_t *ctx)
  783 {
  784     LONG rv = SCARD_S_SUCCESS;
  785     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *)ctx->reader_drv_data;
  786 
  787     LOG_FUNC_CALLED(ctx);
  788 
  789     if (ctx->flags & SC_CTX_FLAG_TERMINATE)
  790         return SC_ERROR_NOT_ALLOWED;
  791 
  792 #ifndef _WIN32
  793     if (gpriv->pcsc_wait_ctx != (SCARDCONTEXT)-1) {
  794         rv = gpriv->SCardCancel(gpriv->pcsc_wait_ctx);
  795         if (rv == SCARD_S_SUCCESS) {
  796              /* Also close and clear the waiting context */
  797              rv = gpriv->SCardReleaseContext(gpriv->pcsc_wait_ctx);
  798              gpriv->pcsc_wait_ctx = -1;
  799         }
  800     }
  801 #else
  802     rv = gpriv->SCardCancel(gpriv->pcsc_ctx);
  803 #endif
  804     if (rv != SCARD_S_SUCCESS) {
  805         PCSC_LOG(ctx, "SCardCancel/SCardReleaseContext failed", rv);
  806         return pcsc_to_opensc_error(rv);
  807     }
  808     return SC_SUCCESS;
  809 }
  810 
  811 static struct sc_reader_operations pcsc_ops;
  812 
  813 static struct sc_reader_driver pcsc_drv = {
  814     "PC/SC reader",
  815     "pcsc",
  816     &pcsc_ops,
  817     NULL
  818 };
  819 
  820 static int pcsc_init(sc_context_t *ctx)
  821 {
  822     struct pcsc_global_private_data *gpriv;
  823     scconf_block *conf_block = NULL;
  824     int ret = SC_ERROR_INTERNAL;
  825 
  826 
  827     gpriv = calloc(1, sizeof(struct pcsc_global_private_data));
  828     if (gpriv == NULL) {
  829         ret = SC_ERROR_OUT_OF_MEMORY;
  830         goto out;
  831     }
  832 
  833     if(strcmp(ctx->app_name, "cardmod") == 0) {
  834         gpriv->cardmod = 1;
  835     }
  836 
  837     /* PC/SC Defaults */
  838     gpriv->provider_library = DEFAULT_PCSC_PROVIDER;
  839     gpriv->connect_exclusive = 0;
  840     gpriv->disconnect_action = SCARD_LEAVE_CARD;
  841     gpriv->transaction_end_action = SCARD_LEAVE_CARD;
  842     gpriv->reconnect_action = SCARD_LEAVE_CARD;
  843     gpriv->enable_pinpad = 1;
  844     gpriv->fixed_pinlength = 0;
  845     gpriv->enable_pace = 1;
  846     gpriv->pcsc_ctx = -1;
  847     gpriv->pcsc_wait_ctx = -1;
  848     /* max send/receive sizes: if exist in configuration these options overwrite
  849      *             the values by default and values declared by reader */
  850     gpriv->force_max_send_size = 0;
  851     gpriv->force_max_recv_size = 0;
  852 
  853     conf_block = sc_get_conf_block(ctx, "reader_driver", "pcsc", 1);
  854     if (conf_block) {
  855         gpriv->provider_library =
  856             scconf_get_str(conf_block, "provider_library", gpriv->provider_library);
  857         gpriv->connect_exclusive =
  858             scconf_get_bool(conf_block, "connect_exclusive", gpriv->connect_exclusive);
  859         gpriv->disconnect_action =
  860             pcsc_reset_action(scconf_get_str(conf_block, "disconnect_action", "leave"));
  861         gpriv->transaction_end_action =
  862             pcsc_reset_action(scconf_get_str(conf_block, "transaction_end_action", "leave"));
  863         gpriv->reconnect_action =
  864             pcsc_reset_action(scconf_get_str(conf_block, "reconnect_action", "leave"));
  865         gpriv->enable_pinpad = scconf_get_bool(conf_block, "enable_pinpad",
  866                 gpriv->enable_pinpad);
  867         gpriv->fixed_pinlength = scconf_get_bool(conf_block, "fixed_pinlength",
  868                 gpriv->fixed_pinlength);
  869         gpriv->enable_pace = scconf_get_bool(conf_block, "enable_pace",
  870                 gpriv->enable_pace);
  871         gpriv->force_max_send_size = scconf_get_int(conf_block,
  872                 "max_send_size", gpriv->force_max_send_size);
  873         gpriv->force_max_recv_size = scconf_get_int(conf_block,
  874                 "max_recv_size", gpriv->force_max_recv_size);
  875     }
  876 
  877     if (gpriv->cardmod) {
  878         /* for cardmod, don't manipulate winscard.dll or the OS's builtin
  879          * management of SCARDHANDLEs */
  880         gpriv->provider_library = DEFAULT_PCSC_PROVIDER;
  881         gpriv->connect_exclusive = 0;
  882         gpriv->disconnect_action = SCARD_LEAVE_CARD;
  883         gpriv->transaction_end_action = SCARD_LEAVE_CARD;
  884         gpriv->reconnect_action = SCARD_LEAVE_CARD;
  885     }
  886     sc_log(ctx,
  887             "PC/SC options: connect_exclusive=%d disconnect_action=%u transaction_end_action=%u"
  888             " reconnect_action=%u enable_pinpad=%d enable_pace=%d",
  889             gpriv->connect_exclusive,
  890             (unsigned int)gpriv->disconnect_action,
  891             (unsigned int)gpriv->transaction_end_action,
  892             (unsigned int)gpriv->reconnect_action, gpriv->enable_pinpad,
  893             gpriv->enable_pace);
  894 
  895     gpriv->dlhandle = sc_dlopen(gpriv->provider_library);
  896     if (gpriv->dlhandle == NULL) {
  897         ret = SC_ERROR_CANNOT_LOAD_MODULE;
  898         goto out;
  899     }
  900 
  901     gpriv->SCardEstablishContext = (SCardEstablishContext_t)sc_dlsym(gpriv->dlhandle, "SCardEstablishContext");
  902     gpriv->SCardReleaseContext = (SCardReleaseContext_t)sc_dlsym(gpriv->dlhandle, "SCardReleaseContext");
  903     gpriv->SCardConnect = (SCardConnect_t)sc_dlsym(gpriv->dlhandle, "SCardConnect");
  904     gpriv->SCardReconnect = (SCardReconnect_t)sc_dlsym(gpriv->dlhandle, "SCardReconnect");
  905     gpriv->SCardDisconnect = (SCardDisconnect_t)sc_dlsym(gpriv->dlhandle, "SCardDisconnect");
  906     gpriv->SCardBeginTransaction = (SCardBeginTransaction_t)sc_dlsym(gpriv->dlhandle, "SCardBeginTransaction");
  907     gpriv->SCardEndTransaction = (SCardEndTransaction_t)sc_dlsym(gpriv->dlhandle, "SCardEndTransaction");
  908     gpriv->SCardStatus = (SCardStatus_t)sc_dlsym(gpriv->dlhandle, "SCardStatus");
  909     gpriv->SCardGetStatusChange = (SCardGetStatusChange_t)sc_dlsym(gpriv->dlhandle, "SCardGetStatusChange");
  910     gpriv->SCardCancel = (SCardCancel_t)sc_dlsym(gpriv->dlhandle, "SCardCancel");
  911     gpriv->SCardTransmit = (SCardTransmit_t)sc_dlsym(gpriv->dlhandle, "SCardTransmit");
  912     gpriv->SCardListReaders = (SCardListReaders_t)sc_dlsym(gpriv->dlhandle, "SCardListReaders");
  913 
  914     if (gpriv->SCardConnect == NULL)
  915         gpriv->SCardConnect = (SCardConnect_t)sc_dlsym(gpriv->dlhandle, "SCardConnectA");
  916     if (gpriv->SCardStatus == NULL)
  917         gpriv->SCardStatus = (SCardStatus_t)sc_dlsym(gpriv->dlhandle, "SCardStatusA");
  918     if (gpriv->SCardGetStatusChange == NULL)
  919         gpriv->SCardGetStatusChange = (SCardGetStatusChange_t)sc_dlsym(gpriv->dlhandle, "SCardGetStatusChangeA");
  920     if (gpriv->SCardListReaders == NULL)
  921         gpriv->SCardListReaders = (SCardListReaders_t)sc_dlsym(gpriv->dlhandle, "SCardListReadersA");
  922 
  923     /* If we have SCardGetAttrib it is correct API */
  924     gpriv->SCardGetAttrib = (SCardGetAttrib_t)sc_dlsym(gpriv->dlhandle, "SCardGetAttrib");
  925     if (gpriv->SCardGetAttrib != NULL) {
  926 #ifdef __APPLE__
  927         gpriv->SCardControl = (SCardControl_t)sc_dlsym(gpriv->dlhandle, "SCardControl132");
  928 #endif
  929         if (gpriv->SCardControl == NULL) {
  930             gpriv->SCardControl = (SCardControl_t)sc_dlsym(gpriv->dlhandle, "SCardControl");
  931         }
  932     }
  933     else {
  934         gpriv->SCardControlOLD = (SCardControlOLD_t)sc_dlsym(gpriv->dlhandle, "SCardControl");
  935     }
  936 
  937     if (
  938         gpriv->SCardReleaseContext == NULL ||
  939         gpriv->SCardConnect == NULL ||
  940         gpriv->SCardReconnect == NULL ||
  941         gpriv->SCardDisconnect == NULL ||
  942         gpriv->SCardBeginTransaction == NULL ||
  943         gpriv->SCardEndTransaction == NULL ||
  944         gpriv->SCardStatus == NULL ||
  945         gpriv->SCardGetStatusChange == NULL ||
  946         gpriv->SCardCancel == NULL ||
  947         (gpriv->SCardControl == NULL && gpriv->SCardControlOLD == NULL) ||
  948         gpriv->SCardTransmit == NULL ||
  949         gpriv->SCardListReaders == NULL
  950     ) {
  951         ret = SC_ERROR_CANNOT_LOAD_MODULE;
  952         goto out;
  953     }
  954 
  955     ctx->reader_drv_data = gpriv;
  956     gpriv = NULL;
  957     ret = SC_SUCCESS;
  958 
  959 out:
  960     if (gpriv != NULL) {
  961         if (gpriv->dlhandle != NULL)
  962             sc_dlclose(gpriv->dlhandle);
  963         free(gpriv);
  964     }
  965 
  966     return ret;
  967 }
  968 
  969 
  970 static int pcsc_finish(sc_context_t *ctx)
  971 {
  972     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
  973 
  974     LOG_FUNC_CALLED(ctx);
  975 
  976     if (gpriv) {
  977         if (!gpriv->cardmod && gpriv->pcsc_ctx != (SCARDCONTEXT)-1 &&
  978                 !(ctx->flags & SC_CTX_FLAG_TERMINATE))
  979             gpriv->SCardReleaseContext(gpriv->pcsc_ctx);
  980         if (gpriv->dlhandle != NULL)
  981             sc_dlclose(gpriv->dlhandle);
  982         free(gpriv);
  983     }
  984 
  985     return SC_SUCCESS;
  986 }
  987 
  988 
  989 /**
  990  * @brief Detects reader's PACE capabilities
  991  *
  992  * @param reader reader to probe (\c pace_ioctl must be initialized)
  993  *
  994  * @return Bitmask of \c SC_READER_CAP_PACE_GENERIC, \c SC_READER_CAP_PACE_EID and \c * SC_READER_CAP_PACE_ESIGN logically OR'ed if supported
  995  */
  996 static unsigned long part10_detect_pace_capabilities(sc_reader_t *reader, SCARDHANDLE card_handle)
  997 {
  998     u8 pace_capabilities_buf[] = {
  999         PACE_FUNCTION_GetReaderPACECapabilities,/* idxFunction */
 1000         0, 0,                   /* lengthInputData */
 1001     };
 1002     u8 rbuf[7];
 1003     u8 *p = rbuf;
 1004     DWORD rcount = sizeof rbuf;
 1005     struct pcsc_private_data *priv;
 1006     unsigned long flags = 0;
 1007 
 1008     if (!reader)
 1009         goto err;
 1010     priv = reader->drv_data;
 1011     if (!priv)
 1012         goto err;
 1013 
 1014     if (priv->pace_ioctl && priv->gpriv) {
 1015         if (SCARD_S_SUCCESS != priv->gpriv->SCardControl(card_handle,
 1016                     priv->pace_ioctl, pace_capabilities_buf,
 1017                     sizeof pace_capabilities_buf, rbuf, sizeof(rbuf),
 1018                     &rcount)) {
 1019             sc_log(reader->ctx, "PC/SC v2 part 10 amd1: Get PACE properties failed!");
 1020             goto err;
 1021         }
 1022 
 1023     if (rcount != 7)
 1024         goto err;
 1025     /* Result */
 1026     if ((uint32_t) *p != 0)
 1027         goto err;
 1028     p += sizeof(uint32_t);
 1029     /* length_OutputData */
 1030     if ((uint16_t) *p != 1)
 1031         goto err;
 1032     p += sizeof(uint16_t);
 1033 
 1034     if (*p & PACE_CAPABILITY_eSign)
 1035         flags |= SC_READER_CAP_PACE_ESIGN;
 1036     if (*p & PACE_CAPABILITY_eID)
 1037         flags |= SC_READER_CAP_PACE_EID;
 1038     if (*p & PACE_CAPABILITY_generic)
 1039         flags |= SC_READER_CAP_PACE_GENERIC;
 1040     if (*p & PACE_CAPABILITY_DestroyPACEChannel)
 1041         flags |= SC_READER_CAP_PACE_DESTROY_CHANNEL;
 1042     }
 1043 
 1044 err:
 1045     return flags;
 1046 }
 1047 
 1048 static int
 1049 part10_find_property_by_tag(unsigned char buffer[], int length,
 1050     int tag_searched);
 1051 /**
 1052  * @brief Detects reader's maximum data size
 1053  *
 1054  * @param reader reader to probe (\c get_tlv_properties must be initialized)
 1055  *
 1056  * @return maximum data size
 1057  */
 1058 static size_t part10_detect_max_data(sc_reader_t *reader, SCARDHANDLE card_handle)
 1059 {
 1060     u8 rbuf[256];
 1061     DWORD rcount = sizeof rbuf;
 1062     struct pcsc_private_data *priv = NULL;
 1063     /* 0 means extended APDU not supported */
 1064     size_t max_data = 0;
 1065     int r;
 1066 
 1067     if (!reader)
 1068         goto err;
 1069     priv = reader->drv_data;
 1070     if (!priv)
 1071         goto err;
 1072 
 1073     if (priv->get_tlv_properties && priv->gpriv) {
 1074         if (SCARD_S_SUCCESS != priv->gpriv->SCardControl(card_handle,
 1075                 priv->get_tlv_properties, NULL, 0, rbuf, sizeof(rbuf), &rcount)) {
 1076             sc_log(reader->ctx, "PC/SC v2 part 10: Get TLV properties failed!");
 1077             goto err;
 1078         }
 1079 
 1080         r = part10_find_property_by_tag(rbuf, rcount,
 1081                 PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize);
 1082         sc_log(reader->ctx, "get dwMaxAPDUDataSize property returned %i", r);
 1083 
 1084         /* 256 < X <= 0x10000: short and extended APDU of up to X bytes of data */
 1085         if (r > 0x100 && r <= 0x10000)
 1086             max_data = r;
 1087     }
 1088 err:
 1089     return max_data;
 1090 }
 1091 
 1092 static int part10_get_vendor_product(struct sc_reader *reader,
 1093         SCARDHANDLE card_handle, int *id_vendor, int *id_product)
 1094 {
 1095     u8 rbuf[256];
 1096     DWORD rcount = sizeof rbuf;
 1097     struct pcsc_private_data *priv;
 1098     int this_vendor = -1, this_product = -1;
 1099 
 1100     if (!reader)
 1101         return SC_ERROR_INVALID_ARGUMENTS;
 1102     priv = reader->drv_data;
 1103     if (!priv)
 1104         return SC_ERROR_INVALID_ARGUMENTS;
 1105 
 1106     if (priv->get_tlv_properties && priv->gpriv) {
 1107         if (SCARD_S_SUCCESS != priv->gpriv->SCardControl(card_handle,
 1108                     priv->get_tlv_properties, NULL, 0, rbuf, sizeof(rbuf),
 1109                     &rcount)) {
 1110             sc_log(reader->ctx,
 1111                     "PC/SC v2 part 10: Get TLV properties failed!");
 1112             return SC_ERROR_TRANSMIT_FAILED;
 1113         }
 1114 
 1115         this_vendor = part10_find_property_by_tag(rbuf, rcount,
 1116                 PCSCv2_PART10_PROPERTY_wIdVendor);
 1117         this_product = part10_find_property_by_tag(rbuf, rcount,
 1118                 PCSCv2_PART10_PROPERTY_wIdProduct);
 1119     }
 1120 
 1121     sc_log(reader->ctx, "id_vendor=%04x id_product=%04x", this_vendor, this_product);
 1122 
 1123     if (id_vendor)
 1124         *id_vendor = this_vendor;
 1125     if (id_product)
 1126         *id_product = this_product;
 1127 
 1128     return SC_SUCCESS;
 1129 }
 1130 
 1131 static void detect_reader_features(sc_reader_t *reader, SCARDHANDLE card_handle) {
 1132     sc_context_t *ctx = reader->ctx;
 1133     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
 1134     struct pcsc_private_data *priv = reader->drv_data;
 1135     DWORD rcount, feature_len, i;
 1136     PCSC_TLV_STRUCTURE *pcsc_tlv;
 1137     union {
 1138         PCSC_TLV_STRUCTURE msg;
 1139         u8 buf[256];
 1140     } feature_buf;
 1141     union {
 1142 #ifdef PIN_PROPERTIES_v5
 1143         PIN_PROPERTIES_STRUCTURE_v5 capsv5;
 1144 #endif
 1145         PIN_PROPERTIES_STRUCTURE caps;
 1146         u8 buf[SC_MAX_APDU_BUFFER_SIZE];
 1147     } rbuf;
 1148     LONG rv;
 1149     const char *log_disabled = "but it's disabled in configuration file";
 1150     int id_vendor = 0, id_product = 0;
 1151 
 1152     LOG_FUNC_CALLED(ctx);
 1153 
 1154     sc_log(ctx, "Requesting reader features ... ");
 1155 
 1156     if (gpriv->SCardControl == NULL)
 1157         return;
 1158 
 1159     rv = gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, feature_buf.buf, sizeof(feature_buf.buf), &feature_len);
 1160     if (rv != SCARD_S_SUCCESS) {
 1161         PCSC_TRACE(reader, "SCardControl failed", rv);
 1162         return;
 1163     }
 1164 
 1165     if ((feature_len % sizeof(PCSC_TLV_STRUCTURE)) != 0) {
 1166         sc_log(ctx, "Inconsistent TLV from reader!");
 1167         return;
 1168     }
 1169 
 1170     /* get the number of elements instead of the complete size */
 1171     feature_len /= sizeof(PCSC_TLV_STRUCTURE);
 1172 
 1173     pcsc_tlv = &feature_buf.msg;
 1174     for (i = 0; i < feature_len; i++) {
 1175         sc_log(ctx, "Reader feature %02x found", pcsc_tlv[i].tag);
 1176         if (pcsc_tlv[i].tag == FEATURE_VERIFY_PIN_DIRECT) {
 1177             priv->verify_ioctl = ntohl(pcsc_tlv[i].value);
 1178         } else if (pcsc_tlv[i].tag == FEATURE_VERIFY_PIN_START) {
 1179             priv->verify_ioctl_start = ntohl(pcsc_tlv[i].value);
 1180         } else if (pcsc_tlv[i].tag == FEATURE_VERIFY_PIN_FINISH) {
 1181             priv->verify_ioctl_finish = ntohl(pcsc_tlv[i].value);
 1182         } else if (pcsc_tlv[i].tag == FEATURE_MODIFY_PIN_DIRECT) {
 1183             priv->modify_ioctl = ntohl(pcsc_tlv[i].value);
 1184         } else if (pcsc_tlv[i].tag == FEATURE_MODIFY_PIN_START) {
 1185             priv->modify_ioctl_start = ntohl(pcsc_tlv[i].value);
 1186         } else if (pcsc_tlv[i].tag == FEATURE_MODIFY_PIN_FINISH) {
 1187             priv->modify_ioctl_finish = ntohl(pcsc_tlv[i].value);
 1188         } else if (pcsc_tlv[i].tag == FEATURE_IFD_PIN_PROPERTIES) {
 1189             priv->pin_properties_ioctl = ntohl(pcsc_tlv[i].value);
 1190         } else if (pcsc_tlv[i].tag == FEATURE_GET_TLV_PROPERTIES)  {
 1191             priv->get_tlv_properties = ntohl(pcsc_tlv[i].value);
 1192         } else if (pcsc_tlv[i].tag == FEATURE_EXECUTE_PACE) {
 1193             priv->pace_ioctl = ntohl(pcsc_tlv[i].value);
 1194         } else {
 1195             sc_log(ctx, "Reader feature %02x is not supported", pcsc_tlv[i].tag);
 1196         }
 1197     }
 1198 
 1199     /* Set reader capabilities based on detected IOCTLs */
 1200     if (priv->verify_ioctl || (priv->verify_ioctl_start && priv->verify_ioctl_finish)) {
 1201         const char *log_text = "Reader supports pinpad PIN verification";
 1202         if (priv->gpriv->enable_pinpad) {
 1203             sc_log(ctx, "%s", log_text);
 1204             reader->capabilities |= SC_READER_CAP_PIN_PAD;
 1205         } else {
 1206             sc_log(ctx, "%s %s", log_text, log_disabled);
 1207         }
 1208     }
 1209 
 1210     if (priv->modify_ioctl || (priv->modify_ioctl_start && priv->modify_ioctl_finish)) {
 1211         const char *log_text = "Reader supports pinpad PIN modification";
 1212         if (priv->gpriv->enable_pinpad) {
 1213             sc_log(ctx, "%s", log_text);
 1214             reader->capabilities |= SC_READER_CAP_PIN_PAD;
 1215         } else {
 1216             sc_log(ctx, "%s %s", log_text, log_disabled);
 1217         }
 1218     }
 1219 
 1220     /* Some readers claim to have PinPAD support even if they have not */
 1221     if ((reader->capabilities & SC_READER_CAP_PIN_PAD) &&
 1222         part10_get_vendor_product(reader, card_handle, &id_vendor, &id_product) == SC_SUCCESS) {
 1223         /* HID Global OMNIKEY 3x21/6121 Smart Card Reader, fixed in libccid 1.4.29 (remove when last supported OS is using 1.4.29) */
 1224         if ((id_vendor == 0x076B && id_product == 0x3031) ||
 1225             (id_vendor == 0x076B && id_product == 0x6632)) {
 1226             sc_log(ctx, "%s is not pinpad reader, ignoring", reader->name);
 1227             reader->capabilities &= ~SC_READER_CAP_PIN_PAD;
 1228         }
 1229     }
 1230 
 1231     /* Detect display */
 1232     if (priv->pin_properties_ioctl) {
 1233         rcount = sizeof(rbuf.buf);
 1234         rv = gpriv->SCardControl(card_handle, priv->pin_properties_ioctl,
 1235             NULL, 0, rbuf.buf, sizeof(rbuf.buf), &rcount);
 1236         if (rv == SCARD_S_SUCCESS) {
 1237 #ifdef PIN_PROPERTIES_v5
 1238             if (rcount == sizeof(PIN_PROPERTIES_STRUCTURE_v5)) {
 1239                 PIN_PROPERTIES_STRUCTURE_v5 *caps = &rbuf.capsv5;
 1240                 if (caps->wLcdLayout > 0) {
 1241                     sc_log(ctx, "Reader has a display: %04X", caps->wLcdLayout);
 1242                     reader->capabilities |= SC_READER_CAP_DISPLAY;
 1243                 } else
 1244                     sc_log(ctx, "Reader does not have a display.");
 1245             }
 1246 #endif
 1247             if (rcount == sizeof(PIN_PROPERTIES_STRUCTURE)) {
 1248                 PIN_PROPERTIES_STRUCTURE *caps = &rbuf.caps;
 1249                 if (caps->wLcdLayout > 0) {
 1250                     sc_log(ctx, "Reader has a display: %04X", caps->wLcdLayout);
 1251                     reader->capabilities |= SC_READER_CAP_DISPLAY;
 1252                 }
 1253                 else   {
 1254                     sc_log(ctx, "Reader does not have a display.");
 1255                 }
 1256             }
 1257             else   {
 1258                 sc_log(ctx,
 1259                         "Returned PIN properties structure has bad length (%lu/%"SC_FORMAT_LEN_SIZE_T"u)",
 1260                         (unsigned long)rcount,
 1261                         sizeof(PIN_PROPERTIES_STRUCTURE));
 1262             }
 1263         }
 1264     }
 1265 
 1266     if (priv->pace_ioctl) {
 1267         const char *log_text = "Reader supports PACE";
 1268         if (priv->gpriv->enable_pace) {
 1269             reader->capabilities |= part10_detect_pace_capabilities(reader, card_handle);
 1270 
 1271             if (reader->capabilities & SC_READER_CAP_PACE_GENERIC)
 1272                 sc_log(ctx, "%s", log_text);
 1273         }
 1274         else {
 1275             sc_log(ctx, "%s %s", log_text, log_disabled);
 1276         }
 1277     }
 1278 
 1279     if (priv->get_tlv_properties) {
 1280         /* Try to set reader max_send_size and max_recv_size based on
 1281          * detected max_data */
 1282         int max_data = part10_detect_max_data(reader, card_handle);
 1283 
 1284         if (max_data > 0) {
 1285             sc_log(ctx, "Reader supports transceiving %d bytes of data",
 1286                     max_data);
 1287             if (!priv->gpriv->force_max_send_size)
 1288                 reader->max_send_size = max_data;
 1289             else
 1290                 sc_log(ctx, "Sending is limited to %"SC_FORMAT_LEN_SIZE_T"u bytes of data"
 1291                         " in configuration file", reader->max_send_size);
 1292             if (!priv->gpriv->force_max_recv_size)
 1293                 reader->max_recv_size = max_data;
 1294             else
 1295                 sc_log(ctx, "Receiving is limited to %"SC_FORMAT_LEN_SIZE_T"u bytes of data"
 1296                         " in configuration file", reader->max_recv_size);
 1297         } else {
 1298             sc_log(ctx, "Assuming that the reader supports transceiving "
 1299                     "short length APDUs only");
 1300         }
 1301 
 1302         /* debug the product and vendor ID of the reader */
 1303         part10_get_vendor_product(reader, card_handle, NULL, NULL);
 1304     }
 1305 
 1306     if(gpriv->SCardGetAttrib != NULL) {
 1307         rcount = sizeof(rbuf.buf);
 1308         if (gpriv->SCardGetAttrib(card_handle, SCARD_ATTR_VENDOR_NAME,
 1309                     rbuf.buf, &rcount) == SCARD_S_SUCCESS
 1310                 && rcount > 0) {
 1311             /* add NUL termination, just in case... */
 1312             rbuf.buf[(sizeof rbuf.buf)-1] = '\0';
 1313             reader->vendor = strdup((char *) rbuf.buf);
 1314         }
 1315 
 1316         rcount = sizeof i;
 1317         if(gpriv->SCardGetAttrib(card_handle, SCARD_ATTR_VENDOR_IFD_VERSION,
 1318                     (u8 *) &i, &rcount) == SCARD_S_SUCCESS
 1319                 && rcount == sizeof i) {
 1320             reader->version_major = (i >> 24) & 0xFF;
 1321             reader->version_minor = (i >> 16) & 0xFF;
 1322         }
 1323     }
 1324 }
 1325 
 1326 int pcsc_add_reader(sc_context_t *ctx,
 1327         char *reader_name, size_t reader_name_len,
 1328         sc_reader_t **out_reader)
 1329 {
 1330     int ret = SC_ERROR_INTERNAL;
 1331     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
 1332     struct pcsc_private_data *priv;
 1333     sc_reader_t *reader;
 1334 
 1335     sc_log(ctx, "Adding new PC/SC reader '%s'", reader_name);
 1336 
 1337     if ((reader = calloc(1, sizeof(sc_reader_t))) == NULL) {
 1338         ret = SC_ERROR_OUT_OF_MEMORY;
 1339         goto err1;
 1340     }
 1341     *out_reader = reader;
 1342     if ((priv = calloc(1, sizeof(struct pcsc_private_data))) == NULL) {
 1343         ret = SC_ERROR_OUT_OF_MEMORY;
 1344         goto err1;
 1345     }
 1346 
 1347     priv->gpriv = gpriv;
 1348 
 1349     reader->drv_data = priv;
 1350     reader->ops = &pcsc_ops;
 1351     reader->driver = &pcsc_drv;
 1352     if ((reader->name = strdup(reader_name)) == NULL) {
 1353         ret = SC_ERROR_OUT_OF_MEMORY;
 1354         goto err1;
 1355     }
 1356 
 1357     /* max send/receive sizes: with default values only short APDU supported */
 1358     reader->max_send_size = priv->gpriv->force_max_send_size ?
 1359         priv->gpriv->force_max_send_size :
 1360         SC_READER_SHORT_APDU_MAX_SEND_SIZE;
 1361     reader->max_recv_size = priv->gpriv->force_max_recv_size ?
 1362         priv->gpriv->force_max_recv_size :
 1363         SC_READER_SHORT_APDU_MAX_RECV_SIZE;
 1364 
 1365     ret = _sc_add_reader(ctx, reader);
 1366 
 1367     if (ret == SC_SUCCESS) {
 1368         refresh_attributes(reader);
 1369     }
 1370 
 1371 err1:
 1372     return ret;
 1373 }
 1374 
 1375 static int pcsc_detect_readers(sc_context_t *ctx)
 1376 {
 1377     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
 1378     DWORD active_proto, reader_buf_size = 0;
 1379     SCARDHANDLE card_handle;
 1380     LONG rv;
 1381     char *reader_buf = NULL, *reader_name;
 1382     const char *mszGroups = NULL;
 1383     int ret = SC_ERROR_INTERNAL;
 1384     size_t i;
 1385 
 1386     LOG_FUNC_CALLED(ctx);
 1387 
 1388     if (!gpriv) {
 1389         /* FIXME: this is not the correct error */
 1390         ret = SC_ERROR_NO_READERS_FOUND;
 1391         goto out;
 1392     }
 1393 
 1394     if (gpriv->cardmod) {
 1395         ret = SC_ERROR_NOT_ALLOWED;
 1396         goto out;
 1397     }
 1398 
 1399     sc_log(ctx, "Probing PC/SC readers");
 1400     gpriv->attached_reader = NULL;
 1401     gpriv->removed_reader = NULL;
 1402 
 1403     do {
 1404         if (gpriv->pcsc_ctx == (SCARDCONTEXT)-1) {
 1405             /*
 1406              * Cannot call SCardListReaders with -1
 1407              * context as in Windows ERROR_INVALID_HANDLE
 1408              * is returned instead of SCARD_E_INVALID_HANDLE
 1409              */
 1410             rv = SCARD_E_INVALID_HANDLE;
 1411         } else {
 1412             rv = gpriv->SCardListReaders(gpriv->pcsc_ctx, NULL,
 1413                     NULL, (LPDWORD) &reader_buf_size);
 1414 
 1415             /*
 1416              * All readers have disappeared, so mark them as
 1417              * such so we don't keep polling them over and over.
 1418              */
 1419             if (rv == (LONG)SCARD_E_NO_SERVICE
 1420 #ifdef SCARD_E_NO_READERS_AVAILABLE
 1421                     || rv == (LONG)SCARD_E_NO_READERS_AVAILABLE
 1422 #endif
 1423                     || rv == (LONG)SCARD_E_SERVICE_STOPPED) {
 1424                 for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
 1425                     sc_reader_t *reader = sc_ctx_get_reader(ctx, i);
 1426 
 1427                     if (!reader) {
 1428                         ret = SC_ERROR_INTERNAL;
 1429                         goto out;
 1430                     }
 1431 
 1432                     reader->flags |= SC_READER_REMOVED;
 1433                     gpriv->removed_reader = reader;
 1434                 }
 1435             }
 1436 
 1437             if ((rv == (LONG)SCARD_E_NO_SERVICE) || (rv == (LONG)SCARD_E_SERVICE_STOPPED)) {
 1438                 gpriv->SCardReleaseContext(gpriv->pcsc_ctx);
 1439                 gpriv->pcsc_ctx = -1;
 1440                 gpriv->pcsc_wait_ctx = -1;
 1441                 /* reconnecting below may may restart PC/SC service */
 1442                 rv = SCARD_E_INVALID_HANDLE;
 1443             }
 1444         }
 1445         if (rv != SCARD_S_SUCCESS) {
 1446             if (rv != (LONG)SCARD_E_INVALID_HANDLE) {
 1447                 PCSC_LOG(ctx, "SCardListReaders failed", rv);
 1448                 ret = pcsc_to_opensc_error(rv);
 1449                 goto out;
 1450             }
 1451 
 1452             sc_log(ctx, "Establish PC/SC context");
 1453 
 1454             rv = gpriv->SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &gpriv->pcsc_ctx);
 1455             if (rv != SCARD_S_SUCCESS) {
 1456                 gpriv->pcsc_ctx = -1;
 1457                 PCSC_LOG(ctx, "SCardEstablishContext failed", rv);
 1458                 ret = pcsc_to_opensc_error(rv);
 1459                 goto out;
 1460             }
 1461 
 1462             /* try to fetch the list of readers again */
 1463             rv = SCARD_E_INVALID_HANDLE;
 1464         }
 1465     } while (rv != SCARD_S_SUCCESS);
 1466 
 1467     /* The +2 below is to make sure we have zero terminators, in case we get invalid data */
 1468     reader_buf = calloc(reader_buf_size+2, sizeof(char));
 1469     if (!reader_buf) {
 1470         ret = SC_ERROR_OUT_OF_MEMORY;
 1471         goto out;
 1472     }
 1473     rv = gpriv->SCardListReaders(gpriv->pcsc_ctx, mszGroups, reader_buf,
 1474             (LPDWORD) &reader_buf_size);
 1475     if (rv != SCARD_S_SUCCESS) {
 1476         PCSC_LOG(ctx, "SCardListReaders failed", rv);
 1477         ret = pcsc_to_opensc_error(rv);
 1478         goto out;
 1479     }
 1480 
 1481     /* check if existing readers were returned in the list */
 1482     for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
 1483         sc_reader_t *reader = sc_ctx_get_reader(ctx, i);
 1484 
 1485         if (!reader) {
 1486             ret = SC_ERROR_INTERNAL;
 1487             goto out;
 1488         }
 1489 
 1490         for (reader_name = reader_buf; *reader_name != '\x0';
 1491                 reader_name += strlen(reader_name) + 1) {
 1492             if (!strcmp(reader->name, reader_name)) {
 1493                 if (reader->flags & SC_READER_REMOVED) {
 1494                     reader->flags &= ~SC_READER_REMOVED;
 1495                     gpriv->attached_reader = reader;
 1496                     refresh_attributes(reader);
 1497                 }
 1498                 break;
 1499             }
 1500         }
 1501 
 1502         if (*reader_name != '\x0') {
 1503             /* existing reader found; remove it from the list */
 1504             char *next_reader_name = reader_name + strlen(reader_name) + 1;
 1505 
 1506             memmove(reader_name, next_reader_name,
 1507                     (reader_buf + reader_buf_size) - next_reader_name);
 1508             reader_buf_size -= (next_reader_name - reader_name);
 1509         } else {
 1510             if (!(reader->flags & SC_READER_REMOVED)) {
 1511                 /* existing reader not found */
 1512                 reader->flags |= SC_READER_REMOVED;
 1513                 gpriv->removed_reader = reader;
 1514             }
 1515         }
 1516     }
 1517 
 1518     /* add readers remaining in the list */
 1519     for (reader_name = reader_buf; *reader_name != '\x0';
 1520             reader_name += strlen(reader_name) + 1) {
 1521         sc_reader_t *reader = NULL;
 1522         struct pcsc_private_data *priv = NULL;
 1523 
 1524         ret = pcsc_add_reader(ctx, reader_name, strlen(reader_name), &reader);
 1525         if (ret != SC_SUCCESS) {
 1526             _sc_delete_reader(ctx, reader);
 1527             continue;
 1528         }
 1529         gpriv->attached_reader = reader;
 1530 
 1531         /* check for pinpad support early, to allow opensc-tool -l display accurate information */
 1532         priv = reader->drv_data;
 1533         if (priv->reader_state.dwEventState & SCARD_STATE_EXCLUSIVE)
 1534             continue;
 1535 
 1536         rv = SCARD_E_SHARING_VIOLATION;
 1537         /* Use DIRECT mode only if there is no card in the reader */
 1538         if (!(reader->flags & SC_READER_CARD_PRESENT)) {
 1539 #ifndef _WIN32  /* Apple 10.5.7 and pcsc-lite previous to v1.5.5 do not support 0 as protocol identifier */
 1540             rv = gpriv->SCardConnect(gpriv->pcsc_ctx, reader->name, SCARD_SHARE_DIRECT, SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, &card_handle, &active_proto);
 1541 #else
 1542             rv = gpriv->SCardConnect(gpriv->pcsc_ctx, reader->name, SCARD_SHARE_DIRECT, 0, &card_handle, &active_proto);
 1543 #endif
 1544             PCSC_TRACE(reader, "SCardConnect(DIRECT)", rv);
 1545         }
 1546         if (rv == (LONG)SCARD_E_SHARING_VIOLATION) {
 1547             /* Assume that there is a card in the reader in shared mode if
 1548              * direct communication failed */
 1549             rv = gpriv->SCardConnect(gpriv->pcsc_ctx, reader->name,
 1550                     SCARD_SHARE_SHARED,
 1551                     SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, &card_handle,
 1552                     &active_proto);
 1553             PCSC_TRACE(reader, "SCardConnect(SHARED)", rv);
 1554             reader->active_protocol = pcsc_proto_to_opensc(active_proto);
 1555         }
 1556 
 1557         if (rv == SCARD_S_SUCCESS) {
 1558             detect_reader_features(reader, card_handle);
 1559             gpriv->SCardDisconnect(card_handle, SCARD_LEAVE_CARD);
 1560         }
 1561     }
 1562 
 1563     ret = SC_SUCCESS;
 1564 
 1565 out:
 1566     free(reader_buf);
 1567 
 1568     LOG_FUNC_RETURN(ctx, ret);
 1569 }
 1570 
 1571 
 1572 /* Wait for an event to occur.
 1573  */
 1574 static int pcsc_wait_for_event(sc_context_t *ctx, unsigned int event_mask, sc_reader_t **event_reader, unsigned int *event,
 1575         int timeout, void **reader_states)
 1576 {
 1577     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *)ctx->reader_drv_data;
 1578     LONG rv;
 1579     SCARD_READERSTATE *rgReaderStates;
 1580     size_t i;
 1581     unsigned int num_watch, count;
 1582     int r = SC_ERROR_INTERNAL, detect_readers = 0, detected_hotplug = 0;
 1583     DWORD dwtimeout;
 1584 
 1585     LOG_FUNC_CALLED(ctx);
 1586 
 1587     if (!event_reader && !event && reader_states)   {
 1588         sc_log(ctx, "free allocated reader states");
 1589         free(*reader_states);
 1590         *reader_states = NULL;
 1591         LOG_FUNC_RETURN(ctx, SC_SUCCESS);
 1592     }
 1593 
 1594     if (reader_states == NULL || *reader_states == NULL) {
 1595         rgReaderStates = calloc(sc_ctx_get_reader_count(ctx) + 2, sizeof(SCARD_READERSTATE));
 1596         if (!rgReaderStates)
 1597             LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
 1598 
 1599         /* Find out the current status */
 1600         num_watch = 0;
 1601         count = sc_ctx_get_reader_count(ctx);
 1602         for (i = 0; i < count; i++) {
 1603             sc_reader_t *reader = sc_ctx_get_reader(ctx, i);
 1604             if (reader->flags & SC_READER_REMOVED)
 1605                 continue;
 1606             struct pcsc_private_data *priv = reader->drv_data;
 1607             rgReaderStates[num_watch].szReader = reader->name;
 1608             if (priv->reader_state.szReader == NULL) {
 1609                 rgReaderStates[num_watch].dwCurrentState = SCARD_STATE_UNAWARE;
 1610             } else {
 1611                 rgReaderStates[num_watch].dwCurrentState = priv->reader_state.dwEventState;
 1612             }
 1613             rgReaderStates[num_watch].dwEventState = SCARD_STATE_UNAWARE;
 1614             num_watch++;
 1615         }
 1616         sc_log(ctx, "Trying to watch %d reader%s", num_watch, num_watch == 1 ? "" : "s");
 1617         if (event_mask & SC_EVENT_READER_ATTACHED) {
 1618 #ifdef __APPLE__
 1619             /* OS X 10.6.2 - 10.12.6 do not support PnP notification */
 1620             sc_log(ctx, "PnP notification not supported");
 1621             /* Always check on new readers as if a hotplug
 1622              * event was detected. This overwrites a
 1623              * SC_ERROR_EVENT_TIMEOUT if a new reader is
 1624              * detected with SC_SUCCESS. */
 1625             detect_readers = 1;
 1626             detected_hotplug = 1;
 1627 #else
 1628             rgReaderStates[num_watch].szReader = "\\\\?PnP?\\Notification";
 1629             rgReaderStates[num_watch].dwCurrentState = SCARD_STATE_UNAWARE;
 1630             rgReaderStates[num_watch].dwEventState = SCARD_STATE_UNAWARE;
 1631             num_watch++;
 1632             sc_log(ctx, "Trying to detect new readers");
 1633 #endif
 1634         }
 1635     }
 1636     else {
 1637         rgReaderStates = (SCARD_READERSTATE *)(*reader_states);
 1638         for (num_watch = 0; rgReaderStates[num_watch].szReader; num_watch++)
 1639             sc_log(ctx, "re-use reader '%s'", rgReaderStates[num_watch].szReader);
 1640     }
 1641 #ifndef _WIN32
 1642     /* Establish a new context, assuming that it is called from a different thread with pcsc-lite */
 1643     if (gpriv->pcsc_wait_ctx == (SCARDCONTEXT)-1) {
 1644         rv = gpriv->SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &gpriv->pcsc_wait_ctx);
 1645         if (rv != SCARD_S_SUCCESS) {
 1646             gpriv->pcsc_wait_ctx = -1;
 1647             PCSC_LOG(ctx, "SCardEstablishContext(wait) failed", rv);
 1648             r = pcsc_to_opensc_error(rv);
 1649             goto out;
 1650         }
 1651     }
 1652 #else
 1653     gpriv->pcsc_wait_ctx = gpriv->pcsc_ctx;
 1654 #endif
 1655     if (!event_reader || !event)
 1656     {
 1657         r = SC_ERROR_INTERNAL;
 1658         goto out;
 1659     }
 1660 
 1661     *event_reader = NULL;
 1662     *event = 0;
 1663 
 1664     if (num_watch == 0) {
 1665         sc_log(ctx, "No readers available to be watched");
 1666         r = SC_ERROR_NO_READERS_FOUND;
 1667         goto out;
 1668     }
 1669 
 1670     rv = gpriv->SCardGetStatusChange(gpriv->pcsc_wait_ctx, 0, rgReaderStates, num_watch);
 1671     if (rv != SCARD_S_SUCCESS) {
 1672         if (rv != (LONG)SCARD_E_TIMEOUT) {
 1673             PCSC_LOG(ctx, "SCardGetStatusChange(1) failed", rv);
 1674             r = pcsc_to_opensc_error(rv);
 1675             goto out;
 1676         }
 1677     }
 1678 
 1679     /* Wait for a status change
 1680      */
 1681     for( ; ; ) {
 1682         SCARD_READERSTATE *rsp;
 1683         sc_log(ctx, "Looping...");
 1684 
 1685         /* Scan the current state of all readers to see if they
 1686          * match any of the events we're polling for */
 1687         for (i = 0, rsp = rgReaderStates; i < num_watch; i++, rsp++) {
 1688             DWORD state, prev_state;
 1689             sc_log(ctx, "'%s' before=0x%08X now=0x%08X",
 1690                     rsp->szReader,
 1691                     (unsigned int)rsp->dwCurrentState,
 1692                     (unsigned int)rsp->dwEventState);
 1693             prev_state = rsp->dwCurrentState;
 1694             state = rsp->dwEventState;
 1695             rsp->dwCurrentState = rsp->dwEventState;
 1696             if (state & SCARD_STATE_CHANGED) {
 1697                 /* check for hotplug events  */
 1698                 if (!strcmp(rsp->szReader, "\\\\?PnP?\\Notification")) {
 1699                     sc_log(ctx, "detected hotplug event");
 1700                     /* Windows sends hotplug event on both, attaching and
 1701                      * detaching a reader. pcscd only sends it in case of
 1702                      * attaching a reader. We'll detect later in which case we
 1703                      * are. */
 1704                     detect_readers = 1;
 1705                     detected_hotplug = 1;
 1706 
 1707                     /* Windows wants us to manually reset the changed state */
 1708                     rsp->dwEventState &= ~SCARD_STATE_CHANGED;
 1709 
 1710                     /* By default, ignore a hotplug event as if a timeout
 1711                      * occurred, since it may be an unrequested removal or
 1712                      * false alarm. Just continue to loop and check at the end
 1713                      * of this function whether we need to return the attached
 1714                      * reader or not. */
 1715                     r = SC_ERROR_EVENT_TIMEOUT;
 1716                 } else {
 1717                     sc_reader_t *reader = sc_ctx_get_reader_by_name(ctx, rsp->szReader);
 1718 
 1719                     if ((state & SCARD_STATE_PRESENT) && !(prev_state & SCARD_STATE_PRESENT)) {
 1720                         sc_log(ctx, "card inserted event");
 1721                         *event |= SC_EVENT_CARD_INSERTED;
 1722                     }
 1723 
 1724                     if ((prev_state & SCARD_STATE_PRESENT) && !(state & SCARD_STATE_PRESENT)) {
 1725                         sc_log(ctx, "card removed event");
 1726                         *event |= SC_EVENT_CARD_REMOVED;
 1727                     }
 1728 
 1729                     if ((state & SCARD_STATE_UNKNOWN) && !(prev_state & SCARD_STATE_UNKNOWN)) {
 1730                         sc_log(ctx, "reader detached event");
 1731                         *event |= SC_EVENT_READER_DETACHED;
 1732                         detect_readers = 1;
 1733                     }
 1734 
 1735                     if ((state & SCARD_STATE_IGNORE) && !(prev_state & SCARD_STATE_IGNORE)) {
 1736                         sc_log(ctx, "reader detached event");
 1737                         *event |= SC_EVENT_READER_DETACHED;
 1738                         detect_readers = 1;
 1739                     }
 1740 
 1741                     if ((prev_state & SCARD_STATE_UNKNOWN) && !(state & SCARD_STATE_UNKNOWN)) {
 1742                         sc_log(ctx, "reader re-attached event");
 1743                         *event |= SC_EVENT_READER_ATTACHED;
 1744                         detect_readers = 1;
 1745                     }
 1746 
 1747                     if (*event & event_mask) {
 1748                         sc_log(ctx, "Matching event 0x%02X in reader %s", *event, rsp->szReader);
 1749                         *event_reader = reader;
 1750                         r = SC_SUCCESS;
 1751                         goto out;
 1752                     } else {
 1753                         *event = 0;
 1754                     }
 1755                 }
 1756             }
 1757         }
 1758 
 1759         /* if a reader was detected, we need to create a new list of readers */
 1760         if (detected_hotplug)
 1761             goto out;
 1762 
 1763         /* Set the timeout if caller wants to time out */
 1764         if (timeout == -1) {
 1765             dwtimeout = INFINITE;
 1766         }
 1767         else
 1768             dwtimeout = timeout;
 1769 
 1770         rv = gpriv->SCardGetStatusChange(gpriv->pcsc_wait_ctx, dwtimeout, rgReaderStates, num_watch);
 1771 
 1772         if (rv == (LONG)SCARD_E_CANCELLED) {
 1773             /* C_Finalize was called, events don't matter */
 1774             r = SC_ERROR_EVENT_TIMEOUT;
 1775             goto out;
 1776         }
 1777 
 1778         if (rv == (LONG)SCARD_E_TIMEOUT) {
 1779             r = SC_ERROR_EVENT_TIMEOUT;
 1780             goto out;
 1781         }
 1782 
 1783         if (rv != SCARD_S_SUCCESS) {
 1784             PCSC_LOG(ctx, "SCardGetStatusChange(2) failed", rv);
 1785             r = pcsc_to_opensc_error(rv);
 1786             goto out;
 1787         }
 1788     }
 1789 out:
 1790     /* in case of an error re-detect all readers */
 1791     if (r < 0 && r != SC_ERROR_EVENT_TIMEOUT)
 1792         detect_readers = 1;
 1793 
 1794     if (detect_readers) {
 1795         pcsc_detect_readers(ctx);
 1796     }
 1797 
 1798     if (detected_hotplug) {
 1799         if (gpriv->attached_reader) {
 1800             if (event_reader && event && !*event) {
 1801                 /* no other event has been detected, yet */
 1802                 *event_reader = gpriv->attached_reader;
 1803                 *event = SC_EVENT_READER_ATTACHED;
 1804                 r = SC_SUCCESS;
 1805             }
 1806             gpriv->attached_reader = NULL;
 1807         } else if (gpriv->removed_reader) {
 1808             /* Normally, we only check the hotplug event for attached readers.
 1809              * However, Windows also notifies on removal. Check, if the latter
 1810              * was requested by the caller. */
 1811             if (event_mask & SC_EVENT_READER_DETACHED
 1812                     && event_reader && event && !*event) {
 1813                 /* no other event has been detected, yet */
 1814                 *event_reader = gpriv->removed_reader;
 1815                 *event = SC_EVENT_READER_DETACHED;
 1816                 r = SC_SUCCESS;
 1817             }
 1818             gpriv->removed_reader = NULL;
 1819         } else {
 1820             /* false alarm, there was no reader attached or removed,
 1821              * avoid re-initialize the reader states by resetting detect_readers */
 1822             detect_readers = 0;
 1823         }
 1824     }
 1825 
 1826     if (detect_readers) {
 1827         free(rgReaderStates);
 1828         if (reader_states && *reader_states)
 1829             *reader_states = NULL;
 1830     } else {
 1831         if (!reader_states) {
 1832             free(rgReaderStates);
 1833         }
 1834         else if (*reader_states == NULL) {
 1835             sc_log(ctx, "return allocated reader states");
 1836             *reader_states = rgReaderStates;
 1837         }
 1838     }
 1839 
 1840     LOG_FUNC_RETURN(ctx, r);
 1841 }
 1842 
 1843 
 1844 
 1845 /*
 1846  * Pinpad support, based on PC/SC v2 Part 10 interface
 1847  * Similar to CCID in spirit.
 1848  */
 1849 
 1850 /* Local definitions */
 1851 #define SC_CCID_PIN_TIMEOUT 30
 1852 
 1853 /* CCID definitions */
 1854 #define SC_CCID_PIN_ENCODING_BIN   0x00
 1855 #define SC_CCID_PIN_ENCODING_BCD   0x01
 1856 #define SC_CCID_PIN_ENCODING_ASCII 0x02
 1857 
 1858 #define SC_CCID_PIN_UNITS_BYTES    0x80
 1859 
 1860 /* Build a PIN verification block + APDU */
 1861 static int part10_build_verify_pin_block(struct sc_reader *reader, u8 * buf, size_t * size, struct sc_pin_cmd_data *data)
 1862 {
 1863     int offset = 0, count = 0;
 1864     sc_apdu_t *apdu = data->apdu;
 1865     u8 tmp;
 1866     unsigned int tmp16;
 1867     unsigned int off;
 1868     PIN_VERIFY_STRUCTURE *pin_verify  = (PIN_VERIFY_STRUCTURE *)buf;
 1869 
 1870     /* PIN verification control message */
 1871     pin_verify->bTimerOut = SC_CCID_PIN_TIMEOUT;
 1872     pin_verify->bTimerOut2 = SC_CCID_PIN_TIMEOUT;
 1873 
 1874     /* bmFormatString */
 1875     tmp = 0x00;
 1876     if (data->pin1.encoding == SC_PIN_ENCODING_ASCII) {
 1877         tmp |= SC_CCID_PIN_ENCODING_ASCII;
 1878 
 1879         /* If the PIN offset is specified, use it, as long as it fits in 4 bits */
 1880         if (data->pin1.offset >= 5) {
 1881             off = data->pin1.offset - 5;
 1882             if (off > 15)
 1883                 return SC_ERROR_NOT_SUPPORTED;
 1884             tmp |= SC_CCID_PIN_UNITS_BYTES;
 1885             tmp |= off << 3;
 1886         }
 1887     } else if (data->pin1.encoding == SC_PIN_ENCODING_BCD) {
 1888         tmp |= SC_CCID_PIN_ENCODING_BCD;
 1889         tmp |= SC_CCID_PIN_UNITS_BYTES;
 1890     } else if (data->pin1.encoding == SC_PIN_ENCODING_GLP) {
 1891         /* see comment about GLP PINs in sec.c */
 1892         tmp |= SC_CCID_PIN_ENCODING_BCD;
 1893         tmp |= 0x08 << 3;
 1894     } else
 1895         return SC_ERROR_NOT_SUPPORTED;
 1896 
 1897     pin_verify->bmFormatString = tmp;
 1898 
 1899     /* bmPINBlockString */
 1900     tmp = 0x00;
 1901     if (data->pin1.encoding == SC_PIN_ENCODING_GLP) {
 1902         /* GLP PIN length is encoded in 4 bits and block size is always 8 bytes */
 1903         tmp |= 0x40 | 0x08;
 1904     } else if (data->pin1.encoding == SC_PIN_ENCODING_ASCII && data->flags & SC_PIN_CMD_NEED_PADDING) {
 1905         /*
 1906          * Use fixed-size PIN frame if pad length is below the limit. If not, leave the
 1907          * PIN frame size at 0, hoping for adaptive support by the reader (which includes
 1908          * both a variable-length frame when Lc is 0 or a pre-padded frame when Lc != 0).
 1909          */
 1910         if (data->pin1.pad_length <= 15)
 1911             tmp |= data->pin1.pad_length;
 1912     }
 1913     pin_verify->bmPINBlockString = tmp;
 1914 
 1915     /* bmPINLengthFormat */
 1916     tmp = 0x00;
 1917     if (data->pin1.encoding == SC_PIN_ENCODING_GLP) {
 1918         /* GLP PINs expect the effective PIN length from bit 4 */
 1919         tmp |= 0x04;
 1920     }
 1921     pin_verify->bmPINLengthFormat = tmp;    /* bmPINLengthFormat */
 1922 
 1923     if (!data->pin1.min_length || !data->pin1.max_length)
 1924         return SC_ERROR_INVALID_ARGUMENTS;
 1925 
 1926     tmp16 = (data->pin1.min_length << 8 ) + data->pin1.max_length;
 1927     pin_verify->wPINMaxExtraDigit = HOST_TO_CCID_16(tmp16); /* Min Max */
 1928 
 1929     pin_verify->bEntryValidationCondition = 0x02; /* Keypress only */
 1930 
 1931     if (reader->capabilities & SC_READER_CAP_DISPLAY)
 1932         pin_verify->bNumberMessage = 0xFF; /* Default message */
 1933     else
 1934         pin_verify->bNumberMessage = 0x00; /* No messages */
 1935 
 1936     /* Ignore language and T=1 parameters. */
 1937     pin_verify->wLangId = HOST_TO_CCID_16(0x0000);
 1938     pin_verify->bMsgIndex = 0x00;
 1939     pin_verify->bTeoPrologue[0] = 0x00;
 1940     pin_verify->bTeoPrologue[1] = 0x00;
 1941     pin_verify->bTeoPrologue[2] = 0x00;
 1942 
 1943     /* APDU itself */
 1944     LOG_TEST_RET(reader->ctx,
 1945             sc_apdu2bytes(reader->ctx, apdu,
 1946                 reader->active_protocol, pin_verify->abData,
 1947                 SC_MAX_APDU_BUFFER_SIZE),
 1948             "Could not encode PIN APDU");
 1949     offset += sc_apdu_get_length(apdu, reader->active_protocol);
 1950 
 1951     pin_verify->ulDataLength = HOST_TO_CCID_32(offset); /* APDU size */
 1952 
 1953     count = sizeof(PIN_VERIFY_STRUCTURE) + offset;
 1954     *size = count;
 1955     return SC_SUCCESS;
 1956 }
 1957 
 1958 
 1959 
 1960 /* Build a PIN modification block + APDU */
 1961 static int part10_build_modify_pin_block(struct sc_reader *reader, u8 * buf, size_t * size, struct sc_pin_cmd_data *data)
 1962 {
 1963     int offset = 0, count = 0;
 1964     sc_apdu_t *apdu = data->apdu;
 1965     u8 tmp;
 1966     unsigned int tmp16;
 1967     PIN_MODIFY_STRUCTURE *pin_modify  = (PIN_MODIFY_STRUCTURE *)buf;
 1968     struct sc_pin_cmd_pin *pin_ref =
 1969         data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ?
 1970         &data->pin2 : &data->pin1;
 1971 
 1972     /* PIN verification control message */
 1973     pin_modify->bTimerOut = SC_CCID_PIN_TIMEOUT;    /* bTimeOut */
 1974     pin_modify->bTimerOut2 = SC_CCID_PIN_TIMEOUT;   /* bTimeOut2 */
 1975 
 1976     /* bmFormatString */
 1977     tmp = 0x00;
 1978     if (pin_ref->encoding == SC_PIN_ENCODING_ASCII) {
 1979         tmp |= SC_CCID_PIN_ENCODING_ASCII;
 1980     } else if (pin_ref->encoding == SC_PIN_ENCODING_BCD) {
 1981         tmp |= SC_CCID_PIN_ENCODING_BCD;
 1982         tmp |= SC_CCID_PIN_UNITS_BYTES;
 1983     } else if (pin_ref->encoding == SC_PIN_ENCODING_GLP) {
 1984         /* see comment about GLP PINs in sec.c */
 1985         tmp |= SC_CCID_PIN_ENCODING_BCD;
 1986         tmp |= 0x08 << 3;
 1987     } else
 1988         return SC_ERROR_NOT_SUPPORTED;
 1989 
 1990     pin_modify->bmFormatString = tmp;   /* bmFormatString */
 1991 
 1992     /* bmPINBlockString */
 1993     tmp = 0x00;
 1994     if (pin_ref->encoding == SC_PIN_ENCODING_GLP) {
 1995         /* GLP PIN length is encoded in 4 bits and block size is always 8 bytes */
 1996         tmp |= 0x40 | 0x08;
 1997     } else if (pin_ref->encoding == SC_PIN_ENCODING_ASCII && pin_ref->pad_length) {
 1998         if (pin_ref->pad_length <= 15)
 1999             tmp |= pin_ref->pad_length;
 2000     }
 2001     pin_modify->bmPINBlockString = tmp; /* bmPINBlockString */
 2002 
 2003     /* bmPINLengthFormat */
 2004     tmp = 0x00;
 2005     if (pin_ref->encoding == SC_PIN_ENCODING_GLP) {
 2006         /* GLP PINs expect the effective PIN length from bit 4 */
 2007         tmp |= 0x04;
 2008     }
 2009     pin_modify->bmPINLengthFormat = tmp;    /* bmPINLengthFormat */
 2010 
 2011     /* Set offsets if available, otherwise default to 0 */
 2012     pin_modify->bInsertionOffsetOld = (data->pin1.offset >= 5 ? data->pin1.offset - 5 : 0);
 2013     pin_modify->bInsertionOffsetNew = (data->pin2.offset >= 5 ? data->pin2.offset - 5 : 0);
 2014 
 2015     if (!pin_ref->min_length || !pin_ref->max_length)
 2016         return SC_ERROR_INVALID_ARGUMENTS;
 2017 
 2018     tmp16 = (pin_ref->min_length << 8 ) + pin_ref->max_length;
 2019     pin_modify->wPINMaxExtraDigit = HOST_TO_CCID_16(tmp16); /* Min Max */
 2020 
 2021     /* bConfirmPIN flags
 2022      * 0x01: New Pin, Confirm Pin
 2023      * 0x03: Enter Old Pin, New Pin, Confirm Pin
 2024      */
 2025     pin_modify->bConfirmPIN = data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ? 0x01 : 0x03;
 2026     pin_modify->bEntryValidationCondition = 0x02;   /* bEntryValidationCondition, keypress only */
 2027 
 2028     /* bNumberMessage flags
 2029      * 0x02: Messages seen on Pinpad display: New Pin, Confirm Pin
 2030      * 0x03: Messages seen on Pinpad display: Enter Old Pin, New Pin, Confirm Pin
 2031      * Could be 0xFF too.
 2032      */
 2033     if (reader->capabilities & SC_READER_CAP_DISPLAY)
 2034         pin_modify->bNumberMessage = data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ? 0x02 : 0x03;
 2035     else
 2036         pin_modify->bNumberMessage = 0x00; /* No messages */
 2037 
 2038     /* Ignore language and T=1 parameters. */
 2039     pin_modify->wLangId = HOST_TO_CCID_16(0x0000);
 2040     pin_modify->bMsgIndex1 = (data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ? 0x01: 0x00); /* Default message indexes */
 2041     pin_modify->bMsgIndex2 = (data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ? 0x02: 0x01);
 2042     pin_modify->bMsgIndex3 = 0x02;
 2043     pin_modify->bTeoPrologue[0] = 0x00;
 2044     pin_modify->bTeoPrologue[1] = 0x00;
 2045     pin_modify->bTeoPrologue[2] = 0x00;
 2046 
 2047     /* APDU itself */
 2048     LOG_TEST_RET(reader->ctx,
 2049             sc_apdu2bytes(reader->ctx, apdu,
 2050                 reader->active_protocol, pin_modify->abData,
 2051                 SC_MAX_APDU_BUFFER_SIZE),
 2052             "Could not encode PIN APDU");
 2053     offset += sc_apdu_get_length(apdu, reader->active_protocol);
 2054 
 2055     pin_modify->ulDataLength = HOST_TO_CCID_32(offset); /* APDU size */
 2056 
 2057     count = sizeof(PIN_MODIFY_STRUCTURE) + offset;
 2058     *size = count;
 2059     return SC_SUCCESS;
 2060 }
 2061 
 2062 /* Find a given PCSC v2 part 10 property */
 2063 static int
 2064 part10_find_property_by_tag(unsigned char buffer[], int length,
 2065     int tag_searched)
 2066 {
 2067     unsigned char *p;
 2068     int found = 0, len, value = -1;
 2069 
 2070     p = buffer;
 2071     while (p-buffer < length)
 2072     {
 2073         if (*p++ == tag_searched)
 2074         {
 2075             found = 1;
 2076             break;
 2077         }
 2078 
 2079         /* go to next tag */
 2080         len = *p++;
 2081         p += len;
 2082     }
 2083 
 2084     if (found)
 2085     {
 2086         len = *p++;
 2087 
 2088         switch(len)
 2089         {
 2090             case 1:
 2091                 value = *p;
 2092                 break;
 2093             case 2:
 2094                 value = *p + (*(p+1)<<8);
 2095                 break;
 2096             case 4:
 2097                 value = *p + (*(p+1)<<8) + (*(p+2)<<16) + (*(p+3)<<24);
 2098                 break;
 2099             default:
 2100                 value = -1;
 2101         }
 2102     }
 2103 
 2104     return value;
 2105 } /* part10_find_property_by_tag */
 2106 
 2107 /* Make sure the pin min and max are supported by the reader
 2108  * and fix the values if needed */
 2109 static int
 2110 part10_check_pin_min_max(sc_reader_t *reader, struct sc_pin_cmd_data *data)
 2111 {
 2112     int r;
 2113     unsigned char buffer[256];
 2114     size_t length = sizeof buffer;
 2115     struct pcsc_private_data *priv = reader->drv_data;
 2116     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) reader->ctx->reader_drv_data;
 2117     struct sc_pin_cmd_pin *pin_ref =
 2118         data->flags & SC_PIN_CMD_IMPLICIT_CHANGE ?
 2119         &data->pin2 : &data->pin1;
 2120 
 2121     if (gpriv->fixed_pinlength != 0) {
 2122         pin_ref->min_length = gpriv->fixed_pinlength;
 2123         pin_ref->max_length = gpriv->fixed_pinlength;
 2124         return 0;
 2125     }
 2126 
 2127     if (!priv->get_tlv_properties)
 2128         return 0;
 2129 
 2130     r = pcsc_internal_transmit(reader, NULL, 0, buffer, &length,
 2131         priv->get_tlv_properties);
 2132     LOG_TEST_RET(reader->ctx, r,
 2133         "PC/SC v2 part 10: Get TLV properties failed!");
 2134 
 2135     /* minimum pin size */
 2136     r = part10_find_property_by_tag(buffer, length,
 2137         PCSCv2_PART10_PROPERTY_bMinPINSize);
 2138     if (r >= 0)
 2139     {
 2140         unsigned int value = r;
 2141 
 2142         if (pin_ref->min_length < value)
 2143             pin_ref->min_length = r;
 2144     }
 2145 
 2146     /* maximum pin size */
 2147     r = part10_find_property_by_tag(buffer, length,
 2148         PCSCv2_PART10_PROPERTY_bMaxPINSize);
 2149     if (r > 0)
 2150     {
 2151         unsigned int value = r;
 2152 
 2153         if (!pin_ref->max_length || pin_ref->max_length > value)
 2154             pin_ref->max_length = r;
 2155     }
 2156 
 2157     return 0;
 2158 }
 2159 
 2160 /* Do the PIN command */
 2161 static int
 2162 pcsc_pin_cmd(sc_reader_t *reader, struct sc_pin_cmd_data *data)
 2163 {
 2164     struct pcsc_private_data *priv = reader->drv_data;
 2165     u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
 2166     /* sbuf holds a pin verification/modification structure plus an APDU. */
 2167     u8 sbuf[sizeof(PIN_VERIFY_STRUCTURE)>sizeof(PIN_MODIFY_STRUCTURE)?
 2168         sizeof(PIN_VERIFY_STRUCTURE)+SC_MAX_APDU_BUFFER_SIZE:
 2169         sizeof(PIN_MODIFY_STRUCTURE)+SC_MAX_APDU_BUFFER_SIZE];
 2170     size_t rcount = sizeof(rbuf), scount = 0;
 2171     int r;
 2172     DWORD ioctl = 0;
 2173     sc_apdu_t *apdu;
 2174 
 2175     LOG_FUNC_CALLED(reader->ctx);
 2176 
 2177     if (reader->ctx->flags & SC_CTX_FLAG_TERMINATE)
 2178         return SC_ERROR_NOT_ALLOWED;
 2179 
 2180     if (priv->gpriv->SCardControl == NULL)
 2181         return SC_ERROR_NOT_SUPPORTED;
 2182 
 2183     /* The APDU must be provided by the card driver */
 2184     if (!data->apdu) {
 2185         sc_log(reader->ctx, "No APDU provided for PC/SC v2 pinpad verification!");
 2186         return SC_ERROR_NOT_SUPPORTED;
 2187     }
 2188 
 2189     apdu = data->apdu;
 2190     switch (data->cmd) {
 2191     case SC_PIN_CMD_VERIFY:
 2192         if (!(priv->verify_ioctl || (priv->verify_ioctl_start && priv->verify_ioctl_finish))) {
 2193             sc_log(reader->ctx, "Pinpad reader does not support verification!");
 2194             return SC_ERROR_NOT_SUPPORTED;
 2195         }
 2196         part10_check_pin_min_max(reader, data);
 2197         r = part10_build_verify_pin_block(reader, sbuf, &scount, data);
 2198         ioctl = priv->verify_ioctl ? priv->verify_ioctl : priv->verify_ioctl_start;
 2199         break;
 2200     case SC_PIN_CMD_CHANGE:
 2201     case SC_PIN_CMD_UNBLOCK:
 2202         if (!(priv->modify_ioctl || (priv->modify_ioctl_start && priv->modify_ioctl_finish))) {
 2203             sc_log(reader->ctx, "Pinpad reader does not support modification!");
 2204             return SC_ERROR_NOT_SUPPORTED;
 2205         }
 2206         part10_check_pin_min_max(reader, data);
 2207         r = part10_build_modify_pin_block(reader, sbuf, &scount, data);
 2208         ioctl = priv->modify_ioctl ? priv->modify_ioctl : priv->modify_ioctl_start;
 2209         break;
 2210     default:
 2211         sc_log(reader->ctx, "Unknown PIN command %d", data->cmd);
 2212         return SC_ERROR_NOT_SUPPORTED;
 2213     }
 2214 
 2215     /* If PIN block building failed, we fail too */
 2216     LOG_TEST_RET(reader->ctx, r, "PC/SC v2 pinpad block building failed!");
 2217     /* If not, debug it, just for fun */
 2218     sc_log_hex(reader->ctx, "PC/SC v2 pinpad block", sbuf, scount);
 2219 
 2220     r = pcsc_internal_transmit(reader, sbuf, scount, rbuf, &rcount, ioctl);
 2221 
 2222     LOG_TEST_RET(reader->ctx, r, "PC/SC v2 pinpad: block transmit failed!");
 2223     /* finish the call if it was a two-phase operation */
 2224     if ((ioctl == priv->verify_ioctl_start)
 2225             || (ioctl == priv->modify_ioctl_start)) {
 2226         if (rcount != 0) {
 2227             LOG_FUNC_RETURN(reader->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
 2228         }
 2229         ioctl = (ioctl == priv->verify_ioctl_start) ? priv->verify_ioctl_finish : priv->modify_ioctl_finish;
 2230 
 2231         rcount = sizeof(rbuf);
 2232         r = pcsc_internal_transmit(reader, sbuf, 0, rbuf, &rcount, ioctl);
 2233         LOG_TEST_RET(reader->ctx, r, "PC/SC v2 pinpad: finish operation failed!");
 2234     }
 2235 
 2236     /* We expect only two bytes of result data (SW1 and SW2) */
 2237     if (rcount != 2) {
 2238         LOG_FUNC_RETURN(reader->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
 2239     }
 2240 
 2241     /* Extract the SWs for the result APDU */
 2242     apdu->sw1 = (unsigned int) rbuf[rcount - 2];
 2243     apdu->sw2 = (unsigned int) rbuf[rcount - 1];
 2244 
 2245     r = SC_SUCCESS;
 2246     switch (((unsigned int) apdu->sw1 << 8) | apdu->sw2) {
 2247     case 0x6400: /* Input timed out */
 2248         r = SC_ERROR_KEYPAD_TIMEOUT;
 2249         break;
 2250     case 0x6401: /* Input cancelled */
 2251         r = SC_ERROR_KEYPAD_CANCELLED;
 2252         break;
 2253     case 0x6402: /* PINs don't match */
 2254         r = SC_ERROR_KEYPAD_PIN_MISMATCH;
 2255         break;
 2256     case 0x6403: /* Entered PIN is not in length limits */
 2257         r = SC_ERROR_INVALID_PIN_LENGTH; /* XXX: designed to be returned when PIN is in API call */
 2258         break;
 2259     case 0x6B80: /* Wrong data in the buffer, rejected by firmware */
 2260         r = SC_ERROR_READER;
 2261         break;
 2262     }
 2263 
 2264     LOG_TEST_RET(reader->ctx, r, "PIN command failed");
 2265 
 2266     /* PIN command completed, all is good */
 2267     return SC_SUCCESS;
 2268 }
 2269 
 2270 static int transform_pace_input(struct establish_pace_channel_input *pace_input,
 2271         u8 *sbuf, size_t *scount)
 2272 {
 2273     u8 *p = sbuf;
 2274     uint16_t lengthInputData, lengthCertificateDescription;
 2275     uint8_t lengthCHAT, lengthPIN;
 2276 
 2277     if (!pace_input || !sbuf || !scount)
 2278         return SC_ERROR_INVALID_ARGUMENTS;
 2279 
 2280     lengthInputData = 5 + pace_input->pin_length + pace_input->chat_length
 2281         + pace_input->certificate_description_length;
 2282 
 2283     if ((unsigned)(lengthInputData + 3) > *scount)
 2284         return SC_ERROR_OUT_OF_MEMORY;
 2285 
 2286     /* idxFunction */
 2287     *(p++) = PACE_FUNCTION_EstablishPACEChannel;
 2288 
 2289     /* lengthInputData */
 2290     memcpy(p, &lengthInputData, sizeof lengthInputData);
 2291     p += sizeof lengthInputData;
 2292 
 2293     *(p++) = pace_input->pin_id;
 2294 
 2295     /* length CHAT */
 2296     lengthCHAT = pace_input->chat_length;
 2297     *(p++) = lengthCHAT;
 2298     /* CHAT */
 2299     memcpy(p, pace_input->chat, lengthCHAT);
 2300     p += lengthCHAT;
 2301 
 2302     /* length PIN */
 2303     lengthPIN = pace_input->pin_length;
 2304     *(p++) = lengthPIN;
 2305 
 2306     /* PIN */
 2307     memcpy(p, pace_input->pin, lengthPIN);
 2308     p += lengthPIN;
 2309 
 2310     /* lengthCertificateDescription */
 2311     lengthCertificateDescription = pace_input->certificate_description_length;
 2312     memcpy(p, &lengthCertificateDescription,
 2313             sizeof lengthCertificateDescription);
 2314     p += sizeof lengthCertificateDescription;
 2315 
 2316     /* certificate description */
 2317     memcpy(p, pace_input->certificate_description,
 2318             lengthCertificateDescription);
 2319 
 2320     *scount = lengthInputData + 3;
 2321 
 2322     return SC_SUCCESS;
 2323 }
 2324 
 2325 static int transform_pace_output(u8 *rbuf, size_t rbuflen,
 2326         struct establish_pace_channel_output *pace_output)
 2327 {
 2328     size_t parsed = 0;
 2329 
 2330     uint8_t ui8;
 2331     uint16_t ui16;
 2332 
 2333     if (!rbuf || !pace_output)
 2334         return SC_ERROR_INVALID_ARGUMENTS;
 2335 
 2336     /* Result */
 2337     if (parsed+4 > rbuflen)
 2338         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2339     memcpy(&pace_output->result, &rbuf[parsed], 4);
 2340     parsed += 4;
 2341 
 2342     /* length_OutputData */
 2343     if (parsed+2 > rbuflen)
 2344         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2345     memcpy(&ui16, &rbuf[parsed], 2);
 2346     if ((size_t)ui16+6 != rbuflen)
 2347         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2348     parsed += 2;
 2349 
 2350     /* MSE:Set AT Statusbytes */
 2351     if (parsed+2 > rbuflen)
 2352         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2353     pace_output->mse_set_at_sw1 = rbuf[parsed+0];
 2354     pace_output->mse_set_at_sw2 = rbuf[parsed+1];
 2355     parsed += 2;
 2356 
 2357     /* length_CardAccess */
 2358     if (parsed+2 > rbuflen)
 2359         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2360     memcpy(&ui16, &rbuf[parsed], 2);
 2361     /* do not just yet copy ui16 to pace_output->ef_cardaccess_length */
 2362     parsed += 2;
 2363 
 2364     /* EF_CardAccess */
 2365     if (parsed+ui16 > rbuflen)
 2366         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2367     if (pace_output->ef_cardaccess) {
 2368         /* caller wants EF.CardAccess */
 2369         if (pace_output->ef_cardaccess_length < ui16)
 2370             return SC_ERROR_OUT_OF_MEMORY;
 2371 
 2372         /* now save ui16 to pace_output->ef_cardaccess_length */
 2373         pace_output->ef_cardaccess_length = ui16;
 2374         memcpy(pace_output->ef_cardaccess, &rbuf[parsed], ui16);
 2375     } else {
 2376         /* caller does not want EF.CardAccess */
 2377         pace_output->ef_cardaccess_length = 0;
 2378     }
 2379     parsed += ui16;
 2380 
 2381     if (parsed < rbuflen) {
 2382         /* The following elements are only present if the execution of PACE is
 2383          * to be followed by an execution of Terminal Authentication Version 2
 2384          * as defined in [TR-03110]. These data are needed to perform the
 2385          * Terminal Authentication. */
 2386 
 2387         /* length_CARcurr */
 2388         ui8 = rbuf[parsed];
 2389         /* do not just yet copy ui8 to pace_output->recent_car_length */
 2390         parsed += 1;
 2391 
 2392         /* CARcurr */
 2393         if (parsed+ui8 > rbuflen)
 2394             return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2395         if (pace_output->recent_car) {
 2396             /* caller wants most recent certificate authority reference */
 2397             if (pace_output->recent_car_length < ui8)
 2398                 return SC_ERROR_OUT_OF_MEMORY;
 2399             /* now save ui8 to pace_output->recent_car_length */
 2400             pace_output->recent_car_length = ui8;
 2401             memcpy(pace_output->recent_car, &rbuf[parsed], ui8);
 2402         } else {
 2403             /* caller does not want most recent certificate authority reference */
 2404             pace_output->recent_car_length = 0;
 2405         }
 2406         parsed += ui8;
 2407 
 2408         /* length_CARprev */
 2409         ui8 = rbuf[parsed];
 2410         /* do not just yet copy ui8 to pace_output->previous_car_length */
 2411         parsed += 1;
 2412 
 2413         /* length_CCARprev */
 2414         if (parsed+ui8 > rbuflen)
 2415             return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2416         if (pace_output->previous_car) {
 2417             /* caller wants previous certificate authority reference */
 2418             if (pace_output->previous_car_length < ui8)
 2419                 return SC_ERROR_OUT_OF_MEMORY;
 2420             /* now save ui8 to pace_output->previous_car_length */
 2421             pace_output->previous_car_length = ui8;
 2422             memcpy(pace_output->previous_car, &rbuf[parsed], ui8);
 2423         } else {
 2424             /* caller does not want previous certificate authority reference */
 2425             pace_output->previous_car_length = 0;
 2426         }
 2427         parsed += ui8;
 2428 
 2429         /* length_IDicc */
 2430         if (parsed+2 > rbuflen)
 2431             return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2432         memcpy(&ui16, &rbuf[parsed], 2);
 2433         /* do not just yet copy ui16 to pace_output->id_icc_length */
 2434         parsed += 2;
 2435 
 2436         /* IDicc */
 2437         if (parsed+ui16 > rbuflen)
 2438             return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2439         if (pace_output->id_icc) {
 2440             /* caller wants Ephemeral PACE public key of the IFD */
 2441             if (pace_output->id_icc_length < ui16)
 2442                 return SC_ERROR_OUT_OF_MEMORY;
 2443 
 2444             /* now save ui16 to pace_output->id_icc_length */
 2445             pace_output->id_icc_length = ui16;
 2446             memcpy(pace_output->id_icc, &rbuf[parsed], ui16);
 2447         } else {
 2448             /* caller does not want Ephemeral PACE public key of the IFD */
 2449             pace_output->id_icc_length = 0;
 2450         }
 2451         parsed += ui16;
 2452 
 2453         if (parsed < rbuflen)
 2454             return SC_ERROR_UNKNOWN_DATA_RECEIVED;
 2455     } else {
 2456         pace_output->recent_car_length = 0;
 2457         pace_output->previous_car_length = 0;
 2458         pace_output->id_icc_length = 0;
 2459     }
 2460 
 2461     return SC_SUCCESS;
 2462 }
 2463 
 2464 
 2465 static int
 2466 pcsc_perform_pace(struct sc_reader *reader, void *input_pace, void *output_pace)
 2467 {
 2468     struct establish_pace_channel_input *pace_input = (struct establish_pace_channel_input *) input_pace;
 2469     struct establish_pace_channel_output *pace_output = (struct establish_pace_channel_output *) output_pace;
 2470     struct pcsc_private_data *priv;
 2471     u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE], sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE];
 2472     size_t rcount = sizeof rbuf, scount = sizeof sbuf;
 2473 
 2474     if (!reader || !(reader->capabilities & SC_READER_CAP_PACE_GENERIC))
 2475         return SC_ERROR_INVALID_ARGUMENTS;
 2476 
 2477     priv = reader->drv_data;
 2478     if (!priv)
 2479         return SC_ERROR_INVALID_ARGUMENTS;
 2480 
 2481     LOG_TEST_RET(reader->ctx,
 2482             transform_pace_input(pace_input, sbuf, &scount),
 2483             "Creating EstabishPACEChannel input data");
 2484 
 2485     LOG_TEST_RET(reader->ctx,
 2486             pcsc_internal_transmit(reader, sbuf, scount, rbuf, &rcount,
 2487                 priv->pace_ioctl),
 2488             "Executing EstabishPACEChannel");
 2489 
 2490     LOG_TEST_RET(reader->ctx,
 2491             transform_pace_output(rbuf, rcount, pace_output),
 2492             "Parsing EstabishPACEChannel output data");
 2493 
 2494     return SC_SUCCESS;
 2495 }
 2496 
 2497 static void detect_protocol(sc_reader_t *reader, SCARDHANDLE card_handle)
 2498 {
 2499     DWORD readers_len = 0, state, prot, atr_len = SC_MAX_ATR_SIZE;
 2500     unsigned char atr[SC_MAX_ATR_SIZE];
 2501     struct pcsc_private_data *priv = reader->drv_data;
 2502     /* attempt to detect protocol in use T0/T1/RAW */
 2503     DWORD rv = priv->gpriv->SCardStatus(card_handle, NULL,
 2504             &readers_len, &state, &prot, atr, &atr_len);
 2505     if (rv != SCARD_S_SUCCESS) {
 2506         prot = SCARD_PROTOCOL_T0;
 2507     }
 2508     reader->active_protocol = pcsc_proto_to_opensc(prot);
 2509 }
 2510 
 2511 int pcsc_use_reader(sc_context_t *ctx, void * pcsc_context_handle, void * pcsc_card_handle)
 2512 {
 2513     SCARDHANDLE card_handle;
 2514     struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
 2515     char reader_name[128];
 2516     DWORD reader_name_size = sizeof(reader_name);
 2517     int ret = SC_ERROR_INTERNAL;
 2518 
 2519     LOG_FUNC_CALLED(ctx);
 2520 
 2521     if (!gpriv) {
 2522         ret = SC_ERROR_NO_READERS_FOUND;
 2523         goto out;
 2524     }
 2525 
 2526     if (!gpriv->cardmod) {
 2527         ret = SC_ERROR_INTERNAL;
 2528         goto out;
 2529     }
 2530 
 2531     /* Only minidriver calls this and only uses one reader */
 2532     /* if we already have a reader, update it */
 2533     if (sc_ctx_get_reader_count(ctx) > 0) {
 2534         sc_log(ctx, "Reusing the reader");
 2535         sc_reader_t *reader = list_get_at(&ctx->readers, 0);
 2536 
 2537         if (reader) {
 2538             struct pcsc_private_data *priv = reader->drv_data;
 2539             priv->pcsc_card =*(SCARDHANDLE *)pcsc_card_handle;
 2540             gpriv->pcsc_ctx = *(SCARDCONTEXT *)pcsc_context_handle;
 2541             ret = SC_SUCCESS;
 2542             goto out;
 2543         } else {
 2544             ret = SC_ERROR_INTERNAL;
 2545             goto out;
 2546         }
 2547     }
 2548 
 2549     sc_log(ctx, "Probing PC/SC reader");
 2550     gpriv->attached_reader = NULL;
 2551 
 2552     gpriv->pcsc_ctx = *(SCARDCONTEXT *)pcsc_context_handle;
 2553     card_handle =  *(SCARDHANDLE *)pcsc_card_handle;
 2554 
 2555     if(SCARD_S_SUCCESS == gpriv->SCardGetAttrib(card_handle,
 2556                 SCARD_ATTR_DEVICE_SYSTEM_NAME_A, (LPBYTE)
 2557                 reader_name, &reader_name_size)) {
 2558         sc_reader_t *reader = NULL;
 2559 
 2560         ret = pcsc_add_reader(ctx, reader_name, reader_name_size, &reader);
 2561         if (ret == SC_SUCCESS) {
 2562             struct pcsc_private_data *priv = reader->drv_data;
 2563             priv->pcsc_card = card_handle;
 2564             detect_protocol(reader, card_handle);
 2565             detect_reader_features(reader, card_handle);
 2566             gpriv->attached_reader = reader;
 2567         } else {
 2568             _sc_delete_reader(ctx, reader);
 2569         }
 2570     }
 2571 
 2572 out:
 2573     LOG_FUNC_RETURN(ctx, ret);
 2574 }
 2575 
 2576 struct sc_reader_driver * sc_get_pcsc_driver(void)
 2577 {
 2578     pcsc_ops.init = pcsc_init;
 2579     pcsc_ops.finish = pcsc_finish;
 2580     pcsc_ops.detect_readers = pcsc_detect_readers;
 2581     pcsc_ops.transmit = pcsc_transmit;
 2582     pcsc_ops.detect_card_presence = pcsc_detect_card_presence;
 2583     pcsc_ops.lock = pcsc_lock;
 2584     pcsc_ops.unlock = pcsc_unlock;
 2585     pcsc_ops.release = pcsc_release;
 2586     pcsc_ops.connect = pcsc_connect;
 2587     pcsc_ops.disconnect = pcsc_disconnect;
 2588     pcsc_ops.perform_verify = pcsc_pin_cmd;
 2589     pcsc_ops.wait_for_event = pcsc_wait_for_event;
 2590     pcsc_ops.cancel = pcsc_cancel;
 2591     pcsc_ops.reset = pcsc_reset;
 2592     pcsc_ops.use_reader = pcsc_use_reader;
 2593     pcsc_ops.perform_pace = pcsc_perform_pace;
 2594 
 2595     return &pcsc_drv;
 2596 }
 2597 
 2598 #endif   /* ENABLE_PCSC */