From e7d702b5c981530c96311cbb89d7c6e171d83ca5 Mon Sep 17 00:00:00 2001 From: Mart Somermaa Date: Fri, 30 Sep 2022 22:05:41 +0300 Subject: [PATCH] refactor(SmartCard): add null object constructor WE2-716 Signed-off-by: Mart Somermaa --- include/pcsc-cpp/pcsc-cpp-utils.hpp | 7 +++++++ include/pcsc-cpp/pcsc-cpp.hpp | 3 ++- src/SmartCard.cpp | 6 +++++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/include/pcsc-cpp/pcsc-cpp-utils.hpp b/include/pcsc-cpp/pcsc-cpp-utils.hpp index 9975558..69da5a1 100644 --- a/include/pcsc-cpp/pcsc-cpp-utils.hpp +++ b/include/pcsc-cpp/pcsc-cpp-utils.hpp @@ -57,3 +57,10 @@ inline std::string removeAbsolutePathPrefix(const std::string& filePath) #define THROW(ExceptionType, message) \ THROW_WITH_CALLER_INFO(ExceptionType, message, __FILE__, __LINE__, __func__) + +#define REQUIRE_NON_NULL(val) \ + if (!val) { \ + throw std::logic_error("Null " + std::string(#val) + " in " \ + + pcsc_cpp::removeAbsolutePathPrefix(__FILE__) + ':' \ + + std::to_string(__LINE__) + ':' + __func__); \ + } diff --git a/include/pcsc-cpp/pcsc-cpp.hpp b/include/pcsc-cpp/pcsc-cpp.hpp index 5c934b6..dc27a44 100644 --- a/include/pcsc-cpp/pcsc-cpp.hpp +++ b/include/pcsc-cpp/pcsc-cpp.hpp @@ -207,7 +207,7 @@ constexpr uint8_t PIN_PAD_PIN_ENTRY_TIMEOUT = 90; // 1 minute, 30 seconds class SmartCard { public: - enum class Protocol { T0, T1 }; // AUTO = T0 | T1 + enum class Protocol { UNDEFINED, T0, T1 }; // AUTO = T0 | T1 using ptr = std::unique_ptr; @@ -229,6 +229,7 @@ class SmartCard }; SmartCard(const ContextPtr& context, const string_t& readerName, byte_vector atr); + SmartCard(); // Null object constructor. ~SmartCard(); // The rule of five. diff --git a/src/SmartCard.cpp b/src/SmartCard.cpp index b2a0db5..ca60f2f 100644 --- a/src/SmartCard.cpp +++ b/src/SmartCard.cpp @@ -273,20 +273,23 @@ SmartCard::SmartCard(const ContextPtr& contex, const string_t& readerName, byte_ // TODO: debug("Card ATR -> " + bytes2hexstr(atr)); } +SmartCard::SmartCard() = default; SmartCard::~SmartCard() = default; SmartCard::TransactionGuard SmartCard::beginTransaction() { + REQUIRE_NON_NULL(card); return SmartCard::TransactionGuard {*card, transactionInProgress}; } bool SmartCard::readerHasPinPad() const { - return card->readerHasPinPad(); + return card ? card->readerHasPinPad() : false; } ResponseApdu SmartCard::transmit(const CommandApdu& command) const { + REQUIRE_NON_NULL(card); if (!transactionInProgress) { THROW(std::logic_error, "Call SmartCard::transmit() inside a transaction"); } @@ -296,6 +299,7 @@ ResponseApdu SmartCard::transmit(const CommandApdu& command) const ResponseApdu SmartCard::transmitCTL(const CommandApdu& command, uint16_t lang, uint8_t minlen) const { + REQUIRE_NON_NULL(card); if (!transactionInProgress) { THROW(std::logic_error, "Call SmartCard::transmit() inside a transaction"); }