Introduce new (much simpler) Exception type. 62/40962/5
authorBartlomiej Grzelewski <b.grzelewski@samsung.com>
Tue, 9 Jun 2015 13:09:59 +0000 (15:09 +0200)
committerBartlomiej Grzelewski <b.grzelewski@samsung.com>
Fri, 12 Jun 2015 11:24:09 +0000 (13:24 +0200)
This commit changes the exception class hierarhy. Exceptions class won't
be hidden inside classes. From now exceptions will be defined globally
per project.

It does not mean that you cannot create hidden exception inside class.

Change-Id: If10bc10154684de91ea1f82332860ef53bdd2d3a

21 files changed:
src/manager/CMakeLists.txt
src/manager/common/exception.cpp [new file with mode: 0644]
src/manager/common/exception.h [new file with mode: 0644]
src/manager/common/stringify.h
src/manager/crypto/generic-backend/exception.h
src/manager/crypto/generic-backend/gkey.h
src/manager/crypto/generic-backend/gstore.h
src/manager/crypto/platform/decider.cpp
src/manager/crypto/sw-backend/crypto.h
src/manager/crypto/sw-backend/internals.cpp
src/manager/crypto/sw-backend/key.cpp
src/manager/crypto/sw-backend/store.cpp
src/manager/crypto/tz-backend/store.cpp
src/manager/dpl/log/include/dpl/log/log.h
src/manager/service/ckm-logic.cpp
src/manager/service/ckm-logic.h
src/manager/service/crypto-logic.cpp
src/manager/service/crypto-logic.h
src/manager/service/file-lock.cpp
src/manager/service/file-system.cpp
src/manager/service/file-system.h

index 3b8c28d..73820db 100644 (file)
@@ -17,6 +17,7 @@ SET(COMMON_SOURCES
     ${COMMON_PATH}/common/base64.cpp
     ${COMMON_PATH}/common/crypto-init.cpp
     ${COMMON_PATH}/common/data-type.cpp
+    ${COMMON_PATH}/common/exception.cpp
     ${COMMON_PATH}/common/protocols.cpp
     ${COMMON_PATH}/common/message-buffer.cpp
     ${COMMON_PATH}/common/certificate-impl.cpp
diff --git a/src/manager/common/exception.cpp b/src/manager/common/exception.cpp
new file mode 100644 (file)
index 0000000..d3b8c9b
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  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
+ */
+/*
+ * @file       exception.cpp
+ * @author     Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version    1.0
+ */
+#include <exception.h>
+
+#include <dpl/log/log.h>
+
+namespace CKM {
+namespace Exc {
+
+PrintError::PrintError(
+       const std::string &path,
+       const std::string &function,
+       int line,
+       int error,
+       const std::string &message)
+{
+    LogErrorPosition(message << " (Error: " << error << ")", path.c_str(), line, function.c_str());
+}
+
+PrintDebug::PrintDebug(
+       const std::string &path,
+       const std::string &function,
+       int line,
+       int error,
+       const std::string &message)
+{
+    LogDebugPosition(message << " (Error: " << error << ")", path.c_str(), line, function.c_str());
+}
+
+} // namespace Exc
+} // namespace CKM
+
diff --git a/src/manager/common/exception.h b/src/manager/common/exception.h
new file mode 100644 (file)
index 0000000..611cad1
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  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
+ */
+/*
+ * @file       exception.h
+ * @author     Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version    1.0
+ */
+#pragma once
+
+#include <exception>
+#include <string>
+#include <iostream>
+#include <sstream>
+
+#include <ckm/ckm-error.h>
+
+#include <symbol-visibility.h>
+#include <stringify.h>
+
+namespace CKM {
+namespace Exc {
+
+class COMMON_API Exception : public std::exception {
+public:
+    Exception(const char *path, const char *function, int line, const std::string &message = std::string())
+      : m_path(path)
+      , m_function(function)
+      , m_line(line)
+      , m_message(message)
+    {}
+
+    virtual ~Exception() noexcept {}
+
+    virtual const char *what(void) const noexcept {
+        return m_message.c_str();
+    }
+
+    virtual std::string message(void) const {
+        std::ostringstream msg;
+        msg << "[" << m_path << ":" << m_line << " " << m_function << "()] " << m_message;
+        return msg.str();
+    }
+
+    virtual int error(void) const = 0;
+
+protected:
+    std::string m_path;
+    std::string m_function;
+    int m_line;
+    std::string m_message;
+};
+
+class DefaultExceptionLogger {
+public:
+    template <typename... Args>
+    DefaultExceptionLogger(const Args&...) {}
+};
+
+template<
+    int Error = 0,
+    typename Stringify = StringifyAvoid,
+    typename Before = DefaultExceptionLogger,
+    typename After = DefaultExceptionLogger>
+class COMMON_API DefineException : public Exception {
+public:
+    template<typename... Args>
+    DefineException(const char *path, const char *function, int line, const Args&... args)
+      : Exception(path, function, line, Stringify()(args...))
+    {
+        Before(m_path, m_function, m_line, DefineException<Error,Stringify,Before,After>::error(), m_message);
+    }
+    ~DefineException() noexcept {
+        After(m_path, m_function, m_line, DefineException<Error,Stringify,Before,After>::error(), m_message);
+    }
+    virtual int error(void) const {
+        return Error;
+    }
+};
+
+class COMMON_API PrintError {
+public:
+    PrintError(
+        const std::string &path,
+        const std::string &function,
+        int line, int error,
+        const std::string &message = std::string());
+};
+
+class COMMON_API PrintDebug {
+public:
+    PrintDebug(
+        const std::string &path,
+        const std::string &function,
+        int line, int error,
+        const std::string &message = std::string());
+};
+
+typedef DefineException<CKM_API_ERROR_SERVER_ERROR,
+        Stringify, PrintError> InternalError;
+typedef DefineException<CKM_API_ERROR_INPUT_PARAM,
+        Stringify, PrintError> InputParam;
+typedef DefineException<CKM_API_ERROR_DB_LOCKED,
+        Stringify, PrintError> DatabaseLocked;
+typedef DefineException<CKM_API_ERROR_FILE_SYSTEM,
+        Stringify, PrintError> FileSystemFailed;
+typedef DefineException<CKM_API_ERROR_AUTHENTICATION_FAILED,
+        Stringify, PrintError> AuthenticationFailed;
+
+} // namespace Exc
+} // namespace CKM
+
+#define ThrowErr(name, ...) \
+  throw name(__FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
+
index 58d6fda..49a9a46 100644 (file)
@@ -16,9 +16,9 @@
 /*
  * @file       stringify.h
  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Bartlomiej Grzelewski (b.grzelewski@samsung.com)
  * @version    1.0
  */
-
 #pragma once
 
 #include <sstream>
 
 namespace CKM {
 
-/*
- * Helper functions for easy argument concatenation. Can be used in logs and exceptions.
- * Ex)
- * template <typename... Args>
- * std::runtime_error my_exception(const Args&... args)
- * {
- *     return std::runtime_error(stringify(args...));
- * };
- *
- * throw my_exception("Function foo has failed. Status: ", status, " error code: ", error);
- */
+template <bool Mode>
+class StringifyBasic;
+
+template <>
+class StringifyBasic<false> {
+public:
+    std::string operator()() {
+        return std::string();
+    }
 
-std::string stringify() {
-    return std::string();
-}
+    template <typename... Args>
+    std::string operator()(const Args&... args){
+        return std::string();
+    }
+};
 
-void concatenate(std::ostringstream&) {}
+template <>
+class StringifyBasic<true> {
+    void concatenate(std::ostringstream&) {}
 
-template <typename T, typename... Args>
-void concatenate(std::ostringstream& stream, const T& arg1, const Args&... args) {
-    stream << arg1;
-    concatenate(stream, args...);
-}
+    template <typename t, typename... Args>
+    void concatenate(std::ostringstream& stream, const t& arg1, const Args&... args) {
+        stream << arg1;
+        concatenate(stream, args...);
+    }
+public:
+    std::string operator()() {
+        return std::string();
+    }
 
-template <typename T, typename... Args>
-std::string stringify(const T& arg1, const Args&... args){
-    std::ostringstream stream;
-    concatenate(stream, arg1, args...);
-    return stream.str();
-}
+    template <typename T, typename... Args>
+    std::string operator()(const T& arg1, const Args&... args){
+        std::ostringstream stream;
+        concatenate(stream, arg1, args...);
+        return stream.str();
+    }
+};
+
+#ifdef DEBUG
+#define DEBUG_STATUS true
+#else
+#define DEBUG_STATUS false
+#endif
+
+typedef StringifyBasic<true>  Stringify;
+typedef StringifyBasic<false> StringifyAvoid;
+typedef StringifyBasic<true>  StringifyError;
+typedef StringifyBasic<DEBUG_STATUS> StringifyDebug;
+
+#undef DEBUG_STATUS
 
 } // namespace CKM
+
index 756db7b..18e5b70 100644 (file)
  */
 #pragma once
 
-#include <dpl/exception.h>
+#include <exception.h>
 
 namespace CKM {
+namespace Exc {
 namespace Crypto {
-namespace Exception {
 
-DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
-DECLARE_EXCEPTION_TYPE(Base, InternalError)
-DECLARE_EXCEPTION_TYPE(Base, KeyNotSupported)
-DECLARE_EXCEPTION_TYPE(Base, OperationNotSupported)
-DECLARE_EXCEPTION_TYPE(Base, WrongBackend)
-DECLARE_EXCEPTION_TYPE(Base, InputParam)
+typedef CKM::Exc::InputParam InputParam;
+typedef CKM::Exc::InternalError InternalError;
+typedef CKM::Exc::InternalError KeyNotSupported;
+typedef CKM::Exc::InternalError OperationNotSupported;
+typedef CKM::Exc::InternalError WrongBackend;
 
-} // namespace Exception
+} // namespace Exc
 } // namespace Crypto
 } // namespace CKM
 
index 8ad6eda..9327645 100644 (file)
@@ -34,23 +34,23 @@ protected:
     GKey(){}
 public:
     virtual RawBuffer getBinary() {
-        Throw(Exception::OperationNotSupported);
+        ThrowErr(Exc::Crypto::OperationNotSupported);
     }
 
     virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &) {
-        Throw(Exception::OperationNotSupported);
+        ThrowErr(Exc::Crypto::OperationNotSupported);
     }
 
     virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &) {
-        Throw(Exception::OperationNotSupported);
+        ThrowErr(Exc::Crypto::OperationNotSupported);
     }
 
     virtual RawBuffer sign(const CryptoAlgorithm &, const RawBuffer &) {
-        Throw(Exception::OperationNotSupported);
+        ThrowErr(Exc::Crypto::OperationNotSupported);
     }
 
     virtual int verify(const CryptoAlgorithm &, const RawBuffer &, const RawBuffer &) {
-        Throw(Exception::OperationNotSupported);
+        ThrowErr(Exc::Crypto::OperationNotSupported);
     }
 
     virtual ~GKey () {}
