From e95bfeda5e72765f55f4cb433ffcf716f6562866 Mon Sep 17 00:00:00 2001 From: Jihoon Jung Date: Tue, 22 Jun 2021 09:24:56 +0900 Subject: [PATCH] Initial commit Change-Id: I6a33bff0d63dfeb507c41c60856ddf910aaaaba6 Signed-off-by: Jihoon Jung --- AUTHOR | 1 + CMakeLists.txt | 53 ++++ LICENSE.APLv2 | 206 +++++++++++++++ NOTICE | 3 + USBTerminal.cpp | 510 ++++++++++++++++++++++++++++++++++++ include/USBTerminal.h | 91 +++++++ packaging/smartcard-plugin-usb.spec | 40 +++ smartcard-plugin-usb.manifest | 6 + 8 files changed, 910 insertions(+) create mode 100644 AUTHOR create mode 100644 CMakeLists.txt create mode 100644 LICENSE.APLv2 create mode 100644 NOTICE create mode 100755 USBTerminal.cpp create mode 100644 include/USBTerminal.h create mode 100755 packaging/smartcard-plugin-usb.spec create mode 100644 smartcard-plugin-usb.manifest diff --git a/AUTHOR b/AUTHOR new file mode 100644 index 0000000..d8dcd77 --- /dev/null +++ b/AUTHOR @@ -0,0 +1 @@ +Jihoon Jung diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c322982 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,53 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +PROJECT(smartcard-plugin-usb CXX) + +SET(CMAKE_VERBOSE_MAKEFILE OFF) + +SET(VERSION_MAJOR 1) +SET(VERSION ${VERSION_MAJOR}.0.0) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) + +AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} SRCS) + +INCLUDE(FindPkgConfig) +pkg_check_modules(pkgs_common REQUIRED dlog smartcard-service-common libpcsclite) + +FOREACH(flag ${pkgs_common_CFLAGS}) + SET(EXTRA_CXXFLAGS "${EXTRA_CXXFLAGS} ${flag}") +ENDFOREACH(flag) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CXXFLAGS} -finstrument-functions -std=c++0x") +#SET(CMAKE_C_FLAGS_DEBUG "-O0 -g") +#SET(CMAKE_C_FLAGS_RELEASE "-O2") + +FIND_PROGRAM(UNAME NAMES uname) +EXEC_PROGRAM("${UNAME}" ARGS "-m" OUTPUT_VARIABLE "ARCH") +IF("${ARCH}" STREQUAL "arm") + ADD_DEFINITIONS("-DTARGET") + MESSAGE("add -DTARGET") +ENDIF("${ARCH}" STREQUAL "arm") + +MESSAGE("CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}") + +MESSAGE("CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}") +ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"") +ADD_DEFINITIONS("-DSLP_DEBUG") + +ADD_DEFINITIONS("-DLOG_TAG=\"SMARTCARD_PLUGIN_USB\"") + +SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed") + +ADD_LIBRARY(${PROJECT_NAME} SHARED ${SRCS}) + +#SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES SOVERSION ${VERSION_MAJOR}) +#SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES VERSION ${VERSION}) + +TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${pkgs_common_LDFLAGS}) + +IF (TIZEN_ARCH_64) + INSTALL(TARGETS ${PROJECT_NAME} DESTINATION lib64/se) +ELSE (TIZEN_ARCH_64) + INSTALL(TARGETS ${PROJECT_NAME} DESTINATION lib/se) +ENDIF(TIZEN_ARCH_64) + diff --git a/LICENSE.APLv2 b/LICENSE.APLv2 new file mode 100644 index 0000000..9728e1d --- /dev/null +++ b/LICENSE.APLv2 @@ -0,0 +1,206 @@ +Copyright (c) 2000 - 2021 Samsung Electronics Co., Ltd. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..0e0f016 --- /dev/null +++ b/NOTICE @@ -0,0 +1,3 @@ +Copyright (c) Samsung Electronics Co., Ltd. All rights reserved. +Except as noted, this software is licensed under Apache License, Version 2. +Please, see the LICENSE.APLv2 file for Apache License terms and conditions. diff --git a/USBTerminal.cpp b/USBTerminal.cpp new file mode 100755 index 0000000..ec29113 --- /dev/null +++ b/USBTerminal.cpp @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2021 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "smartcard-types.h" +#include "Debug.h" +#include "TerminalInterface.h" +#include "USBTerminal.h" + +#ifndef EXPORT_API +#define EXPORT_API __attribute__((visibility("default"))) +#endif + +typedef struct _callback_param_t +{ + void *callback; + void *param; +} +callback_param_t; + +using namespace smartcard_service_api; + +static const char *se_name = "USB0"; + +void __attribute__ ((constructor)) lib_init() +{ +} + +void __attribute__ ((destructor)) lib_fini() +{ +} + +/* below three functions must be implemented */ +extern "C" EXPORT_API const char *get_name() +{ + return se_name; +} + +extern "C" EXPORT_API void *create_instance() +{ + return (void *)USBTerminal::getInstance(); +} + +extern "C" EXPORT_API void destroy_instance(void *instance) +{ + USBTerminal *inst = (USBTerminal *)instance; + if (inst == USBTerminal::getInstance()) + { + inst->finalize(); + } + else + { + _ERR("instance is invalid : getInstance [%p], instance [%p]", + USBTerminal::getInstance(), instance); + } +} + +namespace smartcard_service_api +{ + USBTerminal::USBTerminal() : Terminal() + { + name = (char *)se_name; + cardConnected = false; + readerConnected = false; + readerStates[0].szReader = "\\\\?PnP?\\Notification"; // name of the card reader to monitor + readerStates[0].dwCurrentState = SCARD_STATE_UNAWARE; + readerStates[0].dwEventState = SCARD_STATE_UNKNOWN; + + initialize(); + } + + USBTerminal::~USBTerminal() + { + finalize(); + } + + USBTerminal *USBTerminal::getInstance() + { + static USBTerminal instance; + + return &instance; + } + + bool USBTerminal::initialize() + { + _BEGIN(); + + if (initialized == false) + { + LONG rv = SCARD_S_SUCCESS; + LPSTR readerName = NULL; + DWORD readerLen; + + rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &mainContext); + if (rv != SCARD_S_SUCCESS) + { + _ERR("SCardEstablishContext failed : %s", pcsc_stringify_error(rv)); + return false; + } + + + readerLen = SCARD_AUTOALLOCATE; + rv = SCardListReaders(mainContext, NULL, (LPSTR)&readerName, &readerLen); + if (rv == SCARD_S_SUCCESS) + { + _INFO("Reader Connected : %s", readerName); + readerStates[1].szReader = readerName; + readerStates[1].dwCurrentState = SCARD_STATE_UNAWARE; + readerStates[1].dwEventState = SCARD_STATE_UNKNOWN; + + readerConnected = true; + } + + monitorEventsThreadId = pthread_create(&monitorEventsThread, NULL, USBTerminal::monitorEvents, NULL); + + if (monitorEventsThreadId >= 0) + { + initialized = true; + } + else + { + _ERR("initialize failed"); + } + } + + _END(); + + return initialized; + } + + void USBTerminal::finalize() + { + _BEGIN(); + + if (isInitialized()) + { + initialized = false; + SCardCancel(monitorEventsThreadContext); + pthread_join(monitorEventsThread, NULL); + + if (readerStates[1].szReader != NULL) + free((void *)readerStates[1].szReader); + } + + _END(); + } + + bool USBTerminal::open() + { + _BEGIN(); + + _INFO("Nothing to do for open operation"); + + _END(); + + return true; + } + + void USBTerminal::close() + { + _BEGIN(); + + _INFO("Nothing to do for close operation"); + + _END(); + } + + int USBTerminal::transmitSync(const ByteArray &command, + ByteArray &response) + { + int result = SCARD_ERROR_OK; + + _BEGIN(); + + if (cardConnected == true) + { + if (command.size() > 0) + { + LONG rv = SCARD_S_SUCCESS; + const uint8_t *send = command.getBuffer(); + unsigned int send_len = command.size(); + uint8_t resp[MAX_BUFFER_SIZE] = {0,}; + uint32_t resp_len = MAX_BUFFER_SIZE; + SCARD_IO_REQUEST pioRecvPci; + + _INFO("Sending: %s", command.toString().c_str()); + + rv = SCardTransmit(cardHandle, activeProtocol, send, send_len, + &pioRecvPci, resp, (LPDWORD)&resp_len); + if (rv == SCARD_S_SUCCESS) + { + response.assign(resp, resp_len); + _INFO("Received: %s", response.toString().c_str()); + } + else + { + _ERR("SCardTransmit failed, [%s]", pcsc_stringify_error(rv)); + + result = SCARD_ERROR_IO_FAILED; + } + } + else + { + _ERR("apdu is empty"); + + result = SCARD_ERROR_ILLEGAL_PARAM; + } + } + else + { + _ERR("Card is not connected"); + + result = SCARD_ERROR_SE_NOT_INITIALIZED; + } + + _END(); + + return result; + } + + int USBTerminal::getATRSync(ByteArray &atr) + { + int result = SCARD_ERROR_OK; + + _BEGIN(); + + if (cardConnected == true) + { + atr = currentAtr; + } + else + { + _ERR("Card is not connected"); + + result = SCARD_ERROR_SE_NOT_INITIALIZED; + } + + _END(); + + return result; + } + + int USBTerminal::transmit(const ByteArray &command, terminalTransmitCallback callback, void *userData) + { + _INFO("transmit Async function is not supported"); + + return SCARD_ERROR_NOT_SUPPORTED; + } + + int USBTerminal::getATR(terminalGetATRCallback callback, void *userData) + { + _INFO("Get ATR Async function is not supported"); + + return SCARD_ERROR_NOT_SUPPORTED; + } + + bool USBTerminal::isSecureElementPresence() const + { + _BEGIN(); + + _INFO("isReaderConnected : %d", isReaderConnected()); + + _END(); + + return isReaderConnected(); + } + + gboolean USBTerminal::cardConnect(gpointer user_data) + { + _BEGIN(); + + LONG rv; + USBTerminal *mTerminal = USBTerminal::getInstance(); + SCARDHANDLE hCard; + char pbReader[MAX_READERNAME] = ""; + BYTE pbAtr[MAX_ATR_SIZE] = ""; + DWORD dwActiveProtocol, dwReaderLen, dwState, dwProt, dwAtrLen; + pthread_mutex_t *eventMutex = (pthread_mutex_t *)user_data; + const char *readerName = mTerminal->readerStates[1].szReader; + + if (eventMutex == NULL) + { + _INFO("eventMutex is NULL"); + return false; + } + + pthread_mutex_lock(eventMutex); + + if (mTerminal->isReaderConnected() != true || readerName == NULL) + { + _INFO("Reader is not connected"); + pthread_mutex_unlock(eventMutex); + return false; + } + + + dwActiveProtocol = -1; + rv = SCardConnect(mTerminal->getMainContext(), readerName, SCARD_SHARE_SHARED, + SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &hCard, &dwActiveProtocol); + if (rv != SCARD_S_SUCCESS) + { + _INFO("SCardConnect failed : %s", pcsc_stringify_error(rv)); + pthread_mutex_unlock(eventMutex); + return false; + } + + _INFO("Card Inserted"); + mTerminal->setCardConnected(true); + mTerminal->setCardHandle(hCard); + + _INFO(" Protocol: %ld\n", dwActiveProtocol); + switch(dwActiveProtocol) + { + case SCARD_PROTOCOL_T0: + mTerminal->setActiveProtocol(SCARD_PCI_T0); + break; + case SCARD_PROTOCOL_T1: + mTerminal->setActiveProtocol(SCARD_PCI_T1); + break; + default: + _INFO("Unknown protocol. set default protocol"); + mTerminal->setActiveProtocol(SCARD_PCI_T1); + } + + dwAtrLen = sizeof(pbAtr); + dwReaderLen = sizeof(pbReader); + rv = SCardStatus(hCard, pbReader, &dwReaderLen, &dwState, &dwProt, + pbAtr, &dwAtrLen); + if (rv != SCARD_S_SUCCESS) + { + _INFO("SCardStatus failed : %s", pcsc_stringify_error(rv)); + pthread_mutex_unlock(eventMutex); + return false; + } + + _INFO(" Reader: %s (length %ld bytes)", pbReader, dwReaderLen); + _INFO(" State: 0x%lX", dwState); + _INFO(" Prot: %ld", dwProt); + _INFO(" ATR (length %ld bytes):", dwAtrLen); + + ByteArray atrArray(pbAtr, dwAtrLen); + _INFO(" %s", atrArray.toString().c_str()); + mTerminal->setCurrentAtr(atrArray); + + pthread_mutex_unlock(eventMutex); + + if (mTerminal->statusCallback != NULL) + mTerminal->statusCallback(mTerminal->getName(), NOTIFY_CARD_AVAILABLE, SCARD_ERROR_OK, NULL); + + _END(); + + return false; + } + + gboolean USBTerminal::cardDisconnect(gpointer user_data) + { + _BEGIN(); + + USBTerminal *mTerminal = USBTerminal::getInstance(); + pthread_mutex_t *eventMutex = (pthread_mutex_t *)user_data; + + _INFO("Card Removed"); + + pthread_mutex_lock(eventMutex); + + mTerminal->setCardConnected(false); + + pthread_mutex_unlock(eventMutex); + + if (mTerminal->statusCallback != NULL) + mTerminal->statusCallback(mTerminal->getName(), NOTIFY_CARD_NOT_AVAILABLE, SCARD_ERROR_OK, NULL); + + _END(); + + return false; + } + + int USBTerminal::resetReaderStates(SCARDCONTEXT hContext) + { + int readerCount = 1; + LONG rv; + LPSTR readerName = NULL; + DWORD readerLen; + + USBTerminal *mTerminal = USBTerminal::getInstance(); + + _BEGIN(); + + readerLen = SCARD_AUTOALLOCATE; + rv = SCardListReaders(hContext, NULL, (LPSTR)&readerName, &readerLen); + if (rv == SCARD_S_SUCCESS) + { + _INFO("[Monitor] Reader Connected : %s", readerName); + + if (mTerminal->readerStates[1].szReader != NULL) + free((void *)mTerminal->readerStates[1].szReader); + + mTerminal->readerStates[1].szReader = readerName; + mTerminal->readerStates[1].dwCurrentState = SCARD_STATE_UNAWARE; + mTerminal->readerStates[1].dwEventState = SCARD_STATE_UNKNOWN; + + mTerminal->setReaderConnected(true); + readerCount = 2; + + if (mTerminal->statusCallback != NULL) + mTerminal->statusCallback(mTerminal->getName(), NOTIFY_SE_AVAILABLE, SCARD_ERROR_OK, NULL); + } + else + { + _INFO("[Monitor] Reader Removed"); + mTerminal->setReaderConnected(false); + readerCount = 1; + + if (mTerminal->statusCallback != NULL) + mTerminal->statusCallback(mTerminal->getName(), NOTIFY_SE_NOT_AVAILABLE, SCARD_ERROR_OK, NULL); + } + + _END(); + + return readerCount; + } + + void *USBTerminal::monitorEvents(void *data) + { + LONG rv; + DWORD readerCounts = 1; + pthread_mutex_t eventMutex; + + SCARDCONTEXT hContext; + USBTerminal *mTerminal = USBTerminal::getInstance(); + + pthread_mutex_init(&eventMutex, NULL); + + _BEGIN(); + + rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); + if (rv != SCARD_S_SUCCESS) + { + _ERR("[Monitor] SCardEstablishContext failed : %s", pcsc_stringify_error(rv)); + return NULL; + } + + mTerminal->setMonitorEventsThreadContext(hContext); + + if (mTerminal->isReaderConnected()) + readerCounts = 2; + + while (mTerminal->isInitialized()) + { + rv = SCardGetStatusChange(hContext, INFINITE, mTerminal->readerStates, readerCounts); + if (rv != SCARD_S_SUCCESS) + { + _INFO("[Monitor] SCardGetStatusChange error : %s", pcsc_stringify_error(rv)); + break; + } + + pthread_mutex_lock(&eventMutex); + + if (mTerminal->readerStates[0].dwEventState & SCARD_STATE_CHANGED) + { + _INFO("[Monitor] reader state changed"); + readerCounts = USBTerminal::resetReaderStates(hContext); + } + + if (mTerminal->isReaderConnected()) + { + if ((mTerminal->readerStates[1].dwEventState & SCARD_STATE_EMPTY) == SCARD_STATE_EMPTY) + { + _INFO("[Monitor] Card Removed"); + g_idle_add(&USBTerminal::cardDisconnect, &eventMutex); + } + else if ((mTerminal->readerStates[1].dwEventState & SCARD_STATE_PRESENT) == SCARD_STATE_PRESENT) + { + _INFO("[Monitor] Card Inserted"); + g_idle_add(&USBTerminal::cardConnect, &eventMutex); + } + + mTerminal->readerStates[1].dwCurrentState = mTerminal->readerStates[1].dwEventState; + } + + pthread_mutex_unlock(&eventMutex); + } + + rv = SCardReleaseContext(hContext); + if (rv != SCARD_S_SUCCESS) + _ERR("[Monitor] SCardReleaseContext failed : %s", pcsc_stringify_error(rv)); + + _END(); + + return NULL; + } +} /* namespace smartcard_service_api */ diff --git a/include/USBTerminal.h b/include/USBTerminal.h new file mode 100644 index 0000000..7de3eaa --- /dev/null +++ b/include/USBTerminal.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBTERMINAL_H_ +#define USBTERMINAL_H_ + +/* standard library header */ +#include +#include + +#include "Lock.h" +#include "Terminal.h" +#include +#include + +using namespace std; + +namespace smartcard_service_api +{ + class USBTerminal: public Terminal + { + private: + PMutex mutex; + + USBTerminal(); + ~USBTerminal(); + + static int resetReaderStates(SCARDCONTEXT hContext); + static void *monitorEvents(void *data); + static gboolean cardConnect(gpointer user_data); + static gboolean cardDisconnect(gpointer user_data); + + ByteArray currentAtr; + SCARDCONTEXT mainContext; + SCARDHANDLE cardHandle; + bool cardConnected; + bool readerConnected; + const SCARD_IO_REQUEST *activeProtocol; + + /* Monitor Events Thread */ + int monitorEventsThreadId; + SCARDCONTEXT monitorEventsThreadContext; + pthread_t monitorEventsThread; + public: + SCARD_READERSTATE readerStates[2]; + + static USBTerminal *getInstance(); + + bool initialize(); + void finalize(); + + bool open(); + void close(); + + bool isSecureElementPresence() const; + + int transmitSync(const ByteArray &command, ByteArray &response); + int getATRSync(ByteArray &atr); + + int transmit(const ByteArray &command, terminalTransmitCallback callback, void *userData); + int getATR(terminalGetATRCallback callback, void *userData); + + SCARDCONTEXT getMainContext() { return mainContext; } + void setMonitorEventsThreadContext(SCARDCONTEXT _monitorEventsThreadContext) + { monitorEventsThreadContext = _monitorEventsThreadContext; } + void setCardHandle(SCARDHANDLE _cardHandle) { cardHandle = _cardHandle; } + SCARDHANDLE getCardHandle() { return cardHandle; } + void setCardConnected(bool _cardConnected) { cardConnected = _cardConnected; } + inline bool isCardConnected() const { return cardConnected; } + void setReaderConnected(bool _readerConnected) { readerConnected = _readerConnected; } + inline bool isReaderConnected() const { return readerConnected; } + void setActiveProtocol(const SCARD_IO_REQUEST *_activeProtocol) { activeProtocol = _activeProtocol; } + const SCARD_IO_REQUEST *getActiveProtocol() const { return activeProtocol; } + + void setCurrentAtr(ByteArray &atr) { currentAtr = atr; } + }; +} /* namespace smartcard_service_api */ +#endif /* USBTERMINAL_H_ */ diff --git a/packaging/smartcard-plugin-usb.spec b/packaging/smartcard-plugin-usb.spec new file mode 100755 index 0000000..0573d53 --- /dev/null +++ b/packaging/smartcard-plugin-usb.spec @@ -0,0 +1,40 @@ +Name: smartcard-plugin-usb +Summary: Smartcard plugin usb +Version: 0.0.1 +Release: 0 +Group: Network & Connectivity/Smartcard +License: Apache-2.0 +Source0: %{name}-%{version}.tar.gz +BuildRequires: cmake +BuildRequires: pkgconfig(glib-2.0) +BuildRequires: pkgconfig(dlog) +BuildRequires: pkgconfig(smartcard-service-common) +BuildRequires: pkgconfig(libpcsclite) +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig + + +%description +Smartcard Service plugin usb + +%prep +%setup -q + +%build +cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \ +%ifarch aarch64 x86_64 + -DTIZEN_ARCH_64=1 \ +%endif + +%install +%make_install + +%post -p /sbin/ldconfig + +%postun -p /sbin/ldconfig + +%files +%manifest %{name}.manifest +%license LICENSE.APLv2 +%defattr(-,root,root,-) +%{_libdir}/se/lib*.so diff --git a/smartcard-plugin-usb.manifest b/smartcard-plugin-usb.manifest new file mode 100644 index 0000000..ca37499 --- /dev/null +++ b/smartcard-plugin-usb.manifest @@ -0,0 +1,6 @@ + + + + + + -- 2.7.4