--- /dev/null
+Jihoon Jung <jh8801.jung@samsung.com>
--- /dev/null
+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)
+
--- /dev/null
+Copyright (c) 2000 - 2021 Samsung Electronics Co., Ltd. All rights reserved.\r
+\r
+ Apache License\r
+ Version 2.0, January 2004\r
+ http://www.apache.org/licenses/\r
+\r
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\r
+\r
+ 1. Definitions.\r
+\r
+ "License" shall mean the terms and conditions for use, reproduction,\r
+ and distribution as defined by Sections 1 through 9 of this document.\r
+\r
+ "Licensor" shall mean the copyright owner or entity authorized by\r
+ the copyright owner that is granting the License.\r
+\r
+ "Legal Entity" shall mean the union of the acting entity and all\r
+ other entities that control, are controlled by, or are under common\r
+ control with that entity. For the purposes of this definition,\r
+ "control" means (i) the power, direct or indirect, to cause the\r
+ direction or management of such entity, whether by contract or\r
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the\r
+ outstanding shares, or (iii) beneficial ownership of such entity.\r
+\r
+ "You" (or "Your") shall mean an individual or Legal Entity\r
+ exercising permissions granted by this License.\r
+\r
+ "Source" form shall mean the preferred form for making modifications,\r
+ including but not limited to software source code, documentation\r
+ source, and configuration files.\r
+\r
+ "Object" form shall mean any form resulting from mechanical\r
+ transformation or translation of a Source form, including but\r
+ not limited to compiled object code, generated documentation,\r
+ and conversions to other media types.\r
+\r
+ "Work" shall mean the work of authorship, whether in Source or\r
+ Object form, made available under the License, as indicated by a\r
+ copyright notice that is included in or attached to the work\r
+ (an example is provided in the Appendix below).\r
+\r
+ "Derivative Works" shall mean any work, whether in Source or Object\r
+ form, that is based on (or derived from) the Work and for which the\r
+ editorial revisions, annotations, elaborations, or other modifications\r
+ represent, as a whole, an original work of authorship. For the purposes\r
+ of this License, Derivative Works shall not include works that remain\r
+ separable from, or merely link (or bind by name) to the interfaces of,\r
+ the Work and Derivative Works thereof.\r
+\r
+ "Contribution" shall mean any work of authorship, including\r
+ the original version of the Work and any modifications or additions\r
+ to that Work or Derivative Works thereof, that is intentionally\r
+ submitted to Licensor for inclusion in the Work by the copyright owner\r
+ or by an individual or Legal Entity authorized to submit on behalf of\r
+ the copyright owner. For the purposes of this definition, "submitted"\r
+ means any form of electronic, verbal, or written communication sent\r
+ to the Licensor or its representatives, including but not limited to\r
+ communication on electronic mailing lists, source code control systems,\r
+ and issue tracking systems that are managed by, or on behalf of, the\r
+ Licensor for the purpose of discussing and improving the Work, but\r
+ excluding communication that is conspicuously marked or otherwise\r
+ designated in writing by the copyright owner as "Not a Contribution."\r
+\r
+ "Contributor" shall mean Licensor and any individual or Legal Entity\r
+ on behalf of whom a Contribution has been received by Licensor and\r
+ subsequently incorporated within the Work.\r
+\r
+ 2. Grant of Copyright License. Subject to the terms and conditions of\r
+ this License, each Contributor hereby grants to You a perpetual,\r
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
+ copyright license to reproduce, prepare Derivative Works of,\r
+ publicly display, publicly perform, sublicense, and distribute the\r
+ Work and such Derivative Works in Source or Object form.\r
+\r
+ 3. Grant of Patent License. Subject to the terms and conditions of\r
+ this License, each Contributor hereby grants to You a perpetual,\r
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable\r
+ (except as stated in this section) patent license to make, have made,\r
+ use, offer to sell, sell, import, and otherwise transfer the Work,\r
+ where such license applies only to those patent claims licensable\r
+ by such Contributor that are necessarily infringed by their\r
+ Contribution(s) alone or by combination of their Contribution(s)\r
+ with the Work to which such Contribution(s) was submitted. If You\r
+ institute patent litigation against any entity (including a\r
+ cross-claim or counterclaim in a lawsuit) alleging that the Work\r
+ or a Contribution incorporated within the Work constitutes direct\r
+ or contributory patent infringement, then any patent licenses\r
+ granted to You under this License for that Work shall terminate\r
+ as of the date such litigation is filed.\r
+\r
+ 4. Redistribution. You may reproduce and distribute copies of the\r
+ Work or Derivative Works thereof in any medium, with or without\r
+ modifications, and in Source or Object form, provided that You\r
+ meet the following conditions:\r
+\r
+ (a) You must give any other recipients of the Work or\r
+ Derivative Works a copy of this License; and\r
+\r
+ (b) You must cause any modified files to carry prominent notices\r
+ stating that You changed the files; and\r
+\r
+ (c) You must retain, in the Source form of any Derivative Works\r
+ that You distribute, all copyright, patent, trademark, and\r
+ attribution notices from the Source form of the Work,\r
+ excluding those notices that do not pertain to any part of\r
+ the Derivative Works; and\r
+\r
+ (d) If the Work includes a "NOTICE" text file as part of its\r
+ distribution, then any Derivative Works that You distribute must\r
+ include a readable copy of the attribution notices contained\r
+ within such NOTICE file, excluding those notices that do not\r
+ pertain to any part of the Derivative Works, in at least one\r
+ of the following places: within a NOTICE text file distributed\r
+ as part of the Derivative Works; within the Source form or\r
+ documentation, if provided along with the Derivative Works; or,\r
+ within a display generated by the Derivative Works, if and\r
+ wherever such third-party notices normally appear. The contents\r
+ of the NOTICE file are for informational purposes only and\r
+ do not modify the License. You may add Your own attribution\r
+ notices within Derivative Works that You distribute, alongside\r
+ or as an addendum to the NOTICE text from the Work, provided\r
+ that such additional attribution notices cannot be construed\r
+ as modifying the License.\r
+\r
+ You may add Your own copyright statement to Your modifications and\r
+ may provide additional or different license terms and conditions\r
+ for use, reproduction, or distribution of Your modifications, or\r
+ for any such Derivative Works as a whole, provided Your use,\r
+ reproduction, and distribution of the Work otherwise complies with\r
+ the conditions stated in this License.\r
+\r
+ 5. Submission of Contributions. Unless You explicitly state otherwise,\r
+ any Contribution intentionally submitted for inclusion in the Work\r
+ by You to the Licensor shall be under the terms and conditions of\r
+ this License, without any additional terms or conditions.\r
+ Notwithstanding the above, nothing herein shall supersede or modify\r
+ the terms of any separate license agreement you may have executed\r
+ with Licensor regarding such Contributions.\r
+\r
+ 6. Trademarks. This License does not grant permission to use the trade\r
+ names, trademarks, service marks, or product names of the Licensor,\r
+ except as required for reasonable and customary use in describing the\r
+ origin of the Work and reproducing the content of the NOTICE file.\r
+\r
+ 7. Disclaimer of Warranty. Unless required by applicable law or\r
+ agreed to in writing, Licensor provides the Work (and each\r
+ Contributor provides its Contributions) on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r
+ implied, including, without limitation, any warranties or conditions\r
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\r
+ PARTICULAR PURPOSE. You are solely responsible for determining the\r
+ appropriateness of using or redistributing the Work and assume any\r
+ risks associated with Your exercise of permissions under this License.\r
+\r
+ 8. Limitation of Liability. In no event and under no legal theory,\r
+ whether in tort (including negligence), contract, or otherwise,\r
+ unless required by applicable law (such as deliberate and grossly\r
+ negligent acts) or agreed to in writing, shall any Contributor be\r
+ liable to You for damages, including any direct, indirect, special,\r
+ incidental, or consequential damages of any character arising as a\r
+ result of this License or out of the use or inability to use the\r
+ Work (including but not limited to damages for loss of goodwill,\r
+ work stoppage, computer failure or malfunction, or any and all\r
+ other commercial damages or losses), even if such Contributor\r
+ has been advised of the possibility of such damages.\r
+\r
+ 9. Accepting Warranty or Additional Liability. While redistributing\r
+ the Work or Derivative Works thereof, You may choose to offer,\r
+ and charge a fee for, acceptance of support, warranty, indemnity,\r
+ or other liability obligations and/or rights consistent with this\r
+ License. However, in accepting such obligations, You may act only\r
+ on Your own behalf and on Your sole responsibility, not on behalf\r
+ of any other Contributor, and only if You agree to indemnify,\r
+ defend, and hold each Contributor harmless for any liability\r
+ incurred by, or claims asserted against, such Contributor by reason\r
+ of your accepting any such warranty or additional liability.\r
+\r
+ END OF TERMS AND CONDITIONS\r
+\r
+ APPENDIX: How to apply the Apache License to your work.\r
+\r
+ To apply the Apache License to your work, attach the following\r
+ boilerplate notice, with the fields enclosed by brackets "[]"\r
+ replaced with your own identifying information. (Don't include\r
+ the brackets!) The text should be enclosed in the appropriate\r
+ comment syntax for the file format. We also recommend that a\r
+ file or class name and description of purpose be included on the\r
+ same "printed page" as the copyright notice for easier\r
+ identification within third-party archives.\r
+\r
+ Copyright [yyyy] [name of copyright owner]\r
+\r
+ Licensed under the Apache License, Version 2.0 (the "License");\r
+ you may not use this file except in compliance with the License.\r
+ You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+\r
+\r
+\r
--- /dev/null
+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.
--- /dev/null
+/*
+ * 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 <cstdio>
+#include <cstring>
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/types.h>
+
+#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 */
--- /dev/null
+/*
+ * 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 <vector>
+#include <map>
+
+#include "Lock.h"
+#include "Terminal.h"
+#include <winscard.h>
+#include <glib.h>
+
+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_ */
--- /dev/null
+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
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
+