index 49fb545..13c7d26 100644 (file)
@@ -33,11 +33,11 @@ namespace Crypto {
 
 class GStore {
 public:
-    virtual GKeyShPtr getKey(const Token &) { Throw(Exception::OperationNotSupported); }
-    virtual TokenPair generateAKey(const CryptoAlgorithm &) { Throw(Exception::OperationNotSupported); }
-    virtual Token generateSKey(const CryptoAlgorithm &) { Throw(Exception::OperationNotSupported); }
-    virtual Token import(DataType, const RawBuffer &) { Throw(Exception::OperationNotSupported); }
-    virtual void destroy(const Token &) { Throw(Exception::OperationNotSupported); }
+    virtual GKeyShPtr getKey(const Token &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
+    virtual TokenPair generateAKey(const CryptoAlgorithm &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
+    virtual Token generateSKey(const CryptoAlgorithm &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
+    virtual Token import(DataType, const RawBuffer &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
+    virtual void destroy(const Token &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
     virtual ~GStore() {}
 
 protected:
index f934642..16255d9 100644 (file)
@@ -24,6 +24,7 @@
 
 #include <platform/decider.h>
 
+#include <generic-backend/exception.h>
 #include <sw-backend/store.h>
 #include <tz-backend/store.h>
 
@@ -49,9 +50,8 @@ GStore& Decider::getStore(CryptoBackend cryptoBackend) {
     if (gStore)
         return *gStore;
 
-    LogError("Backend not available. BackendId: " << (int)cryptoBackend);
-    ThrowMsg(CKM::Crypto::Exception::Base,
-             "Backend not available. BackendId: " << (int)cryptoBackend);
+    ThrowErr(Exc::Crypto::InternalError,
+             "Backend not available. BackendId: ", (int)cryptoBackend);
 }
 
 GStore& Decider::getStore(DataType data, bool exportable) {
index cd05da5..b8d643d 100644 (file)
@@ -72,22 +72,15 @@ public:
     EvpCipherWrapper(const EVP_CIPHER *type, const T &key, const T &iv, bool encryption)
     {
         if (static_cast<int>(key.size()) != EVP_CIPHER_key_length(type)) {
-            LogError("Wrong key size! Expected: "
-                << EVP_CIPHER_key_length(type) << " Get: " << key.size());
-            ThrowMsg(CKM::Crypto::Exception::InternalError, "Wrong key size! Expected: "
-                << EVP_CIPHER_key_length(type) << " Get: " << key.size());
+            ThrowErr(Exc::Crypto::InternalError, "Wrong key size! Expected: ", EVP_CIPHER_key_length(type) ," Get: ", key.size());
         }
 
         if (static_cast<int>(iv.size()) < EVP_CIPHER_iv_length(type)) {
-            LogError("Wrong iv size! Expected: "
-                << EVP_CIPHER_iv_length(type) << " Get: " << iv.size());
-            ThrowMsg(CKM::Crypto::Exception::InternalError, "Wrong iv size! Expected: "
-                << EVP_CIPHER_iv_length(type) << " Get: " << iv.size());
+            ThrowErr(Exc::Crypto::InternalError, "Wrong iv size! Expected: ", EVP_CIPHER_iv_length(type) , " Get: ", iv.size());
         }
 
         if (1 != EVP_CipherInit_ex(m_ctx, type, NULL, key.data(), iv.data(), encryption ? 1 : 0)) {
-            LogError("Failed in EVP_CipherInit");
-            ThrowMsg(CKM::Crypto::Exception::InternalError, "Failed in EVP_CipherInit");
+            ThrowErr(Exc::Crypto::InternalError, "Failed in EVP_CipherInit");
         }
 
         EVP_CIPHER_CTX_set_padding(m_ctx, 1);
@@ -98,8 +91,7 @@ public:
         int bytesLen = static_cast<int>(data.size() + EVP_CIPHER_CTX_block_size(m_ctx));
         T output(bytesLen);
         if (1 != EVP_CipherUpdate(m_ctx, output.data(), &bytesLen, data.data(), data.size())) {
-            LogError("Failed in EVP_CipherUpdate");
-            ThrowMsg(CKM::Crypto::Exception::InternalError, "Failed in EVP_CipherUpdate");
+            ThrowErr(Exc::Crypto::InternalError, "Failed in EVP_CipherUpdate");
         }
         output.resize(bytesLen);
         return output;
@@ -109,8 +101,7 @@ public:
         int bytesLen = EVP_CIPHER_CTX_block_size(m_ctx);
         T output(bytesLen);
         if (1 != EVP_CipherFinal_ex(m_ctx, output.data(), &bytesLen)) {
-            LogError("Failed in EVP_CipherFinal");
-            ThrowMsg(CKM::Crypto::Exception::InternalError, "Failed in EVP_CipherFinal");
+            ThrowErr(Exc::Crypto::InternalError, "Failed in EVP_CipherFinal");
         }
         output.resize(bytesLen);
         return output;
index 9fe6c3d..e9bbab2 100644 (file)
@@ -57,18 +57,15 @@ CKM::RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) {
     BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
 
     if (NULL == pkey) {
-        LogDebug("attempt to parse an empty key!");
-        ThrowMsg(CKM::Crypto::Exception::InternalError, "attempt to parse an empty key!");
+        ThrowErr(CKM::Exc::Crypto::InternalError, "attempt to parse an empty key!");
     }
 
     if (NULL == bio.get()) {
-        LogError("Error in memory allocation! Function: BIO_new.");
-        ThrowMsg(CKM::Crypto::Exception::InternalError, "Error in memory allocation! Function: BIO_new.");
+        ThrowErr(CKM::Exc::Crypto::InternalError, "Error in memory allocation! Function: BIO_new.");
     }
 
     if (1 != fun(bio.get(), pkey)) {
-        LogError("Error in conversion EVP_PKEY to DER");
-        ThrowMsg(CKM::Crypto::Exception::InternalError, "Error in conversion EVP_PKEY to DER");
+        ThrowErr(CKM::Exc::Crypto::InternalError, "Error in conversion EVP_PKEY to DER");
     }
 
     CKM::RawBuffer output(8196);
@@ -76,8 +73,7 @@ CKM::RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) {
     int size = BIO_read(bio.get(), output.data(), output.size());
 
     if (size <= 0) {
-        LogError("Error in BIO_read: " << size);
-        ThrowMsg(CKM::Crypto::Exception::InternalError, "Error in BIO_read: " << size);
+        ThrowErr(CKM::Exc::Crypto::InternalError, "Error in BIO_read: ", size);
     }
 
     output.resize(size);
@@ -108,8 +104,7 @@ int initialize() {
         hw_rand_ret = RAND_load_file(DEV_URANDOM_FILE, 32);
 
         if(hw_rand_ret != 32) {
-            LogError("Error in U_RAND_file_load");
-            ThrowMsg(Crypto::Exception::InternalError, "Error in U_RAND_file_load");
+            ThrowErr(Exc::Crypto::InternalError, "Error in U_RAND_file_load");
         }
     }
 
@@ -135,8 +130,7 @@ const EVP_MD *getMdAlgo(const HashAlgorithm hashAlgo) {
          md_algo = EVP_sha512();
          break;
     default:
-        LogError("Error in hashAlgorithm value");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in hashAlgorithm value");
+        ThrowErr(Exc::Crypto::InternalError, "Error in hashAlgorithm value");
     }
     return md_algo;
 }
@@ -154,8 +148,7 @@ int getRsaPadding(const RSAPaddingAlgorithm padAlgo) {
         rsa_padding = RSA_X931_PADDING;
         break;
     default:
-        LogError("Error in RSAPaddingAlgorithm value");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in RSAPaddingAlgorithm value");
+        ThrowErr(Exc::Crypto::InternalError, "Error in RSAPaddingAlgorithm value");
     }
     return rsa_padding;
 }
@@ -166,30 +159,25 @@ TokenPair createKeyPairRSA(CryptoBackend backendId, const int size)
 
     // check the parameters of functions
     if(size!=1024 && size!=2048 && size!=4096) {
-        LogError("Error in RSA input size");
-        ThrowMsg(Crypto::Exception::InputParam, "Error in RSA input size");
+        ThrowErr(Exc::Crypto::InputParam, "Error in RSA input size");
     }
 
     EvpPkeyCtxUPtr ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL), EVP_PKEY_CTX_free);
     if(!ctx) {
-        LogError("Error in EVP_PKEY_CTX_new_id function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new_id function !!");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function !!");
     }
 
     if(EVP_PKEY_keygen_init(ctx.get()) <= 0) {
-        LogError("Error in EVP_PKEY_keygen_init function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen_init function !!");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function !!");
     }
 
     if(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), size) <= 0) {
-        LogError("Error in EVP_PKEY_CTX_set_rsa_keygen_bits function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_rsa_keygen_bits function !!");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_keygen_bits function !!");
     }
 
     EVP_PKEY *pkeyTmp = NULL;
     if(!EVP_PKEY_keygen(ctx.get(), &pkeyTmp)) {
-        LogError("Error in EVP_PKEY_keygen function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen function !!");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!");
     }
     pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free);
 
@@ -205,52 +193,44 @@ TokenPair createKeyPairDSA(CryptoBackend backendId, const int size)
 
     // check the parameters of functions
     if(size!=1024 && size!=2048 && size!=3072 && size!=4096) {
-        LogError("Error in DSA input size");
-        ThrowMsg(Crypto::Exception::InputParam, "Error in DSA input size");
+        ThrowErr(Exc::Crypto::InputParam, "Error in DSA input size");
     }
 
     /* Create the context for generating the parameters */
     EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL), EVP_PKEY_CTX_free);
     if(!pctx) {
-        LogError("Error in EVP_PKEY_CTX_new_id function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new_id function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) {
-        LogError("Error in EVP_PKEY_paramgen_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_paramgen_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen_init function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx.get(), size)) {
-        LogError("Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(", size, ") function");
     }
 
     /* Generate parameters */
     EVP_PKEY *pparamTmp = NULL;
     if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) {
-        LogError("Error in EVP_PKEY_paramgen function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_paramgen function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen function");
     }
     pparam = EvpPkeyUPtr(pparamTmp, EVP_PKEY_free);
 
     // Start to generate key
     EvpPkeyCtxUPtr kctx(EVP_PKEY_CTX_new(pparam.get(), NULL), EVP_PKEY_CTX_free);
     if(!kctx) {
-        LogError("Error in EVP_PKEY_CTX_new function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) {
-        LogError("Error in EVP_PKEY_keygen_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function");
     }
 
     /* Generate the key */
     EVP_PKEY *pkeyTmp = NULL;
     if(!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) {
-        LogError("Error in EVP_PKEY_keygen function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen function !!");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!");
     }
     pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free);
 
@@ -275,54 +255,46 @@ TokenPair createKeyPairECDSA(CryptoBackend backendId, ElipticCurve type)
         ecCurve = NID_secp384r1;
         break;
     default:
-        LogError("Error in EC type");
-        ThrowMsg(Crypto::Exception::InputParam, "Error in EC type");
+        ThrowErr(Exc::Crypto::InputParam, "Error in EC type");
     }
 
     /* Create the context for generating the parameters */
     EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL), EVP_PKEY_CTX_free);
     if(!pctx) {
-        LogError("Error in EVP_PKEY_CTX_new_id function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new_id function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) {
-        LogError("Error in EVP_PKEY_paramgen_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_paramgen_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen_init function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx.get(), ecCurve)) {
-        LogError("Error in EVP_PKEY_CTX_set_ec_paramgen_curve_nid function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_ec_paramgen_curve_nid function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_ec_paramgen_curve_nid function");
     }
 
     /* Generate parameters */
     EVP_PKEY *pparamTmp = NULL;
     if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) {
-        LogError("Error in EVP_PKEY_paramgen function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_paramgen function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen function");
     }
     pparam = EvpPkeyUPtr(pparamTmp, EVP_PKEY_free);
 
     // Start to generate key
     EvpPkeyCtxUPtr kctx(EVP_PKEY_CTX_new(pparam.get(), NULL), EVP_PKEY_CTX_free);
     if(!kctx) {
-        LogError("Error in EVP_PKEY_CTX_new function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function");
     }
 
     if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) {
-        LogError("Error in EVP_PKEY_keygen_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function");
     }
 
     /* Generate the key */
     EVP_PKEY *pkeyTmp = NULL;
     if(!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) {
-        LogError("Error in EVP_PKEY_keygen function !!");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen function !!");
-        }
-        pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free);
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!");
+    }
+    pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free);
 
     return std::make_pair<Token, Token>(Token(backendId, DataType(KeyType::KEY_ECDSA_PRIVATE), i2d(i2d_PrivateKey_bio, pkey.get())),
                                         Token(backendId, DataType(KeyType::KEY_ECDSA_PUBLIC), i2d(i2d_PUBKEY_bio, pkey.get())));
