From dc1cfa6252073ac345412e7df9c5cc0365bb7f11 Mon Sep 17 00:00:00 2001 From: Szczepan Zalega Date: Tue, 28 Jul 2020 12:29:43 +0200 Subject: Extract Nitrokey Storage only features to separate unit --- NK_C_API_helpers.h | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 NK_C_API_helpers.h (limited to 'NK_C_API_helpers.h') diff --git a/NK_C_API_helpers.h b/NK_C_API_helpers.h new file mode 100644 index 0000000..e9ae4d1 --- /dev/null +++ b/NK_C_API_helpers.h @@ -0,0 +1,88 @@ +#ifndef LIBNITROKEY_NK_C_API_HELPERS_H +#define LIBNITROKEY_NK_C_API_HELPERS_H + + +#include "NK_C_API.h" +#include +#include +#include "libnitrokey/NitrokeyManager.h" +#include +#include "libnitrokey/LibraryException.h" +#include "libnitrokey/cxx_semantics.h" +#include "libnitrokey/stick20_commands.h" +#include "libnitrokey/device_proto.h" +#include "libnitrokey/version.h" + + +extern uint8_t NK_last_command_status; + + +template +T* duplicate_vector_and_clear(std::vector &v){ + auto d = new T[v.size()]; + std::copy(v.begin(), v.end(), d); + std::fill(v.begin(), v.end(), 0); + return d; +} + +template +std::tuple get_with_status(T func, R fallback) { + NK_last_command_status = 0; + try { + return std::make_tuple(0, func()); + } + catch (CommandFailedException & commandFailedException){ + NK_last_command_status = commandFailedException.last_command_status; + } + catch (LibraryException & libraryException){ + NK_last_command_status = libraryException.exception_id(); + } + catch (const DeviceCommunicationException &deviceException){ + NK_last_command_status = 256-deviceException.getType(); + } + return std::make_tuple(NK_last_command_status, fallback); +} + +template +uint8_t * get_with_array_result(T func){ + return std::get<1>(get_with_status(func, nullptr)); +} + +template +char* get_with_string_result(T func){ + auto result = std::get<1>(get_with_status(func, nullptr)); + if (result == nullptr) { + return strndup("", MAXIMUM_STR_REPLY_LENGTH); + } + return result; +} + +template +auto get_with_result(T func){ + return std::get<1>(get_with_status(func, static_cast(0))); +} + +template +uint8_t get_without_result(T func){ + NK_last_command_status = 0; + try { + func(); + return 0; + } + catch (CommandFailedException & commandFailedException){ + NK_last_command_status = commandFailedException.last_command_status; + } + catch (LibraryException & libraryException){ + NK_last_command_status = libraryException.exception_id(); + } + catch (const InvalidCRCReceived &invalidCRCException){ + ; + } + catch (const DeviceCommunicationException &deviceException){ + NK_last_command_status = 256-deviceException.getType(); + } + return NK_last_command_status; +} + + +#endif // LIBNITROKEY_NK_C_API_HELPERS_H -- cgit v1.2.1