@@ -333,14 +305,14 @@ Token createKeyAES(CryptoBackend backendId, const int sizeBits)
     // check the parameters of functions
     if(sizeBits!=128 && sizeBits!=192 && sizeBits!=256) {
         LogError("Error in AES input size");
-        ThrowMsg(Crypto::Exception::InputParam, "Error in AES input size");
+        ThrowMsg(Exc::Crypto::InputParam, "Error in AES input size");
     }
 
     uint8_t key[32];
     int sizeBytes = sizeBits/8;
     if (!RAND_bytes(key, sizeBytes)) {
         LogError("Error in AES key generation");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in AES key generation");
+        ThrowMsg(Exc::Crypto::InternalError, "Error in AES key generation");
     }
 
     return Token(backendId, DataType(KeyType::KEY_AES), CKM::RawBuffer(key, key+sizeBytes));
@@ -367,7 +339,7 @@ RawBuffer sign(EVP_PKEY *pkey,
 //       (privateKey.getType() != KeyType::KEY_ECDSA_PRIVATE))
 //    {
 //        LogError("Error in private key type");
-//        ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in private key type");
+//        ThrowErr(CryptoService::Exception::Crypto_internal, "Error in private key type");
 //    }
 //
 //    if(privateKey.getType()==KeyType::KEY_RSA_PRIVATE) {
@@ -375,8 +347,7 @@ RawBuffer sign(EVP_PKEY *pkey,
 //    }
 
     if (NULL == pkey) {
-        LogError("Error in EVP_PKEY_keygen function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_keygen function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function");
     }
 
     if(md_algo == NULL) {
@@ -393,20 +364,17 @@ RawBuffer signMessage(EVP_PKEY *privKey,
     EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new(privKey, NULL), EVP_PKEY_CTX_free);
  
     if(!pctx.get()) {
-        LogError("Error in EVP_PKEY_CTX_new function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function");
     }
 
     if(EVP_PKEY_sign_init(pctx.get()) != EVP_SUCCESS) {
-        LogError("Error in EVP_PKEY_sign_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_sign_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_sign_init function");
     }
 
     /* Set padding algorithm */
     if(EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) {
         if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) {
-            LogError("Error in EVP_PKEY_CTX_set_rsa_padding function");
-            ThrowMsg(Crypto::Exception::InternalError,
+            ThrowErr(Exc::Crypto::InternalError,
                      "Error in EVP_PKEY_CTX_set_rsa_padding function");
         }
     }
@@ -416,8 +384,7 @@ RawBuffer signMessage(EVP_PKEY *privKey,
      * signature. Length is returned in slen */
     size_t slen;
     if(EVP_SUCCESS != EVP_PKEY_sign(pctx.get(), NULL, &slen, message.data(), message.size())) {
-        LogError("Error in EVP_PKEY_sign function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_sign function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_sign function");
     }
 
     /* Allocate memory for the signature based on size in slen */
@@ -434,8 +401,7 @@ RawBuffer signMessage(EVP_PKEY *privKey,
         return sig;
     }
 
-    LogError("Error in EVP_PKEY_sign function. Input param error.");
-    ThrowMsg(Crypto::Exception::InputParam, "Error in EVP_PKEY_sign function. Input param error.");
+    ThrowErr(Exc::Crypto::InputParam, "Error in EVP_PKEY_sign function. Input param error.");
 }
 
 RawBuffer digestSignMessage(EVP_PKEY *privKey,
@@ -449,27 +415,23 @@ RawBuffer digestSignMessage(EVP_PKEY *privKey,
 
     // Create the Message Digest Context
     if(!mdctx.get()) {
-        LogError("Error in EVP_MD_CTX_create function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_MD_CTX_create function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_MD_CTX_create function");
     }
 
     if(EVP_SUCCESS != EVP_DigestSignInit(mdctx.get(), &pctx, md_algo, NULL, privKey)) {
-        LogError("Error in EVP_DigestSignInit function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestSignInit function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignInit function");
     }
 
     /* Set padding algorithm */
     if(EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) {
         if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) {
-            LogError("Error in EVP_PKEY_CTX_set_rsa_padding function");
-            ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
+            ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
         }
     }
 
     /* Call update with the message */
     if(EVP_SUCCESS != EVP_DigestSignUpdate(mdctx.get(), message.data(), message.size())) {
-        LogError("Error in EVP_DigestSignUpdate function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestSignUpdate function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignUpdate function");
     }
 
     /* Finalize the DigestSign operation */
@@ -477,8 +439,7 @@ RawBuffer digestSignMessage(EVP_PKEY *privKey,
      * signature. Length is returned in slen */
     size_t slen;
     if(EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), NULL, &slen)) {
-        LogError("Error in EVP_DigestSignFinal function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestSignFinal function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignFinal function");
     }
 
     /* Allocate memory for the signature based on size in slen */
@@ -486,8 +447,7 @@ RawBuffer digestSignMessage(EVP_PKEY *privKey,
 
     /* Obtain the signature */
     if(EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), sig.data(), &slen)) {
-        LogError("Error in EVP_DigestSignFinal function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestSignFinal function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignFinal function");
     }
 
     // Set value to return RawData
@@ -517,7 +477,7 @@ int verify(EVP_PKEY *pkey,
 //       (publicKey.getType() != KeyType::KEY_ECDSA_PUBLIC))
 //    {
 //        LogError("Error in private key type");
-//        ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in private key type");
+//        ThrowErr(CryptoService::Exception::Crypto_internal, "Error in private key type");
 //    }
 //
 //    if(publicKey.getType()==KeyType::KEY_RSA_PUBLIC) {
@@ -526,8 +486,7 @@ int verify(EVP_PKEY *pkey,
 
 //    auto shrPKey = publicKey.getEvpShPtr();
     if (NULL == pkey) {
-        LogError("Error in getEvpShPtr function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in getEvpShPtr function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in getEvpShPtr function");
     }
 
     if (md_algo == NULL) {
@@ -545,20 +504,17 @@ int verifyMessage(EVP_PKEY *pubKey,
     EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new(pubKey, NULL), EVP_PKEY_CTX_free);
 
     if(!pctx.get()) {
-        LogError("Error in EVP_PKEY_CTX_new function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_new function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function");
     }
 
     if(EVP_PKEY_verify_init(pctx.get()) != EVP_SUCCESS) {
-        LogError("Error in EVP_PKEY_verify_init function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_verify_init function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_verify_init function");
     }
 
     /* Set padding algorithm  */
     if(EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) {
         if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) {
-            LogError("Error in EVP_PKEY_CTX_set_rsa_padding function");
-            ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
+            ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
         }
     }
 
@@ -581,25 +537,21 @@ int digestVerifyMessage(EVP_PKEY *pubKey,
 
     /* Create the Message Digest Context */
     if(!mdctx.get()) {
-        LogError("Error in EVP_MD_CTX_create function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_MD_CTX_create function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_MD_CTX_create function");
     }
 
     if(EVP_SUCCESS != EVP_DigestVerifyInit(mdctx.get(), &pctx, md_algo, NULL, pubKey)) {
-        LogError("Error in EVP_DigestVerifyInit function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestVerifyInit function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestVerifyInit function");
     }
 
     if(EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) {
         if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) {
-            LogError("Error in EVP_PKEY_CTX_set_rsa_padding function");
-            ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
+            ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function");
         }
     }
 
     if(EVP_SUCCESS != EVP_DigestVerifyUpdate(mdctx.get(), message.data(), message.size()) ) {
-        LogError("Error in EVP_DigestVerifyUpdate function");
-        ThrowMsg(Crypto::Exception::InternalError, "Error in EVP_DigestVerifyUpdate function");
+        ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestVerifyUpdate function");
     }
 
     if(EVP_SUCCESS == EVP_DigestVerifyFinal(mdctx.get(), const_cast<unsigned char*>(signature.data()), signature.size()) ) {
index 93a32e1..01837b9 100644 (file)
@@ -74,8 +74,7 @@ EvpShPtr AKey::getEvpShPtr() {
     }
 
     if (!pkey) {
-        LogError("Failed to parse key");
-        ThrowMsg(Exception::InternalError, "Failed to parse key");
+        ThrowErr(Exc::Crypto::InternalError, "Failed to parse key");
     }
 
     m_evp.reset(pkey, EVP_PKEY_free);
@@ -92,8 +91,7 @@ EvpShPtr Cert::getEvpShPtr() {
     X509 *x509 = d2i_X509(NULL, &ptr, size);
 
     if (!x509) {
-        LogError("Failed to parse certificate.");
-        ThrowMsg(Exception::InternalError, "Failed to parse certificate.");
+        ThrowErr(Exc::Crypto::InternalError, "Failed to parse certificate.");
     }
 
     m_evp.reset(X509_get_pubkey(x509), EVP_PKEY_free);
index a3fd002..9f18575 100644 (file)
@@ -20,8 +20,6 @@
  */
 #include <memory>
 
-#include <dpl/log/log.h>
-
 #include <generic-backend/exception.h>
 #include <sw-backend/key.h>
 #include <sw-backend/store.h>
@@ -40,8 +38,7 @@ Store::Store(CryptoBackend backendId)
 
 GKeyShPtr Store::getKey(const Token &token) {
     if (token.backendId != m_backendId) {
-        LogError("Decider choose wrong backend!");
-        ThrowMsg(Exception::WrongBackend, "Decider choose wrong backend!");
+        ThrowErr(Exc::Crypto::WrongBackend, "Decider choose wrong backend!");
     }
 
     if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic()) {
@@ -56,10 +53,8 @@ GKeyShPtr Store::getKey(const Token &token) {
         return std::make_shared<Cert>(token.data, token.dataType);
     }
 
-    LogDebug(
-        "This type of data is not supported by openssl backend: " << (int)token.dataType);
-    ThrowMsg(Exception::KeyNotSupported,
-        "This type of data is not supported by openssl backend: " << (int)token.dataType);
+    ThrowErr(Exc::Crypto::KeyNotSupported,
+        "This type of data is not supported by openssl backend: ", (int)token.dataType);
 }
 
 TokenPair Store::generateAKey(const CryptoAlgorithm &algorithm)
@@ -71,7 +66,7 @@ TokenPair Store::generateAKey(const CryptoAlgorithm &algorithm)
     {
         int keyLength = 0;
         if(!algorithm.getParam(ParamName::GEN_KEY_LEN, keyLength))
-            ThrowMsg(Crypto::Exception::InputParam, "Error, parameter GEN_KEY_LEN not found.");
+            ThrowErr(Exc::Crypto::InputParam, "Error, parameter GEN_KEY_LEN not found.");
 
         if(keyType == AlgoType::RSA_GEN)
             return Internals::createKeyPairRSA(m_backendId, keyLength);
@@ -82,18 +77,18 @@ TokenPair Store::generateAKey(const CryptoAlgorithm &algorithm)
     {
         int ecType = 0;
         if(!algorithm.getParam(ParamName::GEN_EC, ecType))
-            ThrowMsg(Crypto::Exception::InputParam, "Error, parameter GEN_EC not found.");
+            ThrowErr(Exc::Crypto::InputParam, "Error, parameter GEN_EC not found.");
 
         return Internals::createKeyPairECDSA(m_backendId, static_cast<ElipticCurve>(ecType));
     }
-    ThrowMsg(Crypto::Exception::InputParam, "wrong key type");
+    ThrowErr(Exc::Crypto::InputParam, "wrong key type");
 }
 
 Token Store::generateSKey(const CryptoAlgorithm &algorithm)
 {
     int keyLength = 0;
     if(!algorithm.getParam(ParamName::GEN_KEY_LEN, keyLength))
-        ThrowMsg(Crypto::Exception::InputParam, "Error, parameter GEN_KEY_LEN not found.");
+        ThrowErr(Exc::Crypto::InputParam, "Error, parameter GEN_KEY_LEN not found.");
 
     return Internals::createKeyAES(m_backendId, keyLength);
 }
@@ -102,10 +97,6 @@ Token Store::import(DataType dataType, const RawBuffer &buffer) {
     return Token(m_backendId, dataType, buffer);
 }
 
-
-
-
-
 } // namespace SW
 } // namespace Crypto
 } // namespace CKM
index 481595b..100ca6f 100644 (file)
@@ -18,8 +18,6 @@
  * @author     BartÅ‚omiej Grzelewski (b.grzelewski@samsung.com)
  * @version    1.0
  */
-#include <dpl/log/log.h>
-
 #include <generic-backend/exception.h>
 #include <tz-backend/key.h>
 #include <tz-backend/store.h>
@@ -33,18 +31,15 @@ Store::Store(CryptoBackend backendId)
 {}
 
 GKeyShPtr Store::getKey(const Token &) {
-    LogError("Trust zone backend is not implemented!");
-    ThrowMsg(Exception::Base, "Trust zone backend is not implemented!");
+    ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!");
 }
 
 TokenPair Store::generateAKey(const CryptoAlgorithm &) {
-    LogError("Trust zone backend is not implemented!");
-    ThrowMsg(Exception::Base, "Trust zone backend is not implemented!");
+    ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!");
 }
 
 Token Store::import(DataType, const RawBuffer &) {
-    LogError("Trust zone backend is not implemented!");
-    ThrowMsg(Exception::Base, "Trust zone backend is not implemented!");
+    ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!");
 }
 
 } // namespace TZ
index 28e1eb4..1865a23 100644 (file)
@@ -148,9 +148,27 @@ do
     }                                                                           \
 } while (0)
 
+#define DPL_MACRO_FOR_LOGGING_POSITION(message, level, file, line, function)    \
+do                                                                              \
+{                                                                               \
+    if (level > CKM::Log::AbstractLogProvider::LogLevel::None &&                \
+        CKM::Log::LogSystemSingleton::Instance().GetLogLevel() >= level)        \
+    {                                                                           \
+        std::ostringstream platformLog;                                         \
+        platformLog << message;                                                 \
+        CKM::Log::LogSystemSingleton::Instance().Log(level,                     \
+                                                     platformLog.str().c_str(), \
+                                                     file,                      \
+                                                     line,                      \
+                                                     function);                 \
+    }                                                                           \
+} while (0)
+
 /* Errors must be always logged. */
 #define  LogError(message)          \
     DPL_MACRO_FOR_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Error)
+#define  LogErrorPosition(message, file, line, function)          \
+    DPL_MACRO_FOR_LOGGING_POSITION(message, CKM::Log::AbstractLogProvider::LogLevel::Error, file, line, function)
 
 #ifdef BUILD_TYPE_DEBUG
     #define LogDebug(message)       \
@@ -161,6 +179,8 @@ do
         DPL_MACRO_FOR_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Warning)
     #define LogPedantic(message)    \
         DPL_MACRO_FOR_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Pedantic)
+    #define LogDebugPosition(message, file, line, function) \
+        DPL_MACRO_FOR_LOGGING_POSITION(message, CKM::Log::AbstractLogProvider::LogLevel::Debug, file, line, function)
 #else
     #define LogDebug(message)       \
         DPL_MACRO_DUMMY_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Debug)
@@ -170,6 +190,11 @@ do
         DPL_MACRO_DUMMY_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Warning)
     #define LogPedantic(message)    \
         DPL_MACRO_DUMMY_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Pedantic)
+    #define LogDebugPosition(message, file, line, function)                                    \
+        do {                                                                                   \
+            (void) file; (void) line; (void) function;                                         \
+            DPL_MACRO_DUMMY_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Debug);  \
+        } while(0)
 #endif // BUILD_TYPE_DEBUG
 
 #endif // CENT_KEY_LOG_H
index d37bc5b..a2c3e45 100644 (file)
@@ -168,12 +168,8 @@ int CKMLogic::unlockDatabase(uid_t user, const Password & password)
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("Error in KeyProvider " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("FileSystem error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -199,7 +195,7 @@ UserData & CKMLogic::selectDatabase(const Credentials &cred, const Label &incomi
     if ( !m_accessControl.isSystemService(cred) )
     {
         if (0 == m_userDataMap.count(cred.clientUid))
-            ThrowMsg(Exception::DatabaseLocked, "database with UID: " << cred.clientUid << " locked");
+            ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked");
 
         if (0 != incoming_label.compare(LABEL_SYSTEM_DB))
             return m_userDataMap[cred.clientUid];
@@ -207,7 +203,7 @@ UserData & CKMLogic::selectDatabase(const Credentials &cred, const Label &incomi
 
     // system database selected, modify the label
     if (CKM_API_SUCCESS != unlockSystemDB() )
-        ThrowMsg(Exception::DatabaseLocked, "can not unlock system database");
+        ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
     return m_userDataMap[SYSTEM_DB_UID];
 }
 
@@ -293,9 +289,8 @@ RawBuffer CKMLogic::changeUserPassword(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("Error in KeyProvider " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -334,9 +329,8 @@ RawBuffer CKMLogic::resetUserPassword(
     int retCode = CKM_API_SUCCESS;
     try {
         retCode = resetUserPasswordHelper(user, newPassword);
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -372,9 +366,8 @@ RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) {
     } catch (const DB::Crypto::Exception::TransactionError &e) {
         LogError("DB::Crypto transaction failed with message " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -510,21 +503,14 @@ int CKMLogic::verifyAndSaveDataHelper(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::InternalError &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
     } catch (const DB::Crypto::Exception::TransactionError &e) {
         LogError("DB::Crypto transaction failed with message " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -609,9 +595,6 @@ RawBuffer CKMLogic::savePKCS12(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::InternalError &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -681,10 +664,9 @@ RawBuffer CKMLogic::removeData(
     {
         retCode = removeDataHelper(cred, name, label);
     }
-    catch (const CKMLogic::Exception::DatabaseLocked &e)
+    catch (const Exc::Exception &e)
     {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+        retCode = e.error();
     }
     catch (const CKM::Exception &)
     {
@@ -897,18 +879,11 @@ RawBuffer CKMLogic::getData(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with error: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -993,18 +968,11 @@ RawBuffer CKMLogic::getPKCS12(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with error: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1202,10 +1170,10 @@ int CKMLogic::createKeyPairHelper(
 
     AlgoType keyType = AlgoType::RSA_GEN;
     if(!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
-        ThrowMsg(Crypto::Exception::InputParam, "Error, parameter ALGO_TYPE not found.");
+        ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
     DataType dt(keyType);
     if(!dt.isKey())
-        ThrowMsg(Crypto::Exception::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
+        ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
 
     bool exportable = policyPrivate.extractable || policyPublic.extractable;
     TokenPair keys = m_decider.getStore(dt, exportable).generateAKey(keyGenParams);
@@ -1261,27 +1229,14 @@ RawBuffer CKMLogic::createKeyPair(
                         labelPublic,
                         policyPrivate,
                         policyPublic);
-    } catch (const Crypto::Exception::OperationNotSupported &e) {
-        LogDebug("GStore error: operation not supported: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const Crypto::Exception::InternalError & e) {
-        LogDebug("GStore key generation failed: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch( const Crypto::Exception::InputParam & e) {
-        LogDebug("Missing or wrong input parameters: " << e.GetMessage());
-        retCode = CKM_API_ERROR_INPUT_PARAM;
+    } catch(const Exc::Exception &e) {
+        retCode = e.error();
     } catch (DB::Crypto::Exception::TransactionError &e) {
         LogDebug("DB::Crypto error: transaction error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (CKM::CryptoLogic::Exception::Base &e) {
-        LogDebug("CryptoLogic error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (DB::Crypto::Exception::InternalError &e) {
         LogDebug("DB::Crypto internal error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1303,30 +1258,17 @@ RawBuffer CKMLogic::createKeyAES(
 
     try {
         retCode = createKeyAESHelper(cred, size, name, label, policy);
-    } catch (const Crypto::Exception::OperationNotSupported &e) {
-        LogDebug("GStore error: operation not supported: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const Crypto::Exception::InternalError & e) {
-        LogDebug("GStore key generation failed: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch( const Crypto::Exception::InputParam & e) {
-        LogDebug("Missing or wrong input parameters: " << e.GetMessage());
-        retCode = CKM_API_ERROR_INPUT_PARAM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (std::invalid_argument &e) {
         LogDebug("invalid argument error: " << e.what());
         retCode = CKM_API_ERROR_INPUT_PARAM;
     } catch (DB::Crypto::Exception::TransactionError &e) {
         LogDebug("DB::Crypto error: transaction error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (CKM::CryptoLogic::Exception::Base &e) {
-        LogDebug("CryptoLogic error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (DB::Crypto::Exception::InternalError &e) {
         LogDebug("DB::Crypto internal error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1449,9 +1391,8 @@ RawBuffer CKMLogic::getCertificateChain(
                                             trustedCertificates,
                                             useTrustedSystemCertificates,
                                             chainRawVector);
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -1487,18 +1428,11 @@ RawBuffer CKMLogic::getCertificateChain(
                                             trustedCertificates,
                                             useTrustedSystemCertificates,
                                             chainRawVector);
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const std::exception& e) {
         LogError("STD exception " << e.what());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1539,24 +1473,11 @@ RawBuffer CKMLogic::createSignature(
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
-    } catch (const CKM::Crypto::Exception::InputParam &e) {
-        LogError("CKM::Crypto failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_INPUT_PARAM;
-    } catch (const CKM::Crypto::Exception::Base &e) {
-        LogError("CKM::Crypto failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("Unknown CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1600,24 +1521,14 @@ RawBuffer CKMLogic::verifySignature(
         if (retCode == CKM_API_SUCCESS) {
             retCode = m_decider.getStore(row).getKey(row)->verify(params, message, signature);
         }
-    } catch (const Crypto::Exception::Base &e) {
-        LogError("GStore failed with error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const KeyProvider::Exception::Base &e) {
         LogError("KeyProvider failed with error: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
     } catch (const CKM::Exception &e) {
         LogError("Unknown CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1694,9 +1605,8 @@ RawBuffer CKMLogic::setPermission(
     int retCode;
     Try {
         retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } Catch (CKM::Exception) {
         LogError("Error in set row!");
         retCode = CKM_API_ERROR_DB_ERROR;
index c09b97e..afc90be 100644 (file)
@@ -49,12 +49,6 @@ struct UserData {
 class CKMLogic {
 public:
     static const uid_t SYSTEM_DB_UID;
-    class Exception
-    {
-    public:
-        DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, DatabaseLocked)
-    };
 
     CKMLogic();
     CKMLogic(const CKMLogic &) = delete;
index 1a91329..29e920e 100644 (file)
@@ -64,14 +64,14 @@ void CryptoLogic::pushKey(const Label &smackLabel,
                             const RawBuffer &applicationKey)
 {
     if (smackLabel.length() == 0) {
-        ThrowMsg(Exception::InternalError, "Empty smack label.");
+        ThrowErr(Exc::InternalError, "Empty smack label.");
     }
     if (applicationKey.size() == 0) {
-        ThrowMsg(Exception::InternalError, "Empty application key.");
+        ThrowErr(Exc::InternalError, "Empty application key.");
     }
     if (haveKey(smackLabel)) {
-        ThrowMsg(Exception::InternalError, "Application key for " << smackLabel
-                 << "label already exists.");
+        ThrowErr(Exc::InternalError, "Application key for ", smackLabel,
+            "label already exists.");
     }
     m_keyMap[smackLabel] = applicationKey;
 }
@@ -116,8 +116,7 @@ std::pair<RawBuffer,RawBuffer> CryptoLogic::encryptDataAesGcm(
     RawBuffer tmp = enc.Finalize();
     std::copy(tmp.begin(), tmp.end(), std::back_inserter(result));
     if (0 == enc.Control(EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_SIZE, tag.data())) {
-        LogError("Error in aes control function. Get tag failed.");
-        ThrowMsg(Exception::EncryptDBRowError, "Error in aes control function. Get tag failed.");
+        ThrowErr(Exc::InternalError, "Error in aes control function. Get tag failed.");
     }
     return std::make_pair(result, tag);
 }
@@ -130,13 +129,11 @@ RawBuffer CryptoLogic::decryptDataAesGcm(
 {
     Crypto::SW::Cipher::AesGcmDecryption dec(key, iv);
     if (tag.size() < AES_GCM_TAG_SIZE) {
-        LogError("Error in decryptDataAesGcm. Tag is too short.");
-        ThrowMsg(Exception::DecryptDBRowError, "Error in decryptDataAesGcm. Tag is too short");
+        ThrowErr(Exc::AuthenticationFailed, "Error in decryptDataAesGcm. Tag is too short");
     }
     void *ptr = (void*)tag.data();
     if (0 == dec.Control(EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_SIZE, ptr)) {
-        LogError("Error in aes control function. Set tag failed.");
-        ThrowMsg(Exception::DecryptDBRowError, "Error in aes control function. Set tag failed.");
+        ThrowErr(Exc::AuthenticationFailed, "Error in aes control function. Set tag failed.");
     }
     RawBuffer result = dec.Append(data);
     RawBuffer tmp = dec.Finalize();
@@ -160,7 +157,7 @@ RawBuffer CryptoLogic::passwordToKey(
                 result.size(),
                 result.data()))
     {
-        ThrowMsg(Exception::InternalError, "PCKS5_PKKDF_HMAC_SHA1 failed.");
+        ThrowErr(Exc::InternalError, "PCKS5_PKKDF_HMAC_SHA1 failed.");
     }
     return result;
 }
@@ -169,8 +166,7 @@ RawBuffer CryptoLogic::generateRandIV() const {
     RawBuffer civ(EVP_MAX_IV_LENGTH);
 
     if (1 != RAND_bytes(civ.data(), civ.size())) {
-        ThrowMsg(Exception::InternalError,
-          "RAND_bytes failed to generate IV.");
+        ThrowErr(Exc::InternalError, "RAND_bytes failed to generate IV.");
     }
 
     return civ;
@@ -188,12 +184,12 @@ void CryptoLogic::encryptRow(const Password &password, DB::Row &row)
         crow.dataSize = crow.data.size();
 
         if (crow.dataSize <= 0) {
-            ThrowMsg(Exception::EncryptDBRowError, "Invalid dataSize.");
+            ThrowErr(Exc::InternalError, "Invalid dataSize.");
         }
 
         if (!haveKey(row.ownerLabel)) {
-            ThrowMsg(Exception::EncryptDBRowError, "Missing application key for " <<
-              row.ownerLabel << " label.");
+            ThrowErr(Exc::InternalError, "Missing application key for ",
+              row.ownerLabel, " label.");
         }
 
         if (crow.iv.empty()) {
@@ -219,14 +215,9 @@ void CryptoLogic::encryptRow(const Password &password, DB::Row &row)
 
         row = crow;
     } catch(const CKM::Base64Encoder::Exception::Base &e) {
-        LogDebug("Base64Encoder error: " << e.GetMessage());
-        ThrowMsg(Exception::Base64EncoderError, e.GetMessage());
+        ThrowErr(Exc::InternalError, e.GetMessage());
     } catch(const CKM::Base64Decoder::Exception::Base &e) {
-        LogDebug("Base64Encoder error: " << e.GetMessage());
-        ThrowMsg(Exception::Base64DecoderError, e.GetMessage());
-    } catch(const CKM::Crypto::Exception::Base &e) {
-        LogDebug("Crypto error: " << e.GetMessage());
-        ThrowMsg(Exception::EncryptDBRowError, e.GetMessage());
+        ThrowErr(Exc::InternalError, e.GetMessage());
     }
 }
 
@@ -238,18 +229,18 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row)
         RawBuffer digest, dataDigest;
 
         if (row.algorithmType != DBCMAlgType::AES_GCM_256) {
-            ThrowMsg(Exception::DecryptDBRowError, "Invalid algorithm type.");
+            ThrowErr(Exc::AuthenticationFailed, "Invalid algorithm type.");
         }
 
         if ((row.encryptionScheme & ENCR_PASSWORD) && password.empty()) {
-            ThrowMsg(Exception::DecryptDBRowError,
+            ThrowErr(Exc::AuthenticationFailed,
               "DB row is password protected, but given password is "
               "empty.");
         }
 
         if ((row.encryptionScheme & ENCR_APPKEY) && !haveKey(row.ownerLabel)) {
-            ThrowMsg(Exception::DecryptDBRowError, "Missing application key for " <<
-              row.ownerLabel << " label.");
+            ThrowErr(Exc::AuthenticationFailed, "Missing application key for ",
+              row.ownerLabel, " label.");
         }
 
         decBase64(crow.iv);
@@ -268,9 +259,7 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row)
         }
 
         if (static_cast<int>(crow.data.size()) < crow.dataSize) {
-            ThrowMsg(Exception::DecryptDBRowError,
-                "Decrypted row size mismatch");
-            LogError("Decryption row size mismatch");
+            ThrowErr(Exc::AuthenticationFailed, "Decrypted row size mismatch");
         }
 
         if (static_cast<int>(crow.data.size()) > crow.dataSize) {
@@ -279,14 +268,11 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row)
 
         row = crow;
     } catch(const CKM::Base64Encoder::Exception::Base &e) {
-        LogDebug("Base64Encoder error: " << e.GetMessage());
-        ThrowMsg(Exception::Base64EncoderError, e.GetMessage());
+        ThrowErr(Exc::InternalError, e.GetMessage());
     } catch(const CKM::Base64Decoder::Exception::Base &e) {
-        LogDebug("Base64Encoder error: " << e.GetMessage());
-        ThrowMsg(Exception::Base64DecoderError, e.GetMessage());
-    } catch(const CKM::Crypto::Exception::Base &e) {
-        LogDebug("Crypto error: " << e.GetMessage());
-        ThrowMsg(Exception::DecryptDBRowError, e.GetMessage());
+        ThrowErr(Exc::InternalError, e.GetMessage());
+    } catch(const Exc::Exception &e) {
+        ThrowErr(Exc::AuthenticationFailed, e.message());
     }
 }
 
@@ -300,7 +286,7 @@ void CryptoLogic::encBase64(RawBuffer &data)
     encdata = benc.get();
 
     if (encdata.size() == 0) {
-        ThrowMsg(Exception::Base64EncoderError, "Base64Encoder returned empty data.");
+        ThrowErr(Exc::InternalError, "Base64Encoder returned empty data.");
     }
 
     data = std::move(encdata);
@@ -313,15 +299,14 @@ void CryptoLogic::decBase64(RawBuffer &data)
 
     bdec.reset();
     bdec.append(data);
-    if (not bdec.finalize()) {
-        ThrowMsg(Exception::Base64DecoderError,
-          "Failed in Base64Decoder.finalize.");
+    if (!bdec.finalize()) {
+        ThrowErr(Exc::InternalError, "Failed in Base64Decoder.finalize.");
     }
 
     decdata = bdec.get();
 
     if (decdata.size() == 0) {
-        ThrowMsg(Exception::Base64DecoderError, "Base64Decoder returned empty data.");
+        ThrowErr(Exc::InternalError, "Base64Decoder returned empty data.");
     }
 
     data = std::move(decdata);
index 43e4b9c..82e3271 100644 (file)
 #include <map>
 #include <ckm/ckm-type.h>
 #include <db-crypto.h>
-#include <dpl/exception.h>
 
 namespace CKM {
 
 class CryptoLogic {
 public:
-    class Exception
-    {
-        public:
-            DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
-            DECLARE_EXCEPTION_TYPE(Base, InternalError)
-            DECLARE_EXCEPTION_TYPE(Base, Base64EncoderError)
-            DECLARE_EXCEPTION_TYPE(Base, Base64DecoderError)
-            DECLARE_EXCEPTION_TYPE(Base, EncryptDBRowError)
-            DECLARE_EXCEPTION_TYPE(Base, DecryptDBRowError)
-    };
     CryptoLogic();
     CryptoLogic(const CryptoLogic &second) = delete;
     CryptoLogic(CryptoLogic &&second);
index 11aa562..41ce574 100644 (file)
@@ -41,7 +41,7 @@ namespace {
 template <typename... Args>
 std::runtime_error io_exception(const Args&... args)
 {
-    return std::runtime_error(stringify(args...));
+    return std::runtime_error(Stringify()(args...));
 };
 
 } // namespace anonymous
index a5e63f9..96446c1 100644 (file)
@@ -37,6 +37,7 @@
 #include <dpl/fstream_accessors.h>
 #include <dpl/log/log.h>
 
+#include <exception.h>
 #include <file-system.h>
 
 namespace {
@@ -89,9 +90,8 @@ RawBuffer FileSystem::loadFile(const std::string &path) const {
 
     if (is.fail()) {
         auto description = GetErrnoString(errno);
-        LogError("Error opening file: " << path << " Reason: " << description);
-        ThrowMsg(Exception::OpenFailed,
-                 "Error opening file: " << path << " Reason: " << description);
+        ThrowErr(Exc::FileSystemFailed,
+                 "Error opening file: ", path, " Reason: ", description);
     }
 
     std::istreambuf_iterator<char> begin(is),end;
@@ -122,7 +122,7 @@ void FileSystem::saveFile(const std::string &path, const RawBuffer &buffer) cons
     os.close();
 
     if (os.fail())
-        ThrowMsg(Exception::SaveFailed, "Failed to save file: " << path);
+        ThrowErr(Exc::FileSystemFailed, "Failed to save file: ", path);
 }
 
 void FileSystem::saveDKEK(const RawBuffer &buffer) const {
@@ -141,9 +141,8 @@ void FileSystem::addRemovedApp(const std::string &smackLabel) const
     outfile.close();
     if (outfile.fail()) {
         auto desc = GetErrnoString(errno);
-        LogError("Could not update file: " << getRemovedAppsPath() << " Reason: " << desc);
-        ThrowMsg(Exception::SaveFailed,
-                 "Could not update file: " << getRemovedAppsPath() << " Reason: " << desc);
+        ThrowErr(Exc::FileSystemFailed,
+                 "Could not update file: ", getRemovedAppsPath(), " Reason: ", desc);
     }
 }
 
index ace87e9..6b396c3 100644 (file)
@@ -32,14 +32,6 @@ typedef std::vector<uid_t> UidVector;
 
 class FileSystem {
 public:
-    class Exception {
-    public:
-        DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
-        DECLARE_EXCEPTION_TYPE(Base, OpenFailed)
-        DECLARE_EXCEPTION_TYPE(Base, SaveFailed)
-        DECLARE_EXCEPTION_TYPE(Base, RenameFailed)
-    };
-
     FileSystem(uid_t uid);
 
     std::string getDBPath() const;